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
//! `process` on macOS.

use core::ffi::{c_char, c_int};

pub(crate) mod signal;

use core::time::Duration;

use crate::path::with_cstr;
use crate::process::ResourceUsage;
use crate::process::unix::{Limit, Resource};
use crate::sys::{cvt, errno};
use crate::{Error, ErrorKind, Result};

const SIGKILL: c_int = 9;
pub(crate) const SIGSTOP: i32 = 17;
pub(crate) const SIGCONT: i32 = 19;
pub(crate) const SIGCHLD: i32 = 20;
pub(crate) const SIGUSR1: i32 = 30;
pub(crate) const SIGUSR2: i32 = 31;

unsafe extern "C" {
    fn getpid() -> c_int;
    fn getppid() -> c_int;
    fn getpgid(pid: c_int) -> c_int;
    fn getsid(pid: c_int) -> c_int;
    #[link_name = "kill"]
    fn c_kill(pid: c_int, signal: c_int) -> c_int;
    fn faccessat(dir: c_int, path: *const c_char, mode: c_int, flags: c_int) -> c_int;
    fn getrusage(who: c_int, usage: *mut RUsage) -> c_int;
    fn getrlimit(resource: c_int, limit: *mut [u64; 2]) -> c_int;
    fn setrlimit(resource: c_int, limit: *const [u64; 2]) -> c_int;
    fn _exit(code: c_int) -> !;
    #[link_name = "abort"]
    fn c_abort() -> !;
}

pub(crate) fn id() -> u32 {
    // SAFETY: no argument, and the call cannot fail.
    unsafe { getpid() as u32 }
}

pub(crate) fn parent_id() -> u32 {
    // SAFETY: no argument, and the call cannot fail.
    unsafe { getppid() as u32 }
}

pub(crate) fn exit(code: i32) -> ! {
    // SAFETY: terminates the process without running anything of it.
    unsafe { _exit(code) }
}

pub(crate) fn abort() -> ! {
    // SAFETY: raises SIGABRT until the process dies of it.
    unsafe { c_abort() }
}

pub(crate) const HAS_PROCESSES: bool = true;
/// What separates the directories of a search path.
pub(crate) const SEARCH_SEPARATOR: u8 = b':';
/// What goes between a directory and a name.
pub(crate) const DIR_SEPARATOR: &[u8] = b"/";
/// What a program's name ends with when it has no extension.
pub(crate) const PROGRAM_SUFFIX: &[u8] = b"";

/// An entry of a search path, as the directory it names.
pub(crate) fn search_dir(entry: &[u8]) -> &[u8] {
    entry
}

/// Whether `name` is a name to search for, and not a path.
pub(crate) fn is_bare_name(name: &[u8]) -> bool {
    !name.contains(&b'/')
}

/// Whether `path` is a regular file the caller may execute.
pub(crate) fn is_program(path: &[u8]) -> bool {
    const AT_FDCWD: c_int = -2;
    const X_OK: c_int = 1;
    const AT_EACCESS: c_int = 0x0010;

    if !crate::sys::fs::metadata(path, true).is_ok_and(|metadata| metadata.is_file()) {
        return false;
    }
    with_cstr(path, |path| {
        // SAFETY: `path` is a NUL-terminated string.
        cvt(unsafe { faccessat(AT_FDCWD, path.as_ptr(), X_OK, AT_EACCESS) })
    })
    .is_ok()
}

/// `kill`: `pid` may be negative, for a process group.
pub(crate) fn send_signal(pid: i32, signal: i32) -> Result<()> {
    // SAFETY: no memory is involved.
    cvt(unsafe { c_kill(pid, signal) }).map(drop)
}

pub(crate) fn exists(pid: u32) -> Result<bool> {
    match send_signal(pid as i32, 0) {
        Ok(()) => Ok(true),
        Err(error) => exists_from(error),
    }
}

/// What a failure to send signal 0 says.
fn exists_from(error: Error) -> Result<bool> {
    match error.raw_os_error() {
        errno::ESRCH => Ok(false),
        // It is there, and someone else's.
        errno::EPERM => Ok(true),
        _ => Err(error),
    }
}

