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
//! Processes: the current one, and child processes.
//!
//! [`id`], [`parent_id`], [`exit`] and [`abort`] concern the current
//! process, [`args`] and [`vars`] what it was started with. A [`Command`] describes a program to run and [`Command::spawn`]
//! starts it as a [`Child`], which is waited for with [`Child::wait`] and
//! gives an [`ExitStatus`]. [`Signals`] receives the requests to stop that
//! the system or the user send the process: Unix signals, Windows console
//! control events.
//!
//! # What a child process receives
//!
//! The same on every platform, whatever the rest of the program does:
//!
//! - **The program** is a path, used as given. No search path is consulted,
//!   on any platform, and no extension is added (`cmd.exe`, not `cmd`):
//!   [`find_program`] does the search, in the directories it is given.
//! - **The arguments** as byte strings, exactly (see [`Command::args`]).
//! - **The environment**: the caller's, or the list given to
//!   [`Command::env`].
//! - **A working directory**: the caller's, or [`Command::current_dir`].
//! - **Three standard handles**, each one the caller's own, the null device
//!   or a handle given by the caller ([`Stdio`]). **Nothing else**: no other
//!   handle of the calling process reaches the child, not even one made
//!   inheritable with [`set_inheritable`](crate::io::set_inheritable) or
//!   opened by other code without close-on-exec.
//! - On Linux and macOS, default dispositions for every signal (nothing
//!   ignored, which undoes Rust's own ignoring of `SIGPIPE`) and an empty
//!   signal mask.
//!
//! Spawning builds the argument and environment blocks the system wants, and
//! needs the `alloc` feature for it.
//!
//! # Setting a child up, and containing it
//!
//! What a child can be given before its program starts has no form the
//! systems share, and is in the extension modules:
//!
//! - `unix::CommandExt`: a process group or a session, resource limits,
//!   a user, groups and a file creation mask;
//! - `linux::CommandExt`: new namespaces and their user maps, a cgroup
//!   (which is what limits the memory of a child and of everything it
//!   starts), a signal to receive when the parent goes away; and
//!   `linux::ConfineExt`: the capabilities it keeps, a system call filter
//!   and who answers for it, the clocks of a time namespace;
//! - `windows::CommandExt`: a console process group, a console, and a
//!   `windows::Job` to be created in, which limits the memory, the
//!   processor time and the number of the processes in it, and can
//!   terminate them all, also when the parent goes away.
//!
//! `unix::fork` duplicates the calling process.
//!
//! # Other processes
//!
//! [`resource_usage`] says what the process has consumed, and
//! [`Child::resource_usage`] what a child did; `unix::limit` reads and
//! sets the limits of the process.
//!
//! Process descriptors are in `linux`.
//!
//! [`exists`] and [`kill`] take the identifier of any process. Signals,
//! process groups and sessions are in `unix`, console process groups in
//! `windows`.
//!
//! # Not covered
//!
//! Scheduling priorities: a Unix `nice` value and a Windows priority class
//! have no meaning in common. What a thread can set for itself is in the
//! extensions of [`thread`](crate::thread).
//!
//! Setting a variable of the environment: see [`vars`].
//!
//! Asking another process to stop has no portable form either: a signal
//! reaches any process (`unix::send_signal`), a console control event only
//! the processes of a console, by group (`windows::send_ctrl_event`).
//!
//! oscall installs no signal handler unless a [`Signals`] exists.
//!
//! # WebAssembly
//!
//! There are no processes: [`id`] and [`parent_id`] are `0`,
//! [`Command::spawn`] fails with [`ErrorKind::Unsupported`](crate::ErrorKind).
//! [`exit`], [`args`] and [`vars`] work on WASI; without WASI, [`exit`] and
//! [`abort`] trap and the other two fail.

#[cfg(feature = "alloc")]
use core::fmt;
#[cfg(feature = "alloc")]
use core::marker::PhantomData;

pub(crate) mod env;
#[cfg(any(target_os = "linux", target_os = "fullrust"))]
pub mod linux;
mod signal;

pub use env::{Args, Vars, args, vars};
#[cfg(feature = "alloc")]
pub use env::{Var, args_vec, vars_vec};

pub(crate) use signal::Wake;
pub use signal::{Signal, Signals};

#[cfg(feature = "alloc")]
use crate::BorrowedHandle;
use core::time::Duration;

use crate::sys;
use crate::{AsPath, ErrorKind, Result};

/// The identifier of the current process.
///
/// `0` on WebAssembly, which has no processes.
#[inline]
pub fn id() -> u32 {
    sys::process::id()
}

/// The identifier of the process that created the current one.
///
/// `0` when there is none to report: on Linux when the parent lives in
/// another process namespace, on WebAssembly always.
///
/// On Linux and macOS, a process whose parent has exited is adopted, usually
/// by process 1, and this changes accordingly. Windows keeps no such link:
/// the identifier is the creator's even after it has exited, and may by then
/// name an unrelated process.
#[inline]
pub fn parent_id() -> u32 {
    sys::process::parent_id()
}

/// Terminates the current process at once, with `code` as its exit code.
///
/// Nothing of the program runs any more: no destructor, no `atexit`
/// function, no panic hook. Buffers held in memory are not written out,
/// which includes those of `std::io::stdout()` and of C's `stdio`. The
/// other threads are stopped wherever they are.
///
/// `exit_group` on Linux, `_exit` on macOS, `proc_exit` on WASI.
/// `ExitProcess` on Windows, which still notifies the loaded DLLs
/// (`DLL_PROCESS_DETACH`) once the other threads are gone.
///
/// Only the low 8 bits of `code` reach the parent on Linux and macOS. WASI
/// accepts codes from 0 to 125 only.
///
/// On WebAssembly without WASI there is no process to exit: this traps.
#[inline]
pub fn exit(code: i32) -> ! {
    sys::process::exit(code)
}

/// Terminates the current process abnormally, at once.
///
/// As for [`exit`], nothing of the program runs any more and nothing is
/// flushed.
///
/// On Linux and macOS the process raises `SIGABRT` and dies of it, which a
/// parent sees as a termination by signal, and which may write a core dump.
/// A handler the program installed for `SIGABRT` runs first; if it returns,
/// the process is killed all the same. On Windows this is a fail-fast
/// (`__fastfail(FAST_FAIL_FATAL_APP_EXIT)`), reported to the parent as exit
/// code `0xC0000409`. On WebAssembly it is a trap.
#[inline]
pub fn abort() -> ! {
    sys::process::abort()
}

/// Looks for the program `name` in the directories of `search_path`, the
/// way a shell does with `PATH`: writes the path of the first match into
/// `buf` and returns its length. The result is what `Command::new` takes.
///
/// `search_path` is a list of directories in the system's notation:
/// separated by `:` on Linux and macOS, by `;` on Windows (where a
/// directory may be written between double quotes). It is given by the
/// caller, typically from the `PATH` environment variable, which oscall
/// does not read; nothing else is searched, on any platform: not the
/// current directory, not the system directories Windows adds of its own.
/// An empty entry is skipped (a shell takes it to mean the current
/// directory). A relative directory gives a relative result.
///
/// A match is a regular file, or a link to one, which on Linux and macOS
/// the caller has the permission to execute (`faccessat` with the effective
/// identity). Windows has no such permission.
///
/// On Windows a `name` without an extension is looked for with `.exe`
/// added, and only so; a name with an extension is looked for as it is.
/// `PATHEXT` is not consulted: what it names besides `.exe` are mostly
/// scripts, which only a command interpreter can run (`cmd.exe /C`).
///
/// A `name` that contains a directory separator (or, on Windows, a drive
/// letter) is a path already: it is not searched for, only checked, and
/// copied to `buf` unchanged.
///
/// Nothing guarantees the file is still there, or still the same, when it
/// is run.
///
/// # Errors
///
/// [`ErrorKind::NotFound`] if no directory has the program,
/// [`ErrorKind::BufferTooSmall`] if a path to check does not fit in `buf`,
/// and [`ErrorKind::InvalidInput`] if `name` or `search_path` contains a
/// NUL. Without the `alloc` feature, a candidate longer than 511 bytes
/// cannot be checked and is passed over.
///
/// On WebAssembly there are no programs to run: fails with
/// [`ErrorKind::Unsupported`].
pub fn find_program<N: AsPath + ?Sized, S: AsPath + ?Sized>(
    name: &N,
    search_path: &S,
    buf: &mut [u8],
) -> Result<usize> {
    let name = name.as_path_bytes();
    let search_path = search_path.as_path_bytes();
    if !sys::process::HAS_PROCESSES {
        return Err(ErrorKind::Unsupported.into());
    }
    if name.contains(&0) || search_path.contains(&0) {
        return Err(ErrorKind::InvalidInput.into());
    }
    if name.is_empty() {
        return Err(ErrorKind::NotFound.into());
    }
    // Puts the parts end to end in `buf` and checks the result.
    let mut check = |parts: &[&[u8]]| -> Result<Option<usize>> {
        let mut len = 0;
        for part in parts {
            buf.get_mut(len..len + part.len())
                .ok_or(ErrorKind::BufferTooSmall)?
                .copy_from_slice(part);
            len += part.len();
        }
        Ok(sys::process::is_program(&buf[..len]).then_some(len))
    };
    if !sys::process::is_bare_name(name) {
        return check(&[name])?.ok_or(ErrorKind::NotFound.into());
    }
    let suffix: &[u8] = if name.contains(&b'.') {
        b""
    } else {
        sys::process::PROGRAM_SUFFIX
    };
    for dir in search_path.split(|&c| c == sys::process::SEARCH_SEPARATOR) {
        let dir = sys::process::search_dir(dir);
        let Some(&last) = dir.last() else {
            continue;
        };
        let separator: &[u8] = if sys::fs::is_separator(last) {
            b""
        } else {
            sys::process::DIR_SEPARATOR
        };
        if let Some(len) = check(&[dir, separator, name, suffix])? {
            return Ok(len);
        }
    }
    Err(ErrorKind::NotFound.into())
}

