Welcome to mirror list, hosted at ThFree Co, Russian Federation.

Process.cs « diagnosticts « system « monitoring « services « System « referencesource « class « mcs - github.com/mono/mono.git - Unnamed repository; edit this file 'description' to name the repository.
summaryrefslogtreecommitdiff
blob: 43272662e97ea12213fc7599c2c8b415cf01e63d (plain)
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
//------------------------------------------------------------------------------
// <copyright file="Process.cs" company="Microsoft">
//     Copyright (c) Microsoft Corporation.  All rights reserved.
// </copyright>                                                                
//------------------------------------------------------------------------------

namespace System.Diagnostics {
    using System.Text;
    using System.Threading;
    using System.Runtime.InteropServices;
    using System.ComponentModel;
    using System.ComponentModel.Design;
    using System.Runtime.CompilerServices;
    using System.Runtime.ConstrainedExecution;
    using System.Diagnostics;
    using System;
    using System.Collections;
    using System.IO;
    using Microsoft.Win32;        
    using Microsoft.Win32.SafeHandles;
    using System.Collections.Specialized;
    using System.Globalization;
    using System.Security;
    using System.Security.Permissions;
    using System.Security.Principal;
    using System.Runtime.Versioning;
    
    /// <devdoc>
    ///    <para>
    ///       Provides access to local and remote
    ///       processes. Enables you to start and stop system processes.
    ///    </para>
    /// </devdoc>
    [
    MonitoringDescription(SR.ProcessDesc),
    DefaultEvent("Exited"), 
    DefaultProperty("StartInfo"),
    Designer("System.Diagnostics.Design.ProcessDesigner, " + AssemblyRef.SystemDesign),
    // Disabling partial trust scenarios
    PermissionSet(SecurityAction.LinkDemand, Name="FullTrust"),
    PermissionSet(SecurityAction.InheritanceDemand, Name="FullTrust"),
    HostProtection(SharedState=true, Synchronization=true, ExternalProcessMgmt=true, SelfAffectingProcessMgmt=true)
    ]
    public class Process : Component {
        //
        // FIELDS
        //

        bool haveProcessId;
        int processId;
        bool haveProcessHandle;
        SafeProcessHandle m_processHandle;
        bool isRemoteMachine;
        string machineName;
        ProcessInfo processInfo;
        Int32 m_processAccess;

#if !FEATURE_PAL        
        ProcessThreadCollection threads;
        ProcessModuleCollection modules;
#endif // !FEATURE_PAL        

        bool haveMainWindow;
        IntPtr mainWindowHandle;  // no need to use SafeHandle for window        
        string mainWindowTitle;
        
        bool haveWorkingSetLimits;
        IntPtr minWorkingSet;
        IntPtr maxWorkingSet;
        
        bool haveProcessorAffinity;
        IntPtr processorAffinity;

        bool havePriorityClass;
        ProcessPriorityClass priorityClass;

        ProcessStartInfo startInfo;
        
        bool watchForExit;
        bool watchingForExit;
        EventHandler onExited;
        bool exited;
        int exitCode;
        bool signaled;
		
        DateTime exitTime;
        bool haveExitTime;
        
        bool responding;
        bool haveResponding;
        
        bool priorityBoostEnabled;
        bool havePriorityBoostEnabled;
        
        bool raisedOnExited;
        RegisteredWaitHandle registeredWaitHandle;
        WaitHandle waitHandle;
        ISynchronizeInvoke synchronizingObject;
        StreamReader standardOutput;
        StreamWriter standardInput;
        StreamReader standardError;
        OperatingSystem operatingSystem;
        bool disposed;
        
        static object s_CreateProcessLock = new object();
        
        // This enum defines the operation mode for redirected process stream.
        // We don't support switching between synchronous mode and asynchronous mode.
        private enum StreamReadMode 
        {
            undefined, 
            syncMode, 
            asyncMode
        }
        
        StreamReadMode outputStreamReadMode;
        StreamReadMode errorStreamReadMode;
        
       
        // Support for asynchrously reading streams
        [Browsable(true), MonitoringDescription(SR.ProcessAssociated)]
        //[System.Runtime.InteropServices.ComVisible(false)]        
        public event DataReceivedEventHandler OutputDataReceived;
        [Browsable(true), MonitoringDescription(SR.ProcessAssociated)]
        //[System.Runtime.InteropServices.ComVisible(false)]        
        public event DataReceivedEventHandler ErrorDataReceived;
        // Abstract the stream details
        internal AsyncStreamReader output;
        internal AsyncStreamReader error;
        internal bool pendingOutputRead;
        internal bool pendingErrorRead;


        private static SafeFileHandle InvalidPipeHandle = new SafeFileHandle(IntPtr.Zero, false);
#if DEBUG
        internal static TraceSwitch processTracing = new TraceSwitch("processTracing", "Controls debug output from Process component");
#else
        internal static TraceSwitch processTracing = null;
#endif

        //
        // CONSTRUCTORS
        //

        /// <devdoc>
        ///    <para>
        ///       Initializes a new instance of the <see cref='System.Diagnostics.Process'/> class.
        ///    </para>
        /// </devdoc>
        public Process() {
            this.machineName = ".";
            this.outputStreamReadMode = StreamReadMode.undefined;
            this.errorStreamReadMode = StreamReadMode.undefined;            
            this.m_processAccess = NativeMethods.PROCESS_ALL_ACCESS;
        }        
        
        [ResourceExposure(ResourceScope.Machine)]
        Process(string machineName, bool isRemoteMachine, int processId, ProcessInfo processInfo) : base() {
            Debug.Assert(SyntaxCheck.CheckMachineName(machineName), "The machine name should be valid!");
            this.processInfo = processInfo;
            this.machineName = machineName;
            this.isRemoteMachine = isRemoteMachine;
            this.processId = processId;
            this.haveProcessId = true;
            this.outputStreamReadMode = StreamReadMode.undefined;
            this.errorStreamReadMode = StreamReadMode.undefined;
            this.m_processAccess = NativeMethods.PROCESS_ALL_ACCESS;
        }

        //
        // PROPERTIES
        //

        /// <devdoc>
        ///     Returns whether this process component is associated with a real process.
        /// </devdoc>
        /// <internalonly/>
        [Browsable(false), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden), MonitoringDescription(SR.ProcessAssociated)]
        bool Associated {
            get {
                return haveProcessId || haveProcessHandle;
            }
        }

 #if !FEATURE_PAL
        /// <devdoc>
        ///    <para>
        ///       Gets the base priority of
        ///       the associated process.
        ///    </para>
        /// </devdoc>
        [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden), MonitoringDescription(SR.ProcessBasePriority)]
        public int BasePriority {
            get {
                EnsureState(State.HaveProcessInfo);
                return processInfo.basePriority;
            }
        }
#endif // FEATURE_PAL

        /// <devdoc>
        ///    <para>
        ///       Gets
        ///       the
        ///       value that was specified by the associated process when it was terminated.
        ///    </para>
        /// </devdoc>
        [Browsable(false),DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden), MonitoringDescription(SR.ProcessExitCode)]
        public int ExitCode {
            get {
                EnsureState(State.Exited);
                return exitCode;
            }
          }

        /// <devdoc>
        ///    <para>
        ///       Gets a
        ///       value indicating whether the associated process has been terminated.
        ///    </para>
        /// </devdoc>
        [Browsable(false), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden), MonitoringDescription(SR.ProcessTerminated)]
        public bool HasExited {
            get {
                if (!exited) {
                    EnsureState(State.Associated);
                    SafeProcessHandle handle = null;
                    try {
                        handle = GetProcessHandle(NativeMethods.PROCESS_QUERY_INFORMATION | NativeMethods.SYNCHRONIZE, false);
                        if (handle.IsInvalid) {
                            exited = true;
                        }
                        else {
                            int exitCode;
                            
                            // Although this is the wrong way to check whether the process has exited,
                            // it was historically the way we checked for it, and a lot of code then took a dependency on
                            // the fact that this would always be set before the pipes were closed, so they would read
                            // the exit code out after calling ReadToEnd() or standard output or standard error. In order
                            // to allow 259 to function as a valid exit code and to break as few people as possible that
                            // took the ReadToEnd dependency, we check for an exit code before doing the more correct
                            // check to see if we have been signalled.
                            if (NativeMethods.GetExitCodeProcess(handle, out exitCode) && exitCode != NativeMethods.STILL_ACTIVE) {
                                this.exited = true;
                                this.exitCode = exitCode;                                
                            }
                            else {                                                        

                                // The best check for exit is that the kernel process object handle is invalid, 
                                // or that it is valid and signaled.  Checking if the exit code != STILL_ACTIVE 
                                // does not guarantee the process is closed,
                                // since some process could return an actual STILL_ACTIVE exit code (259).
                                if (!signaled) // if we just came from WaitForExit, don't repeat
                                {
                                    ProcessWaitHandle wh = null;
                                    try 
                                    {
                                        wh = new ProcessWaitHandle(handle);
                                        this.signaled = wh.WaitOne(0, false);					
                                    }
                                    finally
                                    {

                                        if (wh != null)
                                        wh.Close();
                                    }
                                }
                                if (signaled) 
                                {
                                    if (!NativeMethods.GetExitCodeProcess(handle, out exitCode))                               
                                        throw new Win32Exception();
                                
                                    this.exited = true;
                                    this.exitCode = exitCode;
                                }
                            }
                        }	
                    }
                    finally 
                    {
                        ReleaseProcessHandle(handle);
                    }

                    if (exited) {
                        RaiseOnExited();
                    }
                }
                return exited;
            }
        }

        private ProcessThreadTimes GetProcessTimes() {
            ProcessThreadTimes processTimes = new ProcessThreadTimes();
            SafeProcessHandle handle = null;
            try {
                int access = NativeMethods.PROCESS_QUERY_INFORMATION;

                if (EnvironmentHelpers.IsWindowsVistaOrAbove()) 
                    access = NativeMethods.PROCESS_QUERY_LIMITED_INFORMATION;

                handle = GetProcessHandle(access, false);
                if( handle.IsInvalid) {
                    // On OS older than XP, we will not be able to get the handle for a process
                    // after it terminates. 
                    // On Windows XP and newer OS, the information about a process will stay longer. 
                    throw new InvalidOperationException(SR.GetString(SR.ProcessHasExited, processId.ToString(CultureInfo.CurrentCulture)));
                }

                if (!NativeMethods.GetProcessTimes(handle, 
                                                   out processTimes.create, 
                                                   out processTimes.exit, 
                                                   out processTimes.kernel, 
                                                   out processTimes.user)) {
                    throw new Win32Exception();
                }

            }
            finally {
                ReleaseProcessHandle(handle);                
            }
            return processTimes;
        }

 #if !FEATURE_PAL
        /// <devdoc>
        ///    <para>
        ///       Gets the time that the associated process exited.
        ///    </para>
        /// </devdoc>
        [Browsable(false), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden), MonitoringDescription(SR.ProcessExitTime)]
        public DateTime ExitTime {
            get {
                if (!haveExitTime) {
                    EnsureState(State.IsNt | State.Exited);
                    exitTime = GetProcessTimes().ExitTime;
                    haveExitTime = true;
                }
                return exitTime;
            }
        }
#endif // !FEATURE_PAL

        /// <devdoc>
        ///    <para>
        ///       Returns the native handle for the associated process. The handle is only available
        ///       if this component started the process.
        ///    </para>
        /// </devdoc>
        [Browsable(false), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden), MonitoringDescription(SR.ProcessHandle)]
        public IntPtr Handle {
            [ResourceExposure(ResourceScope.Machine)]
            [ResourceConsumption(ResourceScope.Machine)]
            get {
                EnsureState(State.Associated);
                return OpenProcessHandle(this.m_processAccess).DangerousGetHandle();
            }
        }

        [Browsable(false), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]  
        public SafeProcessHandle SafeHandle {
            get {
                EnsureState(State.Associated);
                return OpenProcessHandle(this.m_processAccess);
            }
        }

#if !FEATURE_PAL
        /// <devdoc>
        ///    <para>
        ///       Gets the number of handles that are associated
        ///       with the process.
        ///    </para>
        /// </devdoc>
        [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden), MonitoringDescription(SR.ProcessHandleCount)]
        public int HandleCount {
            get {
                EnsureState(State.HaveProcessInfo);
                return processInfo.handleCount;
            }
        }