pub(crate) fn kill(pid: u32) -> Result<()> {
    send_signal(pid as i32, SIGKILL)
}

/// `struct timeval`: the microseconds are an `int`, padded.
#[repr(C)]
#[derive(Clone, Copy, Default)]
struct TimeVal {
    seconds: i64,
    micros: i32,
}

/// `struct rusage`: two `timeval`s and fourteen `long`s, the first of
/// which is the peak resident set size in bytes.
#[repr(C)]
#[derive(Clone, Copy, Default)]
pub(crate) struct RUsage {
    user: TimeVal,
    system: TimeVal,
    max_rss: i64,
    others: [i64; 13],
}

const _: () = assert!(size_of::<RUsage>() == 144);

pub(crate) fn usage_from(usage: &RUsage) -> ResourceUsage {
    let time = |time: TimeVal| {
        Duration::new(time.seconds.max(0) as u64, 0)
            + Duration::from_micros(time.micros.clamp(0, 999_999) as u64)
    };
    ResourceUsage {
        user_time: time(usage.user),
        system_time: time(usage.system),
        max_resident_memory: usage.max_rss.max(0) as u64,
    }
}

pub(crate) fn resource_usage() -> Result<ResourceUsage> {
    const RUSAGE_SELF: c_int = 0;
    let mut usage = RUsage::default();
    // SAFETY: the system writes one `struct rusage`.
    cvt(unsafe { getrusage(RUSAGE_SELF, &raw mut usage) })?;
    Ok(usage_from(&usage))
}

/// `RLIM_INFINITY`.
const UNLIMITED: u64 = 0x7fff_ffff_ffff_ffff;

/// The `RLIMIT_*` number, from `<sys/resource.h>`.
fn resource_number(resource: Resource) -> c_int {
    match resource {
        Resource::CpuTime => 0,
        Resource::FileSize => 1,
        Resource::Data => 2,
        Resource::Stack => 3,
        Resource::CoreSize => 4,
        Resource::AddressSpace => 5,
        Resource::LockedMemory => 6,
        Resource::Processes => 7,
        Resource::OpenFiles => 8,
    }
}

pub(crate) fn limit(resource: Resource) -> Result<Limit> {
    // `struct rlimit`: the soft limit, then the hard one, as `rlim_t`.
    let mut old = [0u64; 2];
    // SAFETY: the system writes one `struct rlimit`.
    cvt(unsafe { getrlimit(resource_number(resource), &raw mut old) })?;
    let value = |raw: u64| (raw < UNLIMITED).then_some(raw);
    Ok(Limit {
        soft: value(old[0]),
        hard: value(old[1]),
    })
}

/// `limit` as a `struct rlimit`: the soft limit, then the hard one.
fn raw_limit(limit: Limit) -> Result<[u64; 2]> {
    let raw = |value: Option<u64>| match value {
        None => Ok(UNLIMITED),
        Some(value) if value >= UNLIMITED => Err(Error::from(ErrorKind::InvalidInput)),
        Some(value) => Ok(value),
    };
    Ok([raw(limit.soft)?, raw(limit.hard)?])
}

pub(crate) fn set_limit(resource: Resource, limit: Limit) -> Result<()> {
    let new = raw_limit(limit)?;
    // SAFETY: the system reads one `struct rlimit`.
    cvt(unsafe { setrlimit(resource_number(resource), &raw const new) }).map(drop)
}

pub(crate) fn process_group(pid: u32) -> Result<u32> {
    // SAFETY: no memory is involved.
    cvt(unsafe { getpgid(pid as c_int) }).map(|pgid| pgid as u32)
}

pub(crate) fn session(pid: u32) -> Result<u32> {
    // SAFETY: no memory is involved.
    cvt(unsafe { getsid(pid as c_int) }).map(|sid| sid as u32)
}

#[cfg(feature = "alloc")]
pub(crate) use spawn::{Child, fork, spawn};

#[cfg(feature = "alloc")]
mod spawn {
    use alloc::vec::Vec;
    use core::ffi::{c_char, c_int, c_short, c_void};
    use core::ptr;
    use core::sync::atomic::{AtomicBool, Ordering};