/// As [`find_program`], returning the path in a `Vec`.
#[cfg(feature = "alloc")]
pub fn find_program_vec<N: AsPath + ?Sized, S: AsPath + ?Sized>(
    name: &N,
    search_path: &S,
) -> Result<alloc::vec::Vec<u8>> {
    let name = name.as_path_bytes();
    let search_path = search_path.as_path_bytes();
    // The longest candidate, with a separator and the suffix.
    let len = name.len() + search_path.len() + 1 + sys::process::PROGRAM_SUFFIX.len();
    let mut buf = alloc::vec::Vec::new();
    buf.try_reserve_exact(len)
        .map_err(|_| ErrorKind::OutOfMemory)?;
    buf.resize(len, 0);
    let len = find_program(name, search_path, &mut buf)?;
    buf.truncate(len);
    Ok(buf)
}

/// Whether `pid` is the identifier of a process.
///
/// The answer is about the past: the process may exit at any time, and the
/// system may later give its identifier to another one. Only a `Child`
/// names a process for sure.
///
/// On Linux and macOS a process that has exited still exists until its
/// parent has waited for it; on Windows it does not, even while handles to
/// it remain open. `kill(pid, 0)` on Linux and macOS; `OpenProcess` and
/// `WaitForSingleObject` on Windows.
///
/// # Errors
///
/// [`ErrorKind::InvalidInput`] if `pid` is 0 or does not fit in the
/// system's type. On WebAssembly, [`ErrorKind::Unsupported`].
pub fn exists(pid: u32) -> Result<bool> {
    sys::process::exists(checked_pid(pid)?)
}

/// Terminates the process `pid` at once, as `Child::kill` does a child:
/// `SIGKILL` on Linux and macOS, `TerminateProcess` (with exit code 1) on
/// Windows. The caller must be allowed to: the same user, roughly.
///
/// An identifier only names a process for as long as the process exists:
/// by the time of the call it may name another one. Prefer `Child::kill`
/// for a child.
///
/// # Errors
///
/// [`ErrorKind::InvalidInput`] if `pid` is 0 or does not fit in the
/// system's type. When there is no such process,
/// [`ErrorKind::NoSuchProcess`] on Linux and macOS, and
/// [`ErrorKind::InvalidInput`] on Windows, which says no more
/// (`ERROR_INVALID_PARAMETER`). [`ErrorKind::PermissionDenied`] when the
/// process is someone else's. On WebAssembly, [`ErrorKind::Unsupported`].
pub fn kill(pid: u32) -> Result<()> {
    sys::process::kill(checked_pid(pid)?)
}

/// What a process has consumed: see [`resource_usage`] and
/// `Child::resource_usage`.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub struct ResourceUsage {
    pub(crate) user_time: Duration,
    pub(crate) system_time: Duration,
    pub(crate) max_resident_memory: u64,
}

impl ResourceUsage {
    /// The processor time spent running the program's own code, summed
    /// over its threads.
    #[inline]
    pub const fn user_time(&self) -> Duration {
        self.user_time
    }

    /// The processor time the system spent working for the process, summed
    /// over its threads.
    #[inline]
    pub const fn system_time(&self) -> Duration {
        self.system_time
    }

    /// The most physical memory the process had in use at one time, in
    /// bytes: the peak resident set size on Linux (counted in kibibytes)
    /// and macOS, the peak working set size on Windows.
    ///
    /// Linux keeps the count per processor and adds it up lazily: the
    /// value is approximate, short by megabytes on a machine with many
    /// processors, and can be 0 for a small process that did not live
    /// long.
    #[inline]
    pub const fn max_resident_memory(&self) -> u64 {
        self.max_resident_memory
    }
}

/// What the current process has consumed so far, all threads together.
/// The children it has waited for are not counted.
///
/// `getrusage(RUSAGE_SELF)` on Linux and macOS; `NtQueryInformationProcess`
/// on Windows (what `GetProcessTimes` and `GetProcessMemoryInfo` report).
/// How finely the times are counted is up to the system: Linux and Windows
/// may account by clock ticks. [`Clock::ProcessCpu`](crate::time::Clock)
/// is the precise clock of the two times together.
///
/// On WebAssembly: fails with [`ErrorKind::Unsupported`].
pub fn resource_usage() -> Result<ResourceUsage> {
    sys::process::resource_usage()
}

/// A process identifier that names one process: not 0 or a negative
/// number, which mean groups of processes to the Unix calls.
fn checked_pid(pid: u32) -> Result<u32> {
    if pid == 0 || pid > i32::MAX as u32 {
        return Err(ErrorKind::InvalidInput.into());
    }
    Ok(pid)
}

/// A list of byte strings borrowed from the caller: a slice of anything
/// that is [`AsPath`], behind one type.
#[cfg(feature = "alloc")]
#[derive(Clone, Copy)]
pub(crate) struct List<'a> {
    data: *const (),
    len: usize,
    /// Returns element `i` of the slice at `data`.
    get: unsafe fn(*const (), usize) -> *const [u8],
    marker: PhantomData<&'a [u8]>,
}

#[cfg(feature = "alloc")]
impl<'a> List<'a> {
    fn new<S: AsPath>(items: &'a [S]) -> Self {
        /// # Safety
        ///
        /// `data` must point to a live slice of `S` longer than `i`.
        unsafe fn get<S: AsPath>(data: *const (), i: usize) -> *const [u8] {
            // SAFETY: the caller's contract.
            unsafe { &*data.cast::<S>().add(i) }.as_path_bytes()
        }
        Self {
            data: items.as_ptr().cast(),
            len: items.len(),
            get: get::<S>,
            marker: PhantomData,
        }
    }

    fn empty() -> Self {
        Self::new::<&[u8]>(&[])
    }

    /// The strings, in order.
    #[allow(dead_code)]
    pub(crate) fn iter(self) -> impl Iterator<Item = &'a [u8]> {
        // SAFETY: `data` and `len` come from a slice borrowed for 'a, of
        // the type `get` was instantiated for, and the bytes an element
        // returns are borrowed from it.
        (0..self.len).map(move |i| unsafe { &*(self.get)(self.data, i) })
    }
}

/// Where one of the standard handles of a child process comes from.
#[cfg(feature = "alloc")]
#[derive(Clone, Copy, Debug, Default)]
#[non_exhaustive]
pub enum Stdio<'a> {
    /// The corresponding standard handle of the calling process (the
    /// default). If the caller has none, neither has the child.
    #[default]
    Inherit,
    /// The null device (`/dev/null`, `NUL`): reads find the end of the file
    /// at once, writes are discarded.
    Null,
    /// A duplicate of this handle: a file, an end of a
    /// [`pipe`](crate::io::pipe)... The caller keeps its own handle, which
    /// need not be inheritable, and usually closes it after spawning: the
    /// read end of a pipe only sees the end of the stream once every
    /// handle to the write end is closed.
    Handle(BorrowedHandle<'a>),
}

/// The description of a process to create.
///
/// A `Command` borrows everything it is given and allocates nothing until
/// [`spawn`](Self::spawn). It can spawn any number of children.
///
/// ```no_run
/// use oscall::process::{Command, Stdio};
///
/// let mut child = Command::new("/bin/sh")
///     .args(&["-c", "echo hello"])
///     .stdin(Stdio::Null)
///     .spawn()?;
/// assert!(child.wait()?.success());
/// # Ok::<(), oscall::Error>(())
/// ```
#[cfg(feature = "alloc")]
#[derive(Clone)]
pub struct Command<'a> {
    pub(crate) program: &'a [u8],
    pub(crate) arg0: Option<&'a [u8]>,
    pub(crate) args: List<'a>,
    pub(crate) env: Option<List<'a>>,
    pub(crate) current_dir: Option<&'a [u8]>,
    pub(crate) stdio: [Stdio<'a>; 3],
    /// Windows only: the whole command line, replacing `arg0` and `args`.
    #[allow(dead_code)]
    pub(crate) raw_command_line: Option<&'a [u8]>,
    /// Windows only: `CREATE_NEW_PROCESS_GROUP`.
    #[allow(dead_code)]
    pub(crate) new_process_group: bool,
    /// Linux and macOS only: the process group to join, 0 for a new one.
    #[allow(dead_code)]
    pub(crate) process_group: Option<u32>,
    /// Linux and macOS only: `setsid`.
    #[allow(dead_code)]
    pub(crate) new_session: bool,
    /// Windows only: `CREATE_NEW_CONSOLE`.
    #[allow(dead_code)]
    pub(crate) new_console: bool,
    /// What `linux::CommandExt` sets.
    #[cfg(any(target_os = "linux", target_os = "fullrust"))]
    pub(crate) linux: linux::Options<'a>,
    /// Linux and macOS only: what else `unix::CommandExt` sets.
    #[cfg(any(target_os = "linux", target_os = "fullrust", target_os = "macos"))]
    pub(crate) setup: unix::Setup<'a>,
    /// Windows only: the job object to create the child in.
    #[cfg(windows)]
    pub(crate) job: Option<BorrowedHandle<'a>>,
}