#endif // !FEATURE_PAL

        /// <devdoc>
        ///    <para>
        ///       Gets
        ///       the unique identifier for the associated process.
        ///    </para>
        /// </devdoc>
        [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden), MonitoringDescription(SR.ProcessId)]
        public int Id {
            get {
                EnsureState(State.HaveId);
                return processId;
            }
        }

        /// <devdoc>
        ///    <para>
        ///       Gets
        ///       the name of the computer on which the associated process is running.
        ///    </para>
        /// </devdoc>
        [Browsable(false), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden), MonitoringDescription(SR.ProcessMachineName)]
        public string MachineName {
            get {
                EnsureState(State.Associated);
                return machineName;
            }
        }

 #if !FEATURE_PAL

        /// <devdoc>
        ///    <para>
        ///       Returns the window handle of the main window of the associated process.
        ///    </para>
        /// </devdoc>
        [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden), MonitoringDescription(SR.ProcessMainWindowHandle)]
        public IntPtr MainWindowHandle {
            [ResourceExposure(ResourceScope.Machine)]
            [ResourceConsumption(ResourceScope.Machine)]
            get {
                if (!haveMainWindow) {
                    EnsureState(State.IsLocal | State.HaveId);
                    mainWindowHandle = ProcessManager.GetMainWindowHandle(processId);

                    if (mainWindowHandle != (IntPtr)0) {
                        haveMainWindow = true;
                    } else {
                        // We do the following only for the side-effect that it will throw when if the process no longer exists on the system.  In Whidbey
                        // we always did this check but have now changed it to just require a ProcessId. In the case where someone has called Refresh() 
                        // and the process has exited this call will throw an exception where as the above code would return 0 as the handle.
                        EnsureState(State.HaveProcessInfo);
                    }
                }
                return mainWindowHandle;
            }
        }

        /// <devdoc>
        ///    <para>
        ///       Returns the caption of the <see cref='System.Diagnostics.Process.MainWindowHandle'/> of
        ///       the process. If the handle is zero (0), then an empty string is returned.
        ///    </para>
        /// </devdoc>
        [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden), MonitoringDescription(SR.ProcessMainWindowTitle)]
        public string MainWindowTitle {
            [ResourceExposure(ResourceScope.None)]
            [ResourceConsumption(ResourceScope.Machine, ResourceScope.Machine)]
            get {
                if (mainWindowTitle == null) {
                    IntPtr handle = MainWindowHandle;
                    if (handle == (IntPtr)0) {
                        mainWindowTitle = String.Empty;
                    }
                    else {
                        int length = NativeMethods.GetWindowTextLength(new HandleRef(this, handle)) * 2;
                        StringBuilder builder = new StringBuilder(length);
                        NativeMethods.GetWindowText(new HandleRef(this, handle), builder, builder.Capacity);
                        mainWindowTitle = builder.ToString();
                    }
                }
                return mainWindowTitle;
            }
        }



        /// <devdoc>
        ///    <para>
        ///       Gets
        ///       the main module for the associated process.
        ///    </para>
        /// </devdoc>
        [Browsable(false), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden), MonitoringDescription(SR.ProcessMainModule)]
        public ProcessModule MainModule {
            [ResourceExposure(ResourceScope.Process)]
            [ResourceConsumption(ResourceScope.Machine, ResourceScope.Machine)]
            get {
                // We only return null if we couldn't find a main module.
                // This could be because
                //      1. The process hasn't finished loading the main module (most likely)
                //      2. There are no modules loaded (possible for certain OS processes)
                //      3. Possibly other?
                
                if (OperatingSystem.Platform == PlatformID.Win32NT) {
                    EnsureState(State.HaveId | State.IsLocal);
                    // on NT the first module is the main module                    
                    ModuleInfo module = NtProcessManager.GetFirstModuleInfo(processId);
                    return new ProcessModule(module);
                }
                else {
                    ProcessModuleCollection moduleCollection = Modules;                        
                    // on 9x we have to do a little more work
                    EnsureState(State.HaveProcessInfo);
                    foreach (ProcessModule pm in moduleCollection) {
                        if (pm.moduleInfo.Id == processInfo.mainModuleId) {
                            return pm;
                        }
                    }
                    return null;
                }
            }
        }

        /// <devdoc>
        ///    <para>
        ///       Gets or sets the maximum allowable working set for the associated
        ///       process.
        ///    </para>
        /// </devdoc>
        [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden), MonitoringDescription(SR.ProcessMaxWorkingSet)]
        public IntPtr MaxWorkingSet {
            get {
                EnsureWorkingSetLimits();
                return maxWorkingSet;
            }
            [ResourceExposure(ResourceScope.Process)]
            [ResourceConsumption(ResourceScope.Process)]
            set {
                SetWorkingSetLimits(null, value);
            }
        }

        /// <devdoc>
        ///    <para>
        ///       Gets or sets the minimum allowable working set for the associated
        ///       process.
        ///    </para>
        /// </devdoc>
        [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden), MonitoringDescription(SR.ProcessMinWorkingSet)]
        public IntPtr MinWorkingSet {
            get {
                EnsureWorkingSetLimits();
                return minWorkingSet;
            }
            [ResourceExposure(ResourceScope.Process)]
            [ResourceConsumption(ResourceScope.Process)]
            set {
                SetWorkingSetLimits(value, null);
            }
        }

        /// <devdoc>
        ///    <para>
        ///       Gets
        ///       the modules that have been loaded by the associated process.
        ///    </para>
        /// </devdoc>
        [Browsable(false), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden), MonitoringDescription(SR.ProcessModules)]
        public ProcessModuleCollection Modules {
            [ResourceExposure(ResourceScope.None)]
            [ResourceConsumption(ResourceScope.Machine, ResourceScope.Machine)]
            get {
                if (modules == null) {
                    EnsureState(State.HaveId | State.IsLocal);
                    ModuleInfo[] moduleInfos = ProcessManager.GetModuleInfos(processId);
                    ProcessModule[] newModulesArray = new ProcessModule[moduleInfos.Length];
                    for (int i = 0; i < moduleInfos.Length; i++) {
                        newModulesArray[i] = new ProcessModule(moduleInfos[i]);
                    }
                    ProcessModuleCollection newModules = new ProcessModuleCollection(newModulesArray);
                    modules = newModules;
                }
                return modules;
            }
        }

        /// <devdoc>
        ///     Returns the amount of memory that the system has allocated on behalf of the
        ///     associated process that can not be written to the virtual memory paging file.
        /// </devdoc>
        [Obsolete("This property has been deprecated.  Please use System.Diagnostics.Process.NonpagedSystemMemorySize64 instead.  http://go.microsoft.com/fwlink/?linkid=14202")]
        [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden), MonitoringDescription(SR.ProcessNonpagedSystemMemorySize)]
        public int NonpagedSystemMemorySize {
            get {
                EnsureState(State.HaveNtProcessInfo);
                return unchecked((int)processInfo.poolNonpagedBytes);
            }
        }

        [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden), MonitoringDescription(SR.ProcessNonpagedSystemMemorySize)]
        [System.Runtime.InteropServices.ComVisible(false)]            
        public long NonpagedSystemMemorySize64 {
            get {
                EnsureState(State.HaveNtProcessInfo);
                return processInfo.poolNonpagedBytes;
            }
        }

        /// <devdoc>
        ///     Returns the amount of memory that the associated process has allocated
        ///     that can be written to the virtual memory paging file.
        /// </devdoc>
        [Obsolete("This property has been deprecated.  Please use System.Diagnostics.Process.PagedMemorySize64 instead.  http://go.microsoft.com/fwlink/?linkid=14202")]
        [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden), MonitoringDescription(SR.ProcessPagedMemorySize)]
        public int PagedMemorySize {
            get {
                EnsureState(State.HaveNtProcessInfo);
                return unchecked((int)processInfo.pageFileBytes);
            }
        }

        [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden), MonitoringDescription(SR.ProcessPagedMemorySize)]
        [System.Runtime.InteropServices.ComVisible(false)]
        public long PagedMemorySize64 {
            get {
                EnsureState(State.HaveNtProcessInfo);
                return processInfo.pageFileBytes;
            }
        }


        /// <devdoc>
        ///     Returns the amount of memory that the system has allocated on behalf of the
        ///     associated process that can be written to the virtual memory paging file.
        /// </devdoc>
        [Obsolete("This property has been deprecated.  Please use System.Diagnostics.Process.PagedSystemMemorySize64 instead.  http://go.microsoft.com/fwlink/?linkid=14202")]
        [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden), MonitoringDescription(SR.ProcessPagedSystemMemorySize)]
        public int PagedSystemMemorySize {
            get {
                EnsureState(State.HaveNtProcessInfo);
                return unchecked((int)processInfo.poolPagedBytes);
            }
        }

        [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden), MonitoringDescription(SR.ProcessPagedSystemMemorySize)]
        [System.Runtime.InteropServices.ComVisible(false)]
        public long PagedSystemMemorySize64 {
            get {
                EnsureState(State.HaveNtProcessInfo);
                return processInfo.poolPagedBytes;
            }
        }


        /// <devdoc>
        ///    <para>
        ///       Returns the maximum amount of memory that the associated process has
        ///       allocated that could be written to the virtual memory paging file.
        ///    </para>
        /// </devdoc>
        [Obsolete("This property has been deprecated.  Please use System.Diagnostics.Process.PeakPagedMemorySize64 instead.  http://go.microsoft.com/fwlink/?linkid=14202")]
        [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden), MonitoringDescription(SR.ProcessPeakPagedMemorySize)]
        public int PeakPagedMemorySize {
            get {
                EnsureState(State.HaveNtProcessInfo);
                return unchecked((int)processInfo.pageFileBytesPeak);
            }
        }

        [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden), MonitoringDescription(SR.ProcessPeakPagedMemorySize)]
        [System.Runtime.InteropServices.ComVisible(false)]
        public long PeakPagedMemorySize64 {
            get {
                EnsureState(State.HaveNtProcessInfo);
                return processInfo.pageFileBytesPeak;
            }
        }
        
        /// <devdoc>
        ///    <para>
        ///       Returns the maximum amount of physical memory that the associated
        ///       process required at once.
        ///    </para>
        /// </devdoc>
        [Obsolete("This property has been deprecated.  Please use System.Diagnostics.Process.PeakWorkingSet64 instead.  http://go.microsoft.com/fwlink/?linkid=14202")]
        [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden), MonitoringDescription(SR.ProcessPeakWorkingSet)]
        public int PeakWorkingSet {
            get {
                EnsureState(State.HaveNtProcessInfo);
                return unchecked((int)processInfo.workingSetPeak);
            }
        }

        [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden), MonitoringDescription(SR.ProcessPeakWorkingSet)]
        [System.Runtime.InteropServices.ComVisible(false)]
        public long PeakWorkingSet64 {
            get {
                EnsureState(State.HaveNtProcessInfo);
                return processInfo.workingSetPeak;
            }
        }

        /// <devdoc>
        ///     Returns the maximum amount of virtual memory that the associated
        ///     process has requested.
        /// </devdoc>
        [Obsolete("This property has been deprecated.  Please use System.Diagnostics.Process.PeakVirtualMemorySize64 instead.  http://go.microsoft.com/fwlink/?linkid=14202")]
        [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden), MonitoringDescription(SR.ProcessPeakVirtualMemorySize)]
        public int PeakVirtualMemorySize {
            get {
                EnsureState(State.HaveNtProcessInfo);
                return unchecked((int)processInfo.virtualBytesPeak);
            }
        }

        [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden), MonitoringDescription(SR.ProcessPeakVirtualMemorySize)]
        [System.Runtime.InteropServices.ComVisible(false)]
        public long PeakVirtualMemorySize64 {
            get {
                EnsureState(State.HaveNtProcessInfo);
                return processInfo.virtualBytesPeak;
            }
        }

        private OperatingSystem OperatingSystem {
            get {
                if (operatingSystem == null) {
                    operatingSystem = Environment.OSVersion;
                }                
                return operatingSystem;
            }
        }

        /// <devdoc>
        ///    <para>
        ///       Gets or sets a value indicating whether the associated process priority
        ///       should be temporarily boosted by the operating system when the main window
        ///       has focus.
        ///    </para>
        /// </devdoc>
        [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden), MonitoringDescription(SR.ProcessPriorityBoostEnabled)]
        public bool PriorityBoostEnabled {
            get {
                EnsureState(State.IsNt);
                if (!havePriorityBoostEnabled) {
                    SafeProcessHandle handle = null;
                    try {
                        handle = GetProcessHandle(NativeMethods.PROCESS_QUERY_INFORMATION);
                        bool disabled = false;
                        if (!NativeMethods.GetProcessPriorityBoost(handle, out disabled)) {
                            throw new Win32Exception();
                        }
                        priorityBoostEnabled = !disabled;
                        havePriorityBoostEnabled = true;
                    }
                    finally {
                        ReleaseProcessHandle(handle);
                    }
                }
                return priorityBoostEnabled;
            }
            set {
                EnsureState(State.IsNt);
                SafeProcessHandle handle = null;
                try {
                    handle = GetProcessHandle(NativeMethods.PROCESS_SET_INFORMATION);
                    if (!NativeMethods.SetProcessPriorityBoost(handle, !value))
                        throw new Win32Exception();
                    priorityBoostEnabled = value;
                    havePriorityBoostEnabled = true;
                }
                finally {
                    ReleaseProcessHandle(handle);
                }
            }
        }

        /// <devdoc>
        ///    <para>
        ///       Gets or sets the overall priority category for the
        ///       associated process.
        ///    </para>
        /// </devdoc>
        [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden), MonitoringDescription(SR.ProcessPriorityClass)]
        public ProcessPriorityClass PriorityClass {
            get {
                if (!havePriorityClass) {
                    SafeProcessHandle handle = null;
                    try {
                        handle = GetProcessHandle(NativeMethods.PROCESS_QUERY_INFORMATION);
                        int value = NativeMethods.GetPriorityClass(handle);
                        if (value == 0) {
                            throw new Win32Exception();
                        }
                        priorityClass = (ProcessPriorityClass)value;
                        havePriorityClass = true;
                    }
                    finally {
                        ReleaseProcessHandle(handle);
                    }
                }
                return priorityClass;
            }
            [ResourceExposure(ResourceScope.Machine)]
            [ResourceConsumption(ResourceScope.Machine)]
            set {
                if (!Enum.IsDefined(typeof(ProcessPriorityClass), value)) { 
                    throw new InvalidEnumArgumentException("value", (int)value, typeof(ProcessPriorityClass));
                }

                // BelowNormal and AboveNormal are only available on Win2k and greater.
                if (((value & (ProcessPriorityClass.BelowNormal | ProcessPriorityClass.AboveNormal)) != 0)   && 
                    (OperatingSystem.Platform != PlatformID.Win32NT || OperatingSystem.Version.Major < 5)) {
                    throw new PlatformNotSupportedException(SR.GetString(SR.PriorityClassNotSupported), null);
                }                
                                    
                SafeProcessHandle handle = null;

                try {
                    handle = GetProcessHandle(NativeMethods.PROCESS_SET_INFORMATION);
                    if (!NativeMethods.SetPriorityClass(handle, (int)value)) {
                        throw new Win32Exception();
                    }
                    priorityClass = value;
                    havePriorityClass = true;
                }
                finally {
                    ReleaseProcessHandle(handle);
                }
            }
        }

        /// <devdoc>
        ///     Returns the number of bytes that the associated process has allocated that cannot
        ///     be shared with other processes.
        /// </devdoc>
        [Obsolete("This property has been deprecated.  Please use System.Diagnostics.Process.PrivateMemorySize64 instead.  http://go.microsoft.com/fwlink/?linkid=14202")]
        [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden), MonitoringDescription(SR.ProcessPrivateMemorySize)]
        public int PrivateMemorySize {
            get {
                EnsureState(State.HaveNtProcessInfo);
                return unchecked((int)processInfo.privateBytes);
            }
        }

        [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden), MonitoringDescription(SR.ProcessPrivateMemorySize)]
        [System.Runtime.InteropServices.ComVisible(false)]            
        public long PrivateMemorySize64 {
            get {
                EnsureState(State.HaveNtProcessInfo);
                return processInfo.privateBytes;
            }
        }

        /// <devdoc>
        ///     Returns the amount of time the process has spent running code inside the operating
        ///     system core.
        /// </devdoc>
        [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden), MonitoringDescription(SR.ProcessPrivilegedProcessorTime)]
        public TimeSpan PrivilegedProcessorTime {
            get {
                EnsureState(State.IsNt);
                return GetProcessTimes().PrivilegedProcessorTime;
            }
        }

        /// <devdoc>
        ///    <para>
        ///       Gets
        ///       the friendly name of the process.
        ///    </para>
        /// </devdoc>
        [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden), MonitoringDescription(SR.ProcessProcessName)]
        public string ProcessName {
            [ResourceExposure(ResourceScope.None)]
            [ResourceConsumption(ResourceScope.Process, ResourceScope.Process)]
            get {
                EnsureState(State.HaveProcessInfo);
                String processName =  processInfo.processName;
                //
                // On some old NT-based OS like win2000, the process name from NTQuerySystemInformation is up to 15 characters.
                // Processes executing notepad_1234567.exe and notepad_12345678.exe will have the same process name.
                // GetProcessByNames will not be able find the process for notepad_12345678.exe.
                // So we will try to replace the name of the process by its main module name if the name is 15 characters.
                // However we can't always get the module name:
                //     (1) Normal user will not be able to get module information about processes. 
                //     (2) We can't get module information about remoting process.
                // We can't get module name for a remote process
                // 
                if (processName.Length == 15 && ProcessManager.IsNt && ProcessManager.IsOSOlderThanXP && !isRemoteMachine) { 
                    try {
                        String mainModuleName = MainModule.ModuleName;
                        if (mainModuleName != null) {
                            processInfo.processName = Path.ChangeExtension(Path.GetFileName(mainModuleName), null);
                        }
                    }
                    catch(Exception) {
                        // If we can't access the module information, we can still use the might-be-truncated name. 
                        // We could fail for a few reasons:
                        // (1) We don't enough privilege to get module information.
                        // (2) The process could have terminated.
                    }
                }
                
                return processInfo.processName;
            }
        }

        /// <devdoc>
        ///    <para>
        ///       Gets
        ///       or sets which processors the threads in this process can be scheduled to run on.
        ///    </para>
        /// </devdoc>
        [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden), MonitoringDescription(SR.ProcessProcessorAffinity)]
        public IntPtr ProcessorAffinity {
            get {
                if (!haveProcessorAffinity) {
                    SafeProcessHandle handle = null;
                    try {
                        handle = GetProcessHandle(NativeMethods.PROCESS_QUERY_INFORMATION);
                        IntPtr processAffinity;
                        IntPtr systemAffinity;
                        if (!NativeMethods.GetProcessAffinityMask(handle, out processAffinity, out systemAffinity))
                            throw new Win32Exception();
                        processorAffinity = processAffinity;
                    }
                    finally {
                        ReleaseProcessHandle(handle);
                    }
                    haveProcessorAffinity = true;
                }
                return processorAffinity;
            }
            [ResourceExposure(ResourceScope.Machine)]
            [ResourceConsumption(ResourceScope.Machine)]
            set {
                SafeProcessHandle handle = null;
                try {
                    handle = GetProcessHandle(NativeMethods.PROCESS_SET_INFORMATION);
                    if (!NativeMethods.SetProcessAffinityMask(handle, value)) 
                        throw new Win32Exception();
                        
                    processorAffinity = value;
                    haveProcessorAffinity = true;
                }
                finally {
                    ReleaseProcessHandle(handle);
                }
            }
        }

        /// <devdoc>
        ///    <para>
        ///       Gets a value indicating whether or not the user
        ///       interface of the process is responding.
        ///    </para>
        /// </devdoc>
        [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden), MonitoringDescription(SR.ProcessResponding)]
        public bool Responding {
            [ResourceExposure(ResourceScope.None)]
            [ResourceConsumption(ResourceScope.Machine, ResourceScope.Machine)]
            get {
                if (!haveResponding) {
                    IntPtr mainWindow = MainWindowHandle;
                    if (mainWindow == (IntPtr)0) {
                        responding = true;
                    }
                    else {
                        IntPtr result;
                        responding = NativeMethods.SendMessageTimeout(new HandleRef(this, mainWindow), NativeMethods.WM_NULL, IntPtr.Zero, IntPtr.Zero, NativeMethods.SMTO_ABORTIFHUNG, 5000, out result) != (IntPtr)0;
                    }
                }
                return responding;
            }
        }

        [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden), MonitoringDescription(SR.ProcessSessionId)]
        public int SessionId {
            get {
                EnsureState(State.HaveNtProcessInfo);
                return processInfo.sessionId;                
            }
        }