    use super::{
        _exit, RUsage, SIGKILL, SIGSTOP, c_kill, raw_limit, resource_number, setrlimit, usage_from,
    };
    use crate::process::{CStrings, Command, ExitStatus, ResourceUsage, Stdio};
    use crate::sys::io::fcntl;
    use crate::sys::{cvt, errno};
    use crate::{Error, ErrorKind, OwnedHandle, Result};

    /// `posix_spawnattr_t` and `posix_spawn_file_actions_t` are both a
    /// pointer to something `libSystem` allocates.
    type Opaque = *mut c_void;
    /// `sigset_t`: one bit per signal, 1 to 32.
    type SigSet = u32;

    unsafe extern "C" {
        fn posix_spawn(
            pid: *mut c_int,
            path: *const c_char,
            file_actions: *const Opaque,
            attributes: *const Opaque,
            argv: *const *const c_char,
            envp: *const *const c_char,
        ) -> c_int;
        fn posix_spawnattr_init(attributes: *mut Opaque) -> c_int;
        fn posix_spawnattr_destroy(attributes: *mut Opaque) -> c_int;
        fn posix_spawnattr_setflags(attributes: *mut Opaque, flags: c_short) -> c_int;
        fn posix_spawnattr_setsigdefault(attributes: *mut Opaque, set: *const SigSet) -> c_int;
        fn posix_spawnattr_setsigmask(attributes: *mut Opaque, set: *const SigSet) -> c_int;
        fn posix_spawnattr_setpgroup(attributes: *mut Opaque, group: c_int) -> c_int;
        fn posix_spawn_file_actions_init(actions: *mut Opaque) -> c_int;
        fn posix_spawn_file_actions_destroy(actions: *mut Opaque) -> c_int;
        fn posix_spawn_file_actions_addopen(
            actions: *mut Opaque,
            fd: c_int,
            path: *const c_char,
            flags: c_int,
            mode: u16,
        ) -> c_int;
        fn posix_spawn_file_actions_adddup2(actions: *mut Opaque, fd: c_int, new: c_int) -> c_int;
        fn posix_spawn_file_actions_addinherit_np(actions: *mut Opaque, fd: c_int) -> c_int;
        // macOS 10.15.
        fn posix_spawn_file_actions_addchdir_np(actions: *mut Opaque, path: *const c_char)
        -> c_int;
        /// The address of `environ`, which a dynamic library cannot name.
        fn _NSGetEnviron() -> *mut *const *const c_char;
        fn wait4(pid: c_int, status: *mut c_int, options: c_int, usage: *mut RUsage) -> c_int;
        #[link_name = "fork"]
        fn c_fork() -> c_int;
        /// `mode_t` is 16 bits.
        fn umask(mask: u16) -> u16;
        fn setgroups(count: c_int, groups: *const u32) -> c_int;
        fn getegid() -> u32;
        fn setgid(gid: u32) -> c_int;
        fn setuid(uid: u32) -> c_int;
        /// Returns the error number.
        fn pthread_sigmask(how: c_int, set: *const SigSet, old: *mut SigSet) -> c_int;
        #[link_name = "read"]
        fn c_read(fd: c_int, buf: *mut c_void, len: usize) -> isize;
        #[link_name = "write"]
        fn c_write(fd: c_int, buf: *const c_void, len: usize) -> isize;
        fn open(path: *const c_char, flags: c_int, ...) -> c_int;
        fn dup2(fd: c_int, new: c_int) -> c_int;
        fn close(fd: c_int) -> c_int;
        fn chdir(path: *const c_char) -> c_int;
        fn setsid() -> c_int;
        fn setpgid(pid: c_int, group: c_int) -> c_int;
    }

    const SIG_SETMASK: c_int = 3;

    /// The process the call is made from becomes the program: nothing is
    /// spawned.
    const POSIX_SPAWN_SETEXEC: c_short = 0x0040;
    const POSIX_SPAWN_SETPGROUP: c_short = 0x0002;
    /// macOS 10.15.
    const POSIX_SPAWN_SETSID: c_short = 0x0400;