#[cfg(feature = "alloc")]
impl<'a> Command<'a> {
    /// A command that runs the program at `program`, with no arguments, the
    /// caller's environment, working directory and standard handles.
    ///
    /// `program` is a path, absolute or relative to the working directory
    /// of the caller, like every path given to oscall, and whether or not
    /// [`current_dir`](Self::current_dir) gives the child another one. It
    /// is never looked up in `PATH`, and on Windows no `.exe` is added: see
    /// [`find_program`].
    ///
    /// What the file must be is the system's business: an executable or a
    /// script with a `#!` line on Linux and macOS, an executable image on
    /// Windows.
    ///
    /// Not a batch file: on Windows, [`spawn`](Self::spawn) fails with
    /// [`ErrorKind::InvalidInput`] when the name of the program ends in
    /// `.bat` or `.cmd` (whatever the case, and however the name is
    /// spelled: with dots and spaces after it, or as `x.bat\.`, which the
    /// system all takes for `x.bat`). The system would run it with
    /// `cmd.exe`, which splits the command line by rules of its own:
    /// arguments quoted for an ordinary program can then run other
    /// commands. To run a batch file, name `cmd.exe` as the program and
    /// write the command line `cmd.exe` is to see with
    /// `windows::CommandExt::raw_command_line` (`cmd /C ...`), quoted for
    /// it; the check does not apply to a command that has one.
    pub fn new<P: AsPath + ?Sized>(program: &'a P) -> Self {
        Self {
            program: program.as_path_bytes(),
            arg0: None,
            args: List::empty(),
            env: None,
            current_dir: None,
            stdio: [Stdio::Inherit; 3],
            raw_command_line: None,
            new_process_group: false,
            process_group: None,
            new_session: false,
            new_console: false,
            #[cfg(any(target_os = "linux", target_os = "fullrust"))]
            linux: linux::Options::default(),
            #[cfg(any(target_os = "linux", target_os = "fullrust", target_os = "macos"))]
            setup: unix::Setup::NONE,
            #[cfg(windows)]
            job: None,
        }
    }

    /// Sets the arguments of the program, not counting the first one of
    /// its `argv`, which is the program's name (see [`arg0`](Self::arg0)).
    ///
    /// The arguments are byte strings: anything but NUL on Linux and
    /// macOS, WTF-8 on Windows, like paths ([`AsPath`]), and they reach the
    /// child exactly as given. Windows has no argument list, only a command
    /// line that each program splits itself: oscall builds it with the
    /// quoting rules of `CommandLineToArgvW` and of the C runtime, which
    /// nearly every program uses, exactly like `std`. For the programs that
    /// parse it differently (`cmd.exe`), see
    /// `windows::CommandExt::raw_command_line`.
    ///
    /// An argument that contains a NUL makes [`spawn`](Self::spawn) fail
    /// with [`ErrorKind::InvalidInput`].
    pub fn args<S: AsPath>(mut self, args: &'a [S]) -> Self {
        self.args = List::new(args);
        self
    }

    /// Sets the first element of the program's `argv`, the name it sees
    /// itself called by. By default it is the path given to
    /// [`new`](Self::new).
    ///
    /// On Windows it is the first token of the command line, and cannot
    /// contain a `"`.
    pub fn arg0<S: AsPath + ?Sized>(mut self, arg0: &'a S) -> Self {
        self.arg0 = Some(arg0.as_path_bytes());
        self
    }

    /// Sets the whole environment of the child: a list of `NAME=value`
    /// strings, with the encoding of arguments. An empty list gives an
    /// empty environment.
    ///
    /// Each string must have a name: a `=` somewhere after its first
    /// byte (the first may itself be a `=`: Windows keeps variables named
    /// `=C:`). An empty string, one without a `=`, one that starts with
    /// its only `=`, or one that contains a NUL makes
    /// [`spawn`](Self::spawn) fail with [`ErrorKind::InvalidInput`], on
    /// every platform: such an entry is ignored by some programs, taken
    /// for the end of the environment by others. Duplicates are not
    /// looked for.
    ///
    /// On Linux and macOS the list is passed in the order given. On
    /// Windows the system wants the variables sorted by name, without
    /// regard to case, and oscall sorts them so (`CompareStringOrdinal`);
    /// variables of the same name stay in the order given.
    ///
    /// Without this call the child inherits the environment of the calling
    /// process, which means:
    ///
    /// - on Windows and macOS, the environment as it is when `spawn` is
    ///   called;
    /// - on Linux, where the environment is kept by the language runtime
    ///   and not by the system: with the `std` feature, what
    ///   `std::env::vars_os` returns at the time of the call (changes made
    ///   by C code with `setenv` are seen when the program links a libc);
    ///   without `std`, the environment the process was *started* with,
    ///   read from `/proc/self/environ` (`spawn` fails if `/proc` is not
    ///   mounted).
    pub fn env<S: AsPath>(mut self, vars: &'a [S]) -> Self {
        self.env = Some(List::new(vars));
        self
    }

    /// Sets the working directory of the child. By default it is the
    /// caller's.
    ///
    /// A directory that cannot be entered makes [`spawn`](Self::spawn) fail.
    ///
    /// This does not change what a relative program path means: on Linux
    /// and macOS, where the system would look for it from the child's
    /// directory, `spawn` makes it absolute first, with the caller's
    /// current directory (`getcwd`; the program then sees the absolute
    /// path where the system shows it the path it was started by, as a
    /// script's interpreter does). The first argument is not changed.
    pub fn current_dir<P: AsPath + ?Sized>(mut self, dir: &'a P) -> Self {
        self.current_dir = Some(dir.as_path_bytes());
        self
    }

    /// Sets the standard input of the child.
    pub fn stdin(mut self, stdio: Stdio<'a>) -> Self {
        self.stdio[0] = stdio;
        self
    }

    /// Sets the standard output of the child.
    pub fn stdout(mut self, stdio: Stdio<'a>) -> Self {
        self.stdio[1] = stdio;
        self
    }

    /// Sets the standard error output of the child.
    pub fn stderr(mut self, stdio: Stdio<'a>) -> Self {
        self.stdio[2] = stdio;
        self
    }

    /// Starts the program as a child process.
    ///
    /// A program that cannot be started is reported here, with the
    /// system's reason, and no child is left behind:
    /// [`ErrorKind::NotFound`] if the file does not exist,
    /// [`ErrorKind::PermissionDenied`] if it may not be executed or is a
    /// directory.
    ///
    /// This may be called from several threads at once: each child gets
    /// its own standard handles and no one else's.
    ///
    /// - **Linux**: there is no libc to do it. All signals are blocked,
    ///   the child is created with `clone(CLONE_VM | CLONE_VFORK)` on a
    ///   stack of its own, sets itself up with raw system calls and calls
    ///   `execve`; the caller is suspended until then. Every descriptor
    ///   other than the three standard ones is closed in the child
    ///   (`close_range`). The child is tracked by a pidfd. A child that
    ///   is given another user or group (`unix::CommandExt`) is created
    ///   with a copy of the caller's memory instead, as `fork` does
    ///   (`clone(CLONE_VFORK)` without `CLONE_VM`: the caller is
    ///   suspended all the same): the kernel marks the memory of a
    ///   process that changes identity as not to be dumped or debugged,
    ///   and that must not be the caller's. It costs the copy of the page
    ///   tables.
    /// - **macOS**: `posix_spawn`, with `POSIX_SPAWN_CLOEXEC_DEFAULT`. A
    ///   command with limits, a user, groups or a file creation mask
    ///   (`unix::CommandExt`), which `posix_spawn` cannot set, calls
    ///   `fork` first: the child sets those, its session or group, its
    ///   standard descriptors and its directory with async-signal-safe
    ///   calls, and replaces itself with the program by `posix_spawn`
    ///   with `POSIX_SPAWN_SETEXEC`, which closes everything else and
    ///   resets the signals as for any other child.
    /// - **Windows**: `CreateProcessW` with an explicit list of the handles
    ///   to inherit (`PROC_THREAD_ATTRIBUTE_HANDLE_LIST`). The handles the
    ///   child receives are inheritable duplicates that exist for the
    ///   duration of the call; a process created meanwhile by other code,
    ///   with plain handle inheritance, would get them too.
    /// - **WebAssembly**: fails with [`ErrorKind::Unsupported`].
    ///
    /// # A program that was just written
    ///
    /// On Linux and macOS, running a file that any process still has open
    /// for writing fails with [`ErrorKind::ExecutableFileBusy`]. In a program
    /// with several threads this can happen after the file was closed: a
    /// child created by another thread in the meantime holds a copy of the
    /// descriptor until it calls `execve`. A program that writes an
    /// executable and runs it at once should try again on that error.
    pub fn spawn(&self) -> Result<Child> {
        if sys::process::HAS_PROCESSES
            && let Some(vars) = self.env
        {
            for var in vars.iter() {
                let named = var.iter().skip(1).any(|&byte| byte == b'=');
                if !named || var.contains(&0) {
                    return Err(ErrorKind::InvalidInput.into());
                }
            }
        }
        let inner = sys::process::spawn(self)?;
        Ok(Child {
            inner,
            status: None,
            usage: None,
        })
    }
}

#[cfg(feature = "alloc")]
impl fmt::Debug for Command<'_> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        /// Bytes as a string, lossily.
        struct Bytes<'a>(&'a [u8]);
        impl fmt::Debug for Bytes<'_> {
            fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
                fmt::Debug::fmt(&alloc::string::String::from_utf8_lossy(self.0), f)
            }
        }
        /// A list of them.
        struct Strings<'a>(List<'a>);
        impl fmt::Debug for Strings<'_> {
            fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
                f.debug_list().entries(self.0.iter().map(Bytes)).finish()
            }
        }
        f.debug_struct("Command")
            .field("program", &Bytes(self.program))
            .field("arg0", &self.arg0.map(Bytes))
            .field("args", &Strings(self.args))
            .field("env", &self.env.map(Strings))
            .field("current_dir", &self.current_dir.map(Bytes))
            .field("stdin", &self.stdio[0])
            .field("stdout", &self.stdio[1])
            .field("stderr", &self.stdio[2])
            .finish_non_exhaustive()
    }
}

