oscall 0.0.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
//! `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);
    }
}

/// 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();
    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);
    }
    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);
    }

    /// 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();
    }

    #[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();
        }
    }
}