#endif // !FEATURE_PAL

        /// <devdoc>
        ///    <para>
        ///       Gets or sets the properties to pass into the <see cref='System.Diagnostics.Process.Start'/> method for the <see cref='System.Diagnostics.Process'/>
        ///       .
        ///    </para>
        /// </devdoc>
        [Browsable(false), DesignerSerializationVisibility(DesignerSerializationVisibility.Content), MonitoringDescription(SR.ProcessStartInfo)]
        public ProcessStartInfo StartInfo {
            get {
                if (startInfo == null) {
                    startInfo = new ProcessStartInfo(this);
                }                
                return startInfo;
            }
            [ResourceExposure(ResourceScope.Machine)]
            set {
                if (value == null) { 
                    throw new ArgumentNullException("value");
                }
                startInfo = value;
            }
        }

#if !FEATURE_PAL        
        /// <devdoc>
        ///     Returns the time the associated process was started.
        /// </devdoc>
        [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden), MonitoringDescription(SR.ProcessStartTime)]
        public DateTime StartTime {
            get {
                EnsureState(State.IsNt);
                return GetProcessTimes().StartTime;
            }
        }
#endif // !FEATURE_PAL

        /// <devdoc>
        ///   Represents the object used to marshal the event handler
        ///   calls issued as a result of a Process exit. Normally 
        ///   this property will  be set when the component is placed 
        ///   inside a control or  a from, since those components are 
        ///   bound to a specific thread.
        /// </devdoc>
        [
        Browsable(false),
        DefaultValue(null),         
        MonitoringDescription(SR.ProcessSynchronizingObject)
        ]
        public ISynchronizeInvoke SynchronizingObject {
            get {
               if (this.synchronizingObject == null && DesignMode) {
                    IDesignerHost host = (IDesignerHost)GetService(typeof(IDesignerHost));
                    if (host != null) {
                        object baseComponent = host.RootComponent;
                        if (baseComponent != null && baseComponent is ISynchronizeInvoke)
                            this.synchronizingObject = (ISynchronizeInvoke)baseComponent;
                    }                        
                }

                return this.synchronizingObject;
            }
            
            set {
                this.synchronizingObject = value;
            }
        }

#if !FEATURE_PAL        
        
        /// <devdoc>
        ///    <para>
        ///       Gets the set of threads that are running in the associated
        ///       process.
        ///    </para>
        /// </devdoc>
        [Browsable(false), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden), MonitoringDescription(SR.ProcessThreads)]
        public ProcessThreadCollection Threads {
            [ResourceExposure(ResourceScope.Process)]
            [ResourceConsumption(ResourceScope.Process)]
            get {
                if (threads == null) {
                    EnsureState(State.HaveProcessInfo);
                    int count = processInfo.threadInfoList.Count;
                    ProcessThread[] newThreadsArray = new ProcessThread[count];
                    for (int i = 0; i < count; i++) {
                        newThreadsArray[i] = new ProcessThread(isRemoteMachine, (ThreadInfo)processInfo.threadInfoList[i]);
                    }
                    ProcessThreadCollection newThreads = new ProcessThreadCollection(newThreadsArray);
                    threads = newThreads;
                }
                return threads;
            }
        }

        /// <devdoc>
        ///     Returns the amount of time the associated process has spent utilizing the CPU.
        ///     It is the sum of the <see cref='System.Diagnostics.Process.UserProcessorTime'/> and
        ///     <see cref='System.Diagnostics.Process.PrivilegedProcessorTime'/>.
        /// </devdoc>
        [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden), MonitoringDescription(SR.ProcessTotalProcessorTime)]
        public TimeSpan TotalProcessorTime {
            get {
                EnsureState(State.IsNt);
                return GetProcessTimes().TotalProcessorTime;
            }
        }

        /// <devdoc>
        ///     Returns the amount of time the associated process has spent running code
        ///     inside the application portion of the process (not the operating system core).
        /// </devdoc>
        [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden), MonitoringDescription(SR.ProcessUserProcessorTime)]
        public TimeSpan UserProcessorTime {
            get {
                EnsureState(State.IsNt);
                return GetProcessTimes().UserProcessorTime;
            }
        }

        /// <devdoc>
        ///     Returns the amount of virtual memory that the associated process has requested.
        /// </devdoc>
        [Obsolete("This property has been deprecated.  Please use System.Diagnostics.Process.VirtualMemorySize64 instead.  http://go.microsoft.com/fwlink/?linkid=14202")]        
        [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden), MonitoringDescription(SR.ProcessVirtualMemorySize)]
        public int VirtualMemorySize {
            get {
                EnsureState(State.HaveNtProcessInfo);
                return unchecked((int)processInfo.virtualBytes);
            }
        }
