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

w32process-unix.c « metadata « mono - github.com/mono/mono.git - Unnamed repository; edit this file 'description' to name the repository.
summaryrefslogtreecommitdiff
blob: 892e9c07447aea140da98d9a09add758e02947d7 (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
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
/**
 * \file
 * System.Diagnostics.Process support
 *
 * Author:
 *	Dick Porter (dick@ximian.com)
 *
 * Copyright 2002 Ximian, Inc.
 * Copyright 2002-2006 Novell, Inc.
 * Licensed under the MIT license. See LICENSE file in the project root for full license information.
 */

#include <config.h>
#include <glib.h>

#include <stdio.h>
#include <string.h>
#include <pthread.h>
#include <sched.h>
#include <sys/time.h>
#include <errno.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include <signal.h>
#include <sys/time.h>
#include <fcntl.h>
#ifdef HAVE_SYS_PARAM_H
#include <sys/param.h>
#endif
#include <ctype.h>

#ifdef HAVE_SYS_WAIT_H
#include <sys/wait.h>
#endif
#ifdef HAVE_SYS_RESOURCE_H
#include <sys/resource.h>
#endif

#ifdef HAVE_SYS_MKDEV_H
#include <sys/mkdev.h>
#endif

#ifdef HAVE_UTIME_H
#include <utime.h>
#endif

#if defined (HAVE_FORK) && defined (HAVE_EXECVE)
// For close_my_fds
#if defined (_AIX)
#include <procinfo.h>
#elif defined (__FreeBSD__)
#include <sys/sysctl.h>
#include <sys/user.h>
#include <libutil.h>
#elif defined(__linux__)
#include <dirent.h>
#endif
#endif

#include <mono/metadata/object-internals.h>
#include <mono/metadata/w32process.h>
#include <mono/metadata/w32process-internals.h>
#include <mono/metadata/w32process-unix-internals.h>
#include <mono/metadata/w32error.h>
#include <mono/metadata/class.h>
#include <mono/metadata/class-internals.h>
#include <mono/metadata/object.h>
#include <mono/metadata/metadata.h>
#include <mono/metadata/metadata-internals.h>
#include <mono/metadata/exception.h>
#include <mono/metadata/w32handle.h>
#include <mono/metadata/w32file.h>
#include <mono/utils/mono-membar.h>
#include <mono/utils/mono-logger-internals.h>
#include <mono/utils/strenc-internals.h>
#include <mono/utils/strenc.h>
#include <mono/utils/mono-proclib.h>
#include <mono/utils/mono-path.h>
#include <mono/utils/mono-lazy-init.h>
#include <mono/utils/mono-signal-handler.h>
#include <mono/utils/mono-time.h>
#include <mono/utils/mono-mmap.h>
#include <mono/utils/strenc.h>
#include <mono/utils/mono-io-portability.h>
#include <mono/utils/w32api.h>
#include <mono/utils/mono-errno.h>
#include <mono/utils/mono-once.h>
#include <mono/utils/mono-error-internals.h>
#include <mono/utils/mono-threads-coop.h>
#include "object-internals.h"
#include "icall-decl.h"

#if !defined(DISABLE_PROCESSES)

#ifndef MAXPATHLEN
#define MAXPATHLEN 242
#endif

#define STILL_ACTIVE ((int) 0x00000103)

#define LOGDEBUG(...)
/* define LOGDEBUG(...) g_message(__VA_ARGS__)  */

/* The process' environment strings */
#if defined (HAVE_FORK) && defined (HAVE_EXECVE)
#if defined(__APPLE__)
#if defined (TARGET_OSX)
/* Apple defines this in crt_externs.h but doesn't provide that header for 
 * arm-apple-darwin9.  We'll manually define the symbol on Apple as it does
 * in fact exist on all implementations (so far) 
 */
G_BEGIN_DECLS
gchar ***_NSGetEnviron(void);
G_END_DECLS
#define environ (*_NSGetEnviron())
#else
static char *mono_environ[1] = { NULL };
#define environ mono_environ
#endif /* defined (TARGET_OSX) */
#else
G_BEGIN_DECLS
extern char **environ;
G_END_DECLS
#endif
#endif

typedef enum {
	STARTF_USESHOWWINDOW=0x001,
	STARTF_USESIZE=0x002,
	STARTF_USEPOSITION=0x004,
	STARTF_USECOUNTCHARS=0x008,
	STARTF_USEFILLATTRIBUTE=0x010,
	STARTF_RUNFULLSCREEN=0x020,
	STARTF_FORCEONFEEDBACK=0x040,
	STARTF_FORCEOFFFEEDBACK=0x080,
	STARTF_USESTDHANDLES=0x100
} StartupFlags;

typedef struct {
	gpointer input;
	gpointer output;
	gpointer error;
} StartupHandles;

typedef struct {
#if G_BYTE_ORDER == G_BIG_ENDIAN
	guint32 highDateTime;
	guint32 lowDateTime;
#else
	guint32 lowDateTime;
	guint32 highDateTime;
#endif
} ProcessTime;

/*
 * Process describes processes we create.
 * It contains a semaphore that can be waited on in order to wait
 * for process termination.
 */
typedef struct _Process {
	pid_t pid; /* the pid of the process. This value is only valid until the process has exited. */
	MonoCoopSem exit_sem; /* this semaphore will be released when the process exits */
	int status; /* the exit status */
	gint32 handle_count; /* the number of handles to this process instance */
	/* we keep a ref to the creating _WapiHandle_process handle until
	 * the process has exited, so that the information there isn't lost.
	 */
	gpointer handle;
	gboolean signalled;
	struct _Process *next;
} Process;

/* MonoW32HandleProcess is a structure containing all the required information for process handling. */
typedef struct {
	pid_t pid;
	gboolean child;
	guint32 exitstatus;
	gpointer main_thread;
	guint64 create_time;
	guint64 exit_time;
	char *pname;
	size_t min_working_set;
	size_t max_working_set;
	gboolean exited;
	Process *process;
} MonoW32HandleProcess;

/*
 * VS_VERSIONINFO:
 *
 * 2 bytes: Length in bytes (this block, and all child blocks. does _not_ include alignment padding between blocks)
 * 2 bytes: Length in bytes of VS_FIXEDFILEINFO struct
 * 2 bytes: Type (contains 1 if version resource contains text data and 0 if version resource contains binary data)
 * Variable length unicode string (null terminated): Key (currently "VS_VERSION_INFO")
 * Variable length padding to align VS_FIXEDFILEINFO on a 32-bit boundary
 * VS_FIXEDFILEINFO struct
 * Variable length padding to align Child struct on a 32-bit boundary
 * Child struct (zero or one StringFileInfo structs, zero or one VarFileInfo structs)
 */

/*
 * StringFileInfo:
 *
 * 2 bytes: Length in bytes (includes this block, as well as all Child blocks)
 * 2 bytes: Value length (always zero)
 * 2 bytes: Type (contains 1 if version resource contains text data and 0 if version resource contains binary data)
 * Variable length unicode string: Key (currently "StringFileInfo")
 * Variable length padding to align Child struct on a 32-bit boundary
 * Child structs ( one or more StringTable structs.  Each StringTable struct's Key member indicates the appropriate language and code page for displaying the text in that StringTable struct.)
 */

/*
 * StringTable:
 *
 * 2 bytes: Length in bytes (includes this block as well as all Child blocks, but excludes any padding between String blocks)
 * 2 bytes: Value length (always zero)
 * 2 bytes: Type (contains 1 if version resource contains text data and 0 if version resource contains binary data)
 * Variable length unicode string: Key. An 8-digit hex number stored as a unicode string.  The four most significant digits represent the language identifier.  The four least significant digits represent the code page for which the data is formatted.
 * Variable length padding to align Child struct on a 32-bit boundary
 * Child structs (an array of one or more String structs (each aligned on a 32-bit boundary)
 */

/*
 * String:
 *
 * 2 bytes: Length in bytes (of this block)
 * 2 bytes: Value length (the length in words of the Value member)
 * 2 bytes: Type (contains 1 if version resource contains text data and 0 if version resource contains binary data)
 * Variable length unicode string: Key. arbitrary string, identifies data.
 * Variable length padding to align Value on a 32-bit boundary
 * Value: Variable length unicode string, holding data.
 */

/*
 * VarFileInfo:
 *
 * 2 bytes: Length in bytes (includes this block, as well as all Child blocks)
 * 2 bytes: Value length (always zero)
 * 2 bytes: Type (contains 1 if version resource contains text data and 0 if version resource contains binary data)
 * Variable length unicode string: Key (currently "VarFileInfo")
 * Variable length padding to align Child struct on a 32-bit boundary
 * Child structs (a Var struct)
 */

/*
 * Var:
 *
 * 2 bytes: Length in bytes of this block
 * 2 bytes: Value length in bytes of the Value
 * 2 bytes: Type (contains 1 if version resource contains text data and 0 if version resource contains binary data)
 * Variable length unicode string: Key ("Translation")
 * Variable length padding to align Value on a 32-bit boundary
 * Value: an array of one or more 4 byte values that are language and code page identifier pairs, low-order word containing a language identifier, and the high-order word containing a code page number.  Either word can be zero, indicating that the file is language or code page independent.
 */

#if G_BYTE_ORDER == G_BIG_ENDIAN
#define VS_FFI_SIGNATURE	0xbd04effe
#define VS_FFI_STRUCVERSION	0x00000100
#else
#define VS_FFI_SIGNATURE	0xfeef04bd
#define VS_FFI_STRUCVERSION	0x00010000
#endif

#define VOS_UNKNOWN		0x00000000
#define VOS_DOS			0x00010000
#define VOS_OS216		0x00020000
#define VOS_OS232		0x00030000
#define VOS_NT			0x00040000
#define VOS__BASE		0x00000000
#define VOS__WINDOWS16		0x00000001
#define VOS__PM16		0x00000002
#define VOS__PM32		0x00000003
#define VOS__WINDOWS32		0x00000004
/* Should "embrace and extend" here with some entries for linux etc */

#define VOS_DOS_WINDOWS16	0x00010001
#define VOS_DOS_WINDOWS32	0x00010004
#define VOS_OS216_PM16		0x00020002
#define VOS_OS232_PM32		0x00030003
#define VOS_NT_WINDOWS32	0x00040004

#define VFT_UNKNOWN		0x0000
#define VFT_APP			0x0001
#define VFT_DLL			0x0002
#define VFT_DRV			0x0003
#define VFT_FONT		0x0004
#define VFT_VXD			0x0005
#define VFT_STATIC_LIB		0x0007

#define VFT2_UNKNOWN		0x0000
#define VFT2_DRV_PRINTER	0x0001
#define VFT2_DRV_KEYBOARD	0x0002
#define VFT2_DRV_LANGUAGE	0x0003
#define VFT2_DRV_DISPLAY	0x0004
#define VFT2_DRV_MOUSE		0x0005
#define VFT2_DRV_NETWORK	0x0006
#define VFT2_DRV_SYSTEM		0x0007
#define VFT2_DRV_INSTALLABLE	0x0008
#define VFT2_DRV_SOUND		0x0009
#define VFT2_DRV_COMM		0x000a
#define VFT2_DRV_INPUTMETHOD	0x000b
#define VFT2_FONT_RASTER	0x0001
#define VFT2_FONT_VECTOR	0x0002
#define VFT2_FONT_TRUETYPE	0x0003

#define MAKELANGID(primary,secondary) ((guint16)((secondary << 10) | (primary)))

#define ALIGN32(ptr) ptr = (gpointer)((char *)ptr + 3); ptr = (gpointer)((char *)ptr - ((gsize)ptr & 3));

#if HAVE_SIGACTION
static mono_lazy_init_t process_sig_chld_once = MONO_LAZY_INIT_STATUS_NOT_INITIALIZED;
#endif

static gchar *cli_launcher;

static Process *processes;
static MonoCoopMutex processes_mutex;

static pid_t current_pid;
static gpointer current_process;

static const gunichar2 utf16_space [2] = { 0x20, 0 };
static const gunichar2 utf16_quote [2] = { 0x22, 0 };

static MonoBoolean
mono_get_exit_code_process (gpointer handle, gint32 *exitcode);

/* Check if a pid is valid - i.e. if a process exists with this pid. */
static gboolean
process_is_alive (pid_t pid)
{
#if defined(HOST_WATCHOS)
	return TRUE; // TODO: Rewrite using sysctl
#elif defined(HOST_DARWIN) || defined(__OpenBSD__) || defined(__FreeBSD__) || defined(_AIX)
	if (pid == 0)
		return FALSE;
	if (kill (pid, 0) == 0)
		return TRUE;
	if (errno == EPERM)
		return TRUE;
	return FALSE;
#elif defined(__HAIKU__)
	team_info teamInfo;
	if (get_team_info ((team_id)pid, &teamInfo) == B_OK)
		return TRUE;
	return FALSE;
#else
	gchar *dir = g_strdup_printf ("/proc/%d", pid);
	gboolean result = access (dir, F_OK) == 0;
	g_free (dir);
	return result;
#endif
}

static void
process_details (MonoW32Handle *handle_data)
{
	MonoW32HandleProcess *process_handle = (MonoW32HandleProcess *) handle_data->specific;
	g_print ("pid: %d, exited: %s, exitstatus: %d",
		process_handle->pid, process_handle->exited ? "true" : "false", process_handle->exitstatus);
}

static const gchar*
process_typename (void)
{
	return "Process";
}

static gsize
process_typesize (void)
{
	return sizeof (MonoW32HandleProcess);
}

static MonoW32HandleWaitRet
process_wait (MonoW32Handle *handle_data, guint32 timeout, gboolean *alerted)
{
	MonoW32HandleProcess *process_handle;
	pid_t pid G_GNUC_UNUSED, ret;
	int status;
	gint64 start, now;
	Process *process;

	mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER_PROCESS, "%s (%p, %" G_GUINT32_FORMAT ")", __func__, handle_data, timeout);

	if (alerted)
		*alerted = FALSE;

	process_handle = (MonoW32HandleProcess*) handle_data->specific;

	if (process_handle->exited) {
		/* We've already done this one */
		mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER_PROCESS, "%s (%p, %" G_GUINT32_FORMAT "): Process already exited", __func__, handle_data, timeout);
		return MONO_W32HANDLE_WAIT_RET_SUCCESS_0;
	}

	pid = process_handle->pid;

	if (pid == mono_process_current_pid ()) {
		mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER_PROCESS, "%s (%p, %" G_GUINT32_FORMAT "): waiting on current process", __func__, handle_data, timeout);
		return MONO_W32HANDLE_WAIT_RET_TIMEOUT;
	}

	mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER_PROCESS, "%s (%p, %" G_GUINT32_FORMAT "): PID: %d", __func__, handle_data, timeout, pid);

	if (!process_handle->child) {
		mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER_PROCESS, "%s (%p, %" G_GUINT32_FORMAT "): waiting on non-child process", __func__, handle_data, timeout);

		if (!process_is_alive (pid)) {
			/* assume the process has exited */
			process_handle->exited = TRUE;
			process_handle->exitstatus = -1;
			mono_w32handle_set_signal_state (handle_data, TRUE, TRUE);

			mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER_PROCESS, "%s (%p, %" G_GUINT32_FORMAT "): non-child process is not alive anymore (2)", __func__, handle_data, timeout);
			return MONO_W32HANDLE_WAIT_RET_SUCCESS_0;
		}

		mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER_PROCESS, "%s (%p, %" G_GUINT32_FORMAT "): non-child process wait failed, error : %s (%d))", __func__, handle_data, timeout, g_strerror (errno), errno);
		return MONO_W32HANDLE_WAIT_RET_FAILED;
	}

	/* We don't need to lock processes here, the entry
	 * has a handle_count > 0 which means it will not be freed. */
	process = process_handle->process;
	g_assert (process);

	start = mono_msec_ticks ();
	now = start;

	while (1) {
		if (timeout != MONO_INFINITE_WAIT) {
			mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER_PROCESS, "%s (%p, %" G_GUINT32_FORMAT "): waiting on semaphore for %" G_GINT64_FORMAT " ms...",
				__func__, handle_data, timeout, timeout - (now - start));
			ret = mono_coop_sem_timedwait (&process->exit_sem, (timeout - (now - start)), alerted ? MONO_SEM_FLAGS_ALERTABLE : MONO_SEM_FLAGS_NONE);
		} else {
			mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER_PROCESS, "%s (%p, %" G_GUINT32_FORMAT "): waiting on semaphore forever...",
				__func__, handle_data, timeout);
			ret = mono_coop_sem_wait (&process->exit_sem, alerted ? MONO_SEM_FLAGS_ALERTABLE : MONO_SEM_FLAGS_NONE);
		}

		if (ret == MONO_SEM_TIMEDWAIT_RET_SUCCESS) {
			/* Success, process has exited */
			mono_coop_sem_post (&process->exit_sem);
			break;
		}

		if (ret == MONO_SEM_TIMEDWAIT_RET_TIMEDOUT) {
			mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER_PROCESS, "%s (%p, %" G_GUINT32_FORMAT "): wait timeout (timeout = 0)", __func__, handle_data, timeout);
			return MONO_W32HANDLE_WAIT_RET_TIMEOUT;
		}

		now = mono_msec_ticks ();
		if (now - start >= timeout) {
			mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER_PROCESS, "%s (%p, %" G_GUINT32_FORMAT "): wait timeout", __func__, handle_data, timeout);
			return MONO_W32HANDLE_WAIT_RET_TIMEOUT;
		}

		if (alerted && ret == MONO_SEM_TIMEDWAIT_RET_ALERTED) {
			mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER_PROCESS, "%s (%p, %" G_GUINT32_FORMAT "): wait alerted", __func__, handle_data, timeout);
			*alerted = TRUE;
			return MONO_W32HANDLE_WAIT_RET_ALERTED;
		}
	}

	/* Process must have exited */
	mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER_PROCESS, "%s (%p, %" G_GUINT32_FORMAT "): Waited successfully", __func__, handle_data, timeout);

	status = process->status;
	if (WIFSIGNALED (status))
		process_handle->exitstatus = 128 + WTERMSIG (status);
	else
		process_handle->exitstatus = WEXITSTATUS (status);

	process_handle->exit_time = mono_100ns_datetime ();

	process_handle->exited = TRUE;

	mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER_PROCESS, "%s (%p, %" G_GUINT32_FORMAT "): Setting pid %d signalled, exit status %d",
		   __func__, handle_data, timeout, process_handle->pid, process_handle->exitstatus);

	mono_w32handle_set_signal_state (handle_data, TRUE, TRUE);

	return MONO_W32HANDLE_WAIT_RET_SUCCESS_0;
}

