File size: 128,019 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 3109 3110 3111 3112 3113 3114 3115 3116 3117 3118 3119 3120 3121 3122 3123 3124 3125 3126 3127 3128 3129 3130 3131 3132 3133 3134 3135 3136 3137 3138 3139 3140 3141 3142 3143 3144 3145 3146 3147 3148 3149 3150 3151 3152 3153 3154 3155 3156 3157 3158 3159 3160 3161 3162 3163 3164 3165 3166 3167 3168 3169 3170 3171 3172 3173 3174 3175 3176 3177 3178 3179 3180 3181 3182 3183 3184 3185 3186 3187 3188 3189 3190 3191 3192 3193 3194 3195 3196 3197 3198 3199 3200 3201 3202 3203 3204 3205 3206 3207 3208 3209 3210 3211 3212 3213 3214 3215 3216 3217 3218 3219 3220 3221 3222 3223 3224 3225 3226 3227 3228 3229 3230 3231 3232 3233 3234 3235 3236 3237 3238 3239 3240 3241 3242 3243 3244 3245 3246 3247 3248 3249 3250 3251 3252 3253 3254 3255 3256 3257 3258 3259 3260 3261 3262 3263 3264 3265 3266 3267 3268 3269 3270 3271 3272 3273 3274 3275 3276 3277 3278 3279 3280 3281 3282 3283 3284 3285 3286 3287 3288 3289 3290 3291 3292 3293 3294 3295 3296 3297 3298 3299 3300 3301 3302 3303 3304 3305 3306 3307 3308 3309 3310 3311 3312 3313 3314 3315 3316 3317 3318 3319 3320 3321 3322 3323 3324 3325 3326 3327 3328 3329 3330 3331 3332 | // Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.
using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.Management.Automation.Host;
using System.Management.Automation.Internal;
using System.Management.Automation.Remoting;
using System.Management.Automation.Runspaces;
using System.Management.Automation.Runspaces.Internal;
using System.Management.Automation.Tracing;
#if !UNIX
using System.Security.Principal;
#endif
using System.Threading;
using Microsoft.PowerShell.Commands;
using Dbg = System.Management.Automation.Diagnostics;
#pragma warning disable 1634, 1691 // Stops compiler from warning about unknown warnings
namespace System.Management.Automation
{
/// <summary>
/// Remote runspace which will be created on the client side. This
/// runspace is wrapped on a RunspacePool(1).
/// </summary>
internal class RemoteRunspace : Runspace, IDisposable
{
#region Private Members
private readonly List<RemotePipeline> _runningPipelines = new List<RemotePipeline>();
private readonly object _syncRoot = new object();
private RunspaceStateInfo _runspaceStateInfo = new RunspaceStateInfo(RunspaceState.BeforeOpen);
private readonly bool _bSessionStateProxyCallInProgress = false;
private readonly RunspaceConnectionInfo _connectionInfo;
private RemoteDebugger _remoteDebugger;
private PSPrimitiveDictionary _applicationPrivateData;
private bool _disposed = false;
// the following two variables have been added for supporting
// the Invoke-Command | Invoke-Command scenario
private InvokeCommandCommand _currentInvokeCommand = null;
private long _currentLocalPipelineId = 0;
/// <summary>
/// This is queue of all the state change event which have occurred for
/// this runspace. RaiseRunspaceStateEvents raises event for each
/// item in this queue. We don't raise events from with SetRunspaceState
/// because SetRunspaceState is often called from with in the a lock.
/// Raising event with in a lock introduces chances of deadlock in GUI
/// applications.
/// </summary>
private Queue<RunspaceEventQueueItem> _runspaceEventQueue = new Queue<RunspaceEventQueueItem>();
protected class RunspaceEventQueueItem
{
public RunspaceEventQueueItem(RunspaceStateInfo runspaceStateInfo, RunspaceAvailability currentAvailability, RunspaceAvailability newAvailability)
{
this.RunspaceStateInfo = runspaceStateInfo;
this.CurrentRunspaceAvailability = currentAvailability;
this.NewRunspaceAvailability = newAvailability;
}
public RunspaceStateInfo RunspaceStateInfo;
public RunspaceAvailability CurrentRunspaceAvailability;
public RunspaceAvailability NewRunspaceAvailability;
}
/// <summary>
/// In RemoteRunspace, it is required to invoke pipeline
/// as part of open call (i.e. while state is Opening).
/// If this property is true, runspace state check is
/// not performed in AddToRunningPipelineList call.
/// </summary>
private bool _bypassRunspaceStateCheck;
/// <summary>
/// In RemoteRunspace, it is required to invoke pipeline
/// as part of open call (i.e. while state is Opening).
/// If this property is true, runspace state check is
/// not performed in AddToRunningPipelineList call.
/// </summary>
protected bool ByPassRunspaceStateCheck
{
get
{
return _bypassRunspaceStateCheck;
}
set
{
_bypassRunspaceStateCheck = value;
}
}
/// <summary>
/// Temporary place to remember whether to close this runspace on pop or not.
/// Used by Start-PSSession.
/// </summary>
internal bool ShouldCloseOnPop { get; set; } = false;
#endregion Private Members
#region Constructors
/// <summary>
/// Construct a remote runspace based on the connection information
/// and the specified host.
/// </summary>
/// <param name="typeTable">
/// The TypeTable to use while deserializing/serializing remote objects.
/// TypeTable has the following information used by serializer:
/// 1. SerializationMethod
/// 2. SerializationDepth
/// 3. SpecificSerializationProperties
/// TypeTable has the following information used by deserializer:
/// 1. TargetTypeForDeserialization
/// 2. TypeConverter
/// </param>
/// <param name="connectionInfo">connection information which identifies
/// the remote computer</param>
/// <param name="host">Host on the client.</param>
/// <param name="applicationArguments">
/// <param name="name">Friendly name for remote runspace session.</param>
/// <param name="id">Id for remote runspace.</param>
/// Application arguments the server can see in <see cref="System.Management.Automation.Remoting.PSSenderInfo.ApplicationArguments"/>
/// </param>
internal RemoteRunspace(TypeTable typeTable, RunspaceConnectionInfo connectionInfo, PSHost host, PSPrimitiveDictionary applicationArguments, string name = null, int id = -1)
{
PSEtwLog.SetActivityIdForCurrentThread(this.InstanceId);
PSEtwLog.LogOperationalVerbose(PSEventId.RunspaceConstructor, PSOpcode.Constructor,
PSTask.CreateRunspace, PSKeyword.UseAlwaysOperational,
InstanceId.ToString());
_connectionInfo = connectionInfo.Clone();
OriginalConnectionInfo = connectionInfo.Clone();
RunspacePool = new RunspacePool(1, 1, typeTable, host, applicationArguments, connectionInfo, name);
this.PSSessionId = id;
SetEventHandlers();
}
/// <summary>
/// Constructs a RemoteRunspace object based on the passed in RunspacePool object,
/// with a starting state of Disconnected.
/// </summary>
/// <param name="runspacePool"></param>
internal RemoteRunspace(RunspacePool runspacePool)
{
// The RemoteRunspace object can only be constructed this way with a RunspacePool that
// is in the disconnected state.
if (runspacePool.RunspacePoolStateInfo.State != RunspacePoolState.Disconnected
|| runspacePool.ConnectionInfo is not WSManConnectionInfo)
{
throw PSTraceSource.NewInvalidOperationException(RunspaceStrings.InvalidRunspacePool);
}
RunspacePool = runspacePool;
// The remote runspace pool object can only have the value one set for min/max pools.
// This sets the runspace pool object min/max pool values to one. The PSRP/WSMan stack
// will fail during connection if the min/max pool values do not match.
RunspacePool.RemoteRunspacePoolInternal.SetMinRunspaces(1);
RunspacePool.RemoteRunspacePoolInternal.SetMaxRunspaces(1);
_connectionInfo = runspacePool.ConnectionInfo.Clone();
// Update runspace DisconnectedOn and ExpiresOn property from WSManConnectionInfo
UpdateDisconnectExpiresOn();
// Initial state must be Disconnected.
SetRunspaceState(RunspaceState.Disconnected, null);
// Normal Availability for a disconnected runspace is "None", which means it can be connected.
// However, we can also have disconnected runspace objects that are *not* available for
// connection and in this case the Availability is set to "Busy".
_runspaceAvailability = RunspacePool.RemoteRunspacePoolInternal.AvailableForConnection ?
Runspaces.RunspaceAvailability.None : Runspaces.RunspaceAvailability.Busy;
SetEventHandlers();
PSEtwLog.SetActivityIdForCurrentThread(this.InstanceId);
PSEtwLog.LogOperationalVerbose(PSEventId.RunspaceConstructor, PSOpcode.Constructor,
PSTask.CreateRunspace, PSKeyword.UseAlwaysOperational,
this.InstanceId.ToString());
}
/// <summary>
/// Helper function to set event handlers.
/// </summary>
private void SetEventHandlers()
{
// RemoteRunspace must have the same instanceID as its contained RunspacePool instance because
// the PSRP/WinRS layer tracks remote runspace Ids.
this.InstanceId = RunspacePool.InstanceId;
_eventManager = new PSRemoteEventManager(_connectionInfo.ComputerName, this.InstanceId);
RunspacePool.StateChanged += HandleRunspacePoolStateChanged;
RunspacePool.RemoteRunspacePoolInternal.HostCallReceived += HandleHostCallReceived;
RunspacePool.RemoteRunspacePoolInternal.URIRedirectionReported += HandleURIDirectionReported;
RunspacePool.ForwardEvent += HandleRunspacePoolForwardEvent;
RunspacePool.RemoteRunspacePoolInternal.SessionCreateCompleted += HandleSessionCreateCompleted;
}
#endregion Constructors
#region Properties
/// <summary>
/// Initialsessionstate information for this runspace.
/// </summary>
public override InitialSessionState InitialSessionState
{
get
{
throw PSTraceSource.NewNotImplementedException();
}
}
/// <summary>
/// Manager for JobSourceAdapters registered in this runspace.
/// </summary>
public override JobManager JobManager
{
get
{
throw PSTraceSource.NewNotImplementedException();
}
}
/// <summary>
/// Return version of this runspace.
/// </summary>
public override Version Version { get; } = PSVersionInfo.PSVersion;
/// <summary>
/// PS Version running on server.
/// </summary>
internal Version ServerVersion { get; private set; }
/// <summary>
/// Retrieve information about current state of the runspace.
/// </summary>
public override RunspaceStateInfo RunspaceStateInfo
{
get
{
lock (_syncRoot)
{
// Do not return internal state.
return _runspaceStateInfo.Clone();
}
}
}
/// <summary>
/// This property determines whether a new thread is create for each invocation.
/// </summary>
/// <remarks>
/// Any updates to the value of this property must be done before the Runspace is opened
/// </remarks>
/// <exception cref="InvalidRunspaceStateException">
/// An attempt to change this property was made after opening the Runspace
/// </exception>
/// <exception cref="InvalidOperationException">
/// The thread options cannot be changed to the requested value
/// </exception>
public override PSThreadOptions ThreadOptions
{
get
{
return _createThreadOptions;
}
set
{
lock (_syncRoot)
{
if (value != _createThreadOptions)
{
if (this.RunspaceStateInfo.State != RunspaceState.BeforeOpen)
{
throw new InvalidRunspaceStateException(StringUtil.Format(RunspaceStrings.ChangePropertyAfterOpen));
}
_createThreadOptions = value;
}
}
}
}
private PSThreadOptions _createThreadOptions = PSThreadOptions.Default;
/// <summary>
/// Gets the current availability of the Runspace.
/// </summary>
public override RunspaceAvailability RunspaceAvailability
{
get { return _runspaceAvailability; }
protected set { _runspaceAvailability = value; }
}
private RunspaceAvailability _runspaceAvailability = RunspaceAvailability.None;
/// <summary>
/// Event raised when RunspaceState changes.
/// </summary>
public override event EventHandler<RunspaceStateEventArgs> StateChanged;
/// <summary>
/// Event raised when the availability of the Runspace changes.
/// </summary>
public override event EventHandler<RunspaceAvailabilityEventArgs> AvailabilityChanged;
/// <summary>
/// Returns true if there are any subscribers to the AvailabilityChanged event.
/// </summary>
internal override bool HasAvailabilityChangedSubscribers
{
get { return this.AvailabilityChanged != null; }
}
/// <summary>
/// Raises the AvailabilityChanged event.
/// </summary>
protected override void OnAvailabilityChanged(RunspaceAvailabilityEventArgs e)
{
EventHandler<RunspaceAvailabilityEventArgs> eh = this.AvailabilityChanged;
if (eh != null)
{
try
{
eh(this, e);
}
catch (Exception)
{
}
}
}
/// <summary>
/// Connection information to this runspace.
/// </summary>
public override RunspaceConnectionInfo ConnectionInfo
{
get
{
return _connectionInfo;
}
}
/// <summary>
/// ConnectionInfo originally supplied by the user.
/// </summary>
public override RunspaceConnectionInfo OriginalConnectionInfo { get; }
/// <summary>
/// Gets the event manager.
/// </summary>
public override PSEventManager Events
{
get
{
return _eventManager;
}
}
private PSRemoteEventManager _eventManager;
#pragma warning disable 56503
/// <summary>
/// Gets the execution context for this runspace.
/// </summary>
internal override ExecutionContext GetExecutionContext
{
get
{
throw PSTraceSource.NewNotImplementedException();
}
}
/// <summary>
/// Returns true if the internal host is in a nested prompt.
/// </summary>
internal override bool InNestedPrompt
{
get
{
return false; // nested prompts are not supported on remote runspaces
}
}
#pragma warning restore 56503
/// <summary>
/// Gets the client remote session associated with this
/// runspace.
/// </summary>
/// <remarks>This member is actually not required
/// for the product code. However, there are
/// existing transport manager tests which depend on
/// the same. Once transport manager is modified,
/// this needs to be removed</remarks>
internal ClientRemoteSession ClientRemoteSession
{
get
{
try
{
return RunspacePool.RemoteRunspacePoolInternal.DataStructureHandler.RemoteSession;
}
catch (InvalidRunspacePoolStateException e)
{
throw e.ToInvalidRunspaceStateException();
}
}
}
/// <summary>
/// Gets command information on a currently running remote command.
/// If no command is running then null is returned.
/// </summary>
internal ConnectCommandInfo RemoteCommand
{
get
{
if (RunspacePool.RemoteRunspacePoolInternal.ConnectCommands == null)
{
return null;
}
Dbg.Assert(RunspacePool.RemoteRunspacePoolInternal.ConnectCommands.Length < 2, "RemoteRunspace should have no more than one remote running command.");
if (RunspacePool.RemoteRunspacePoolInternal.ConnectCommands.Length > 0)
{
return RunspacePool.RemoteRunspacePoolInternal.ConnectCommands[0];
}
else
{
return null;
}
}
}
/// <summary>
/// Gets friendly name for the remote PSSession.
/// </summary>
internal string PSSessionName
{
get { return RunspacePool.RemoteRunspacePoolInternal.Name; }
set { RunspacePool.RemoteRunspacePoolInternal.Name = value; }
}
/// <summary>
/// Gets the Id value for the remote PSSession.
/// </summary>
internal int PSSessionId { get; set; } = -1;
/// <summary>
/// Returns true if Runspace supports disconnect.
/// </summary>
internal bool CanDisconnect
{
get { return RunspacePool.RemoteRunspacePoolInternal.CanDisconnect; }
}
/// <summary>
/// Returns true if Runspace can be connected.
/// </summary>
internal bool CanConnect
{
get { return RunspacePool.RemoteRunspacePoolInternal.AvailableForConnection; }
}
/// <summary>
/// This is used to indicate a special loopback remote session used for JEA restrictions.
/// </summary>
internal bool IsConfiguredLoopBack
{
get;
set;
}
/// <summary>
/// Debugger.
/// </summary>
public override Debugger Debugger
{
get
{
return _remoteDebugger;
}
}
#endregion Properties
#region Open
/// <summary>
/// Open the runspace Asynchronously.
/// </summary>
/// <exception cref="InvalidRunspaceStateException">
/// RunspaceState is not BeforeOpen
/// </exception>
public override void OpenAsync()
{
AssertIfStateIsBeforeOpen();
try
{
RunspacePool.BeginOpen(null, null);
}
catch (InvalidRunspacePoolStateException e)
{
throw e.ToInvalidRunspaceStateException();
}
}
/// <summary>
/// Open the runspace synchronously.
/// </summary>
/// <exception cref="InvalidRunspaceStateException">
/// RunspaceState is not BeforeOpen
/// </exception>
public override void Open()
{
AssertIfStateIsBeforeOpen();
try
{
RunspacePool.ThreadOptions = this.ThreadOptions;
RunspacePool.ApartmentState = this.ApartmentState;
RunspacePool.Open();
}
catch (InvalidRunspacePoolStateException e)
{
throw e.ToInvalidRunspaceStateException();
}
}
#endregion Open
#region Close
/// <summary>
/// Close the runspace Asynchronously.
/// </summary>
public override void CloseAsync()
{
try
{
RunspacePool.BeginClose(null, null);
}
catch (InvalidRunspacePoolStateException e)
{
throw e.ToInvalidRunspaceStateException();
}
}
/// <summary>
/// Close the runspace synchronously.
/// </summary>
/// <remarks>
/// Attempts to execute pipelines after a call to close will fail.
/// </remarks>
public override void Close()
{
try
{
IAsyncResult result = RunspacePool.BeginClose(null, null);
WaitForFinishofPipelines();
// It is possible for the result ASyncResult object to be null if the runspace
// pool is already being closed from a server initiated close event.
if (result != null)
{
RunspacePool.EndClose(result);
}
}
catch (InvalidRunspacePoolStateException e)
{
throw e.ToInvalidRunspaceStateException();
}
}
/// <summary>
/// Dispose this runspace.
/// </summary>
/// <param name="disposing">True if called from Dispose.</param>
protected override void Dispose(bool disposing)
{
try
{
if (_disposed)
{
return;
}
lock (_syncRoot)
{
if (_disposed)
{
return;
}
_disposed = true;
}
if (disposing)
{
try
{
Close();
}
catch (PSRemotingTransportException)
{
//
// If the WinRM listener has been removed before the runspace is closed, then calling
// Close() will cause a PSRemotingTransportException. We don't want this exception
// surfaced. Most developers don't expect an exception from calling Dispose.
// See [Windows 8 Bugs] 968184.
//
}
// Release RunspacePool event forwarding handlers.
_remoteDebugger?.Dispose();
try
{
RunspacePool.StateChanged -= HandleRunspacePoolStateChanged;
RunspacePool.RemoteRunspacePoolInternal.HostCallReceived -= HandleHostCallReceived;
RunspacePool.RemoteRunspacePoolInternal.URIRedirectionReported -= HandleURIDirectionReported;
RunspacePool.ForwardEvent -= HandleRunspacePoolForwardEvent;
RunspacePool.RemoteRunspacePoolInternal.SessionCreateCompleted -= HandleSessionCreateCompleted;
_eventManager = null;
RunspacePool.Dispose();
// _runspacePool = null;
}
catch (InvalidRunspacePoolStateException e)
{
throw e.ToInvalidRunspaceStateException();
}
}
}
finally
{
base.Dispose(disposing);
}
}
#endregion Close
#region Reset Runspace State
/// <summary>
/// Resets the runspace state to allow for fast reuse. Not all of the runspace
/// elements are reset. The goal is to minimize the chance of the user taking
/// accidental dependencies on prior runspace state.
/// </summary>
/// <exception cref="PSInvalidOperationException">
/// Thrown when runspace is not in proper state or availability or if the
/// reset operation fails in the remote session.
/// </exception>
public override void ResetRunspaceState()
{
PSInvalidOperationException invalidOperation = null;
if (this.RunspaceStateInfo.State != Runspaces.RunspaceState.Opened)
{
invalidOperation = PSTraceSource.NewInvalidOperationException(
RunspaceStrings.RunspaceNotInOpenedState, this.RunspaceStateInfo.State);
}
else if (this.RunspaceAvailability != Runspaces.RunspaceAvailability.Available)
{
invalidOperation = PSTraceSource.NewInvalidOperationException(
RunspaceStrings.ConcurrentInvokeNotAllowed);
}
else
{
bool success = RunspacePool.RemoteRunspacePoolInternal.ResetRunspaceState();
if (!success)
{
invalidOperation = PSTraceSource.NewInvalidOperationException();
}
}
if (invalidOperation != null)
{
invalidOperation.Source = "ResetRunspaceState";
throw invalidOperation;
}
}
#endregion
#region Disconnect-Connect
/// <summary>
/// Queries the server for disconnected runspaces and creates an array of runspace
/// objects associated with each disconnected runspace on the server. Each
/// runspace object in the returned array is in the Disconnected state and can be
/// connected to the server by calling the Connect() method on the runspace.
/// </summary>
/// <param name="connectionInfo">Connection object for the target server.</param>
/// <param name="host">Client host object.</param>
/// <param name="typeTable">TypeTable object.</param>
/// <returns>Array of Runspace objects each in the Disconnected state.</returns>
internal static Runspace[] GetRemoteRunspaces(RunspaceConnectionInfo connectionInfo, PSHost host, TypeTable typeTable)
{
List<Runspace> runspaces = new List<Runspace>();
RunspacePool[] runspacePools = RemoteRunspacePoolInternal.GetRemoteRunspacePools(connectionInfo, host, typeTable);
// We don't yet know how many runspaces there are in these runspace pool objects. This information isn't updated
// until a Connect() is performed. But we can use the ConnectCommands list to prune runspace pool objects that
// clearly have more than one command/runspace.
foreach (RunspacePool runspacePool in runspacePools)
{
if (runspacePool.RemoteRunspacePoolInternal.ConnectCommands.Length < 2)
{
runspaces.Add(new RemoteRunspace(runspacePool));
}
}
return runspaces.ToArray();
}
/// <summary>
/// Creates a single disconnected remote Runspace object based on connection information and
/// session / command identifiers.
/// </summary>
/// <param name="connectionInfo">Connection object for target machine.</param>
/// <param name="sessionId">Session Id to connect to.</param>
/// <param name="commandId">Optional command Id to connect to.</param>
/// <param name="host">Optional PSHost.</param>
/// <param name="typeTable">Optional TypeTable.</param>
/// <returns>Disconnect remote Runspace object.</returns>
internal static Runspace GetRemoteRunspace(RunspaceConnectionInfo connectionInfo, Guid sessionId, Guid? commandId, PSHost host, TypeTable typeTable)
{
RunspacePool runspacePool = RemoteRunspacePoolInternal.GetRemoteRunspacePool(
connectionInfo,
sessionId,
commandId,
host,
typeTable);
return new RemoteRunspace(runspacePool);
}
/// <summary>
/// Disconnects the runspace synchronously.
/// </summary>
/// <remarks>
/// Disconnects the remote runspace and any running command from the server
/// machine. Any data generated by the running command on the server is
/// cached on the server machine. This runspace object goes to the disconnected
/// state. This object can be reconnected to the server by calling the
/// Connect() method.
/// If the remote runspace on the server remains disconnected for the IdleTimeout
/// value (as defined in the WSManConnectionInfo object) then it is closed and
/// torn down on the server.
/// </remarks>
/// <exception cref="InvalidRunspaceStateException">
/// RunspaceState is not Opened.
/// </exception>
public override void Disconnect()
{
if (!CanDisconnect)
{
throw PSTraceSource.NewInvalidOperationException(RunspaceStrings.DisconnectNotSupportedOnServer);
}
UpdatePoolDisconnectOptions();
try
{
RunspacePool.Disconnect();
}
catch (InvalidRunspacePoolStateException e)
{
throw e.ToInvalidRunspaceStateException();
}
}
/// <summary>
/// Disconnects the runspace asynchronously.
/// </summary>
/// <remarks>
/// Disconnects the remote runspace and any running command from the server
/// machine. Any data generated by the running command on the server is
/// cached on the server machine. This runspace object goes to the disconnected
/// state. This object can be reconnected to the server by calling the
/// Connect() method.
/// If the remote runspace on the server remains disconnected for the IdleTimeout
/// value (as defined in the WSManConnectionInfo object) then it is closed and
/// torn down on the server.
/// </remarks>
/// <exception cref="InvalidRunspaceStateException">
/// RunspaceState is not Opened.
/// </exception>
public override void DisconnectAsync()
{
if (!CanDisconnect)
{
throw PSTraceSource.NewInvalidOperationException(RunspaceStrings.DisconnectNotSupportedOnServer);
}
UpdatePoolDisconnectOptions();
try
{
RunspacePool.BeginDisconnect(null, null);
}
catch (InvalidRunspacePoolStateException e)
{
throw e.ToInvalidRunspaceStateException();
}
}
/// <summary>
/// Connects the runspace to its remote counterpart synchronously.
/// </summary>
/// <remarks>
/// Connects the runspace object to its corresponding runspace on the target
/// server machine. The target server machine is identified by the connection
/// object passed in during construction. The remote runspace is identified
/// by the internal runspace Guid value.
/// </remarks>
/// <exception cref="InvalidRunspaceStateException">
/// RunspaceState is not Disconnected.
/// </exception>
public override void Connect()
{
if (!CanConnect)
{
throw PSTraceSource.NewInvalidOperationException(RunspaceStrings.CannotConnect);
}
UpdatePoolDisconnectOptions();
try
{
RunspacePool.Connect();
}
catch (InvalidRunspacePoolStateException e)
{
throw e.ToInvalidRunspaceStateException();
}
}
/// <summary>
/// Connects a runspace to its remote counterpart asynchronously.
/// </summary>
/// <remarks>
/// Connects the runspace object to its corresponding runspace on the target
/// server machine. The target server machine is identified by the connection
/// object passed in during construction. The remote runspace is identified
/// by the internal runspace Guid value.
/// </remarks>
/// <exception cref="InvalidRunspaceStateException">
/// RunspaceState is not Disconnected.
/// </exception>
public override void ConnectAsync()
{
if (!CanConnect)
{
throw PSTraceSource.NewInvalidOperationException(RunspaceStrings.CannotConnect);
}
UpdatePoolDisconnectOptions();
try
{
RunspacePool.BeginConnect(null, null);
}
catch (InvalidRunspacePoolStateException e)
{
throw e.ToInvalidRunspaceStateException();
}
}
/// <summary>
/// Creates a PipeLine object in the disconnected state for the currently disconnected
/// remote running command associated with this runspace.
/// </summary>
/// <returns>Pipeline object in disconnected state.</returns>
public override Pipeline CreateDisconnectedPipeline()
{
if (RemoteCommand == null)
{
throw PSTraceSource.NewInvalidOperationException(RunspaceStrings.NoDisconnectedCommand);
}
return new RemotePipeline(this);
}
/// <summary>
/// Creates a PowerShell object in the disconnected state for the currently disconnected
/// remote running command associated with this runspace.
/// </summary>
/// <returns>PowerShell object in disconnected state.</returns>
public override PowerShell CreateDisconnectedPowerShell()
{
if (RemoteCommand == null)
{
throw PSTraceSource.NewInvalidOperationException(RunspaceStrings.NoDisconnectedCommand);
}
return new PowerShell(RemoteCommand, this);
}
/// <summary>
/// Returns Runspace capabilities.
/// </summary>
/// <returns>RunspaceCapability.</returns>
public override RunspaceCapability GetCapabilities()
{
RunspaceCapability returnCaps = RunspaceCapability.Default;
if (CanDisconnect)
{
returnCaps |= RunspaceCapability.SupportsDisconnect;
}
if (_connectionInfo is WSManConnectionInfo)
{
return returnCaps;
}
if (_connectionInfo is NamedPipeConnectionInfo)
{
returnCaps |= RunspaceCapability.NamedPipeTransport;
}
else if (_connectionInfo is VMConnectionInfo)
{
returnCaps |= RunspaceCapability.VMSocketTransport;
}
else if (_connectionInfo is SSHConnectionInfo)
{
returnCaps |= RunspaceCapability.SSHTransport;
}
else if (_connectionInfo is ContainerConnectionInfo containerConnectionInfo)
{
if ((containerConnectionInfo != null) &&
(containerConnectionInfo.ContainerProc.RuntimeId == Guid.Empty))
{
returnCaps |= RunspaceCapability.NamedPipeTransport;
}
}
else
{
// Unknown connection info type means a custom connection/transport, which at
// minimum supports remote runspace capability starting from PowerShell v7.x.
returnCaps |= RunspaceCapability.CustomTransport;
}
return returnCaps;
}
/// <summary>
/// Update the pool disconnect options so that any changes will be
/// passed to the server during the disconnect/connect operations.
/// </summary>
private void UpdatePoolDisconnectOptions()
{
WSManConnectionInfo runspaceWSManConnectionInfo = RunspacePool.ConnectionInfo as WSManConnectionInfo;
WSManConnectionInfo wsManConnectionInfo = ConnectionInfo as WSManConnectionInfo;
Dbg.Assert(runspaceWSManConnectionInfo != null, "Disconnect-Connect feature is currently only supported for WSMan transport");
Dbg.Assert(wsManConnectionInfo != null, "Disconnect-Connect feature is currently only supported for WSMan transport");
runspaceWSManConnectionInfo.IdleTimeout = wsManConnectionInfo.IdleTimeout;
runspaceWSManConnectionInfo.OutputBufferingMode = wsManConnectionInfo.OutputBufferingMode;
}
#endregion
#region Remote Debugging
/// <summary>
/// Remote DebuggerStop event.
/// </summary>
internal event EventHandler<PSEventArgs> RemoteDebuggerStop;
/// <summary>
/// Remote BreakpointUpdated event.
/// </summary>
internal event EventHandler<PSEventArgs> RemoteDebuggerBreakpointUpdated;
#endregion
#region CreatePipeline
/// <summary>
/// Create an empty pipeline.
/// </summary>
/// <returns>An empty pipeline.</returns>
public override Pipeline CreatePipeline()
{
return CoreCreatePipeline(null, false, false);
}
/// <summary>
/// Create a pipeline from a command string.
/// </summary>
/// <param name="command">A valid command string.</param>
/// <returns>
/// A pipeline pre-filled with Commands specified in commandString.
/// </returns>
/// <exception cref="ArgumentNullException">
/// command is null
/// </exception>
public override Pipeline CreatePipeline(string command)
{
if (command == null)
{
throw PSTraceSource.NewArgumentNullException(nameof(command));
}
return CoreCreatePipeline(command, false, false);
}
/// <summary>
/// Create a pipeline from a command string.
/// </summary>
/// <param name="command">A valid command string.</param>
/// <param name="addToHistory">If true command is added to history.</param>
/// <returns>
/// A pipeline pre-filled with Commands specified in commandString.
/// </returns>
/// <exception cref="ArgumentNullException">
/// command is null
/// </exception>
public override Pipeline CreatePipeline(string command, bool addToHistory)
{
if (command == null)
{
throw PSTraceSource.NewArgumentNullException(nameof(command));
}
return CoreCreatePipeline(command, addToHistory, false);
}
/// <summary>
/// Creates a nested pipeline.
/// </summary>
/// <remarks>
/// Nested pipelines are needed for nested prompt scenario. Nested
/// prompt requires that we execute new pipelines( child pipelines)
/// while current pipeline (lets call it parent pipeline) is blocked.
/// </remarks>
/// <exception cref="PSNotSupportedException">Not supported in remoting
/// scenarios</exception>
public override Pipeline CreateNestedPipeline()
{
return CoreCreatePipeline(null, false, true);
}
/// <summary>
/// Creates a nested pipeline.
/// </summary>
/// <param name="command">A valid command string.</param>
/// <param name="addToHistory">If true command is added to history.</param>
/// <returns>
/// A pipeline pre-filled with Commands specified in commandString.
/// </returns>
/// <exception cref="PSNotSupportedException">Not supported in remoting
/// scenarios</exception>
public override Pipeline CreateNestedPipeline(string command, bool addToHistory)
{
if (command == null)
{
throw PSTraceSource.NewArgumentNullException(nameof(command));
}
return CoreCreatePipeline(command, addToHistory, true);
}
#endregion CreatePipeline
#region Running Pipeline Management
/// <summary>
/// Add the pipeline to list of pipelines in execution.
/// </summary>
/// <param name="pipeline">Pipeline to add to the
/// list of pipelines in execution</param>
/// <exception cref="InvalidRunspaceStateException">
/// Thrown if the runspace is not in the Opened state.
/// <see cref="RunspaceState"/>.
/// </exception>
/// <exception cref="ArgumentNullException">Thrown if
/// <paramref name="pipeline"/> is null.
/// </exception>
internal void AddToRunningPipelineList(RemotePipeline pipeline)
{
Dbg.Assert(pipeline != null, "caller should validate the parameter");
lock (_syncRoot)
{
if (!_bypassRunspaceStateCheck &&
_runspaceStateInfo.State != RunspaceState.Opened &&
_runspaceStateInfo.State != RunspaceState.Disconnected) // Disconnected runspaces can have running pipelines.
{
InvalidRunspaceStateException e =
new InvalidRunspaceStateException
(
StringUtil.Format(RunspaceStrings.RunspaceNotOpenForPipeline,
_runspaceStateInfo.State.ToString()
),
_runspaceStateInfo.State,
RunspaceState.Opened
);
if (this.ConnectionInfo != null)
{
e.Source = this.ConnectionInfo.ComputerName;
}
throw e;
}
// Add the pipeline to list of Executing pipeline.
// Note:_runningPipelines is always accessed with the lock so
// there is no need to create a synchronized version of list
_runningPipelines.Add(pipeline);
}
}
/// <summary>
/// Remove the pipeline from list of pipelines in execution.
/// </summary>
/// <param name="pipeline">Pipeline to remove from the
/// list of pipelines in execution</param>
/// <exception cref="ArgumentNullException">
/// Thrown if <paramref name="pipeline"/> is null.
/// </exception>
internal void RemoveFromRunningPipelineList(RemotePipeline pipeline)
{
Dbg.Assert(pipeline != null, "caller should validate the parameter");
lock (_syncRoot)
{
Dbg.Assert(_runspaceStateInfo.State != RunspaceState.BeforeOpen,
"Runspace should not be before open when pipeline is running");
// Remove the pipeline to list of Executing pipeline.
// Note:_runningPipelines is always accessed with the lock so
// there is no need to create a synchronized version of list
_runningPipelines.Remove(pipeline);
pipeline.PipelineFinishedEvent.Set();
}
}
/// <summary>
/// Check to see, if there is any other pipeline running in this
/// runspace. If not, then add this to the list of pipelines.
/// </summary>
/// <param name="pipeline">Pipeline to check and add.</param>
/// <param name="syncCall">whether this is being called from
/// a synchronous method call</param>
internal void DoConcurrentCheckAndAddToRunningPipelines(RemotePipeline pipeline, bool syncCall)
{
// Concurrency check should be done under runspace lock
lock (_syncRoot)
{
if (_bSessionStateProxyCallInProgress)
{
throw PSTraceSource.NewInvalidOperationException(RunspaceStrings.NoPipelineWhenSessionStateProxyInProgress);
}
// Delegate to pipeline to do check if it is fine to invoke if another
// pipeline is running.
pipeline.DoConcurrentCheck(syncCall);
// Finally add to the list of running pipelines.
AddToRunningPipelineList(pipeline);
}
}
#endregion Running Pipeline Management
#region SessionState Proxy
/// <summary>
/// Returns SessionState proxy object.
/// </summary>
/// <returns></returns>
internal override SessionStateProxy GetSessionStateProxy()
{
return _sessionStateProxy ??= new RemoteSessionStateProxy(this);
}
private RemoteSessionStateProxy _sessionStateProxy = null;
#endregion SessionState Proxy
#region Private Methods
private void HandleRunspacePoolStateChanged(object sender, RunspacePoolStateChangedEventArgs e)
{
RunspaceState newState = (RunspaceState)e.RunspacePoolStateInfo.State;
RunspaceState prevState = SetRunspaceState(newState, e.RunspacePoolStateInfo.Reason);
switch (newState)
{
case RunspaceState.Opened:
switch (prevState)
{
case RunspaceState.Opening:
// For newly opened remote runspaces, set the debug mode based on the
// associated host. This involves running a remote command and is Ok
// since this event is called on a worker thread and not a WinRM callback.
SetDebugModeOnOpen();
break;
case RunspaceState.Connecting:
UpdateDisconnectExpiresOn();
// Application private data containing server debug state is updated on
// a *reconstruct* connect operation when _applicationPrivateData is null.
// Pass new information to the debugger.
if (_applicationPrivateData == null)
{
_applicationPrivateData = GetApplicationPrivateData();
SetDebugInfo(_applicationPrivateData);
}
break;
}
break;
case RunspaceState.Disconnected:
UpdateDisconnectExpiresOn();
break;
}
RaiseRunspaceStateEvents();
}
/// <summary>
/// Set debug mode on remote session based on the interactive host
/// setting, if available.
/// </summary>
private void SetDebugModeOnOpen()
{
// Update client remote debugger based on server capabilities.
_applicationPrivateData = GetApplicationPrivateData();
bool serverSupportsDebugging = SetDebugInfo(_applicationPrivateData);
if (!serverSupportsDebugging) { return; }
// Set server side initial debug mode based on interactive host.
DebugModes hostDebugMode = DebugModes.Default;
try
{
IHostSupportsInteractiveSession interactiveHost =
RunspacePool.RemoteRunspacePoolInternal.Host as IHostSupportsInteractiveSession;
if (interactiveHost != null &&
interactiveHost.Runspace != null &&
interactiveHost.Runspace.Debugger != null)
{
hostDebugMode = interactiveHost.Runspace.Debugger.DebugMode;
}
}
catch (PSNotImplementedException) { }
if ((hostDebugMode & DebugModes.RemoteScript) == DebugModes.RemoteScript)
{
try
{
_remoteDebugger.SetDebugMode(hostDebugMode);
}
catch (Exception)
{
}
}
}
private bool SetDebugInfo(PSPrimitiveDictionary psApplicationPrivateData)
{
DebugModes? debugMode = null;
bool inDebugger = false;
int breakpointCount = 0;
bool breakAll = false;
UnhandledBreakpointProcessingMode unhandledBreakpointMode = UnhandledBreakpointProcessingMode.Ignore;
if (psApplicationPrivateData != null)
{
if (psApplicationPrivateData.ContainsKey(RemoteDebugger.DebugModeSetting))
{
debugMode = (DebugModes)(int)psApplicationPrivateData[RemoteDebugger.DebugModeSetting];
}
if (psApplicationPrivateData.ContainsKey(RemoteDebugger.DebugStopState))
{
inDebugger = (bool)psApplicationPrivateData[RemoteDebugger.DebugStopState];
}
if (psApplicationPrivateData.ContainsKey(RemoteDebugger.DebugBreakpointCount))
{
breakpointCount = (int)psApplicationPrivateData[RemoteDebugger.DebugBreakpointCount];
}
if (psApplicationPrivateData.ContainsKey(RemoteDebugger.BreakAllSetting))
{
breakAll = (bool)psApplicationPrivateData[RemoteDebugger.BreakAllSetting];
}
if (psApplicationPrivateData.ContainsKey(RemoteDebugger.UnhandledBreakpointModeSetting))
{
unhandledBreakpointMode = (UnhandledBreakpointProcessingMode)(int)psApplicationPrivateData[RemoteDebugger.UnhandledBreakpointModeSetting];
}
if (psApplicationPrivateData.ContainsKey(PSVersionInfo.PSVersionTableName))
{
var psVersionTable = psApplicationPrivateData[PSVersionInfo.PSVersionTableName] as PSPrimitiveDictionary;
if (psVersionTable.ContainsKey(PSVersionInfo.PSVersionName))
{
ServerVersion = PSObject.Base(psVersionTable[PSVersionInfo.PSVersionName]) as Version;
}
}
}
if (debugMode != null)
{
// Server supports remote debugging. Create Debugger object for
// this remote runspace.
Dbg.Assert(_remoteDebugger == null, "Remote runspace should not have a debugger yet.");
_remoteDebugger = new RemoteDebugger(this);
// Set initial debugger state.
_remoteDebugger.SetClientDebugInfo(debugMode, inDebugger, breakpointCount, breakAll, unhandledBreakpointMode, ServerVersion);
return true;
}
return false;
}
/// <summary>
/// Asserts if the current state of the runspace is BeforeOpen.
/// </summary>
private void AssertIfStateIsBeforeOpen()
{
lock (_syncRoot)
{
// Call fails if RunspaceState is not BeforeOpen.
if (_runspaceStateInfo.State != RunspaceState.BeforeOpen)
{
InvalidRunspaceStateException e =
new InvalidRunspaceStateException
(
StringUtil.Format(RunspaceStrings.CannotOpenAgain,
new object[] { _runspaceStateInfo.State.ToString() }
),
_runspaceStateInfo.State,
RunspaceState.BeforeOpen
);
throw e;
}
}
}
/// <summary>
/// Set the new runspace state.
/// </summary>
/// <param name="state">The new state.</param>
/// <param name="reason">An exception indicating the state change is the
/// result of an error, otherwise; null.
/// </param>
/// <returns>Previous runspace state.</returns>
/// <remarks>
/// Sets the internal runspace state information member variable. It also
/// adds RunspaceStateInfo to a queue.
/// RaiseRunspaceStateEvents raises event for each item in this queue.
/// </remarks>
private RunspaceState SetRunspaceState(RunspaceState state, Exception reason)
{
RunspaceState prevState;
lock (_syncRoot)
{
prevState = _runspaceStateInfo.State;
if (state != prevState)
{
_runspaceStateInfo = new RunspaceStateInfo(state, reason);
// Add _runspaceStateInfo to _runspaceEventQueue.
// RaiseRunspaceStateEvents will raise event for each item
// in this queue.
// Note:We are doing clone here instead of passing the member
// _runspaceStateInfo because we donot want outside
// to change our runspace state.
RunspaceAvailability previousAvailability = _runspaceAvailability;
this.UpdateRunspaceAvailability(_runspaceStateInfo.State, false);
_runspaceEventQueue.Enqueue(
new RunspaceEventQueueItem(
_runspaceStateInfo.Clone(),
previousAvailability,
_runspaceAvailability));
PSEtwLog.LogOperationalVerbose(PSEventId.RunspaceStateChange, PSOpcode.Open,
PSTask.CreateRunspace, PSKeyword.UseAlwaysOperational,
state.ToString());
}
}
return prevState;
}
/// <summary>
/// Raises events for changes in runspace state.
/// </summary>
private void RaiseRunspaceStateEvents()
{
Queue<RunspaceEventQueueItem> tempEventQueue = null;
EventHandler<RunspaceStateEventArgs> stateChanged = null;
bool hasAvailabilityChangedSubscribers = false;
lock (_syncRoot)
{
stateChanged = this.StateChanged;
hasAvailabilityChangedSubscribers = this.HasAvailabilityChangedSubscribers;
if (stateChanged != null || hasAvailabilityChangedSubscribers)
{
tempEventQueue = _runspaceEventQueue;
_runspaceEventQueue = new Queue<RunspaceEventQueueItem>();
}
else
{
// Clear the events if there are no EventHandlers. This
// ensures that events do not get called for state
// changes prior to their registration.
_runspaceEventQueue.Clear();
}
}
if (tempEventQueue != null)
{
while (tempEventQueue.Count > 0)
{
RunspaceEventQueueItem queueItem = tempEventQueue.Dequeue();
if (hasAvailabilityChangedSubscribers && queueItem.NewRunspaceAvailability != queueItem.CurrentRunspaceAvailability)
{
this.OnAvailabilityChanged(new RunspaceAvailabilityEventArgs(queueItem.NewRunspaceAvailability));
}
// Exception raised by events are not error condition for runspace
// object.
if (stateChanged != null)
{
try
{
stateChanged(this, new RunspaceStateEventArgs(queueItem.RunspaceStateInfo));
}
catch (Exception)
{
}
}
}
}
}
/// <summary>
/// Creates a pipeline.
/// </summary>
/// <param name="command"></param>
/// <param name="addToHistory"></param>
/// <param name="isNested"></param>
/// <returns></returns>
private Pipeline CoreCreatePipeline(string command, bool addToHistory, bool isNested)
{
return new RemotePipeline(this, command, addToHistory, isNested);
}
/// <summary>
/// Waits till all the pipelines running in the runspace have
/// finished execution.
/// </summary>
[SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Finishof")]
private bool WaitForFinishofPipelines()
{
// Take a snapshot of list of active pipelines.
// Note:Before we enter to this CloseHelper routine
// CoreClose has already set the state of Runspace
// to closing. So no new pipelines can be executed on this
// runspace and so no new pipelines will be added to
// _runningPipelines. However we still need to lock because
// running pipelines can be removed from this.
RemotePipeline[] runningPipelines;
lock (_syncRoot)
{
runningPipelines = _runningPipelines.ToArray();
}
if (runningPipelines.Length > 0)
{
WaitHandle[] waitHandles = new WaitHandle[runningPipelines.Length];
for (int i = 0; i < runningPipelines.Length; i++)
{
waitHandles[i] = runningPipelines[i].PipelineFinishedEvent;
}
return WaitHandle.WaitAll(waitHandles);
}
else
{
return true;
}
}
/// <summary>
/// Gets the currently executing pipeline.
/// </summary>
/// <remarks>Internal because it is needed by invoke-history</remarks>
internal override Pipeline GetCurrentlyRunningPipeline()
{
lock (_syncRoot)
{
if (_runningPipelines.Count != 0)
{
return (Pipeline)_runningPipelines[_runningPipelines.Count - 1];
}
else
{
return null;
}
}
}
/// <summary>
/// Handles any host calls received from the server.
/// </summary>
/// <param name="sender">Sender of this information, unused.</param>
/// <param name="eventArgs">arguments describing this event, contains
/// a RemoteHostCall object</param>
private void HandleHostCallReceived(object sender, RemoteDataEventArgs<RemoteHostCall> eventArgs)
{
ClientMethodExecutor.Dispatch(
RunspacePool.RemoteRunspacePoolInternal.DataStructureHandler.TransportManager,
RunspacePool.RemoteRunspacePoolInternal.Host,
null, /* error stream */
null, /* method executor stream */
false, /* is method stream enabled */
RunspacePool.RemoteRunspacePoolInternal,
Guid.Empty, /* powershell id */
eventArgs.Data);
}
/// <summary>
/// When the client remote session reports a URI redirection, this method will report the
/// message to the user as a Warning using Host method calls.
/// </summary>
/// <param name="sender"></param>
/// <param name="eventArgs"></param>
private void HandleURIDirectionReported(object sender, RemoteDataEventArgs<Uri> eventArgs)
{
WSManConnectionInfo wsmanConnectionInfo = _connectionInfo as WSManConnectionInfo;
if (wsmanConnectionInfo != null)
{
// change the runspace's uri to the new URI.
wsmanConnectionInfo.ConnectionUri = eventArgs.Data;
URIRedirectionReported.SafeInvoke(this, eventArgs);
}
}
/// <summary>
/// Forward the events from the runspace pool to the current instance.
/// </summary>
private void HandleRunspacePoolForwardEvent(object sender, PSEventArgs e)
{
if (e.SourceIdentifier.Equals(RemoteDebugger.RemoteDebuggerStopEvent))
{
// Special processing for forwarded remote DebuggerStop event.
RemoteDebuggerStop.SafeInvoke(this, e);
}
else if (e.SourceIdentifier.Equals(RemoteDebugger.RemoteDebuggerBreakpointUpdatedEvent))
{
// Special processing for forwarded remote DebuggerBreakpointUpdated event.
RemoteDebuggerBreakpointUpdated.SafeInvoke(this, e);
}
else
{
_eventManager.AddForwardedEvent(e);
}
}
/// <summary>
/// The session has been successfully created.
/// </summary>
/// <param name="sender"></param>
/// <param name="eventArgs"></param>
private void HandleSessionCreateCompleted(object sender, CreateCompleteEventArgs eventArgs)
{
// Update connectionInfo with updated information from the transport.
if (eventArgs != null)
{
_connectionInfo.IdleTimeout = eventArgs.ConnectionInfo.IdleTimeout;
_connectionInfo.MaxIdleTimeout = eventArgs.ConnectionInfo.MaxIdleTimeout;
WSManConnectionInfo wsmanConnectionInfo = _connectionInfo as WSManConnectionInfo;
if (wsmanConnectionInfo != null)
{
wsmanConnectionInfo.OutputBufferingMode =
((WSManConnectionInfo)eventArgs.ConnectionInfo).OutputBufferingMode;
}
}
}
/// <summary>
/// Updates runspace DisconnectedOn/ExpiresOn based on RS Pool connectionInfo.
/// </summary>
private void UpdateDisconnectExpiresOn()
{
WSManConnectionInfo wsmanConnectionInfo = RunspacePool.RemoteRunspacePoolInternal.ConnectionInfo as WSManConnectionInfo;
if (wsmanConnectionInfo != null)
{
this.DisconnectedOn = wsmanConnectionInfo.DisconnectedOn;
this.ExpiresOn = wsmanConnectionInfo.ExpiresOn;
}
}
#endregion Private Methods
#region Internal Methods
/// <summary>
/// Determines if another Invoke-Command is executing
/// in this runspace in the currently running local pipeline
/// ahead on the specified invoke-command.
/// </summary>
/// <param name="invokeCommand">current invoke-command
/// instance</param>
/// <param name="localPipelineId">Local pipeline id.</param>
/// <returns>True, if another invoke-command is running
/// before, false otherwise.</returns>
internal bool IsAnotherInvokeCommandExecuting(InvokeCommandCommand invokeCommand,
long localPipelineId)
{
// the invoke-command's pipeline should be the currently
// running pipeline. This will ensure that, we do not
// return true, when one invoke-command is running as a
// job and another invoke-command is entered at the
// console prompt
if (_currentLocalPipelineId != localPipelineId && _currentLocalPipelineId != 0)
{
return false;
}
else
{
// the local pipeline ids are the same
// this invoke command is running may be
// running in the same pipeline as another
// invoke command
if (_currentInvokeCommand == null)
{
// this is the first invoke-command, just
// set the reference
SetCurrentInvokeCommand(invokeCommand, localPipelineId);
return false;
}
else if (_currentInvokeCommand.Equals(invokeCommand))
{
// the currently active invoke command is the one
// specified
return false;
}
else
{
// the local pipeline id is the same and there
// is another invoke command that is active already
return true;
}
}
}
/// <summary>
/// Keeps track of the current invoke command executing
/// within the current local pipeline.
/// </summary>
/// <param name="invokeCommand">reference to invoke command
/// which is currently being processed</param>
/// <param name="localPipelineId">The local pipeline id.</param>
internal void SetCurrentInvokeCommand(InvokeCommandCommand invokeCommand,
long localPipelineId)
{
Dbg.Assert(invokeCommand != null, "InvokeCommand instance cannot be null, use ClearInvokeCommand() method to reset current command");
Dbg.Assert(localPipelineId != 0, "Local pipeline id needs to be supplied - cannot be 0");
_currentInvokeCommand = invokeCommand;
_currentLocalPipelineId = localPipelineId;
}
/// <summary>
/// Clears the current invoke-command reference stored within
/// this remote runspace.
/// </summary>
internal void ClearInvokeCommand()
{
_currentLocalPipelineId = 0;
_currentInvokeCommand = null;
}
/// <summary>
/// Aborts any current Opening process. If runspace is not opening then this has no effect.
/// This is currently *only* for named pipe connections where a connection
/// to a process is limited to a single client.
/// </summary>
internal void AbortOpen()
{
System.Management.Automation.Remoting.Client.NamedPipeClientSessionTransportManager transportManager =
RunspacePool.RemoteRunspacePoolInternal.DataStructureHandler.TransportManager as System.Management.Automation.Remoting.Client.NamedPipeClientSessionTransportManager;
transportManager?.AbortConnect();
}
#endregion Internal Methods
#region Misc Properties / Events
/// <summary>
/// The runspace pool that this remote runspace wraps.
/// </summary>
internal RunspacePool RunspacePool { get; }
/// <summary>
/// EventHandler used to report connection URI redirections to the application.
/// </summary>
internal event EventHandler<RemoteDataEventArgs<Uri>> URIRedirectionReported;
#endregion Misc Properties
#region Application private data
/// <summary>
/// Private data to be used by applications built on top of PowerShell.
///
/// Remote runspace gets its application private data from the server (when creating the remote runspace pool)
/// - calling this method on a remote runspace will block until the data is received from the server.
///
/// Runspaces that are part of a <see cref="RunspacePool"/> inherit application private data from the pool.
/// </summary>
public override PSPrimitiveDictionary GetApplicationPrivateData()
{
try
{
return RunspacePool.GetApplicationPrivateData();
}
catch (InvalidRunspacePoolStateException e)
{
throw e.ToInvalidRunspaceStateException();
}
}
internal override void SetApplicationPrivateData(PSPrimitiveDictionary applicationPrivateData)
{
Dbg.Assert(false, "RemoteRunspace.SetApplicationPrivateData shouldn't be called - this runspace does not belong to a runspace pool [although it does use a remote runspace pool internally]");
}
#endregion
}
#region Remote Debugger
/// <summary>
/// RemoteDebugger.
/// </summary>
internal sealed class RemoteDebugger : Debugger, IDisposable
{
#region Members
private readonly RemoteRunspace _runspace;
private PowerShell _psDebuggerCommand;
private bool _remoteDebugSupported;
private bool _isActive;
private int _breakpointCount;
private RemoteDebuggingCapability _remoteDebuggingCapability;
private bool? _remoteBreakpointManagementIsSupported;
private volatile bool _handleDebuggerStop;
private bool _isDebuggerSteppingEnabled;
private UnhandledBreakpointProcessingMode _unhandledBreakpointMode;
private bool _detachCommand;
#if !UNIX
// Windows impersonation flow
private WindowsIdentity _identityToPersonate;
private bool _identityPersonationChecked;
#endif
/// <summary>
/// RemoteDebuggerStopEvent.
/// </summary>
public const string RemoteDebuggerStopEvent = "PSInternalRemoteDebuggerStopEvent";
/// <summary>
/// RemoteDebuggerBreakpointUpdatedEvent.
/// </summary>
public const string RemoteDebuggerBreakpointUpdatedEvent = "PSInternalRemoteDebuggerBreakpointUpdatedEvent";
// Remote debugger settings
public const string DebugModeSetting = "DebugMode";
public const string DebugStopState = "DebugStop";
public const string DebugBreakpointCount = "DebugBreakpointCount";
public const string BreakAllSetting = "BreakAll";
public const string UnhandledBreakpointModeSetting = "UnhandledBreakpointMode";
#endregion
#region Constructor
private RemoteDebugger() { }
/// <summary>
/// Constructor.
/// </summary>
/// <param name="runspace">Associated remote runspace.</param>
public RemoteDebugger(RemoteRunspace runspace)
{
if (runspace == null)
{
throw new PSArgumentNullException(nameof(runspace));
}
_runspace = runspace;
_unhandledBreakpointMode = UnhandledBreakpointProcessingMode.Ignore;
// Hook up remote debugger forwarded event handlers.
_runspace.RemoteDebuggerStop += HandleForwardedDebuggerStopEvent;
_runspace.RemoteDebuggerBreakpointUpdated += HandleForwardedDebuggerBreakpointUpdatedEvent;
}
#endregion
#region Class overrides
/// <summary>
/// Process debugger command.
/// </summary>
/// <param name="command">Debugger PSCommand.</param>
/// <param name="output">Output.</param>
/// <returns>DebuggerCommandResults.</returns>
public override DebuggerCommandResults ProcessCommand(PSCommand command, PSDataCollection<PSObject> output)
{
CheckForValidateState();
_detachCommand = false;
if (command == null)
{
throw new PSArgumentNullException(nameof(command));
}
if (output == null)
{
throw new PSArgumentNullException(nameof(output));
}
if (!DebuggerStopped)
{
throw new PSInvalidOperationException(
DebuggerStrings.CannotProcessDebuggerCommandNotStopped,
null,
Debugger.CannotProcessCommandNotStopped,
ErrorCategory.InvalidOperation,
null);
}
DebuggerCommandResults results = null;
// Execute command on server.
bool executionError = false;
using (_psDebuggerCommand = GetNestedPowerShell())
{
foreach (var cmd in command.Commands)
{
cmd.MergeMyResults(PipelineResultTypes.All, PipelineResultTypes.Output);
_psDebuggerCommand.AddCommand(cmd);
}
PSDataCollection<PSObject> internalOutput = new PSDataCollection<PSObject>();
internalOutput.DataAdded += (sender, args) =>
{
foreach (var item in internalOutput.ReadAll())
{
if (item == null) { return; }
DebuggerCommand dbgCmd = item.BaseObject as DebuggerCommand;
if (dbgCmd != null)
{
bool executedByDebugger = (dbgCmd.ResumeAction != null || dbgCmd.ExecutedByDebugger);
results = new DebuggerCommandResults(dbgCmd.ResumeAction, executedByDebugger);
}
else if (item.BaseObject is DebuggerCommandResults)
{
results = item.BaseObject as DebuggerCommandResults;
}
else
{
output.Add(item);
}
}
};
try
{
_psDebuggerCommand.Invoke(null, internalOutput, null);
}
catch (Exception e)
{
executionError = true;
RemoteException re = e as RemoteException;
if ((re != null) && (re.ErrorRecord != null))
{
// Allow the IncompleteParseException to throw so that the console
// can handle here strings and continued parsing.
if (re.ErrorRecord.CategoryInfo.Reason == nameof(IncompleteParseException))
{
throw new IncompleteParseException(
re.ErrorRecord.Exception?.Message,
re.ErrorRecord.FullyQualifiedErrorId);
}
// Allow the RemoteException and InvalidRunspacePoolStateException to propagate so that the host can
// clean up the debug session.
if ((re.ErrorRecord.CategoryInfo.Reason == nameof(InvalidRunspacePoolStateException)) ||
(re.ErrorRecord.CategoryInfo.Reason == nameof(RemoteException)))
{
throw new PSRemotingTransportException(
(re.ErrorRecord.Exception != null) ? re.ErrorRecord.Exception.Message : string.Empty);
}
}
// Allow all PSRemotingTransportException and RemoteException errors to propagate as this
// indicates a broken debug session.
if ((e is PSRemotingTransportException) || (e is RemoteException))
{
throw;
}
output.Add(
new PSObject(
new ErrorRecord(
e,
"DebuggerError",
ErrorCategory.InvalidOperation,
null)));
}
}
executionError = executionError || _psDebuggerCommand.HadErrors;
_psDebuggerCommand = null;
// Special processing when the detach command is run.
_detachCommand = (!executionError) && (command.Commands.Count > 0) && (command.Commands[0].CommandText.Equals("Detach", StringComparison.OrdinalIgnoreCase));
return results ?? new DebuggerCommandResults(null, false);
}
/// <summary>
/// StopProcessCommand.
/// </summary>
public override void StopProcessCommand()
{
CheckForValidateState();
PowerShell ps = _psDebuggerCommand;
if ((ps != null) &&
(ps.InvocationStateInfo.State == PSInvocationState.Running))
{
ps.BeginStop(null, null);
}
}
/// <summary>
/// Adds the provided set of breakpoints to the debugger.
/// </summary>
/// <param name="breakpoints">Breakpoints to set.</param>
/// <param name="runspaceId">The runspace id of the runspace you want to interact with. A null value will use the current runspace.</param>
public override void SetBreakpoints(IEnumerable<Breakpoint> breakpoints, int? runspaceId)
{
// This is supported only for PowerShell versions >= 7.0
CheckRemoteBreakpointManagementSupport(RemoteDebuggingCommands.SetBreakpoint);
var functionParameters = new Dictionary<string, object>
{
{ "BreakpointList", breakpoints },
};
if (runspaceId.HasValue)
{
functionParameters.Add("RunspaceId", runspaceId.Value);
}
InvokeRemoteBreakpointFunction<CommandBreakpoint>(RemoteDebuggingCommands.SetBreakpoint, functionParameters);
}
/// <summary>
/// Get a breakpoint by id, primarily for Enable/Disable/Remove-PSBreakpoint cmdlets.
/// </summary>
/// <param name="id">Id of the breakpoint you want.</param>
/// <param name="runspaceId">The runspace id of the runspace you want to interact with. A null value will use the current runspace.</param>
/// <returns>The breakpoint with the specified id.</returns>
public override Breakpoint GetBreakpoint(int id, int? runspaceId)
{
// This is supported only for PowerShell versions >= 7.0
CheckRemoteBreakpointManagementSupport(RemoteDebuggingCommands.GetBreakpoint);
var functionParameters = new Dictionary<string, object>
{
{ "Id", id },
};
if (runspaceId.HasValue)
{
functionParameters.Add("RunspaceId", runspaceId.Value);
}
return InvokeRemoteBreakpointFunction<Breakpoint>(RemoteDebuggingCommands.GetBreakpoint, functionParameters);
}
/// <summary>
/// Returns breakpoints primarily for the Get-PSBreakpoint cmdlet.
/// </summary>
/// <param name="runspaceId">The runspace id of the runspace you want to interact with. A null value will use the current runspace.</param>
/// <returns>A list of breakpoints in a runspace.</returns>
public override List<Breakpoint> GetBreakpoints(int? runspaceId)
{
// This is supported only for PowerShell versions >= 7.0
CheckRemoteBreakpointManagementSupport(RemoteDebuggingCommands.GetBreakpoint);
CheckForValidateState();
var breakpoints = new List<Breakpoint>();
using (PowerShell ps = GetNestedPowerShell())
{
ps.AddCommand(RemoteDebuggingCommands.GetBreakpoint);
if (runspaceId.HasValue)
{
ps.AddParameter("RunspaceId", runspaceId.Value);
}
Collection<PSObject> output = ps.Invoke<PSObject>();
foreach (var item in output)
{
if (item?.BaseObject is Breakpoint bp)
{
breakpoints.Add(bp);
}
else if (TryGetRemoteDebuggerException(item, out Exception ex))
{
throw ex;
}
}
}
return breakpoints;
}
/// <summary>
/// Sets a command breakpoint in the debugger.
/// </summary>
/// <param name="command">The name of the command that will trigger the breakpoint. This value may not be null.</param>
/// <param name="action">The action to take when the breakpoint is hit. If null, PowerShell will break into the debugger when the breakpoint is hit.</param>
/// <param name="path">The path to the script file where the breakpoint may be hit. If null, the breakpoint may be hit anywhere the command is invoked.</param>
/// <param name="runspaceId">The runspace id of the runspace you want to interact with. A null value will use the current runspace.</param>
/// <returns>The command breakpoint that was set.</returns>
public override CommandBreakpoint SetCommandBreakpoint(string command, ScriptBlock action, string path, int? runspaceId)
{
// This is supported only for PowerShell versions >= 7.0
CheckRemoteBreakpointManagementSupport(RemoteDebuggingCommands.SetBreakpoint);
Breakpoint breakpoint = new CommandBreakpoint(path, null, command, action);
var functionParameters = new Dictionary<string, object>
{
{ "Breakpoint", breakpoint },
};
if (runspaceId.HasValue)
{
functionParameters.Add("RunspaceId", runspaceId.Value);
}
return InvokeRemoteBreakpointFunction<CommandBreakpoint>(RemoteDebuggingCommands.SetBreakpoint, functionParameters);
}
/// <summary>
/// Sets a line breakpoint in the debugger.
/// </summary>
/// <param name="path">The path to the script file where the breakpoint may be hit. This value may not be null.</param>
/// <param name="line">The line in the script file where the breakpoint may be hit. This value must be greater than or equal to 1.</param>
/// <param name="column">The column in the script file where the breakpoint may be hit. If 0, the breakpoint will trigger on any statement on the line.</param>
/// <param name="action">The action to take when the breakpoint is hit. If null, PowerShell will break into the debugger when the breakpoint is hit.</param>
/// <param name="runspaceId">The runspace id of the runspace you want to interact with. A null value will use the current runspace.</param>
/// <returns>The line breakpoint that was set.</returns>
public override LineBreakpoint SetLineBreakpoint(string path, int line, int column, ScriptBlock action, int? runspaceId)
{
// This is supported only for PowerShell versions >= 7.0
CheckRemoteBreakpointManagementSupport(RemoteDebuggingCommands.SetBreakpoint);
Breakpoint breakpoint = new LineBreakpoint(path, line, column, action);
var functionParameters = new Dictionary<string, object>
{
{ "Breakpoint", breakpoint },
};
if (runspaceId.HasValue)
{
functionParameters.Add("RunspaceId", runspaceId.Value);
}
return InvokeRemoteBreakpointFunction<LineBreakpoint>(RemoteDebuggingCommands.SetBreakpoint, functionParameters);
}
/// <summary>
/// Sets a variable breakpoint in the debugger.
/// </summary>
/// <param name="variableName">The name of the variable that will trigger the breakpoint. This value may not be null.</param>
/// <param name="accessMode">The variable access mode that will trigger the breakpoint.</param>
/// <param name="action">The action to take when the breakpoint is hit. If null, PowerShell will break into the debugger when the breakpoint is hit.</param>
/// <param name="path">The path to the script file where the breakpoint may be hit. If null, the breakpoint may be hit anywhere the variable is accessed using the specified access mode.</param>
/// <param name="runspaceId">The runspace id of the runspace you want to interact with. A null value will use the current runspace.</param>
/// <returns>The variable breakpoint that was set.</returns>
public override VariableBreakpoint SetVariableBreakpoint(string variableName, VariableAccessMode accessMode, ScriptBlock action, string path, int? runspaceId)
{
// This is supported only for PowerShell versions >= 7.0
CheckRemoteBreakpointManagementSupport(RemoteDebuggingCommands.SetBreakpoint);
Breakpoint breakpoint = new VariableBreakpoint(path, variableName, accessMode, action);
var functionParameters = new Dictionary<string, object>
{
{ "Breakpoint", breakpoint },
};
if (runspaceId.HasValue)
{
functionParameters.Add("RunspaceId", runspaceId.Value);
}
return InvokeRemoteBreakpointFunction<VariableBreakpoint>(RemoteDebuggingCommands.SetBreakpoint, functionParameters);
}
/// <summary>
/// Removes a breakpoint from the debugger.
/// </summary>
/// <param name="breakpoint">The breakpoint to remove from the debugger. This value may not be null.</param>
/// <param name="runspaceId">The runspace id of the runspace you want to interact with. A null value will use the current runspace.</param>
/// <returns>True if the breakpoint was removed from the debugger; false otherwise.</returns>
public override bool RemoveBreakpoint(Breakpoint breakpoint, int? runspaceId)
{
// This is supported only for PowerShell versions >= 7.0
CheckRemoteBreakpointManagementSupport(RemoteDebuggingCommands.RemoveBreakpoint);
if (breakpoint == null)
{
return false;
}
var functionParameters = new Dictionary<string, object>
{
{ "Id", breakpoint.Id },
};
if (runspaceId.HasValue)
{
functionParameters.Add("RunspaceId", runspaceId.Value);
}
return InvokeRemoteBreakpointFunction<bool>(RemoteDebuggingCommands.RemoveBreakpoint, functionParameters);
}
/// <summary>
/// Enables a breakpoint in the debugger.
/// </summary>
/// <param name="breakpoint">The breakpoint to enable in the debugger. This value may not be null.</param>
/// <param name="runspaceId">The runspace id of the runspace you want to interact with. A null value will use the current runspace.</param>
/// <returns>The updated breakpoint if it was found; null if the breakpoint was not found in the debugger.</returns>
public override Breakpoint EnableBreakpoint(Breakpoint breakpoint, int? runspaceId)
{
// This is supported only for PowerShell versions >= 7.0
CheckRemoteBreakpointManagementSupport(RemoteDebuggingCommands.EnableBreakpoint);
if (breakpoint == null)
{
return null;
}
var functionParameters = new Dictionary<string, object>
{
{ "Id", breakpoint.Id },
};
if (runspaceId.HasValue)
{
functionParameters.Add("RunspaceId", runspaceId.Value);
}
return InvokeRemoteBreakpointFunction<Breakpoint>(RemoteDebuggingCommands.EnableBreakpoint, functionParameters);
}
/// <summary>
/// Disables a breakpoint in the debugger.
/// </summary>
/// <param name="breakpoint">The breakpoint to enable in the debugger. This value may not be null.</param>
/// <param name="runspaceId">The runspace id of the runspace you want to interact with. A null value will use the current runspace.</param>
/// <returns>The updated breakpoint if it was found; null if the breakpoint was not found in the debugger.</returns>
public override Breakpoint DisableBreakpoint(Breakpoint breakpoint, int? runspaceId)
{
// This is supported only for PowerShell versions >= 7.0
CheckRemoteBreakpointManagementSupport(RemoteDebuggingCommands.DisableBreakpoint);
if (breakpoint == null)
{
return null;
}
var functionParameters = new Dictionary<string, object>
{
{ "Id", breakpoint.Id },
};
if (runspaceId.HasValue)
{
functionParameters.Add("RunspaceId", runspaceId.Value);
}
return InvokeRemoteBreakpointFunction<Breakpoint>(RemoteDebuggingCommands.DisableBreakpoint, functionParameters);
}
/// <summary>
/// SetDebuggerAction.
/// </summary>
/// <param name="resumeAction">DebuggerResumeAction.</param>
public override void SetDebuggerAction(DebuggerResumeAction resumeAction)
{
CheckForValidateState();
SetRemoteDebug(false, RunspaceAvailability.Busy);
using (PowerShell ps = GetNestedPowerShell())
{
ps.AddCommand(RemoteDebuggingCommands.SetDebuggerAction).AddParameter("ResumeAction", resumeAction);
ps.Invoke();
// If an error exception is returned then throw it here.
if (ps.ErrorBuffer.Count > 0)
{
Exception e = ps.ErrorBuffer[0].Exception;
if (e != null) { throw e; }
}
}
}
/// <summary>
/// GetDebuggerStopped.
/// </summary>
/// <returns>DebuggerStopEventArgs.</returns>
public override DebuggerStopEventArgs GetDebuggerStopArgs()
{
CheckForValidateState();
DebuggerStopEventArgs rtnArgs = null;
try
{
using (PowerShell ps = GetNestedPowerShell())
{
ps.AddCommand(RemoteDebuggingCommands.GetDebuggerStopArgs);
Collection<PSObject> output = ps.Invoke<PSObject>();
foreach (var item in output)
{
if (item == null) { continue; }
rtnArgs = item.BaseObject as DebuggerStopEventArgs;
if (rtnArgs != null) { break; }
}
}
}
catch (Exception)
{
}
return rtnArgs;
}
/// <summary>
/// SetDebugMode.
/// </summary>
/// <param name="mode"></param>
public override void SetDebugMode(DebugModes mode)
{
CheckForValidateState();
// Only set debug mode on server if no commands are currently
// running on remote runspace.
if ((_runspace.GetCurrentlyRunningPipeline() != null) ||
(_runspace.RemoteCommand != null))
{
return;
}
using (PowerShell ps = GetNestedPowerShell())
{
ps.SetIsNested(false);
ps.AddCommand(RemoteDebuggingCommands.SetDebugMode).AddParameter("Mode", mode);
ps.Invoke();
}
base.SetDebugMode(mode);
SetIsActive(_breakpointCount);
}
/// <summary>
/// Sets debugger stepping mode.
/// </summary>
/// <param name="enabled">True if stepping is to be enabled.</param>
public override void SetDebuggerStepMode(bool enabled)
{
CheckForValidateState();
// This is supported only for PowerShell versions >= 5.0
if (!_remoteDebuggingCapability.IsCommandSupported(RemoteDebuggingCommands.SetDebuggerStepMode))
{
return;
}
try
{
// Ensure debugger is in correct mode.
base.SetDebugMode(DebugModes.LocalScript | DebugModes.RemoteScript);
// Send Enable-DebuggerStepping virtual command.
using (PowerShell ps = GetNestedPowerShell())
{
ps.AddCommand(RemoteDebuggingCommands.SetDebuggerStepMode).AddParameter("Enabled", enabled);
ps.Invoke();
_isDebuggerSteppingEnabled = enabled;
}
}
catch (Exception)
{
// Don't propagate exceptions.
}
}
/// <summary>
/// True when debugger is active with breakpoints.
/// </summary>
public override bool IsActive
{
get { return _isActive; }
}
/// <summary>
/// True when debugger is stopped at a breakpoint.
/// </summary>
public override bool InBreakpoint
{
get
{
return _handleDebuggerStop || (_runspace.RunspaceAvailability == RunspaceAvailability.RemoteDebug);
}
}
/// <summary>
/// InternalProcessCommand.
/// </summary>
/// <param name="command"></param>
/// <param name="output"></param>
/// <returns></returns>
internal override DebuggerCommand InternalProcessCommand(string command, IList<PSObject> output)
{
throw new PSNotImplementedException();
}
/// <summary>
/// IsRemote.
/// </summary>
internal override bool IsRemote
{
get { return true; }
}
/// <summary>
/// Sets how the debugger deals with breakpoint events that are not handled.
/// Ignore - This is the default behavior and ignores any breakpoint event
/// if there is no handler. Releases any preserved event.
/// Wait - This mode preserves a breakpoint event until a handler is
/// subscribed.
/// </summary>
internal override UnhandledBreakpointProcessingMode UnhandledBreakpointMode
{
get
{
return _unhandledBreakpointMode;
}
set
{
CheckForValidateState();
// This is supported only for PowerShell versions >= 5.0
if (!_remoteDebuggingCapability.IsCommandSupported(RemoteDebuggingCommands.SetUnhandledBreakpointMode))
{
return;
}
SetRemoteDebug(false, (RunspaceAvailability?)null);
// Send Set-PSUnhandledBreakpointMode virtual command.
using (PowerShell ps = GetNestedPowerShell())
{
ps.AddCommand(RemoteDebuggingCommands.SetUnhandledBreakpointMode).AddParameter("UnhandledBreakpointMode", value);
ps.Invoke();
}
_unhandledBreakpointMode = value;
}
}
#endregion
#region IDisposable
/// <summary>
/// Dispose.
/// </summary>
public void Dispose()
{
_runspace.RemoteDebuggerStop -= HandleForwardedDebuggerStopEvent;
_runspace.RemoteDebuggerBreakpointUpdated -= HandleForwardedDebuggerBreakpointUpdatedEvent;
#if !UNIX
if (_identityToPersonate != null)
{
_identityToPersonate.Dispose();
_identityToPersonate = null;
}
#endif
}
#endregion
#region Internal Methods
/// <summary>
/// Internal method that checks the debug state of
/// the remote session and raises the DebuggerStop event
/// if debugger is in stopped state.
/// This is used internally to help clients get back to
/// debug state when reconnecting to remote session in debug state.
/// </summary>
internal void CheckStateAndRaiseStopEvent()
{
DebuggerStopEventArgs stopArgs = GetDebuggerStopArgs();
if (stopArgs != null)
{
ProcessDebuggerStopEvent(stopArgs);
}
}
/// <summary>
/// IsRemoteDebug.
/// </summary>
internal bool IsRemoteDebug
{
get;
private set;
}
/// <summary>
/// Sets client debug info state based on server info.
/// </summary>
/// <param name="debugMode">Debug mode.</param>
/// <param name="inBreakpoint">Currently in breakpoint.</param>
/// <param name="breakpointCount">Breakpoint count.</param>
/// <param name="breakAll">Break All setting.</param>
/// <param name="unhandledBreakpointMode">UnhandledBreakpointMode.</param>
/// <param name="serverPSVersion">Server PowerShell version.</param>
internal void SetClientDebugInfo(
DebugModes? debugMode,
bool inBreakpoint,
int breakpointCount,
bool breakAll,
UnhandledBreakpointProcessingMode unhandledBreakpointMode,
Version serverPSVersion)
{
if (debugMode != null)
{
_remoteDebugSupported = true;
DebugMode = debugMode.Value;
}
else
{
_remoteDebugSupported = false;
}
if (inBreakpoint)
{
SetRemoteDebug(true, RunspaceAvailability.RemoteDebug);
}
_remoteDebuggingCapability = RemoteDebuggingCapability.CreateDebuggingCapability(serverPSVersion);
_breakpointCount = breakpointCount;
_isDebuggerSteppingEnabled = breakAll;
_unhandledBreakpointMode = unhandledBreakpointMode;
SetIsActive(breakpointCount);
}
/// <summary>
/// If a command is stopped while in debug stopped state and it
/// is the only command running then server is no longer debug stopped.
/// </summary>
internal void OnCommandStopped()
{
if (IsRemoteDebug)
{
IsRemoteDebug = false;
}
}
/// <summary>
/// Gets breakpoint information from the target machine and passes that information
/// on through the BreakpointUpdated event.
/// </summary>
internal void SendBreakpointUpdatedEvents()
{
if (!IsDebuggerBreakpointUpdatedEventSubscribed() ||
(_breakpointCount == 0))
{
return;
}
PSDataCollection<PSObject> breakpoints = new PSDataCollection<PSObject>();
// Get breakpoint information by running "Get-PSBreakpoint" PowerShell command.
using (PowerShell ps = GetNestedPowerShell())
{
if (!this.InBreakpoint)
{
// Can't use nested PowerShell if we are not stopped in a breakpoint.
ps.SetIsNested(false);
}
ps.AddCommand("Get-PSBreakpoint");
ps.Invoke(null, breakpoints);
}
// Raise BreakpointUpdated event to client for each breakpoint.
foreach (PSObject obj in breakpoints)
{
Breakpoint breakpoint = obj.BaseObject as Breakpoint;
if (breakpoint != null)
{
RaiseBreakpointUpdatedEvent(
new BreakpointUpdatedEventArgs(breakpoint, BreakpointUpdateType.Set, _breakpointCount));
}
}
}
/// <summary>
/// IsDebuggerSteppingEnabled.
/// </summary>
internal override bool IsDebuggerSteppingEnabled
{
get { return _isDebuggerSteppingEnabled; }
}
#endregion
#region Private Methods
private static bool TryGetRemoteDebuggerException(
PSObject item,
out Exception exception)
{
exception = null;
if (item == null)
{
return false;
}
bool haveExceptionType = false;
foreach (var typeName in item.TypeNames)
{
if (typeName.Equals("Deserialized.System.Exception"))
{
haveExceptionType = true;
break;
}
}
if (haveExceptionType)
{
var errorMessage = item.Properties["Message"]?.Value ?? string.Empty;
exception = new RemoteException(
StringUtil.Format(
RemotingErrorIdStrings.RemoteDebuggerError, item.TypeNames[0], errorMessage));
return true;
}
return false;
}
//
// Event handlers
//
private void HandleForwardedDebuggerStopEvent(object sender, PSEventArgs e)
{
Dbg.Assert(e.SourceArgs.Length == 1, "Forwarded debugger stop event args must always contain one SourceArgs item.");
DebuggerStopEventArgs args;
if (e.SourceArgs[0] is PSObject)
{
args = ((PSObject)e.SourceArgs[0]).BaseObject as DebuggerStopEventArgs;
}
else
{
args = e.SourceArgs[0] as DebuggerStopEventArgs;
}
ProcessDebuggerStopEvent(args);
}
private void ProcessDebuggerStopEvent(DebuggerStopEventArgs args)
{
// It is possible to get a stop event raise request while
// debugger is already in stop mode (after remote runspace debugger
// reconnect). In this case ignore the request.
if (_handleDebuggerStop) { return; }
// Attempt to process debugger stop event on original thread if it
// is available (i.e., if it is blocked by EndInvoke).
PowerShell powershell = _runspace.RunspacePool.RemoteRunspacePoolInternal.GetCurrentRunningPowerShell();
AsyncResult invokeAsyncResult = powershell?.EndInvokeAsyncResult;
bool invokedOnBlockedThread = false;
if ((invokeAsyncResult != null) && (!invokeAsyncResult.IsCompleted))
{
invokedOnBlockedThread = invokeAsyncResult.InvokeCallbackOnThread(
ProcessDebuggerStopEventProc,
args);
}
if (!invokedOnBlockedThread)
{
// Otherwise run on worker thread.
#if !UNIX
Utils.QueueWorkItemWithImpersonation(
_identityToPersonate,
ProcessDebuggerStopEventProc,
args);
#else
Threading.ThreadPool.QueueUserWorkItem(
ProcessDebuggerStopEventProc,
args);
#endif
}
}
private void ProcessDebuggerStopEventProc(object state)
{
RunspaceAvailability prevAvailability = _runspace.RunspaceAvailability;
bool restoreAvailability = true;
try
{
_handleDebuggerStop = true;
// Update runspace availability
SetRemoteDebug(true, RunspaceAvailability.RemoteDebug);
// Raise event and wait for response.
DebuggerStopEventArgs args = state as DebuggerStopEventArgs;
if (args != null)
{
if (IsDebuggerStopEventSubscribed())
{
try
{
// Blocking call.
base.RaiseDebuggerStopEvent(args);
}
finally
{
_handleDebuggerStop = false;
if (!_detachCommand && !args.SuspendRemote)
{
SetDebuggerAction(args.ResumeAction);
}
}
}
else
{
// If no debugger is subscribed to the DebuggerStop event then we
// allow the server side script execution to remain blocked in debug
// stop mode. The runspace Availability reflects this and the client
// must take action (attach debugger or release remote debugger stop
// via SetDebuggerAction()).
restoreAvailability = false;
_handleDebuggerStop = false;
}
}
else
{
// Null arguments may indicate that remote runspace was created without
// default type table and so arguments cannot be serialized. In this case
// we don't want to block the remote side script execution.
_handleDebuggerStop = false;
SetDebuggerAction(DebuggerResumeAction.Continue);
}
}
catch (Exception)
{
_handleDebuggerStop = false;
}
finally
{
// Restore runspace availability.
if (restoreAvailability && (_runspace.RunspaceAvailability == RunspaceAvailability.RemoteDebug))
{
SetRemoteDebug(false, prevAvailability);
}
if (_detachCommand)
{
_detachCommand = false;
}
}
}
private void HandleForwardedDebuggerBreakpointUpdatedEvent(object sender, PSEventArgs e)
{
Dbg.Assert(e.SourceArgs.Length == 1, "Forwarded debugger breakpoint event args must always contain one SourceArgs item.");
BreakpointUpdatedEventArgs bpArgs = e.SourceArgs[0] as BreakpointUpdatedEventArgs;
if (bpArgs != null)
{
UpdateBreakpointCount(bpArgs.BreakpointCount);
base.RaiseBreakpointUpdatedEvent(bpArgs);
}
}
private PowerShell GetNestedPowerShell()
{
PowerShell ps = PowerShell.Create();
ps.Runspace = _runspace;
ps.SetIsNested(true);
return ps;
}
private void CheckForValidateState()
{
if (!_remoteDebugSupported)
{
throw new PSInvalidOperationException(
// The remote session to which you are connected does not support remote debugging.
// You must connect to a remote computer that is running PowerShell 4.0 or greater.
RemotingErrorIdStrings.RemoteDebuggingEndpointVersionError,
null,
"RemoteDebugger:RemoteDebuggingNotSupported",
ErrorCategory.NotImplemented,
null);
}
if (_runspace.RunspaceStateInfo.State != RunspaceState.Opened)
{
throw new InvalidRunspaceStateException();
}
#if !UNIX
if (!_identityPersonationChecked)
{
_identityPersonationChecked = true;
// Save identity to impersonate.
Utils.TryGetWindowsImpersonatedIdentity(out _identityToPersonate);
}
#endif
}
private void SetRemoteDebug(bool remoteDebug, RunspaceAvailability? availability)
{
if (_runspace.RunspaceStateInfo.State != RunspaceState.Opened)
{
return;
}
if (IsRemoteDebug != remoteDebug)
{
IsRemoteDebug = remoteDebug;
_runspace.RunspacePool.RemoteRunspacePoolInternal.IsRemoteDebugStop = remoteDebug;
}
if (availability != null)
{
RunspaceAvailability newAvailability = availability.Value;
if ((_runspace.RunspaceAvailability != newAvailability) &&
(remoteDebug || (newAvailability != RunspaceAvailability.RemoteDebug)))
{
try
{
_runspace.UpdateRunspaceAvailability(newAvailability, true);
}
catch (Exception)
{
}
}
}
}
private void UpdateBreakpointCount(int bpCount)
{
_breakpointCount = bpCount;
SetIsActive(bpCount);
}
private void SetIsActive(int breakpointCount)
{
if ((DebugMode & DebugModes.RemoteScript) == 0)
{
// Debugger is always inactive if RemoteScript is not selected.
if (_isActive) { _isActive = false; }
return;
}
if (breakpointCount > 0)
{
if (!_isActive) { _isActive = true; }
}
else
{
if (_isActive) { _isActive = false; }
}
}
private T InvokeRemoteBreakpointFunction<T>(string functionName, Dictionary<string, object> parameters)
{
CheckForValidateState();
using (PowerShell ps = GetNestedPowerShell())
{
ps.AddCommand(functionName);
foreach (var parameterName in parameters.Keys)
{
ps.AddParameter(parameterName, parameters[parameterName]);
}
Collection<PSObject> output = ps.Invoke<PSObject>();
// If an error exception is returned then throw it here.
if (ps.ErrorBuffer.Count > 0)
{
Exception e = ps.ErrorBuffer[0].Exception;
if (e != null)
{
throw e;
}
}
// This helper is only used to return a single output item of type T.
foreach (var item in output)
{
if (item?.BaseObject is T)
{
return (T)item.BaseObject;
}
if (TryGetRemoteDebuggerException(item, out Exception ex))
{
throw ex;
}
}
return default(T);
}
}
private void CheckRemoteBreakpointManagementSupport(string breakpointCommandNameToCheck)
{
_remoteBreakpointManagementIsSupported ??= _remoteDebuggingCapability.IsCommandSupported(breakpointCommandNameToCheck);
if (!_remoteBreakpointManagementIsSupported.Value)
{
throw new PSNotSupportedException(
StringUtil.Format(
DebuggerStrings.CommandNotSupportedForRemoteUseInServerDebugger,
RemoteDebuggingCommands.CleanCommandName(breakpointCommandNameToCheck)));
}
}
#endregion
}
#endregion
#region RemoteSessionStateProxy
internal class RemoteSessionStateProxy : SessionStateProxy
{
private readonly RemoteRunspace _runspace;
internal RemoteSessionStateProxy(RemoteRunspace runspace)
{
Dbg.Assert(runspace != null, "Caller should validate the parameter");
_runspace = runspace;
}
private Exception _isInNoLanguageModeException = null;
private Exception _getVariableCommandNotFoundException = null;
private Exception _setVariableCommandNotFoundException = null;
/// <summary>
/// Set a variable in session state.
/// </summary>
/// <param name="name">
/// The name of the item to set.
/// </param>
/// <param name="value">
/// The new value of the item being set.
/// </param>
/// <exception cref="ArgumentNullException">
/// name is null
/// </exception>
/// <exception cref="InvalidRunspaceStateException">
/// Runspace is not open.
/// </exception>
/// <exception cref="InvalidOperationException">
/// Another SessionStateProxy call or another pipeline is in progress.
/// </exception>
public override void SetVariable(string name, object value)
{
if (name == null)
{
throw PSTraceSource.NewArgumentNullException(nameof(name));
}
// Verify the runspace has the Set-Variable command. For performance, throw if we got an error
// before.
if (_setVariableCommandNotFoundException != null)
throw _setVariableCommandNotFoundException;
// Since these are implemented as pipelines, we don't need to do our own
// locking of sessionStateCallInProgress like we do with local runspaces.
Pipeline remotePipeline = _runspace.CreatePipeline();
Command command = new Command("Microsoft.PowerShell.Utility\\Set-Variable");
command.Parameters.Add("Name", name);
command.Parameters.Add("Value", value);
remotePipeline.Commands.Add(command);
try
{
remotePipeline.Invoke();
}
catch (RemoteException e)
{
if (string.Equals("CommandNotFoundException", e.ErrorRecord.FullyQualifiedErrorId, StringComparison.OrdinalIgnoreCase))
{
_setVariableCommandNotFoundException = new PSNotSupportedException(RunspaceStrings.NotSupportedOnRestrictedRunspace, e);
throw _setVariableCommandNotFoundException;
}
else throw;
}
if (remotePipeline.Error.Count > 0)
{
// Don't cache these errors, as they are related to the actual variable being set.
ErrorRecord error = (ErrorRecord)remotePipeline.Error.Read();
throw new PSNotSupportedException(RunspaceStrings.NotSupportedOnRestrictedRunspace, error.Exception);
}
}
/// <summary>
/// Get a variable out of session state.
/// </summary>
/// <param name="name">
/// name of variable to look up
/// </param>
/// <returns>
/// The value of the specified variable.
/// </returns>
/// <exception cref="ArgumentNullException">
/// name is null
/// </exception>
/// <exception cref="InvalidRunspaceStateException">
/// Runspace is not open.
/// </exception>
/// <exception cref="InvalidOperationException">
/// Another SessionStateProxy call or another pipeline is in progress.
/// </exception>
public override object GetVariable(string name)
{
if (name == null)
{
throw PSTraceSource.NewArgumentNullException(nameof(name));
}
// Verify the runspace has the Get-Variable command. For performance, throw if we got an error
// before.
if (_getVariableCommandNotFoundException != null)
throw _getVariableCommandNotFoundException;
// Since these are implemented as pipelines, we don't need to do our own
// locking of sessionStateCallInProgress like we do with local runspaces.
Pipeline remotePipeline = _runspace.CreatePipeline();
Command command = new Command("Microsoft.PowerShell.Utility\\Get-Variable");
command.Parameters.Add("Name", name);
remotePipeline.Commands.Add(command);
System.Collections.ObjectModel.Collection<PSObject> result = null;
try
{
result = remotePipeline.Invoke();
}
catch (RemoteException e)
{
if (string.Equals("CommandNotFoundException", e.ErrorRecord.FullyQualifiedErrorId, StringComparison.OrdinalIgnoreCase))
{
_getVariableCommandNotFoundException = new PSNotSupportedException(RunspaceStrings.NotSupportedOnRestrictedRunspace, e);
throw _getVariableCommandNotFoundException;
}
else throw;
}
if (remotePipeline.Error.Count > 0)
{
// Don't cache these errors, as they are related to the actual variable being set.
ErrorRecord error = (ErrorRecord)remotePipeline.Error.Read();
if (string.Equals("CommandNotFoundException", error.FullyQualifiedErrorId, StringComparison.OrdinalIgnoreCase))
{
throw new PSNotSupportedException(RunspaceStrings.NotSupportedOnRestrictedRunspace, error.Exception);
}
else
{
throw new PSInvalidOperationException(error.Exception.Message, error.Exception);
}
}
if (result.Count != 1)
return null;
else
return result[0].Properties["Value"].Value;
}
/// <summary>
/// Get the list of applications out of session state.
/// </summary>
/// <exception cref="InvalidRunspaceStateException">
/// Runspace is not open.
/// </exception>
/// <exception cref="InvalidOperationException">
/// Another SessionStateProxy call or another pipeline is in progress.
/// </exception>
public override List<string> Applications
{
get
{
// Verify the runspace has is not in NoLanguage mode. For performance, throw if we got an error
// before.
if (_isInNoLanguageModeException != null)
throw _isInNoLanguageModeException;
// Since these are implemented as pipelines, we don't need to do our own
// locking of sessionStateCallInProgress like we do with local runspaces.
Pipeline remotePipeline = _runspace.CreatePipeline();
remotePipeline.Commands.AddScript("$executionContext.SessionState.Applications");
List<string> result = new List<string>();
try
{
foreach (PSObject application in remotePipeline.Invoke())
{
result.Add(application.BaseObject as string);
}
}
catch (RemoteException e)
{
if (e.ErrorRecord.CategoryInfo.Category == ErrorCategory.ParserError)
{
_isInNoLanguageModeException = new PSNotSupportedException(RunspaceStrings.NotSupportedOnRestrictedRunspace, e);
throw _isInNoLanguageModeException;
}
else throw;
}
return result;
}
}
/// <summary>
/// Get the list of scripts out of session state.
/// </summary>
/// <exception cref="InvalidRunspaceStateException">
/// Runspace is not open.
/// </exception>
/// <exception cref="InvalidOperationException">
/// Another SessionStateProxy call or another pipeline is in progress.
/// </exception>
public override List<string> Scripts
{
get
{
// Verify the runspace has is not in NoLanguage mode. For performance, throw if we got an error
// before.
if (_isInNoLanguageModeException != null)
throw _isInNoLanguageModeException;
// Since these are implemented as pipelines, we don't need to do our own
// locking of sessionStateCallInProgress like we do with local runspaces.
Pipeline remotePipeline = _runspace.CreatePipeline();
remotePipeline.Commands.AddScript("$executionContext.SessionState.Scripts");
List<string> result = new List<string>();
try
{
foreach (PSObject application in remotePipeline.Invoke())
{
result.Add(application.BaseObject as string);
}
}
catch (RemoteException e)
{
if (e.ErrorRecord.CategoryInfo.Category == ErrorCategory.ParserError)
{
_isInNoLanguageModeException = new PSNotSupportedException(RunspaceStrings.NotSupportedOnRestrictedRunspace, e);
throw _isInNoLanguageModeException;
}
else throw;
}
return result;
}
}
/// <summary>
/// Get the APIs to access drives out of session state.
/// </summary>
/// <exception cref="InvalidRunspaceStateException">
/// Runspace is not open.
/// </exception>
/// <exception cref="InvalidOperationException">
/// Another SessionStateProxy call or another pipeline is in progress.
/// </exception>
public override DriveManagementIntrinsics Drive
{
get
{
throw new PSNotSupportedException();
}
}
/// <summary>
/// Get/Set the language mode out of session state.
/// </summary>
/// <exception cref="InvalidRunspaceStateException">
/// Runspace is not open.
/// </exception>
/// <exception cref="InvalidOperationException">
/// Another SessionStateProxy call or another pipeline is in progress.
/// </exception>
public override PSLanguageMode LanguageMode
{
get
{
// Verify the runspace has is not in NoLanguage mode. For performance, return our
// cached value if we got an error before.
if (_isInNoLanguageModeException != null)
return PSLanguageMode.NoLanguage;
// Since these are implemented as pipelines, we don't need to do our own
// locking of sessionStateCallInProgress like we do with local runspaces.
Pipeline remotePipeline = _runspace.CreatePipeline();
remotePipeline.Commands.AddScript("$executionContext.SessionState.LanguageMode");
System.Collections.ObjectModel.Collection<PSObject> result = null;
try
{
result = remotePipeline.Invoke();
}
catch (RemoteException e)
{
if (e.ErrorRecord.CategoryInfo.Category == ErrorCategory.ParserError)
{
_isInNoLanguageModeException = new PSNotSupportedException(RunspaceStrings.NotSupportedOnRestrictedRunspace, e);
return PSLanguageMode.NoLanguage;
}
else throw;
}
return (PSLanguageMode)LanguagePrimitives.ConvertTo(result[0], typeof(PSLanguageMode), CultureInfo.InvariantCulture);
}
set
{
throw new PSNotSupportedException();
}
}
/// <summary>
/// Get the module info out of session state.
/// </summary>
/// <exception cref="InvalidRunspaceStateException">
/// Runspace is not open.
/// </exception>
/// <exception cref="InvalidOperationException">
/// Another SessionStateProxy call or another pipeline is in progress.
/// </exception>
public override PSModuleInfo Module
{
get
{
throw new PSNotSupportedException();
}
}
/// <summary>
/// Get the APIs to access paths and locations out of session state.
/// </summary>
/// <exception cref="InvalidRunspaceStateException">
/// Runspace is not open.
/// </exception>
/// <exception cref="InvalidOperationException">
/// Another SessionStateProxy call or another pipeline is in progress.
/// </exception>
public override PathIntrinsics Path
{
get
{
throw new PSNotSupportedException();
}
}
/// <summary>
/// Get the APIs to access a provider out of session state.
/// </summary>
/// <exception cref="InvalidRunspaceStateException">
/// Runspace is not open.
/// </exception>
/// <exception cref="InvalidOperationException">
/// Another SessionStateProxy call or another pipeline is in progress.
/// </exception>
public override CmdletProviderManagementIntrinsics Provider
{
get
{
throw new PSNotSupportedException();
}
}
/// <summary>
/// Get the APIs to access variables out of session state.
/// </summary>
/// <exception cref="InvalidRunspaceStateException">
/// Runspace is not open.
/// </exception>
/// <exception cref="InvalidOperationException">
/// Another SessionStateProxy call or another pipeline is in progress.
/// </exception>
public override PSVariableIntrinsics PSVariable
{
get
{
throw new PSNotSupportedException();
}
}
/// <summary>
/// Get the APIs to build script blocks and execute script out of session state.
/// </summary>
/// <exception cref="InvalidRunspaceStateException">
/// Runspace is not open.
/// </exception>
/// <exception cref="InvalidOperationException">
/// Another SessionStateProxy call or another pipeline is in progress.
/// </exception>
public override CommandInvocationIntrinsics InvokeCommand
{
get
{
throw new PSNotSupportedException();
}
}
/// <summary>
/// Gets the instance of the provider interface APIs out of session state.
/// </summary>
/// <exception cref="InvalidRunspaceStateException">
/// Runspace is not open.
/// </exception>
/// <exception cref="InvalidOperationException">
/// Another SessionStateProxy call or another pipeline is in progress.
/// </exception>
public override ProviderIntrinsics InvokeProvider
{
get
{
throw new PSNotSupportedException();
}
}
}
#endregion
}
|