    const POSIX_SPAWN_SETSIGDEF: c_short = 0x0004;
    const POSIX_SPAWN_SETSIGMASK: c_short = 0x0008;
    /// Every descriptor is closed in the child, except those the file
    /// actions create or mark as inherited.
    const POSIX_SPAWN_CLOEXEC_DEFAULT: c_short = 0x4000;

    const O_RDWR: c_int = 2;
    const F_GETFD: c_int = 1;
    const F_SETFD: c_int = 2;
    const F_DUPFD_CLOEXEC: c_int = 67;
    const WNOHANG: c_int = 1;

    /// The functions of the `posix_spawn` family return the error number
    /// instead of setting `errno`.
    fn check(ret: c_int) -> Result<()> {
        if ret == 0 {
            Ok(())
        } else {
            Err(Error::from_raw_os_error(ret))
        }
    }

    struct Attributes(Opaque);

    impl Drop for Attributes {
        fn drop(&mut self) {
            // SAFETY: initialised, and not used afterwards.
            unsafe { posix_spawnattr_destroy(&raw mut self.0) };
        }
    }

    struct FileActions(Opaque);

    impl Drop for FileActions {
        fn drop(&mut self) {
            // SAFETY: initialised, and not used afterwards.
            unsafe { posix_spawn_file_actions_destroy(&raw mut self.0) };
        }
    }

    #[derive(Debug)]
    pub(crate) struct Child {
        pid: c_int,
        /// Set when a wait found that the child is no longer ours to wait
        /// for: someone else collected it, and its identifier is free for
        /// the system to give to another process.
        gone: AtomicBool,
    }