static void
processes_cleanup (void)
{
	static gint32 cleaning_up;
	Process *process;
	Process *prev = NULL;

	mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER_PROCESS, "%s", __func__);

	/* Ensure we're not in here in multiple threads at once, nor recursive. */
	if (mono_atomic_cas_i32 (&cleaning_up, 1, 0) != 0)
		return;

	/*
	 * This needs to be done outside the lock but atomically, hence the CAS above.
	 */
	for (process = processes; process; process = process->next) {
		if (process->signalled && process->handle) {
			/* This process has exited and we need to remove the artifical ref
			 * on the handle */
			mono_w32handle_close (process->handle);
			process->handle = NULL;
		}
	}

	mono_coop_mutex_lock (&processes_mutex);

	for (process = processes; process;) {
		Process *next = process->next;
		if (process->handle_count == 0 && process->signalled) {
			/*
			 * Unlink the entry.
			 */
			if (process == processes)
				processes = process->next;
			else
				prev->next = process->next;

			mono_coop_sem_destroy (&process->exit_sem);
			g_free (process);
		} else {
			prev = process;
		}
		process = next;
	}

	mono_coop_mutex_unlock (&processes_mutex);

	mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER_PROCESS, "%s done", __func__);

	mono_atomic_xchg_i32 (&cleaning_up, 0);
}

static void
process_close (gpointer data)
{
	MonoW32HandleProcess *process_handle;

	mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER_PROCESS, "%s", __func__);

	process_handle = (MonoW32HandleProcess *) data;
	g_free (process_handle->pname);
	process_handle->pname = NULL;
	if (process_handle->process)
		mono_atomic_dec_i32 (&process_handle->process->handle_count);
	processes_cleanup ();
}

static const MonoW32HandleOps process_ops = {
	process_close,		/* close_shared */
	NULL,				/* signal */
	NULL,				/* own */
	NULL,				/* is_owned */
	process_wait,			/* special_wait */
	NULL,				/* prewait */
	process_details,	/* details */
	process_typename,	/* typename */
	process_typesize,	/* typesize */
};

static void
process_set_defaults (MonoW32HandleProcess *process_handle)
{
	/* These seem to be the defaults on w2k */
	process_handle->min_working_set = 204800;
	process_handle->max_working_set = 1413120;

	process_handle->create_time = mono_100ns_datetime ();
}

static void
process_set_name (MonoW32HandleProcess *process_handle)
{
	char *progname, *utf8_progname, *slash;

	progname = g_get_prgname ();
	utf8_progname = mono_utf8_from_external (progname);

	mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER_PROCESS, "%s: using [%s] as prog name", __func__, progname);

	if (utf8_progname) {
		slash = strrchr (utf8_progname, '/');
		if (slash)
			process_handle->pname = g_strdup (slash+1);
		else
			process_handle->pname = g_strdup (utf8_progname);
		g_free (utf8_progname);
	}
}

static mono_once_t init_state = MONO_ONCE_INIT;

void
mono_w32process_init (void)
{
	MonoW32HandleProcess process_handle;

	mono_w32handle_register_ops (MONO_W32TYPE_PROCESS, &process_ops);

	mono_w32handle_register_capabilities (MONO_W32TYPE_PROCESS,
		(MonoW32HandleCapability)(MONO_W32HANDLE_CAP_WAIT | MONO_W32HANDLE_CAP_SPECIAL_WAIT));

	current_pid = getpid ();

	memset (&process_handle, 0, sizeof (process_handle));
	process_handle.pid = current_pid;
	process_set_defaults (&process_handle);
	process_set_name (&process_handle);

	current_process = mono_w32handle_new (MONO_W32TYPE_PROCESS, &process_handle);
	g_assert (current_process != INVALID_HANDLE_VALUE);

	mono_coop_mutex_init (&processes_mutex);
	mono_once (&init_state, &mono_w32process_platform_init_once);
}

void
mono_w32process_cleanup (void)
{
	g_free (cli_launcher);
}

static int
len16 (const gunichar2 *str)
{
	int len = 0;

	while (*str++ != 0)
		len++;

	return len;
}

static gunichar2 *
utf16_concat (const gunichar2 *first, ...)
{
	va_list args;
	int total = 0, i;
	const gunichar2 *s;
	const gunichar2 *p;
	gunichar2 *ret;

	va_start (args, first);
	total += len16 (first);
	for (s = va_arg (args, gunichar2 *); s != NULL; s = va_arg(args, gunichar2 *))
		total += len16 (s);
	va_end (args);

	ret = g_new (gunichar2, total + 1);
	if (ret == NULL)
		return NULL;

	ret [total] = 0;
	i = 0;
	for (s = first; *s != 0; s++)
		ret [i++] = *s;
	va_start (args, first);
	for (s = va_arg (args, gunichar2 *); s != NULL; s = va_arg (args, gunichar2 *)){
		for (p = s; *p != 0; p++)
			ret [i++] = *p;
	}
	va_end (args);

	return ret;
}

guint32
mono_w32process_get_pid (gpointer handle)
{
	MonoW32Handle *handle_data;
	guint32 ret;

	if (!mono_w32handle_lookup_and_ref (handle, &handle_data)) {
		mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER_PROCESS, "%s: unknown handle %p", __func__, handle);
		mono_w32error_set_last (ERROR_INVALID_HANDLE);
		return 0;
	}

	if (handle_data->type != MONO_W32TYPE_PROCESS) {
		mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER_PROCESS, "%s: unknown process handle %p", __func__, handle);
		mono_w32error_set_last (ERROR_INVALID_HANDLE);
		mono_w32handle_unref (handle_data);
		return 0;
	}

	ret = ((MonoW32HandleProcess*) handle_data->specific)->pid;

	mono_w32handle_unref (handle_data);

	return ret;
}

typedef struct {
	guint32 pid;
	gpointer handle;
} GetProcessForeachData;

static gboolean
get_process_foreach_callback (MonoW32Handle *handle_data, gpointer user_data)
{
	GetProcessForeachData *foreach_data;
	MonoW32HandleProcess *process_handle;
	pid_t pid;

	if (handle_data->type != MONO_W32TYPE_PROCESS)
		return FALSE;

	process_handle = (MonoW32HandleProcess*) handle_data->specific;

	mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER_PROCESS, "%s: looking at process %d", __func__, process_handle->pid);

	pid = process_handle->pid;
	if (pid == 0)
		return FALSE;

	foreach_data = (GetProcessForeachData*) user_data;

	/* It's possible to have more than one process handle with the
	 * same pid, but only the one running process can be
	 * unsignalled. */
	if (foreach_data->pid != pid)
		return FALSE;
	if (mono_w32handle_issignalled (handle_data))
		return FALSE;

	foreach_data->handle = mono_w32handle_duplicate (handle_data);
	return TRUE;
}

HANDLE
ves_icall_System_Diagnostics_Process_GetProcess_internal (guint32 pid, MonoError *error)
{
	GetProcessForeachData foreach_data;
	gpointer handle;

	mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER_PROCESS, "%s: looking for process %d", __func__, pid);

	memset (&foreach_data, 0, sizeof (foreach_data));
	foreach_data.pid = pid;
	mono_w32handle_foreach (get_process_foreach_callback, &foreach_data);
	handle = foreach_data.handle;
	if (handle) {
		/* get_process_foreach_callback already added a ref */
		return handle;
	}

	if (process_is_alive (pid)) {
		/* non-child process */
		MonoW32HandleProcess process_handle;

		memset (&process_handle, 0, sizeof (process_handle));
		process_handle.pid = pid;
		process_handle.pname = mono_w32process_get_name (pid);

		handle = mono_w32handle_new (MONO_W32TYPE_PROCESS, &process_handle);
		if (handle == INVALID_HANDLE_VALUE) {
			g_warning ("%s: error creating process handle", __func__);

			mono_w32error_set_last (ERROR_OUTOFMEMORY);
			return NULL;
		}

		return handle;
	}

	mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER_PROCESS, "%s: Can't find pid %d", __func__, pid);

	mono_w32error_set_last (ERROR_PROC_NOT_FOUND);
	return NULL;
}

HANDLE
ves_icall_System_Diagnostics_Process_MainWindowHandle_internal (guint32 pid, MonoError *error)
{
	/*TODO: Implement for unix*/
	return NULL;
}

static gboolean
match_procname_to_modulename (char *procname, char *modulename)
{
	char* lastsep = NULL;
	char* lastsep2 = NULL;
	char* pname = NULL;
	char* mname = NULL;
	gboolean result = FALSE;

	if (procname == NULL || modulename == NULL)
		return (FALSE);

	mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER_PROCESS, "%s: procname=\"%s\", modulename=\"%s\"", __func__, procname, modulename);
	pname = mono_path_resolve_symlinks (procname);
	mname = mono_path_resolve_symlinks (modulename);

	if (!strcmp (pname, mname))
		result = TRUE;

	if (!result) {
		lastsep = strrchr (mname, '/');
		if (lastsep)
			if (!strcmp (lastsep+1, pname))
				result = TRUE;
		if (!result) {
			lastsep2 = strrchr (pname, '/');
			if (lastsep2){
				if (lastsep) {
					if (!strcmp (lastsep+1, lastsep2+1))
						result = TRUE;
				} else {
					if (!strcmp (mname, lastsep2+1))
						result = TRUE;
				}
			}
		}
	}

	g_free (pname);
	g_free (mname);

	mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER_PROCESS, "%s: result is %" G_GINT32_FORMAT, __func__, result);
	return result;
}