#endif // !FEATURE_PAL

        [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden), MonitoringDescription(SR.ProcessVirtualMemorySize)]
        [System.Runtime.InteropServices.ComVisible(false)]        
        public long VirtualMemorySize64 {
            get {
                EnsureState(State.HaveNtProcessInfo);
                return processInfo.virtualBytes;
            }
        }

        /// <devdoc>
        ///    <para>
        ///       Gets or sets whether the <see cref='System.Diagnostics.Process.Exited'/>
        ///       event is fired
        ///       when the process terminates.
        ///    </para>
        /// </devdoc>
        [Browsable(false), DefaultValue(false), MonitoringDescription(SR.ProcessEnableRaisingEvents)]
        public bool EnableRaisingEvents {
            get {
                return watchForExit;
            }
            set {
                if (value != watchForExit) {
                    if (Associated) {
                        if (value) {
                            OpenProcessHandle();
                            EnsureWatchingForExit();
                        }
                        else {
                            StopWatchingForExit();
                        }
                    }
                    watchForExit = value;
                }
            }
        }


        /// <devdoc>
        ///    <para>[To be supplied.]</para>
        /// </devdoc>
        [Browsable(false), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden), MonitoringDescription(SR.ProcessStandardInput)]
        public StreamWriter StandardInput {
            get { 
                if (standardInput == null) {
                    throw new InvalidOperationException(SR.GetString(SR.CantGetStandardIn));
                }

                return standardInput;
            }
        }

        /// <devdoc>
        ///    <para>[To be supplied.]</para>
        /// </devdoc>
        [Browsable(false), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden), MonitoringDescription(SR.ProcessStandardOutput)]
        public StreamReader StandardOutput {
            get {
                if (standardOutput == null) {
                    throw new InvalidOperationException(SR.GetString(SR.CantGetStandardOut));
                }

                if(outputStreamReadMode == StreamReadMode.undefined) {
                    outputStreamReadMode = StreamReadMode.syncMode;
                }
                else if (outputStreamReadMode != StreamReadMode.syncMode) {
                    throw new InvalidOperationException(SR.GetString(SR.CantMixSyncAsyncOperation));                    
                }
                    
                return standardOutput;
            }
        }

        /// <devdoc>
        ///    <para>[To be supplied.]</para>
        /// </devdoc>
        [Browsable(false), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden), MonitoringDescription(SR.ProcessStandardError)]
        public StreamReader StandardError {
            get { 
                if (standardError == null) {
                    throw new InvalidOperationException(SR.GetString(SR.CantGetStandardError));
                }

                if(errorStreamReadMode == StreamReadMode.undefined) {
                    errorStreamReadMode = StreamReadMode.syncMode;
                }
                else if (errorStreamReadMode != StreamReadMode.syncMode) {
                    throw new InvalidOperationException(SR.GetString(SR.CantMixSyncAsyncOperation));                    
                }

                return standardError;
            }
        }

#if !FEATURE_PAL  
        /// <devdoc>
        ///     Returns the total amount of physical memory the associated process.
        /// </devdoc>
        [Obsolete("This property has been deprecated.  Please use System.Diagnostics.Process.WorkingSet64 instead.  http://go.microsoft.com/fwlink/?linkid=14202")]        
        [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden), MonitoringDescription(SR.ProcessWorkingSet)]
        public int WorkingSet {
            get {
                EnsureState(State.HaveNtProcessInfo);
                return unchecked((int)processInfo.workingSet);
            }
        }
#endif // !FEATURE_PAL

        [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden), MonitoringDescription(SR.ProcessWorkingSet)]
        [System.Runtime.InteropServices.ComVisible(false)]        
        public long WorkingSet64 {
            get {
                EnsureState(State.HaveNtProcessInfo);
                return processInfo.workingSet;
            }
        }

        [Category("Behavior"), MonitoringDescription(SR.ProcessExited)]
        public event EventHandler Exited {
            add {
                onExited += value;
            }
            remove {
                onExited -= value;
            }
        }

#if !FEATURE_PAL
    
        /// <devdoc>
        ///    <para>
        ///       Closes a process that has a user interface by sending a close message
        ///       to its main window.
        ///    </para>
        /// </devdoc>
        [ResourceExposure(ResourceScope.Machine)]  // Review usages of this.
        [ResourceConsumption(ResourceScope.Machine)]
        public bool CloseMainWindow() {
            IntPtr mainWindowHandle = MainWindowHandle;
            if (mainWindowHandle == (IntPtr)0) return false;
            int style = NativeMethods.GetWindowLong(new HandleRef(this, mainWindowHandle), NativeMethods.GWL_STYLE);
            if ((style & NativeMethods.WS_DISABLED) != 0) return false;
            NativeMethods.PostMessage(new HandleRef(this, mainWindowHandle), NativeMethods.WM_CLOSE, IntPtr.Zero, IntPtr.Zero);
            return true;
        }

#endif // !FEATURE_PAL

        /// <devdoc>
        ///     Release the temporary handle we used to get process information.
        ///     If we used the process handle stored in the process object (we have all access to the handle,) don't release it.
        /// </devdoc>
        /// <internalonly/>
        void ReleaseProcessHandle(SafeProcessHandle handle) {
            if (handle == null) { 
                return; 
            }

            if (haveProcessHandle && handle == m_processHandle) {
                return;
            }
            Debug.WriteLineIf(processTracing.TraceVerbose, "Process - CloseHandle(process)");
            handle.Close();
        }

        /// <devdoc>
        ///     This is called from the threadpool when a proces exits.
        /// </devdoc>
        /// <internalonly/>
        private void CompletionCallback(object context, bool wasSignaled) {
            StopWatchingForExit();
            RaiseOnExited();      
        }

        /// <internalonly/>
        /// <devdoc>
        ///    <para>
        ///       Free any resources associated with this component.
        ///    </para>
        /// </devdoc>
        protected override void Dispose(bool disposing) {
            if( !disposed) {
                if (disposing) {
                    //Dispose managed and unmanaged resources
                    Close();
                }
                this.disposed = true;
                base.Dispose(disposing);                
            }            
        }

        /// <devdoc>
        ///    <para>
        ///       Frees any resources associated with this component.
        ///    </para>
        /// </devdoc>
        public void Close() {
            if (Associated) {
                if (haveProcessHandle) {
                    StopWatchingForExit();
                    Debug.WriteLineIf(processTracing.TraceVerbose, "Process - CloseHandle(process) in Close()");
                    m_processHandle.Close();
                    m_processHandle = null;
                    haveProcessHandle = false;
                }
                haveProcessId = false;
                isRemoteMachine = false;
                machineName = ".";
                raisedOnExited = false;

                //Don't call close on the Readers and writers
                //since they might be referenced by somebody else while the 
                //process is still alive but this method called.
                standardOutput = null;
                standardInput = null;
                standardError = null;

                output = null;
                error = null;
	

                Refresh();
            }
        }

        /// <devdoc>
        ///     Helper method for checking preconditions when accessing properties.
        /// </devdoc>
        /// <internalonly/>
        [ResourceExposure(ResourceScope.None)]
        [ResourceConsumption(ResourceScope.Machine, ResourceScope.Machine)]
        void EnsureState(State state) {

            if ((state & State.IsWin2k) != (State)0) {
#if !FEATURE_PAL
                if (OperatingSystem.Platform != PlatformID.Win32NT || OperatingSystem.Version.Major < 5)
#endif // !FEATURE_PAL
                    throw new PlatformNotSupportedException(SR.GetString(SR.Win2kRequired));
            }

            if ((state & State.IsNt) != (State)0) {
#if !FEATURE_PAL
                if (OperatingSystem.Platform != PlatformID.Win32NT)
#endif // !FEATURE_PAL                    
                    throw new PlatformNotSupportedException(SR.GetString(SR.WinNTRequired));
            }

            if ((state & State.Associated) != (State)0)
                if (!Associated)
                    throw new InvalidOperationException(SR.GetString(SR.NoAssociatedProcess));

            if ((state & State.HaveId) != (State)0) {
                if (!haveProcessId) {
#if !FEATURE_PAL                    
                    if (haveProcessHandle) {
                        SetProcessId(ProcessManager.GetProcessIdFromHandle(m_processHandle));
                     }
                    else {                     
                        EnsureState(State.Associated);
                        throw new InvalidOperationException(SR.GetString(SR.ProcessIdRequired));
                    }
#else
                    EnsureState(State.Associated);
                    throw new InvalidOperationException(SR.GetString(SR.ProcessIdRequired));
#endif // !FEATURE_PAL
                }
            }

            if ((state & State.IsLocal) != (State)0 && isRemoteMachine) {
                    throw new NotSupportedException(SR.GetString(SR.NotSupportedRemote));
            }
            
            if ((state & State.HaveProcessInfo) != (State)0) {
#if !FEATURE_PAL                
                if (processInfo == null) {
                    if ((state & State.HaveId) == (State)0) EnsureState(State.HaveId);
                    ProcessInfo[] processInfos = ProcessManager.GetProcessInfos(machineName);
                    for (int i = 0; i < processInfos.Length; i++) {
                        if (processInfos[i].processId == processId) {
                            this.processInfo = processInfos[i];
                            break;
                        }
                    }
                    if (processInfo == null) {
                        throw new InvalidOperationException(SR.GetString(SR.NoProcessInfo));
                    }
                }
#else
                throw new InvalidOperationException(SR.GetString(SR.NoProcessInfo));
#endif // !FEATURE_PAL
            }

            if ((state & State.Exited) != (State)0) {
                if (!HasExited) {
                    throw new InvalidOperationException(SR.GetString(SR.WaitTillExit));
                }
                
                if (!haveProcessHandle) {
                    throw new InvalidOperationException(SR.GetString(SR.NoProcessHandle));
                }
            }
        }
            
        /// <devdoc>
        ///     Make sure we are watching for a process exit.
        /// </devdoc>
        /// <internalonly/>
        void EnsureWatchingForExit() {
            if (!watchingForExit) {
                lock (this) {
                    if (!watchingForExit) {
                        Debug.Assert(haveProcessHandle, "Process.EnsureWatchingForExit called with no process handle");
                        Debug.Assert(Associated, "Process.EnsureWatchingForExit called with no associated process");
                        watchingForExit = true;
                        try {
                            this.waitHandle = new ProcessWaitHandle(m_processHandle);
                            this.registeredWaitHandle = ThreadPool.RegisterWaitForSingleObject(this.waitHandle,
                                new WaitOrTimerCallback(this.CompletionCallback), null, -1, true);                    
                        }
                        catch {
                            watchingForExit = false;
                            throw;
                        }
                    }
                }
            }
        }