/// A child process.
///
/// Dropping a `Child` neither waits for the process nor kills it: it keeps
/// running. On Linux and macOS a child that has exited stays in the process
/// table as a zombie until its parent waits for it (or exits itself):
/// call [`wait`](Self::wait), or [`try_wait`](Self::try_wait) until it
/// returns a status, before dropping the `Child` of a process that is not
/// meant to outlive the caller. Once dropped, the child can no longer be
/// waited for through oscall.
///
/// On Linux and macOS a child can be collected behind oscall's back: by
/// the system, when the program ignores `SIGCHLD`, or by other code that
/// waits for any child (`wait`, `waitpid(-1)`). Its status is then lost:
/// once it has exited, [`wait`](Self::wait) and
/// [`try_wait`](Self::try_wait) fail with the system's `ECHILD`, on every
/// call, and the `Child` is finished as far as oscall is concerned:
/// [`kill`](Self::kill) does nothing, and no signal is sent to its
/// identifier, which may be another process's by then.
///
/// On Linux and on Windows a `Child` holds a handle that becomes readable
/// (Linux, a pidfd) or signaled (Windows, the process handle) when the
/// process exits, and implements [`AsHandle`](crate::AsHandle) to lend it.
/// macOS has only the process identifier.
#[cfg(feature = "alloc")]
#[derive(Debug)]
pub struct Child {
    inner: sys::process::Child,
    /// Set once the child has been waited for: the system has then
    /// forgotten the process, and its identifier may name another one.
    status: Option<ExitStatus>,
    /// What the child consumed, when the wait that found it had exited
    /// could tell.
    usage: Option<ResourceUsage>,
}

#[cfg(feature = "alloc")]
impl Child {
    /// The process identifier of the child.
    ///
    /// Once the child has been waited for, the system may give the same
    /// identifier to another process.
    #[inline]
    pub fn id(&self) -> u32 {
        self.inner.id()
    }

    /// Waits for the child to exit and returns how it did.
    ///
    /// Once the child has exited, every call returns the same status
    /// without asking the system again.
    ///
    /// Nothing is done to the child's standard input: a child that reads
    /// it until the end only exits once every handle to the other end is
    /// closed.
    ///
    /// On Linux and macOS, fails with [`ErrorKind::Interrupted`] when a
    /// signal handler runs during the wait; it can be called again.
    ///
    /// `waitid(P_PIDFD)` on Linux, `waitpid` on macOS,
    /// `WaitForSingleObject` and `GetExitCodeProcess` on Windows.
    pub fn wait(&mut self) -> Result<ExitStatus> {
        if let Some(status) = self.status {
            return Ok(status);
        }
        match self.inner.wait(true)? {
            Some((status, usage)) => {
                self.status = Some(status);
                self.usage = usage;
                Ok(status)
            }
            // The system returned from a blocking wait with no child.
            None => Err(ErrorKind::Other.into()),
        }
    }

    /// The exit status of the child if it has exited, `None` if it is still
    /// running. Never blocks.
    pub fn try_wait(&mut self) -> Result<Option<ExitStatus>> {
        if self.status.is_none()
            && let Some((status, usage)) = self.inner.wait(false)?
        {
            self.status = Some(status);
            self.usage = usage;
        }
        Ok(self.status)
    }

    /// What the child consumed in its whole life, once it has been waited
    /// for: `None` until [`wait`](Self::wait) or
    /// [`try_wait`](Self::try_wait) has returned its status.
    ///
    /// On Linux and macOS the system hands this over with the status
    /// (`waitid`, `wait4`), and it includes the descendants of the child
    /// that the child itself waited for. On Windows it is asked of the
    /// process object once the process has exited, and covers that process
    /// alone; `None` if the system refused to tell.
    pub fn resource_usage(&self) -> Option<ResourceUsage> {
        self.usage
    }

    /// Terminates the child at once, without giving it a chance to clean
    /// up: `SIGKILL` on Linux and macOS, `TerminateProcess` (with exit code
    /// 1) on Windows.
    ///
    /// This only asks: [`wait`](Self::wait) afterwards to know that the
    /// process is gone, and to collect it. The processes the child started
    /// itself are not affected.
    ///
    /// Succeeds and does nothing if the child has already exited, or was
    /// collected by other code (see [`Child`]).
    pub fn kill(&self) -> Result<()> {
        if self.status.is_some() {
            return Ok(());
        }
        self.inner.kill()
    }

    /// The system's side of the child, for the
    /// [`Poller`](crate::event::Poller) that registers it.
    #[inline]
    pub(crate) fn sys(&self) -> &sys::process::Child {
        &self.inner
    }

    /// Whether the status of the child has been collected: the system has
    /// then forgotten the process, and its identifier names nothing, or
    /// another process.
    #[inline]
    pub(crate) fn collected(&self) -> bool {
        self.status.is_some()
    }
}

/// On Linux and Windows, the handle that tracks the child: a pidfd, a
/// process handle.
#[cfg(all(
    feature = "alloc",
    any(target_os = "linux", target_os = "fullrust", windows)
))]
impl crate::AsHandle for Child {
    #[inline]
    fn as_handle(&self) -> BorrowedHandle<'_> {
        self.inner.handle()
    }
}

/// How a process ended.
#[cfg(feature = "alloc")]
#[derive(Clone, Copy, PartialEq, Eq, Hash)]
pub struct ExitStatus(Status);

#[cfg(feature = "alloc")]
#[derive(Clone, Copy, PartialEq, Eq, Hash)]
enum Status {
    /// The process exited with this code.
    Exited(i32),
    /// The process was terminated by this signal (Linux, macOS), and
    /// perhaps dumped core.
    #[allow(dead_code)]
    Signaled(i32, bool),
}

#[cfg(feature = "alloc")]
impl ExitStatus {
    #[allow(dead_code)]
    pub(crate) fn exited(code: i32) -> Self {
        Self(Status::Exited(code))
    }

    #[allow(dead_code)]
    pub(crate) fn signaled(signal: i32, core_dumped: bool) -> Self {
        Self(Status::Signaled(signal, core_dumped))
    }

    /// Whether the process exited with code 0.
    #[inline]
    pub fn success(&self) -> bool {
        self.0 == Status::Exited(0)
    }

    /// The exit code of the process: what it returned from `main` or passed
    /// to `exit`.
    ///
    /// On Linux and macOS it is between 0 and 255, and `None` when the
    /// process was terminated by a signal instead (see
    /// `unix::ExitStatusExt::signal`). On Windows it is always `Some`,
    /// and any 32-bit value: a process that was terminated has the code
    /// given by whoever terminated it, one that crashed has the exception
    /// code (`0xC0000005` for an access violation, a negative `i32`).
    #[inline]
    pub fn code(&self) -> Option<i32> {
        match self.0 {
            Status::Exited(code) => Some(code),
            Status::Signaled(..) => None,
        }
    }
}

#[cfg(feature = "alloc")]
impl fmt::Debug for ExitStatus {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self.0 {
            Status::Exited(code) => write!(f, "ExitStatus(code {code})"),
            Status::Signaled(signal, _) => write!(f, "ExitStatus(signal {signal})"),
        }
    }
}

#[cfg(feature = "alloc")]
impl fmt::Display for ExitStatus {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self.0 {
            Status::Exited(code) => write!(f, "exit code: {code}"),
            Status::Signaled(signal, false) => write!(f, "signal: {signal}"),
            Status::Signaled(signal, true) => write!(f, "signal: {signal} (core dumped)"),
        }
    }
}

/// NUL-terminated strings and the NULL-terminated array of pointers to
/// them: an `argv` or an `envp`.
#[cfg(feature = "alloc")]
#[allow(dead_code)]
pub(crate) struct CStrings {
    bytes: alloc::vec::Vec<u8>,
    /// Where each string starts in `bytes`.
    starts: alloc::vec::Vec<usize>,
    pointers: alloc::vec::Vec<*const core::ffi::c_char>,
}

#[cfg(feature = "alloc")]
#[allow(dead_code)]
impl CStrings {
    pub(crate) fn new() -> Self {
        Self {
            bytes: alloc::vec::Vec::new(),
            starts: alloc::vec::Vec::new(),
            pointers: alloc::vec::Vec::new(),
        }
    }

    /// Adds the string made of `parts` put end to end. Fails with
    /// `InvalidInput` if it contains a NUL.
    pub(crate) fn push(&mut self, parts: &[&[u8]]) -> Result<()> {
        let len: usize = parts.iter().map(|part| part.len()).sum();
        self.bytes
            .try_reserve(len + 1)
            .map_err(|_| ErrorKind::OutOfMemory)?;
        self.starts
            .try_reserve(1)
            .map_err(|_| ErrorKind::OutOfMemory)?;
        if parts.iter().any(|part| part.contains(&0)) {
            return Err(ErrorKind::InvalidInput.into());
        }
        self.starts.push(self.bytes.len());
        for part in parts {
            self.bytes.extend_from_slice(part);
        }
        self.bytes.push(0);
        Ok(())
    }

    /// The array of pointers to the strings pushed so far, followed by a
    /// null pointer. It is valid until `self` is changed or dropped.
    pub(crate) fn pointers(&mut self) -> Result<&[*const core::ffi::c_char]> {
        self.pointers.clear();
        self.pointers
            .try_reserve_exact(self.starts.len() + 1)
            .map_err(|_| ErrorKind::OutOfMemory)?;
        let base = self.bytes.as_ptr();
        for &start in &self.starts {
            // SAFETY: `start` is an offset into `bytes`.
            self.pointers.push(unsafe { base.add(start) }.cast());
        }
        self.pointers.push(core::ptr::null());
        Ok(&self.pointers)
    }
}

/// What Linux and macOS add: signals, process groups and sessions, limits,
/// the identity of a child, `fork`.
#[cfg(any(target_os = "linux", target_os = "fullrust", target_os = "macos"))]
pub mod unix {
    use super::Signal;
    #[cfg(feature = "alloc")]
    use super::{Child, Command, ExitStatus, Status};
    use crate::{ErrorKind, Result, sys};

