File size: 117,274 Bytes
8c763fb | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084 2085 2086 2087 2088 2089 2090 2091 2092 2093 2094 2095 2096 2097 2098 2099 2100 2101 2102 2103 2104 2105 2106 2107 2108 2109 2110 2111 2112 2113 2114 2115 2116 2117 2118 2119 2120 2121 2122 2123 2124 2125 2126 2127 2128 2129 2130 2131 2132 2133 2134 2135 2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146 2147 2148 2149 2150 2151 2152 2153 2154 2155 2156 2157 2158 2159 2160 2161 2162 2163 2164 2165 2166 2167 2168 2169 2170 2171 2172 2173 2174 2175 2176 2177 2178 2179 2180 2181 2182 2183 2184 2185 2186 2187 2188 2189 2190 2191 2192 2193 2194 2195 2196 2197 2198 2199 2200 2201 2202 2203 2204 2205 2206 2207 2208 2209 2210 2211 2212 2213 2214 2215 2216 2217 2218 2219 2220 2221 2222 2223 2224 2225 2226 2227 2228 2229 2230 2231 2232 2233 2234 2235 2236 2237 2238 2239 2240 2241 2242 2243 2244 2245 2246 2247 2248 2249 2250 2251 2252 2253 2254 2255 2256 2257 2258 2259 2260 2261 2262 2263 2264 2265 2266 2267 2268 2269 2270 2271 2272 2273 2274 2275 2276 2277 2278 2279 2280 2281 2282 2283 2284 2285 2286 2287 2288 2289 2290 2291 2292 2293 2294 2295 2296 2297 2298 2299 2300 2301 2302 2303 2304 2305 2306 2307 2308 2309 2310 2311 2312 2313 2314 2315 2316 2317 2318 2319 2320 2321 2322 2323 2324 2325 2326 2327 2328 2329 2330 2331 2332 2333 2334 2335 2336 2337 2338 2339 2340 2341 2342 2343 2344 2345 2346 2347 2348 2349 2350 2351 2352 2353 2354 2355 2356 2357 2358 2359 2360 2361 2362 2363 2364 2365 2366 2367 2368 2369 2370 2371 2372 2373 2374 2375 2376 2377 2378 2379 2380 2381 2382 2383 2384 2385 2386 2387 2388 2389 2390 2391 2392 2393 2394 2395 2396 2397 2398 2399 2400 2401 2402 2403 2404 2405 2406 2407 2408 2409 2410 2411 2412 2413 2414 2415 2416 2417 2418 2419 2420 2421 2422 2423 2424 2425 2426 2427 2428 2429 2430 2431 2432 2433 2434 2435 2436 2437 2438 2439 2440 2441 2442 2443 2444 2445 2446 2447 2448 2449 2450 2451 2452 2453 2454 2455 2456 2457 2458 2459 2460 2461 2462 2463 2464 2465 2466 2467 2468 2469 2470 2471 2472 2473 2474 2475 2476 2477 2478 2479 2480 2481 2482 2483 2484 2485 2486 2487 2488 2489 2490 2491 2492 2493 2494 2495 2496 2497 2498 2499 2500 2501 2502 2503 2504 2505 2506 2507 2508 2509 2510 2511 2512 2513 2514 2515 2516 2517 2518 2519 2520 2521 2522 2523 2524 2525 2526 2527 2528 2529 2530 2531 2532 2533 2534 2535 2536 2537 2538 2539 2540 2541 2542 2543 2544 2545 2546 2547 2548 2549 2550 2551 2552 2553 2554 2555 2556 2557 2558 2559 2560 2561 2562 2563 2564 2565 2566 2567 2568 2569 2570 2571 2572 2573 2574 2575 2576 2577 2578 2579 2580 2581 2582 2583 2584 2585 2586 2587 2588 2589 2590 2591 2592 2593 2594 2595 2596 2597 2598 2599 2600 2601 2602 2603 2604 2605 2606 2607 2608 2609 2610 2611 2612 2613 2614 2615 2616 2617 2618 2619 2620 2621 2622 2623 2624 2625 2626 2627 2628 2629 2630 2631 2632 2633 2634 2635 2636 2637 2638 2639 2640 2641 2642 2643 2644 2645 2646 2647 2648 2649 2650 2651 2652 2653 2654 2655 2656 2657 2658 2659 2660 2661 2662 2663 2664 2665 2666 2667 2668 2669 2670 2671 2672 2673 2674 2675 2676 2677 2678 2679 2680 2681 2682 2683 2684 2685 2686 2687 2688 2689 2690 2691 2692 2693 2694 2695 2696 2697 2698 2699 2700 2701 2702 2703 2704 2705 2706 2707 2708 2709 2710 2711 2712 2713 2714 2715 2716 2717 2718 2719 2720 2721 2722 2723 2724 2725 2726 2727 2728 2729 2730 2731 2732 2733 2734 2735 2736 2737 2738 2739 2740 2741 2742 2743 2744 2745 2746 2747 2748 2749 2750 2751 2752 2753 2754 2755 2756 2757 2758 2759 2760 2761 2762 2763 2764 2765 2766 2767 2768 2769 2770 2771 2772 2773 2774 2775 2776 2777 2778 2779 2780 2781 2782 2783 2784 2785 2786 2787 2788 2789 2790 2791 2792 2793 2794 2795 2796 2797 2798 2799 2800 2801 2802 2803 2804 2805 2806 2807 2808 2809 2810 2811 2812 2813 2814 2815 2816 2817 2818 2819 2820 2821 2822 2823 2824 2825 2826 2827 2828 2829 2830 2831 2832 2833 2834 2835 2836 2837 2838 2839 2840 2841 2842 2843 2844 2845 2846 2847 2848 2849 2850 2851 2852 2853 2854 2855 2856 2857 2858 2859 2860 2861 2862 2863 2864 2865 2866 2867 2868 2869 2870 2871 2872 2873 2874 2875 2876 2877 2878 2879 2880 2881 2882 2883 2884 2885 2886 2887 2888 2889 2890 2891 2892 2893 2894 2895 2896 2897 2898 2899 2900 2901 2902 2903 2904 2905 2906 2907 2908 2909 2910 2911 2912 2913 2914 2915 2916 2917 2918 2919 2920 2921 2922 2923 2924 2925 2926 2927 2928 2929 2930 2931 2932 2933 2934 2935 2936 2937 2938 2939 2940 2941 2942 2943 2944 2945 2946 2947 2948 2949 2950 2951 2952 2953 2954 2955 2956 2957 2958 2959 2960 2961 2962 2963 2964 2965 2966 2967 2968 2969 2970 2971 2972 2973 2974 2975 2976 2977 2978 2979 2980 2981 2982 2983 2984 2985 2986 2987 2988 2989 2990 2991 2992 2993 2994 2995 2996 2997 2998 2999 3000 3001 3002 3003 3004 3005 3006 3007 3008 3009 3010 3011 3012 3013 3014 3015 3016 3017 3018 3019 3020 3021 3022 3023 3024 3025 3026 3027 3028 3029 3030 3031 3032 3033 3034 3035 3036 3037 3038 3039 3040 3041 3042 3043 3044 3045 3046 3047 3048 3049 3050 3051 3052 3053 3054 3055 3056 3057 3058 3059 3060 3061 3062 3063 3064 3065 3066 3067 3068 3069 3070 3071 3072 3073 3074 3075 3076 3077 3078 3079 3080 3081 3082 3083 3084 3085 3086 3087 3088 3089 3090 3091 3092 3093 3094 3095 3096 3097 3098 3099 3100 3101 3102 3103 3104 3105 3106 3107 3108 | // Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.IO;
using System.Management.Automation;
using System.Management.Automation.Configuration;
using System.Management.Automation.Host;
using System.Management.Automation.Internal;
using System.Management.Automation.Language;
using System.Management.Automation.Remoting;
using System.Management.Automation.Remoting.Server;
using System.Management.Automation.Runspaces;
using System.Management.Automation.Security;
using System.Management.Automation.Subsystem.Feedback;
using System.Management.Automation.Tracing;
using System.Reflection;
using System.Runtime;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading;
using Microsoft.PowerShell.Commands;
using Microsoft.PowerShell.Telemetry;
#if LEGACYTELEMETRY
using Microsoft.PowerShell.Telemetry.Internal;
#endif
using ConsoleHandle = Microsoft.Win32.SafeHandles.SafeFileHandle;
using Dbg = System.Management.Automation.Diagnostics;
using Debugger = System.Management.Automation.Debugger;
namespace Microsoft.PowerShell
{
/// <summary>
/// Subclasses S.M.A.Host to implement a console-mode monad host.
/// </summary>
[SuppressMessage("Microsoft.Maintainability", "CA1506:AvoidExcessiveClassCoupling")]
internal sealed partial class ConsoleHost
:
PSHost,
IDisposable,
#if LEGACYTELEMETRY
IHostProvidesTelemetryData,
#endif
IHostSupportsInteractiveSession
{
#region static methods
internal const int ExitCodeSuccess = 0;
internal const int ExitCodeCtrlBreak = 128 + 21; // SIGBREAK
internal const int ExitCodeInitFailure = 70; // Internal Software Error
internal const int ExitCodeBadCommandLineParameter = 64; // Command Line Usage Error
#if UNIX
internal const string DECCKM_ON = "\x1b[?1h";
internal const string DECCKM_OFF = "\x1b[?1l";
#endif
/// <summary>
/// Internal Entry point in msh console host implementation.
/// </summary>
/// <param name="bannerText">
/// Banner text to be displayed by ConsoleHost
/// </param>
/// <param name="helpText">
/// Help text for minishell. This is displayed on 'minishell -?'.
/// </param>
/// <param name="issProvidedExternally">
/// True when an external caller provides an InitialSessionState object, which can conflict with '-ConfigurationFile' argument.
/// </param>
/// <returns>
/// The exit code for the shell.
///
/// The behavior here is related to monitor work.
/// The low word of the exit code is available for the user. The high word is reserved for the shell and monitor.
///
/// The shell process needs to return:
///
/// - if the shell.exe fails init, 0xFFFF0000
/// - if the exit keyword is called with no parameter at the point of top-level prompt, 0x80000000 (e.g. 0 with the high
/// bit set)
/// - if the exit keyword is called with any int param less than or equal to 0xFFFF, then that int masked with the high
/// bit set. e.g. "exit 3" results in 0x80000003
/// - if the script ends (in the case of msh -command or msh -commandfile), then 0x80000000.
/// - if ctrl-break is pressed, with 0xFFFE0000
/// - if the shell.exe is passed a bad command-line parameter, with 0xFFFD0000.
/// - if the shell.exe crashes, with 0x00000000
///
/// The monitor process gets the exit code. If the high bit is set, then the shell process exited normally (though
/// possibly due to an error). If not, the shell process crashed. If the shell.exe exit code is x00000000 (crashed)
/// or 0xFFFE0000 (user hit ctrl-break), the monitor should restart the shell.exe. Otherwise, the monitor should exit
/// with the same exit code as the shell.exe.
///
/// Anyone checking the exit code of the shell or monitor can mask off the high word to determine the exit code passed
/// by the script that the shell last executed.
/// </returns>
internal static int Start(
string bannerText,
string helpText,
bool issProvidedExternally)
{
#if DEBUG
if (Environment.GetEnvironmentVariable("POWERSHELL_DEBUG_STARTUP") != null)
{
while (!System.Diagnostics.Debugger.IsAttached)
{
Thread.Sleep(1000);
}
}
#endif
// Check for external InitialSessionState configuration conflict with '-ConfigurationFile' argument.
if (issProvidedExternally && !string.IsNullOrEmpty(s_cpp.ConfigurationFile))
{
throw new ConsoleHostStartupException(ConsoleHostStrings.ShellCannotBeStartedWithConfigConflict);
}
// Put PSHOME in front of PATH so that calling `pwsh` within `pwsh` always starts the same running version.
string path = Environment.GetEnvironmentVariable("PATH");
string pshome = Utils.DefaultPowerShellAppBase;
string dotnetToolsPathSegment = $"{Path.DirectorySeparatorChar}.store{Path.DirectorySeparatorChar}powershell{Path.DirectorySeparatorChar}";
int index = pshome.IndexOf(dotnetToolsPathSegment, StringComparison.Ordinal);
if (index > 0)
{
// We're running PowerShell global tool. In this case the real entry executable should be the 'pwsh'
// or 'pwsh.exe' within the tool folder which should be the path right before the '\.store', not what
// PSHome is pointing to.
pshome = pshome[0..index];
}
pshome += Path.PathSeparator;
// To not impact startup perf, we don't remove duplicates, but we avoid adding a duplicate to the front
// we also don't handle the edge case where PATH only contains $PSHOME
if (string.IsNullOrEmpty(path))
{
Environment.SetEnvironmentVariable("PATH", pshome);
}
else if (!path.StartsWith(pshome, StringComparison.Ordinal))
{
Environment.SetEnvironmentVariable("PATH", pshome + path);
}
try
{
string profileDir = Platform.CacheDirectory;
if (!string.IsNullOrEmpty(profileDir))
{
#if !UNIX
if (!Directory.Exists(profileDir))
{
Directory.CreateDirectory(profileDir);
}
#endif
ProfileOptimization.SetProfileRoot(profileDir);
}
}
catch
{
// It's safe to ignore errors, the guarded code is just there to try and
// improve startup performance.
}
uint exitCode = ExitCodeSuccess;
Thread.CurrentThread.Name = "ConsoleHost main thread";
try
{
// We might be able to ignore console host creation error if we are running in
// server mode, which does not require a console.
HostException hostException = null;
try
{
s_theConsoleHost = ConsoleHost.CreateSingletonInstance();
}
catch (HostException e)
{
hostException = e;
}
PSHostUserInterface hostUI = s_theConsoleHost?.UI ?? new NullHostUserInterface();
s_cpp.ShowErrorHelpBanner(hostUI, bannerText, helpText);
if (s_cpp.ShowVersion)
{
// Alternatively, we could call s_theConsoleHost.UI.WriteLine(s_theConsoleHost.Version.ToString());
// or start up the engine and retrieve the information via $psversiontable.GitCommitId
// but this returns the semantic version and avoids executing a script
s_theConsoleHost.UI.WriteLine($"PowerShell {PSVersionInfo.GitCommitId}");
return 0;
}
// Servermode parameter validation check.
int serverModeCount = 0;
if (s_cpp.ServerMode)
{
serverModeCount++;
}
if (s_cpp.NamedPipeServerMode)
{
serverModeCount++;
}
if (s_cpp.SocketServerMode)
{
serverModeCount++;
}
#if !UNIX
if (s_cpp.V2SocketServerMode)
{
serverModeCount++;
}
#endif
if (serverModeCount > 1)
{
s_tracer.TraceError("Conflicting server mode parameters, parameters must be used exclusively.");
s_theConsoleHost?.ui.WriteErrorLine(ConsoleHostStrings.ConflictingServerModeParameters);
return ExitCodeBadCommandLineParameter;
}
#if !UNIX
TaskbarJumpList.CreateRunAsAdministratorJumpList();
#endif
// First check for and handle PowerShell running in a server mode.
if (s_cpp.ServerMode)
{
ApplicationInsightsTelemetry.SendPSCoreStartupTelemetry("ServerMode", s_cpp.ParametersUsedAsDouble);
ProfileOptimization.StartProfile("StartupProfileData-ServerMode");
StdIOProcessMediator.Run(
initialCommand: s_cpp.InitialCommand,
workingDirectory: s_cpp.WorkingDirectory,
configurationName: null,
configurationFile: s_cpp.ConfigurationFile,
combineErrOutStream: false);
exitCode = 0;
}
else if (s_cpp.SSHServerMode)
{
ApplicationInsightsTelemetry.SendPSCoreStartupTelemetry("SSHServer", s_cpp.ParametersUsedAsDouble);
ProfileOptimization.StartProfile("StartupProfileData-SSHServerMode");
StdIOProcessMediator.Run(
initialCommand: s_cpp.InitialCommand,
workingDirectory: null,
configurationName: null,
configurationFile: s_cpp.ConfigurationFile,
combineErrOutStream: true);
exitCode = 0;
}
else if (s_cpp.NamedPipeServerMode)
{
ApplicationInsightsTelemetry.SendPSCoreStartupTelemetry("NamedPipe", s_cpp.ParametersUsedAsDouble);
ProfileOptimization.StartProfile("StartupProfileData-NamedPipeServerMode");
RemoteSessionNamedPipeServer.RunServerMode(
configurationName: s_cpp.ConfigurationName);
exitCode = 0;
}
#if !UNIX
else if (s_cpp.V2SocketServerMode)
{
if (s_cpp.Token == null)
{
s_tracer.TraceError("Token is required for V2SocketServerMode.");
s_theConsoleHost?.ui.WriteErrorLine(string.Format(CultureInfo.CurrentCulture, ConsoleHostStrings.MissingMandatoryParameter, "-Token", "-V2SocketServerMode"));
return ExitCodeBadCommandLineParameter;
}
if (s_cpp.UTCTimestamp == null)
{
s_tracer.TraceError("UTCTimestamp is required for V2SocketServerMode.");
s_theConsoleHost?.ui.WriteErrorLine(string.Format(CultureInfo.CurrentCulture, ConsoleHostStrings.MissingMandatoryParameter, "-UTCTimestamp", "-v2socketservermode"));
return ExitCodeBadCommandLineParameter;
}
ApplicationInsightsTelemetry.SendPSCoreStartupTelemetry("V2SocketServerMode", s_cpp.ParametersUsedAsDouble);
ProfileOptimization.StartProfile("StartupProfileData-V2SocketServerMode");
HyperVSocketMediator.Run(
initialCommand: s_cpp.InitialCommand,
configurationName: s_cpp.ConfigurationName,
token: s_cpp.Token,
tokenCreationTime: s_cpp.UTCTimestamp.Value);
exitCode = 0;
}
#endif
else if (s_cpp.SocketServerMode)
{
ApplicationInsightsTelemetry.SendPSCoreStartupTelemetry("SocketServerMode", s_cpp.ParametersUsedAsDouble);
ProfileOptimization.StartProfile("StartupProfileData-SocketServerMode");
HyperVSocketMediator.Run(
initialCommand: s_cpp.InitialCommand,
configurationName: s_cpp.ConfigurationName);
exitCode = 0;
}
else
{
// Run PowerShell in normal console mode.
if (hostException != null)
{
// Unable to create console host.
throw hostException;
}
if (LoadPSReadline())
{
ProfileOptimization.StartProfile("StartupProfileData-Interactive");
if (UpdatesNotification.CanNotifyUpdates)
{
// Start a task in the background to check for the update release.
_ = UpdatesNotification.CheckForUpdates();
}
}
else
{
ProfileOptimization.StartProfile("StartupProfileData-NonInteractive");
}
s_theConsoleHost.BindBreakHandler();
IsStdOutputRedirected = Console.IsOutputRedirected;
// Send startup telemetry for ConsoleHost startup
ApplicationInsightsTelemetry.SendPSCoreStartupTelemetry("Normal", s_cpp.ParametersUsedAsDouble);
exitCode = s_theConsoleHost.Run(s_cpp, false);
}
}
finally
{
#pragma warning disable IDE0031
if (s_theConsoleHost != null)
{
#if LEGACYTELEMETRY
TelemetryAPI.ReportExitTelemetry(s_theConsoleHost);
#endif
#if UNIX
if (s_theConsoleHost.IsInteractive && s_theConsoleHost.UI.SupportsVirtualTerminal)
{
// https://github.com/dotnet/runtime/issues/27626 leaves terminal in application mode
// for now, we explicitly emit DECRST 1 sequence
s_theConsoleHost.UI.Write(DECCKM_OFF);
}
#endif
s_theConsoleHost.Dispose();
}
#pragma warning restore IDE0031
}
unchecked
{
return (int)exitCode;
}
}
internal static void ParseCommandLine(string[] args)
{
s_cpp.Parse(args);
#if !UNIX
if (s_cpp.WindowStyle.HasValue)
{
ConsoleControl.SetConsoleMode(s_cpp.WindowStyle.Value);
}
#endif
if (s_cpp.SettingsFile is not null)
{
PowerShellConfig.Instance.SetSystemConfigFilePath(s_cpp.SettingsFile);
}
// Check registry setting for a Group Policy ConfigurationName entry,
// and use it to override anything set by the user on the command line.
// It depends on setting file so 'SetSystemConfigFilePath()' should be called before.
s_cpp.ConfigurationName = CommandLineParameterParser.GetConfigurationNameFromGroupPolicy();
}
private static readonly CommandLineParameterParser s_cpp = new CommandLineParameterParser();
#if UNIX
/// <summary>
/// The break handler for the program. Dispatches a break event to the current Executor.
/// </summary>
private static void MyBreakHandler(object sender, ConsoleCancelEventArgs args)
{
// Set the Cancel property to true to prevent the process from terminating.
args.Cancel = true;
switch (args.SpecialKey)
{
case ConsoleSpecialKey.ControlC:
SpinUpBreakHandlerThread(shouldEndSession: false);
return;
case ConsoleSpecialKey.ControlBreak:
if (s_cpp.NonInteractive)
{
// ControlBreak mimics ControlC in Noninteractive shells
SpinUpBreakHandlerThread(shouldEndSession: true);
}
else
{
// Break into script debugger.
BreakIntoDebugger();
}
return;
}
}
#else
/// <summary>
/// The break handler for the program. Dispatches a break event to the current Executor.
/// </summary>
/// <param name="signal"></param>
/// <returns></returns>
private static bool MyBreakHandler(ConsoleControl.ConsoleBreakSignal signal)
{
switch (signal)
{
case ConsoleControl.ConsoleBreakSignal.CtrlBreak:
if (s_cpp.NonInteractive)
{
// ControlBreak mimics ControlC in Noninteractive shells
SpinUpBreakHandlerThread(shouldEndSession: true);
}
else
{
// Break into script debugger.
BreakIntoDebugger();
}
return true;
// Run the break handler...
case ConsoleControl.ConsoleBreakSignal.CtrlC:
SpinUpBreakHandlerThread(shouldEndSession: false);
return true;
case ConsoleControl.ConsoleBreakSignal.Logoff:
// Just ignore the logoff signal. This signal is sent to console
// apps running as service anytime *any* user logs off which means
// that PowerShell couldn't be used in services/tasks if we didn't
// suppress this signal...
return true;
case ConsoleControl.ConsoleBreakSignal.Close:
case ConsoleControl.ConsoleBreakSignal.Shutdown:
SpinUpBreakHandlerThread(shouldEndSession: true);
return false;
default:
// Log as much sqm data as possible before we exit.
SpinUpBreakHandlerThread(shouldEndSession: true);
return false;
}
}
#endif
private static bool BreakIntoDebugger()
{
ConsoleHost host = ConsoleHost.SingletonInstance;
Debugger debugger = null;
lock (host.hostGlobalLock)
{
if (host._runspaceRef.Runspace != null &&
host._runspaceRef.Runspace.GetCurrentlyRunningPipeline() != null)
{
debugger = host._runspaceRef.Runspace.Debugger;
}
}
if (debugger != null)
{
debugger.SetDebuggerStepMode(true);
return true;
}
return false;
}
/// <summary>
/// Spin up a new thread to cancel the current pipeline. This will allow subsequent break interrupts to be received even
/// if the cancellation is blocked (which can be the case when the pipeline blocks and nothing implements Cmdlet.Stop
/// properly). That is because the OS will not inject another thread when a break event occurs if one has already been
/// injected and is running.
/// </summary>
/// <param name="shouldEndSession">
/// if true, then flag the parent ConsoleHost that it should shutdown the session. If false, then only the current
/// executing instance is stopped.
///
/// </param>
private static void SpinUpBreakHandlerThread(bool shouldEndSession)
{
ConsoleHost host = ConsoleHost.SingletonInstance;
Thread bht = null;
lock (host.hostGlobalLock)
{
bht = host._breakHandlerThread;
if (!host.ShouldEndSession && shouldEndSession)
{
host.ShouldEndSession = shouldEndSession;
}
// Creation of the thread and starting it should be an atomic operation.
// otherwise the code in Run method can get instance of the breakhandlerThread
// after it is created and before started and call join on it. This will result
// in ThreadStateException.
// NTRAID#Windows OutofBand Bugs-938289-2006/07/27-hiteshr
if (bht == null)
{
// we're not already running HandleBreak on a separate thread, so run it now.
host._breakHandlerThread = new Thread(new ThreadStart(ConsoleHost.HandleBreak));
host._breakHandlerThread.Name = "ConsoleHost.HandleBreak";
host._breakHandlerThread.Start();
}
}
}
private static void HandleBreak()
{
ConsoleHost consoleHost = s_theConsoleHost;
if (consoleHost != null)
{
if (consoleHost.InDebugMode)
{
// Only stop a running user command, ignore prompt evaluation.
if (consoleHost.DebuggerCanStopCommand)
{
// Cancel any executing debugger command if in debug mode.
try
{
consoleHost.Runspace.Debugger.StopProcessCommand();
}
catch (Exception)
{
}
}
}
else
{
// Cancel the reconnected debugged running pipeline command.
if (!StopPipeline(consoleHost.runningCmd))
{
Executor.CancelCurrentExecutor();
}
}
if (consoleHost.ShouldEndSession)
{
var runspaceRef = ConsoleHost.SingletonInstance._runspaceRef;
if (runspaceRef != null)
{
var runspace = runspaceRef.Runspace;
runspace?.Close();
}
}
}
// call the console APIs directly, instead of ui.rawui.FlushInputHandle, as ui may be finalized
// already if this thread is lagging behind the main thread.
#if !UNIX
ConsoleHandle handle = ConsoleControl.GetConioDeviceHandle();
ConsoleControl.FlushConsoleInputBuffer(handle);
#endif
ConsoleHost.SingletonInstance._breakHandlerThread = null;
}
private static bool StopPipeline(Pipeline cmd)
{
if (cmd != null &&
(cmd.PipelineStateInfo.State == PipelineState.Running ||
cmd.PipelineStateInfo.State == PipelineState.Disconnected))
{
try
{
cmd.StopAsync();
return true;
}
catch (Exception)
{
}
}
return false;
}
/// <summary>
/// Create single instance of ConsoleHost.
/// </summary>
internal static ConsoleHost CreateSingletonInstance()
{
Dbg.Assert(s_theConsoleHost == null, "CreateSingletonInstance should not be called multiple times");
s_theConsoleHost = new ConsoleHost();
return s_theConsoleHost;
}
internal static ConsoleHost SingletonInstance
{
get
{
Dbg.Assert(s_theConsoleHost != null, "CreateSingletonInstance should be called before calling this method");
return s_theConsoleHost;
}
}
#endregion static methods
#region overrides
/// <summary>
/// See base class.
/// </summary>
/// <value></value>
/// <exception/>
public override string Name
{
get
{
const string myName = "ConsoleHost";
// const, no lock needed.
return myName;
}
}
/// <summary>
/// See base class.
/// </summary>
/// <value></value>
/// <exception/>
public override System.Version Version
{
get
{
// const, no lock needed.
return _ver;
}
}
/// <summary>
/// See base class.
/// </summary>
/// <value></value>
/// <exception/>
public override System.Guid InstanceId { get; } = Guid.NewGuid();
/// <summary>
/// See base class.
/// </summary>
/// <value></value>
/// <exception/>
public override PSHostUserInterface UI
{
get
{
Dbg.Assert(ui != null, "ui should have been allocated in ctor");
return ui;
}
}
/// <summary>
/// See base class.
/// </summary>
public void PushRunspace(Runspace runspace)
{
if (_runspaceRef == null)
{
return;
}
if (runspace is not RemoteRunspace remoteRunspace)
{
throw new ArgumentException(ConsoleHostStrings.PushRunspaceNotRemote, nameof(runspace));
}
remoteRunspace.StateChanged += HandleRemoteRunspaceStateChanged;
// Unsubscribe the local session debugger.
if (_runspaceRef.Runspace.Debugger != null)
{
_runspaceRef.Runspace.Debugger.DebuggerStop -= OnExecutionSuspended;
}
// Subscribe to debugger stop event.
if (remoteRunspace.Debugger != null)
{
remoteRunspace.Debugger.DebuggerStop += OnExecutionSuspended;
}
// Connect a disconnected command.
this.runningCmd = EnterPSSessionCommand.ConnectRunningPipeline(remoteRunspace);
// Push runspace.
_runspaceRef.Override(remoteRunspace, hostGlobalLock, out _isRunspacePushed);
RunspacePushed.SafeInvoke(this, EventArgs.Empty);
if (this.runningCmd != null)
{
EnterPSSessionCommand.ContinueCommand(
remoteRunspace,
this.runningCmd,
this,
InDebugMode,
_runspaceRef.OldRunspace.ExecutionContext);
}
this.runningCmd = null;
}
/// <summary>
/// Handles state changed event of the remote runspace. If the remote runspace
/// gets into a broken or closed state, writes a message and pops out the
/// runspace.
/// </summary>
/// <param name="sender">Not sure.</param>
/// <param name="eventArgs">Arguments describing this event.</param>
private void HandleRemoteRunspaceStateChanged(object sender, RunspaceStateEventArgs eventArgs)
{
RunspaceState state = eventArgs.RunspaceStateInfo.State;
switch (state)
{
case RunspaceState.Opening:
case RunspaceState.Opened:
{
return;
}
case RunspaceState.Closing:
case RunspaceState.Closed:
case RunspaceState.Broken:
case RunspaceState.Disconnected:
{
PopRunspace();
}
break;
}
}
/// <summary>
/// See base class.
/// </summary>
public void PopRunspace()
{
if (_runspaceRef == null ||
!_runspaceRef.IsRunspaceOverridden)
{
return;
}
if (_inPushedConfiguredSession)
{
// For configured endpoint sessions, end session when configured runspace is popped.
this.ShouldEndSession = true;
}
if (_runspaceRef.Runspace.Debugger != null)
{
// Unsubscribe pushed runspace debugger.
_runspaceRef.Runspace.Debugger.DebuggerStop -= OnExecutionSuspended;
StopPipeline(this.runningCmd);
if (this.InDebugMode)
{
ExitDebugMode(DebuggerResumeAction.Continue);
}
}
this.runningCmd = null;
lock (hostGlobalLock)
{
_runspaceRef.Revert();
_isRunspacePushed = false;
}
// Re-subscribe local runspace debugger.
_runspaceRef.Runspace.Debugger.DebuggerStop += OnExecutionSuspended;
// raise events outside the lock
RunspacePopped.SafeInvoke(this, EventArgs.Empty);
}
/// <summary>
/// True if a runspace is pushed; false otherwise.
/// </summary>
public bool IsRunspacePushed
{
get
{
return _isRunspacePushed;
}
}
private bool _isRunspacePushed = false;
/// <summary>
/// Returns the current runspace associated with this host.
/// </summary>
public Runspace Runspace
{
get
{
if (this.RunspaceRef == null)
{
return null;
}
return this.RunspaceRef.Runspace;
}
}
internal LocalRunspace LocalRunspace
{
get
{
if (_isRunspacePushed)
{
return RunspaceRef.OldRunspace as LocalRunspace;
}
if (RunspaceRef == null)
{
return null;
}
return RunspaceRef.Runspace as LocalRunspace;
}
}
public class ConsoleColorProxy
{
private readonly ConsoleHostUserInterface _ui;
public ConsoleColorProxy(ConsoleHostUserInterface ui)
{
ArgumentNullException.ThrowIfNull(ui);
_ui = ui;
}
public ConsoleColor FormatAccentColor
{
[SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")]
get
{
return _ui.FormatAccentColor;
}
[SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")]
set
{
_ui.FormatAccentColor = value;
}
}
public ConsoleColor ErrorAccentColor
{
[SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")]
get
{
return _ui.ErrorAccentColor;
}
[SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")]
set
{
_ui.ErrorAccentColor = value;
}
}
public ConsoleColor ErrorForegroundColor
{
[SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")]
get
{
return _ui.ErrorForegroundColor;
}
[SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")]
set
{
_ui.ErrorForegroundColor = value;
}
}
public ConsoleColor ErrorBackgroundColor
{
[SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")]
get
{
return _ui.ErrorBackgroundColor;
}
[SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")]
set
{
_ui.ErrorBackgroundColor = value;
}
}
public ConsoleColor WarningForegroundColor
{
[SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")]
get
{
return _ui.WarningForegroundColor;
}
[SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")]
set
{
_ui.WarningForegroundColor = value;
}
}
public ConsoleColor WarningBackgroundColor
{
[SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")]
get
{
return _ui.WarningBackgroundColor;
}
[SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")]
set
{
_ui.WarningBackgroundColor = value;
}
}
public ConsoleColor DebugForegroundColor
{
[SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")]
get
{
return _ui.DebugForegroundColor;
}
[SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")]
set
{
_ui.DebugForegroundColor = value;
}
}
public ConsoleColor DebugBackgroundColor
{
[SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")]
get
{
return _ui.DebugBackgroundColor;
}
[SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")]
set
{
_ui.DebugBackgroundColor = value;
}
}
public ConsoleColor VerboseForegroundColor
{
[SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")]
get
{
return _ui.VerboseForegroundColor;
}
[SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")]
set
{
_ui.VerboseForegroundColor = value;
}
}
public ConsoleColor VerboseBackgroundColor
{
[SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")]
get
{
return _ui.VerboseBackgroundColor;
}
[SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")]
set
{
_ui.VerboseBackgroundColor = value;
}
}
public ConsoleColor ProgressForegroundColor
{
[SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")]
get
{
return _ui.ProgressForegroundColor;
}
[SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")]
set
{
_ui.ProgressForegroundColor = value;
}
}
public ConsoleColor ProgressBackgroundColor
{
[SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")]
get
{
return _ui.ProgressBackgroundColor;
}
[SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")]
set
{
_ui.ProgressBackgroundColor = value;
}
}
}
/// <summary>
/// Return the actual console host object so that the user can get at
/// the unproxied methods.
/// </summary>
public override PSObject PrivateData
{
get
{
if (ui == null)
{
return null;
}
return _consoleColorProxy ??= PSObject.AsPSObject(new ConsoleColorProxy(ui));
}
}
private PSObject _consoleColorProxy;
/// <summary>
/// See base class.
/// </summary>
/// <value></value>
/// <exception/>
public override System.Globalization.CultureInfo CurrentCulture
{
get
{
lock (hostGlobalLock)
{
return CultureInfo.CurrentCulture;
}
}
}
/// <summary>
/// See base class.
/// </summary>
/// <value></value>
/// <exception/>
public override System.Globalization.CultureInfo CurrentUICulture
{
get
{
lock (hostGlobalLock)
{
return CultureInfo.CurrentUICulture;
}
}
}
/// <summary>
/// </summary>
/// <exception/>
public override void SetShouldExit(int exitCode)
{
lock (hostGlobalLock)
{
// Check for the pushed runspace scenario.
if (this.IsRunspacePushed)
{
this.PopRunspace();
}
else if (InDebugMode)
{
ExitDebugMode(DebuggerResumeAction.Continue);
}
else
{
_setShouldExitCalled = true;
_exitCodeFromRunspace = exitCode;
ShouldEndSession = true;
}
}
}
/// <summary>
/// If an input loop is running, then starts a new, nested input loop. If an input loop is not running,
/// throws an exception.
/// </summary>
/// <exception cref="InvalidOperationException">
/// If a nested prompt is entered while the host is not running at least one prompt loop.
/// </exception>
public override void EnterNestedPrompt()
{
// save the old Executor, then clear it so that a break does not cancel the pipeline from which this method
// might be called.
Executor oldCurrent = Executor.CurrentExecutor;
try
{
// this assignment is threadsafe -- protected in CurrentExecutor property
Executor.CurrentExecutor = null;
lock (hostGlobalLock)
{
IsNested = oldCurrent != null || this.ui.IsCommandCompletionRunning;
}
InputLoop.RunNewInputLoop(this, IsNested);
}
finally
{
Executor.CurrentExecutor = oldCurrent;
}
}
/// <summary>
/// See base class.
/// </summary>
/// <exception cref="InvalidOperationException">
/// If there is no nested prompt.
/// </exception>
public override void ExitNestedPrompt()
{
lock (hostGlobalLock)
{
IsNested = InputLoop.ExitCurrentLoop();
}
}
/// <summary>
/// See base class.
/// </summary>
public override void NotifyBeginApplication()
{
lock (hostGlobalLock)
{
if (++_beginApplicationNotifyCount == 1)
{
// Save the window title when first notified.
_savedWindowTitle = ui.RawUI.WindowTitle;
#if !UNIX
if (_initialConsoleMode != ConsoleControl.ConsoleModes.Unknown)
{
var outputHandle = ConsoleControl.GetActiveScreenBufferHandle();
_savedConsoleMode = ConsoleControl.GetMode(outputHandle);
ConsoleControl.SetMode(outputHandle, _initialConsoleMode);
}
#endif
}
}
}
/// <summary>
/// See base class
/// <seealso cref="NotifyBeginApplication"/>
/// </summary>
public override void NotifyEndApplication()
{
lock (hostGlobalLock)
{
if (--_beginApplicationNotifyCount == 0)
{
// Restore the window title when the last application started has ended.
ui.RawUI.WindowTitle = _savedWindowTitle;
#if !UNIX
if (_savedConsoleMode != ConsoleControl.ConsoleModes.Unknown)
{
ConsoleControl.SetMode(ConsoleControl.GetActiveScreenBufferHandle(), _savedConsoleMode);
if (_savedConsoleMode.HasFlag(ConsoleControl.ConsoleModes.VirtualTerminal))
{
// If the console output mode we just set already has 'VirtualTerminal' turned on,
// we don't need to try turn on the VT mode separately.
return;
}
}
if (ui.SupportsVirtualTerminal)
{
// Re-enable VT mode if it was previously enabled, as a native command may have turned it off.
ui.TryTurnOnVirtualTerminal();
}
#endif
}
}
}
#if LEGACYTELEMETRY
bool IHostProvidesTelemetryData.HostIsInteractive
{
get
{
return !s_cpp.NonInteractive && !s_cpp.AbortStartup &&
((s_cpp.InitialCommand == null && s_cpp.File == null) || s_cpp.NoExit);
}
}
double IHostProvidesTelemetryData.ProfileLoadTimeInMS { get { return _profileLoadTimeInMS; } }
double IHostProvidesTelemetryData.ReadyForInputTimeInMS { get { return _readyForInputTimeInMS; } }
int IHostProvidesTelemetryData.InteractiveCommandCount { get { return _interactiveCommandCount; } }
private double _readyForInputTimeInMS;
private int _interactiveCommandCount;
#endif
private double _profileLoadTimeInMS;
#endregion overrides
#region non-overrides
/// <summary>
/// Constructs a new instance.
/// </summary>
internal ConsoleHost()
{
#if !UNIX
try
{
// Capture the initial console mode before constructing our ui - that constructor
// will change the console mode to turn on VT100 support.
_initialConsoleMode = ConsoleControl.GetMode(ConsoleControl.GetActiveScreenBufferHandle());
}
catch (Exception)
{
// Make sure we skip setting the console mode later.
_savedConsoleMode = _initialConsoleMode = ConsoleControl.ConsoleModes.Unknown;
}
#endif
Thread.CurrentThread.CurrentUICulture = this.CurrentUICulture;
Thread.CurrentThread.CurrentCulture = this.CurrentCulture;
// BUG: 610329. Tell PowerShell engine to apply console
// related properties while launching Pipeline Execution
// Thread.
base.ShouldSetThreadUILanguageToZero = true;
InDebugMode = false;
_displayDebuggerBanner = true;
this.ui = new ConsoleHostUserInterface(this);
_consoleWriter = new ConsoleTextWriter(ui);
UnhandledExceptionEventHandler handler = new UnhandledExceptionEventHandler(UnhandledExceptionHandler);
AppDomain.CurrentDomain.UnhandledException += handler;
}
[System.Diagnostics.CodeAnalysis.SuppressMessage(
"Performance",
"CA1822:Mark members as static",
Justification = "Accesses instance members in preprocessor branch.")]
private void BindBreakHandler()
{
#if UNIX
Console.CancelKeyPress += new ConsoleCancelEventHandler(MyBreakHandler);
#else
breakHandlerGcHandle = GCHandle.Alloc(new ConsoleControl.BreakHandler(MyBreakHandler));
ConsoleControl.AddBreakHandler((ConsoleControl.BreakHandler)breakHandlerGcHandle.Target);
#endif
}
private void UnhandledExceptionHandler(object sender, UnhandledExceptionEventArgs args)
{
// FYI: sender is a reference to the source app domain
// The CLR will shut down the app as soon as this handler is complete, but just in case, we want
// to exit at our next opportunity.
_shouldEndSession = true;
Exception e = null;
if (args != null)
{
e = (Exception)args.ExceptionObject;
}
ui.WriteLine();
ui.Write(
ConsoleColor.Red,
ui.RawUI.BackgroundColor,
ConsoleHostStrings.UnhandledExceptionShutdownMessage);
ui.WriteLine();
}
/// <summary>
/// Disposes of this instance, per the IDisposable pattern.
/// </summary>
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
private void Dispose(bool isDisposingNotFinalizing)
{
if (!_isDisposed)
{
#if !UNIX
ConsoleControl.RemoveBreakHandler();
if (breakHandlerGcHandle.IsAllocated)
{
breakHandlerGcHandle.Free();
}
#endif
if (isDisposingNotFinalizing)
{
if (IsTranscribing)
{
StopTranscribing();
}
_outputSerializer?.End();
_errorSerializer?.End();
if (_runspaceRef != null)
{
// NTRAID#Windows Out Of Band Releases-925297-2005/12/14
try
{
_runspaceRef.Runspace.Dispose();
}
catch (InvalidRunspaceStateException)
{
}
}
_runspaceRef = null;
ui = null;
}
}
_isDisposed = true;
}
/// <summary>
/// Finalizes an instance of the <see cref="ConsoleHost"/> class.
/// </summary>
~ConsoleHost()
{
Dispose(false);
}
/// <summary>
/// Indicates if the session should be terminated or not. Typically set by the break handler for Close, Logoff, and
/// Shutdown events. Note that the only valid transition for this property is from false to true: it is not legal to
/// try to set it to false after is was set to true.
/// </summary>
/// <value>
/// true to shut down the session. false is only allowed if the property is already false.
/// </value>
internal bool ShouldEndSession
{
// This might get called from the main thread, or from the pipeline thread, or from a break handler thread.
get
{
bool result = false;
lock (hostGlobalLock)
{
result = _shouldEndSession;
}
return result;
}
set
{
lock (hostGlobalLock)
{
// If ShouldEndSession is already true, you can't set it back
Dbg.Assert(!_shouldEndSession || value,
"ShouldEndSession can only be set from false to true");
_shouldEndSession = value;
}
}
}
/// <summary>
/// The Runspace ref object being used by this Host instance. A host only opens one Runspace.
/// </summary>
/// <value></value>
internal RunspaceRef RunspaceRef
{
get
{
return _runspaceRef;
}
}
internal WrappedSerializer.DataFormat OutputFormat { get; private set; }
internal bool OutputFormatSpecified { get; private set; }
internal WrappedSerializer.DataFormat InputFormat { get; private set; }
internal WrappedDeserializer.DataFormat ErrorFormat
{
get
{
WrappedDeserializer.DataFormat format = OutputFormat;
// If this shell is invoked in non-interactive, error is redirected, and OutputFormat was not
// specified write data in error stream in xml format assuming PowerShell->PowerShell usage.
if (!OutputFormatSpecified && !IsInteractive && Console.IsErrorRedirected && _wasInitialCommandEncoded)
{
format = Serialization.DataFormat.XML;
}
return format;
}
}
internal bool IsRunningAsync
{
get
{
return !IsInteractive && ((OutputFormat != Serialization.DataFormat.Text) || Console.IsInputRedirected);
}
}
internal bool IsNested { get; private set; }
internal WrappedSerializer OutputSerializer
{
get
{
_outputSerializer ??=
new WrappedSerializer(
OutputFormat,
"Output",
Console.IsOutputRedirected ? Console.Out : ConsoleTextWriter);
return _outputSerializer;
}
}
internal WrappedSerializer ErrorSerializer
{
get
{
_errorSerializer ??=
new WrappedSerializer(
ErrorFormat,
"Error",
Console.IsErrorRedirected ? Console.Error : ConsoleTextWriter);
return _errorSerializer;
}
}
internal bool IsInteractive
{
get
{
// we're running interactive if we're in a prompt loop, and we're not reading keyboard input from stdin.
return _isRunningPromptLoop && !ui.ReadFromStdin;
}
}
internal TextWriter ConsoleTextWriter
{
get
{
Dbg.Assert(_consoleWriter != null, "consoleWriter should have been initialized");
return _consoleWriter;
}
}
/// <summary>
/// The main run loop of the program: processes command line parameters, and starts up a runspace.
/// </summary>
/// <param name="cpp">
/// Commandline parameter parser. The commandline parameter parser is expected to parse all the
/// arguments before calling this method.
/// </param>
/// <param name="isPrestartWarned">
/// Is there any warning at startup
/// </param>
/// <returns>
/// The process exit code to be returned by Main.
/// </returns>
private uint Run(CommandLineParameterParser cpp, bool isPrestartWarned)
{
Dbg.Assert(cpp != null, "CommandLine parameter parser cannot be null.");
uint exitCode = ExitCodeSuccess;
do
{
s_runspaceInitTracer.WriteLine("starting parse of command line parameters");
exitCode = ExitCodeSuccess;
if (!string.IsNullOrEmpty(cpp.InitialCommand) && isPrestartWarned)
{
s_tracer.TraceError("Start up warnings made command \"{0}\" not executed", cpp.InitialCommand);
string msg = StringUtil.Format(ConsoleHostStrings.InitialCommandNotExecuted, cpp.InitialCommand);
ui.WriteErrorLine(msg);
exitCode = ExitCodeInitFailure;
break;
}
if (cpp.AbortStartup)
{
s_tracer.WriteLine("processing of cmdline args failed, exiting");
exitCode = cpp.ExitCode;
break;
}
OutputFormat = cpp.OutputFormat;
OutputFormatSpecified = cpp.OutputFormatSpecified;
InputFormat = cpp.InputFormat;
_wasInitialCommandEncoded = cpp.WasInitialCommandEncoded;
ui.ReadFromStdin = cpp.ExplicitReadCommandsFromStdin || Console.IsInputRedirected;
ui.NoPrompt = cpp.NoPrompt;
ui.ThrowOnReadAndPrompt = cpp.ThrowOnReadAndPrompt;
_noExit = cpp.NoExit;
#if !UNIX
// See if we need to change the process-wide execution
// policy
if (!string.IsNullOrEmpty(cpp.ExecutionPolicy))
{
ExecutionPolicy executionPolicy = SecuritySupport.ParseExecutionPolicy(cpp.ExecutionPolicy);
SecuritySupport.SetExecutionPolicy(ExecutionPolicyScope.Process, executionPolicy, null);
}
#endif
// If the debug pipe name was specified, create the custom IPC channel.
if (!string.IsNullOrEmpty(cpp.CustomPipeName))
{
RemoteSessionNamedPipeServer.CreateCustomNamedPipeServer(cpp.CustomPipeName);
}
// NTRAID#Windows Out Of Band Releases-915506-2005/09/09
// Removed HandleUnexpectedExceptions infrastructure
exitCode = DoRunspaceLoop(cpp.InitialCommand, cpp.SkipProfiles, cpp.Args, cpp.StaMode, cpp.ConfigurationName, cpp.ConfigurationFile);
}
while (false);
return exitCode;
}
/// <summary>
/// Loops over the Host's sole Runspace; opens the runspace, initializes it, then recycles it if the Runspace fails.
/// </summary>
/// <returns>
/// The process exit code to be returned by Main.
/// </returns>
private uint DoRunspaceLoop(
string initialCommand,
bool skipProfiles,
Collection<CommandParameter> initialCommandArgs,
bool staMode,
string configurationName,
string configurationFilePath)
{
ExitCode = ExitCodeSuccess;
while (!ShouldEndSession)
{
RunspaceCreationEventArgs args = new RunspaceCreationEventArgs(initialCommand, skipProfiles, staMode, configurationName, configurationFilePath, initialCommandArgs);
CreateRunspace(args);
if (ExitCode == ExitCodeInitFailure)
{
break;
}
if (!_noExit)
{
// Wait for runspace to open, init, and run init script before
// setting ShouldEndSession, to allow debugger to work.
ShouldEndSession = true;
}
else
{
// Start nested prompt loop.
EnterNestedPrompt();
}
if (_setShouldExitCalled)
{
ExitCode = unchecked((uint)_exitCodeFromRunspace);
}
else
{
Executor exec = new Executor(this, false, false);
bool dollarHook = exec.ExecuteCommandAndGetResultAsBool("$global:?") ?? false;
if (dollarHook && (_lastRunspaceInitializationException == null))
{
ExitCode = ExitCodeSuccess;
}
else
{
ExitCode = ExitCodeSuccess | 0x1;
}
}
_runspaceRef.Runspace.Close();
_runspaceRef = null;
if (staMode)
{
// don't continue the session in STA mode
ShouldEndSession = true;
}
}
return ExitCode;
}
private Exception InitializeRunspaceHelper(string command, Executor exec, Executor.ExecutionOptions options)
{
Dbg.Assert(!string.IsNullOrEmpty(command), "command should have a value");
Dbg.Assert(exec != null, "non-null Executor instance needed");
s_runspaceInitTracer.WriteLine("running command {0}", command);
Exception e = null;
if (IsRunningAsync)
{
exec.ExecuteCommandAsync(command, out e, options);
}
else
{
exec.ExecuteCommand(command, out e, options);
}
if (e != null)
{
ReportException(e, exec);
}
return e;
}
private void CreateRunspace(RunspaceCreationEventArgs runspaceCreationArgs)
{
try
{
Dbg.Assert(runspaceCreationArgs != null, "Arguments to CreateRunspace should not be null.");
DoCreateRunspace(runspaceCreationArgs);
}
catch (ConsoleHostStartupException startupException)
{
ReportExceptionFallback(startupException.InnerException, startupException.Message);
ExitCode = ExitCodeInitFailure;
}
}
private static bool LoadPSReadline()
{
// Don't load PSReadline if:
// * we don't think the process will be interactive, e.g. -command or -file
// - exception: when -noexit is specified, we will be interactive after the command/file finishes
// * -noninteractive: this should be obvious, they've asked that we don't ever prompt
//
// Note that PSReadline doesn't support redirected stdin/stdout, but we don't check that here because
// a future version might, and we should automatically load it at that unknown point in the future.
// PSReadline will ideally fall back to Console.ReadLine or whatever when stdin/stdout is redirected.
return ((s_cpp.InitialCommand == null && s_cpp.File == null) || s_cpp.NoExit) && !s_cpp.NonInteractive;
}
/// <summary>
/// Opens and Initializes the Host's sole Runspace. Processes the startup scripts and runs any command passed on the
/// command line.
/// </summary>
/// <param name="args">Runspace creation event arguments.</param>
private void DoCreateRunspace(RunspaceCreationEventArgs args)
{
Dbg.Assert(_runspaceRef == null, "_runspaceRef field should be null");
Dbg.Assert(DefaultInitialSessionState != null, "DefaultInitialSessionState should not be null");
s_runspaceInitTracer.WriteLine("Calling RunspaceFactory.CreateRunspace");
// Use session configuration file if provided.
bool customConfigurationProvided = false;
if (!string.IsNullOrEmpty(args.ConfigurationFilePath))
{
try
{
// Replace DefaultInitialSessionState with the initial state configuration defined by the file.
DefaultInitialSessionState = InitialSessionState.CreateFromSessionConfigurationFile(
path: args.ConfigurationFilePath,
roleVerifier: null,
validateFile: true);
}
catch (Exception ex)
{
throw new ConsoleHostStartupException(ConsoleHostStrings.ShellCannotBeStarted, ex);
}
customConfigurationProvided = true;
}
try
{
Runspace consoleRunspace = null;
bool psReadlineFailed = false;
// Load PSReadline by default unless there is no use:
// - we're running a command/file and just exiting
// - stdin is redirected by a parent process
// - we're not interactive
// - we're explicitly reading from stdin (the '-' argument)
// It's also important to have a scenario where PSReadline is not loaded so it can be updated, e.g.
// powershell -command "Update-Module PSReadline"
// This should work just fine as long as no other instances of PowerShell are running.
ReadOnlyCollection<ModuleSpecification> defaultImportModulesList = null;
if (!customConfigurationProvided && LoadPSReadline())
{
// Create and open Runspace with PSReadline.
defaultImportModulesList = DefaultInitialSessionState.Modules;
DefaultInitialSessionState.ImportPSModule(new[] { "PSReadLine" });
consoleRunspace = RunspaceFactory.CreateRunspace(this, DefaultInitialSessionState);
try
{
OpenConsoleRunspace(consoleRunspace, args.StaMode);
}
catch (Exception)
{
consoleRunspace = null;
psReadlineFailed = true;
}
}
if (consoleRunspace == null)
{
if (psReadlineFailed)
{
// Try again but without importing the PSReadline module.
DefaultInitialSessionState.ClearPSModules();
DefaultInitialSessionState.ImportPSModule(defaultImportModulesList);
}
consoleRunspace = RunspaceFactory.CreateRunspace(this, DefaultInitialSessionState);
OpenConsoleRunspace(consoleRunspace, args.StaMode);
}
Runspace.PrimaryRunspace = consoleRunspace;
_runspaceRef = new RunspaceRef(consoleRunspace);
if (psReadlineFailed)
{
// Notify the user that PSReadline could not be loaded.
Console.Error.WriteLine(ConsoleHostStrings.CannotLoadPSReadline);
}
}
catch (Exception e)
{
// no need to do CheckForSevereException here
// since the ConsoleHostStartupException is uncaught
// higher in the call stack and the whole process
// will exit soon
throw new ConsoleHostStartupException(ConsoleHostStrings.ShellCannotBeStarted, e);
}
finally
{
// Stop PerfTrack
PSEtwLog.LogOperationalInformation(PSEventId.Perftrack_ConsoleStartupStop, PSOpcode.WinStop,
PSTask.PowershellConsoleStartup, PSKeyword.UseAlwaysOperational);
}
#if LEGACYTELEMETRY
// Record how long it took from process start to runspace open for telemetry.
_readyForInputTimeInMS = (DateTime.Now - Process.GetCurrentProcess().StartTime).TotalMilliseconds;
#endif
DoRunspaceInitialization(args);
}
private static void OpenConsoleRunspace(Runspace runspace, bool staMode)
{
if (staMode && Platform.IsWindowsDesktop)
{
runspace.ApartmentState = ApartmentState.STA;
}
runspace.ThreadOptions = PSThreadOptions.ReuseThread;
runspace.EngineActivityId = EtwActivity.GetActivityId();
s_runspaceInitTracer.WriteLine("Calling Runspace.Open");
runspace.Open();
}
private void DoRunspaceInitialization(RunspaceCreationEventArgs args)
{
if (_runspaceRef.Runspace.Debugger != null)
{
_runspaceRef.Runspace.Debugger.SetDebugMode(DebugModes.LocalScript | DebugModes.RemoteScript);
_runspaceRef.Runspace.Debugger.DebuggerStop += this.OnExecutionSuspended;
}
Executor exec = new Executor(this, false, false);
// If working directory was specified, set it
if (s_cpp != null && s_cpp.WorkingDirectory != null)
{
Pipeline tempPipeline = exec.CreatePipeline();
var command = new Command("Set-Location");
command.Parameters.Add("LiteralPath", s_cpp.WorkingDirectory);
tempPipeline.Commands.Add(command);
Exception exception;
if (IsRunningAsync)
{
exec.ExecuteCommandAsyncHelper(tempPipeline, out exception, Executor.ExecutionOptions.AddOutputter);
}
else
{
exec.ExecuteCommandHelper(tempPipeline, out exception, Executor.ExecutionOptions.AddOutputter);
}
if (exception != null)
{
_lastRunspaceInitializationException = exception;
ReportException(exception, exec);
}
}
if (!string.IsNullOrEmpty(args.ConfigurationName))
{
// If an endpoint configuration is specified then create a loop-back remote runspace targeting
// the endpoint and push onto runspace ref stack. Ignore profile and configuration scripts.
try
{
RemoteRunspace remoteRunspace = HostUtilities.CreateConfiguredRunspace(args.ConfigurationName, this);
remoteRunspace.ShouldCloseOnPop = true;
PushRunspace(remoteRunspace);
// Ensure that session ends when configured remote runspace is popped.
_inPushedConfiguredSession = true;
}
catch (Exception e)
{
throw new ConsoleHostStartupException(ConsoleHostStrings.ShellCannotBeStarted, e);
}
}
else
{
const string shellId = "Microsoft.PowerShell";
// If the system lockdown policy says "Enforce", do so. Do this after types / formatting, default functions, etc
// are loaded so that they are trusted. (Validation of their signatures is done in F&O).
var languageMode = Utils.EnforceSystemLockDownLanguageMode(_runspaceRef.Runspace.ExecutionContext);
// When displaying banner, also display the language mode if running in any restricted mode.
if (s_cpp.ShowBanner)
{
switch (languageMode)
{
case PSLanguageMode.ConstrainedLanguage:
if (SystemPolicy.GetSystemLockdownPolicy() != SystemEnforcementMode.Audit)
{
s_theConsoleHost.UI.WriteLine(ManagedEntranceStrings.ShellBannerCLMode);
}
else
{
s_theConsoleHost.UI.WriteLine(ManagedEntranceStrings.ShellBannerCLAuditMode);
}
break;
case PSLanguageMode.NoLanguage:
s_theConsoleHost.UI.WriteLine(ManagedEntranceStrings.ShellBannerNLMode);
break;
case PSLanguageMode.RestrictedLanguage:
s_theConsoleHost.UI.WriteLine(ManagedEntranceStrings.ShellBannerRLMode);
break;
default:
break;
}
}
string allUsersProfile = HostUtilities.GetFullProfileFileName(null, false);
string allUsersHostSpecificProfile = HostUtilities.GetFullProfileFileName(shellId, false);
string currentUserProfile = HostUtilities.GetFullProfileFileName(null, true);
string currentUserHostSpecificProfile = HostUtilities.GetFullProfileFileName(shellId, true);
// $PROFILE has to be set from the host
// Should be "per-user,host-specific profile.ps1"
// This should be set even if -noprofile is specified
_runspaceRef.Runspace.SessionStateProxy.SetVariable("PROFILE",
HostUtilities.GetDollarProfile(
allUsersProfile,
allUsersHostSpecificProfile,
currentUserProfile,
currentUserHostSpecificProfile));
if (!args.SkipProfiles)
{
// Run the profiles.
// Profiles are run in the following order:
// 1. host independent profile meant for all users
// 2. host specific profile meant for all users
// 3. host independent profile of the current user
// 4. host specific profile of the current user
var sw = new Stopwatch();
sw.Start();
RunProfile(allUsersProfile, exec);
RunProfile(allUsersHostSpecificProfile, exec);
RunProfile(currentUserProfile, exec);
RunProfile(currentUserHostSpecificProfile, exec);
sw.Stop();
var profileLoadTimeInMs = sw.ElapsedMilliseconds;
if (s_cpp.ShowBanner && !s_cpp.NoProfileLoadTime && profileLoadTimeInMs > 500)
{
Console.Error.WriteLine(ConsoleHostStrings.SlowProfileLoadingMessage, profileLoadTimeInMs);
}
_profileLoadTimeInMS = profileLoadTimeInMs;
}
else
{
s_tracer.WriteLine("-noprofile option specified: skipping profiles");
}
}
#if LEGACYTELEMETRY
// Startup is reported after possibly running the profile, but before running the initial command (or file)
// if one is specified.
TelemetryAPI.ReportStartupTelemetry(this);
#endif
// If a file was specified as the argument to run, then run it...
if (s_cpp != null && s_cpp.File != null)
{
string filePath = s_cpp.File;
s_tracer.WriteLine("running -file '{0}'", filePath);
Pipeline tempPipeline = exec.CreatePipeline();
Command c;
#if UNIX
// if file doesn't have .ps1 extension, we read the contents and treat it as a script to support shebang with no .ps1 extension usage
if (!filePath.EndsWith(".ps1", StringComparison.OrdinalIgnoreCase))
{
string script = File.ReadAllText(filePath);
c = new Command(script, isScript: true, useLocalScope: false);
}
else
#endif
{
c = new Command(filePath, false, false);
}
tempPipeline.Commands.Add(c);
if (args.InitialCommandArgs != null)
{
// add the args passed to the command.
foreach (CommandParameter p in args.InitialCommandArgs)
{
c.Parameters.Add(p);
}
}
// If we're not going to continue, then get the exit code out of the runspace and
// and indicate that it should be returned...
if (!_noExit && this.Runspace is not RemoteRunspace)
{
this.Runspace.ExecutionContext.ScriptCommandProcessorShouldRethrowExit = true;
}
Exception e1;
if (IsRunningAsync)
{
Executor.ExecutionOptions executionOptions = Executor.ExecutionOptions.AddOutputter;
Token[] tokens;
ParseError[] errors;
// Detect if they're using input. If so, read from it.
Ast parsedInput = Parser.ParseFile(filePath, out tokens, out errors);
if (AstSearcher.IsUsingDollarInput(parsedInput))
{
executionOptions |= Executor.ExecutionOptions.ReadInputObjects;
// We will consume all of the input to pass to the script, so don't try to read commands from stdin.
ui.ReadFromStdin = false;
}
exec.ExecuteCommandAsyncHelper(tempPipeline, out e1, executionOptions);
}
else
{
exec.ExecuteCommandHelper(tempPipeline, out e1, Executor.ExecutionOptions.AddOutputter);
}
// Pipeline.Invoke has thrown, that's bad. It means the script did not actually
// execute properly. These exceptions should be reflected in the exit code
if (e1 != null)
{
if (!_noExit)
{
// Set ExitCode to 0x1
lock (hostGlobalLock)
{
_setShouldExitCalled = true;
_exitCodeFromRunspace = 0x1;
ShouldEndSession = true;
}
}
ReportException(e1, exec);
}
}
else if (!string.IsNullOrEmpty(args.InitialCommand))
{
// Run the command passed on the command line
s_tracer.WriteLine("running initial command");
Pipeline tempPipeline = exec.CreatePipeline(args.InitialCommand, true);
if (args.InitialCommandArgs != null)
{
// add the args passed to the command.
foreach (CommandParameter p in args.InitialCommandArgs)
{
tempPipeline.Commands[0].Parameters.Add(p);
}
}
Exception e1;
if (IsRunningAsync)
{
Executor.ExecutionOptions executionOptions = Executor.ExecutionOptions.AddOutputter;
Token[] tokens;
ParseError[] errors;
// Detect if they're using input. If so, read from it.
Ast parsedInput = Parser.ParseInput(args.InitialCommand, out tokens, out errors);
if (AstSearcher.IsUsingDollarInput(parsedInput))
{
executionOptions |= Executor.ExecutionOptions.ReadInputObjects;
// We will consume all of the input to pass to the script, so don't try to read commands from stdin.
ui.ReadFromStdin = false;
}
exec.ExecuteCommandAsyncHelper(tempPipeline, out e1, executionOptions);
}
else
{
exec.ExecuteCommandHelper(tempPipeline, out e1, Executor.ExecutionOptions.AddOutputter);
}
if (e1 != null)
{
// Remember last exception
_lastRunspaceInitializationException = e1;
ReportException(e1, exec);
}
}
}
private void RunProfile(string profileFileName, Executor exec)
{
if (!string.IsNullOrEmpty(profileFileName))
{
s_runspaceInitTracer.WriteLine("checking profile" + profileFileName);
try
{
if (File.Exists(profileFileName))
{
InitializeRunspaceHelper(
". '" + EscapeSingleQuotes(profileFileName) + "'",
exec,
Executor.ExecutionOptions.AddOutputter);
}
else
{
s_runspaceInitTracer.WriteLine("profile file not found");
}
}
catch (Exception e) // Catch-all OK, 3rd party callout
{
ReportException(e, exec);
s_runspaceInitTracer.WriteLine("Could not load profile.");
}
}
}
/// <summary>
/// Escapes backtick and tick characters with a backtick, returns the result.
/// </summary>
/// <param name="str"></param>
/// <returns></returns>
internal static string EscapeSingleQuotes(string str)
{
// worst case we have to escape every character, so capacity is twice as large as input length
StringBuilder sb = new StringBuilder(str.Length * 2);
for (int i = 0; i < str.Length; ++i)
{
char c = str[i];
if (c == '\'')
{
sb.Append(c);
}
sb.Append(c);
}
string result = sb.ToString();
return result;
}
private void WriteErrorLine(string line)
{
const ConsoleColor fg = ConsoleColor.Red;
ConsoleColor bg = UI.RawUI.BackgroundColor;
UI.WriteLine(fg, bg, line);
}
// NTRAID#Windows Out Of Band Releases-915506-2005/09/09
// Removed HandleUnexpectedExceptions infrastructure
private void ReportException(Exception e, Executor exec)
{
Dbg.Assert(e != null, "must supply an Exception");
Dbg.Assert(exec != null, "must supply an Executor");
// NTRAID#Windows Out Of Band Releases-915506-2005/09/09
// Removed HandleUnexpectedExceptions infrastructure
// Attempt to write the exception into the error stream so that the normal F&O machinery will
// display it according to preferences.
object error = null;
Pipeline tempPipeline = exec.CreatePipeline();
// NTRAID#Windows OS Bugs-1143621-2005/04/08-sburns
if (e is IContainsErrorRecord icer)
{
error = icer.ErrorRecord;
}
else
{
error = (object)new ErrorRecord(e, "ConsoleHost.ReportException", ErrorCategory.NotSpecified, null);
}
PSObject wrappedError = new PSObject(error)
{
WriteStream = WriteStreamType.Error
};
Exception e1 = null;
tempPipeline.Input.Write(wrappedError);
if (IsRunningAsync)
{
exec.ExecuteCommandAsyncHelper(tempPipeline, out e1, Executor.ExecutionOptions.AddOutputter);
}
else
{
exec.ExecuteCommandHelper(tempPipeline, out e1, Executor.ExecutionOptions.AddOutputter);
}
if (e1 != null)
{
// that didn't work. Write out the error ourselves as a last resort.
ReportExceptionFallback(e, null);
}
}
/// <summary>
/// Reports an exception according to the exception reporting settings in effect.
/// </summary>
/// <param name="e">
/// The exception to report.
/// </param>
/// <param name="header">
/// Optional header message. Empty or null means "no header"
/// </param>
private void ReportExceptionFallback(Exception e, string header)
{
if (!string.IsNullOrEmpty(header))
{
Console.Error.WriteLine(header);
}
if (e is null)
{
return;
}
// See if the exception has an error record attached to it...
ErrorRecord er = null;
if (e is IContainsErrorRecord icer)
{
er = icer.ErrorRecord;
}
if (e is PSRemotingTransportException)
{
// For remoting errors use full fidelity error writer.
UI.WriteErrorLine(e.Message);
}
else if (e is TargetInvocationException)
{
Console.Error.WriteLine(e.InnerException.Message);
}
else
{
Console.Error.WriteLine(e.Message);
}
// Add the position message for the error if it's available.
if (er?.InvocationInfo is { })
{
Console.Error.WriteLine(er.InvocationInfo.PositionMessage);
}
// Print the stack trace.
Console.Error.WriteLine($"\n--- {e.GetType().FullName} ---");
Console.Error.WriteLine(e.StackTrace);
Exception inner = e.InnerException;
while (inner is { })
{
Console.Error.WriteLine($"--- inner {inner.GetType().FullName} ---");
Console.Error.WriteLine(inner.StackTrace);
inner = inner.InnerException;
}
}
/// <summary>
/// Raised when the host pops a runspace.
/// </summary>
internal event EventHandler RunspacePopped;
/// <summary>
/// Raised when the host pushes a runspace.
/// </summary>
internal event EventHandler RunspacePushed;
#endregion non-overrides
#region debugger
/// <summary>
/// Handler for debugger events.
/// </summary>
private void OnExecutionSuspended(object sender, DebuggerStopEventArgs e)
{
// Check local runspace internalHost to see if debugging is enabled.
LocalRunspace localrunspace = LocalRunspace;
if ((localrunspace != null) && !localrunspace.ExecutionContext.EngineHostInterface.DebuggerEnabled)
{
return;
}
_debuggerStopEventArgs = e;
InputLoop baseLoop = null;
try
{
if (this.IsRunspacePushed)
{
// For remote debugging block data coming from the main (not-nested)
// running command.
baseLoop = InputLoop.GetNonNestedLoop();
baseLoop?.BlockCommandOutput();
}
//
// Display the banner only once per session
//
if (_displayDebuggerBanner)
{
WriteDebuggerMessage(ConsoleHostStrings.EnteringDebugger);
WriteDebuggerMessage(string.Empty);
_displayDebuggerBanner = false;
}
//
// If we hit a breakpoint output its info
//
if (e.Breakpoints.Count > 0)
{
string format = ConsoleHostStrings.HitBreakpoint;
foreach (Breakpoint breakpoint in e.Breakpoints)
{
WriteDebuggerMessage(string.Format(CultureInfo.CurrentCulture, format, breakpoint));
}
WriteDebuggerMessage(string.Empty);
}
//
// Write the source line
//
if (e.InvocationInfo != null)
{
// line = StringUtil.Format(ConsoleHostStrings.DebuggerSourceCodeFormat, scriptFileName, e.InvocationInfo.ScriptLineNumber, e.InvocationInfo.Line);
WriteDebuggerMessage(e.InvocationInfo.PositionMessage);
}
//
// Start the debug mode
//
EnterDebugMode();
}
finally
{
_debuggerStopEventArgs = null;
baseLoop?.ResumeCommandOutput();
}
}
/// <summary>
/// Returns true if the host is in debug mode.
/// </summary>
private bool InDebugMode { get; set; }
/// <summary>
/// True when debugger command is user and available
/// for stopping.
/// </summary>
internal bool DebuggerCanStopCommand
{
get;
set;
}
private Exception _lastRunspaceInitializationException = null;
internal uint ExitCode;
/// <summary>
/// Sets the host to debug mode and enters a nested prompt.
/// </summary>
private void EnterDebugMode()
{
InDebugMode = true;
try
{
//
// Note that we need to enter the nested prompt via the InternalHost interface.
//
// EnterNestedPrompt must always be run on the local runspace.
Runspace runspace = _runspaceRef.OldRunspace ?? this.RunspaceRef.Runspace;
runspace.ExecutionContext.EngineHostInterface.EnterNestedPrompt();
}
catch (PSNotImplementedException)
{
WriteDebuggerMessage(ConsoleHostStrings.SessionDoesNotSupportDebugger);
}
finally
{
InDebugMode = false;
}
}
/// <summary>
/// Exits the debugger's nested prompt.
/// </summary>
private void ExitDebugMode(DebuggerResumeAction resumeAction)
{
_debuggerStopEventArgs.ResumeAction = resumeAction;
try
{
//
// Note that we need to exit the nested prompt via the InternalHost interface.
//
// ExitNestedPrompt must always be run on the local runspace.
Runspace runspace = _runspaceRef.OldRunspace ?? this.RunspaceRef.Runspace;
runspace.ExecutionContext.EngineHostInterface.ExitNestedPrompt();
}
catch (ExitNestedPromptException)
{
// ignore the exception
}
}
/// <summary>
/// Writes a line using the debugger colors.
/// </summary>
private void WriteDebuggerMessage(string line)
{
this.ui.WriteLine(this.ui.DebugForegroundColor, this.ui.DebugBackgroundColor, line);
}
#endregion debugger
#region aux classes
/// <summary>
/// InputLoop represents the prompt-input-execute loop of the interactive host. Input loops can be nested, meaning that
/// one input loop can be interrupted and another started; when the second ends, the first resumes.
///
/// Neither this class' instances nor its static data is threadsafe. Caller is responsible for ensuring threadsafe
/// access.
/// </summary>
private sealed class InputLoop
{
internal static void RunNewInputLoop(ConsoleHost parent, bool isNested)
{
// creates an instance and adds it to the stack and starts it running.
int stackCount = s_instanceStack.Count;
if (stackCount == PSHost.MaximumNestedPromptLevel)
{
throw PSTraceSource.NewInvalidOperationException(ConsoleHostStrings.TooManyNestedPromptsError);
}
InputLoop il = new InputLoop(parent, isNested);
s_instanceStack.Push(il);
il.Run(s_instanceStack.Count > 1);
// Once the loop has finished running, remove it from the instance stack.
InputLoop il2 = s_instanceStack.Pop();
Dbg.Assert(il == il2, "top of instance stack does not correspond to the instance pushed");
}
// Presently, this will not work if the Run loop is blocked on a ReadLine call. Whether that's a
// problem or not depends on when we expect calls to this function to be made.
/// <summary>
/// </summary>
/// <returns>True if next input loop is nested, False otherwise.</returns>
/// <exception cref="InvalidOperationException">
/// when there is no instanceStack.Count == 0
/// </exception>
internal static bool ExitCurrentLoop()
{
if (s_instanceStack.Count == 0)
{
throw PSTraceSource.NewInvalidOperationException(ConsoleHostStrings.InputExitCurrentLoopOutOfSyncError);
}
InputLoop il = s_instanceStack.Peek();
il._shouldExit = true;
// The main (non-nested) input loop has Count == 1,
// so Count == 2 is the value that indicates the next
// popped stack input loop is non-nested.
return (s_instanceStack.Count > 2);
}
/// <summary>
/// Returns current root (non-nested) loop only if there is no
/// nesting. This is used *only* by the debugger for remote debugging
/// where data handling on the base commands needs to be blocked
/// during remote debug stop handling.
/// </summary>
/// <returns></returns>
internal static InputLoop GetNonNestedLoop()
{
if (s_instanceStack.Count == 1)
{
return s_instanceStack.Peek();
}
return null;
}
private InputLoop(ConsoleHost parent, bool isNested)
{
_parent = parent;
_isNested = isNested;
_isRunspacePushed = parent.IsRunspacePushed;
parent.RunspacePopped += HandleRunspacePopped;
parent.RunspacePushed += HandleRunspacePushed;
_exec = new Executor(parent, isNested, false);
_promptExec = new Executor(parent, isNested, true);
}
private void HandleRunspacePushed(object sender, EventArgs e)
{
lock (_syncObject)
{
_isRunspacePushed = true;
_runspacePopped = false;
}
}
/// <summary>
/// When a runspace is popped, we need to reevaluate the
/// prompt.
/// </summary>
/// <param name="sender">Sender of this event, unused.</param>
/// <param name="eventArgs">Arguments describing this event, unused.</param>
private void HandleRunspacePopped(object sender, EventArgs eventArgs)
{
lock (_syncObject)
{
_isRunspacePushed = false;
_runspacePopped = true;
}
}
// NTRAID#Windows Out Of Band Releases-915506-2005/09/09
// Removed HandleUnexpectedExceptions infrastructure
/// <summary>
/// Evaluates the prompt, displays it, gets a command from the console, and executes it. Repeats until the command
/// is "exit", or until the shutdown flag is set.
/// </summary>
internal void Run(bool inputLoopIsNested)
{
PSHostUserInterface c = _parent.UI;
ConsoleHostUserInterface ui = c as ConsoleHostUserInterface;
Dbg.Assert(ui != null, "Host.UI should return an instance.");
bool inBlockMode = false;
// Use nullable so that we don't evaluate suggestions at startup.
bool? previousResponseWasEmpty = null;
var inputBlock = new StringBuilder();
while (!_parent.ShouldEndSession && !_shouldExit)
{
try
{
_parent._isRunningPromptLoop = true;
string prompt = null;
string line = null;
if (!ui.NoPrompt)
{
if (inBlockMode)
{
// use a special prompt that denotes block mode
prompt = ">> ";
}
else
{
// Make sure the cursor is at the start of the line - some external programs don't
// write a newline, so we do that for them.
if (ui.RawUI.CursorPosition.X != 0)
ui.WriteLine();
// Evaluate any suggestions
if (previousResponseWasEmpty == false)
{
EvaluateFeedbacks(ui);
}
// Then output the prompt
if (_parent.InDebugMode)
{
prompt = EvaluateDebugPrompt();
}
prompt ??= EvaluatePrompt();
}
ui.Write(prompt);
}
#if UNIX
if (c.SupportsVirtualTerminal)
{
// enable DECCKM as .NET requires cursor keys to emit VT for Console class
c.Write(DECCKM_ON);
}
#endif
previousResponseWasEmpty = false;
// There could be a profile. So there could be a user defined custom readline command
line = ui.ReadLineWithTabCompletion(_exec);
// line will be null in the case that Ctrl-C terminated the input
if (line == null)
{
previousResponseWasEmpty = true;
s_tracer.WriteLine("line is null");
if (!ui.ReadFromStdin)
{
// If we're not reading from stdin, the we probably got here
// because the user hit ctrl-C. Do a writeline to clean up
// the output...
ui.WriteLine();
}
inBlockMode = false;
if (Console.IsInputRedirected)
{
// null is also the result of reading stdin to EOF.
_parent.ShouldEndSession = true;
break;
}
continue;
}
if (string.IsNullOrWhiteSpace(line))
{
if (inBlockMode)
{
// end block mode and execute the block accumulated block
s_tracer.WriteLine("exiting block mode");
line = inputBlock.ToString();
inBlockMode = false;
}
else if (!_parent.InDebugMode)
{
previousResponseWasEmpty = true;
continue;
}
}
else
{
if (inBlockMode)
{
s_tracer.WriteLine("adding line to block");
inputBlock.Append('\n');
inputBlock.Append(line);
continue;
}
}
Dbg.Assert(line != null, "line should not be null");
Dbg.Assert(line.Length > 0 || _parent.InDebugMode, "line should not be empty unless the host is in debug mode");
Dbg.Assert(!inBlockMode, "should not be in block mode at point of pipeline execution");
Exception e = null;
if (_parent.InDebugMode)
{
DebuggerCommandResults results = ProcessDebugCommand(line, out e);
if (results.ResumeAction != null)
{
_parent.ExitDebugMode(results.ResumeAction.Value);
}
if (e != null)
{
var ex = e as PSInvalidOperationException;
if (e is PSRemotingTransportException ||
e is RemoteException ||
(ex != null &&
ex.ErrorRecord != null &&
ex.ErrorRecord.FullyQualifiedErrorId.Equals("Debugger:CannotProcessCommandNotStopped", StringComparison.OrdinalIgnoreCase)))
{
// Debugger session is broken. Exit nested loop.
_parent.ExitDebugMode(DebuggerResumeAction.Continue);
}
else
{
// Handle incomplete parse and other errors.
inBlockMode = HandleErrors(e, line, inBlockMode, ref inputBlock);
}
}
continue;
}
if (_runspacePopped)
{
string msg = StringUtil.Format(ConsoleHostStrings.CommandNotExecuted, line);
ui.WriteErrorLine(msg);
_runspacePopped = false;
}
else
{
#if UNIX
if (c.SupportsVirtualTerminal)
{
// disable DECCKM to standard mode as applications may not expect VT for cursor keys
c.Write(DECCKM_OFF);
}
#endif
if (_parent.IsRunningAsync && !_parent.IsNested)
{
_exec.ExecuteCommandAsync(line, out e, Executor.ExecutionOptions.AddOutputter | Executor.ExecutionOptions.AddToHistory);
}
else
{
_exec.ExecuteCommand(line, out e, Executor.ExecutionOptions.AddOutputter | Executor.ExecutionOptions.AddToHistory);
}
Thread bht = null;
lock (_parent.hostGlobalLock)
{
bht = _parent._breakHandlerThread;
}
bht?.Join();
// Once the pipeline has been executed, we toss any outstanding progress data and
// take down the display.
ui.ResetProgress();
if (e != null)
{
// Handle incomplete parse and other errors.
inBlockMode = HandleErrors(e, line, inBlockMode, ref inputBlock);
// If a remote runspace is pushed and it is not in a good state
// then pop it.
if (_isRunspacePushed && (_parent.Runspace != null) &&
((_parent.Runspace.RunspaceStateInfo.State != RunspaceState.Opened) ||
(_parent.Runspace.RunspaceAvailability != RunspaceAvailability.Available)))
{
_parent.PopRunspace();
}
}
#if LEGACYTELEMETRY
if (!inBlockMode)
s_theConsoleHost._interactiveCommandCount += 1;
#endif
}
}
// NTRAID#Windows Out Of Band Releases-915506-2005/09/09
// Removed HandleUnexpectedExceptions infrastructure
finally
{
_parent._isRunningPromptLoop = false;
}
}
}
internal void BlockCommandOutput()
{
if (_parent.runningCmd is RemotePipeline rCmdPipeline)
{
rCmdPipeline.DrainIncomingData();
rCmdPipeline.SuspendIncomingData();
}
else
{
_exec.BlockCommandOutput();
}
}
internal void ResumeCommandOutput()
{
if (_parent.runningCmd is RemotePipeline rCmdPipeline)
{
rCmdPipeline.ResumeIncomingData();
}
else
{
_exec.ResumeCommandOutput();
}
}
private bool HandleErrors(Exception e, string line, bool inBlockMode, ref StringBuilder inputBlock)
{
Dbg.Assert(e != null, "Exception reference should not be null.");
if (IsIncompleteParseException(e))
{
if (!inBlockMode)
{
inBlockMode = true;
inputBlock = new StringBuilder(line);
}
else
{
inputBlock.Append(line);
}
}
else
{
// an exception occurred when the command was executed. Tell the user about it.
_parent.ReportException(e, _exec);
}
return inBlockMode;
}
private DebuggerCommandResults ProcessDebugCommand(string cmd, out Exception e)
{
DebuggerCommandResults results = null;
try
{
_parent.DebuggerCanStopCommand = true;
// Use PowerShell object to write streaming data to host.
using (System.Management.Automation.PowerShell ps = System.Management.Automation.PowerShell.Create())
{
PSInvocationSettings settings = new PSInvocationSettings()
{
Host = _parent
};
PSDataCollection<PSObject> output = new PSDataCollection<PSObject>();
ps.AddCommand("Out-Default");
IAsyncResult async = ps.BeginInvoke<PSObject>(output, settings, null, null);
// Let debugger evaluate command and stream output data.
results = _parent.Runspace.Debugger.ProcessCommand(
new PSCommand(
new Command(cmd, true)),
output);
output.Complete();
ps.EndInvoke(async);
}
e = null;
}
catch (Exception ex)
{
e = ex;
results = new DebuggerCommandResults(null, false);
}
finally
{
_parent.DebuggerCanStopCommand = false;
}
// Exit debugger if command fails to evaluate.
return results ?? new DebuggerCommandResults(DebuggerResumeAction.Continue, false);
}
private static bool IsIncompleteParseException(Exception e)
{
// Check e's type.
if (e is IncompleteParseException)
{
return true;
}
// If it is remote exception ferret out the real exception.
if (e is not RemoteException remoteException || remoteException.ErrorRecord == null)
{
return false;
}
return remoteException.ErrorRecord.CategoryInfo.Reason == nameof(IncompleteParseException);
}
private void EvaluateFeedbacks(ConsoleHostUserInterface ui)
{
// Output any training suggestions
try
{
List<FeedbackResult> feedbacks = FeedbackHub.GetFeedback(_parent.Runspace);
if (feedbacks is null || feedbacks.Count is 0)
{
return;
}
HostUtilities.RenderFeedback(feedbacks, ui);
}
catch (Exception e)
{
// Catch-all OK. This is a third-party call-out.
ui.WriteErrorLine(e.Message);
LocalRunspace localRunspace = (LocalRunspace)_parent.Runspace;
localRunspace.GetExecutionContext.AppendDollarError(e);
}
}
private string EvaluatePrompt()
{
string promptString = _promptExec.ExecuteCommandAndGetResultAsString("prompt", out _);
if (string.IsNullOrEmpty(promptString))
{
promptString = ConsoleHostStrings.DefaultPrompt;
}
// Check for the pushed runspace scenario.
if (_isRunspacePushed)
{
if (_parent.Runspace is RemoteRunspace remoteRunspace)
{
promptString = HostUtilities.GetRemotePrompt(remoteRunspace, promptString, _parent._inPushedConfiguredSession);
}
}
else
{
if (_runspacePopped)
{
_runspacePopped = false;
}
}
// Return composed prompt string.
return promptString;
}
private string EvaluateDebugPrompt()
{
PSDataCollection<PSObject> output = new PSDataCollection<PSObject>();
try
{
_parent.Runspace.Debugger.ProcessCommand(
new PSCommand(new Command("prompt")),
output);
}
catch (Exception ex)
{
_parent.ReportException(ex, _exec);
}
PSObject prompt = output.ReadAndRemoveAt0();
string promptString = (prompt != null) ? (prompt.BaseObject as string) : null;
if (promptString != null && _parent.Runspace is RemoteRunspace remoteRunspace)
{
promptString = HostUtilities.GetRemotePrompt(remoteRunspace, promptString, _parent._inPushedConfiguredSession);
}
return promptString;
}
private readonly ConsoleHost _parent;
private readonly bool _isNested;
private bool _shouldExit;
private readonly Executor _exec;
private readonly Executor _promptExec;
private readonly object _syncObject = new object();
private bool _isRunspacePushed = false;
private bool _runspacePopped = false;
// The instance stack is used to keep track of which InputLoop instance should be told to exit
// when PSHost.ExitNestedPrompt is called.
// threadsafety guaranteed by enclosing class
private static readonly Stack<InputLoop> s_instanceStack = new Stack<InputLoop>();
}
[SuppressMessage("Microsoft.Design", "CA1064:ExceptionsShouldBePublic", Justification =
"This exception cannot be used outside of the console host application. It is not thrown by a library routine, only by an application.")]
private sealed class ConsoleHostStartupException : Exception
{
internal
ConsoleHostStartupException()
: base()
{
}
internal
ConsoleHostStartupException(string message)
: base(message)
{
}
internal
ConsoleHostStartupException(string message, Exception innerException)
: base(message, innerException)
{
}
}
#endregion aux classes
/// <summary>
/// By declaring runspace as ObjectRef<Runspace> we are able to hide the real runspace with
/// a remote runspace in the PushRunspace scenario. By declaring it as a mask, the variable
/// runspace becomes an indirect reference to the actual runspace which we can override with
/// a remote runspace while it is pushed. Also we can easily revert back to the original
/// runspace when the PopRunspace command is invoked.
/// </summary>
private RunspaceRef _runspaceRef;
#if !UNIX
private GCHandle breakHandlerGcHandle;
// Set to Unknown so that we avoid saving/restoring the console mode if we don't have a console.
private ConsoleControl.ConsoleModes _savedConsoleMode = ConsoleControl.ConsoleModes.Unknown;
private readonly ConsoleControl.ConsoleModes _initialConsoleMode = ConsoleControl.ConsoleModes.Unknown;
#endif
private Thread _breakHandlerThread;
private bool _isDisposed;
internal ConsoleHostUserInterface ui;
internal Lazy<TextReader> ConsoleIn { get; } = new Lazy<TextReader>(static () => Console.In);
private string _savedWindowTitle = string.Empty;
private readonly Version _ver = PSVersionInfo.PSVersion;
private int _exitCodeFromRunspace;
private bool _noExit = true;
private bool _setShouldExitCalled;
private bool _isRunningPromptLoop;
private bool _wasInitialCommandEncoded;
// hostGlobalLock is used to sync public method calls (in case multiple threads call into the host) and access to
// state that persists across method calls, like progress data. It's internal because the ui object also
// uses this same object.
internal object hostGlobalLock = new object();
// These members are possibly accessed from multiple threads (the break handler thread, a pipeline thread, or the main
// thread). We use hostGlobalLock to sync access to them.
private bool _shouldEndSession;
private int _beginApplicationNotifyCount;
private readonly ConsoleTextWriter _consoleWriter;
private WrappedSerializer _outputSerializer;
private WrappedSerializer _errorSerializer;
private bool _displayDebuggerBanner;
private DebuggerStopEventArgs _debuggerStopEventArgs;
private bool _inPushedConfiguredSession;
internal Pipeline runningCmd;
// The ConsoleHost class is a singleton. Note that there is not a thread-safety issue with these statics as there can
// only be one console host per process.
private static ConsoleHost s_theConsoleHost;
internal static InitialSessionState DefaultInitialSessionState;
[TraceSource("ConsoleHost", "ConsoleHost subclass of S.M.A.PSHost")]
private static readonly PSTraceSource s_tracer = PSTraceSource.GetTracer("ConsoleHost", "ConsoleHost subclass of S.M.A.PSHost");
[TraceSource("ConsoleHostRunspaceInit", "Initialization code for ConsoleHost's Runspace")]
private static readonly PSTraceSource s_runspaceInitTracer =
PSTraceSource.GetTracer("ConsoleHostRunspaceInit", "Initialization code for ConsoleHost's Runspace", false);
}
/// <summary>
/// Defines arguments passed to ConsoleHost.CreateRunspace.
/// </summary>
internal sealed class RunspaceCreationEventArgs : EventArgs
{
/// <summary>
/// Constructs RunspaceCreationEventArgs.
/// </summary>
internal RunspaceCreationEventArgs(
string initialCommand,
bool skipProfiles,
bool staMode,
string configurationName,
string configurationFilePath,
Collection<CommandParameter> initialCommandArgs)
{
InitialCommand = initialCommand;
SkipProfiles = skipProfiles;
StaMode = staMode;
ConfigurationName = configurationName;
ConfigurationFilePath = configurationFilePath;
InitialCommandArgs = initialCommandArgs;
}
internal string InitialCommand { get; set; }
internal bool SkipProfiles { get; set; }
internal bool StaMode { get; set; }
internal string ConfigurationName { get; set; }
internal string ConfigurationFilePath { get; set; }
internal Collection<CommandParameter> InitialCommandArgs { get; set; }
}
} // namespace
|