#if !FEATURE_PAL    

        /// <devdoc>
        ///     Make sure we have obtained the min and max working set limits.
        /// </devdoc>
        /// <internalonly/>
        void EnsureWorkingSetLimits() {
            EnsureState(State.IsNt);
            if (!haveWorkingSetLimits) {
                SafeProcessHandle handle = null;
                try {
                    handle = GetProcessHandle(NativeMethods.PROCESS_QUERY_INFORMATION);
                    IntPtr min;
                    IntPtr max;
                    if (!NativeMethods.GetProcessWorkingSetSize(handle, out min, out max)) {
                        throw new Win32Exception();
                    }
                    minWorkingSet = min;
                    maxWorkingSet = max;
                    haveWorkingSetLimits = true;
                }
                finally {
                    ReleaseProcessHandle(handle);
                }
            }
        }

        public static void EnterDebugMode() {
            if (ProcessManager.IsNt) {
                SetPrivilege("SeDebugPrivilege", NativeMethods.SE_PRIVILEGE_ENABLED);
            }
        }

        [ResourceExposure(ResourceScope.None)]
        [ResourceConsumption(ResourceScope.Process, ResourceScope.Process)]
        private static void SetPrivilege(string privilegeName, int attrib) {
            IntPtr hToken = (IntPtr)0;
            NativeMethods.LUID debugValue = new NativeMethods.LUID();

            // this is only a "pseudo handle" to the current process - no need to close it later
            IntPtr processHandle = NativeMethods.GetCurrentProcess();

            // get the process token so we can adjust the privilege on it.  We DO need to
            // close the token when we're done with it.
            if (!NativeMethods.OpenProcessToken(new HandleRef(null, processHandle), NativeMethods.TOKEN_ADJUST_PRIVILEGES, out hToken)) {
                throw new Win32Exception();
            }

            try {
                if (!NativeMethods.LookupPrivilegeValue(null, privilegeName, out debugValue)) {
                    throw new Win32Exception();
                }
                
                NativeMethods.TokenPrivileges tkp = new NativeMethods.TokenPrivileges();
                tkp.Luid = debugValue;
                tkp.Attributes = attrib;
    
                NativeMethods.AdjustTokenPrivileges(new HandleRef(null, hToken), false, tkp, 0, IntPtr.Zero, IntPtr.Zero);
    
                // AdjustTokenPrivileges can return true even if it failed to
                // set the privilege, so we need to use GetLastError
                if (Marshal.GetLastWin32Error() != NativeMethods.ERROR_SUCCESS) {
                    throw new Win32Exception();
                }
            }
            finally {
                Debug.WriteLineIf(processTracing.TraceVerbose, "Process - CloseHandle(processToken)");
                SafeNativeMethods.CloseHandle(hToken);
            }
        }

        /// <devdoc>
        ///    <para>[To be supplied.]</para>
        /// </devdoc>
        public static void LeaveDebugMode() {
            if (ProcessManager.IsNt) {
                SetPrivilege("SeDebugPrivilege", 0);
            }
        }     

        /// <devdoc>
        ///    <para>
        ///       Returns a new <see cref='System.Diagnostics.Process'/> component given a process identifier and
        ///       the name of a computer in the network.
        ///    </para>
        /// </devdoc>
        [ResourceExposure(ResourceScope.Machine)]
        [ResourceConsumption(ResourceScope.Machine)]
        public static Process GetProcessById(int processId, string machineName) {
            if (!ProcessManager.IsProcessRunning(processId, machineName)) {
                throw new ArgumentException(SR.GetString(SR.MissingProccess, processId.ToString(CultureInfo.CurrentCulture)));
            }
            
            return new Process(machineName, ProcessManager.IsRemoteMachine(machineName), processId, null);
        }

        /// <devdoc>
        ///    <para>
        ///       Returns a new <see cref='System.Diagnostics.Process'/> component given the
        ///       identifier of a process on the local computer.
        ///    </para>
        /// </devdoc>
        [ResourceExposure(ResourceScope.Machine)]
        [ResourceConsumption(ResourceScope.Machine)]
        public static Process GetProcessById(int processId) {
            return GetProcessById(processId, ".");
        }

        /// <devdoc>
        ///    <para>
        ///       Creates an array of <see cref='System.Diagnostics.Process'/> components that are
        ///       associated
        ///       with process resources on the
        ///       local computer. These process resources share the specified process name.
        ///    </para>
        /// </devdoc>
        [ResourceExposure(ResourceScope.Machine)]
        [ResourceConsumption(ResourceScope.Machine)]
        public static Process[] GetProcessesByName(string processName) {
            return GetProcessesByName(processName, ".");
        }

        /// <devdoc>
        ///    <para>
        ///       Creates an array of <see cref='System.Diagnostics.Process'/> components that are associated with process resources on a
        ///       remote computer. These process resources share the specified process name.
        ///    </para>
        /// </devdoc>
        [ResourceExposure(ResourceScope.Machine)]
        [ResourceConsumption(ResourceScope.Machine)]
        public static Process[] GetProcessesByName(string processName, string machineName) {
            if (processName == null) processName = String.Empty;
            Process[] procs = GetProcesses(machineName);
            ArrayList list = new ArrayList();

            for(int i = 0; i < procs.Length; i++) {                
                if( String.Equals(processName, procs[i].ProcessName, StringComparison.OrdinalIgnoreCase)) {
                    list.Add( procs[i]);                    
                } else {
                    procs[i].Dispose();
                }
            }
            
            Process[] temp = new Process[list.Count];
            list.CopyTo(temp, 0);
            return temp;
        }

        /// <devdoc>
        ///    <para>
        ///       Creates a new <see cref='System.Diagnostics.Process'/>
        ///       component for each process resource on the local computer.
        ///    </para>
        /// </devdoc>
        [ResourceExposure(ResourceScope.Machine)]
        [ResourceConsumption(ResourceScope.Machine)]
        public static Process[] GetProcesses() {
            return GetProcesses(".");
        }

        /// <devdoc>
        ///    <para>
        ///       Creates a new <see cref='System.Diagnostics.Process'/>
        ///       component for each
        ///       process resource on the specified computer.
        ///    </para>
        /// </devdoc>
        [ResourceExposure(ResourceScope.Machine)]
        [ResourceConsumption(ResourceScope.Machine)]
        public static Process[] GetProcesses(string machineName) {
            bool isRemoteMachine = ProcessManager.IsRemoteMachine(machineName);
            ProcessInfo[] processInfos = ProcessManager.GetProcessInfos(machineName);
            Process[] processes = new Process[processInfos.Length];
            for (int i = 0; i < processInfos.Length; i++) {
                ProcessInfo processInfo = processInfos[i];
                processes[i] = new Process(machineName, isRemoteMachine, processInfo.processId, processInfo);
            }
            Debug.WriteLineIf(processTracing.TraceVerbose, "Process.GetProcesses(" + machineName + ")");
#if DEBUG
            if (processTracing.TraceVerbose) {
                Debug.Indent();
                for (int i = 0; i < processInfos.Length; i++) {
                    Debug.WriteLine(processes[i].Id + ": " + processes[i].ProcessName);
                }
                Debug.Unindent();
            }
#endif
            return processes;
        }

#endif // !FEATURE_PAL        

        /// <devdoc>
        ///    <para>
        ///       Returns a new <see cref='System.Diagnostics.Process'/>
        ///       component and associates it with the current active process.
        ///    </para>
        /// </devdoc>
        [ResourceExposure(ResourceScope.Process)]
        [ResourceConsumption(ResourceScope.Machine, ResourceScope.Process)]
        public static Process GetCurrentProcess() {
            return new Process(".", false, NativeMethods.GetCurrentProcessId(), null);
        }

        /// <devdoc>
        ///    <para>
        ///       Raises the <see cref='System.Diagnostics.Process.Exited'/> event.
        ///    </para>
        /// </devdoc>
        protected void OnExited() {
            EventHandler exited = onExited;
            if (exited != null) {
                if (this.SynchronizingObject != null && this.SynchronizingObject.InvokeRequired)
                    this.SynchronizingObject.BeginInvoke(exited, new object[]{this, EventArgs.Empty});
                else                        
                   exited(this, EventArgs.Empty);                
            }               
        }

        /// <devdoc>
        ///     Gets a short-term handle to the process, with the given access.  
        ///     If a handle is stored in current process object, then use it.
        ///     Note that the handle we stored in current process object will have all access we need.
        /// </devdoc>
        /// <internalonly/>
        [ResourceExposure(ResourceScope.None)]
        [ResourceConsumption(ResourceScope.Machine, ResourceScope.Machine)]
        SafeProcessHandle GetProcessHandle(int access, bool throwIfExited) {
            Debug.WriteLineIf(processTracing.TraceVerbose, "GetProcessHandle(access = 0x" + access.ToString("X8", CultureInfo.InvariantCulture) + ", throwIfExited = " + throwIfExited + ")");
#if DEBUG
            if (processTracing.TraceVerbose) {
                StackFrame calledFrom = new StackTrace(true).GetFrame(0);
                Debug.WriteLine("   called from " + calledFrom.GetFileName() + ", line " + calledFrom.GetFileLineNumber());
            }
#endif
            if (haveProcessHandle) {
                if (throwIfExited) {
                    // Since haveProcessHandle is true, we know we have the process handle
                    // open with at least SYNCHRONIZE access, so we can wait on it with 
                    // zero timeout to see if the process has exited.
                    ProcessWaitHandle waitHandle = null;
                    try {
                        waitHandle = new ProcessWaitHandle(m_processHandle);             
                        if (waitHandle.WaitOne(0, false)) {
                            if (haveProcessId)
                                throw new InvalidOperationException(SR.GetString(SR.ProcessHasExited, processId.ToString(CultureInfo.CurrentCulture)));
                            else
                                throw new InvalidOperationException(SR.GetString(SR.ProcessHasExitedNoId));
                        }
                    }
                    finally {
                        if( waitHandle != null) {
                            waitHandle.Close();
                        }
                    }            
                }
                return m_processHandle;
            }
            else {
                EnsureState(State.HaveId | State.IsLocal);
                SafeProcessHandle handle = SafeProcessHandle.InvalidHandle;
#if !FEATURE_PAL                
                handle = ProcessManager.OpenProcess(processId, access, throwIfExited);
#else
                IntPtr pseudohandle = NativeMethods.GetCurrentProcess();
                // Get a real handle
                if (!NativeMethods.DuplicateHandle (new HandleRef(this, pseudohandle), 
                                                    new HandleRef(this, pseudohandle), 
                                                    new HandleRef(this, pseudohandle), 
                                                    out handle,
                                                    0, 
                                                    false, 
                                                    NativeMethods.DUPLICATE_SAME_ACCESS | 
                                                    NativeMethods.DUPLICATE_CLOSE_SOURCE)) {
                    throw new Win32Exception();
                }
#endif // !FEATURE_PAL
                if (throwIfExited && (access & NativeMethods.PROCESS_QUERY_INFORMATION) != 0) {         
                    if (NativeMethods.GetExitCodeProcess(handle, out exitCode) && exitCode != NativeMethods.STILL_ACTIVE) {
                        throw new InvalidOperationException(SR.GetString(SR.ProcessHasExited, processId.ToString(CultureInfo.CurrentCulture)));
                    }
                }
                return handle;
            }

        }

        /// <devdoc>
        ///     Gets a short-term handle to the process, with the given access.  If a handle exists,
        ///     then it is reused.  If the process has exited, it throws an exception.
        /// </devdoc>
        /// <internalonly/>
        SafeProcessHandle GetProcessHandle(int access) {
            return GetProcessHandle(access, true);
        }

        /// <devdoc>
        ///     Opens a long-term handle to the process, with all access.  If a handle exists,
        ///     then it is reused.  If the process has exited, it throws an exception.
        /// </devdoc>
        /// <internalonly/>
        SafeProcessHandle OpenProcessHandle() {
            return OpenProcessHandle(NativeMethods.PROCESS_ALL_ACCESS);
        }

        SafeProcessHandle OpenProcessHandle(Int32 access) {
            if (!haveProcessHandle) {
                //Cannot open a new process handle if the object has been disposed, since finalization has been suppressed.            
                if (this.disposed) {
                    throw new ObjectDisposedException(GetType().Name);
                }
                        
                SetProcessHandle(GetProcessHandle(access));
            }                
            return m_processHandle;
        }

        /// <devdoc>
        ///     Raise the Exited event, but make sure we don't do it more than once.
        /// </devdoc>
        /// <internalonly/>
        void RaiseOnExited() {
            if (!raisedOnExited) {
                lock (this) {
                    if (!raisedOnExited) {
                        raisedOnExited = true;
                        OnExited();
                    }
                }
            }
        }

        /// <devdoc>
        ///    <para>
        ///       Discards any information about the associated process
        ///       that has been cached inside the process component. After <see cref='System.Diagnostics.Process.Refresh'/> is called, the
        ///       first request for information for each property causes the process component
        ///       to obtain a new value from the associated process.
        ///    </para>
        /// </devdoc>
        public void Refresh() {
            processInfo = null;
#if !FEATURE_PAL            
            threads = null;
            modules = null;
#endif // !FEATURE_PAL            
            mainWindowTitle = null;
            exited = false;
            signaled = false;
            haveMainWindow = false;
            haveWorkingSetLimits = false;
            haveProcessorAffinity = false;
            havePriorityClass = false;
            haveExitTime = false;
            haveResponding = false;
            havePriorityBoostEnabled = false;
        }

        /// <devdoc>
        ///     Helper to associate a process handle with this component.
        /// </devdoc>
        /// <internalonly/>
        void SetProcessHandle(SafeProcessHandle processHandle) {
            this.m_processHandle = processHandle;
            this.haveProcessHandle = true;
            if (watchForExit) {
                EnsureWatchingForExit();
            }
        }

        /// <devdoc>
        ///     Helper to associate a process id with this component.
        /// </devdoc>
        /// <internalonly/>
        [ResourceExposure(ResourceScope.Machine)]
        void SetProcessId(int processId) {
            this.processId = processId;
            this.haveProcessId = true;
        }

#if !FEATURE_PAL        

        /// <devdoc>
        ///     Helper to set minimum or maximum working set limits.
        /// </devdoc>
        /// <internalonly/>
        [ResourceExposure(ResourceScope.Process)]
        [ResourceConsumption(ResourceScope.Machine, ResourceScope.Machine)]
        void SetWorkingSetLimits(object newMin, object newMax) {
            EnsureState(State.IsNt);

            SafeProcessHandle handle = null;
            try {
                handle = GetProcessHandle(NativeMethods.PROCESS_QUERY_INFORMATION | NativeMethods.PROCESS_SET_QUOTA);
                IntPtr min;
                IntPtr max;
                if (!NativeMethods.GetProcessWorkingSetSize(handle, out min, out max)) {
                    throw new Win32Exception();
                }
                
                if (newMin != null) {
                    min = (IntPtr)newMin;
                }
                
                if (newMax != null) { 
                    max = (IntPtr)newMax;
                }
                
                if ((long)min > (long)max) {
                    if (newMin != null) {
                        throw new ArgumentException(SR.GetString(SR.BadMinWorkset));
                    }
                    else {
                        throw new ArgumentException(SR.GetString(SR.BadMaxWorkset));
                    }
                }
                
                if (!NativeMethods.SetProcessWorkingSetSize(handle, min, max)) {
                    throw new Win32Exception();
                }
                
                // The value may be rounded/changed by the OS, so go get it
                if (!NativeMethods.GetProcessWorkingSetSize(handle, out min, out max)) {
                    throw new Win32Exception();
                }
                minWorkingSet = min;
                maxWorkingSet = max;
                haveWorkingSetLimits = true;
            }
            finally {
                ReleaseProcessHandle(handle);
            }
        }