gboolean
mono_w32process_try_get_modules (gpointer handle, gpointer *modules, guint32 size, guint32 *needed)
{
	MonoW32Handle *handle_data;
	MonoW32HandleProcess *process_handle;
	GSList *mods = NULL, *mods_iter;
	MonoW32ProcessModule *module;
	guint32 count, avail = size / sizeof(gpointer);
	int i;
	pid_t pid;
	char *pname = NULL;

	/* Store modules in an array of pointers (main module as
	 * modules[0]), using the load address for each module as a
	 * token.  (Use 'NULL' as an alternative for the main module
	 * so that the simple implementation can just return one item
	 * for now.)  Get the info from /proc/<pid>/maps on linux,
	 * /proc/<pid>/map on FreeBSD, other systems will have to
	 * implement /dev/kmem reading or whatever other horrid
	 * technique is needed.
	 */
	if (size < sizeof(gpointer))
		return FALSE;

	if (!mono_w32handle_lookup_and_ref (handle, &handle_data)) {
		mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER_PROCESS, "%s: unknown handle %p", __func__, handle);
		mono_w32error_set_last (ERROR_INVALID_HANDLE);
		return FALSE;
	}

	if (handle_data->type != MONO_W32TYPE_PROCESS) {
		mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER_PROCESS, "%s: unknown process handle %p", __func__, handle);
		mono_w32error_set_last (ERROR_INVALID_HANDLE);
		mono_w32handle_unref (handle_data);
		return FALSE;
	}

	process_handle = (MonoW32HandleProcess*) handle_data->specific;

	pid = process_handle->pid;
	pname = g_strdup (process_handle->pname);

	if (!pname) {
		modules[0] = NULL;
		*needed = sizeof(gpointer);
		mono_w32handle_unref (handle_data);
		return TRUE;
	}

	mods = mono_w32process_get_modules (pid);
	if (!mods) {
		modules[0] = NULL;
		*needed = sizeof(gpointer);
		g_free (pname);
		mono_w32handle_unref (handle_data);
		return TRUE;
	}

	count = 0;

	/*
	 * Use the NULL shortcut, as the first line in
	 * /proc/<pid>/maps isn't the executable, and we need
	 * that first in the returned list. Check the module name
	 * to see if it ends with the proc name and substitute
	 * the first entry with it.  FIXME if this turns out to
	 * be a problem.
	 */
	modules[0] = NULL;
	mods_iter = mods;
	for (i = 0; mods_iter; i++) {
		if (i < avail - 1) {
			module = (MonoW32ProcessModule *)mods_iter->data;
			if (modules[0] != NULL)
				modules[i] = module->address_start;
			else if (match_procname_to_modulename (pname, module->filename))
				modules[0] = module->address_start;
			else
				modules[i + 1] = module->address_start;
		}
		mono_w32process_module_free ((MonoW32ProcessModule *)mods_iter->data);
		mods_iter = g_slist_next (mods_iter);
		count++;
	}

	/* count + 1 to leave slot 0 for the main module */
	*needed = sizeof(gpointer) * (count + 1);

	g_slist_free (mods);
	g_free (pname);
	mono_w32handle_unref (handle_data);
	return TRUE;
}

gboolean
mono_w32process_module_get_filename (gpointer handle, gpointer module, gunichar2 **str, guint32 *len)
{
	gint pid;
	gsize bytes = 0;
	gchar *path;
	gunichar2 *proc_path;

	mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER_PROCESS, "%s: Getting module file name, process handle %p module %p " G_GUINT32_FORMAT,
	            __func__, handle, module);

	if (str == NULL || len == NULL)
		return FALSE;

	*str = NULL;
	*len = 0;

	pid = mono_w32process_get_pid (handle);
	if (pid == 0)
		return FALSE;

	path = mono_w32process_get_path (pid);
	if (path == NULL)
		return FALSE;

	proc_path = mono_unicode_from_external (path, &bytes);

	if (proc_path == NULL) {
		g_free (path);
		return FALSE;
	}

	*str = mono_unicode_from_external (path, &bytes);
	*len = bytes / sizeof (gunichar2);

	g_free (path);
	return TRUE;
}

gboolean
mono_w32process_module_get_name (gpointer handle, gpointer module, gunichar2 **str, guint32 *len)
{
	MonoW32Handle *handle_data;
	MonoW32HandleProcess *process_handle;
	pid_t pid;
	gunichar2 *procname;
	char *procname_ext = NULL;
	gsize bytes = 0;
	GSList *mods = NULL, *mods_iter;
	MonoW32ProcessModule *found_module;
	char *pname = NULL;

	mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER_PROCESS, "%s: Getting module base name, process handle %p module %p " G_GUINT32_FORMAT,
		   __func__, handle, module);

	if (str == NULL || len == NULL)
		return FALSE;

	*str = NULL;
	*len = 0;

	if (!mono_w32handle_lookup_and_ref (handle, &handle_data)) {
		mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER_PROCESS, "%s: unknown handle %p", __func__, handle);
		mono_w32error_set_last (ERROR_INVALID_HANDLE);
		return FALSE;
	}

	if (handle_data->type != MONO_W32TYPE_PROCESS) {
		mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER_PROCESS, "%s: unknown process handle %p", __func__, handle);
		mono_w32error_set_last (ERROR_INVALID_HANDLE);
		mono_w32handle_unref (handle_data);
		return FALSE;
	}

	process_handle = (MonoW32HandleProcess*) handle_data->specific;

	pid = process_handle->pid;
	pname = g_strdup (process_handle->pname);

	mods = mono_w32process_get_modules (pid);
	if (!mods && module != NULL) {
		mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER_PROCESS, "%s: Can't get modules %p", __func__, handle);
		g_free (pname);
		mono_w32handle_unref (handle_data);
		return FALSE;
	}

	/* If module != NULL compare the address.
	 * If module == NULL we are looking for the main module.
	 * The best we can do for now check it the module name end with the process name.
	 */
	for (mods_iter = mods; mods_iter; mods_iter = g_slist_next (mods_iter)) {
		found_module = (MonoW32ProcessModule *)mods_iter->data;
		if (procname_ext == NULL &&
			((module == NULL && match_procname_to_modulename (pname, found_module->filename)) ||
			 (module != NULL && found_module->address_start == module))) {
			procname_ext = g_path_get_basename (found_module->filename);
		}

		mono_w32process_module_free (found_module);
	}

	if (procname_ext == NULL) {
		mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER_PROCESS, "%s: Can't find procname_ext from procmods %p", __func__, handle);
		/* If it's *still* null, we might have hit the
		 * case where reading /proc/$pid/maps gives an
		 * empty file for this user.
		 */
		procname_ext = mono_w32process_get_name (pid);
		if (!procname_ext)
			mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER_PROCESS, "%s: Can't find procname_ext from proc_get_name %p pid %d", __func__, handle, pid);
	}

	g_slist_free (mods);
	g_free (pname);

	if (procname_ext) {
		mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER_PROCESS, "%s: Process name is [%s]", __func__,
			   procname_ext);

		procname = mono_unicode_from_external (procname_ext, &bytes);
		if (procname == NULL) {
			mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER_PROCESS, "%s: Can't get procname %p", __func__, handle);
			g_free (procname_ext);
			mono_w32handle_unref (handle_data);
			return FALSE;
		}

		*str = procname;
		*len = bytes / sizeof (gunichar2);

		g_free (procname_ext);
		mono_w32handle_unref (handle_data);
		return TRUE;
	}

	mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER_PROCESS, "%s: Can't find procname_ext %p", __func__, handle);
	mono_w32handle_unref (handle_data);
	return FALSE;
}

gboolean
mono_w32process_module_get_information (gpointer handle, gpointer module, gpointer modinfo, guint32 size)
{
	MonoW32Handle *handle_data;
	MonoW32HandleProcess *process_handle;
	pid_t pid;
	GSList *mods = NULL, *mods_iter;
	MonoW32ProcessModule *found_module;
	gboolean ret = FALSE;
	char *pname = NULL;

	mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER_PROCESS, "%s: Getting module info, process handle %p module %p",
		   __func__, handle, module);

	if (modinfo == NULL || size < sizeof (MODULEINFO))
		return FALSE;

	if (!mono_w32handle_lookup_and_ref (handle, &handle_data)) {
		mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER_PROCESS, "%s: unknown handle %p", __func__, handle);
		mono_w32error_set_last (ERROR_INVALID_HANDLE);
		return FALSE;
	}

	if (handle_data->type != MONO_W32TYPE_PROCESS) {
		mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER_PROCESS, "%s: unknown process handle %p", __func__, handle);
		mono_w32error_set_last (ERROR_INVALID_HANDLE);
		mono_w32handle_unref (handle_data);
		return FALSE;
	}

	process_handle = (MonoW32HandleProcess*) handle_data->specific;

	pid = process_handle->pid;
	pname = g_strdup (process_handle->pname);

	mods = mono_w32process_get_modules (pid);
	if (!mods) {
		g_free (pname);
		mono_w32handle_unref (handle_data);
		return FALSE;
	}

	/* If module != NULL compare the address.
	 * If module == NULL we are looking for the main module.
	 * The best we can do for now check it the module name end with the process name.
	 */
	for (mods_iter = mods; mods_iter; mods_iter = g_slist_next (mods_iter)) {
			found_module = (MonoW32ProcessModule *)mods_iter->data;
			if (ret == FALSE &&
				((module == NULL && match_procname_to_modulename (pname, found_module->filename)) ||
				 (module != NULL && found_module->address_start == module))) {
				((MODULEINFO *)modinfo)->lpBaseOfDll = found_module->address_start;
				((MODULEINFO *)modinfo)->SizeOfImage = (gsize)(found_module->address_end) - (gsize)(found_module->address_start);
				((MODULEINFO *)modinfo)->EntryPoint = found_module->address_offset;
				ret = TRUE;
			}

			mono_w32process_module_free (found_module);
	}

	g_slist_free (mods);
	g_free (pname);
	mono_w32handle_unref (handle_data);
	return ret;
}

#if HAVE_SIGACTION

MONO_SIGNAL_HANDLER_FUNC (static, mono_sigchld_signal_handler, (int _dummy, siginfo_t *info, void *context))
{
	/*
	 * Don't want to do any complicated processing here so just wake up the finalizer thread which will call
	 * mono_w32process_signal_finished ().
	 */
	int old_errno = errno;

	mono_gc_finalize_notify ();

	mono_set_errno (old_errno);
}

static void
process_add_sigchld_handler (void)
{
	struct sigaction sa;

	sa.sa_sigaction = mono_sigchld_signal_handler;
	sigemptyset (&sa.sa_mask);
	sa.sa_flags = SA_NOCLDSTOP | SA_SIGINFO | SA_RESTART;
	g_assert (sigaction (SIGCHLD, &sa, NULL) != -1);
	mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER_PROCESS, "Added SIGCHLD handler");
}

#endif

/*
 * mono_w32process_signal_finished:
 *
 *   Signal the exit semaphore for processes which have finished.
 */
void
mono_w32process_signal_finished (void)
{
	mono_coop_mutex_lock (&processes_mutex);

	for (Process* process = processes; process; process = process->next) {
		int status = -1;
		int pid;

		do {
			pid = waitpid (process->pid, &status, WNOHANG);
		} while (pid == -1 && errno == EINTR);

		// possible values of 'pid':
		//  process->pid : the status changed for this child
		//  0            : status unchanged for this PID
		//  ECHILD       : process has been reaped elsewhere (or never existed)
		//  EINVAL       : invalid PID or other argument

		// Therefore, we ignore status unchanged (nothing to do) and error
		// events (process is cleaned up later).
		if (pid <= 0)
			continue;
		if (process->signalled)
			continue;

		process->signalled = TRUE;
		process->status = status;
		mono_coop_sem_post (&process->exit_sem);
	}

	mono_coop_mutex_unlock (&processes_mutex);
}

#if defined (HAVE_FORK) && defined (HAVE_EXECVE)
static void
switch_dir_separators (char *path)
{
	size_t i, pathLength = strlen (path);

	/* Turn all the slashes round the right way, except for \' */
	/* There are probably other characters that need to be excluded as well. */
	for (i = 0; i < pathLength; i++) {
		if (path[i] == '\\' && i < pathLength - 1 && path[i + 1] != '\'')
			path[i] = '/';
	}
}

static gboolean
is_readable_or_executable (const char *prog)
{
	struct stat buf;
	int a = access (prog, R_OK);
	int b = access (prog, X_OK);
	if (a != 0 && b != 0)
		return FALSE;
	if (stat (prog, &buf))
		return FALSE;
	if (S_ISREG (buf.st_mode))
		return TRUE;
	return FALSE;
}

static gboolean
is_executable (const char *prog)
{
	struct stat buf;
	if (access (prog, X_OK) != 0)
		return FALSE;
	if (stat (prog, &buf))
		return FALSE;
	if (S_ISREG (buf.st_mode))
		return TRUE;
	return FALSE;
}

static gboolean
is_managed_binary (const char *filename)
{
	int original_errno = errno;
#if defined(HAVE_LARGE_FILE_SUPPORT) && defined(O_LARGEFILE)
	int file = open (filename, O_RDONLY | O_LARGEFILE);
#else
	int file = open (filename, O_RDONLY);
#endif
	off_t new_offset;
	unsigned char buffer[8];
	off_t file_size, optional_header_offset;
	off_t pe_header_offset, clr_header_offset;
	gboolean managed = FALSE;
	int num_read;
	guint32 first_word, second_word, magic_number;
	
	/* If we are unable to open the file, then we definitely
	 * can't say that it is managed. The child mono process
	 * probably wouldn't be able to open it anyway.
	 */
	if (file < 0) {
		mono_set_errno (original_errno);
		return FALSE;
	}

	/* Retrieve the length of the file for future sanity checks. */
	file_size = lseek (file, 0, SEEK_END);
	lseek (file, 0, SEEK_SET);

	/* We know we need to read a header field at offset 60. */
	if (file_size < 64)
		goto leave;

	num_read = read (file, buffer, 2);

	if ((num_read != 2) || (buffer[0] != 'M') || (buffer[1] != 'Z'))
		goto leave;

	new_offset = lseek (file, 60, SEEK_SET);

	if (new_offset != 60)
		goto leave;
	
	num_read = read (file, buffer, 4);

	if (num_read != 4)
		goto leave;
	pe_header_offset =  buffer[0]
		| (buffer[1] <<  8)
		| (buffer[2] << 16)
		| (buffer[3] << 24);
	
	if (pe_header_offset + 24 > file_size)
		goto leave;

	new_offset = lseek (file, pe_header_offset, SEEK_SET);

	if (new_offset != pe_header_offset)
		goto leave;

	num_read = read (file, buffer, 4);

	if ((num_read != 4) || (buffer[0] != 'P') || (buffer[1] != 'E') || (buffer[2] != 0) || (buffer[3] != 0))
		goto leave;

	/*
	 * Verify that the header we want in the optional header data
	 * is present in this binary.
	 */
	new_offset = lseek (file, pe_header_offset + 20, SEEK_SET);

	if (new_offset != pe_header_offset + 20)
		goto leave;

	num_read = read (file, buffer, 2);

	if ((num_read != 2) || ((buffer[0] | (buffer[1] << 8)) < 216))
		goto leave;

	optional_header_offset = pe_header_offset + 24;

	/* Read the PE magic number */
	new_offset = lseek (file, optional_header_offset, SEEK_SET);
	
	if (new_offset != optional_header_offset)
		goto leave;

	num_read = read (file, buffer, 2);

	if (num_read != 2)
		goto leave;

	magic_number = (buffer[0] | (buffer[1] << 8));
	
	if (magic_number == 0x10B)  // PE32
		clr_header_offset = 208;
	else if (magic_number == 0x20B)  // PE32+
		clr_header_offset = 224;
	else
		goto leave;

	/* Read the CLR header address and size fields. These will be
	 * zero if the binary is not managed.
	 */
	new_offset = lseek (file, optional_header_offset + clr_header_offset, SEEK_SET);

	if (new_offset != optional_header_offset + clr_header_offset)
		goto leave;

	num_read = read (file, buffer, 8);
	
	/* We are not concerned with endianness, only with
	 * whether it is zero or not.
	 */
	first_word = *(guint32 *)&buffer[0];
	second_word = *(guint32 *)&buffer[4];
	
	if ((num_read != 8) || (first_word == 0) || (second_word == 0))
		goto leave;
	
	managed = TRUE;

leave:
	close (file);
	mono_set_errno (original_errno);
	return managed;
}

