oscall 0.1.1

Low-level cross-platform interface to operating system services: files, memory mapping, networking and more, with no libc on Linux
Documentation
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
//! `oscall::process`: the current process, and child processes.
//!
//! The children are system programs: `/bin/sh` on Linux and macOS,
//! `cmd.exe` and `findstr.exe` on Windows. The few tests that need a child
//! that calls oscall run this test binary again, and skip themselves where
//! the system cannot execute it (a foreign binary run by an emulator).

mod common;

use oscall::process;

#[test]
fn ids() {
    #[cfg(not(target_family = "wasm"))]
    {
        assert_eq!(process::id(), std::process::id());
        assert_ne!(process::parent_id(), 0);
        assert_ne!(process::parent_id(), process::id());
    }
    #[cfg(unix)]
    assert_eq!(process::parent_id(), std::os::unix::process::parent_id());
    #[cfg(target_family = "wasm")]
    {
        assert_eq!(process::id(), 0);
        assert_eq!(process::parent_id(), 0);
    }
}

/// The arguments of this process, which are the test harness's: the same
/// as `std` has.
#[test]
fn arguments() {
    use oscall::ErrorKind;

    let expected: Vec<Vec<u8>> = std::env::args_os()
        .map(|arg| arg.as_encoded_bytes().to_vec())
        .collect();
    assert!(!expected.is_empty());
    let mut buf = vec![0u8; 1 << 16];
    let args: Vec<Vec<u8>> = process::args(&mut buf)
        .unwrap()
        .map(<[u8]>::to_vec)
        .collect();
    assert_eq!(args, expected);
    #[cfg(feature = "alloc")]
    assert_eq!(process::args_vec().unwrap(), expected);

    // A buffer that cannot hold them, and one that holds them exactly
    // (four more bytes each on WASI, for the pointers the host writes, and
    // up to three for their alignment).
    let size: usize = expected.iter().map(|arg| arg.len() + 1).sum();
    for small in [0, 1, size - 1] {
        let error = process::args(&mut buf[..small]).unwrap_err();
        assert_eq!(error.kind(), ErrorKind::BufferTooSmall, "{small}");
    }
    let size = if cfg!(target_os = "wasi") {
        size + 4 * expected.len() + 3
    } else {
        size
    };
    let exact: Vec<&[u8]> = process::args(&mut buf[..size]).unwrap().collect();
    assert_eq!(exact, expected);
}

/// The environment of this process: the same as `std` has, since nothing
/// in these tests changes it.
#[test]
fn environment() {
    use oscall::ErrorKind;

    // Not the hidden variables of Windows, whose names start with `=`:
    // the system writes them itself (`=C:` is the current directory of
    // the drive), and one appeared between two readings while the other
    // tests ran (seen on the 32-bit runner: the second list had `=C:` and
    // the first did not).
    let stable = |(name, _): &(Vec<u8>, Vec<u8>)| !name.starts_with(b"=");
    let mut expected: Vec<(Vec<u8>, Vec<u8>)> = std::env::vars_os()
        .map(|(name, value)| {
            (
                name.as_encoded_bytes().to_vec(),
                value.as_encoded_bytes().to_vec(),
            )
        })
        .filter(stable)
        .collect();
    expected.sort();
    let mut buf = vec![0u8; 1 << 20];
    let mut vars: Vec<(Vec<u8>, Vec<u8>)> = process::vars(&mut buf)
        .unwrap()
        .map(|(name, value)| (name.to_vec(), value.to_vec()))
        .filter(stable)
        .collect();
    vars.sort();
    assert_eq!(vars, expected);
    #[cfg(feature = "alloc")]
    {
        let mut vars = process::vars_vec().unwrap();
        vars.retain(stable);
        vars.sort();
        assert_eq!(vars, expected);
    }
    if !expected.is_empty() {
        let error = process::vars(&mut buf[..1]).unwrap_err();
        assert_eq!(error.kind(), ErrorKind::BufferTooSmall);
    }
    // CI gives the WASI host one variable to hand over: its environment
    // is empty otherwise, and would test nothing.
    if let Some(value) = std::env::var_os("OSCALL_TEST_ENV") {
        assert!(
            vars.iter().any(
                |(name, found)| name == b"OSCALL_TEST_ENV" && found == value.as_encoded_bytes()
            )
        );
    }
}

/// There are no processes on WebAssembly.
#[test]
#[cfg(all(feature = "alloc", target_family = "wasm"))]
fn spawn_unsupported() {
    use oscall::process::{Command, Stdio};

    let error = Command::new("/bin/sh")
        .args(&["-c", "exit 0"])
        .stdin(Stdio::Null)
        .spawn()
        .unwrap_err();
    assert_eq!(error.kind(), oscall::ErrorKind::Unsupported);
}

/// There are no programs to find either, and no process to name.
#[test]
#[cfg(target_family = "wasm")]
fn processes_unsupported() {
    use oscall::ErrorKind;

    let mut buf = [0u8; 64];
    let error = process::find_program("sh", "/bin", &mut buf).unwrap_err();
    assert_eq!(error.kind(), ErrorKind::Unsupported);
    #[cfg(feature = "alloc")]
    assert_eq!(
        process::find_program_vec("sh", "/bin").unwrap_err().kind(),
        ErrorKind::Unsupported
    );
    assert_eq!(
        process::exists(1).unwrap_err().kind(),
        ErrorKind::Unsupported
    );
    assert_eq!(process::kill(1).unwrap_err().kind(), ErrorKind::Unsupported);
    assert_eq!(
        process::resource_usage().unwrap_err().kind(),
        ErrorKind::Unsupported
    );
    assert_eq!(
        process::exists(0).unwrap_err().kind(),
        ErrorKind::InvalidInput
    );
}

/// What `find_program` refuses on every system that has programs.
#[test]
#[cfg(not(target_family = "wasm"))]
fn find_program_errors() {
    use oscall::ErrorKind;

    let mut buf = [0u8; 256];
    let dir = common::tmp_dir("process_find_program_errors");
    let dir = dir.to_str().unwrap();
    for (name, path) in [("a\0", dir), ("a", "x\0y")] {
        let error = process::find_program(name, path, &mut buf).unwrap_err();
        assert_eq!(error.kind(), ErrorKind::InvalidInput, "{error:?}");
    }
    for (name, path) in [
        ("", dir),
        ("missing", dir),
        ("missing", ""),
        ("missing", ";:"),
    ] {
        let error = process::find_program(name, path, &mut buf).unwrap_err();
        assert_eq!(error.kind(), ErrorKind::NotFound, "{error:?}");
    }
    // A candidate that does not fit cannot be checked.
    let error = process::find_program("missing", dir, &mut buf[..4]).unwrap_err();
    assert_eq!(error.kind(), ErrorKind::BufferTooSmall, "{error:?}");
}

#[test]
#[cfg(any(target_os = "linux", target_os = "fullrust", target_os = "macos"))]
fn find_program() {
    use oscall::ErrorKind;
    use std::os::unix::fs::PermissionsExt;

    let dir = common::tmp_dir("process_find_program");
    let file = |name: &str, mode: u32| {
        let path = dir.join(name);
        std::fs::write(&path, "#!/bin/sh\nexit 0\n").unwrap();
        std::fs::set_permissions(&path, std::fs::Permissions::from_mode(mode)).unwrap();
    };
    for sub in ["a", "b", "a/folder", "b/folder"] {
        std::fs::create_dir(dir.join(sub)).unwrap();
    }
    file("a/both", 0o755);
    file("b/both", 0o755);
    file("a/second", 0o644);
    file("b/second", 0o700);
    file("b/data", 0o644);
    std::os::unix::fs::symlink("both", dir.join("b/link")).unwrap();
    std::os::unix::fs::symlink("nowhere", dir.join("a/link")).unwrap();

    let dir = dir.to_str().unwrap();
    let path = format!("{dir}/missing::{dir}/a:{dir}/b/:");
    let find = |name: &str| {
        let mut buf = [0u8; 512];
        let found = process::find_program(name, path.as_str(), &mut buf)
            .map(|len| String::from_utf8(buf[..len].to_vec()).unwrap());
        #[cfg(feature = "alloc")]
        assert_eq!(
            process::find_program_vec(name, path.as_str())
                .map(|found| String::from_utf8(found).unwrap()),
            found
        );
        found
    };
    // The first directory that has it wins.
    assert_eq!(find("both").unwrap(), format!("{dir}/a/both"));
    // A file that may not be executed is passed over; a directory that
    // ends with a separator gets no other.
    assert_eq!(find("second").unwrap(), format!("{dir}/b/second"));
    // A link is followed, a dangling one is not a program.
    assert_eq!(find("link").unwrap(), format!("{dir}/b/link"));
    for name in ["data", "folder", "missing", ".", ".."] {
        assert_eq!(
            find(name).unwrap_err().kind(),
            ErrorKind::NotFound,
            "{name}"
        );
    }
    // A path is not searched for, only checked.
    let both = format!("{dir}/b/both");
    assert_eq!(find(&both).unwrap(), both);
    assert_eq!(find("a/both").unwrap_err().kind(), ErrorKind::NotFound);
    let data = format!("{dir}/b/data");
    assert_eq!(find(&data).unwrap_err().kind(), ErrorKind::NotFound);
    // The buffer must hold every candidate tried, and the result exactly.
    let mut buf = [0u8; 512];
    let path = format!("{dir}/a");
    let len = dir.len() + "/a/both".len();
    assert_eq!(
        process::find_program("both", path.as_str(), &mut buf[..len]),
        Ok(len)
    );
    assert_eq!(
        process::find_program("both", path.as_str(), &mut buf[..len - 1])
            .unwrap_err()
            .kind(),
        ErrorKind::BufferTooSmall
    );
}

#[test]
#[cfg(windows)]
fn find_program() {
    use oscall::ErrorKind;

    let root = std::env::var("SystemRoot").unwrap();
    let dir = common::tmp_dir("process_find_program");
    std::fs::write(dir.join("data"), "x").unwrap();
    std::fs::write(dir.join("tool.exe"), "x").unwrap();
    std::fs::write(dir.join("script.cmd"), "x").unwrap();
    std::fs::create_dir(dir.join("folder.exe")).unwrap();
    let dir = dir.to_str().unwrap();
    let path = format!("{dir}\\missing;;\"{dir}\";{root}\\System32\\;{root}");
    let find = |name: &str| {
        let mut buf = [0u8; 512];
        let found = process::find_program(name, path.as_str(), &mut buf)
            .map(|len| String::from_utf8(buf[..len].to_vec()).unwrap());
        #[cfg(feature = "alloc")]
        assert_eq!(
            process::find_program_vec(name, path.as_str())
                .map(|found| String::from_utf8(found).unwrap()),
            found
        );
        found
    };
    // `.exe` is added to a name without an extension, and only then.
    assert_eq!(find("cmd").unwrap(), format!("{root}\\System32\\cmd.exe"));
    assert_eq!(
        find("cmd.exe").unwrap(),
        format!("{root}\\System32\\cmd.exe")
    );
    assert_eq!(find("tool").unwrap(), format!("{dir}\\tool.exe"));
    assert_eq!(find("script.cmd").unwrap(), format!("{dir}\\script.cmd"));
    for name in [
        "data",
        "script",
        "folder",
        "folder.exe",
        "cmd.com",
        "missing",
    ] {
        assert_eq!(
            find(name).unwrap_err().kind(),
            ErrorKind::NotFound,
            "{name}"
        );
    }
    // A path is not searched for, only checked, and nothing is added.
    let cmd = format!("{root}\\System32\\cmd.exe");
    assert_eq!(find(&cmd).unwrap(), cmd);
    let bare = format!("{root}\\System32\\cmd");
    assert_eq!(find(&bare).unwrap_err().kind(), ErrorKind::NotFound);
    assert_eq!(
        find("System32\\cmd.exe").unwrap_err().kind(),
        ErrorKind::NotFound
    );
    assert_eq!(find("C:cmd.exe").unwrap_err().kind(), ErrorKind::NotFound);
}

#[test]
#[cfg(not(target_family = "wasm"))]
fn pid_errors() {
    use oscall::ErrorKind;

    assert_eq!(process::exists(process::id()), Ok(true));
    for pid in [0, u32::MAX, 1 << 31] {
        let error = process::exists(pid).unwrap_err();
        assert_eq!(error.kind(), ErrorKind::InvalidInput, "{error:?}");
        let error = process::kill(pid).unwrap_err();
        assert_eq!(error.kind(), ErrorKind::InvalidInput, "{error:?}");
    }
}