#endif // !FEATURE_PAL

        /// <devdoc>
        ///    <para>
        ///       Starts a process specified by the <see cref='System.Diagnostics.Process.StartInfo'/> property of this <see cref='System.Diagnostics.Process'/>
        ///       component and associates it with the
        ///    <see cref='System.Diagnostics.Process'/> . If a process resource is reused 
        ///       rather than started, the reused process is associated with this <see cref='System.Diagnostics.Process'/>
        ///       component.
        ///    </para>
        /// </devdoc>
        [ResourceExposure(ResourceScope.None)]
        [ResourceConsumption(ResourceScope.Machine, ResourceScope.Machine)]
        public bool Start() {
            Close();
            ProcessStartInfo startInfo = StartInfo;
            if (startInfo.FileName.Length == 0) 
                throw new InvalidOperationException(SR.GetString(SR.FileNameMissing));

            if (startInfo.UseShellExecute) {
#if !FEATURE_PAL                
                return StartWithShellExecuteEx(startInfo);
#else
                throw new InvalidOperationException(SR.GetString(SR.net_perm_invalid_val, "StartInfo.UseShellExecute", true));
#endif // !FEATURE_PAL
            } else {
                return StartWithCreateProcess(startInfo);
            }
        }


        [ResourceExposure(ResourceScope.Process)]
        [ResourceConsumption(ResourceScope.Process)]
        private static void CreatePipeWithSecurityAttributes(out SafeFileHandle hReadPipe, out SafeFileHandle hWritePipe, NativeMethods.SECURITY_ATTRIBUTES lpPipeAttributes, int nSize) {
            bool ret = NativeMethods.CreatePipe(out hReadPipe, out hWritePipe, lpPipeAttributes, nSize);
            if (!ret || hReadPipe.IsInvalid || hWritePipe.IsInvalid) {
                throw new Win32Exception();
            }
        }

        // Using synchronous Anonymous pipes for process input/output redirection means we would end up 
        // wasting a worker threadpool thread per pipe instance. Overlapped pipe IO is desirable, since 
        // it will take advantage of the NT IO completion port infrastructure. But we can't really use 
        // Overlapped I/O for process input/output as it would break Console apps (managed Console class 
        // methods such as WriteLine as well as native CRT functions like printf) which are making an
        // assumption that the console standard handles (obtained via GetStdHandle()) are opened
        // for synchronous I/O and hence they can work fine with ReadFile/WriteFile synchrnously!
        [ResourceExposure(ResourceScope.None)]
        [ResourceConsumption(ResourceScope.Machine, ResourceScope.Machine)]
        private void CreatePipe(out SafeFileHandle parentHandle, out SafeFileHandle childHandle, bool parentInputs) {
            NativeMethods.SECURITY_ATTRIBUTES securityAttributesParent = new NativeMethods.SECURITY_ATTRIBUTES();
            securityAttributesParent.bInheritHandle = true;
            
            SafeFileHandle hTmp = null;
            try {
                if (parentInputs) {
                    CreatePipeWithSecurityAttributes(out childHandle, out hTmp, securityAttributesParent, 0);                                                          
                } 
                else {
                    CreatePipeWithSecurityAttributes(out hTmp, 
                                                          out childHandle, 
                                                          securityAttributesParent, 
                                                          0);                                                                              
                }
                // Duplicate the parent handle to be non-inheritable so that the child process 
                // doesn't have access. This is done for correctness sake, exact reason is unclear.
                // One potential theory is that child process can do something brain dead like 
                // closing the parent end of the pipe and there by getting into a blocking situation
                // as parent will not be draining the pipe at the other end anymore. 
                if (!NativeMethods.DuplicateHandle(new HandleRef(this, NativeMethods.GetCurrentProcess()), 
                                                                   hTmp,
                                                                   new HandleRef(this, NativeMethods.GetCurrentProcess()), 
                                                                   out parentHandle,
                                                                   0, 
                                                                   false, 
                                                                   NativeMethods.DUPLICATE_SAME_ACCESS)) {                                                                       
                    throw new Win32Exception();
                }
            }
            finally {
                if( hTmp != null && !hTmp.IsInvalid) {
                    hTmp.Close();
                }
            }
        }            

        private static StringBuilder BuildCommandLine(string executableFileName, string arguments) {
            // Construct a StringBuilder with the appropriate command line
            // to pass to CreateProcess.  If the filename isn't already 
            // in quotes, we quote it here.  This prevents some security
            // problems (it specifies exactly which part of the string
            // is the file to execute).
            StringBuilder commandLine = new StringBuilder();
            string fileName = executableFileName.Trim();
            bool fileNameIsQuoted = (fileName.StartsWith("\"", StringComparison.Ordinal) && fileName.EndsWith("\"", StringComparison.Ordinal));
            if (!fileNameIsQuoted) { 
                commandLine.Append("\"");
            }
            
            commandLine.Append(fileName);
            
            if (!fileNameIsQuoted) {
                commandLine.Append("\"");
            }
            
            if (!String.IsNullOrEmpty(arguments)) {
                commandLine.Append(" ");
                commandLine.Append(arguments);                
            }                        

            return commandLine;
        }
        
        [ResourceExposure(ResourceScope.Machine)]
        [ResourceConsumption(ResourceScope.Machine)]
        private bool StartWithCreateProcess(ProcessStartInfo startInfo) {
            if( startInfo.StandardOutputEncoding != null && !startInfo.RedirectStandardOutput) {
                throw new InvalidOperationException(SR.GetString(SR.StandardOutputEncodingNotAllowed));
            }

            if( startInfo.StandardErrorEncoding != null && !startInfo.RedirectStandardError) {
                throw new InvalidOperationException(SR.GetString(SR.StandardErrorEncodingNotAllowed));
            }            
            
            // See knowledge base article Q190351 for an explanation of the following code.  Noteworthy tricky points:
            //    * The handles are duplicated as non-inheritable before they are passed to CreateProcess so
            //      that the child process can not close them
            //    * CreateProcess allows you to redirect all or none of the standard IO handles, so we use
            //      GetStdHandle for the handles that are not being redirected

            //Cannot start a new process and store its handle if the object has been disposed, since finalization has been suppressed.            
            if (this.disposed) {
                throw new ObjectDisposedException(GetType().Name);
            }

            StringBuilder commandLine = BuildCommandLine(startInfo.FileName, startInfo.Arguments);

            NativeMethods.STARTUPINFO startupInfo = new NativeMethods.STARTUPINFO();
            SafeNativeMethods.PROCESS_INFORMATION processInfo = new SafeNativeMethods.PROCESS_INFORMATION();
            SafeProcessHandle procSH = new SafeProcessHandle();
            SafeThreadHandle threadSH = new SafeThreadHandle();
            bool retVal;
            int errorCode = 0;
            // handles used in parent process
            SafeFileHandle standardInputWritePipeHandle = null;
            SafeFileHandle standardOutputReadPipeHandle = null;
            SafeFileHandle standardErrorReadPipeHandle = null;
            GCHandle environmentHandle = new GCHandle();            
            lock (s_CreateProcessLock) {
            try {
                // set up the streams
                if (startInfo.RedirectStandardInput || startInfo.RedirectStandardOutput || startInfo.RedirectStandardError) {                        
                    if (startInfo.RedirectStandardInput) {
                        CreatePipe(out standardInputWritePipeHandle, out startupInfo.hStdInput, true);
                        } else {
                        startupInfo.hStdInput  =  new SafeFileHandle(NativeMethods.GetStdHandle(NativeMethods.STD_INPUT_HANDLE), false);
                    }
    
                    if (startInfo.RedirectStandardOutput) {                        
                        CreatePipe(out standardOutputReadPipeHandle, out startupInfo.hStdOutput, false);
                        } else {
                        startupInfo.hStdOutput = new SafeFileHandle(NativeMethods.GetStdHandle(NativeMethods.STD_OUTPUT_HANDLE), false);
                    }
    
                    if (startInfo.RedirectStandardError) {
                        CreatePipe(out standardErrorReadPipeHandle, out startupInfo.hStdError, false);
                        } else {
                        startupInfo.hStdError = new SafeFileHandle(NativeMethods.GetStdHandle(NativeMethods.STD_ERROR_HANDLE), false);
                    }
    
                    startupInfo.dwFlags = NativeMethods.STARTF_USESTDHANDLES;
                }
    
                // set up the creation flags paramater
                int creationFlags = 0;
#if !FEATURE_PAL                
                if (startInfo.CreateNoWindow)  creationFlags |= NativeMethods.CREATE_NO_WINDOW;               
#endif // !FEATURE_PAL                

                // set up the environment block parameter
                IntPtr environmentPtr = (IntPtr)0;
                if (startInfo.environmentVariables != null) {
                    bool unicode = false;
#if !FEATURE_PAL                    
                    if (ProcessManager.IsNt) {
                        creationFlags |= NativeMethods.CREATE_UNICODE_ENVIRONMENT;                
                        unicode = true;
                    }
#endif // !FEATURE_PAL
                    
                    byte[] environmentBytes = EnvironmentBlock.ToByteArray(startInfo.environmentVariables, unicode);
                    environmentHandle = GCHandle.Alloc(environmentBytes, GCHandleType.Pinned);
                    environmentPtr = environmentHandle.AddrOfPinnedObject();
                }

                string workingDirectory = startInfo.WorkingDirectory;
                if (workingDirectory == string.Empty)
                    workingDirectory = Environment.CurrentDirectory;

#if !FEATURE_PAL                    
                if (startInfo.UserName.Length != 0) {                              
                    NativeMethods.LogonFlags logonFlags = (NativeMethods.LogonFlags)0;                    
                    if( startInfo.LoadUserProfile) {
                        logonFlags = NativeMethods.LogonFlags.LOGON_WITH_PROFILE;
                    }

                    IntPtr password = IntPtr.Zero;
                    try {
                        if( startInfo.Password == null) {
                            password = Marshal.StringToCoTaskMemUni(String.Empty);
                            } else {
                            password = Marshal.SecureStringToCoTaskMemUnicode(startInfo.Password);                        
                        }

                        RuntimeHelpers.PrepareConstrainedRegions();
                        try {} finally {
                           retVal = NativeMethods.CreateProcessWithLogonW(
                                   startInfo.UserName,
                                   startInfo.Domain,
                                   password,
                                   logonFlags,
                                   null,            // we don't need this since all the info is in commandLine
                                   commandLine,
                                   creationFlags,
                                   environmentPtr,
                                   workingDirectory,
                                   startupInfo,        // pointer to STARTUPINFO
                                   processInfo         // pointer to PROCESS_INFORMATION
                               ); 
                           if (!retVal)                            
                              errorCode = Marshal.GetLastWin32Error();
                           if ( processInfo.hProcess!= (IntPtr)0 && processInfo.hProcess!= (IntPtr)NativeMethods.INVALID_HANDLE_VALUE)
                              procSH.InitialSetHandle(processInfo.hProcess);  
                           if ( processInfo.hThread != (IntPtr)0 && processInfo.hThread != (IntPtr)NativeMethods.INVALID_HANDLE_VALUE)
                              threadSH.InitialSetHandle(processInfo.hThread);            
                        }
                        if (!retVal){                            
                                if (errorCode == NativeMethods.ERROR_BAD_EXE_FORMAT || errorCode == NativeMethods.ERROR_EXE_MACHINE_TYPE_MISMATCH) {
                                throw new Win32Exception(errorCode, SR.GetString(SR.InvalidApplication));
                            }

                            throw new Win32Exception(errorCode);
                        }
                        } finally {
                        if( password != IntPtr.Zero) {
                            Marshal.ZeroFreeCoTaskMemUnicode(password);
                        }
                    }
                    } else {
#endif // !FEATURE_PAL
                    RuntimeHelpers.PrepareConstrainedRegions();
                    try {} finally {
                       retVal = NativeMethods.CreateProcess (
                               null,               // we don't need this since all the info is in commandLine
                               commandLine,        // pointer to the command line string
                               null,               // pointer to process security attributes, we don't need to inheriat the handle
                               null,               // pointer to thread security attributes
                               true,               // handle inheritance flag
                               creationFlags,      // creation flags
                               environmentPtr,     // pointer to new environment block
                               workingDirectory,   // pointer to current directory name
                               startupInfo,        // pointer to STARTUPINFO
                               processInfo         // pointer to PROCESS_INFORMATION
                           );
                       if (!retVal)                            
                              errorCode = Marshal.GetLastWin32Error();
                       if ( processInfo.hProcess!= (IntPtr)0 && processInfo.hProcess!= (IntPtr)NativeMethods.INVALID_HANDLE_VALUE)
                           procSH.InitialSetHandle(processInfo.hProcess);  
                       if ( processInfo.hThread != (IntPtr)0 && processInfo.hThread != (IntPtr)NativeMethods.INVALID_HANDLE_VALUE)
                          threadSH.InitialSetHandle(processInfo.hThread);                    
                    }
                    if (!retVal) {
                            if (errorCode == NativeMethods.ERROR_BAD_EXE_FORMAT || errorCode == NativeMethods.ERROR_EXE_MACHINE_TYPE_MISMATCH) {
                          throw new Win32Exception(errorCode, SR.GetString(SR.InvalidApplication));
                       }
                        throw new Win32Exception(errorCode);
                    }
#if !FEATURE_PAL                    
                }
#endif
                } finally {
                // free environment block
                if (environmentHandle.IsAllocated) {
                    environmentHandle.Free();   
                }

                startupInfo.Dispose();
            }
            }

            if (startInfo.RedirectStandardInput) {
                standardInput = new StreamWriter(new FileStream(standardInputWritePipeHandle, FileAccess.Write, 4096, false), Console.InputEncoding, 4096);
                standardInput.AutoFlush = true;
            }
            if (startInfo.RedirectStandardOutput) {
                Encoding enc = (startInfo.StandardOutputEncoding != null) ? startInfo.StandardOutputEncoding : Console.OutputEncoding;
                standardOutput = new StreamReader(new FileStream(standardOutputReadPipeHandle, FileAccess.Read, 4096, false), enc, true, 4096);
            }
            if (startInfo.RedirectStandardError) {
                Encoding enc = (startInfo.StandardErrorEncoding != null) ? startInfo.StandardErrorEncoding : Console.OutputEncoding;
                standardError = new StreamReader(new FileStream(standardErrorReadPipeHandle, FileAccess.Read, 4096, false), enc, true, 4096);
            }
            
            bool ret = false;
            if (!procSH.IsInvalid) {
                SetProcessHandle(procSH);
                SetProcessId(processInfo.dwProcessId);
                threadSH.Close();
                ret = true;
            }

            return ret;

        }