/**
 * Gets the biggest numbered file descriptor for the current process; failing
 * that, the system's file descriptor limit. This is called by the fork child
 * in close_my_fds.
 */
static guint32
max_fd_count (void)
{
#if defined (_AIX)
	struct procentry64 pe;
	pid_t p;
	p = getpid ();
	if (getprocs64 (&pe, sizeof (pe), NULL, 0, &p, 1) != -1) {
		mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER_PROCESS,
			   "%s: maximum returned fd in child is %u",
			   __func__, pe.pi_maxofile);
		return pe.pi_maxofile; // biggest + 1
	}
#endif
	// fallback to user/system limit if unsupported/error
	return eg_getdtablesize ();
}

/**
 * Closes all of the process' opened file descriptors, applying a strategy
 * appropriate for the target system. This is called by the fork child in
 * process_create.
 */
static void
close_my_fds (void)
{
// TODO: Other platforms.
//       * On macOS, use proc_pidinfo + PROC_PIDLISTFDS? See:
//         http://blog.palominolabs.com/2012/06/19/getting-the-files-being-used-by-a-process-on-mac-os-x/
//         (I have no idea how this plays out on i/watch/tvOS.)
//       * On the other BSDs, there's likely a sysctl for this.
//       * On Solaris, there exists posix_spawn_file_actions_addclosefrom_np,
//         but that assumes we're using posix_spawn; we aren't, as we do some
//         complex stuff between fork and exec. There's likely a way to get
//         the FD list/count though (maybe look at addclosefrom source in
//         illumos?) or just walk /proc/pid/fd like Linux?
#if defined (__linux__)
	/* Walk the file descriptors in /proc/self/fd/. Linux has no other API,
	 * as far as I'm aware. Opening a directory won't create an FD. */
	struct dirent *dp;
	DIR *d;
	int fd;
	d = opendir ("/proc/self/fd/");
	if (d) {
		while ((dp = readdir (d)) != NULL) {
			if (dp->d_name [0] == '.')
				continue;
			fd = atoi (dp->d_name);
			if (fd > 2)
				close (fd);
		}
		closedir (d);
		return;
	} else {
		mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER_PROCESS,
			   "%s: opening fd dir failed, using fallback",
			   __func__);
	}
#elif defined (__FreeBSD__)
	/* FreeBSD lets us get a list of FDs. There's a MIB to access them
	 * directly, but it uses a lot of nasty variable length structures. The
	 * system library libutil provides a nicer way to get a fixed length
	 * version instead. */
	struct kinfo_file *kif;
	int count, i;
	/* this is malloced but we won't need to free once we exec/exit */
	kif = kinfo_getfile (getpid (), &count);
	if (kif) {
		for (i = 0; i < count; i++) {
			/* negative FDs look to be used by the OS */
			if (kif [i].kf_fd > 2) /* no neg + no stdio */
				close (kif [i].kf_fd);
		}
		return;
	} else {
		mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER_PROCESS,
			   "%s: kinfo_getfile failed, using fallback",
			   __func__);
	}
#elif defined (_AIX)
	struct procentry64 pe;
	/* this array struct is 1 MB, we're NOT putting it on the stack.
	 * likewise no need to free; getprocs will fail if we use the smalller
	 * versions if we have a lot of FDs (is it worth it?)
	 */
	struct fdsinfo_100K *fds;
	pid_t p;
	p = getpid ();
	fds = (struct fdsinfo_100K *) g_malloc0 (sizeof (struct fdsinfo_100K));
	if (!fds) {
		mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER_PROCESS,
			   "%s: fdsinfo alloc failed, using fallback",
			   __func__);
		goto fallback;
	}

	if (getprocs64 (&pe, sizeof (pe), fds, sizeof (struct fdsinfo_100K), &p, 1) != -1) {
		for (int i = 3; i < pe.pi_maxofile; i++) {
			if (fds->pi_ufd [i].fp != 0)
				close (fds->pi_ufd [i].fp);
		}
		return;
	} else {
		mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER_PROCESS,
			   "%s: getprocs64 failed, using fallback",
			   __func__);
	}
fallback:
#endif
	/* Fallback: Close FDs blindly, according to an FD limit */
	for (guint32 i = max_fd_count () - 1; i > 2; i--)
		close (i);
}
#endif

static gboolean
process_create (const gunichar2 *appname, const gunichar2 *cmdline,
	const gunichar2 *cwd, StartupHandles *startup_handles, MonoW32ProcessInfo *process_info)
{
#if defined (HAVE_FORK) && defined (HAVE_EXECVE)
	char *cmd = NULL, *prog = NULL, *full_prog = NULL, *args = NULL, *args_after_prog = NULL;
	char *dir = NULL, **env_strings = NULL, **argv = NULL;
	guint32 i;
	gboolean ret = FALSE;
	gpointer handle = NULL;
	GError *gerr = NULL;
	int in_fd, out_fd, err_fd;
	pid_t pid = 0;
	int startup_pipe [2] = {-1, -1};
	int dummy;
	Process *process;
	ERROR_DECL (error);

#if HAVE_SIGACTION
	mono_lazy_initialize (&process_sig_chld_once, process_add_sigchld_handler);
#endif

	/* appname and cmdline specify the executable and its args:
	 *
	 * If appname is not NULL, it is the name of the executable.
	 * Otherwise the executable is the first token in cmdline.
	 *
	 * Executable searching:
	 *
	 * If appname is not NULL, it can specify the full path and
	 * file name, or else a partial name and the current directory
	 * will be used.  There is no additional searching.
	 *
	 * If appname is NULL, the first whitespace-delimited token in
	 * cmdline is used.  If the name does not contain a full
	 * directory path, the search sequence is:
	 *
	 * 1) The directory containing the current process
	 * 2) The current working directory
	 * 3) The windows system directory  (Ignored)
	 * 4) The windows directory (Ignored)
	 * 5) $PATH
	 *
	 * Just to make things more interesting, tokens can contain
	 * white space if they are surrounded by quotation marks.
	 */
	if (appname != NULL) {
		cmd = mono_unicode_to_external_checked (appname, error);
		if (cmd == NULL) {
			mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER_PROCESS, "%s: unicode conversion returned NULL; %s",
				   __func__, mono_error_get_message (error));

			mono_error_cleanup (error);
			mono_w32error_set_last (ERROR_PATH_NOT_FOUND);
			goto free_strings;
		}

		switch_dir_separators(cmd);
	}

	if (cmdline != NULL) {
		args = mono_unicode_to_external_checked (cmdline, error);
		if (args == NULL) {
			mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER_PROCESS, "%s: unicode conversion returned NULL; %s", __func__, mono_error_get_message (error));

			mono_error_cleanup (error);
			mono_w32error_set_last (ERROR_PATH_NOT_FOUND);
			goto free_strings;
		}
	}

	if (cwd != NULL) {
		dir = mono_unicode_to_external_checked (cwd, error);
		if (dir == NULL) {
			mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER_PROCESS, "%s: unicode conversion returned NULL; %s", __func__, mono_error_get_message (error));

			mono_error_cleanup (error);
			mono_w32error_set_last (ERROR_PATH_NOT_FOUND);
			goto free_strings;
		}

		/* Turn all the slashes round the right way */
		switch_dir_separators(dir);
	}


	/* We can't put off locating the executable any longer :-( */
	if (cmd != NULL) {
		char *unquoted;
		if (g_ascii_isalpha (cmd[0]) && (cmd[1] == ':')) {
			/* Strip off the drive letter.  I can't
			 * believe that CP/M holdover is still
			 * visible...
			 */
			g_memmove (cmd, cmd+2, strlen (cmd)-2);
			cmd[strlen (cmd)-2] = '\0';
		}

		unquoted = g_shell_unquote (cmd, NULL);
		if (unquoted[0] == '/') {
			/* Assume full path given */
			prog = g_strdup (unquoted);

			/* Executable existing ? */
			if (!is_readable_or_executable (prog)) {
				mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER_PROCESS, "%s: Couldn't find executable %s",
					   __func__, prog);
				g_free (unquoted);
				mono_w32error_set_last (ERROR_FILE_NOT_FOUND);
				goto free_strings;
			}
		} else {
			/* Search for file named by cmd in the current
			 * directory
			 */
			char *curdir = g_get_current_dir ();

			prog = g_strdup_printf ("%s/%s", curdir, unquoted);
			g_free (curdir);

			/* And make sure it's readable */
			if (!is_readable_or_executable (prog)) {
				mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER_PROCESS, "%s: Couldn't find executable %s",
					   __func__, prog);
				g_free (unquoted);
				mono_w32error_set_last (ERROR_FILE_NOT_FOUND);
				goto free_strings;
			}
		}
		g_free (unquoted);

		args_after_prog = args;
	} else {
		char *token = NULL;
		char quote;

		/* Dig out the first token from args, taking quotation
		 * marks into account
		 */

		/* First, strip off all leading whitespace */
		args = g_strchug (args);

		/* args_after_prog points to the contents of args
		 * after token has been set (otherwise argv[0] is
		 * duplicated)
		 */
		args_after_prog = args;

		/* Assume the opening quote will always be the first
		 * character
		 */
		if (args[0] == '\"' || args [0] == '\'') {
			quote = args [0];
			for (i = 1; args[i] != '\0' && args[i] != quote; i++);
			if (args [i + 1] == '\0' || g_ascii_isspace (args[i+1])) {
				/* We found the first token */
				token = g_strndup (args+1, i-1);
				args_after_prog = g_strchug (args + i + 1);
			} else {
				/* Quotation mark appeared in the
				 * middle of the token.  Just give the
				 * whole first token, quotes and all,
				 * to exec.
				 */
			}
		}

		if (token == NULL) {
			/* No quote mark, or malformed */
			for (i = 0; args[i] != '\0'; i++) {
				if (g_ascii_isspace (args[i])) {
					token = g_strndup (args, i);
					args_after_prog = args + i + 1;
					break;
				}
			}
		}

		if (token == NULL && args[0] != '\0') {
			/* Must be just one token in the string */
			token = g_strdup (args);
			args_after_prog = NULL;
		}

		if (token == NULL) {
			/* Give up */
			mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER_PROCESS, "%s: Couldn't find what to exec", __func__);

			mono_w32error_set_last (ERROR_PATH_NOT_FOUND);
			goto free_strings;
		}

		/* Turn all the slashes round the right way. Only for
		 * the prg. name
		 */
		switch_dir_separators(token);

		if (g_ascii_isalpha (token[0]) && (token[1] == ':')) {
			/* Strip off the drive letter.  I can't
			 * believe that CP/M holdover is still
			 * visible...
			 */
			g_memmove (token, token+2, strlen (token)-2);
			token[strlen (token)-2] = '\0';
		}

		if (token[0] == '/') {
			/* Assume full path given */
			prog = g_strdup (token);

			/* Executable existing ? */
			if (!is_readable_or_executable (prog)) {
				mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER_PROCESS, "%s: Couldn't find executable %s",
					   __func__, token);
				g_free (token);
				mono_w32error_set_last (ERROR_FILE_NOT_FOUND);
				goto free_strings;
			}
		} else {
			char *curdir = g_get_current_dir ();

			/* FIXME: Need to record the directory
			 * containing the current process, and check
			 * that for the new executable as the first
			 * place to look
			 */

			prog = g_strdup_printf ("%s/%s", curdir, token);
			g_free (curdir);

			/* I assume X_OK is the criterion to use,
			 * rather than F_OK
			 *
			 * X_OK is too strict *if* the target is a CLR binary
			 */
			if (!is_readable_or_executable (prog)) {
				g_free (prog);
				prog = g_find_program_in_path (token);
				if (prog == NULL) {
					mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER_PROCESS, "%s: Couldn't find executable %s", __func__, token);

					g_free (token);
					mono_w32error_set_last (ERROR_FILE_NOT_FOUND);
					goto free_strings;
				}
			}
		}

		g_free (token);
	}

	mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER_PROCESS, "%s: Exec prog [%s] args [%s]",
		__func__, prog, args_after_prog);

	/* Check for CLR binaries; if found, we will try to invoke
	 * them using the same mono binary that started us.
	 */
	if (is_managed_binary (prog)) {
		gunichar2 *newapp, *newcmd;
		gsize bytes_ignored;

		newapp = mono_unicode_from_external (cli_launcher ? cli_launcher : "mono", &bytes_ignored);
		if (newapp) {
			if (appname)
				newcmd = utf16_concat (utf16_quote, newapp, utf16_quote, utf16_space, appname, utf16_space, cmdline, (const gunichar2 *)NULL);
			else
				newcmd = utf16_concat (utf16_quote, newapp, utf16_quote, utf16_space, cmdline, (const gunichar2 *)NULL);

			g_free (newapp);

			if (newcmd) {
				ret = process_create (NULL, newcmd, cwd, startup_handles, process_info);

				g_free (newcmd);

				goto free_strings;
			}
		}
	} else {
		if (!is_executable (prog)) {
			mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER_PROCESS, "%s: Executable permisson not set on %s", __func__, prog);
			mono_w32error_set_last (ERROR_ACCESS_DENIED);
			goto free_strings;
		}
	}

	if (args_after_prog != NULL && *args_after_prog) {
		char *qprog;

		qprog = g_shell_quote (prog);
		full_prog = g_strconcat (qprog, " ", args_after_prog, (const char*)NULL);
		g_free (qprog);
	} else {
		full_prog = g_shell_quote (prog);
	}

	ret = g_shell_parse_argv (full_prog, NULL, &argv, &gerr);
	if (ret == FALSE) {
		g_message ("process_create: %s\n", gerr->message);
		g_error_free (gerr);
		gerr = NULL;
		goto free_strings;
	}

	if (startup_handles) {
		in_fd = GPOINTER_TO_UINT (startup_handles->input);
		out_fd = GPOINTER_TO_UINT (startup_handles->output);
		err_fd = GPOINTER_TO_UINT (startup_handles->error);
	} else {
		in_fd = GPOINTER_TO_UINT (mono_w32file_get_console_input ());
		out_fd = GPOINTER_TO_UINT (mono_w32file_get_console_output ());
		err_fd = GPOINTER_TO_UINT (mono_w32file_get_console_error ());
	}

	/*
	 * process->env_variables is a an array of MonoString*
	 *
	 * If new_environ is not NULL it specifies the entire set of
	 * environment variables in the new process.  Otherwise the
	 * new process inherits the same environment.
	 */
	if (process_info->env_variables) {
		MonoArrayHandle array = MONO_HANDLE_NEW (MonoArray, process_info->env_variables);
		MonoStringHandle var = MONO_HANDLE_NEW (MonoString, NULL);
		gsize const array_length = mono_array_handle_length (array);

		/* +2: one for the process handle value, and the last one is NULL */
		// What "process handle value"?
		env_strings = g_new0 (gchar*, array_length + 2);

		/* Copy each environ string into 'strings' turning it into utf8 (or the requested encoding) at the same time */
		for (gsize i = 0; i < array_length; ++i) {
			MONO_HANDLE_ARRAY_GETREF (var, array, i);
			MonoGCHandle gchandle = NULL;
			env_strings [i] = mono_unicode_to_external (mono_string_handle_pin_chars (var, &gchandle));
			mono_gchandle_free_internal (gchandle);
		}
	} else {
		gsize env_count = 0;
		for (i = 0; environ[i] != NULL; i++)
			env_count++;

		/* +2: one for the process handle value, and the last one is NULL */
		// What "process handle value"?
		env_strings = g_new0 (gchar*, env_count + 2);

		/* Copy each environ string into 'strings' turning it into utf8 (or the requested encoding) at the same time */
		for (i = 0; i < env_count; i++)
			env_strings [i] = g_strdup (environ[i]);
	}

	/* Create a pipe to make sure the child doesn't exit before
	 * we can add the process to the linked list of processes */
	if (pipe (startup_pipe) == -1) {
		/* Could not create the pipe to synchroniz process startup. We'll just not synchronize.
		 * This is just for a very hard to hit race condition in the first place */
		startup_pipe [0] = startup_pipe [1] = -1;
		mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER_PROCESS, "%s: new process startup not synchronized. We may not notice if the newly created process exits immediately.", __func__);
	}

	switch (pid = fork ()) {
	case -1: /* Error */ {
		mono_w32error_set_last (ERROR_OUTOFMEMORY);
		ret = FALSE;
		break;
	}
	case 0: /* Child */ {
		if (startup_pipe [0] != -1) {
			/* Wait until the parent has updated it's internal data */
			ssize_t _i G_GNUC_UNUSED = read (startup_pipe [0], &dummy, 1);
			mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER_PROCESS, "%s: child: parent has completed its setup", __func__);
			close (startup_pipe [0]);
			close (startup_pipe [1]);
		}

		/* should we detach from the process group? */

		/* Connect stdin, stdout and stderr */
		dup2 (in_fd, 0);
		dup2 (out_fd, 1);
		dup2 (err_fd, 2);

		/* Close this child's file handles. */
		close_my_fds ();

#ifdef DEBUG_ENABLED
		mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER_PROCESS, "%s: exec()ing [%s] in dir [%s]", __func__, cmd,
			   dir == NULL?".":dir);
		for (i = 0; argv[i] != NULL; i++)
			g_message ("arg %" G_GUINT32_FORMAT ": [%s]", i, argv[i]);

		for (i = 0; env_strings[i] != NULL; i++)
			g_message ("env %" G_GUINT32_FORMAT ": [%s]", i, env_strings[i]);
