oscall 0.0.1

Low-level cross-platform interface to operating system services: files, memory mapping, networking and more, with no libc on Linux
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
//! Processes: the current one, and child processes.
//!
//! [`id`], [`parent_id`], [`exit`] and [`abort`] concern the current
//! process. 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.
//!
//! # 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.
//!
//! [`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. Changing credentials is future work.
//!
//! 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`] works on WASI; without WASI, [`exit`] and [`abort`] trap.

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

mod signal;

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)]
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,
}

#[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,
        }
    }

    /// 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.
    /// - **macOS**: `posix_spawn`, with `POSIX_SPAWN_CLOEXEC_DEFAULT`.
    /// - **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.
#[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`).
    #[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.
    ///
    /// 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)?)
    }

    /// More to set on a [`Command`] on Linux and macOS.
    #[cfg(feature = "alloc")]
    pub trait CommandExt {
        /// 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;
    }

    #[cfg(feature = "alloc")]
    impl CommandExt for Command<'_> {
        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
        }
    }

    /// 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.
#[cfg(windows)]
pub mod windows {
    use super::Signal;
    #[cfg(feature = "alloc")]
    use super::{Child, Command};
    #[cfg(feature = "alloc")]
    use crate::AsPath;
    use crate::{Result, sys};

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

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

    #[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
        }
    }

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