    pub(crate) fn spawn(command: &Command<'_>) -> Result<Child> {
        let mut paths = CStrings::new();
        match command.current_dir {
            // The program is relative to the caller's directory, and the
            // child looks for it from its own.
            Some(_) if !command.program.is_empty() && !command.program.starts_with(b"/") => {
                let here = crate::fs::current_dir_vec()?;
                paths.push(&[&here, b"/", command.program])?;
            }
            _ => paths.push(&[command.program])?,
        }
        if let Some(dir) = command.current_dir {
            paths.push(&[dir])?;
        }
        let group = match command.process_group {
            None => None,
            Some(group) => Some(c_int::try_from(group).map_err(|_| ErrorKind::InvalidInput)?),
        };
        let mut argv = CStrings::new();
        argv.push(&[command.arg0.unwrap_or(command.program)])?;
        for arg in command.args.iter() {
            argv.push(&[arg])?;
        }
        let mut envp = CStrings::new();
        if let Some(vars) = command.env {
            for var in vars.iter() {
                envp.push(&[var])?;
            }
        }
        let paths = paths.pointers()?;
        let argv = argv.pointers()?;
        let envp = match command.env {
            Some(_) => envp.pointers()?.as_ptr(),
            // SAFETY: the function returns the address of `environ`.
            // Reading it races with a concurrent `setenv`, as it does for
            // everything that reads the environment.
            None => unsafe { *_NSGetEnviron() },
        };

        let mut attributes = Attributes(ptr::null_mut());
        // SAFETY: the object is written by the call.
        check(unsafe { posix_spawnattr_init(&raw mut attributes.0) })?;
        // Default dispositions for every signal that can have another, and
        // nothing blocked.
        let default: SigSet = !(1 << (SIGKILL - 1) | 1 << (SIGSTOP - 1));
        let mask: SigSet = 0;
        let mut flags =
            POSIX_SPAWN_SETSIGDEF | POSIX_SPAWN_SETSIGMASK | POSIX_SPAWN_CLOEXEC_DEFAULT;
        // What `posix_spawn` has no attribute for is done by a child of
        // our own, which then becomes the program.
        let setup = Setup::new(command)?;
        if setup.is_some() {
            // That child also sets its session or group itself.
            flags |= POSIX_SPAWN_SETEXEC;
        } else if command.new_session {
            flags |= POSIX_SPAWN_SETSID;
        } else if let Some(group) = group {
            flags |= POSIX_SPAWN_SETPGROUP;
            // SAFETY: the attributes are initialised.
            check(unsafe { posix_spawnattr_setpgroup(&raw mut attributes.0, group) })?;
        }
        // SAFETY: the attributes are initialised; the sets are read.
        unsafe {
            check(posix_spawnattr_setsigdefault(
                &raw mut attributes.0,
                &raw const default,
            ))?;
            check(posix_spawnattr_setsigmask(
                &raw mut attributes.0,
                &raw const mask,
            ))?;
            check(posix_spawnattr_setflags(&raw mut attributes.0, flags))?;
        }

        // Where each standard descriptor of the child comes from. They are
        // installed in order: a source that sits on another standard
        // descriptor than its own would be overwritten before it is used,
        // and is moved out of the way here.
        let mut held: [Option<OwnedHandle>; 3] = [None, None, None];
        let mut sources = [Source::Missing; 3];
        for (target, stdio) in command.stdio.iter().enumerate() {
            let fd = target as c_int;
            sources[target] = match stdio {
                // Inheriting a descriptor that is not open is an error
                // for `posix_spawn`: the child simply has none either.
                // SAFETY: no memory is involved.
                Stdio::Inherit if unsafe { fcntl(fd, F_GETFD) } == -1 => Source::Missing,
                Stdio::Inherit => Source::Keep,
                Stdio::Null => Source::Null,
                Stdio::Handle(handle) if handle.as_raw() == fd => Source::Keep,
                Stdio::Handle(handle) if (0..3).contains(&handle.as_raw()) => {
                    let min: c_int = 3;
                    // SAFETY: no memory is involved; the descriptor
                    // returned is new.
                    let moved = unsafe {
                        OwnedHandle::from_raw(cvt(fcntl(handle.as_raw(), F_DUPFD_CLOEXEC, min))?)
                    };
                    let fd = moved.as_raw();
                    held[target] = Some(moved);
                    Source::Fd(fd)
                }
                Stdio::Handle(handle) => Source::Fd(handle.as_raw()),
            };
        }
        let dir = if command.current_dir.is_some() {
            paths[1]
        } else {
            ptr::null()
        };

        let mut actions = FileActions(ptr::null_mut());
        // SAFETY: the object is written by the call.
        check(unsafe { posix_spawn_file_actions_init(&raw mut actions.0) })?;
        for (target, source) in sources.iter().enumerate() {
            let target = target as c_int;
            // SAFETY: the actions are initialised; the path is copied.
            check(unsafe {
                match *source {
                    Source::Missing => 0,
                    // A child of our own has put every descriptor in its
                    // place by the time it calls `posix_spawn`.
                    _ if setup.is_some() => {
                        posix_spawn_file_actions_addinherit_np(&raw mut actions.0, target)
                    }
                    Source::Keep => {
                        posix_spawn_file_actions_addinherit_np(&raw mut actions.0, target)
                    }
                    Source::Null => posix_spawn_file_actions_addopen(
                        &raw mut actions.0,
                        target,
                        c"/dev/null".as_ptr(),
                        O_RDWR,
                        0,
                    ),
                    Source::Fd(fd) => {
                        posix_spawn_file_actions_adddup2(&raw mut actions.0, fd, target)
                    }
                }
            })?;
        }
        if !dir.is_null() && setup.is_none() {
            // SAFETY: the actions are initialised; the path is copied.
            check(unsafe { posix_spawn_file_actions_addchdir_np(&raw mut actions.0, dir) })?;
        }

        // SAFETY: every pointer is valid for the call: C strings,
        // NULL-terminated arrays of them, initialised objects.
        let run = |pid: *mut c_int| unsafe {
            posix_spawn(
                pid,
                paths[0],
                &raw const actions.0,
                &raw const attributes.0,
                argv.as_ptr(),
                envp,
            )
        };
        let mut pid: c_int = 0;
        match setup {
            None => check(run(&raw mut pid))?,
            Some(setup) => {
                let own = Own {
                    session: command.new_session,
                    group,
                    sources,
                    setup,
                    dir,
                };
                pid = fork_and_run(&own, || run(ptr::null_mut()))?;
            }
        }
        drop(held);
        Ok(Child {
            pid,
            gone: AtomicBool::new(false),
        })
    }