/// What the process has consumed grows with what it does.
#[test]
#[cfg(not(target_family = "wasm"))]
fn resource_usage() {
    use oscall::time::Clock;
    use std::time::Duration;

    const BLOCK: usize = 48 << 20;
    let total = |usage: process::ResourceUsage| usage.user_time() + usage.system_time();

    let before = process::resource_usage().unwrap();
    // Not on Linux, whose count of resident pages is approximate: see
    // `child_resource_usage`.
    if !cfg!(any(target_os = "linux", target_os = "fullrust")) {
        assert!(before.max_resident_memory() > 0);
    }
    // Memory that is really used, and a tenth of a second of processor.
    let mut block = vec![0u8; BLOCK];
    for at in (0..BLOCK).step_by(512) {
        block[at] = at as u8;
    }
    let start = Clock::ProcessCpu.now().unwrap();
    let mut sum = 0u64;
    while Clock::ProcessCpu.now().unwrap() - start < Duration::from_millis(100) {
        for byte in block.iter().step_by(4096) {
            sum = sum.wrapping_mul(31).wrapping_add(u64::from(*byte));
        }
    }
    std::hint::black_box(sum);
    let after = process::resource_usage().unwrap();
    let clock = Clock::ProcessCpu.now().unwrap();
    drop(block);

    let peak = after.max_resident_memory();
    // Linux counts resident pages approximately (per processor, in
    // batches): most of the block is there.
    assert!(peak >= BLOCK as u64 / 2, "{peak}");
    assert!(peak >= before.max_resident_memory(), "{before:?} {after:?}");
    assert!(peak < 1 << 44, "{peak}");
    // The times are those of the clock, as coarsely as the system counts
    // them (in clock ticks on Windows, of up to 1/64 second).
    let spent = total(after).saturating_sub(total(before));
    assert!(spent >= Duration::from_millis(50), "{before:?} {after:?}");
    assert!(
        total(after) <= clock + Duration::from_millis(100),
        "{after:?} {clock:?}"
    );
}

/// The limits of the process, and that they can be changed: the size of a
/// core dump is the one limit nothing else in the tests depends on.
#[test]
#[cfg(any(target_os = "linux", target_os = "fullrust", target_os = "macos"))]
fn limits() {
    use oscall::ErrorKind;
    use oscall::process::unix::{self, Limit, Resource};

    for resource in [
        Resource::OpenFiles,
        Resource::Stack,
        Resource::CoreSize,
        Resource::FileSize,
        Resource::CpuTime,
        Resource::AddressSpace,
        Resource::Data,
        Resource::LockedMemory,
        Resource::Processes,
    ] {
        let limit = unix::limit(resource).unwrap();
        if let (Some(soft), Some(hard)) = (limit.soft, limit.hard) {
            assert!(soft <= hard, "{resource:?}: {limit:?}");
        }
        // Setting what is there changes nothing, and is allowed. Not for
        // the number of processes on macOS, whose hard limit the system
        // lowers to `kern.maxprocperuid` when it is set (seen: 3132, set
        // again, reads 2088).
        let adjusted = cfg!(target_os = "macos") && resource == Resource::Processes;
        if !adjusted && (resource != Resource::OpenFiles || limit.soft.is_some()) {
            unix::set_limit(resource, limit).unwrap();
            assert_eq!(unix::limit(resource), Ok(limit), "{resource:?}");
        }
    }
    // This process has files open, and may open more.
    let files = unix::limit(Resource::OpenFiles).unwrap();
    assert!(files.soft.is_none_or(|soft| soft > 3), "{files:?}");

    let core = unix::limit(Resource::CoreSize).unwrap();
    let none = Limit {
        soft: Some(0),
        hard: core.hard,
    };
    unix::set_limit(Resource::CoreSize, none).unwrap();
    let seen = unix::limit(Resource::CoreSize);
    // A process created now starts with it.
    let child = std::process::Command::new("/bin/sh")
        .args(["-c", "ulimit -c"])
        .output();
    // A soft limit above the hard one, and a value the system takes for
    // "no limit".
    let above = core.hard.map(|hard| {
        unix::set_limit(
            Resource::CoreSize,
            Limit {
                soft: Some(hard + 1),
                hard: Some(hard),
            },
        )
    });
    let huge = unix::set_limit(
        Resource::CoreSize,
        Limit {
            soft: Some(u64::MAX),
            hard: core.hard,
        },
    );
    unix::set_limit(Resource::CoreSize, core).unwrap();
    assert_eq!(unix::limit(Resource::CoreSize), Ok(core));

    assert_eq!(seen, Ok(none));
    assert_eq!(String::from_utf8_lossy(&child.unwrap().stdout).trim(), "0");
    if let Some(above) = above {
        let error = above.unwrap_err();
        assert_eq!(error.kind(), ErrorKind::InvalidInput, "{error:?}");
    }
    let error = huge.unwrap_err();
    assert_eq!(error.kind(), ErrorKind::InvalidInput, "{error:?}");
}

/// The child half of the tests that run this binary again: does what the
/// `OSCALL_TEST_HELPER` variable says, and nothing in an ordinary run.
#[test]
#[cfg(not(target_family = "wasm"))]
fn helper_child_process() {
    let Some(mode) = std::env::var_os("OSCALL_TEST_HELPER") else {
        return;
    };
    let mode = mode.into_string().unwrap();
    if let Some(code) = mode.strip_prefix("exit:") {
        process::exit(code.parse().unwrap());
    } else if mode == "abort" {
        process::abort();
    } else if let Some(file) = mode.strip_prefix("ids:") {
        let ids = format!("{} {}", process::id(), process::parent_id());
        std::fs::write(file, ids).unwrap();
        process::exit(0);
    } else if let Some(file) = mode.strip_prefix("args:") {
        // What follows `--` on the command line, each followed by a NUL.
        let mut out = Vec::new();
        for arg in std::env::args_os().skip_while(|arg| arg != "--").skip(1) {
            out.extend_from_slice(arg.as_encoded_bytes());
            out.push(0);
        }
        std::fs::write(file, out).unwrap();
        process::exit(0);
    } else if let Some(file) = mode.strip_prefix("oscall-args:") {
        // The same, as oscall reads them, and then the variables of the
        // environment whose names start with `OSCALL_T_`.
        let mut buf = vec![0u8; 1 << 16];
        let mut out = Vec::new();
        for arg in process::args(&mut buf)
            .unwrap()
            .skip_while(|arg| *arg != b"--")
            .skip(1)
        {
            out.extend_from_slice(arg);
            out.push(0);
        }
        out.push(0xff);
        let mut buf = vec![0u8; 1 << 20];
        for (name, value) in process::vars(&mut buf).unwrap() {
            if name.starts_with(b"OSCALL_T_") {
                out.extend_from_slice(name);
                out.push(0);
                out.extend_from_slice(value);
                out.push(0);
            }
        }
        std::fs::write(file, out).unwrap();
        process::exit(0);
    }
    #[cfg(all(
        feature = "alloc",
        any(target_os = "linux", target_os = "fullrust", windows)
    ))]
    if let Some(kind) = mode.strip_prefix("orphan:") {
        children::orphan_helper(kind == "tied");
    }
    #[cfg(all(feature = "alloc", windows))]
    if mode == "bare-job" {
        children::bare_job_helper();
    }
    #[cfg(all(feature = "alloc", not(windows)))]
    if mode == "fork" {
        children::fork_helper();
    }
    panic!("unknown helper mode {mode}");
}

#[cfg(all(feature = "alloc", not(target_family = "wasm")))]
mod children {
    use std::fs::File;
    use std::path::{Path, PathBuf};
    use std::sync::mpsc;
    use std::time::{Duration, Instant};

    use oscall::process::{Child, Command, ExitStatus, Stdio};
    use oscall::{AsHandle, Error, ErrorKind, OwnedHandle, io};

    use super::common::{handle_of, tmp_dir};

    /// A path as oscall takes one, whatever its features.
    fn bytes(path: &Path) -> &[u8] {
        path.as_os_str().as_encoded_bytes()
    }

    /// The system's command interpreter.
    #[cfg(not(windows))]
    fn shell() -> String {
        "/bin/sh".to_owned()
    }
    #[cfg(windows)]
    fn shell() -> String {
        system32("cmd.exe")
    }
    #[cfg(windows)]
    fn system32(name: &str) -> String {
        format!("{}\\System32\\{name}", std::env::var("SystemRoot").unwrap())
    }

    /// The option of [`shell`] that takes a command.
    const RUN: &str = if cfg!(windows) { "/C" } else { "-c" };

    /// A program and its arguments that copy the lines of standard input
    /// that have an `x` to standard output, until the end of the input.
    fn filter() -> (String, Vec<&'static str>) {
        #[cfg(windows)]
        return (system32("findstr.exe"), vec!["x"]);
        #[cfg(not(windows))]
        return (
            shell(),
            vec![
                "-c",
                r#"while read -r line; do case "$line" in *x*) echo "$line";; esac; done"#,
            ],
        );
    }

    fn write_all(handle: impl AsHandle, mut buf: &[u8]) {
        while !buf.is_empty() {
            let n = io::write(handle.as_handle(), buf).unwrap();
            assert!(n > 0);
            buf = &buf[n..];
        }
    }

    fn read_bytes(handle: impl AsHandle) -> Vec<u8> {
        let mut out = Vec::new();
        let mut buf = [0u8; 4096];
        loop {
            match io::read(handle.as_handle(), &mut buf) {
                Ok(0) => break,
                Ok(n) => out.extend_from_slice(&buf[..n]),
                // Windows reports the closed pipe as an error.
                Err(error) if error.kind() == ErrorKind::BrokenPipe => break,
                Err(error) => panic!("read failed: {error}"),
            }
        }
        out
    }

    /// Reads to the end, and returns the text without the carriage returns
    /// Windows programs write.
    fn read_text(handle: impl AsHandle) -> String {
        String::from_utf8_lossy(&read_bytes(handle)).replace('\r', "")
    }

    /// Waits for the child, for a limited time.
    fn wait(child: &mut Child) -> ExitStatus {
        let start = Instant::now();
        loop {
            if let Some(status) = child.try_wait().unwrap() {
                // The answer does not change.
                assert_eq!(child.wait().unwrap(), status);
                assert_eq!(child.try_wait().unwrap(), Some(status));
                return status;
            }
            if start.elapsed() > Duration::from_secs(60) {
                child.kill().unwrap();
                panic!("the child did not exit");
            }
            std::thread::sleep(Duration::from_millis(2));
        }
    }

    struct Output {
        status: ExitStatus,
        stdout: String,
        stderr: String,
    }