#endif

		/* set cwd */
		if (dir != NULL && chdir (dir) == -1) {
			/* set error */
			_exit (-1);
		}

		/* exec */
		execve (argv[0], argv, env_strings);

		/* set error */
		_exit (-1);

		break;
	}
	default: /* Parent */ {
		MonoW32Handle *handle_data;
		MonoW32HandleProcess process_handle;

		memset (&process_handle, 0, sizeof (process_handle));
		process_handle.pid = pid;
		process_handle.child = TRUE;
		process_handle.pname = g_strdup (prog);
		process_set_defaults (&process_handle);

		/* Add our process into the linked list of processes */
		process = (Process *) g_malloc0 (sizeof (Process));
		process->pid = pid;
		process->handle_count = 1;
		mono_coop_sem_init (&process->exit_sem, 0);

		process_handle.process = process;

		handle = mono_w32handle_new (MONO_W32TYPE_PROCESS, &process_handle);
		if (handle == INVALID_HANDLE_VALUE) {
			g_warning ("%s: error creating process handle", __func__);

			mono_coop_sem_destroy (&process->exit_sem);
			g_free (process);

			mono_w32error_set_last (ERROR_OUTOFMEMORY);
			ret = FALSE;
			break;
		}

		if (!mono_w32handle_lookup_and_ref (handle, &handle_data))
			g_error ("%s: unknown handle %p", __func__, handle);

		if (handle_data->type != MONO_W32TYPE_PROCESS)
			g_error ("%s: unknown process handle %p", __func__, handle);

		/* Keep the process handle artificially alive until the process
		 * exits so that the information in the handle isn't lost. */
		process->handle = mono_w32handle_duplicate (handle_data);

		mono_coop_mutex_lock (&processes_mutex);
		process->next = processes;
		mono_memory_barrier ();
		processes = process;
		mono_coop_mutex_unlock (&processes_mutex);

		if (process_info != NULL) {
			process_info->process_handle = handle;
			process_info->pid = pid;
		}

		mono_w32handle_unref (handle_data);

		break;
	}
	}

	if (startup_pipe [1] != -1) {
		/* Write 1 byte, doesn't matter what */
		ssize_t _i G_GNUC_UNUSED = write (startup_pipe [1], startup_pipe, 1);
		close (startup_pipe [0]);
		close (startup_pipe [1]);
	}

free_strings:
	g_free (cmd);
	g_free (full_prog);
	g_free (prog);
	g_free (args);
	g_free (dir);
	g_strfreev (env_strings);
	g_strfreev (argv);

	mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER_PROCESS, "%s: returning handle %p for pid %d", __func__, handle, pid);

	/* Check if something needs to be cleaned up. */
	processes_cleanup ();

	return ret;
#else
	mono_w32error_set_last (ERROR_NOT_SUPPORTED);
	return FALSE;
#endif // defined (HAVE_FORK) && defined (HAVE_EXECVE)
}

MonoBoolean
ves_icall_System_Diagnostics_Process_ShellExecuteEx_internal (MonoW32ProcessStartInfoHandle proc_start_info, MonoW32ProcessInfo *process_info, MonoError *error)
{
	MonoCreateProcessCoop coop;
	mono_createprocess_coop_init (&coop, proc_start_info, process_info);

	gboolean ret;
	gboolean handler_needswait = FALSE;

	if (!coop.filename) {
		/* w2k returns TRUE for this, for some reason. */
		ret = TRUE;
		goto done;
	}

	const gunichar2 *lpFile;
	lpFile = coop.filename;
	const gunichar2 *lpParameters;
	lpParameters = coop.arguments;
	const gunichar2 *lpDirectory;
	lpDirectory = coop.length.working_directory ? coop.working_directory : NULL;

	/* Put both executable and parameters into the second argument
	 * to process_create (), so it searches $PATH.  The conversion
	 * into and back out of utf8 is because there is no
	 * g_strdup_printf () equivalent for gunichar2 :-(
	 */
	gunichar2 *args;
	args = utf16_concat (utf16_quote, lpFile, utf16_quote, lpParameters ? utf16_space : NULL, lpParameters, (const gunichar2 *)NULL);
	if (args == NULL) {
		mono_w32error_set_last (ERROR_INVALID_DATA);
		ret = FALSE;
		goto done;
	}
	ret = process_create (NULL, args, lpDirectory, NULL, process_info);
	g_free (args);

	if (!ret && mono_w32error_get_last () == ERROR_OUTOFMEMORY)
		goto done;

	if (!ret) {

#if defined(TARGET_IOS) || defined(TARGET_ANDROID)
		// don't try the "open" handlers on iOS/Android, they don't exist there anyway
		goto done;
#endif

		static char *handler;
		static gunichar2 *handler_utf16;
#ifndef HOST_DARWIN
		gboolean finished = FALSE;
#endif

		if (handler_utf16 == (gunichar2 *)-1) {
			ret = FALSE;
			goto done;
		}

#ifdef HOST_DARWIN
		handler = g_strdup ("/usr/bin/open");
		handler_needswait = TRUE;
#else
		/*
		 * On Linux, try: xdg-open, the FreeDesktop standard way of doing it,
		 * if that fails, try to use gnome-open, then kfmclient
		 */
		MONO_ENTER_GC_SAFE;
		handler = g_find_program_in_path ("xdg-open");
		if (handler != NULL)
			handler_needswait = TRUE;
		else {
			handler = g_find_program_in_path ("gnome-open");
			if (handler == NULL){
				handler = g_find_program_in_path ("kfmclient");
				if (handler == NULL){
					handler_utf16 = (gunichar2 *) -1;
					ret = FALSE;
					finished = TRUE;
				} else {
					/* kfmclient needs exec argument */
					char *old = handler;
					handler = g_strconcat (old, " exec",
							       (const char*)NULL);
					g_free (old);
				}
			}
		}
		MONO_EXIT_GC_SAFE;
		if (finished)
			goto done;
#endif
		handler_utf16 = g_utf8_to_utf16 (handler, -1, NULL, NULL, NULL);
		g_free (handler);

		/* Put quotes around the filename, in case it's a url
		 * that contains #'s (process_create() calls
		 * g_shell_parse_argv(), which deliberately throws
		 * away anything after an unquoted #).  Fixes bug
		 * 371567.
		 */
		args = utf16_concat (handler_utf16, utf16_space, utf16_quote, lpFile, utf16_quote,
			lpParameters ? utf16_space : NULL, lpParameters, (const gunichar2 *)NULL);
		if (args == NULL) {
			mono_w32error_set_last (ERROR_INVALID_DATA);
			ret = FALSE;
			goto done;
		}
		ret = process_create (NULL, args, lpDirectory, NULL, process_info);
		g_free (args);
		if (!ret) {
			if (mono_w32error_get_last () != ERROR_OUTOFMEMORY)
				mono_w32error_set_last (ERROR_INVALID_DATA);
			ret = FALSE;
			goto done;
		}

		if (handler_needswait) {
			gint32 exitcode;
			MonoW32HandleWaitRet waitret;
			waitret = process_wait ((MonoW32Handle*)process_info->process_handle, MONO_INFINITE_WAIT, NULL);
			(void)waitret;
			mono_get_exit_code_process (process_info->process_handle, &exitcode);
			if (exitcode != 0)
				ret = FALSE;
		}
		/* Shell exec should not return a process handle when it spawned a GUI thing, like a browser. */
		mono_w32handle_close (process_info->process_handle);
		process_info->process_handle = INVALID_HANDLE_VALUE;
	}

done:
	if (ret == FALSE) {
		process_info->pid = -mono_w32error_get_last ();
	} else {
#if !defined(MONO_CROSS_COMPILE)
		process_info->pid = mono_w32process_get_pid (process_info->process_handle);
#else
		process_info->pid = 0;
#endif
	}

	mono_createprocess_coop_cleanup (&coop);

	return ret;
}

/* Only used when UseShellExecute is false */
static gboolean
process_get_complete_path (const gunichar2 *appname, gchar **completed)
{
	char *found = NULL;
	gboolean result = FALSE;

	char *utf8app = g_utf16_to_utf8 (appname, -1, NULL, NULL, NULL);

	if (g_path_is_absolute (utf8app)) {
		*completed = g_shell_quote (utf8app);
		result = TRUE;
		goto exit;
	}

	if (g_file_test (utf8app, G_FILE_TEST_IS_EXECUTABLE) && !g_file_test (utf8app, G_FILE_TEST_IS_DIR)) {
		*completed = g_shell_quote (utf8app);
		result = TRUE;
		goto exit;
	}
	
	found = g_find_program_in_path (utf8app);
	if (found == NULL) {
		*completed = NULL;
		result = FALSE;
		goto exit;
	}

	*completed = g_shell_quote (found);
	result = TRUE;
exit:
	g_free (found);
	g_free (utf8app);
	return result;
}

static gboolean
process_get_shell_arguments (MonoCreateProcessCoop *coop, gunichar2 **shell_path)
{
	gchar *complete_path = NULL;

	*shell_path = NULL;

	if (process_get_complete_path (coop->filename, &complete_path)) {
		*shell_path = g_utf8_to_utf16 (complete_path, -1, NULL, NULL, NULL);
		g_free (complete_path);
	}

	return *shell_path != NULL;
}

MonoBoolean
ves_icall_System_Diagnostics_Process_CreateProcess_internal (MonoW32ProcessStartInfoHandle proc_start_info,
	HANDLE stdin_handle, HANDLE stdout_handle, HANDLE stderr_handle, MonoW32ProcessInfo *process_info, MonoError *error)
{
	MonoCreateProcessCoop coop;
	mono_createprocess_coop_init (&coop, proc_start_info, process_info);

	gboolean ret;
	StartupHandles startup_handles;
	gunichar2 *shell_path = NULL;

	memset (&startup_handles, 0, sizeof (startup_handles));
	startup_handles.input = stdin_handle;
	startup_handles.output = stdout_handle;
	startup_handles.error = stderr_handle;

	if (!process_get_shell_arguments (&coop, &shell_path)) {
		process_info->pid = -ERROR_FILE_NOT_FOUND;
		ret = FALSE;
		goto exit;
	}

	gunichar2 *args;
	args = coop.length.arguments ? coop.arguments : NULL;

	/* The default dir name is "".  Turn that into NULL to mean "current directory" */
	gunichar2 *dir;
	dir = coop.length.working_directory ? coop.working_directory : NULL;

	ret = process_create (shell_path, args, dir, &startup_handles, process_info);

	if (!ret)
		process_info->pid = -mono_w32error_get_last ();

exit:
	g_free (shell_path);
	mono_createprocess_coop_cleanup (&coop);
	return ret;
}

/* Returns an array of pids */
MonoArrayHandle
ves_icall_System_Diagnostics_Process_GetProcesses_internal (MonoError *error)
{
	int count = 0;
	guint32 *raw = 0;
	gpointer *pidarray = 0;
	MonoArrayHandle procs = NULL_HANDLE_ARRAY;

	// FIXME mono_process_list should probably return array of int
	// as all of the users of the elements truncate to that.

	MONO_ENTER_GC_SAFE;
	pidarray = mono_process_list (&count);
	MONO_EXIT_GC_SAFE;
	if (!pidarray) {
		mono_error_set_not_supported (error, "This system does not support EnumProcesses");
		goto exit;
	}
	procs = mono_array_new_handle (mono_domain_get (), mono_get_int32_class (), count, error);
	if (!is_ok (error)) {
		procs = NULL_HANDLE_ARRAY;
		goto exit;
	}

	MONO_ENTER_NO_SAFEPOINTS;

	raw = mono_array_addr_internal (MONO_HANDLE_RAW (procs), guint32, 0);
	if (sizeof (guint32) == sizeof (gpointer)) {
		memcpy (raw, pidarray, count * sizeof (gint32));
	} else {
		for (int i = 0; i < count; ++i)
			raw [i] = GPOINTER_TO_UINT (pidarray [i]);
	}

	MONO_EXIT_NO_SAFEPOINTS;

exit:
	g_free (pidarray);
	return procs;
}