    /// Where a standard descriptor of the child comes from.
    #[derive(Clone, Copy)]
    enum Source {
        /// The child has none.
        Missing,
        /// The caller's own, which is in place.
        Keep,
        /// The null device.
        Null,
        /// A duplicate of this descriptor, which is 3 or more.
        Fd(c_int),
    }

    /// What a child of our own does before it becomes the program.
    struct Own {
        session: bool,
        group: Option<c_int>,
        sources: [Source; 3],
        setup: Setup,
        /// Null to stay in the caller's directory.
        dir: *const c_char,
    }

    impl Own {
        /// Sets the calling process up. Returns the error number of what
        /// failed, 0 if nothing did.
        ///
        /// Runs in a child made by `fork` of a process that may have other
        /// threads: it only reads memory and calls functions that are
        /// async-signal-safe (`setsid`, `setpgid`, `open`, `dup2`,
        /// `close`, `fcntl`, `chdir`, and those of [`Setup::apply`]).
        fn apply(&self) -> c_int {
            let failed = |ret: c_int| ret == -1;
            let error = || crate::sys::last_error().raw_os_error();
            // SAFETY: the path is a C string; the descriptors closed and
            // replaced are the child's own copies.
            unsafe {
                if self.session {
                    if failed(setsid()) {
                        return error();
                    }
                } else if let Some(group) = self.group
                    && failed(setpgid(0, group))
                {
                    return error();
                }

                // The standard descriptors, here and not by file actions:
                // when `posix_spawn` replaces the calling process, a
                // `dup2` action whose source is close-on-exec, as all of
                // oscall's descriptors are, fails with `EBADF` (measured).
                // What `dup2` makes is not close-on-exec.
                for (target, source) in self.sources.iter().enumerate() {
                    let target = target as c_int;
                    match *source {
                        Source::Missing => {}
                        Source::Keep => {
                            if failed(fcntl(target, F_SETFD, 0)) {
                                return error();
                            }
                        }
                        Source::Null => {
                            let fd = open(c"/dev/null".as_ptr(), O_RDWR);
                            if failed(fd) {
                                return error();
                            }
                            if fd != target {
                                let moved = dup2(fd, target);
                                close(fd);
                                if failed(moved) {
                                    return error();
                                }
                            }
                        }
                        Source::Fd(fd) => {
                            if failed(dup2(fd, target)) {
                                return error();
                            }
                        }
                    }
                }

                let code = self.setup.apply();
                if code != 0 {
                    return code;
                }
                // With the identity the program will have.
                if !self.dir.is_null() && failed(chdir(self.dir)) {
                    return error();
                }
            }
            0
        }
    }

    /// What `posix_spawn` has no attribute for: the file creation mask,
    /// the limits and the identity.
    struct Setup {
        umask: Option<u16>,
        limits: Vec<(c_int, [u64; 2])>,
        /// The list for `setgroups`: the group of the child, then its
        /// supplementary groups (see [`Setup::new`]).
        groups: Option<Vec<u32>>,
        gid: Option<u32>,
        uid: Option<u32>,
    }