    #[derive(Default)]
    struct Options<'a> {
        env: Option<&'a [String]>,
        dir: Option<&'a Path>,
        arg0: Option<&'a str>,
    }

    /// Runs a shell command with no input and collects what it writes
    /// (which must fit in the pipes).
    fn run_with(script: &str, options: &Options<'_>) -> Output {
        let (out_read, out_write) = io::pipe().unwrap();
        let (err_read, err_write) = io::pipe().unwrap();
        let shell = shell();
        let args = [RUN, script];
        let mut command = Command::new(&shell)
            .args(&args)
            .stdin(Stdio::Null)
            .stdout(Stdio::Handle(out_write.as_handle()))
            .stderr(Stdio::Handle(err_write.as_handle()));
        if let Some(env) = options.env {
            command = command.env(env);
        }
        if let Some(dir) = options.dir {
            command = command.current_dir(bytes(dir));
        }
        if let Some(arg0) = options.arg0 {
            command = command.arg0(arg0);
        }
        let mut child = command.spawn().unwrap();
        assert_ne!(child.id(), 0);
        assert_ne!(child.id(), oscall::process::id());
        drop((out_write, err_write));
        let stdout = read_text(&out_read);
        let stderr = read_text(&err_read);
        Output {
            status: wait(&mut child),
            stdout,
            stderr,
        }
    }

    fn run(script: &str) -> Output {
        run_with(script, &Options::default())
    }

    #[test]
    fn exit_codes() {
        for code in [0, 1, 7, 42, 255] {
            let output = run(&format!("exit {code}"));
            assert_eq!(output.status.code(), Some(code));
            assert_eq!(output.status.success(), code == 0);
            assert_eq!(output.stdout, "");
            assert_eq!(output.stderr, "");
            assert!(format!("{:?} {}", output.status, output.status).contains(&code.to_string()));
            #[cfg(not(windows))]
            {
                use oscall::process::unix::ExitStatusExt;
                assert_eq!(output.status.signal(), None);
                assert!(!output.status.core_dumped());
            }
        }
    }

    #[test]
    fn output_and_error() {
        let script = if cfg!(windows) {
            "echo out& echo err>&2"
        } else {
            "echo out; echo err >&2"
        };
        let output = run(script);
        assert!(output.status.success());
        assert_eq!(output.stdout, "out\n");
        assert_eq!(output.stderr, "err\n");
    }

    /// One handle for both outputs, as a shell's `2>&1`.
    #[test]
    fn shared_output() {
        let script = if cfg!(windows) {
            "echo out& echo err>&2"
        } else {
            "echo out; echo err >&2"
        };
        let (read, write) = io::pipe().unwrap();
        let shell = shell();
        let mut child = Command::new(&shell)
            .args(&[RUN, script])
            .stdin(Stdio::Null)
            .stdout(Stdio::Handle(write.as_handle()))
            .stderr(Stdio::Handle(write.as_handle()))
            .spawn()
            .unwrap();
        drop(write);
        assert_eq!(read_text(&read), "out\nerr\n");
        assert!(wait(&mut child).success());
    }

    /// Arguments reach the program byte for byte. On Linux and macOS the
    /// shell prints its own arguments.
    #[test]
    #[cfg(not(windows))]
    fn arguments() {
        let script = r#"for arg in "$@"; do printf '[%s]\n' "$arg"; done"#;
        let args: Vec<Vec<u8>> = [
            &b"-c"[..],
            script.as_bytes(),
            b"name",
            b"plain",
            b"two words",
            b"",
            b"  spaces  ",
            b"tab\there",
            br#"quote"inside"#,
            br#""quoted""#,
            br"back\slash",
            br"trailing\",
            br#"both\"of them\\"#,
            b"'single'",
            b"$HOME `id` $(id) ; & | > < * ? ~ # !",
            b"%PATH% ^ %%",
            "h\u{e9}llo \u{4e16}\u{754c} \u{1f600}".as_bytes(),
            b"not utf-8: \xff\xfe\x80",
            b"-n",
            b"--",
        ]
        .iter()
        .map(|arg| arg.to_vec())
        .collect();
        let mut expected = Vec::new();
        for arg in &args[3..] {
            expected.push(b'[');
            expected.extend_from_slice(arg);
            expected.extend_from_slice(b"]\n");
        }

        let (read, write) = io::pipe().unwrap();
        let mut child = Command::new("/bin/sh")
            .args(&args)
            .stdin(Stdio::Null)
            .stdout(Stdio::Handle(write.as_handle()))
            .spawn()
            .unwrap();
        drop(write);
        let out = read_bytes(&read);
        assert!(wait(&mut child).success());
        assert_eq!(out, expected);
    }

    /// `$0` is the program by default, and what `arg0` says otherwise.
    #[test]
    #[cfg(not(windows))]
    fn arg0() {
        let output = run(r#"printf %s "$0""#);
        assert_eq!(output.stdout, "/bin/sh");
        let options = Options {
            arg0: Some("another name"),
            ..Options::default()
        };
        let output = run_with(r#"printf %s "$0""#, &options);
        assert_eq!(output.stdout, "another name");
    }

    /// An argument cannot hold a NUL, nor can anything else.
    #[test]
    fn nul_is_refused() {
        let shell = shell();
        let invalid = |command: Command<'_>| {
            assert_eq!(command.spawn().unwrap_err().kind(), ErrorKind::InvalidInput);
        };
        invalid(Command::new(&shell).args(&[RUN, "exit\0 0"]));
        invalid(Command::new(&shell).args(&[RUN, "exit 0"]).env(&["A=\0"]));
        invalid(
            Command::new(&shell)
                .args(&[RUN, "exit 0"])
                .current_dir("a\0"),
        );
        invalid(Command::new(&shell).args(&[RUN, "exit 0"]).arg0("a\0"));
        invalid(Command::new("a\0b"));
    }

    /// The environment of this process, and what tells the helper its
    /// `mode`.
    fn helper_env(mode: &str) -> Vec<Vec<u8>> {
        let mut env: Vec<Vec<u8>> = std::env::vars_os()
            .filter(|(name, _)| name != "OSCALL_TEST_HELPER")
            .map(|(name, value)| [name.as_encoded_bytes(), b"=", value.as_encoded_bytes()].concat())
            .collect();
        env.push(format!("OSCALL_TEST_HELPER={mode}").into_bytes());
        env
    }

    /// Runs this test binary as the helper `mode`, with `args` after `--`.
    /// `None` where the system cannot run it.
    fn helper(mode: &str, args: &[Vec<u8>]) -> Option<ExitStatus> {
        let exe = std::env::current_exe().ok()?;
        let env = helper_env(mode);
        let mut all: Vec<Vec<u8>> = ["--exact", "--nocapture", "helper_child_process", "--"]
            .iter()
            .map(|arg| arg.as_bytes().to_vec())
            .collect();
        all.extend_from_slice(args);
        let spawned = Command::new(bytes(&exe))
            .args(&all)
            .env(&env)
            .stdin(Stdio::Null)
            .stdout(Stdio::Null)
            .stderr(Stdio::Null)
            .spawn();
        match spawned {
            Ok(mut child) => Some(wait(&mut child)),
            // The binary is for another architecture, and runs here under
            // an emulator the kernel knows nothing about.
            Err(error) if is_exec_format(error) => {
                eprintln!("skipped: the system cannot execute {}", exe.display());
                None
            }
            Err(error) => panic!("cannot run {}: {error}", exe.display()),
        }
    }

    fn is_exec_format(error: Error) -> bool {
        const ENOEXEC: i32 = 8;
        cfg!(not(any(windows, target_os = "macos"))) && error.raw_os_error() == ENOEXEC
    }

    /// A program started by `std` splits its command line the way nearly
    /// every Windows program does, which is what oscall quotes for. (The
    /// test harness refuses arguments that are not Unicode: those are for
    /// the test above.)
    #[test]
    fn arguments_through_std() {
        let dir = tmp_dir("process_arguments_through_std");
        let file = std::path::absolute(dir.join("args")).unwrap();
        let args: Vec<Vec<u8>> = [
            "plain",
            "two words",
            "",
            "  spaces  ",
            "tab\there",
            r#"quote"inside"#,
            r#""quoted""#,
            r"back\slash",
            r"trailing\",
            r"trailing space\ ",
            r"two trailing\\",
            r#"both\"of them\\"#,
            r#"\\"\\\"#,
            "'single'",
            "$HOME ; & | > < * ? ~ # ! ^ %PATH% %%",
            "h\u{e9}llo \u{4e16}\u{754c} \u{1f600}",
            "-n",
            "--",
        ]
        .iter()
        .map(|arg| arg.as_bytes().to_vec())
        .collect();
        let mode = format!("args:{}", file.display());
        let Some(status) = helper(&mode, &args) else {
            return;
        };
        assert!(status.success(), "{status}");
        let mut expected = Vec::new();
        for arg in &args {
            expected.extend_from_slice(arg);
            expected.push(0);
        }
        assert_eq!(std::fs::read(&file).unwrap(), expected);
    }

    /// A child reads with oscall the arguments and the environment it was
    /// given: on Windows that is oscall splitting the line oscall quoted.
    #[test]
    fn arguments_and_environment_of_a_child() {
        let dir = tmp_dir("process_arguments_and_environment_of_a_child");
        let file = std::path::absolute(dir.join("args")).unwrap();
        let args: Vec<Vec<u8>> = [
            "plain",
            "two words",
            "",
            "tab\there",
            r#"quote"inside"#,
            r#""quoted""#,
            r"trailing\",
            r"trailing space\ ",
            r#"both\"of them\\"#,
            r#"\\"\\\"#,
            "%PATH% ^ & |",
            "h\u{e9}llo \u{4e16}\u{754c} \u{1f600}",
            "",
        ]
        .iter()
        .map(|arg| arg.as_bytes().to_vec())
        .collect();
        let vars = [
            ("OSCALL_T_PLAIN", "value"),
            ("OSCALL_T_EMPTY", ""),
            ("OSCALL_T_EQUALS", "a=b=c"),
            ("OSCALL_T_UNICODE", "h\u{e9}llo \u{1f600}"),
            ("OSCALL_T_SPACES", " a  b "),
        ];
        let exe = match std::env::current_exe() {
            Ok(exe) => exe,
            Err(_) => return,
        };
        let mut env = helper_env(&format!("oscall-args:{}", file.display()));
        env.retain(|var| !var.starts_with(b"OSCALL_T_"));
        for (name, value) in vars {
            env.push(format!("{name}={value}").into_bytes());
        }
        let mut all: Vec<Vec<u8>> = ["--exact", "--nocapture", "helper_child_process", "--"]
            .iter()
            .map(|arg| arg.as_bytes().to_vec())
            .collect();
        all.extend_from_slice(&args);
        let spawned = Command::new(bytes(&exe))
            .args(&all)
            .env(&env)
            .stdin(Stdio::Null)
            .stdout(Stdio::Null)
            .stderr(Stdio::Null)
            .spawn();
        let status = match spawned {
            Ok(mut child) => wait(&mut child),
            Err(error) if is_exec_format(error) => {
                eprintln!("skipped: the system cannot execute {}", exe.display());
                return;
            }
            Err(error) => panic!("cannot run {}: {error}", exe.display()),
        };
        assert!(status.success(), "{status}");
        let mut expected = Vec::new();
        for arg in &args {
            expected.extend_from_slice(arg);
            expected.push(0);
        }
        expected.push(0xff);
        let written = std::fs::read(&file).unwrap();
        let (got_args, got_vars) = written.split_at(expected.len().min(written.len()));
        assert_eq!(got_args, expected);
        // The order of an environment is the system's business: Windows
        // sorts the block it is given.
        let mut got: Vec<&[u8]> = got_vars.split(|&b| b == 0).collect();
        assert_eq!(got.pop(), Some(&b""[..]));
        let mut got: Vec<(&[u8], &[u8])> = got.chunks(2).map(|pair| (pair[0], pair[1])).collect();
        got.sort();
        let mut want: Vec<(&[u8], &[u8])> = vars
            .iter()
            .map(|(name, value)| (name.as_bytes(), value.as_bytes()))
            .collect();
        want.sort();
        assert_eq!(got, want);
    }

    /// The whole command line, for the programs with their own rules.
    #[test]
    #[cfg(windows)]
    fn raw_command_line() {
        use oscall::process::windows::CommandExt;

        let (read, write) = io::pipe().unwrap();
        let shell = shell();
        let mut child = Command::new(&shell)
            .args(&["ignored"])
            .raw_command_line(r#"cmd /C echo "a  b"   c& exit 3"#)
            .stdin(Stdio::Null)
            .stdout(Stdio::Handle(write.as_handle()))
            .spawn()
            .unwrap();
        drop(write);
        assert_eq!(read_text(&read), "\"a  b\"   c\n");
        assert_eq!(wait(&mut child).code(), Some(3));
    }

    /// A batch file is not run with arguments quoted for something else.
    #[test]
    #[cfg(windows)]
    fn batch_files() {
        use oscall::process::windows::CommandExt;

        let dir = tmp_dir("process_batch_files");
        let dir = std::path::absolute(&dir).unwrap();
        let marker = dir.join("marker");
        let inject = format!("\"&echo x>{}", marker.display());
        for name in [
            "x.bat",
            "x.cmd",
            "X.BAT",
            "x.Cmd",
            "x.bat.",
            "x.bat ",
            "x.cmd. . ",
            // Spellings the system brings down to the same name.
            "x.bat\\.",
            "x.bat/.",
            "sub\\..\\x.bat",
            ".\\x.cmd\\",
        ] {
            let file = dir.join(if name.to_ascii_lowercase().contains("cmd") {
                "x.cmd"
            } else {
                "x.bat"
            });
            std::fs::write(&file, "@exit /b 7\r\n").unwrap();
            let program = dir.join(name);
            let error = Command::new(bytes(&program))
                .args(&[inject.as_str()])
                .stdin(Stdio::Null)
                .spawn()
                .unwrap_err();
            assert_eq!(error.kind(), ErrorKind::InvalidInput, "{name}: {error:?}");
            // Nor without arguments, nor when it does not exist.
            let error = Command::new(bytes(&program)).spawn().unwrap_err();
            assert_eq!(error.kind(), ErrorKind::InvalidInput, "{name}: {error:?}");
            let error = Command::new(name).spawn().unwrap_err();
            assert_eq!(error.kind(), ErrorKind::InvalidInput, "{name}: {error:?}");
        }
        assert!(!marker.exists());
        // Other names are not concerned.
        for name in ["x.bat.exe", "bat", "x.batx", ".bat\\x"] {
            let error = Command::new(name).spawn().unwrap_err();
            assert_eq!(error.kind(), ErrorKind::NotFound, "{name}: {error:?}");
        }

        // The way to run one: the interpreter, and the command line it is
        // to see.
        let line = format!("cmd /C \"{}\"", dir.join("x.bat").display());
        let shell = shell();
        let mut child = Command::new(&shell)
            .raw_command_line(&line)
            .stdin(Stdio::Null)
            .spawn()
            .unwrap();
        assert_eq!(wait(&mut child).code(), Some(7));
    }

    /// Every entry of an environment has a name.
    #[test]
    fn invalid_environment() {
        let shell = shell();
        for vars in [
            &[""][..],
            &["A=1", "", "B=2"],
            &["A=1", "B"],
            &["="],
            &["=B"],
            &["A=1", "B=2\0"],
        ] {
            let error = Command::new(&shell)
                .args(&[RUN, "exit 0"])
                .env(vars)
                .stdin(Stdio::Null)
                .spawn()
                .unwrap_err();
            assert_eq!(error.kind(), ErrorKind::InvalidInput, "{vars:?}: {error:?}");
        }
        // An empty value is a value, and a name may start with a `=`.
        let script = if cfg!(windows) {
            "echo [%OSCALL_A%][%OSCALL_B%]"
        } else {
            r#"echo "[${OSCALL_A-unset}][$OSCALL_B]""#
        };
        let mut vars = vec![
            "OSCALL_A=".to_owned(),
            "OSCALL_B=b".to_owned(),
            "=Q:=x".to_owned(),
        ];
        if cfg!(windows) {
            vars.push(format!(
                "SystemRoot={}",
                std::env::var("SystemRoot").unwrap()
            ));
        }
        let options = Options {
            env: Some(&vars),
            ..Options::default()
        };
        let output = run_with(script, &options);
        assert!(output.status.success(), "{}", output.stderr);
        // `cmd.exe` has no empty variables: one without a value is unset.
        let expected = if cfg!(windows) {
            "[%OSCALL_A%][b]\n"
        } else {
            "[][b]\n"
        };
        assert_eq!(output.stdout, expected);
    }

    #[test]
    fn exit_and_abort() {
        let Some(status) = helper("exit:0", &[]) else {
            return;
        };
        assert!(status.success());
        let status = helper("exit:37", &[]).unwrap();
        assert_eq!(status.code(), Some(37));
        assert!(!status.success());

        let status = helper("abort", &[]).unwrap();
        assert!(!status.success());
        #[cfg(windows)]
        assert_eq!(status.code(), Some(0xc000_0409_u32 as i32));
        #[cfg(not(windows))]
        {
            use oscall::process::unix::ExitStatusExt;
            const SIGABRT: i32 = 6;
            assert_eq!(status.code(), None);
            assert_eq!(status.signal(), Some(SIGABRT));
        }
    }

    /// The child's idea of who it is and who started it.
    #[test]
    fn child_ids() {
        let dir = tmp_dir("process_child_ids");
        let file = std::path::absolute(dir.join("ids")).unwrap();
        let mode = format!("ids:{}", file.display());
        if helper(&mode, &[]).is_none() {
            return;
        }
        let ids = std::fs::read_to_string(&file).unwrap();
        let (id, parent) = ids.split_once(' ').unwrap();
        assert_ne!(id.parse::<u32>().unwrap(), oscall::process::id());
        assert_eq!(parent.parse::<u32>().unwrap(), oscall::process::id());
    }

    #[test]
    fn explicit_environment() {
        let script = if cfg!(windows) {
            "echo %OSCALL_A%-%OSCALL_B%-%OSCALL_C%"
        } else {
            r#"echo "$OSCALL_A-$OSCALL_B-${OSCALL_C-unset}-${HOME-unset}""#
        };
        let vars = vec![
            "OSCALL_A=two words".to_owned(),
            "OSCALL_B=h\u{e9}=\u{4e16}".to_owned(),
        ];
        let options = Options {
            env: Some(&vars),
            ..Options::default()
        };
        let output = run_with(script, &options);
        assert!(output.status.success());
        if cfg!(windows) {
            // `cmd.exe` writes in the console's code page: compare what is
            // ASCII. An undefined variable is left as it is.
            let out = &output.stdout;
            assert!(out.starts_with("two words-h"), "{out:?}");
            assert!(out.ends_with("-%OSCALL_C%\n"), "{out:?}");
        } else {
            assert_eq!(output.stdout, "two words-h\u{e9}=\u{4e16}-unset-unset\n");
        }

        // Nothing at all.
        let script = if cfg!(windows) {
            "echo %OSCALL_A%-%SystemRoot%"
        } else {
            r#"echo "${OSCALL_A-unset}-${HOME-unset}""#
        };
        let options = Options {
            env: Some(&[]),
            ..Options::default()
        };
        let output = run_with(script, &options);
        assert!(output.status.success());
        let expected = if cfg!(windows) {
            "%OSCALL_A%-%SystemRoot%\n"
        } else {
            "unset-unset\n"
        };
        assert_eq!(output.stdout, expected);
    }

    /// By default the child has the caller's environment.
    #[test]
    fn inherited_environment() {
        let name = if cfg!(windows) { "SystemRoot" } else { "PATH" };
        let value = std::env::var(name).unwrap();
        let script = if cfg!(windows) {
            "echo %SystemRoot%"
        } else {
            r#"echo "$PATH""#
        };
        let output = run(script);
        assert!(output.status.success());
        assert_eq!(output.stdout, format!("{value}\n"));
    }

    #[test]
    fn working_directory() {
        let dir = tmp_dir("process_working_directory");
        let script = if cfg!(windows) {
            "echo x> marker"
        } else {
            "echo x > marker"
        };
        let options = Options {
            dir: Some(&dir),
            ..Options::default()
        };
        let output = run_with(script, &options);
        assert!(output.status.success(), "{}", output.stderr);
        assert!(dir.join("marker").is_file());
        assert!(!PathBuf::from("marker").exists());

        // A directory that does not exist: no child.
        let shell = shell();
        let missing = dir.join("missing");
        let result = Command::new(&shell)
            .args(&[RUN, "exit 0"])
            .current_dir(bytes(&missing))
            .spawn();
        let kind = result.unwrap_err().kind();
        if cfg!(windows) {
            assert_eq!(kind, ErrorKind::NotADirectory);
        } else {
            assert_eq!(kind, ErrorKind::NotFound);
        }
    }

    /// A relative program is relative to the caller's directory, whatever
    /// the child's is.
    #[test]
    #[cfg(not(windows))]
    fn relative_program() {
        let dir = tmp_dir("process_relative_program");
        let sub = dir.join("sub");
        std::fs::create_dir(&sub).unwrap();
        let script = dir.join("script");
        assert!(script.is_relative());
        std::fs::write(&script, "#!/bin/sh\necho \"$0\" > marker\nexit 5\n").unwrap();
        let executable = oscall::fs::Permissions::from_mode(0o755);
        oscall::fs::set_permissions(bytes(&script), executable).unwrap();
        let command = Command::new(bytes(&script))
            .stdin(Stdio::Null)
            .current_dir(bytes(&sub));
        let mut child = loop {
            match command.spawn() {
                Ok(child) => break child,
                // A child another test created while the script was being
                // written still has it open: it is about to let go.
                Err(error) if error.kind() == ErrorKind::ExecutableFileBusy => {
                    std::thread::sleep(Duration::from_millis(2));
                }
                Err(error) => panic!("{error:?}"),
            }
        };
        assert_eq!(wait(&mut child).code(), Some(5));
        // It ran in the directory asked for, and was found from ours. The
        // shell is told the absolute path of the script.
        let seen = std::fs::read_to_string(sub.join("marker")).unwrap();
        let absolute = std::path::absolute(&script).unwrap();
        assert_eq!(seen.trim_end(), absolute.to_str().unwrap());
        assert!(!dir.join("marker").exists());

        // Without another directory for the child the path is not touched.
        let (read, write) = io::pipe().unwrap();
        std::fs::write(&script, "#!/bin/sh\necho \"$0\"\n").unwrap();
        let command = Command::new(bytes(&script))
            .stdin(Stdio::Null)
            .stdout(Stdio::Handle(write.as_handle()));
        let mut child = loop {
            match command.spawn() {
                Ok(child) => break child,
                Err(error) if error.kind() == ErrorKind::ExecutableFileBusy => {
                    std::thread::sleep(Duration::from_millis(2));
                }
                Err(error) => panic!("{error:?}"),
            }
        };
        drop(write);
        assert_eq!(read_text(&read).trim_end(), script.to_str().unwrap());
        assert!(wait(&mut child).success());
    }

    /// As above. The only program at hand that can be named by a relative
    /// path is this one.
    #[test]
    #[cfg(windows)]
    fn relative_program() {
        let dir = tmp_dir("process_relative_program");
        let exe = std::env::current_exe().unwrap();
        let here = std::env::current_dir().unwrap();
        let Ok(relative) = exe.strip_prefix(&here) else {
            eprintln!("skipped: {} is not under {}", exe.display(), here.display());
            return;
        };
        let env = helper_env("exit:5");
        let mut child = Command::new(bytes(relative))
            .args(&["--exact", "--nocapture", "helper_child_process"])
            .env(&env)
            .stdin(Stdio::Null)
            .stdout(Stdio::Null)
            .stderr(Stdio::Null)
            .current_dir(bytes(&dir))
            .spawn()
            .unwrap();
        assert_eq!(wait(&mut child).code(), Some(5));
    }

    /// What `find_program` finds, `Command` runs.
    #[test]
    fn found_program() {
        let Some(path) = std::env::var_os("PATH") else {
            eprintln!("skipped: no PATH");
            return;
        };
        let name = if cfg!(windows) { "cmd" } else { "sh" };
        let program = oscall::process::find_program_vec(name, path.as_encoded_bytes()).unwrap();
        assert!(std::path::Path::new(std::str::from_utf8(&program).unwrap()).is_file());
        let mut child = Command::new(&program)
            .args(&[RUN, "exit 3"])
            .stdin(Stdio::Null)
            .spawn()
            .unwrap();
        assert_eq!(wait(&mut child).code(), Some(3));
    }

    /// Windows wants the environment sorted by name, without regard to
    /// case; `cmd.exe` prints the one it was given in order, with the two
    /// variables whose names only differ by case in the order given.
    #[test]
    #[cfg(windows)]
    fn sorted_environment() {
        let vars = vec![
            format!("SystemRoot={}", std::env::var("SystemRoot").unwrap()),
            "OSCALL_ZZ=1".to_owned(),
            "oscall_mm=2".to_owned(),
            "OSCALL_AA=3".to_owned(),
            "oscall_b=4".to_owned(),
            "OSCALL_B=5".to_owned(),
            "=X:=X:\\".to_owned(),
        ];
        let options = Options {
            env: Some(&vars),
            ..Options::default()
        };
        let output = run_with("set", &options);
        assert!(output.status.success(), "{}", output.stderr);
        let ours: Vec<&str> = output
            .stdout
            .lines()
            .filter(|line| line.to_ascii_lowercase().starts_with("oscall_"))
            .collect();
        assert_eq!(
            ours,
            [
                "OSCALL_AA=3",
                "oscall_b=4",
                "OSCALL_B=5",
                "oscall_mm=2",
                "OSCALL_ZZ=1"
            ],
            "{}",
            output.stdout
        );
    }

    /// What a child consumed is known once it has been waited for.
    #[test]
    fn child_resource_usage() {
        let script = if cfg!(windows) {
            "for /L %i in (1,1,30000) do @rem"
        } else {
            "i=0; while [ $i -lt 100000 ]; do i=$((i+1)); done"
        };
        let shell = shell();
        let mut child = Command::new(&shell)
            .args(&[RUN, script])
            .stdin(Stdio::Null)
            .stdout(Stdio::Null)
            .spawn()
            .unwrap();
        assert_eq!(child.resource_usage(), None);
        let started = Instant::now();
        assert!(wait(&mut child).success());
        let elapsed = started.elapsed();
        let usage = child
            .resource_usage()
            .expect("no usage for a child waited for");
        assert_eq!(child.resource_usage(), Some(usage));
        let peak = usage.max_resident_memory();
        assert!(peak < 1 << 40, "{usage:?}");
        // Linux counts resident pages per processor, in batches it only
        // adds up now and then: a small process that did not live long
        // can read as having had none (seen on a machine with 192
        // processors: a shell that used 67 ms of processor, 0 bytes).
        if !cfg!(any(target_os = "linux", target_os = "fullrust")) {
            assert!(peak > 0, "{usage:?}");
        }
        let total = usage.user_time() + usage.system_time();
        // One thread, more or less: no more processor time than time.
        assert!(
            total <= 2 * elapsed + Duration::from_secs(1),
            "{usage:?} {elapsed:?}"
        );
        // Windows counts in clock ticks, of which a short run may get none.
        if !cfg!(windows) {
            assert!(total > Duration::ZERO, "{usage:?}");
        }

        // A child that was killed has its usage too.
        let (mut child, _input) = blocked_child();
        child.kill().unwrap();
        child.wait().unwrap();
        assert!(child.resource_usage().is_some());
    }

    /// A process named by its identifier alone.
    #[test]
    fn exists_and_kill() {
        let (mut child, _input) = blocked_child();
        let pid = child.id();
        assert_eq!(oscall::process::exists(pid), Ok(true));
        oscall::process::kill(pid).unwrap();
        let status = child.wait().unwrap();
        #[cfg(windows)]
        assert_eq!(status.code(), Some(1));
        #[cfg(not(windows))]
        {
            use oscall::process::unix::{ExitStatusExt, SIGKILL};
            assert_eq!(status.signal(), Some(SIGKILL));
        }
        // Waited for, it is gone. (On Windows the identifier cannot be
        // given to another process while `child` holds a handle; on Linux
        // and macOS it could, but not before many others.)
        assert_eq!(oscall::process::exists(pid), Ok(false));
        let error = oscall::process::kill(pid).unwrap_err();
        let expected = if cfg!(windows) {
            ErrorKind::InvalidInput
        } else {
            ErrorKind::NoSuchProcess
        };
        assert_eq!(error.kind(), expected, "{error:?}");
    }

    /// A child in a console process group of its own runs like any other.
    #[test]
    #[cfg(windows)]
    fn new_process_group() {
        use oscall::process::windows::CommandExt;

        let (read, write) = io::pipe().unwrap();
        let shell = shell();
        let mut child = Command::new(&shell)
            .args(&[RUN, "echo out& exit 3"])
            .new_process_group()
            .stdin(Stdio::Null)
            .stdout(Stdio::Handle(write.as_handle()))
            .spawn()
            .unwrap();
        drop(write);
        assert_eq!(read_text(&read), "out\n");
        assert_eq!(wait(&mut child).code(), Some(3));
    }

    /// As `blocked_child`, with more set on the command.
    #[cfg(not(windows))]
    fn blocked_child_with(
        configure: impl for<'a> FnOnce(Command<'a>) -> Command<'a>,
    ) -> (Child, OwnedHandle) {
        let (read, write) = io::pipe().unwrap();
        let (program, args) = filter();
        let command = Command::new(&program)
            .args(&args)
            .stdin(Stdio::Handle(read.as_handle()))
            .stdout(Stdio::Null)
            .stderr(Stdio::Null);
        (configure(command).spawn().unwrap(), write)
    }

    #[test]
    #[cfg(not(windows))]
    fn signal_by_pid() {
        use oscall::process::unix::{self, ExitStatusExt};

        let (mut child, _input) = blocked_child();
        let pid = child.id();
        unix::send_signal(pid, 0).unwrap();
        assert_eq!(child.try_wait().unwrap(), None);
        let error = unix::send_signal(pid, 1000).unwrap_err();
        assert_eq!(error.kind(), ErrorKind::InvalidInput, "{error:?}");
        unix::send_signal(pid, unix::SIGUSR1).unwrap();
        assert_eq!(child.wait().unwrap().signal(), Some(unix::SIGUSR1));
        let error = unix::send_signal(pid, 0).unwrap_err();
        assert_eq!(error.kind(), ErrorKind::NoSuchProcess, "{error:?}");

        // Neither the caller's group nor everything.
        for pid in [0, u32::MAX, 1 << 31] {
            let error = unix::send_signal(pid, 0).unwrap_err();
            assert_eq!(error.kind(), ErrorKind::InvalidInput, "{error:?}");
            let error = unix::send_signal_to_group(pid, 0).unwrap_err();
            assert_eq!(error.kind(), ErrorKind::InvalidInput, "{error:?}");
            let error = unix::process_group(pid).unwrap_err();
            assert_eq!(error.kind(), ErrorKind::InvalidInput, "{error:?}");
            let error = unix::session(pid).unwrap_err();
            assert_eq!(error.kind(), ErrorKind::InvalidInput, "{error:?}");
        }
        let error = unix::send_signal_to_group(1, 0).unwrap_err();
        assert_eq!(error.kind(), ErrorKind::InvalidInput, "{error:?}");
    }

    #[test]
    #[cfg(not(windows))]
    fn process_groups() {
        use oscall::process::unix::{self, CommandExt, ExitStatusExt};

        let own = oscall::process::id();
        let group = unix::process_group(own).unwrap();
        let session = unix::session(own).unwrap();
        assert_ne!(group, 0);
        assert_ne!(session, 0);

        // By default, the caller's group and session.
        let (mut child, _input) = blocked_child();
        assert_eq!(unix::process_group(child.id()), Ok(group));
        assert_eq!(unix::session(child.id()), Ok(session));
        child.kill().unwrap();
        child.wait().unwrap();

        // A group of its own, in the same session, and another child in it.
        let (mut leader, _leader_input) = blocked_child_with(|command| command.process_group(0));
        assert_eq!(unix::process_group(leader.id()), Ok(leader.id()));
        assert_eq!(unix::session(leader.id()), Ok(session));
        let id = leader.id();
        let (mut member, _member_input) = blocked_child_with(|command| command.process_group(id));
        assert_eq!(unix::process_group(member.id()), Ok(leader.id()));
        // The whole group, and nothing else: this process is not in it.
        unix::send_signal_to_group(leader.id(), 0).unwrap();
        unix::send_signal_to_group(leader.id(), unix::SIGTERM).unwrap();
        assert_eq!(leader.wait().unwrap().signal(), Some(unix::SIGTERM));
        assert_eq!(member.wait().unwrap().signal(), Some(unix::SIGTERM));
        let error = unix::send_signal_to_group(id, 0).unwrap_err();
        assert_eq!(error.kind(), ErrorKind::NoSuchProcess, "{error:?}");

        // A group that does not exist cannot be joined: no child.
        let (read, _write) = io::pipe().unwrap();
        let (program, args) = filter();
        let error = Command::new(&program)
            .args(&args)
            .stdin(Stdio::Handle(read.as_handle()))
            .process_group(id)
            .spawn()
            .unwrap_err();
        assert_eq!(error.kind(), ErrorKind::PermissionDenied, "{error:?}");

        // A session of its own, and so a group; the group asked for is
        // ignored.
        let (mut child, _input) =
            blocked_child_with(|command| command.new_session().process_group(group));
        assert_eq!(unix::session(child.id()), Ok(child.id()));
        assert_eq!(unix::process_group(child.id()), Ok(child.id()));
        child.kill().unwrap();
        child.wait().unwrap();
    }

    /// Runs a shell command set up by `configure`, with no input, and
    /// collects what it writes.
    #[cfg(not(windows))]
    fn run_configured<'a>(
        script: &'a str,
        configure: impl FnOnce(Command<'a>) -> Command<'a>,
    ) -> Result<Output, Error> {
        const SHELL: &str = "/bin/sh";
        let (out_read, out_write) = io::pipe().unwrap();
        let (err_read, err_write) = io::pipe().unwrap();
        let args = [RUN, script];
        // The command borrows for as long as what the caller gives it
        // lives; what is made here does not live that long.
        let command = configure(Command::new(SHELL));
        let mut child = command
            .args(&args)
            .stdin(Stdio::Null)
            .stdout(Stdio::Handle(out_write.as_handle()))
            .stderr(Stdio::Handle(err_write.as_handle()))
            .spawn()?;
        drop((out_write, err_write));
        let stdout = read_text(&out_read);
        let stderr = read_text(&err_read);
        Ok(Output {
            status: wait(&mut child),
            stdout,
            stderr,
        })
    }

    /// The limits given to a child are its own: the caller's stay.
    #[test]
    #[cfg(not(windows))]
    fn child_limits() {
        use oscall::process::unix::{self, CommandExt, Limit, Resource};

        // (The size of a core dump is what another test changes for this
        // process meanwhile: the child's is set here, the caller's is not
        // looked at.)
        let files = unix::limit(Resource::OpenFiles).unwrap();
        // Lower than what anything runs with, and enough for a shell.
        let limits = [
            (
                Resource::OpenFiles,
                Limit {
                    soft: Some(57),
                    hard: files.hard,
                },
            ),
            (
                Resource::CoreSize,
                Limit {
                    soft: Some(0),
                    hard: Some(0),
                },
            ),
        ];
        let output = run_configured("ulimit -n; ulimit -c; ulimit -H -c", |command| {
            command.limits(&limits)
        })
        .unwrap();
        assert_eq!(output.stdout, "57\n0\n0\n", "{}", output.stderr);
        assert!(output.status.success());
        // Without them, the caller's; which the above did not change.
        let output = run_configured("ulimit -n", |command| command.limits(&[])).unwrap();
        let inherited = files.soft.map_or("unlimited".to_owned(), |n| n.to_string());
        assert_eq!(output.stdout.trim(), inherited);
        assert_eq!(unix::limit(Resource::OpenFiles), Ok(files));

        // A limit that cannot be set: no child. A value the system takes
        // for "no limit" is found before there is one, a soft limit above
        // the hard one by the child.
        for limit in [
            Limit {
                soft: Some(u64::MAX),
                hard: None,
            },
            Limit {
                soft: Some(2),
                hard: Some(1),
            },
        ] {
            let limits = [(Resource::CoreSize, limit)];
            let error = run_configured("exit 0", |command| command.limits(&limits))
                .err()
                .unwrap();
            assert_eq!(error.kind(), ErrorKind::InvalidInput, "{error:?}");
        }
        // Raising a hard limit needs a privilege.
        if let Some(hard) = files.hard
            && !is_root()
        {
            let limits = [(
                Resource::OpenFiles,
                Limit {
                    soft: files.soft,
                    hard: Some(hard + 1),
                },
            )];
            let error = run_configured("exit 0", |command| command.limits(&limits))
                .err()
                .unwrap();
            assert_eq!(error.kind(), ErrorKind::PermissionDenied, "{error:?}");
        }
    }

    /// The user and the group of this process, as `id` reports them.
    #[cfg(not(windows))]
    fn own_ids() -> (u32, u32) {
        let output = run("id -u; id -g");
        let mut ids = output.stdout.lines().map(|id| id.parse().unwrap());
        (ids.next().unwrap(), ids.next().unwrap())
    }

    #[cfg(not(windows))]
    fn is_root() -> bool {
        own_ids().0 == 0
    }

    /// The groups of this process, as `id -G` writes those of a process:
    /// its own group, then the others.
    #[cfg(not(any(windows, target_os = "macos")))]
    fn own_groups() -> String {
        run("id -G").stdout
    }

    /// The same on macOS, where `id` does not say: for a user it knows,
    /// root included, it asks the directory, which has more groups than
    /// the 16 a process holds (seen: 23 for root, and 16 for a child of
    /// its that is a user no one knows).
    #[cfg(target_os = "macos")]
    fn own_groups() -> String {
        unsafe extern "C" {
            fn getgroups(count: i32, list: *mut u32) -> i32;
            fn getegid() -> u32;
        }
        let mut list = [0u32; 64];
        // SAFETY: the list is writable for the count given.
        let count = unsafe { getgroups(list.len() as i32, list.as_mut_ptr()) };
        assert!(count >= 0);
        // SAFETY: no argument, and the call cannot fail.
        let own = unsafe { getegid() };
        let others = list[..count as usize].iter().filter(|group| **group != own);
        let mut out = own.to_string();
        for group in others {
            out.push_str(&format!(" {group}"));
        }
        out + "\n"
    }

    /// The file creation mask of a child, alone and with everything else
    /// a command can set: on macOS these children are made another way.
    #[test]
    #[cfg(not(windows))]
    fn child_umask() {
        use oscall::process::unix::{self, CommandExt};

        for mask in [0o027, 0o777, 0] {
            let output = run_configured("umask", |command| command.umask(mask)).unwrap();
            assert_eq!(output.stdout, format!("{mask:04o}\n"), "{}", output.stderr);
            assert!(output.status.success());
        }
        // What the files of the child get.
        let dir = tmp_dir("process_child_umask");
        let dir = std::path::absolute(&dir).unwrap();
        let output = run_configured(
            "umask; pwd; echo text > file; echo error >&2; exit 7",
            |c| c.umask(0o026).current_dir(bytes(&dir)).arg0("custom"),
        )
        .unwrap();
        let mut lines = output.stdout.lines();
        assert_eq!(lines.next(), Some("0026"));
        let here = PathBuf::from(lines.next().unwrap());
        assert_eq!(
            here.canonicalize().unwrap(),
            dir.canonicalize().unwrap(),
            "{here:?}"
        );
        assert_eq!(output.stderr, "error\n");
        assert_eq!(output.status.code(), Some(7));
        let metadata = oscall::fs::metadata(bytes(&dir.join("file"))).unwrap();
        assert_eq!(metadata.permissions().mode() & 0o777, 0o640);

        // Only permission bits.
        let error = run_configured("exit 0", |command| command.umask(0o1000))
            .err()
            .unwrap();
        assert_eq!(error.kind(), ErrorKind::InvalidInput, "{error:?}");

        // With a group or a session of its own.
        let (mut child, _input) = blocked_child_with(|c| c.umask(0o022).process_group(0));
        assert_eq!(unix::process_group(child.id()), Ok(child.id()));
        let gone = child.id();
        child.kill().unwrap();
        child.wait().unwrap();
        let (mut child, _input) = blocked_child_with(|c| c.umask(0o022).new_session());
        assert_eq!(unix::session(child.id()), Ok(child.id()));
        assert_eq!(unix::process_group(child.id()), Ok(child.id()));
        child.kill().unwrap();
        child.wait().unwrap();
        // A group that cannot be joined (it no longer exists), a program
        // that is not there, a directory that is not there: the reason,
        // and no child.
        let error = run_configured("exit 0", |c| c.umask(0o022).process_group(gone))
            .err()
            .unwrap();
        assert_eq!(error.kind(), ErrorKind::PermissionDenied, "{error:?}");
        let missing = dir.join("missing");
        let error = Command::new(bytes(&missing)).umask(0o022).spawn();
        let error = error.unwrap_err();
        assert_eq!(error.kind(), ErrorKind::NotFound, "{error:?}");
        let error = run_configured("exit 0", |c| c.umask(0o022).current_dir(bytes(&missing)))
            .err()
            .unwrap();
        assert_eq!(error.kind(), ErrorKind::NotFound, "{error:?}");
        // And nothing but the standard handles reaches such a child.
        let (read, write) = io::pipe().unwrap();
        io::set_inheritable(&write, true).unwrap();
        let (mut child, input) = blocked_child_with(|command| command.umask(0o022));
        // Had the child the write end too, this read would last as long as
        // the child, which waits for us.
        drop(write);
        let (sender, receiver) = mpsc::channel();
        let reader = std::thread::spawn(move || {
            let mut buf = [0u8; 1];
            let _ = sender.send(io::read(&read, &mut buf));
        });
        let result = receiver.recv_timeout(Duration::from_secs(20));
        child.kill().unwrap();
        child.wait().unwrap();
        drop(input);
        reader.join().unwrap();
        match result {
            Ok(Ok(0)) => {}
            other => panic!("the child inherited the pipe: {other:?}"),
        }
    }

    /// Whether this process may dump core and be traced:
    /// `prctl(PR_GET_DUMPABLE)`.
    #[cfg(any(target_os = "linux", target_os = "fullrust"))]
    fn dumpable() -> usize {
        use oscall::raw::linux::{nr, syscall1};
        const PR_GET_DUMPABLE: usize = 3;
        // SAFETY: the call reads a flag of the process.
        unsafe { syscall1(nr::PRCTL, PR_GET_DUMPABLE) }
    }

    /// The user and the groups of a child. What can be asked depends on
    /// who runs the tests: root (as in a container) can become anyone,
    /// anyone else only itself.
    #[test]
    #[cfg(not(windows))]
    fn child_identity() {
        use oscall::process::unix::CommandExt;

        let (uid, gid) = own_ids();
        // What one is already is always allowed.
        let output = run_configured("id -u; id -g", |c| c.uid(uid).gid(gid)).unwrap();
        assert_eq!(
            output.stdout,
            format!("{uid}\n{gid}\n"),
            "{}",
            output.stderr
        );

        if uid == 0 {
            // Another user, with its group and no other: what the child
            // is, and stays (it cannot go back).
            let groups = [4242];
            #[cfg(not(target_os = "macos"))]
            let dumpable = dumpable();
            let output = run_configured("id -u; id -g; id -G", |command| {
                command.uid(4243).gid(4242).groups(&groups)
            })
            .unwrap();
            assert_eq!(output.stdout, "4243\n4242\n4242\n", "{}", output.stderr);
            // On Linux the child changes its identity while it shares the
            // memory of this process, and what the kernel then notes on
            // that memory (no core dump, no debugger) is not left on it.
            #[cfg(not(target_os = "macos"))]
            assert_eq!(self::dumpable(), dumpable);
            // The user alone: the groups stay the caller's.
            let before = own_groups();
            let output = run_configured("id -u; id -G", |c| c.uid(4243)).unwrap();
            assert_eq!(output.stdout, format!("4243\n{before}"));
            // The limits are set before the privilege goes. Raising a hard
            // limit takes one (`CAP_SYS_RESOURCE` on Linux): the hard
            // limit is lowered first, so that the second one raises it,
            // where this process may do that. Root in a container often
            // may not (Docker gives it no such capability): the limit
            // asked for is then the one it has, which a child sets whoever
            // it is.
            use oscall::process::unix::{Limit, Resource};
            let lower = Limit {
                soft: Some(0),
                hard: Some(0),
            };
            let raise = Limit {
                soft: Some(0),
                hard: None,
            };
            let both = [(Resource::CoreSize, lower), (Resource::CoreSize, raise)];
            let may_raise = run_configured("exit 0", |command| command.limits(&both)).is_ok();
            let limits = if may_raise { &both[..] } else { &both[1..] };
            let output = run_configured("id -u; ulimit -H -c", |command| {
                command.uid(4243).limits(limits)
            })
            .unwrap();
            assert_eq!(output.stdout, "4243\nunlimited\n", "{}", output.stderr);
            // A group and groups that are not it: the child has them all.
            // (On macOS the list of a process starts with its own group,
            // which `setgid` writes there: over the first of the groups
            // given, were they given to `setgroups` as they are.)
            let output = run_configured("id -g; id -G", |command| {
                command.uid(4243).gid(4242).groups(&[7, 8])
            })
            .unwrap();
            assert_eq!(output.stdout, "4242\n4242 7 8\n", "{}", output.stderr);
            // Groups and no group: the child keeps the caller's.
            let output = run_configured("id -g; id -G", |c| c.uid(4243).groups(&[7, 8])).unwrap();
            assert_eq!(
                output.stdout,
                format!("{gid}\n{gid} 7 8\n"),
                "{}",
                output.stderr
            );
            // An empty list is no supplementary group.
            let output = run_configured("id -G", |c| c.uid(4243).gid(4242).groups(&[])).unwrap();
            assert_eq!(output.stdout, "4242\n", "{}", output.stderr);
            // As many as the system takes, and one more.
            let most = if cfg!(target_os = "macos") { 15 } else { 65536 };
            let many: Vec<u32> = (5000..=5000 + most).collect();
            let output = run_configured("exit 0", |c| c.groups(&many[..most as usize]));
            assert!(output.unwrap().status.success());
            let error = run_configured("exit 0", |c| c.groups(&many)).err().unwrap();
            assert_eq!(error.kind(), ErrorKind::InvalidInput, "{error:?}");
        } else {
            // Not without privilege: the reason, and no child.
            for configure in [
                (|c| c.uid(0)) as for<'a> fn(Command<'a>) -> Command<'a>,
                |c| c.gid(0),
                |c| c.groups(&[]),
                |c| c.groups(&[0]),
            ] {
                let error = run_configured("exit 0", configure).err().unwrap();
                assert_eq!(error.kind(), ErrorKind::PermissionDenied, "{error:?}");
            }
        }
    }

    /// What `mode` of the helper does: starts a child that waits for its
    /// input to end, with this process's own standard handles, and exits
    /// without waiting for it. With `tied`, the child is one that does not
    /// outlive this process.
    #[cfg(any(target_os = "linux", target_os = "fullrust", windows))]
    pub(super) fn orphan_helper(tied: bool) -> ! {
        let (program, args) = filter();
        let command = Command::new(&program).args(&args).stderr(Stdio::Null);
        #[cfg(not(windows))]
        let command = {
            use oscall::process::linux::CommandExt;
            if tied {
                command.parent_death_signal(oscall::process::unix::SIGKILL)
            } else {
                command
            }
        };
        #[cfg(windows)]
        let job = {
            use oscall::process::windows::{Job, JobLimits};
            let job = Job::new().unwrap();
            let mut limits = JobLimits::new();
            limits.kill_on_close = tied;
            job.set_limits(&limits).unwrap();
            job
        };
        #[cfg(windows)]
        let command = {
            use oscall::process::windows::CommandExt;
            command.job(&job)
        };
        let child = command.spawn().unwrap();
        std::mem::forget(child);
        // The handle of the job is closed by the system, with the process.
        oscall::process::exit(0)
    }

    /// Runs the helper `mode`, which leaves a child behind, and reports
    /// whether that child outlives it: it holds the write end of a pipe,
    /// and waits for an input that does not come.
    #[cfg(any(target_os = "linux", target_os = "fullrust", windows))]
    fn orphan_survives(mode: &str) -> Option<bool> {
        let exe = std::env::current_exe().unwrap();
        let env = helper_env(mode);
        let args = ["--exact", "--nocapture", "helper_child_process"];
        let (in_read, in_write) = io::pipe().unwrap();
        let (out_read, out_write) = io::pipe().unwrap();
        let spawned = Command::new(bytes(&exe))
            .args(&args)
            .env(&env)
            .stdin(Stdio::Handle(in_read.as_handle()))
            .stdout(Stdio::Handle(out_write.as_handle()))
            .stderr(Stdio::Null)
            .spawn();
        let mut helper = match spawned {
            Ok(child) => child,
            Err(error) if is_exec_format(error) => {
                eprintln!("skipped: the system cannot execute {}", exe.display());
                return None;
            }
            Err(error) => panic!("cannot run {}: {error}", exe.display()),
        };
        drop((in_read, out_write));
        assert_eq!(wait(&mut helper).code(), Some(0));
        // The helper is gone. The output ends when its child is too.
        let (sender, ended) = mpsc::channel();
        let reader = std::thread::spawn(move || {
            read_bytes(&out_read);
            let _ = sender.send(());
        });
        // One that survives never ends it, however long this waits; one
        // that does not is given the time a loaded machine may need.
        let survives = ended.recv_timeout(Duration::from_millis(300)).is_err()
            && (mode.ends_with("plain") || ended.recv_timeout(Duration::from_secs(60)).is_err());
        // Its input ends: it exits by itself if it is still there.
        drop(in_write);
        reader.join().unwrap();
        Some(survives)
    }

    /// A child that is sent a signal when its parent goes away, and one
    /// that is not.
    #[test]
    #[cfg(any(target_os = "linux", target_os = "fullrust"))]
    fn parent_death_signal() {
        use oscall::process::linux::CommandExt;
        use oscall::process::unix::{self, ExitStatusExt};

        // While the thread that created it lives, nothing happens.
        let (mut child, input) =
            blocked_child_with(|command| command.parent_death_signal(unix::SIGTERM));
        std::thread::sleep(Duration::from_millis(20));
        assert_eq!(child.try_wait().unwrap(), None);
        drop(input);
        assert!(wait(&mut child).code().is_some());

        // The parent is the thread, not the process: when the thread
        // ends, the signal is sent.
        let (mut child, _input) = std::thread::spawn(|| {
            blocked_child_with(|command| command.parent_death_signal(unix::SIGTERM))
        })
        .join()
        .unwrap();
        assert_eq!(wait(&mut child).signal(), Some(unix::SIGTERM));

        // A child that is given another identity too: the kernel forgets
        // the signal of a process whose user or group changes, so it has
        // to be asked for afterwards. Only root can change them.
        if is_root() {
            use oscall::process::unix::CommandExt as _;
            let (mut child, _input) = std::thread::spawn(|| {
                blocked_child_with(|command| {
                    command
                        .uid(4243)
                        .gid(4242)
                        .parent_death_signal(unix::SIGTERM)
                })
            })
            .join()
            .unwrap();
            assert_eq!(wait(&mut child).signal(), Some(unix::SIGTERM));
        }

        // Not a signal: no child.
        for signal in [0, -1, 65, 1000] {
            let error = run_configured("exit 0", |c| c.parent_death_signal(signal))
                .err()
                .unwrap();
            assert_eq!(error.kind(), ErrorKind::InvalidInput, "{error:?}");
        }

        // The process that ends: its child goes with it, where one that
        // did not ask stays.
        if let Some(survives) = orphan_survives("orphan:plain") {
            assert!(survives);
        }
        if let Some(survives) = orphan_survives("orphan:tied") {
            assert!(!survives);
        }
    }

    /// The process is duplicated. Not this one: the copy would hold every
    /// descriptor the tests that run at the same time have open, for as
    /// long as it lives, and a pipe one of them closed would stay open (a
    /// writer that is to die of `SIGPIPE` then does not). The helper runs
    /// nothing else.
    #[test]
    #[cfg(not(windows))]
    fn fork() {
        if let Some(status) = helper("fork", &[]) {
            assert_eq!(status.code(), Some(0));
        }
    }

    /// What the helper does for the test above. The process has other
    /// threads (the test harness's): the child only makes system calls,
    /// and exits.
    #[cfg(not(windows))]
    pub(super) fn fork_helper() -> ! {
        use oscall::process::unix::{self, ExitStatusExt, Fork};

        let own = oscall::process::id();
        let (read, write) = io::pipe().unwrap();
        // SAFETY: the child calls nothing but `id`, `write` and `exit`,
        // which are one system call each.
        match unsafe { unix::fork() }.unwrap() {
            Fork::Child => {
                let id = oscall::process::id().to_ne_bytes();
                let parent = oscall::process::parent_id().to_ne_bytes();
                let written = io::write(&write, &id).is_ok_and(|n| n == 4)
                    && io::write(&write, &parent).is_ok_and(|n| n == 4);
                oscall::process::exit(if written { 42 } else { 1 })
            }
            Fork::Parent(mut child) => {
                drop(write);
                let said = read_bytes(&read);
                assert_eq!(wait(&mut child).code(), Some(42));
                assert_ne!(child.id(), own);
                assert_eq!(said[..4], child.id().to_ne_bytes());
                assert_eq!(said[4..], own.to_ne_bytes());
            }
        }

        // A child that waits is a child like another: it can be killed.
        let (read, write) = io::pipe().unwrap();
        // SAFETY: as above, with `read`.
        match unsafe { unix::fork() }.unwrap() {
            Fork::Child => {
                let mut byte = [0];
                let _ = io::read(&read, &mut byte);
                oscall::process::exit(3)
            }
            Fork::Parent(mut child) => {
                assert_eq!(child.try_wait().unwrap(), None);
                assert_eq!(unix::process_group(child.id()), unix::process_group(own));
                child.kill().unwrap();
                assert_eq!(wait(&mut child).signal(), Some(unix::SIGKILL));
                drop(write);
            }
        }
        oscall::process::exit(0)
    }

    /// The limits of a job are what was set.
    #[test]
    #[cfg(windows)]
    fn job_limits() {
        use oscall::process::windows::{Job, JobLimits};

        let job = Job::new().unwrap();
        assert_eq!(job.limits().unwrap(), JobLimits::new());
        assert_eq!(JobLimits::new(), JobLimits::default());
        let accounting = job.accounting().unwrap();
        assert_eq!(accounting.total_processes, 0);
        assert_eq!(accounting.active_processes, 0);
        assert_eq!(accounting.terminated_processes, 0);
        assert_eq!(accounting.user_time, Duration::ZERO);
        assert_eq!(accounting.system_time, Duration::ZERO);

        let mut limits = JobLimits::new();
        limits.process_memory = Some(256 << 20);
        limits.job_memory = Some(512 << 20);
        limits.active_processes = Some(5);
        limits.process_time = Some(Duration::from_millis(1500));
        limits.job_time = Some(Duration::from_secs(90));
        limits.kill_on_close = true;
        job.set_limits(&limits).unwrap();
        assert_eq!(job.limits().unwrap(), limits);

        // Each alone, and that setting replaces what was there.
        let mut one = JobLimits::new();
        one.active_processes = Some(1);
        job.set_limits(&one).unwrap();
        assert_eq!(job.limits().unwrap(), one);
        job.set_limits(&JobLimits::new()).unwrap();
        assert_eq!(job.limits().unwrap(), JobLimits::new());
        // Terminating a job that has nothing is nothing.
        job.terminate(1).unwrap();
        // The handle is one like another.
        let handle: OwnedHandle = job.into();
        drop(handle);
    }

    /// A child created in a job is in it, and ends with it.
    #[test]
    #[cfg(windows)]
    fn job_spawn() {
        use oscall::process::windows::{CommandExt, Job, JobLimits};

        let in_job = |job: &Job| {
            let (read, write) = io::pipe().unwrap();
            let (program, args) = filter();
            let child = Command::new(&program)
                .args(&args)
                .stdin(Stdio::Handle(read.as_handle()))
                .stdout(Stdio::Null)
                .stderr(Stdio::Null)
                .job(job)
                .spawn();
            child.map(|child| (child, write))
        };

        let job = Job::new().unwrap();
        let mut limits = JobLimits::new();
        limits.active_processes = Some(2);
        job.set_limits(&limits).unwrap();
        let (mut first, _first_input) = in_job(&job).unwrap();
        let (mut second, second_input) = in_job(&job).unwrap();
        let accounting = job.accounting().unwrap();
        assert_eq!(accounting.total_processes, 2);
        assert_eq!(accounting.active_processes, 2);
        // The job is full: no third child.
        let full = in_job(&job).map(|_| ()).unwrap_err();
        assert_eq!(job.accounting().unwrap().active_processes, 2);
        // One that exits makes room.
        drop(second_input);
        assert!(wait(&mut second).code().is_some());
        wait_for_active(&job, 1);
        let (mut third, _third_input) = in_job(&job).unwrap();
        assert_eq!(job.accounting().unwrap().total_processes, 3);
        // Everything in the job, with the code given.
        assert_eq!(first.try_wait().unwrap(), None);
        job.terminate(77).unwrap();
        assert_eq!(wait(&mut first).code(), Some(77));
        assert_eq!(wait(&mut third).code(), Some(77));
        wait_for_active(&job, 0);

        // A program that exits by itself, with its code. (These children
        // all have standard handles, the null device included: the list
        // of jobs goes with the list of handles. For the list of jobs
        // alone, see `job_spawn_without_handles`.)
        let shell = shell();
        let mut child = Command::new(&shell)
            .args(&[RUN, "exit 5"])
            .stdin(Stdio::Null)
            .stdout(Stdio::Null)
            .stderr(Stdio::Null)
            .job(&job)
            .spawn()
            .unwrap();
        assert_eq!(wait(&mut child).code(), Some(5));
        assert_eq!(job.accounting().unwrap().total_processes, 4);

        // What the full job said: `ERROR_NOT_ENOUGH_QUOTA`.
        assert_eq!(full.raw_os_error(), 1816, "{full:?}");
    }

    /// A child created in a job by a process that has no standard handle
    /// to give it: the list of jobs is then the only attribute of the
    /// child, and nothing is inherited. Such a process is a helper: the
    /// harness has its standard handles, and the null device is one too.
    #[test]
    #[cfg(windows)]
    fn job_spawn_without_handles() {
        let status = helper("bare-job", &[]).unwrap();
        // Any other code is the step of the helper that failed.
        assert_eq!(status.code(), Some(0));
    }

    /// What the helper does for the test above. It has nothing to write
    /// to: what goes wrong is told by the exit code.
    #[cfg(windows)]
    pub(super) fn bare_job_helper() -> ! {
        use oscall::process::exit;
        use oscall::process::windows::{CommandExt, Job};

        #[link(name = "kernel32")]
        unsafe extern "system" {
            fn SetStdHandle(which: u32, handle: *mut core::ffi::c_void) -> i32;
        }
        // `STD_INPUT_HANDLE`, `STD_OUTPUT_HANDLE`, `STD_ERROR_HANDLE`.
        for which in [-10i32, -11, -12] {
            // SAFETY: no memory is involved; the process then has no such
            // handle, which is a state the system knows.
            if unsafe { SetStdHandle(which as u32, std::ptr::null_mut()) } == 0 {
                exit(10);
            }
        }
        let Ok(job) = Job::new() else { exit(11) };
        let shell = shell();
        // Every standard handle is inherited, and there is none.
        let spawned = Command::new(&shell)
            .args(&[RUN, "exit 5"])
            .job(&job)
            .spawn();
        let Ok(mut child) = spawned else { exit(12) };
        if child.wait().ok().and_then(|status| status.code()) != Some(5) {
            exit(13);
        }
        // It was in the job.
        match job.accounting() {
            Ok(accounting) if accounting.total_processes == 1 => exit(0),
            _ => exit(14),
        }
    }

    /// Waits until `job` has `count` processes: a process that has exited
    /// may be counted for a moment more.
    #[cfg(windows)]
    fn wait_for_active(job: &oscall::process::windows::Job, count: u32) {
        let start = Instant::now();
        loop {
            let accounting = job.accounting().unwrap();
            if accounting.active_processes == count {
                return;
            }
            assert!(
                start.elapsed() < Duration::from_secs(60),
                "{accounting:?}, not {count}"
            );
            std::thread::sleep(Duration::from_millis(2));
        }
    }

    /// A process assigned to a job, and a job whose last handle is closed.
    #[test]
    #[cfg(windows)]
    fn job_assign_and_close() {
        use oscall::process::windows::{Job, JobLimits};

        let job = Job::new().unwrap();
        let (mut child, _input) = blocked_child();
        job.assign(&child).unwrap();
        let accounting = job.accounting().unwrap();
        assert_eq!(accounting.total_processes, 1);
        assert_eq!(accounting.active_processes, 1);
        // Closing a job leaves its processes alone...
        drop(job);
        std::thread::sleep(Duration::from_millis(20));
        assert_eq!(child.try_wait().unwrap(), None);

        // ... unless it was told otherwise. Jobs nest: the child is now
        // in both.
        let job = Job::new().unwrap();
        let mut limits = JobLimits::new();
        limits.kill_on_close = true;
        job.set_limits(&limits).unwrap();
        job.assign(&child).unwrap();
        assert_eq!(child.try_wait().unwrap(), None);
        drop(job);
        let closed = wait(&mut child);

        // A process that has exited cannot be assigned.
        let job = Job::new().unwrap();
        let exited = job.assign(&child).unwrap_err();
        assert_eq!(exited.kind(), ErrorKind::PermissionDenied, "{exited:?}");
        // What the processes of a job that is closed exit with: nothing
        // tells them from a process that ended well.
        assert_eq!(closed.code(), Some(0), "{closed:?}");
    }

    /// The children of a process that ends, in a job that is closed with
    /// it, end too; in a job that is not told to, they stay.
    #[test]
    #[cfg(windows)]
    fn job_kill_on_parent_exit() {
        assert_eq!(orphan_survives("orphan:plain"), Some(true));
        assert_eq!(orphan_survives("orphan:tied"), Some(false));
    }

    /// A limit that is enforced: a process that goes on computing past
    /// the processor time it is allowed is terminated.
    #[test]
    #[cfg(windows)]
    fn job_time_limit() {
        use oscall::process::windows::{CommandExt, Job, JobLimits};

        let job = Job::new().unwrap();
        let mut limits = JobLimits::new();
        limits.process_time = Some(Duration::from_millis(100));
        job.set_limits(&limits).unwrap();
        let shell = shell();
        // Counts for ever.
        let mut child = Command::new(&shell)
            .args(&[RUN, "for /L %i in (0,0,1) do @rem"])
            .stdin(Stdio::Null)
            .stdout(Stdio::Null)
            .stderr(Stdio::Null)
            .job(&job)
            .spawn()
            .unwrap();
        let status = wait(&mut child);
        // `STATUS_QUOTA_EXCEEDED`.
        assert_eq!(status.code(), Some(0xc000_0044_u32 as i32), "{status:?}");
        let accounting = job.accounting().unwrap();
        assert_eq!(accounting.terminated_processes, 1, "{accounting:?}");
        assert!(
            accounting.user_time >= Duration::from_millis(100),
            "{accounting:?}"
        );
    }

    #[test]
    fn pipes() {
        let (in_read, in_write) = io::pipe().unwrap();
        let (out_read, out_write) = io::pipe().unwrap();
        let (program, args) = filter();
        let mut child = Command::new(&program)
            .args(&args)
            .stdin(Stdio::Handle(in_read.as_handle()))
            .stdout(Stdio::Handle(out_write.as_handle()))
            .spawn()
            .unwrap();
        drop((in_read, out_write));
        assert_eq!(child.try_wait().unwrap(), None);
        write_all(&in_write, b"x one\nno\nx two\n");
        // The child reads until every write end is closed: this one is the
        // last, the child has none.
        drop(in_write);
        assert_eq!(read_text(&out_read), "x one\nx two\n");
        assert!(wait(&mut child).success());
    }

    #[test]
    fn files() {
        let dir = tmp_dir("process_files");
        std::fs::write(dir.join("in"), "x one\nno\nx two\n").unwrap();
        let input = File::open(dir.join("in")).unwrap();
        let output = File::create(dir.join("out")).unwrap();
        let (program, args) = filter();
        let mut child = Command::new(&program)
            .args(&args)
            .stdin(Stdio::Handle(handle_of(&input)))
            .stdout(Stdio::Handle(handle_of(&output)))
            .stderr(Stdio::Null)
            .spawn()
            .unwrap();
        assert!(wait(&mut child).success());
        let text = std::fs::read_to_string(dir.join("out")).unwrap();
        assert_eq!(text.replace('\r', ""), "x one\nx two\n");
        // The caller's handles are still its own.
        assert!(!io::is_inheritable(handle_of(&output)).unwrap());
    }

    #[test]
    fn null() {
        // Reading finds the end at once.
        let (program, args) = filter();
        let mut child = Command::new(&program)
            .args(&args)
            .stdin(Stdio::Null)
            .stdout(Stdio::Null)
            .stderr(Stdio::Null)
            .spawn()
            .unwrap();
        assert!(wait(&mut child).code().is_some());

        // Writing goes nowhere.
        let script = if cfg!(windows) {
            "echo out& echo err>&2& exit 3"
        } else {
            "echo out; echo err >&2; exit 3"
        };
        let shell = shell();
        let mut child = Command::new(&shell)
            .args(&[RUN, script])
            .stdin(Stdio::Null)
            .stdout(Stdio::Null)
            .stderr(Stdio::Null)
            .spawn()
            .unwrap();
        assert_eq!(wait(&mut child).code(), Some(3));
    }

    /// A handle that is not open cannot be given to a child.
    #[test]
    fn invalid_handle() {
        // On Windows -1 is a pseudo-handle, of the current process: take a
        // value no handle of a test process has.
        #[cfg(windows)]
        let values = [0x7ffc_0000usize as oscall::RawHandle];
        #[cfg(not(windows))]
        let values: [oscall::RawHandle; 2] = [-1, 1_000_000];
        let shell = shell();
        for raw in values {
            // SAFETY: the value is not an open handle, and is only used to
            // check that it is refused.
            let handle = unsafe { oscall::BorrowedHandle::borrow_raw(raw) };
            for target in 0..3 {
                let mut command = Command::new(&shell).args(&[RUN, "exit 0"]);
                command = match target {
                    0 => command.stdin(Stdio::Handle(handle)),
                    1 => command.stdout(Stdio::Handle(handle)),
                    _ => command.stderr(Stdio::Handle(handle)),
                };
                let error = command.spawn().unwrap_err();
                assert_eq!(error.kind(), ErrorKind::BadHandle, "{error:?}");
            }
        }
    }

    /// A child that waits for its input, and the write end of that input.
    fn blocked_child() -> (Child, OwnedHandle) {
        let (read, write) = io::pipe().unwrap();
        let (program, args) = filter();
        let child = Command::new(&program)
            .args(&args)
            .stdin(Stdio::Handle(read.as_handle()))
            .stdout(Stdio::Null)
            .stderr(Stdio::Null)
            .spawn()
            .unwrap();
        (child, write)
    }

    #[test]
    fn try_wait() {
        let (mut child, input) = blocked_child();
        for _ in 0..3 {
            assert_eq!(child.try_wait().unwrap(), None);
        }
        std::thread::sleep(Duration::from_millis(20));
        assert_eq!(child.try_wait().unwrap(), None);
        drop(input);
        let status = wait(&mut child);
        assert!(status.code().is_some());
        assert_eq!(child.try_wait().unwrap(), Some(status));
        assert_eq!(child.wait().unwrap(), status);
    }

    #[test]
    fn kill() {
        let (mut child, _input) = blocked_child();
        assert_eq!(child.try_wait().unwrap(), None);
        child.kill().unwrap();
        let status = child.wait().unwrap();
        assert!(!status.success());
        #[cfg(windows)]
        assert_eq!(status.code(), Some(1));
        #[cfg(not(windows))]
        {
            use oscall::process::unix::{ExitStatusExt, SIGKILL};
            assert_eq!(status.code(), None);
            assert_eq!(status.signal(), Some(SIGKILL));
            assert!(!status.core_dumped());
        }
        // Killing what is dead is not an error, and the status stays.
        child.kill().unwrap();
        assert_eq!(child.try_wait().unwrap(), Some(status));
        assert_eq!(child.wait().unwrap(), status);
    }

    /// A child that has exited by itself and has not been waited for.
    #[test]
    fn kill_after_exit() {
        let (mut child, input) = blocked_child();
        drop(input);
        // Leave it the time to exit; whether it has or not, `kill` works.
        std::thread::sleep(Duration::from_millis(200));
        child.kill().unwrap();
        let _ = child.wait().unwrap();
        child.kill().unwrap();
    }

    #[test]
    #[cfg(not(windows))]
    fn signals() {
        use oscall::process::unix::{self, ChildExt, ExitStatusExt};

        let (mut child, _input) = blocked_child();
        // Nothing is sent, the process is there.
        child.send_signal(0).unwrap();
        assert_eq!(child.try_wait().unwrap(), None);
        child.send_signal(unix::SIGTERM).unwrap();
        let status = child.wait().unwrap();
        assert_eq!(status.signal(), Some(unix::SIGTERM));
        assert_eq!(status.code(), None);
        assert!(!status.success());
        assert!(format!("{status}").contains("signal"));
        assert_eq!(
            child.send_signal(unix::SIGTERM).unwrap_err().kind(),
            ErrorKind::NoSuchProcess
        );

        // Stopped and continued, a child is still running.
        let (mut child, input) = blocked_child();
        child.send_signal(unix::SIGSTOP).unwrap();
        assert_eq!(child.try_wait().unwrap(), None);
        child.send_signal(unix::SIGCONT).unwrap();
        assert_eq!(child.try_wait().unwrap(), None);
        child.send_signal(unix::SIGKILL).unwrap();
        assert_eq!(child.wait().unwrap().signal(), Some(unix::SIGKILL));
        drop(input);

        // The others, for their values: the default action of each is to
        // terminate the process. (Not SIGQUIT: a shell ignores it.)
        assert_eq!(unix::SIGQUIT, 3);
        for signal in [unix::SIGHUP, unix::SIGINT, unix::SIGUSR1, unix::SIGUSR2] {
            let (mut child, _input) = blocked_child();
            child.send_signal(signal).unwrap();
            assert_eq!(child.wait().unwrap().signal(), Some(signal));
        }
    }

    /// The child starts with default dispositions, whatever the caller's
    /// are: Rust ignores SIGPIPE in this process, and the child dies of it.
    #[test]
    #[cfg(not(windows))]
    fn signal_dispositions() {
        use oscall::process::unix::ExitStatusExt;

        const SIGPIPE: i32 = 13;
        let (read, write) = io::pipe().unwrap();
        // Nobody reads.
        drop(read);
        let mut child = Command::new("/bin/sh")
            .args(&["-c", "echo one; echo two; exit 0"])
            .stdin(Stdio::Null)
            .stdout(Stdio::Handle(write.as_handle()))
            .stderr(Stdio::Null)
            .spawn()
            .unwrap();
        let status = wait(&mut child);
        assert_eq!(status.signal(), Some(SIGPIPE), "{status}");
    }

    #[test]
    fn missing_program() {
        let dir = tmp_dir("process_missing_program");
        for path in [dir.join("missing"), dir.join("missing").join("program")] {
            let error = Command::new(bytes(&path)).spawn().unwrap_err();
            assert_eq!(error.kind(), ErrorKind::NotFound, "{error:?}");
        }
        // The program is a path: a bare name is not looked up anywhere.
        let name = if cfg!(windows) { "cmd.exe" } else { "sh" };
        let error = Command::new(name).spawn().unwrap_err();
        assert_eq!(error.kind(), ErrorKind::NotFound, "{error:?}");
        let error = Command::new("").spawn().unwrap_err();
        assert!(
            matches!(error.kind(), ErrorKind::NotFound | ErrorKind::InvalidInput),
            "{error:?}"
        );
    }

    #[test]
    fn not_executable() {
        let dir = tmp_dir("process_not_executable");
        // A directory is never a program.
        let error = Command::new(bytes(&dir)).spawn().unwrap_err();
        assert_eq!(error.kind(), ErrorKind::PermissionDenied, "{error:?}");

        // Nor is a file without the permission to execute it. Windows has
        // no such permission; a file that is not a program image is its
        // own error there.
        let file = dir.join("script");
        std::fs::write(&file, "#!/bin/sh\nexit 5\n").unwrap();
        let command = Command::new(bytes(&file)).stdin(Stdio::Null);
        let error = command.spawn().unwrap_err();
        if cfg!(windows) {
            const ERROR_BAD_EXE_FORMAT: i32 = 193;
            assert_eq!(error.raw_os_error(), ERROR_BAD_EXE_FORMAT);
            return;
        }
        assert_eq!(error.kind(), ErrorKind::PermissionDenied, "{error:?}");

        // With it, the script runs; a relative path is a path too, and a
        // `Command` can be used any number of times.
        let executable = oscall::fs::Permissions::from_mode(0o755);
        oscall::fs::set_permissions(bytes(&file), executable).unwrap();
        assert!(format!("{command:?}").contains("script"));
        // A child another test created while the script was being written
        // still has it open, until it lets go.
        let spawn = |command: &Command<'_>| loop {
            match command.spawn() {
                Ok(child) => break child,
                Err(error) if error.kind() == ErrorKind::ExecutableFileBusy => {
                    std::thread::sleep(Duration::from_millis(2));
                }
                Err(error) => panic!("{error:?}"),
            }
        };
        for _ in 0..2 {
            let mut child = spawn(&command);
            assert_eq!(wait(&mut child).code(), Some(5));
        }
        let mut child = spawn(&command.clone());
        assert_eq!(wait(&mut child).code(), Some(5));
    }

    /// A handle the child was not given is not in the child, even when it
    /// is inheritable.
    #[test]
    fn nothing_else_is_inherited() {
        let (read, write) = io::pipe().unwrap();
        io::set_inheritable(&write, true).unwrap();
        let (mut child, input) = blocked_child();
        // Had the child the write end too, this read would last as long as
        // the child, which waits for us.
        drop(write);
        let (sender, receiver) = mpsc::channel();
        let reader = std::thread::spawn(move || {
            let mut buf = [0u8; 1];
            let _ = sender.send(io::read(&read, &mut buf));
        });
        let result = receiver.recv_timeout(Duration::from_secs(20));
        child.kill().unwrap();
        child.wait().unwrap();
        drop(input);
        reader.join().unwrap();
        match result {
            Ok(Ok(0)) => {}
            Ok(Err(error)) if error.kind() == ErrorKind::BrokenPipe => {}
            other => panic!("the child inherited the pipe: {other:?}"),
        }
    }

    /// The handle of a child is a real one, private to the process.
    #[test]
    #[cfg(any(target_os = "linux", target_os = "fullrust", windows))]
    fn child_handle() {
        let (mut child, input) = blocked_child();
        assert!(!io::is_inheritable(child.as_handle()).unwrap());
        let copy = io::duplicate(&child).unwrap();
        drop(input);
        wait(&mut child);
        drop(copy);
    }

    #[test]
    fn concurrent_spawns() {
        let threads: Vec<_> = (0..8)
            .map(|thread| {
                std::thread::spawn(move || {
                    for round in 0..8 {
                        let token = thread * 10 + round;
                        let script = if cfg!(windows) {
                            format!("echo {token}& exit {token}")
                        } else {
                            format!("echo {token}; exit {token}")
                        };
                        let output = run(&script);
                        assert_eq!(output.stdout, format!("{token}\n"));
                        assert_eq!(output.stderr, "");
                        assert_eq!(output.status.code(), Some(token));
                    }
                })
            })
            .collect();
        for thread in threads {
            thread.join().unwrap();
        }
    }
}