    /// What a process may be limited in: the usual `RLIMIT_*` resources.
    #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
    #[non_exhaustive]
    pub enum Resource {
        /// The number of open descriptors, or rather one more than the
        /// highest descriptor the process can have (`RLIMIT_NOFILE`).
        OpenFiles,
        /// The size of the initial thread's stack, in bytes
        /// (`RLIMIT_STACK`).
        Stack,
        /// The size of a core dump, in bytes; 0 for none (`RLIMIT_CORE`).
        CoreSize,
        /// The size of a file the process writes, in bytes
        /// (`RLIMIT_FSIZE`).
        FileSize,
        /// The processor time of the process, in seconds (`RLIMIT_CPU`):
        /// `SIGXCPU` at the soft limit, `SIGKILL` at the hard one.
        CpuTime,
        /// The size of the address space, in bytes (`RLIMIT_AS`).
        AddressSpace,
        /// The size of the data segment, in bytes (`RLIMIT_DATA`).
        Data,
        /// The memory the process may lock, in bytes (`RLIMIT_MEMLOCK`).
        LockedMemory,
        /// The number of processes (on Linux, of threads) of the user
        /// (`RLIMIT_NPROC`).
        Processes,
    }

    /// The two limits of a resource; `None` is no limit (`RLIM_INFINITY`).
    ///
    /// A limit holds for one process, and each process a program starts
    /// has the same allowance again: nothing here bounds what a child and
    /// its descendants use together, and no resource counts the memory in
    /// use ([`AddressSpace`](Resource::AddressSpace) counts what is
    /// mapped, used or not). On Linux that is what a cgroup is for:
    /// `linux::CommandExt::cgroup` starts a child in one.
    #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
    pub struct Limit {
        /// The limit that is enforced. A process may set it to anything up
        /// to the hard limit.
        pub soft: Option<u64>,
        /// The ceiling of the soft limit. A process may lower it, and not
        /// raise it again without privilege.
        pub hard: Option<u64>,
    }

    /// The limits of the current process for `resource`: `prlimit64` on
    /// Linux, `getrlimit` on macOS.
    pub fn limit(resource: Resource) -> Result<Limit> {
        sys::process::limit(resource)
    }

    /// Sets the limits of the current process for `resource`: `prlimit64`
    /// on Linux, `setrlimit` on macOS. They apply to every thread, and the
    /// processes created afterwards start with them.
    ///
    /// # Errors
    ///
    /// [`ErrorKind::InvalidInput`] if the soft limit is above the hard
    /// one, or a value is too large for the system to tell from "no
    /// limit"; [`ErrorKind::PermissionDenied`] to raise the hard limit
    /// without the privilege. macOS also refuses, with
    /// [`ErrorKind::InvalidInput`], a soft limit of
    /// [`OpenFiles`](Resource::OpenFiles) that is `None` or above
    /// `kern.maxfilesperproc`.
    ///
    /// The system may adjust what it is given: macOS lowers the limits of
    /// [`Processes`](Resource::Processes) to `kern.maxprocperuid`. Read
    /// the limits back with [`limit`] to know what they are.
    pub fn set_limit(resource: Resource, limit: Limit) -> Result<()> {
        sys::process::set_limit(resource, limit)
    }

    /// Hang up: the controlling terminal was closed.
    pub const SIGHUP: i32 = 1;
    /// Interrupt, as Ctrl-C sends.
    pub const SIGINT: i32 = 2;
    /// Quit, as Ctrl-\ sends: terminates with a core dump.
    pub const SIGQUIT: i32 = 3;
    /// Kill: cannot be caught, blocked or ignored.
    pub const SIGKILL: i32 = 9;
    /// The polite request to terminate.
    pub const SIGTERM: i32 = 15;
    /// Stop: cannot be caught, blocked or ignored.
    pub const SIGSTOP: i32 = sys::process::SIGSTOP;
    /// Continue a stopped process.
    pub const SIGCONT: i32 = sys::process::SIGCONT;
    /// The first signal left to applications.
    pub const SIGUSR1: i32 = sys::process::SIGUSR1;
    /// The second signal left to applications.
    pub const SIGUSR2: i32 = sys::process::SIGUSR2;
    /// A write to a pipe or a socket that nobody reads. Rust programs
    /// start with it ignored, and get an error from the write instead.
    pub const SIGPIPE: i32 = 13;
    /// A timer set with `alarm` or `setitimer` ran out.
    pub const SIGALRM: i32 = 14;
    /// A child process exited, stopped or continued. Ignored by default.
    pub const SIGCHLD: i32 = sys::process::SIGCHLD;
    /// The size of the terminal changed. Ignored by default.
    pub const SIGWINCH: i32 = 28;

    /// [`Signal`]s by their numbers.
    pub trait SignalExt {
        /// The signal of this number, the system's: this module has
        /// constants for the usual ones, and the others differ between
        /// Linux and macOS. Any number is accepted here; a
        /// [`Signals`](super::Signals) refuses those it cannot receive.
        fn from_raw(signal: i32) -> Self;

        /// The system's number for the signal.
        fn as_raw(&self) -> i32;
    }

    impl SignalExt for Signal {
        fn from_raw(signal: i32) -> Self {
            Self(signal)
        }

        fn as_raw(&self) -> i32 {
            self.0
        }
    }

    /// Makes the process ignore `signal` from now on: `sigaction` with
    /// `SIG_IGN`. A program that is given the signal does not know.
    ///
    /// On macOS a signal that has a handler, oscall's or another, is not
    /// set to "ignore": oscall's handler takes its place and discards the
    /// signal (see [`Signals`](super::Signals) for why, and for what it
    /// changes: notably, [`SIGCHLD`] is only really ignored, and the
    /// children collected by the system, when it had no handler).
    ///
    /// This replaces whatever handler the signal had, for the whole
    /// process, and nothing remembers it. Ignoring [`SIGCHLD`] has a
    /// meaning of its own: the system then collects the children itself,
    /// and waiting for one fails. A program started by
    /// `Command` starts with nothing ignored whatever
    /// the caller does.
    ///
    /// # Errors
    ///
    /// [`ErrorKind::InvalidInput`] for a number that is no signal, for
    /// `SIGKILL` and `SIGSTOP`, and on Linux for signals 32 to 34, which
    /// are not the program's but its C library's;
    /// [`ErrorKind::ResourceBusy`] while a [`Signals`](super::Signals)
    /// listens to the signal.
    pub fn ignore_signal(signal: i32) -> Result<()> {
        sys::process::signal::set_disposition(signal, true)
    }

    /// Gives `signal` its default action back: `sigaction` with `SIG_DFL`.
    /// What that is depends on the signal: most terminate the process, a
    /// few are ignored or stop it.
    ///
    /// This replaces whatever handler the signal had, for the whole
    /// process, and nothing remembers it: code that relies on a handler of
    /// its own (a runtime, a profiler) stops being told.
    ///
    /// A signal that was sent before the call and is delivered after it
    /// gets the default action too. A signal sent to a process reaches one
    /// of its threads when that thread next runs, which can be a while
    /// after the sender is done, on macOS in particular.
    ///
    /// On macOS, for a signal that has a handler and whose default is to
    /// do nothing, oscall's handler takes the place of the other and
    /// discards the signal, as for [`ignore_signal`].
    ///
    /// # Errors
    ///
    /// As [`ignore_signal`].
    pub fn default_signal(signal: i32) -> Result<()> {
        sys::process::signal::set_disposition(signal, false)
    }

    /// Sends a signal to the process `pid`: `kill`. `signal` is the
    /// system's number for it: this module has constants for the usual
    /// ones, and the others differ between Linux and macOS.
    ///
    /// Signal 0 sends nothing and only checks that the process is there
    /// and may be sent signals by the caller (see
    /// [`exists`](super::exists)).
    ///
    /// An identifier only names a process for as long as the process
    /// exists: prefer [`ChildExt::send_signal`] for a child.
    ///
    /// # Errors
    ///
    /// [`ErrorKind::InvalidInput`] if `pid` is 0 or does not fit in an
    /// `i32` (see [`send_signal_to_group`] for groups), or if the system
    /// has no such signal; [`ErrorKind::NoSuchProcess`];
    /// [`ErrorKind::PermissionDenied`].
    pub fn send_signal(pid: u32, signal: i32) -> Result<()> {
        sys::process::send_signal(super::checked_pid(pid)? as i32, signal)
    }

    /// Sends a signal to every process of the process group `pgid`:
    /// `kill` with the group's number negated.
    ///
    /// # Errors
    ///
    /// As [`send_signal`]; [`ErrorKind::NoSuchProcess`] when the group has
    /// no process.
    pub fn send_signal_to_group(pgid: u32, signal: i32) -> Result<()> {
        // Group 1 would be -1: every process the caller may signal.
        if pgid == 1 {
            return Err(ErrorKind::InvalidInput.into());
        }
        sys::process::send_signal(-(super::checked_pid(pgid)? as i32), signal)
    }

    /// The process group of the process `pid`: `getpgid`. A group is named
    /// by the identifier of the process that created it.
    pub fn process_group(pid: u32) -> Result<u32> {
        sys::process::process_group(super::checked_pid(pid)?)
    }

    /// The session of the process `pid`: `getsid`. A session is named by
    /// the identifier of the process that created it.
    pub fn session(pid: u32) -> Result<u32> {
        sys::process::session(super::checked_pid(pid)?)
    }