    impl Setup {
        /// Checks and converts what `command` asks for; `None` when it
        /// asks for nothing of the kind.
        fn new(command: &Command<'_>) -> Result<Option<Self>> {
            let setup = &command.setup;
            if setup.is_none() {
                return Ok(None);
            }
            let umask = match setup.umask {
                None => None,
                Some(mask) if mask & !0o777 == 0 => Some(mask as u16),
                Some(_) => return Err(ErrorKind::InvalidInput.into()),
            };
            // The first entry of the list of a process is not a
            // supplementary group but the place of its own group:
            // `setgid` writes the group there, over what `setgroups` put
            // (measured: a child given the group 4242 and the groups 7
            // and 8 had 4242 and 8). So the list starts with the group
            // the child is to have, which is not repeated after it. The
            // system takes 16 entries, that one included.
            let groups = match setup.groups {
                None => None,
                Some(groups) => {
                    // SAFETY: no argument, and the call cannot fail.
                    let own = setup.gid.unwrap_or_else(|| unsafe { getegid() });
                    let mut list = Vec::new();
                    list.try_reserve_exact(groups.len().saturating_add(1))
                        .map_err(|_| ErrorKind::OutOfMemory)?;
                    list.push(own);
                    list.extend(groups.iter().copied().filter(|group| *group != own));
                    if c_int::try_from(list.len()).is_err() {
                        return Err(ErrorKind::InvalidInput.into());
                    }
                    Some(list)
                }
            };
            let mut limits = Vec::new();
            limits
                .try_reserve_exact(setup.limits.len())
                .map_err(|_| ErrorKind::OutOfMemory)?;
            for &(resource, limit) in setup.limits {
                limits.push((resource_number(resource), raw_limit(limit)?));
            }
            Ok(Some(Self {
                umask,
                limits,
                groups,
                gid: setup.gid,
                uid: setup.uid,
            }))
        }

        /// Applies the setup to the calling process. Returns the error
        /// number of what failed, 0 if nothing did.
        ///
        /// Runs in a child made by `fork` of a process that may have
        /// other threads: it only reads memory and calls functions that
        /// are async-signal-safe (`umask`, `setrlimit`, `setgroups`,
        /// `setgid`, `setuid`).
        fn apply(&self) -> c_int {
            let failed = |ret: c_int| ret == -1;
            let error = || crate::sys::last_error().raw_os_error();
            // SAFETY: the pointers and lengths are those of live slices;
            // the calls change the calling process alone.
            unsafe {
                if let Some(mask) = self.umask {
                    umask(mask);
                }
                // Before the identity changes: raising a hard limit needs
                // the privilege the child may be about to give up.
                for (resource, limit) in &self.limits {
                    if failed(setrlimit(*resource, limit)) {
                        return error();
                    }
                }
                // The groups first, then the group, then the user: each
                // needs the privilege that changing the user gives up.
                if let Some(groups) = &self.groups
                    && failed(setgroups(groups.len() as c_int, groups.as_ptr()))
                {
                    return error();
                }
                if let Some(gid) = self.gid
                    && failed(setgid(gid))
                {
                    return error();
                }
                if let Some(uid) = self.uid
                    && failed(setuid(uid))
                {
                    return error();
                }
            }
            0
        }
    }

    /// Creates a child with `fork` that sets itself up as `own` says and
    /// then calls `exec`, which replaces it with the program or returns an
    /// error number. Returns the child's identifier once the program runs
    /// in it; if it could not, the reason, and the child is gone.
    fn fork_and_run(own: &Own, exec: impl Fn() -> c_int) -> Result<c_int> {
        // The pipe the child reports a failure through: close-on-exec, so
        // that it ends without a word when the program starts.
        let (error_read, mut error_write) = crate::sys::io::pipe()?;
        if error_write.as_raw() < 3 {
            // Not where the program's standard handles go.
            let min: c_int = 3;
            // SAFETY: no memory is involved; the descriptor returned is
            // new.
            error_write = unsafe {
                OwnedHandle::from_raw(cvt(fcntl(error_write.as_raw(), F_DUPFD_CLOEXEC, min))?)
            };
        }

        // No signal handler of this program may run in the child. The
        // program starts with the mask its attributes give it.
        let all: SigSet = !0;
        let mut saved: SigSet = 0;
        // SAFETY: both sets are valid for the call.
        check(unsafe { pthread_sigmask(SIG_SETMASK, &raw const all, &raw mut saved) })?;

        // SAFETY: the child calls nothing but async-signal-safe functions
        // (and `posix_spawn`, which with `POSIX_SPAWN_SETEXEC` is one
        // system call on objects built before the fork), then exits
        // without running anything of this program.
        let forked = unsafe { c_fork() };
        if forked == 0 {
            let mut code = own.apply();
            if code == 0 {
                code = exec();
            }
            // SAFETY: `code` is four readable bytes; `_exit` runs nothing.
            unsafe {
                c_write(
                    error_write.as_raw(),
                    (&raw const code).cast(),
                    size_of::<c_int>(),
                );
                _exit(127)
            }
        }
        let forked = cvt(forked);

        // The child, if there is one, has its own copy of the write end:
        // once ours is closed, reading returns what the child wrote, or
        // nothing when the program started. Signals are still blocked:
        // nothing interrupts these calls.
        drop(error_write);
        let mut failure = None;
        if let Ok(pid) = forked {
            let mut code: c_int = 0;
            // SAFETY: `code` is four writable bytes.
            let read = unsafe {
                c_read(
                    error_read.as_raw(),
                    (&raw mut code).cast(),
                    size_of::<c_int>(),
                )
            };
            if read == size_of::<c_int>() as isize {
                failure = Some(Error::from_raw_os_error(code));
                // The child has exited, or is about to: collect it.
                // SAFETY: neither the status nor the usage is asked for.
                unsafe { wait4(pid, ptr::null_mut(), 0, ptr::null_mut()) };
            }
        }
        // SAFETY: the set is valid for the call.
        unsafe { pthread_sigmask(SIG_SETMASK, &raw const saved, ptr::null_mut()) };
        let pid = forked?;
        match failure {
            Some(error) => Err(error),
            None => Ok(pid),
        }
    }