#if !FEATURE_PAL

        [ResourceExposure(ResourceScope.Machine)]
        [ResourceConsumption(ResourceScope.Machine)]
        private bool StartWithShellExecuteEx(ProcessStartInfo startInfo) {                        
            //Cannot start a new process and store its handle if the object has been disposed, since finalization has been suppressed.            
            if (this.disposed)
                throw new ObjectDisposedException(GetType().Name);

            if( !String.IsNullOrEmpty(startInfo.UserName) || (startInfo.Password != null) ) {
                throw new InvalidOperationException(SR.GetString(SR.CantStartAsUser));                
            }
            
            if (startInfo.RedirectStandardInput || startInfo.RedirectStandardOutput || startInfo.RedirectStandardError) {
                throw new InvalidOperationException(SR.GetString(SR.CantRedirectStreams));
            }

            if (startInfo.StandardErrorEncoding != null) {
                throw new InvalidOperationException(SR.GetString(SR.StandardErrorEncodingNotAllowed));
            }

            if (startInfo.StandardOutputEncoding != null) {
                throw new InvalidOperationException(SR.GetString(SR.StandardOutputEncodingNotAllowed));
            }

            // can't set env vars with ShellExecuteEx...
            if (startInfo.environmentVariables != null) {
                throw new InvalidOperationException(SR.GetString(SR.CantUseEnvVars));
            }

            NativeMethods.ShellExecuteInfo shellExecuteInfo = new NativeMethods.ShellExecuteInfo();
            shellExecuteInfo.fMask = NativeMethods.SEE_MASK_NOCLOSEPROCESS;
            if (startInfo.ErrorDialog) {
                shellExecuteInfo.hwnd = startInfo.ErrorDialogParentHandle;
            }
            else {
                shellExecuteInfo.fMask |= NativeMethods.SEE_MASK_FLAG_NO_UI;
            }

            switch (startInfo.WindowStyle) {
                case ProcessWindowStyle.Hidden:
                    shellExecuteInfo.nShow = NativeMethods.SW_HIDE;
                    break;
                case ProcessWindowStyle.Minimized:
                    shellExecuteInfo.nShow = NativeMethods.SW_SHOWMINIMIZED;
                    break;
                case ProcessWindowStyle.Maximized:
                    shellExecuteInfo.nShow = NativeMethods.SW_SHOWMAXIMIZED;
                    break;
                default:
                    shellExecuteInfo.nShow = NativeMethods.SW_SHOWNORMAL;
                    break;
            }

            
            try {
                if (startInfo.FileName.Length != 0)
                    shellExecuteInfo.lpFile = Marshal.StringToHGlobalAuto(startInfo.FileName);
                if (startInfo.Verb.Length != 0)
                    shellExecuteInfo.lpVerb = Marshal.StringToHGlobalAuto(startInfo.Verb);
                if (startInfo.Arguments.Length != 0)
                    shellExecuteInfo.lpParameters = Marshal.StringToHGlobalAuto(startInfo.Arguments);
                if (startInfo.WorkingDirectory.Length != 0)
                    shellExecuteInfo.lpDirectory = Marshal.StringToHGlobalAuto(startInfo.WorkingDirectory);

                shellExecuteInfo.fMask |= NativeMethods.SEE_MASK_FLAG_DDEWAIT;

                ShellExecuteHelper executeHelper = new ShellExecuteHelper(shellExecuteInfo);
                if (!executeHelper.ShellExecuteOnSTAThread()) {
                    int error = executeHelper.ErrorCode;
                    if (error == 0) {
                        switch ((long)shellExecuteInfo.hInstApp) {
                            case NativeMethods.SE_ERR_FNF: error = NativeMethods.ERROR_FILE_NOT_FOUND; break;
                            case NativeMethods.SE_ERR_PNF: error = NativeMethods.ERROR_PATH_NOT_FOUND; break;
                            case NativeMethods.SE_ERR_ACCESSDENIED: error = NativeMethods.ERROR_ACCESS_DENIED; break;
                            case NativeMethods.SE_ERR_OOM: error = NativeMethods.ERROR_NOT_ENOUGH_MEMORY; break;
                            case NativeMethods.SE_ERR_DDEFAIL:
                            case NativeMethods.SE_ERR_DDEBUSY:
                            case NativeMethods.SE_ERR_DDETIMEOUT: error = NativeMethods.ERROR_DDE_FAIL; break;
                            case NativeMethods.SE_ERR_SHARE: error = NativeMethods.ERROR_SHARING_VIOLATION; break;
                            case NativeMethods.SE_ERR_NOASSOC: error = NativeMethods.ERROR_NO_ASSOCIATION; break;
                            case NativeMethods.SE_ERR_DLLNOTFOUND: error = NativeMethods.ERROR_DLL_NOT_FOUND; break;
                            default: error = (int)shellExecuteInfo.hInstApp; break;
                        }
                    }
                    if( error == NativeMethods.ERROR_BAD_EXE_FORMAT || error == NativeMethods.ERROR_EXE_MACHINE_TYPE_MISMATCH) {
                        throw new Win32Exception(error, SR.GetString(SR.InvalidApplication));
                    }
                    throw new Win32Exception(error);
                }
            
            }
            finally {                
                if (shellExecuteInfo.lpFile != (IntPtr)0) Marshal.FreeHGlobal(shellExecuteInfo.lpFile);
                if (shellExecuteInfo.lpVerb != (IntPtr)0) Marshal.FreeHGlobal(shellExecuteInfo.lpVerb);
                if (shellExecuteInfo.lpParameters != (IntPtr)0) Marshal.FreeHGlobal(shellExecuteInfo.lpParameters);
                if (shellExecuteInfo.lpDirectory != (IntPtr)0) Marshal.FreeHGlobal(shellExecuteInfo.lpDirectory);
            }

            if (shellExecuteInfo.hProcess != (IntPtr)0) {                
                SafeProcessHandle handle = new SafeProcessHandle(shellExecuteInfo.hProcess);
                SetProcessHandle(handle);
                return true;
            }
            
            return false;            
        }

        [ResourceExposure(ResourceScope.Machine)]
        [ResourceConsumption(ResourceScope.Machine)]
        public static Process Start( string fileName, string userName, SecureString password, string domain ) {
            ProcessStartInfo startInfo = new ProcessStartInfo(fileName);            
            startInfo.UserName = userName;
            startInfo.Password = password;
            startInfo.Domain = domain;
            startInfo.UseShellExecute = false;
            return Start(startInfo);
        }
        
        [ResourceExposure(ResourceScope.Machine)]
        [ResourceConsumption(ResourceScope.Machine)]
        public static Process Start( string fileName, string arguments, string userName, SecureString password, string domain ) {
            ProcessStartInfo startInfo = new ProcessStartInfo(fileName, arguments);                        
            startInfo.UserName = userName;
            startInfo.Password = password;
            startInfo.Domain = domain;
            startInfo.UseShellExecute = false;            
            return Start(startInfo);            
        }


#endif // !FEATURE_PAL

        /// <devdoc>
        ///    <para>
        ///       Starts a process resource by specifying the name of a
        ///       document or application file. Associates the process resource with a new <see cref='System.Diagnostics.Process'/>
        ///       component.
        ///    </para>
        /// </devdoc>
        [ResourceExposure(ResourceScope.Machine)]
        [ResourceConsumption(ResourceScope.Machine)]
        public static Process Start(string fileName) {
            return Start(new ProcessStartInfo(fileName));
        }

        /// <devdoc>
        ///    <para>
        ///       Starts a process resource by specifying the name of an
        ///       application and a set of command line arguments. Associates the process resource
        ///       with a new <see cref='System.Diagnostics.Process'/>
        ///       component.
        ///    </para>
        /// </devdoc>
        [ResourceExposure(ResourceScope.Machine)]
        [ResourceConsumption(ResourceScope.Machine)]
        public static Process Start(string fileName, string arguments) {
            return Start(new ProcessStartInfo(fileName, arguments));
        }

        /// <devdoc>
        ///    <para>
        ///       Starts a process resource specified by the process start
        ///       information passed in, for example the file name of the process to start.
        ///       Associates the process resource with a new <see cref='System.Diagnostics.Process'/>
        ///       component.
        ///    </para>
        /// </devdoc>
        [ResourceExposure(ResourceScope.Machine)]
        [ResourceConsumption(ResourceScope.Machine)]
        public static Process Start(ProcessStartInfo startInfo) {
            Process process = new Process();
            if (startInfo == null) throw new ArgumentNullException("startInfo");
            process.StartInfo = startInfo;
            if (process.Start()) {
                return process;
            }
            return null;
        }

        /// <devdoc>
        ///    <para>
        ///       Stops the
        ///       associated process immediately.
        ///    </para>
        /// </devdoc>
        [ResourceExposure(ResourceScope.Machine)]
        [ResourceConsumption(ResourceScope.Machine)]
        public void Kill() {
            SafeProcessHandle handle = null;
            try {
                handle = GetProcessHandle(NativeMethods.PROCESS_TERMINATE);
                if (!NativeMethods.TerminateProcess(handle, -1))
                    throw new Win32Exception();
            }
            finally {
                ReleaseProcessHandle(handle);
            }
        }

        /// <devdoc>
        ///     Make sure we are not watching for process exit.
        /// </devdoc>
        /// <internalonly/>
        void StopWatchingForExit() {
            if (watchingForExit) {
                lock (this) {
                    if (watchingForExit) {
                        watchingForExit = false;
                        registeredWaitHandle.Unregister(null);
                        waitHandle.Close();
                        waitHandle = null;
                        registeredWaitHandle = null;
                    }
                }
            }
        }

        public override string ToString() {
#if !FEATURE_PAL        
            if (Associated) {
                string processName  =  String.Empty;  
                //
                // On windows 9x, we can't map a handle to an id.
                // So ProcessName will throw. We shouldn't throw in Process.ToString though.
                // Process.GetProcesses should be used to get all the processes on the machine.
                // The processes returned from it will have a nice name.
                //
                try {
                    processName = this.ProcessName;
                }    
                catch(PlatformNotSupportedException) {
                }
                if( processName.Length != 0) { 
                    return String.Format(CultureInfo.CurrentCulture, "{0} ({1})", base.ToString(), processName);
                }
                return base.ToString();
            }    
            else
#endif // !FEATURE_PAL                
                return base.ToString();
        }

        /// <devdoc>
        ///    <para>
        ///       Instructs the <see cref='System.Diagnostics.Process'/> component to wait the specified number of milliseconds for the associated process to exit.
        ///    </para>
        /// </devdoc>
        public bool WaitForExit(int milliseconds) {
            SafeProcessHandle handle = null;
	     bool exited;
            ProcessWaitHandle processWaitHandle = null;
            try {
                handle = GetProcessHandle(NativeMethods.SYNCHRONIZE, false);                
                if (handle.IsInvalid) {
                    exited = true;
                }
                else {
                    processWaitHandle = new ProcessWaitHandle(handle);
                    if( processWaitHandle.WaitOne(milliseconds, false)) {
                        exited = true;
                        signaled = true;
                    }
                    else {
                        exited = false;
                        signaled = false;
                    }
                }
            }
            finally {
                if( processWaitHandle != null) {
                    processWaitHandle.Close();
                }

                // If we have a hard timeout, we cannot wait for the streams
                if( output != null && milliseconds == -1) {
                    output.WaitUtilEOF();
                }

                if( error != null && milliseconds == -1) {
                    error.WaitUtilEOF();
                }

                ReleaseProcessHandle(handle);

            }
            
            if (exited && watchForExit) {
                RaiseOnExited();
            }
			
            return exited;
        }

        /// <devdoc>
        ///    <para>
        ///       Instructs the <see cref='System.Diagnostics.Process'/> component to wait
        ///       indefinitely for the associated process to exit.
        ///    </para>
        /// </devdoc>
        public void WaitForExit() {
            WaitForExit(-1);
        }