    /// What [`CommandExt`] sets besides the group and the session.
    #[cfg(feature = "alloc")]
    #[derive(Clone, Copy)]
    pub(crate) struct Setup<'a> {
        pub(crate) limits: &'a [(Resource, Limit)],
        pub(crate) groups: Option<&'a [u32]>,
        pub(crate) gid: Option<u32>,
        pub(crate) uid: Option<u32>,
        pub(crate) umask: Option<u32>,
    }

    #[cfg(feature = "alloc")]
    impl Setup<'_> {
        pub(crate) const NONE: Self = Self {
            limits: &[],
            groups: None,
            gid: None,
            uid: None,
            umask: None,
        };

        /// Whether nothing is set.
        #[allow(dead_code)]
        pub(crate) fn is_none(&self) -> bool {
            self.limits.is_empty()
                && self.groups.is_none()
                && self.gid.is_none()
                && self.uid.is_none()
                && self.umask.is_none()
        }
    }

    /// More to set on a [`Command`] on Linux and macOS.
    ///
    /// Everything here is done in the child, before the program starts
    /// and in this order: the session or the process group, the standard
    /// handles, the file creation mask, the limits, the groups, the
    /// group, the user; then the working directory is entered, with the
    /// new identity. If any of
    /// it is refused, [`spawn`](Command::spawn) fails with the system's
    /// reason and no child is left behind.
    #[cfg(feature = "alloc")]
    pub trait CommandExt<'a> {
        /// Puts the child in the process group `pgid`, which must be one
        /// of the caller's session, or with 0 in a new group of its own,
        /// named by its process identifier. By default the child is in
        /// the caller's group.
        ///
        /// A group is what a terminal sends its signals to (Ctrl-C), and
        /// what [`send_signal_to_group`] addresses: a child in a group of
        /// its own, with the processes it starts, can be signalled as a
        /// whole, and does not receive the signals of the caller's
        /// terminal. Such a group is in the background of that terminal:
        /// reading from it stops the process (`SIGTTIN`).
        ///
        /// The group is set before the program starts: `setpgid` in the
        /// child on Linux, `POSIX_SPAWN_SETPGROUP` on macOS.
        fn process_group(self, pgid: u32) -> Self;

        /// Makes the child the leader of a new session, and so of a new
        /// process group, with no controlling terminal: `setsid` in the
        /// child on Linux, `POSIX_SPAWN_SETSID` on macOS.
        /// [`process_group`](Self::process_group) is then ignored.
        fn new_session(self) -> Self;

        /// Sets resource limits for the child: each one as [`set_limit`]
        /// would in the child itself (`prlimit64` on Linux, `setrlimit`
        /// on macOS), in the order given. The caller's own limits are not
        /// touched; by default the child starts with them.
        ///
        /// A limit the system refuses makes [`spawn`](Command::spawn) fail
        /// with the error [`set_limit`] documents. The limits are set
        /// before the user changes, with the caller's privileges, and
        /// before the program is started: with one that leaves no room to
        /// start it (an address space smaller than the program), `spawn`
        /// fails, or the program does as it starts.
        fn limits(self, limits: &'a [(Resource, Limit)]) -> Self;

        /// Sets the user of the child: `setuid`, which for a privileged
        /// caller sets the real, the effective and the saved identifiers,
        /// irrevocably. By default the child has the caller's.
        ///
        /// Changing to another user needs privilege (root, or
        /// `CAP_SETUID` on Linux): without it [`spawn`](Command::spawn)
        /// fails with [`ErrorKind::PermissionDenied`]. Naming the caller's
        /// own user is always allowed.
        ///
        /// The supplementary groups are **not** changed unless
        /// [`groups`](Self::groups) says so: a privileged caller that
        /// gives a child another user should give it that user's groups,
        /// or the child keeps the caller's.
        fn uid(self, uid: u32) -> Self;

        /// Sets the group of the child: `setgid`, before the user changes.
        /// Needs privilege like [`uid`](Self::uid).
        fn gid(self, gid: u32) -> Self;

        /// Sets the supplementary groups of the child: `setgroups`, before
        /// the group and the user change. An empty list leaves it none.
        ///
        /// This needs privilege even to set the groups the caller already
        /// has (root, or on Linux `CAP_SETGID` in a user namespace that
        /// allows `setgroups`): without it [`spawn`](Command::spawn) fails
        /// with [`ErrorKind::PermissionDenied`]. The system limits the
        /// length of the list (65536 groups on Linux, 15 on macOS) and
        /// refuses a longer one with [`ErrorKind::InvalidInput`].
        ///
        /// On macOS the list a process holds has 16 places, of which the
        /// first is the place of its own group: the child's list is its
        /// group ([`gid`](Self::gid), or the caller's) followed by these
        /// groups, the group itself left out if it is among them, and
        /// does not count there.
        fn groups(self, groups: &'a [u32]) -> Self;

        /// Sets the file creation mask of the child: the permission bits
        /// that the files and directories it creates do *not* get
        /// (`umask`). By default the child has the caller's.
        ///
        /// Only the nine permission bits count (`0o777`); a mask with any
        /// other bit makes [`spawn`](Command::spawn) fail with
        /// [`ErrorKind::InvalidInput`].
        fn umask(self, mask: u32) -> Self;
    }

    #[cfg(feature = "alloc")]
    impl<'a> CommandExt<'a> for Command<'a> {
        fn process_group(mut self, pgid: u32) -> Self {
            self.process_group = Some(pgid);
            self
        }

        fn new_session(mut self) -> Self {
            self.new_session = true;
            self
        }

        fn limits(mut self, limits: &'a [(Resource, Limit)]) -> Self {
            self.setup.limits = limits;
            self
        }

        fn uid(mut self, uid: u32) -> Self {
            self.setup.uid = Some(uid);
            self
        }

        fn gid(mut self, gid: u32) -> Self {
            self.setup.gid = Some(gid);
            self
        }

        fn groups(mut self, groups: &'a [u32]) -> Self {
            self.setup.groups = Some(groups);
            self
        }

        fn umask(mut self, mask: u32) -> Self {
            self.setup.umask = Some(mask);
            self
        }
    }

    /// Which of the two processes [`fork`] returned in.
    #[cfg(feature = "alloc")]
    #[derive(Debug)]
    pub enum Fork {
        /// The calling process, with the child it now has: to wait for,
        /// like any other [`Child`].
        Parent(Child),
        /// The new process.
        Child,
    }

    /// Duplicates the calling process: the new one is a copy of it at the
    /// time of the call, with a copy of its memory and of its open
    /// handles, and **only the calling thread**. Both return from the
    /// call, and [`Fork`] says which is which.
    ///
    /// To run another program, use a [`Command`]: it is faster (the
    /// memory is not copied), has none of the hazards below, and exists
    /// everywhere. This is for what a `Command` cannot express, at the
    /// price of the rules below. Windows has no such operation.
    ///
    /// `clone` with `SIGCHLD` and `CLONE_PIDFD` as a raw system call on
    /// Linux and fullrust; `fork` of `libSystem` on macOS.
    ///
    /// # What the child inherits
    ///
    /// Everything `fork` copies: the memory, every descriptor
    /// (close-on-exec or not: nothing is executed), the signal
    /// dispositions and the signal mask, the working directory, the
    /// limits. Pending signals, timers and memory locks are not, nor on
    /// Linux the parent death signal.
    ///
    /// Every descriptor means those of the whole process, whichever
    /// thread or library opened them: for as long as the child lives, a
    /// pipe or a socket the parent closes is still open in it, and its
    /// other end sees no end of stream and no broken pipe.
    ///
    /// The handlers of a [`Signals`](super::Signals) of the parent stay
    /// installed in the child, where they report to the *parent's*
    /// `Signals` (the two share what the handler writes to): a child
    /// that is to live on should be created with those signals blocked,
    /// or exit soon.
    ///
    /// # Safety
    ///
    /// The other threads of the process do not exist in the child, but
    /// what they were doing does: a lock one of them held (the
    /// allocator's, the one of `stdout`, any `Mutex`) stays locked for
    /// ever, and data they were changing stays half changed. So:
    ///
    /// - **In a process that has other threads**, the child may only make
    ///   system calls, through functions that take no lock, do not
    ///   allocate and do not touch thread-local state (on macOS: the
    ///   async-signal-safe functions of `libSystem`), until it replaces
    ///   itself with another program or calls [`exit`](super::exit). Of
    ///   oscall, that is what maps directly to one system call on handles
    ///   and identifiers: [`io`](crate::io), [`id`](super::id),
    ///   [`kill`](super::kill), [`send_signal`]. It must not allocate,
    ///   panic, print through `std`, return from `main` or call
    ///   `std::process::exit` (which runs `atexit` functions and flushes
    ///   buffers the parent still owns). A test harness, a runtime or a
    ///   library may have started threads the caller knows nothing
    ///   about.
    /// - **On Linux with a libc in the process** the call is made behind
    ///   its back, as every system call of oscall is: the functions
    ///   registered with `pthread_atfork` do not run (those of libc
    ///   itself, which reset its allocator and its `stdio` locks in the
    ///   child, included), and what libc caches about the calling thread
    ///   is the parent's in the child: its thread identifier (which
    ///   `raise`, `abort`, `pthread_kill` and recursive or
    ///   error-checking mutexes rely on; glibc before 2.25 also cached
    ///   the process identifier), the robust mutex list, the list of
    ///   threads that no longer exist. The rule above therefore applies
    ///   **even in a single-threaded process**: system calls only, then
    ///   `execve` or [`exit`](super::exit). A program that needs a child
    ///   that goes on running C code must call libc's own `fork`.
    /// - **On fullrust** there is no libc, and the runtime to protect is
    ///   fullrust's `std`, which is not told either. In a single-threaded
    ///   process no lock can be held by a thread that is gone, and Rust
    ///   code goes on working in the child, apart from what `std`
    ///   remembers of the thread and of the process (identifiers it was
    ///   asked for before); with other threads the first rule applies.
    /// - **On macOS** `fork` runs the `atfork` handlers and `libSystem`
    ///   keeps its own state consistent, but in a process with several
    ///   threads only async-signal-safe functions are safe in the child,
    ///   and the system frameworks (anything above `libSystem`) do not
    ///   work in a forked child at all until it executes a program.
    ///
    /// Buffers held in memory exist twice: what one process flushes, the
    /// other may flush again.
    ///
    /// # Errors
    ///
    /// The system's: [`ErrorKind::WouldBlock`] when the limit on
    /// processes is reached, [`ErrorKind::OutOfMemory`]. No child exists
    /// then.
    #[cfg(feature = "alloc")]
    pub unsafe fn fork() -> Result<Fork> {
        // SAFETY: the caller's contract.
        Ok(match unsafe { sys::process::fork() }? {
            Some(inner) => Fork::Parent(Child {
                inner,
                status: None,
                usage: None,
            }),
            None => Fork::Child,
        })
    }

    /// More about an [`ExitStatus`] on Linux and macOS.
    #[cfg(feature = "alloc")]
    pub trait ExitStatusExt {
        /// The number of the signal that terminated the process, `None` if
        /// it exited by itself.
        fn signal(&self) -> Option<i32>;

        /// Whether the system says the process dumped core when a signal
        /// terminated it.
        fn core_dumped(&self) -> bool;
    }

    #[cfg(feature = "alloc")]
    impl ExitStatusExt for ExitStatus {
        fn signal(&self) -> Option<i32> {
            match self.0 {
                Status::Signaled(signal, _) => Some(signal),
                Status::Exited(_) => None,
            }
        }

        fn core_dumped(&self) -> bool {
            matches!(self.0, Status::Signaled(_, true))
        }
    }

    /// More to do with a [`Child`] on Linux and macOS.
    #[cfg(feature = "alloc")]
    pub trait ChildExt {
        /// Sends a signal to the child. `signal` is the system's number
        /// for it: this module has constants for the usual ones, and the
        /// others differ between Linux and macOS.
        ///
        /// Signal 0 sends nothing and only checks that the process is
        /// there. Fails with [`ErrorKind::NoSuchProcess`] once the child
        /// has been waited for, or once a wait has found that other code
        /// collected it: no signal is ever sent to a process identifier
        /// that the system may have given to another process.
        ///
        /// `pidfd_send_signal` on Linux, `kill` on macOS.
        fn send_signal(&self, signal: i32) -> Result<()>;
    }

    #[cfg(feature = "alloc")]
    impl ChildExt for Child {
        fn send_signal(&self, signal: i32) -> Result<()> {
            if self.status.is_some() {
                return Err(ErrorKind::NoSuchProcess.into());
            }
            self.inner.send_signal(signal)
        }
    }
}