    /// `fork`: `None` in the child.
    ///
    /// # Safety
    ///
    /// See `process::unix::fork`.
    pub(crate) unsafe fn fork() -> Result<Option<Child>> {
        // SAFETY: the caller's contract.
        let pid = cvt(unsafe { c_fork() })?;
        if pid == 0 {
            return Ok(None);
        }
        Ok(Some(Child {
            pid,
            gone: AtomicBool::new(false),
        }))
    }

    impl Child {
        pub(crate) fn id(&self) -> u32 {
            self.pid as u32
        }

        /// Whether the child was found to have been collected by other
        /// code: its identifier is no longer its own.
        pub(crate) fn is_gone(&self) -> bool {
            self.gone.load(Ordering::Acquire)
        }

        pub(crate) fn wait(
            &self,
            block: bool,
        ) -> Result<Option<(ExitStatus, Option<ResourceUsage>)>> {
            // Not asked again: the identifier may by now be the one of
            // another child of this process, which this call would collect.
            if self.gone.load(Ordering::Acquire) {
                return Err(Error::from_raw_os_error(errno::ECHILD));
            }
            let mut status: c_int = 0;
            let mut usage = RUsage::default();
            let options = if block { 0 } else { WNOHANG };
            // SAFETY: `status` and `usage` are written by the call. The
            // process is a child that has not been waited for: the
            // identifier is its own.
            let waited = unsafe { wait4(self.pid, &raw mut status, options, &raw mut usage) };
            let pid = match cvt(waited) {
                Ok(pid) => pid,
                Err(error) => {
                    // Collected by other code, or by the system because
                    // SIGCHLD is ignored.
                    if error.raw_os_error() == errno::ECHILD {
                        self.gone.store(true, Ordering::Release);
                    }
                    return Err(error);
                }
            };
            if pid == 0 {
                return Ok(None);
            }
            // The low seven bits are the terminating signal, 0 for an exit
            // (and 0x7f for a stop, which is not asked for).
            let signal = status & 0x7f;
            let status = if signal == 0 {
                ExitStatus::exited(status >> 8 & 0xff)
            } else {
                ExitStatus::signaled(signal, status & 0x80 != 0)
            };
            Ok(Some((status, Some(usage_from(&usage)))))
        }

        pub(crate) fn kill(&self) -> Result<()> {
            if self.gone.load(Ordering::Acquire) {
                return Ok(());
            }
            self.send_signal(SIGKILL)
        }

        pub(crate) fn send_signal(&self, signal: i32) -> Result<()> {
            // The caller only gets here while the child has not been waited
            // for: the identifier is still its own.
            if self.pid <= 0 || self.gone.load(Ordering::Acquire) {
                return Err(ErrorKind::NoSuchProcess.into());
            }
            // SAFETY: no memory is involved.
            cvt(unsafe { c_kill(self.pid, signal) }).map(drop)
        }
    }
}