void
mono_w32process_set_cli_launcher (gchar *path)
{
	g_free (cli_launcher);
	cli_launcher = g_strdup (path);
}

gpointer
ves_icall_Microsoft_Win32_NativeMethods_GetCurrentProcess (void)
{
	return current_process;
}

MonoBoolean
ves_icall_Microsoft_Win32_NativeMethods_GetExitCodeProcess (gpointer handle, gint32 *exitcode)
{
	return mono_get_exit_code_process (handle, exitcode);
}

static MonoBoolean
mono_get_exit_code_process (gpointer handle, gint32 *exitcode)
{
	MonoW32Handle *handle_data;
	MonoW32HandleProcess *process_handle;

	if (!exitcode)
		return FALSE;

	if (!mono_w32handle_lookup_and_ref (handle, &handle_data)) {
		mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER_PROCESS, "%s: unknown handle %p", __func__, handle);
		mono_w32error_set_last (ERROR_INVALID_HANDLE);
		return FALSE;
	}

	if (handle_data->type != MONO_W32TYPE_PROCESS) {
		mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER_PROCESS, "%s: unknown process handle %p", __func__, handle);
		mono_w32error_set_last (ERROR_INVALID_HANDLE);
		mono_w32handle_unref (handle_data);
		return FALSE;
	}

	process_handle = (MonoW32HandleProcess*) handle_data->specific;

	if (process_handle->pid == current_pid) {
		*exitcode = STILL_ACTIVE;
		mono_w32handle_unref (handle_data);
		return TRUE;
	}

	/* A process handle is only signalled if the process has exited
	 * and has been waited for. Make sure any process exit has been
	 * noticed before checking if the process is signalled.
	 * Fixes bug 325463. */
	mono_w32handle_wait_one (handle, 0, TRUE);

	*exitcode = mono_w32handle_issignalled (handle_data) ? process_handle->exitstatus : STILL_ACTIVE;

	mono_w32handle_unref (handle_data);

	return TRUE;
}

MonoBoolean
ves_icall_Microsoft_Win32_NativeMethods_CloseProcess (gpointer handle)
{
	return mono_w32handle_close (handle);
}

MonoBoolean
ves_icall_Microsoft_Win32_NativeMethods_TerminateProcess (gpointer handle, gint32 exitcode)
{
#ifdef HAVE_KILL
	MonoW32Handle *handle_data;
	int ret;
	pid_t pid;

	if (!mono_w32handle_lookup_and_ref (handle, &handle_data)) {
		mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER_PROCESS, "%s: unknown handle %p", __func__, handle);
		mono_w32error_set_last (ERROR_INVALID_HANDLE);
		return FALSE;
	}

	if (handle_data->type != MONO_W32TYPE_PROCESS) {
		mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER_PROCESS, "%s: unknown process handle %p", __func__, handle);
		mono_w32error_set_last (ERROR_INVALID_HANDLE);
		mono_w32handle_unref (handle_data);
		return FALSE;
	}

	pid = ((MonoW32HandleProcess*) handle_data->specific)->pid;

	ret = kill (pid, exitcode == -1 ? SIGKILL : SIGTERM);
	if (ret == 0) {
		mono_w32handle_unref (handle_data);
		return TRUE;
	}

	switch (errno) {
	case EINVAL: mono_w32error_set_last (ERROR_INVALID_PARAMETER); break;
	case EPERM:  mono_w32error_set_last (ERROR_ACCESS_DENIED);     break;
	case ESRCH:  mono_w32error_set_last (ERROR_PROC_NOT_FOUND);    break;
	default:     mono_w32error_set_last (ERROR_GEN_FAILURE);       break;
	}

	mono_w32handle_unref (handle_data);
	return FALSE;
#else
	g_error ("kill() is not supported by this platform");
#endif
}

MonoBoolean
ves_icall_Microsoft_Win32_NativeMethods_GetProcessWorkingSetSize (gpointer handle, gsize *min, gsize *max)
{
	MonoW32Handle *handle_data;
	MonoW32HandleProcess *process_handle;

	if (!min || !max)
		return FALSE;

	if (!mono_w32handle_lookup_and_ref (handle, &handle_data)) {
		mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER_PROCESS, "%s: unknown handle %p", __func__, handle);
		mono_w32error_set_last (ERROR_INVALID_HANDLE);
		return FALSE;
	}

	if (handle_data->type != MONO_W32TYPE_PROCESS) {
		mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER_PROCESS, "%s: unknown process handle %p", __func__, handle);
		mono_w32error_set_last (ERROR_INVALID_HANDLE);
		mono_w32handle_unref (handle_data);
		return FALSE;
	}

	process_handle = (MonoW32HandleProcess*) handle_data->specific;

	if (!process_handle->child) {
		mono_w32handle_unref (handle_data);
		return FALSE;
	}

	*min = process_handle->min_working_set;
	*max = process_handle->max_working_set;

	mono_w32handle_unref (handle_data);
	return TRUE;
}

MonoBoolean
ves_icall_Microsoft_Win32_NativeMethods_SetProcessWorkingSetSize (gpointer handle, gsize min, gsize max)
{
	MonoW32Handle *handle_data;
	MonoW32HandleProcess *process_handle;

	if (!mono_w32handle_lookup_and_ref (handle, &handle_data)) {
		mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER_PROCESS, "%s: unknown handle %p", __func__, handle);
		mono_w32error_set_last (ERROR_INVALID_HANDLE);
		return FALSE;
	}

	if (handle_data->type != MONO_W32TYPE_PROCESS) {
		mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER_PROCESS, "%s: unknown process handle %p", __func__, handle);
		mono_w32error_set_last (ERROR_INVALID_HANDLE);
		mono_w32handle_unref (handle_data);
		return FALSE;
	}

	process_handle = (MonoW32HandleProcess*) handle_data->specific;

	if (!process_handle->child) {
		mono_w32handle_unref (handle_data);
		return FALSE;
	}

	process_handle->min_working_set = min;
	process_handle->max_working_set = max;

	mono_w32handle_unref (handle_data);
	return TRUE;
}

gint32
ves_icall_Microsoft_Win32_NativeMethods_GetPriorityClass (gpointer handle)
{
#ifdef HAVE_GETPRIORITY
	MonoW32Handle *handle_data;
	gint res;
	gint32 ret;
	pid_t pid;

	if (!mono_w32handle_lookup_and_ref (handle, &handle_data)) {
		mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER_PROCESS, "%s: unknown handle %p", __func__, handle);
		mono_w32error_set_last (ERROR_INVALID_HANDLE);
		return 0;
	}

	if (handle_data->type != MONO_W32TYPE_PROCESS) {
		mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER_PROCESS, "%s: unknown process handle %p", __func__, handle);
		mono_w32error_set_last (ERROR_INVALID_HANDLE);
		mono_w32handle_unref (handle_data);
		return 0;
	}

	pid = ((MonoW32HandleProcess*) handle_data->specific)->pid;

	mono_set_errno (0);
	res = getpriority (PRIO_PROCESS, pid);
	if (res == -1 && errno != 0) {
		switch (errno) {
		case EPERM:
		case EACCES:
			mono_w32error_set_last (ERROR_ACCESS_DENIED);
			break;
		case ESRCH:
			mono_w32error_set_last (ERROR_PROC_NOT_FOUND);
			break;
		default:
			mono_w32error_set_last (ERROR_GEN_FAILURE);
		}

		mono_w32handle_unref (handle_data);
		return 0;
	}

	if (res == 0)
		ret = MONO_W32PROCESS_PRIORITY_CLASS_NORMAL;
	else if (res < -15)
		ret = MONO_W32PROCESS_PRIORITY_CLASS_REALTIME;
	else if (res < -10)
		ret = MONO_W32PROCESS_PRIORITY_CLASS_HIGH;
	else if (res < 0)
		ret = MONO_W32PROCESS_PRIORITY_CLASS_ABOVE_NORMAL;
	else if (res > 10)
		ret = MONO_W32PROCESS_PRIORITY_CLASS_IDLE;
	else if (res > 0)
		ret = MONO_W32PROCESS_PRIORITY_CLASS_BELOW_NORMAL;
	else
		ret = MONO_W32PROCESS_PRIORITY_CLASS_NORMAL;

	mono_w32handle_unref (handle_data);
	return ret;
#else
	mono_w32error_set_last (ERROR_NOT_SUPPORTED);
	return 0;
#endif
}

MonoBoolean
ves_icall_Microsoft_Win32_NativeMethods_SetPriorityClass (gpointer handle, gint32 priorityClass)
{
#ifdef HAVE_SETPRIORITY
	MonoW32Handle *handle_data;
	int ret;
	int prio;
	pid_t pid;

	if (!mono_w32handle_lookup_and_ref (handle, &handle_data)) {
		mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER_PROCESS, "%s: unknown handle %p", __func__, handle);
		mono_w32error_set_last (ERROR_INVALID_HANDLE);
		return FALSE;
	}

	if (handle_data->type != MONO_W32TYPE_PROCESS) {
		mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER_PROCESS, "%s: unknown process handle %p", __func__, handle);
		mono_w32error_set_last (ERROR_INVALID_HANDLE);
		mono_w32handle_unref (handle_data);
		return FALSE;
	}

	pid = ((MonoW32HandleProcess*) handle_data->specific)->pid;

	switch (priorityClass) {
	case MONO_W32PROCESS_PRIORITY_CLASS_IDLE:
		prio = 19;
		break;
	case MONO_W32PROCESS_PRIORITY_CLASS_BELOW_NORMAL:
		prio = 10;
		break;
	case MONO_W32PROCESS_PRIORITY_CLASS_NORMAL:
		prio = 0;
		break;
	case MONO_W32PROCESS_PRIORITY_CLASS_ABOVE_NORMAL:
		prio = -5;
		break;
	case MONO_W32PROCESS_PRIORITY_CLASS_HIGH:
		prio = -11;
		break;
	case MONO_W32PROCESS_PRIORITY_CLASS_REALTIME:
		prio = -20;
		break;
	default:
		mono_w32error_set_last (ERROR_INVALID_PARAMETER);
		mono_w32handle_unref (handle_data);
		return FALSE;
	}

	ret = setpriority (PRIO_PROCESS, pid, prio);
	if (ret == -1) {
		switch (errno) {
		case EPERM:
		case EACCES:
			mono_w32error_set_last (ERROR_ACCESS_DENIED);
			break;
		case ESRCH:
			mono_w32error_set_last (ERROR_PROC_NOT_FOUND);
			break;
		default:
			mono_w32error_set_last (ERROR_GEN_FAILURE);
		}
	}

	mono_w32handle_unref (handle_data);
	return ret == 0;
#else
	mono_w32error_set_last (ERROR_NOT_SUPPORTED);
	return FALSE;
#endif
}

static void
ticks_to_processtime (guint64 ticks, ProcessTime *processtime)
{
	processtime->lowDateTime = ticks & 0xFFFFFFFF;
	processtime->highDateTime = ticks >> 32;
}

MonoBoolean
ves_icall_Microsoft_Win32_NativeMethods_GetProcessTimes (gpointer handle, gint64 *creation_time, gint64 *exit_time, gint64 *kernel_time, gint64 *user_time)
{
	MonoW32Handle *handle_data;
	MonoW32HandleProcess *process_handle;
	ProcessTime *creation_processtime, *exit_processtime, *kernel_processtime, *user_processtime;

	if (!creation_time || !exit_time || !kernel_time || !user_time) {
		/* Not sure if w32 allows NULLs here or not */
		return FALSE;
	}

	creation_processtime = (ProcessTime*) creation_time;
	exit_processtime = (ProcessTime*) exit_time;
	kernel_processtime = (ProcessTime*) kernel_time;
	user_processtime = (ProcessTime*) user_time;

	memset (creation_processtime, 0, sizeof (ProcessTime));
	memset (exit_processtime, 0, sizeof (ProcessTime));
	memset (kernel_processtime, 0, sizeof (ProcessTime));
	memset (user_processtime, 0, sizeof (ProcessTime));

	if (!mono_w32handle_lookup_and_ref (handle, &handle_data)) {
		mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER_PROCESS, "%s: unknown handle %p", __func__, handle);
		mono_w32error_set_last (ERROR_INVALID_HANDLE);
		return FALSE;
	}

	if (handle_data->type != MONO_W32TYPE_PROCESS) {
		mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER_PROCESS, "%s: unknown process handle %p", __func__, handle);
		mono_w32error_set_last (ERROR_INVALID_HANDLE);
		mono_w32handle_unref (handle_data);
		return FALSE;
	}

	process_handle = (MonoW32HandleProcess*) handle_data->specific;

	if (!process_handle->child) {
		gint64 start_ticks, user_ticks, kernel_ticks;

		mono_process_get_times (GINT_TO_POINTER (process_handle->pid),
			&start_ticks, &user_ticks, &kernel_ticks);

		ticks_to_processtime (start_ticks, creation_processtime);
		ticks_to_processtime (kernel_ticks, kernel_processtime);
		ticks_to_processtime (user_ticks, user_processtime);

		mono_w32handle_unref (handle_data);
		return TRUE;
	}

	ticks_to_processtime (process_handle->create_time, creation_processtime);

	/* A process handle is only signalled if the process has
	 * exited, otherwise exit_processtime isn't set */
	if (mono_w32handle_issignalled (handle_data))
		ticks_to_processtime (process_handle->exit_time, exit_processtime);

#ifdef HAVE_GETRUSAGE
	if (process_handle->pid == getpid ()) {
		struct rusage time_data;
		if (getrusage (RUSAGE_SELF, &time_data) == 0) {
			ticks_to_processtime ((guint64)time_data.ru_utime.tv_sec * 10000000 + (guint64)time_data.ru_utime.tv_usec * 10, user_processtime);
			ticks_to_processtime ((guint64)time_data.ru_stime.tv_sec * 10000000 + (guint64)time_data.ru_stime.tv_usec * 10, kernel_processtime);
		}
	}
#endif

	mono_w32handle_unref (handle_data);
	return TRUE;
}

static IMAGE_SECTION_HEADER *
get_enclosing_section_header (guint32 rva, IMAGE_NT_HEADERS32 *nt_headers)
{
	IMAGE_SECTION_HEADER *section = IMAGE_FIRST_SECTION32 (nt_headers);
	guint32 i;

	for (i = 0; i < GUINT16_FROM_LE (nt_headers->FileHeader.NumberOfSections); i++, section++) {
		guint32 size = GUINT32_FROM_LE (section->Misc.VirtualSize);
		if (size == 0) {
			size = GUINT32_FROM_LE (section->SizeOfRawData);
		}

		if ((rva >= GUINT32_FROM_LE (section->VirtualAddress)) &&
		    (rva < (GUINT32_FROM_LE (section->VirtualAddress) + size))) {
			return(section);
		}
	}

	return(NULL);
}