/// What Windows adds: console control events, console process groups, the
/// command line as one string, job objects.
#[cfg(windows)]
pub mod windows {
    use core::time::Duration;

    use super::Signal;
    #[cfg(feature = "alloc")]
    use super::{Child, Command};
    #[cfg(feature = "alloc")]
    use crate::AsPath;
    use crate::{AsHandle, BorrowedHandle, OwnedHandle, Result, sys};

    /// A job object: a group of processes that the system limits, accounts
    /// for and terminates as one. The processes a member creates are
    /// members too, and none can leave.
    ///
    /// A process is put in a job when it is created (`CommandExt::job`),
    /// or afterwards ([`assign`](Self::assign)).
    ///
    /// Dropping the `Job` closes the handle. The job itself lasts as long
    /// as it has processes, with its limits, but can no longer be reached;
    /// with [`JobLimits::kill_on_close`], closing the last handle
    /// terminates every process in it instead (their exit code is then 0,
    /// like that of a process that ended well). Since the system closes the
    /// handles of a process that ends, however it ends, that is how
    /// children are made not to outlive their parent on Windows: the
    /// parent creates such a job, keeps it, and creates its children in
    /// it.
    ///
    #[cfg_attr(feature = "alloc", doc = "```no_run")]
    #[cfg_attr(not(feature = "alloc"), doc = "```ignore")]
    /// use oscall::process::Command;
    /// use oscall::process::windows::{CommandExt, Job, JobLimits};
    ///
    /// let job = Job::new()?;
    /// let mut limits = JobLimits::new();
    /// limits.kill_on_close = true;
    /// limits.job_memory = Some(1 << 30);
    /// job.set_limits(&limits)?;
    /// let mut child = Command::new("C:\\Windows\\System32\\cmd.exe")
    ///     .job(&job)
    ///     .spawn()?;
    /// child.wait()?;
    /// # Ok::<(), oscall::Error>(())
    /// ```
    ///
    /// Jobs nest: a process that is itself in a job (as programs run by a
    /// service, a terminal or a continuous integration runner often are)
    /// can create jobs and put its children in them, and the limits of
    /// every job a process is in apply together.
    #[derive(Debug)]
    pub struct Job(OwnedHandle);

    /// The limits of a [`Job`]: see [`Job::set_limits`]. `None` is no
    /// limit.
    #[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
    #[non_exhaustive]
    pub struct JobLimits {
        /// The memory each process of the job may commit, in bytes
        /// (`JOB_OBJECT_LIMIT_PROCESS_MEMORY`). An allocation beyond it
        /// fails.
        pub process_memory: Option<u64>,
        /// The memory all the processes of the job may commit together,
        /// in bytes (`JOB_OBJECT_LIMIT_JOB_MEMORY`).
        pub job_memory: Option<u64>,
        /// How many processes the job may have at one time
        /// (`JOB_OBJECT_LIMIT_ACTIVE_PROCESS`). Creating or assigning one
        /// more fails.
        pub active_processes: Option<u32>,
        /// The processor time each process may spend in user mode
        /// (`JOB_OBJECT_LIMIT_PROCESS_TIME`), counted in units of 100
        /// nanoseconds. A process that exceeds it is terminated, with
        /// the exit code `0xC0000044` (`STATUS_QUOTA_EXCEEDED`).
        pub process_time: Option<Duration>,
        /// The processor time all the processes of the job may spend in
        /// user mode together (`JOB_OBJECT_LIMIT_JOB_TIME`). When it is
        /// exceeded every process of the job is terminated. Setting it
        /// starts the count again from zero.
        pub job_time: Option<Duration>,
        /// Whether closing the last handle to the job terminates its
        /// processes (`JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE`), with the exit
        /// code 0.
        pub kill_on_close: bool,
    }

    impl JobLimits {
        /// No limit at all.
        pub const fn new() -> Self {
            Self {
                process_memory: None,
                job_memory: None,
                active_processes: None,
                process_time: None,
                job_time: None,
                kill_on_close: false,
            }
        }
    }

    /// What the processes of a [`Job`] have done: see [`Job::accounting`].
    #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
    #[non_exhaustive]
    pub struct JobAccounting {
        /// The processor time spent in user mode by every process the job
        /// ever had.
        pub user_time: Duration,
        /// The processor time spent in the kernel by every process the
        /// job ever had.
        pub system_time: Duration,
        /// How many processes the job has had in its life, those of now
        /// included.
        pub total_processes: u32,
        /// How many processes the job has now.
        pub active_processes: u32,
        /// How many processes were terminated for exceeding a limit.
        pub terminated_processes: u32,
    }

    impl Job {
        /// Creates a job with no name, no process and no limit:
        /// `CreateJobObjectW`. The handle is not inheritable.
        pub fn new() -> Result<Self> {
            sys::process::job::create().map(Self)
        }

        /// Puts a process in the job: `AssignProcessToJobObject`.
        /// `process` is a handle to it, such as a [`Child`] lends.
        ///
        /// A process that runs before it is assigned may by then have
        /// created others, which are not in the job: to leave no such
        /// window, create the process in the job (`CommandExt::job`).
        ///
        /// # Errors
        ///
        /// [`ErrorKind::PermissionDenied`](crate::ErrorKind::PermissionDenied)
        /// when the process is in a job already that this one cannot
        /// nest in, when it has exited, or when the handle lacks the
        /// rights; the system's error when the limit on processes is
        /// reached.
        pub fn assign<H: AsHandle>(&self, process: H) -> Result<()> {
            sys::process::job::assign(self.0.as_handle(), process.as_handle())
        }

        /// Sets the limits of the job, replacing all those it had:
        /// `SetInformationJobObject` with
        /// `JobObjectExtendedLimitInformation`. They apply to the
        /// processes already in the job as to those that join.
        ///
        /// A memory limit that does not fit in the system's `SIZE_T` (on
        /// 32-bit Windows) is the largest that does. A job that is nested
        /// in another is still held by the limits of the outer one.
        pub fn set_limits(&self, limits: &JobLimits) -> Result<()> {
            sys::process::job::set_limits(self.0.as_handle(), limits)
        }

        /// The limits of the job: `QueryInformationJobObject`.
        pub fn limits(&self) -> Result<JobLimits> {
            sys::process::job::limits(self.0.as_handle())
        }

        /// Terminates every process of the job at once, each with
        /// `exit_code` as its exit code: `TerminateJobObject`. The job
        /// stays usable.
        pub fn terminate(&self, exit_code: u32) -> Result<()> {
            sys::process::job::terminate(self.0.as_handle(), exit_code)
        }

        /// What the processes of the job have consumed, and how many
        /// there are: `QueryInformationJobObject` with
        /// `JobObjectBasicAccountingInformation`.
        pub fn accounting(&self) -> Result<JobAccounting> {
            sys::process::job::accounting(self.0.as_handle())
        }
    }