#if !FEATURE_PAL        

        /// <devdoc>
        ///    <para>
        ///       Causes the <see cref='System.Diagnostics.Process'/> component to wait the
        ///       specified number of milliseconds for the associated process to enter an
        ///       idle state.
        ///       This is only applicable for processes with a user interface,
        ///       therefore a message loop.
        ///    </para>
        /// </devdoc>
        public bool WaitForInputIdle(int milliseconds) {
            SafeProcessHandle handle = null;
            bool idle;
            try {
                handle = GetProcessHandle(NativeMethods.SYNCHRONIZE | NativeMethods.PROCESS_QUERY_INFORMATION);
                int ret = NativeMethods.WaitForInputIdle(handle, milliseconds);
                switch (ret) {
                    case NativeMethods.WAIT_OBJECT_0:
                        idle = true;
                        break;
                    case NativeMethods.WAIT_TIMEOUT:
                        idle = false;
                        break;
                    case NativeMethods.WAIT_FAILED:
                    default:
                        throw new InvalidOperationException(SR.GetString(SR.InputIdleUnkownError));
                }
            }
            finally {
                ReleaseProcessHandle(handle);
            }
            return idle;
        }

        /// <devdoc>
        ///    <para>
        ///       Instructs the <see cref='System.Diagnostics.Process'/> component to wait
        ///       indefinitely for the associated process to enter an idle state. This
        ///       is only applicable for processes with a user interface, therefore a message loop.
        ///    </para>
        /// </devdoc>
        public bool WaitForInputIdle() {
            return WaitForInputIdle(Int32.MaxValue);
        }

#endif // !FEATURE_PAL        

        // Support for working asynchronously with streams
        /// <devdoc>
        /// <para>
        /// Instructs the <see cref='System.Diagnostics.Process'/> component to start
        /// reading the StandardOutput stream asynchronously. The user can register a callback
        /// that will be called when a line of data terminated by \n,\r or \r\n is reached, or the end of stream is reached
        /// then the remaining information is returned. The user can add an event handler to OutputDataReceived.
        /// </para>
        /// </devdoc>
        [System.Runtime.InteropServices.ComVisible(false)]        
        public void BeginOutputReadLine() {

            if(outputStreamReadMode == StreamReadMode.undefined) {
                outputStreamReadMode = StreamReadMode.asyncMode;
            }
            else if (outputStreamReadMode != StreamReadMode.asyncMode) {
                throw new InvalidOperationException(SR.GetString(SR.CantMixSyncAsyncOperation));                    
            }
            
            if (pendingOutputRead)
                throw new InvalidOperationException(SR.GetString(SR.PendingAsyncOperation));

            pendingOutputRead = true;
            // We can't detect if there's a pending sychronous read, tream also doesn't.
            if (output == null) {
                if (standardOutput == null) {
                    throw new InvalidOperationException(SR.GetString(SR.CantGetStandardOut));
                }

                Stream s = standardOutput.BaseStream;
                output = new AsyncStreamReader(this, s, new UserCallBack(this.OutputReadNotifyUser), standardOutput.CurrentEncoding);
            }
            output.BeginReadLine();
        }


        /// <devdoc>
        /// <para>
        /// Instructs the <see cref='System.Diagnostics.Process'/> component to start
        /// reading the StandardError stream asynchronously. The user can register a callback
        /// that will be called when a line of data terminated by \n,\r or \r\n is reached, or the end of stream is reached
        /// then the remaining information is returned. The user can add an event handler to ErrorDataReceived.
        /// </para>
        /// </devdoc>
        [System.Runtime.InteropServices.ComVisible(false)]        
        public void BeginErrorReadLine() {

            if(errorStreamReadMode == StreamReadMode.undefined) {
                errorStreamReadMode = StreamReadMode.asyncMode;
            }
            else if (errorStreamReadMode != StreamReadMode.asyncMode) {
                throw new InvalidOperationException(SR.GetString(SR.CantMixSyncAsyncOperation));                    
            }
            
            if (pendingErrorRead) {
                throw new InvalidOperationException(SR.GetString(SR.PendingAsyncOperation));
            }

            pendingErrorRead = true;
            // We can't detect if there's a pending sychronous read, stream also doesn't.
            if (error == null) {
                if (standardError == null) {
                    throw new InvalidOperationException(SR.GetString(SR.CantGetStandardError));
                }

                Stream s = standardError.BaseStream;
                error = new AsyncStreamReader(this, s, new UserCallBack(this.ErrorReadNotifyUser), standardError.CurrentEncoding);
            }
            error.BeginReadLine();
        }

        /// <devdoc>
        /// <para>
        /// Instructs the <see cref='System.Diagnostics.Process'/> component to cancel the asynchronous operation
        /// specified by BeginOutputReadLine().
        /// </para>
        /// </devdoc>
        [System.Runtime.InteropServices.ComVisible(false)]
        public void CancelOutputRead() {        
            if (output != null) {
                output.CancelOperation();
            }
            else {
                throw new InvalidOperationException(SR.GetString(SR.NoAsyncOperation));
            }

            pendingOutputRead = false;
        }

        /// <devdoc>
        /// <para>
        /// Instructs the <see cref='System.Diagnostics.Process'/> component to cancel the asynchronous operation
        /// specified by BeginErrorReadLine().
        /// </para>
        /// </devdoc>
        [System.Runtime.InteropServices.ComVisible(false)]        
        public void CancelErrorRead() {
            if (error != null) {
                error.CancelOperation();
            }
            else {
                throw new InvalidOperationException(SR.GetString(SR.NoAsyncOperation));
            }

            pendingErrorRead = false;
        }

        internal void OutputReadNotifyUser(String data) {
            // To avoid ---- between remove handler and raising the event
            DataReceivedEventHandler outputDataReceived = OutputDataReceived;
            if (outputDataReceived != null) {
                DataReceivedEventArgs e = new DataReceivedEventArgs(data);
                if (SynchronizingObject != null && SynchronizingObject.InvokeRequired) {
                    SynchronizingObject.Invoke(outputDataReceived, new object[] {this, e});
                }
                else {
                    outputDataReceived(this,e);  // Call back to user informing data is available.
                }
            }
        }

        internal void ErrorReadNotifyUser(String data) {
            // To avoid ---- between remove handler and raising the event
            DataReceivedEventHandler errorDataReceived = ErrorDataReceived;
            if (errorDataReceived != null) {
                DataReceivedEventArgs e = new DataReceivedEventArgs(data);
                if (SynchronizingObject != null && SynchronizingObject.InvokeRequired) {
                    SynchronizingObject.Invoke(errorDataReceived, new object[] {this, e});
                }
                else {
                    errorDataReceived(this,e); // Call back to user informing data is available.
                }
            }
        }

        /// <summary>
        ///     A desired internal state.
        /// </summary>
        /// <internalonly/>
        enum State {
            HaveId = 0x1,
            IsLocal = 0x2,
            IsNt = 0x4,
            HaveProcessInfo = 0x8,
            Exited = 0x10,
            Associated = 0x20,
            IsWin2k = 0x40,
            HaveNtProcessInfo = HaveProcessInfo | IsNt
        }
    }

    /// <devdoc>
    ///     This data structure contains information about a process that is collected
    ///     in bulk by querying the operating system.  The reason to make this a separate
    ///     structure from the process component is so that we can throw it away all at once
    ///     when Refresh is called on the component.
    /// </devdoc>
    /// <internalonly/>
    internal class ProcessInfo {
        public ArrayList threadInfoList = new ArrayList();
        public int basePriority;
        public string processName;
        public int processId;
        public int handleCount;
        public long poolPagedBytes;
        public long poolNonpagedBytes;
        public long virtualBytes;
        public long virtualBytesPeak;
        public long workingSetPeak;
        public long workingSet;
        public long pageFileBytesPeak;
        public long pageFileBytes;
        public long privateBytes;
        public int mainModuleId; // used only for win9x - id is only for use with CreateToolHelp32
        public int sessionId; 
    }

    /// <devdoc>
    ///     This data structure contains information about a thread in a process that
    ///     is collected in bulk by querying the operating system.  The reason to
    ///     make this a separate structure from the ProcessThread component is so that we
    ///     can throw it away all at once when Refresh is called on the component.
    /// </devdoc>
    /// <internalonly/>
    internal class ThreadInfo {
        public int threadId;
        public int processId;
        public int basePriority;
        public int currentPriority;
        public IntPtr startAddress;
        public ThreadState threadState;
#if !FEATURE_PAL        
        public ThreadWaitReason threadWaitReason;
#endif // !FEATURE_PAL
    }

    /// <devdoc>
    ///     This data structure contains information about a module in a process that
    ///     is collected in bulk by querying the operating system.  The reason to
    ///     make this a separate structure from the ProcessModule component is so that we
    ///     can throw it away all at once when Refresh is called on the component.
    /// </devdoc>
    /// <internalonly/>
    internal class ModuleInfo {
        public string baseName;
        public string fileName;
        public IntPtr baseOfDll;
        public IntPtr entryPoint;
        public int sizeOfImage;
        public int Id; // used only on win9x - for matching up with ProcessInfo.mainModuleId
    }

    internal static class EnvironmentBlock {
        public static byte[] ToByteArray(StringDictionary sd, bool unicode) {
            // get the keys
            string[] keys = new string[sd.Count];
            byte[] envBlock = null;
            sd.Keys.CopyTo(keys, 0);
            
            // get the values
            string[] values = new string[sd.Count];
            sd.Values.CopyTo(values, 0);
            
            // sort both by the keys
            // Windows 2000 requires the environment block to be sorted by the key
            // It will first converting the case the strings and do ordinal comparison.
            Array.Sort(keys, values, OrdinalCaseInsensitiveComparer.Default);

            // create a list of null terminated "key=val" strings
            StringBuilder stringBuff = new StringBuilder();
            for (int i = 0; i < sd.Count; ++ i) {
                stringBuff.Append(keys[i]);
                stringBuff.Append('=');
                stringBuff.Append(values[i]);
                stringBuff.Append('\0');
            }
            // an extra null at the end indicates end of list.
            stringBuff.Append('\0');
                        
            if( unicode) {
                envBlock = Encoding.Unicode.GetBytes(stringBuff.ToString());                        
            }
            else {
                envBlock = Encoding.Default.GetBytes(stringBuff.ToString());

                if (envBlock.Length > UInt16.MaxValue)
                    throw new InvalidOperationException(SR.GetString(SR.EnvironmentBlockTooLong, envBlock.Length));
            }

            return envBlock;
        }        
    }

    internal class OrdinalCaseInsensitiveComparer : IComparer {
        internal static readonly OrdinalCaseInsensitiveComparer Default = new OrdinalCaseInsensitiveComparer();
        
        public int Compare(Object a, Object b) {
            String sa = a as String;
            String sb = b as String;
            if (sa != null && sb != null) {
                return String.Compare(sa, sb, StringComparison.OrdinalIgnoreCase); 
            }
            return Comparer.Default.Compare(a,b);
        }
    }

    internal class ProcessThreadTimes {
        internal long create;
        internal long exit; 
        internal long kernel; 
        internal long user;

        public DateTime StartTime {   
            get {             
                return DateTime.FromFileTime(create);
            }
        }

        public DateTime ExitTime {
            get {
                return DateTime.FromFileTime(exit);
            }
        }

        public TimeSpan PrivilegedProcessorTime {
            get {
                return new TimeSpan(kernel);
            }
        }

        public TimeSpan UserProcessorTime {
            get {
                return new TimeSpan(user);
            }
        }
        
        public TimeSpan TotalProcessorTime {
            get {
                return new TimeSpan(user + kernel);
            }
        }
    }

    internal class ShellExecuteHelper {
        private NativeMethods.ShellExecuteInfo _executeInfo;
        private int _errorCode;
        private bool _succeeded;
        
        public ShellExecuteHelper(NativeMethods.ShellExecuteInfo executeInfo) {
            _executeInfo = executeInfo;            
        }

        [ResourceExposure(ResourceScope.None)]
        [ResourceConsumption(ResourceScope.Machine, ResourceScope.Machine)]
        public void ShellExecuteFunction()    {
            if (!(_succeeded = NativeMethods.ShellExecuteEx(_executeInfo))) {
                _errorCode = Marshal.GetLastWin32Error();
            }
        }

        public bool ShellExecuteOnSTAThread() {
            //
            // SHELL API ShellExecute() requires STA in order to work correctly.
            // If current thread is not a STA thread, we need to call ShellExecute on a new thread.
            //
            if( Thread.CurrentThread.GetApartmentState() != ApartmentState.STA) {
                ThreadStart threadStart = new ThreadStart(this.ShellExecuteFunction);
                Thread executionThread = new Thread(threadStart);
                executionThread.SetApartmentState(ApartmentState.STA);    
                executionThread.Start();
                executionThread.Join();
            }    
            else {
                ShellExecuteFunction();
            }
            return _succeeded;
        }        

        public int ErrorCode {
            get { 
                return _errorCode; 
            }
        }
    }
}