/* This works for both 32bit and 64bit files, as the differences are
 * all after the section header block
 */
static gpointer
get_ptr_from_rva (guint32 rva, IMAGE_NT_HEADERS32 *ntheaders, gpointer file_map)
{
	IMAGE_SECTION_HEADER *section_header;
	guint32 delta;

	section_header = get_enclosing_section_header (rva, ntheaders);
	if (section_header == NULL) {
		return(NULL);
	}

	delta = (guint32)(GUINT32_FROM_LE (section_header->VirtualAddress) -
			  GUINT32_FROM_LE (section_header->PointerToRawData));

	return((guint8 *)file_map + rva - delta);
}

static gpointer
scan_resource_dir (IMAGE_RESOURCE_DIRECTORY *root, IMAGE_NT_HEADERS32 *nt_headers, gpointer file_map,
	IMAGE_RESOURCE_DIRECTORY_ENTRY *entry, int level, guint32 res_id, guint32 lang_id, gsize *size)
{
	IMAGE_RESOURCE_DIRECTORY_ENTRY swapped_entry;
	gboolean is_string, is_dir;
	guint32 name_offset, dir_offset, data_offset;

	swapped_entry.Name = GUINT32_FROM_LE (entry->Name);
	swapped_entry.OffsetToData = GUINT32_FROM_LE (entry->OffsetToData);

	is_string = swapped_entry.NameIsString;
	is_dir = swapped_entry.DataIsDirectory;
	name_offset = swapped_entry.NameOffset;
	dir_offset = swapped_entry.OffsetToDirectory;
	data_offset = swapped_entry.OffsetToData;

	if (level == 0) {
		/* Normally holds a directory entry for each type of
		 * resource
		 */
		if ((is_string == FALSE &&
		     name_offset != res_id) ||
		    (is_string == TRUE)) {
			return(NULL);
		}
	} else if (level == 1) {
		/* Normally holds a directory entry for each resource
		 * item
		 */
	} else if (level == 2) {
		/* Normally holds a directory entry for each language
		 */
		if ((is_string == FALSE &&
		     name_offset != lang_id &&
		     lang_id != 0) ||
		    (is_string == TRUE)) {
			return(NULL);
		}
	} else {
		g_assert_not_reached ();
	}

	if (is_dir == TRUE) {
		IMAGE_RESOURCE_DIRECTORY *res_dir = (IMAGE_RESOURCE_DIRECTORY *)((guint8 *)root + dir_offset);
		IMAGE_RESOURCE_DIRECTORY_ENTRY *sub_entries = (IMAGE_RESOURCE_DIRECTORY_ENTRY *)(res_dir + 1);
		guint32 entries, i;

		entries = GUINT16_FROM_LE (res_dir->NumberOfNamedEntries) + GUINT16_FROM_LE (res_dir->NumberOfIdEntries);

		for (i = 0; i < entries; i++) {
			IMAGE_RESOURCE_DIRECTORY_ENTRY *sub_entry = &sub_entries[i];
			gpointer ret;

			ret = scan_resource_dir (root, nt_headers, file_map,
						 sub_entry, level + 1, res_id,
						 lang_id, size);
			if (ret != NULL) {
				return(ret);
			}
		}

		return(NULL);
	} else {
		IMAGE_RESOURCE_DATA_ENTRY *data_entry = (IMAGE_RESOURCE_DATA_ENTRY *)((guint8 *)root + data_offset);
		*size = GUINT32_FROM_LE (data_entry->Size);

		return(get_ptr_from_rva (GUINT32_FROM_LE (data_entry->OffsetToData), nt_headers, file_map));
	}
}

static gpointer
find_pe_file_resources32 (gpointer file_map, guint32 map_size, guint32 res_id, guint32 lang_id, gsize *size)
{
	IMAGE_DOS_HEADER *dos_header;
	IMAGE_NT_HEADERS32 *nt_headers;
	IMAGE_RESOURCE_DIRECTORY *resource_dir;
	IMAGE_RESOURCE_DIRECTORY_ENTRY *resource_dir_entry;
	guint32 resource_rva, entries, i;
	gpointer ret = NULL;

	dos_header = (IMAGE_DOS_HEADER *)file_map;
	if (dos_header->e_magic != IMAGE_DOS_SIGNATURE) {
		mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER_PROCESS, "%s: Bad dos signature 0x%x", __func__, dos_header->e_magic);

		mono_w32error_set_last (ERROR_INVALID_DATA);
		return(NULL);
	}

	if (map_size < sizeof(IMAGE_NT_HEADERS32) + GUINT32_FROM_LE (dos_header->e_lfanew)) {
		mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER_PROCESS, "%s: File is too small: %" G_GUINT32_FORMAT, __func__, map_size);

		mono_w32error_set_last (ERROR_BAD_LENGTH);
		return(NULL);
	}

	nt_headers = (IMAGE_NT_HEADERS32 *)((guint8 *)file_map + GUINT32_FROM_LE (dos_header->e_lfanew));
	if (nt_headers->Signature != IMAGE_NT_SIGNATURE) {
		mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER_PROCESS, "%s: Bad NT signature 0x%x", __func__, nt_headers->Signature);

		mono_w32error_set_last (ERROR_INVALID_DATA);
		return(NULL);
	}

	if (nt_headers->OptionalHeader.Magic == IMAGE_NT_OPTIONAL_HDR64_MAGIC) {
		/* Do 64-bit stuff */
		resource_rva = GUINT32_FROM_LE (((IMAGE_NT_HEADERS64 *)nt_headers)->OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_RESOURCE].VirtualAddress);
	} else {
		resource_rva = GUINT32_FROM_LE (nt_headers->OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_RESOURCE].VirtualAddress);
	}

	if (resource_rva == 0) {
		mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER_PROCESS, "%s: No resources in file!", __func__);

		mono_w32error_set_last (ERROR_INVALID_DATA);
		return(NULL);
	}

	resource_dir = (IMAGE_RESOURCE_DIRECTORY *)get_ptr_from_rva (resource_rva, (IMAGE_NT_HEADERS32 *)nt_headers, file_map);
	if (resource_dir == NULL) {
		mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER_PROCESS, "%s: Can't find resource directory", __func__);

		mono_w32error_set_last (ERROR_INVALID_DATA);
		return(NULL);
	}

	entries = GUINT16_FROM_LE (resource_dir->NumberOfNamedEntries) + GUINT16_FROM_LE (resource_dir->NumberOfIdEntries);
	resource_dir_entry = (IMAGE_RESOURCE_DIRECTORY_ENTRY *)(resource_dir + 1);

	for (i = 0; i < entries; i++) {
		IMAGE_RESOURCE_DIRECTORY_ENTRY *direntry = &resource_dir_entry[i];
		ret = scan_resource_dir (resource_dir,
					 (IMAGE_NT_HEADERS32 *)nt_headers,
					 file_map, direntry, 0, res_id,
					 lang_id, size);
		if (ret != NULL) {
			return(ret);
		}
	}

	return(NULL);
}

static gpointer
find_pe_file_resources64 (gpointer file_map, guint32 map_size, guint32 res_id, guint32 lang_id, gsize *size)
{
	IMAGE_DOS_HEADER *dos_header;
	IMAGE_NT_HEADERS64 *nt_headers;
	IMAGE_RESOURCE_DIRECTORY *resource_dir;
	IMAGE_RESOURCE_DIRECTORY_ENTRY *resource_dir_entry;
	guint32 resource_rva, entries, i;
	gpointer ret = NULL;

	dos_header = (IMAGE_DOS_HEADER *)file_map;
	if (dos_header->e_magic != IMAGE_DOS_SIGNATURE) {
		mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER_PROCESS, "%s: Bad dos signature 0x%x", __func__, dos_header->e_magic);

		mono_w32error_set_last (ERROR_INVALID_DATA);
		return(NULL);
	}

	if (map_size < sizeof(IMAGE_NT_HEADERS64) + GUINT32_FROM_LE (dos_header->e_lfanew)) {
		mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER_PROCESS, "%s: File is too small: %" G_GUINT32_FORMAT, __func__, map_size);

		mono_w32error_set_last (ERROR_BAD_LENGTH);
		return(NULL);
	}

	nt_headers = (IMAGE_NT_HEADERS64 *)((guint8 *)file_map + GUINT32_FROM_LE (dos_header->e_lfanew));
	if (nt_headers->Signature != IMAGE_NT_SIGNATURE) {
		mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER_PROCESS, "%s: Bad NT signature 0x%x", __func__,
			   nt_headers->Signature);

		mono_w32error_set_last (ERROR_INVALID_DATA);
		return(NULL);
	}

	if (nt_headers->OptionalHeader.Magic == IMAGE_NT_OPTIONAL_HDR64_MAGIC) {
		/* Do 64-bit stuff */
		resource_rva = GUINT32_FROM_LE (((IMAGE_NT_HEADERS64 *)nt_headers)->OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_RESOURCE].VirtualAddress);
	} else {
		resource_rva = GUINT32_FROM_LE (nt_headers->OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_RESOURCE].VirtualAddress);
	}

	if (resource_rva == 0) {
		mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER_PROCESS, "%s: No resources in file!", __func__);

		mono_w32error_set_last (ERROR_INVALID_DATA);
		return(NULL);
	}

	resource_dir = (IMAGE_RESOURCE_DIRECTORY *)get_ptr_from_rva (resource_rva, (IMAGE_NT_HEADERS32 *)nt_headers, file_map);
	if (resource_dir == NULL) {
		mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER_PROCESS, "%s: Can't find resource directory", __func__);

		mono_w32error_set_last (ERROR_INVALID_DATA);
		return(NULL);
	}

	entries = GUINT16_FROM_LE (resource_dir->NumberOfNamedEntries) + GUINT16_FROM_LE (resource_dir->NumberOfIdEntries);
	resource_dir_entry = (IMAGE_RESOURCE_DIRECTORY_ENTRY *)(resource_dir + 1);

	for (i = 0; i < entries; i++) {
		IMAGE_RESOURCE_DIRECTORY_ENTRY *direntry = &resource_dir_entry[i];
		ret = scan_resource_dir (resource_dir,
					 (IMAGE_NT_HEADERS32 *)nt_headers,
					 file_map, direntry, 0, res_id,
					 lang_id, size);
		if (ret != NULL) {
			return(ret);
		}
	}

	return(NULL);
}

static gpointer
find_pe_file_resources (gpointer file_map, guint32 map_size, guint32 res_id, guint32 lang_id, gsize *size)
{
	/* Figure this out when we support 64bit PE files */
	if (1) {
		return find_pe_file_resources32 (file_map, map_size, res_id,
						 lang_id, size);
	} else {
		return find_pe_file_resources64 (file_map, map_size, res_id,
						 lang_id, size);
	}
}

static guint32
unicode_chars (const gunichar2 *str)
{
	guint32 len = 0;

	do {
		if (str[len] == '\0') {
			return(len);
		}
		len++;
	} while(1);
}

static gboolean
unicode_compare (const gunichar2 *str1, const gunichar2 *str2)
{
	while (*str1 && *str2) {
		if (*str1 != *str2) {
			return(FALSE);
		}
		++str1;
		++str2;
	}

	return(*str1 == *str2);
}

/* compare a little-endian null-terminated utf16 string and a normal string.
 * Can be used only for ascii or latin1 chars.
 */
static gboolean
unicode_string_equals (const gunichar2 *str1, const gchar *str2)
{
	while (*str1 && *str2) {
		if (GUINT16_TO_LE (*str1) != *str2) {
			return(FALSE);
		}
		++str1;
		++str2;
	}

	return(*str1 == *str2);
}

typedef struct {
	guint16 data_len;
	guint16 value_len;
	guint16 type;
	gunichar2 *key;
} version_data;

/* Returns a pointer to the value data, because there's no way to know
 * how big that data is (value_len is set to zero for most blocks :-( )
 */
static gconstpointer
get_versioninfo_block (gconstpointer data, version_data *block)
{
	block->data_len = GUINT16_FROM_LE (*((guint16 *)data));
	data = (char *)data + sizeof(guint16);
	block->value_len = GUINT16_FROM_LE (*((guint16 *)data));
	data = (char *)data + sizeof(guint16);

	/* No idea what the type is supposed to indicate */
	block->type = GUINT16_FROM_LE (*((guint16 *)data));
	data = (char *)data + sizeof(guint16);
	block->key = ((gunichar2 *)data);

	/* Skip over the key (including the terminator) */
	data = ((gunichar2 *)data) + (unicode_chars (block->key) + 1);

	/* align on a 32-bit boundary */
	ALIGN32 (data);

	return(data);
}

static gconstpointer
get_fixedfileinfo_block (gconstpointer data, version_data *block)
{
	gconstpointer data_ptr;
	VS_FIXEDFILEINFO *ffi;

	data_ptr = get_versioninfo_block (data, block);

	if (block->value_len != sizeof(VS_FIXEDFILEINFO)) {
		mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER_PROCESS, "%s: FIXEDFILEINFO size mismatch", __func__);
		return(NULL);
	}

	if (!unicode_string_equals (block->key, "VS_VERSION_INFO")) {
		mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER_PROCESS, "%s: VS_VERSION_INFO mismatch", __func__);

		return(NULL);
	}

	ffi = ((VS_FIXEDFILEINFO *)data_ptr);
	if ((ffi->dwSignature != VS_FFI_SIGNATURE) ||
	    (ffi->dwStrucVersion != VS_FFI_STRUCVERSION)) {
		mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER_PROCESS, "%s: FIXEDFILEINFO bad signature", __func__);

		return(NULL);
	}

	return(data_ptr);
}

static gconstpointer
get_varfileinfo_block (gconstpointer data_ptr, version_data *block)
{
	/* data is pointing at a Var block
	 */
	data_ptr = get_versioninfo_block (data_ptr, block);

	return(data_ptr);
}