    impl AsHandle for Job {
        #[inline]
        fn as_handle(&self) -> BorrowedHandle<'_> {
            self.0.as_handle()
        }
    }

    impl From<Job> for OwnedHandle {
        #[inline]
        fn from(job: Job) -> Self {
            job.0
        }
    }

    /// Ctrl-Break was typed in the console, or sent with
    /// [`send_ctrl_event`]: `CTRL_BREAK_EVENT`. Like
    /// [`Signal::INTERRUPT`], it terminates a process that does not
    /// listen; unlike it, it cannot be disabled.
    pub const CTRL_BREAK: Signal = Signal(sys::process::signal::BREAK);

    /// A user is logging off: `CTRL_LOGOFF_EVENT`. A service receives it
    /// when any user does, and goes on; a program of that user's session
    /// is terminated a few seconds later (see [`Signal`]).
    pub const CTRL_LOGOFF: Signal = Signal(sys::process::signal::LOGOFF);

    /// Sends [`Signal::INTERRUPT`] (Ctrl-C) or [`CTRL_BREAK`] to the
    /// processes of the console process group `group` that share the
    /// console of the caller: `GenerateConsoleCtrlEvent`. This is how a
    /// child is asked to stop on Windows.
    ///
    /// A group is named by the identifier of the process that was created
    /// to start it (`CommandExt::new_process_group`), and holds its
    /// descendants. Group 0 is every process attached to the console,
    /// **the caller included**, and usually its parents too.
    ///
    /// The system only sends Ctrl-C to group 0; and a process created at
    /// the head of a new group starts with Ctrl-C disabled. So what works
    /// for a child is [`CTRL_BREAK`], sent to the group it was created to
    /// start.
    ///
    /// The call succeeds whether or not a process received anything: a
    /// process that has no console, or another console, is out of reach.
    ///
    /// # Errors
    ///
    /// [`ErrorKind::InvalidInput`](crate::ErrorKind::InvalidInput) for any
    /// other event: the system does not let a program generate them.
    pub fn send_ctrl_event(event: Signal, group: u32) -> Result<()> {
        sys::process::signal::send_ctrl_event(event.0, group)
    }

    /// Makes the process ignore Ctrl-C, or stop ignoring it:
    /// `SetConsoleCtrlHandler(NULL, ignored)`. While it is ignored no
    /// handler is told, and a [`Signals`](super::Signals) receives no
    /// [`Signal::INTERRUPT`].
    ///
    /// The setting is inherited by the processes the caller creates. A
    /// process created with `CommandExt::new_process_group` starts with
    /// Ctrl-C ignored.
    pub fn set_ctrl_c_ignored(ignored: bool) -> Result<()> {
        sys::process::signal::set_ctrl_c_ignored(ignored)
    }

    /// A privilege: a right over the system as a whole (to lock memory,
    /// to shut the machine down, to read any file for a backup), which an
    /// account is given by the administrator and a process holds in its
    /// access token. See [`privilege_state`] and [`set_privilege`].
    ///
    /// ```no_run
    /// use oscall::process::windows::{self, Privilege, PrivilegeState};
    ///
    /// let lock_memory = Privilege::lookup(Privilege::LOCK_MEMORY)?;
    /// if windows::privilege_state(lock_memory)? != PrivilegeState::Absent {
    ///     windows::set_privilege(lock_memory, true)?;
    ///     // Large pages can be asked for.
    /// }
    /// # Ok::<(), oscall::Error>(())
    /// ```
    ///
    /// The value is the number the running system has for the privilege
    /// (a `LUID`): it is looked up by name, and means nothing to another
    /// machine.
    #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
    pub struct Privilege(u64);

    impl Privilege {
        /// The name of the privilege to keep pages in physical memory,
        /// which mapping large pages
        /// (`mem::windows::MapOptionsExt::large_pages`) takes. No account
        /// has it unless the administrator gave it ("Lock pages in
        /// memory"); the system's own account does.
        pub const LOCK_MEMORY: &'static str = "SeLockMemoryPrivilege";
        /// The name of the privilege to pass through directories the
        /// account may not list, which every account has, enabled.
        pub const CHANGE_NOTIFY: &'static str = "SeChangeNotifyPrivilege";
        /// The name of the privilege to open any process, whoever owns
        /// it: an administrator's.
        pub const DEBUG: &'static str = "SeDebugPrivilege";
        /// The name of the privilege to read any file whatever its access
        /// list says, for a backup.
        pub const BACKUP: &'static str = "SeBackupPrivilege";
        /// The name of the privilege to write any file whatever its
        /// access list says, to restore a backup.
        pub const RESTORE: &'static str = "SeRestorePrivilege";
        /// The name of the privilege to shut the system down.
        pub const SHUTDOWN: &'static str = "SeShutdownPrivilege";
        /// The name of the privilege to create symbolic links.
        pub const CREATE_SYMBOLIC_LINK: &'static str = "SeCreateSymbolicLinkPrivilege";
        /// The name of the privilege to give a process a larger working
        /// set, which most accounts have.
        pub const INCREASE_WORKING_SET: &'static str = "SeIncreaseWorkingSetPrivilege";

        /// The privilege called `name`: one of the constants of this
        /// type, or any other name the system knows.
        ///
        /// Fails with the code of `ERROR_NO_SUCH_PRIVILEGE` (1313) for a
        /// name it does not know. `LookupPrivilegeValueW`.
        pub fn lookup<P: crate::AsPath + ?Sized>(name: &P) -> Result<Self> {
            crate::path::with_wide(name.as_path_bytes(), |name| {
                sys::process::privilege::lookup(name).map(Self)
            })
        }
    }

    /// What the access token of the process has of a privilege: see
    /// [`privilege_state`].
    #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
    #[non_exhaustive]
    pub enum PrivilegeState {
        /// The token does not hold the privilege: nothing the process
        /// does gives it. The account has to be given the privilege, and
        /// to log on again.
        Absent,
        /// The token holds the privilege, which is not enabled: the
        /// system refuses what takes it until [`set_privilege`] enables
        /// it. That is how most privileges of an account start.
        Disabled,
        /// The token holds the privilege, and it is enabled.
        Enabled,
    }

    /// Tells what the access token of the process has of `privilege`.
    ///
    /// The token is the process's, made when its user logged on and
    /// inherited from the process that created this one: what the
    /// administrator has given the account since is not in it. A thread
    /// that acts for somebody else (impersonation, which nothing in
    /// oscall does) has a token of its own, which this does not look at.
    ///
    /// `OpenProcessToken`, `GetTokenInformation` (`TokenPrivileges`).
    pub fn privilege_state(privilege: Privilege) -> Result<PrivilegeState> {
        sys::process::privilege::state(privilege.0)
    }

    /// Enables or disables `privilege` in the access token of the
    /// process, **for every thread of it** and for the processes it
    /// creates from then on.
    ///
    /// Fails with
    /// [`ErrorKind::PermissionDenied`](crate::ErrorKind::PermissionDenied)
    /// (`ERROR_NOT_ALL_ASSIGNED`, 1300) for a privilege the token does not
    /// hold ([`PrivilegeState::Absent`]): enabling is not acquiring.
    /// Enabling what is enabled, or disabling what is not, does nothing.
    ///
    /// A privilege is a switch of the whole process and stays as it was
    /// set: code that enables one for a call and disables it afterwards
    /// disables it for whoever else had enabled it.
    ///
    /// `OpenProcessToken`, `AdjustTokenPrivileges`.
    pub fn set_privilege(privilege: Privilege, enabled: bool) -> Result<()> {
        sys::process::privilege::set(privilege.0, enabled)
    }

    /// More to set on a [`Command`] on Windows.
    #[cfg(feature = "alloc")]
    pub trait CommandExt<'a> {
        /// Sets the whole command line of the child, passed to
        /// `CreateProcessW` as it is (converted from WTF-8), in place of
        /// the one oscall builds from [`arg0`](Command::arg0) and
        /// [`args`](Command::args), which are then ignored.
        ///
        /// By convention the command line starts with the name of the
        /// program. This is for the programs that do not parse their
        /// command line the usual way: `cmd.exe`, and through it batch
        /// files.
        fn raw_command_line<S: AsPath + ?Sized>(self, line: &'a S) -> Self;

        /// Makes the child the root of a new console process group, named
        /// by its process identifier: `CREATE_NEW_PROCESS_GROUP`. The
        /// processes it starts are in the group too, unless they ask for
        /// their own. See [`send_ctrl_event`].
        ///
        /// A process created so starts with Ctrl-C disabled, for itself
        /// and its descendants (see [`set_ctrl_c_ignored`]); Ctrl-Break is
        /// not affected.
        fn new_process_group(self) -> Self;

        /// Gives the child a console of its own instead of the caller's:
        /// `CREATE_NEW_CONSOLE`. In an interactive session that is a new
        /// window. The control events of the caller's console no longer
        /// reach the child, nor those the caller generates.
        ///
        /// The standard handles are still what the `Command` says: the
        /// caller's, by default, console or not.
        fn new_console(self) -> Self;

        /// Creates the child in `job`
        /// (`PROC_THREAD_ATTRIBUTE_JOB_LIST`): it is a member before it
        /// runs anything, so everything it creates is in the job too.
        ///
        /// [`spawn`](Command::spawn) fails, with the system's
        /// `ERROR_NOT_ENOUGH_QUOTA`, when the job cannot take one more
        /// process (its limit on active processes).
        fn job(self, job: &'a Job) -> Self;
    }

    #[cfg(feature = "alloc")]
    impl<'a> CommandExt<'a> for Command<'a> {
        fn raw_command_line<S: AsPath + ?Sized>(mut self, line: &'a S) -> Self {
            self.raw_command_line = Some(line.as_path_bytes());
            self
        }

        fn new_process_group(mut self) -> Self {
            self.new_process_group = true;
            self
        }

        fn new_console(mut self) -> Self {
            self.new_console = true;
            self
        }

        fn job(mut self, job: &'a Job) -> Self {
            self.job = Some(job.0.as_handle());
            self
        }
    }

    /// More to do with a [`Child`] on Windows.
    #[cfg(feature = "alloc")]
    pub trait ChildExt {
        /// Sends [`CTRL_BREAK`] to the console process group the child
        /// was created to start, which asks it and its descendants to
        /// stop: [`send_ctrl_event`] with the child's identifier. A
        /// program that does not handle the event is terminated by it.
        ///
        /// The child must have been created with
        /// `CommandExt::new_process_group`, and share the console of the
        /// caller; otherwise nothing is received, and the call may succeed
        /// all the same.
        ///
        /// Does nothing, and fails with
        /// [`ErrorKind::InvalidInput`](crate::ErrorKind::InvalidInput),
        /// once the child has been waited for.
        fn send_ctrl_break(&self) -> Result<()>;
    }

    #[cfg(feature = "alloc")]
    impl ChildExt for Child {
        fn send_ctrl_break(&self) -> Result<()> {
            if self.status.is_some() {
                return Err(crate::ErrorKind::InvalidInput.into());
            }
            send_ctrl_event(CTRL_BREAK, self.inner.id())
        }
    }
}