static gconstpointer
get_string_block (gconstpointer data_ptr, const gunichar2 *string_key, gpointer *string_value,
	guint32 *string_value_len, version_data *block)
{
	guint16 data_len = block->data_len;
	guint16 string_len = 28; /* Length of the StringTable block */
	char *orig_data_ptr = (char *)data_ptr - 28;

	/* data_ptr is pointing at an array of one or more String blocks
	 * with total length (not including alignment padding) of
	 * data_len
	 */
	while (((char *)data_ptr - (char *)orig_data_ptr) < data_len) {
		/* align on a 32-bit boundary */
		ALIGN32 (data_ptr);

		data_ptr = get_versioninfo_block (data_ptr, block);
		if (block->data_len == 0) {
			/* We must have hit padding, so give up
			 * processing now
			 */
			mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER_PROCESS, "%s: Hit 0-length block, giving up", __func__);

			return(NULL);
		}

		string_len = string_len + block->data_len;

		if (string_key != NULL &&
		    string_value != NULL &&
		    string_value_len != NULL &&
		    unicode_compare (string_key, block->key) == TRUE) {
			*string_value = (gpointer)data_ptr;
			*string_value_len = block->value_len;
		}

		/* Skip over the value */
		data_ptr = ((gunichar2 *)data_ptr) + block->value_len;
	}

	return(data_ptr);
}

/* Returns a pointer to the byte following the Stringtable block, or
 * NULL if the data read hits padding.  We can't recover from this
 * because the data length does not include padding bytes, so it's not
 * possible to just return the start position + length
 *
 * If lang == NULL it means we're just stepping through this block
 */
static gconstpointer
get_stringtable_block (gconstpointer data_ptr, gchar *lang, const gunichar2 *string_key, gpointer *string_value,
	guint32 *string_value_len, version_data *block)
{
	guint16 data_len = block->data_len;
	guint16 string_len = 36; /* length of the StringFileInfo block */
	gchar *found_lang;
	gchar *lowercase_lang;

	/* data_ptr is pointing at an array of StringTable blocks,
	 * with total length (not including alignment padding) of
	 * data_len
	 */

	while(string_len < data_len) {
		/* align on a 32-bit boundary */
		ALIGN32 (data_ptr);

		data_ptr = get_versioninfo_block (data_ptr, block);
		if (block->data_len == 0) {
			/* We must have hit padding, so give up
			 * processing now
			 */
			mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER_PROCESS, "%s: Hit 0-length block, giving up", __func__);
			return(NULL);
		}

		string_len = string_len + block->data_len;

		found_lang = g_utf16_to_utf8 (block->key, 8, NULL, NULL, NULL);
		if (found_lang == NULL) {
			mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER_PROCESS, "%s: Didn't find a valid language key, giving up", __func__);
			return(NULL);
		}

		lowercase_lang = g_utf8_strdown (found_lang, -1);
		g_free (found_lang);
		found_lang = lowercase_lang;
		lowercase_lang = NULL;

		if (lang != NULL && !strcmp (found_lang, lang)) {
			/* Got the one we're interested in */
			data_ptr = get_string_block (data_ptr, string_key,
						     string_value,
						     string_value_len, block);
		} else {
			data_ptr = get_string_block (data_ptr, NULL, NULL,
						     NULL, block);
		}

		g_free (found_lang);

		if (data_ptr == NULL) {
			/* Child block hit padding */
			mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER_PROCESS, "%s: Child block hit 0-length block, giving up", __func__);
			return(NULL);
		}
	}

	return(data_ptr);
}

#if G_BYTE_ORDER == G_BIG_ENDIAN
static gconstpointer
big_up_string_block (gconstpointer data_ptr, version_data *block)
{
	guint16 data_len = block->data_len;
	guint16 string_len = 28; /* Length of the StringTable block */
	gchar *big_value;
	char *orig_data_ptr = (char *)data_ptr - 28;

	/* data_ptr is pointing at an array of one or more String
	 * blocks with total length (not including alignment padding)
	 * of data_len
	 */
	while (((char *)data_ptr - (char *)orig_data_ptr) < data_len) {
		/* align on a 32-bit boundary */
		ALIGN32 (data_ptr);

		data_ptr = get_versioninfo_block (data_ptr, block);
		if (block->data_len == 0) {
			/* We must have hit padding, so give up
			 * processing now
			 */
			mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER_PROCESS, "%s: Hit 0-length block, giving up", __func__);
			return(NULL);
		}

		string_len = string_len + block->data_len;

		big_value = g_convert ((gchar *)block->key,
				       unicode_chars (block->key) * 2,
				       "UTF-16BE", "UTF-16LE", NULL, NULL,
				       NULL);
		if (big_value == NULL) {
			mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER_PROCESS, "%s: Didn't find a valid string, giving up", __func__);
			return(NULL);
		}

		/* The swapped string should be exactly the same
		 * length as the original little-endian one, but only
		 * copy the number of original chars just to be on the
		 * safe side
		 */
		memcpy (block->key, big_value, unicode_chars (block->key) * 2);
		g_free (big_value);

		big_value = g_convert ((gchar *)data_ptr,
				       unicode_chars ((const gunichar2*)data_ptr) * 2,
				       "UTF-16BE", "UTF-16LE", NULL, NULL,
				       NULL);
		if (big_value == NULL) {
			mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER_PROCESS, "%s: Didn't find a valid data string, giving up", __func__);
			return(NULL);
		}
		memcpy ((gpointer)data_ptr, big_value,
			unicode_chars ((const gunichar2*)data_ptr) * sizeof(gunichar2));
		g_free (big_value);

		data_ptr = ((gunichar2 *)data_ptr) + block->value_len;
	}

	return(data_ptr);
}

/* Returns a pointer to the byte following the Stringtable block, or
 * NULL if the data read hits padding.  We can't recover from this
 * because the data length does not include padding bytes, so it's not
 * possible to just return the start position + length
 */
static gconstpointer
big_up_stringtable_block (gconstpointer data_ptr, version_data *block)
{
	guint16 data_len = block->data_len;
	guint16 string_len = 36; /* length of the StringFileInfo block */
	gchar *big_value;

	/* data_ptr is pointing at an array of StringTable blocks,
	 * with total length (not including alignment padding) of
	 * data_len
	 */

	while(string_len < data_len) {
		/* align on a 32-bit boundary */
		ALIGN32 (data_ptr);

		data_ptr = get_versioninfo_block (data_ptr, block);
		if (block->data_len == 0) {
			/* We must have hit padding, so give up
			 * processing now
			 */
			mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER_PROCESS, "%s: Hit 0-length block, giving up", __func__);
			return(NULL);
		}

		string_len = string_len + block->data_len;

		big_value = g_convert ((gchar *)block->key, 16, "UTF-16BE",
				       "UTF-16LE", NULL, NULL, NULL);
		if (big_value == NULL) {
			mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER_PROCESS, "%s: Didn't find a valid string, giving up", __func__);
			return(NULL);
		}

		memcpy (block->key, big_value, 16);
		g_free (big_value);

		data_ptr = big_up_string_block (data_ptr, block);

		if (data_ptr == NULL) {
			/* Child block hit padding */
			mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER_PROCESS, "%s: Child block hit 0-length block, giving up", __func__);
			return(NULL);
		}
	}

	return(data_ptr);
}

/* Follows the data structures and turns all UTF-16 strings from the
 * LE found in the resource section into UTF-16BE
 */
static void
big_up (gconstpointer datablock, guint32 size)
{
	gconstpointer data_ptr;
	gint32 data_len; /* signed to guard against underflow */
	version_data block;

	data_ptr = get_fixedfileinfo_block (datablock, &block);
	if (data_ptr != NULL) {
		VS_FIXEDFILEINFO *ffi = (VS_FIXEDFILEINFO *)data_ptr;

		/* Byteswap all the fields */
		ffi->dwFileVersionMS = GUINT32_SWAP_LE_BE (ffi->dwFileVersionMS);
		ffi->dwFileVersionLS = GUINT32_SWAP_LE_BE (ffi->dwFileVersionLS);
		ffi->dwProductVersionMS = GUINT32_SWAP_LE_BE (ffi->dwProductVersionMS);
		ffi->dwProductVersionLS = GUINT32_SWAP_LE_BE (ffi->dwProductVersionLS);
		ffi->dwFileFlagsMask = GUINT32_SWAP_LE_BE (ffi->dwFileFlagsMask);
		ffi->dwFileFlags = GUINT32_SWAP_LE_BE (ffi->dwFileFlags);
		ffi->dwFileOS = GUINT32_SWAP_LE_BE (ffi->dwFileOS);
		ffi->dwFileType = GUINT32_SWAP_LE_BE (ffi->dwFileType);
		ffi->dwFileSubtype = GUINT32_SWAP_LE_BE (ffi->dwFileSubtype);
		ffi->dwFileDateMS = GUINT32_SWAP_LE_BE (ffi->dwFileDateMS);
		ffi->dwFileDateLS = GUINT32_SWAP_LE_BE (ffi->dwFileDateLS);

		/* The FFI and header occupies the first 92 bytes
		 */
		data_ptr = (char *)data_ptr + sizeof(VS_FIXEDFILEINFO);
		data_len = block.data_len - 92;

		/* There now follow zero or one StringFileInfo blocks
		 * and zero or one VarFileInfo blocks
		 */
		while (data_len > 0) {
			/* align on a 32-bit boundary */
			ALIGN32 (data_ptr);

			data_ptr = get_versioninfo_block (data_ptr, &block);
			if (block.data_len == 0) {
				/* We must have hit padding, so give
				 * up processing now
				 */
				mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER_PROCESS, "%s: Hit 0-length block, giving up", __func__);
				return;
			}

			data_len = data_len - block.data_len;

			if (unicode_string_equals (block.key, "VarFileInfo")) {
				data_ptr = get_varfileinfo_block (data_ptr,
								  &block);
				data_ptr = ((guchar *)data_ptr) + block.value_len;
			} else if (unicode_string_equals (block.key,
							  "StringFileInfo")) {
				data_ptr = big_up_stringtable_block (data_ptr,
								     &block);
			} else {
				/* Bogus data */
				mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER_PROCESS, "%s: Not a valid VERSIONINFO child block", __func__);
				return;
			}

			if (data_ptr == NULL) {
				/* Child block hit padding */
				mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER_PROCESS, "%s: Child block hit 0-length block, giving up", __func__);
				return;
			}
		}
	}
}
#endif

gboolean
mono_w32process_get_fileversion_info (const gunichar2 *filename, gpointer *data)
{
	gpointer file_map;
	gpointer versioninfo;
	void *map_handle;
	guint32 map_size;
	gsize datasize;

	g_assert (data);
	*data = NULL;

	file_map = mono_pe_file_map (filename, &map_size, &map_handle);
	if (!file_map)
		return FALSE;

	versioninfo = find_pe_file_resources (file_map, map_size, RT_VERSION, 0, &datasize);
	if (!versioninfo) {
		mono_pe_file_unmap (file_map, map_handle);
		return FALSE;
	}

	*data = g_malloc0 (datasize);

	/* This could probably process the data so that mono_w32process_ver_query_value() doesn't have to follow the
	 * data blocks every time. But hey, these functions aren't likely to appear in many profiles. */
	memcpy (*data, versioninfo, datasize);

#if G_BYTE_ORDER == G_BIG_ENDIAN
	big_up (*data, datasize);
#endif

	mono_pe_file_unmap (file_map, map_handle);

	return TRUE;
}

gboolean
mono_w32process_ver_query_value (gconstpointer datablock, const gunichar2 *subblock, gpointer *buffer, guint32 *len)
{
	gchar *subblock_utf8, *lang_utf8 = NULL;
	gboolean ret = FALSE;
	version_data block;
	gconstpointer data_ptr;
	gint32 data_len; /* signed to guard against underflow */
	gboolean want_var = FALSE;
	gboolean want_string = FALSE;
	gunichar2 lang[8];
	const gunichar2 *string_key = NULL;
	gpointer string_value = NULL;
	guint32 string_value_len = 0;
	gchar *lowercase_lang;

	subblock_utf8 = g_utf16_to_utf8 (subblock, -1, NULL, NULL, NULL);
	if (subblock_utf8 == NULL) {
		return(FALSE);
	}

	if (!strcmp (subblock_utf8, "\\VarFileInfo\\Translation")) {
		want_var = TRUE;
	} else if (!strncmp (subblock_utf8, "\\StringFileInfo\\", 16)) {
		want_string = TRUE;
		memcpy (lang, subblock + 16, 8 * sizeof(gunichar2));
		lang_utf8 = g_utf16_to_utf8 (lang, 8, NULL, NULL, NULL);
		lowercase_lang = g_utf8_strdown (lang_utf8, -1);
		g_free (lang_utf8);
		lang_utf8 = lowercase_lang;
		lowercase_lang = NULL;
		string_key = subblock + 25;
	}

	if (!strcmp (subblock_utf8, "\\")) {
		data_ptr = get_fixedfileinfo_block (datablock, &block);
		if (data_ptr != NULL) {
			*buffer = (gpointer)data_ptr;
			*len = block.value_len;

			ret = TRUE;
		}
	} else if (want_var || want_string) {
		data_ptr = get_fixedfileinfo_block (datablock, &block);
		if (data_ptr != NULL) {
			/* The FFI and header occupies the first 92
			 * bytes
			 */
			data_ptr = (char *)data_ptr + sizeof(VS_FIXEDFILEINFO);
			data_len = block.data_len - 92;

			/* There now follow zero or one StringFileInfo
			 * blocks and zero or one VarFileInfo blocks
			 */
			while (data_len > 0) {
				/* align on a 32-bit boundary */
				ALIGN32 (data_ptr);

				data_ptr = get_versioninfo_block (data_ptr,
								  &block);
				if (block.data_len == 0) {
					/* We must have hit padding,
					 * so give up processing now
					 */
					mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER_PROCESS, "%s: Hit 0-length block, giving up", __func__);
					goto done;
				}

				data_len = data_len - block.data_len;

				if (unicode_string_equals (block.key, "VarFileInfo")) {
					data_ptr = get_varfileinfo_block (data_ptr, &block);
					if (want_var) {
						*buffer = (gpointer)data_ptr;
						*len = block.value_len;
						ret = TRUE;
						goto done;
					} else {
						/* Skip over the Var block */
						data_ptr = ((guchar *)data_ptr) + block.value_len;
					}
				} else if (unicode_string_equals (block.key, "StringFileInfo")) {
					data_ptr = get_stringtable_block (data_ptr, lang_utf8, string_key, &string_value, &string_value_len, &block);
					if (want_string &&
					    string_value != NULL &&
					    string_value_len != 0) {
						*buffer = string_value;
						*len = unicode_chars ((const gunichar2 *)string_value) + 1; /* Include trailing null */
						ret = TRUE;
						goto done;
					}
				} else {
					/* Bogus data */
					mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER_PROCESS, "%s: Not a valid VERSIONINFO child block", __func__);
					goto done;
				}

				if (data_ptr == NULL) {
					/* Child block hit padding */
					mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER_PROCESS, "%s: Child block hit 0-length block, giving up", __func__);
					goto done;
				}
			}
		}
	}

  done:
	if (lang_utf8) {
		g_free (lang_utf8);
	}

	g_free (subblock_utf8);
	return(ret);
}

#endif /* !defined(DISABLE_PROCESSES) */