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
//! `process` on Linux and fullrust.
//!
//! Signal numbers and the structures used here are the same on the six
//! architectures supported (`include/uapi/asm-generic/signal.h`,
//! `siginfo.h`); what differs is said where it matters.

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::{errno, syscall};
use crate::{Error, Result};

const SIGABRT: usize = 6;
const SIGKILL: usize = 9;
pub(crate) const SIGUSR1: i32 = 10;
pub(crate) const SIGUSR2: i32 = 12;
pub(crate) const SIGCHLD: i32 = 17;
pub(crate) const SIGCONT: i32 = 18;
pub(crate) const SIGSTOP: i32 = 19;

const AT_FDCWD: i32 = -100;

const SIG_UNBLOCK: usize = 1;
#[cfg(feature = "alloc")]
const SIG_SETMASK: usize = 2;

/// The size of the kernel's `sigset_t`, which the `rt_sig*` calls take as
/// an argument: 64 signals, on 32-bit and 64-bit architectures alike. A
/// `u64` holds it, and the two values used here, no signal and every
/// signal, read the same whatever the word size and the byte order.
const SIGSET_SIZE: usize = 8;

/// A `struct sigaction` (the kernel's, not libc's) that sets the default
/// disposition: `sa_handler = SIG_DFL` (0), no flag, no restorer, an empty
/// mask. Its layout is `handler, flags, [restorer,] mask`, with the
/// restorer on x86, arm and aarch64 only (`SA_RESTORER`): all zeroes is
/// the same value in every layout, and eight words cover the largest.
type DefaultAction = [usize; 8];

pub(crate) fn id() -> u32 {
    // SAFETY: no argument, and the call cannot fail.
    unsafe { syscall!(GETPID) }.map_or(0, |pid| pid as u32)
}

pub(crate) fn parent_id() -> u32 {
    // SAFETY: no argument, and the call cannot fail.
    unsafe { syscall!(GETPPID) }.map_or(0, |pid| pid as u32)
}

pub(crate) fn exit(code: i32) -> ! {
    loop {
        // SAFETY: terminates every thread of the process; does not return.
        let _ = unsafe { syscall!(EXIT_GROUP, code) };
    }
}

pub(crate) fn abort() -> ! {
    // What libc's `abort` does. First the signal as it is: a handler the
    // program installed runs. If that did not end the process (the handler
    // returned, the signal is ignored or blocked), restore the default
    // disposition, send it again and unblock it.
    let action: DefaultAction = [0; 8];
    let set: u64 = 1 << (SIGABRT - 1);
    // SAFETY: the structures are valid for the calls that read them, and
    // the signal is sent to the calling thread only.
    unsafe {
        let pid = syscall!(GETPID).unwrap_or(0);
        let tid = syscall!(GETTID).unwrap_or(0);
        let _ = syscall!(TGKILL, pid, tid, SIGABRT);
        let _ = syscall!(RT_SIGACTION, SIGABRT, action.as_ptr(), 0, SIGSET_SIZE);
        let _ = syscall!(TGKILL, pid, tid, SIGABRT);
        let _ = syscall!(RT_SIGPROCMASK, SIG_UNBLOCK, &raw const set, 0, SIGSET_SIZE);
    }
    // Not reached, unless the kernel refused all of the above.
    exit(127)
}

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 X_OK: usize = 1;
    const AT_EACCESS: usize = 0x200;

    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.
        let result = unsafe { syscall!(FACCESSAT2, AT_FDCWD, path.as_ptr(), X_OK, AT_EACCESS) };
        match result {
            // An emulator older than the call (Linux 5.8): the same check
            // with the real identity, which is nearly always the same.
            Err(error) if error.raw_os_error() == errno::ENOSYS => {
                // SAFETY: as above.
                unsafe { syscall!(FACCESSAT, AT_FDCWD, path.as_ptr(), X_OK) }
            }
            result => result,
        }
    })
    .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.
    unsafe { syscall!(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 as i32)
}

/// `struct rusage`: two `__kernel_old_timeval` (seconds and microseconds,
/// each a `long`) and fourteen `long`s, the first of which is the peak
/// resident set size in kibibytes.
pub(crate) type RUsage = [isize; 18];

pub(crate) fn usage_from(usage: &RUsage) -> ResourceUsage {
    let time = |seconds: isize, micros: isize| {
        Duration::new(seconds.max(0) as u64, 0)
            + Duration::from_micros(micros.clamp(0, 999_999) as u64)
    };
    ResourceUsage {
        user_time: time(usage[0], usage[1]),
        system_time: time(usage[2], usage[3]),
        max_resident_memory: (usage[4].max(0) as u64).saturating_mul(1024),
    }
}

pub(crate) fn resource_usage() -> Result<ResourceUsage> {
    const RUSAGE_SELF: usize = 0;
    let mut usage: RUsage = [0; 18];
    // SAFETY: the kernel writes one `struct rusage`.
    unsafe { syscall!(GETRUSAGE, RUSAGE_SELF, &raw mut usage) }?;
    Ok(usage_from(&usage))
}

/// `RLIM64_INFINITY`.
const UNLIMITED: u64 = u64::MAX;

/// The `RLIMIT_*` number: `include/uapi/asm-generic/resource.h`, which the
/// six architectures supported share.
fn resource_number(resource: Resource) -> usize {
    match resource {
        Resource::CpuTime => 0,
        Resource::FileSize => 1,
        Resource::Data => 2,
        Resource::Stack => 3,
        Resource::CoreSize => 4,
        Resource::Processes => 6,
        Resource::OpenFiles => 7,
        Resource::LockedMemory => 8,
        Resource::AddressSpace => 9,
    }
}

pub(crate) fn limit(resource: Resource) -> Result<Limit> {
    // `struct rlimit64`: the soft limit, then the hard one.
    let mut old = [0u64; 2];
    // SAFETY: the kernel writes one `struct rlimit64`; process 0 is the
    // caller.
    unsafe { syscall!(PRLIMIT64, 0, resource_number(resource), 0, &raw mut old) }?;
    let value = |raw: u64| (raw != UNLIMITED).then_some(raw);
    Ok(Limit {
        soft: value(old[0]),
        hard: value(old[1]),
    })
}

pub(crate) fn set_limit(resource: Resource, limit: Limit) -> Result<()> {
    let raw = |value: Option<u64>| match value {
        None => Ok(UNLIMITED),
        Some(UNLIMITED) => Err(Error::from(crate::ErrorKind::InvalidInput)),
        Some(value) => Ok(value),
    };
    let new = [raw(limit.soft)?, raw(limit.hard)?];
    // SAFETY: the kernel reads one `struct rlimit64`.
    unsafe { syscall!(PRLIMIT64, 0, resource_number(resource), &raw const new, 0) }.map(drop)
}

pub(crate) fn process_group(pid: u32) -> Result<u32> {
    // SAFETY: no memory is involved.
    unsafe { syscall!(GETPGID, pid) }.map(|pgid| pgid as u32)
}

pub(crate) fn session(pid: u32) -> Result<u32> {
    // SAFETY: no memory is involved.
    unsafe { syscall!(GETSID, pid) }.map(|sid| sid as u32)
}

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

#[cfg(feature = "alloc")]
mod spawn {
    use core::ffi::{c_char, c_void};

    use super::{
        AT_FDCWD, DefaultAction, RUsage, SIG_SETMASK, SIGCHLD, SIGKILL, SIGSET_SIZE, SIGSTOP,
        usage_from,
    };
    use crate::mem::Protection;
    use crate::process::{CStrings, Command, ExitStatus, ResourceUsage, Stdio};
    use crate::sys::io::fcntl;
    use crate::sys::{check, errno, mem, nr, syscall};
    use crate::{AsHandle, BorrowedHandle, Error, ErrorKind, OwnedHandle, Result};

    #[cfg(not(feature = "std"))]
    const O_RDONLY: usize = 0;
    const O_RDWR: usize = 2;
    /// The same on every architecture.
    const O_CLOEXEC: usize = 0o2000000;
    const F_SETFD: usize = 2;
    const F_DUPFD_CLOEXEC: usize = 1030;

    const CLONE_VM: usize = 0x100;
    const CLONE_PIDFD: usize = 0x1000;
    const CLONE_VFORK: usize = 0x4000;

    const P_PID: usize = 1;
    const P_PIDFD: usize = 3;
    const WNOHANG: usize = 1;
    const WEXITED: usize = 4;
    const CLD_EXITED: i32 = 1;
    const CLD_KILLED: i32 = 2;
    const CLD_DUMPED: i32 = 3;

    /// The highest signal number (`_NSIG`).
    const SIGNALS: usize = 64;

    /// The stack the child runs on until it calls `execve`. It runs a few
    /// small functions that make system calls.
    const STACK_SIZE: usize = 64 * 1024;

    /// What the child needs. Everything is prepared by the parent: the
    /// child only makes system calls.
    #[repr(C)]
    struct Exec {
        program: *const c_char,
        argv: *const *const c_char,
        envp: *const *const c_char,
        /// Null to stay in the parent's directory.
        dir: *const c_char,
        /// The descriptor to install as each standard one; -1 to leave the
        /// parent's alone. One that is not its own target is 3 or more.
        stdio: [i32; 3],
        /// The write end of a close-on-exec pipe, 3 or more: the child
        /// writes the error number there if it cannot run the program.
        error: i32,
        /// Whether to start a session.
        session: bool,
        /// The process group to join, 0 for a new one, -1 for the parent's.
        group: i32,
    }

    /// Creates a child process that shares the memory of the caller, runs
    /// `f(arg)` on the stack that ends at `stack`, and suspends the caller
    /// until the child calls `execve` or exits (`flags` must have
    /// `CLONE_VM | CLONE_VFORK`). Returns the child's process identifier,
    /// or a negative error number.
    ///
    /// The first three arguments of `clone` are the same on every
    /// architecture (flags, stack, parent tid pointer, which with
    /// `CLONE_PIDFD` receives the pidfd); the order of the last two varies,
    /// and they are not used with these flags.
    ///
    /// The function and its argument travel on the child's stack. The
    /// child never returns into the caller's frames: it has its own stack,
    /// and `f` does not return.
    ///
    /// # Safety
    ///
    /// `stack` must be the end of a writable region large enough for `f`.
    /// `f` runs in a copy of the calling thread that shares its memory and
    /// its thread-local storage: it must only make system calls, and must
    /// not allocate, panic, take locks nor touch thread-local state.
    #[cfg(target_arch = "x86_64")]
    #[unsafe(naked)]
    unsafe extern "C" fn clone_vfork(
        flags: usize,
        stack: *mut u8,
        pidfd: *mut i32,
        f: unsafe extern "C" fn(*mut c_void) -> !,
        arg: *mut c_void,
    ) -> isize {
        // rdi = flags, rsi = stack, rdx = pidfd, rcx = f, r8 = arg.
        // clone(rdi = flags, rsi = stack, rdx = ptid, r10 = ctid, r8 = tls).
        core::arch::naked_asm!(
            "and rsi, -16",
            "sub rsi, 16",
            "mov [rsi], rcx",
            "mov [rsi + 8], r8",
            "xor r10d, r10d",
            "xor r8d, r8d",
            "mov eax, {clone}",
            "syscall",
            "test rax, rax",
            "jz 2f",
            "ret",
            // The child: rsp is the new stack, 16-byte aligned once the
            // two words are popped, as the ABI wants before a call.
            "2:",
            "xor ebp, ebp",
            "pop rax",
            "pop rdi",
            "call rax",
            "ud2",
            clone = const nr::CLONE,
        )
    }

    /// See the x86_64 version.
    #[cfg(target_arch = "x86")]
    #[unsafe(naked)]
    unsafe extern "C" fn clone_vfork(
        flags: usize,
        stack: *mut u8,
        pidfd: *mut i32,
        f: unsafe extern "C" fn(*mut c_void) -> !,
        arg: *mut c_void,
    ) -> isize {
        // After the push: [esp + 8] = flags, + 12 = stack, + 16 = pidfd,
        // + 20 = f, + 24 = arg.
        // clone(ebx = flags, ecx = stack, edx = ptid, esi = tls, edi = ctid).
        core::arch::naked_asm!(
            "push ebx",
            "mov ecx, [esp + 12]",
            "and ecx, -16",
            "sub ecx, 16",
            "mov eax, [esp + 24]",
            "mov [ecx], eax",
            "mov eax, [esp + 20]",
            "mov [ecx + 4], eax",
            "mov ebx, [esp + 8]",
            "mov edx, [esp + 16]",
            "mov eax, {clone}",
            "int 0x80",
            "test eax, eax",
            "jz 2f",
            "pop ebx",
            "ret",
            // The child: esp is 16-byte aligned and points to the argument,
            // as the ABI wants at a call.
            "2:",
            "xor ebp, ebp",
            "mov eax, [esp + 4]",
            "call eax",
            "ud2",
            clone = const nr::CLONE,
        )
    }

    /// See the x86_64 version.
    #[cfg(target_arch = "aarch64")]
    #[unsafe(naked)]
    unsafe extern "C" fn clone_vfork(
        flags: usize,
        stack: *mut u8,
        pidfd: *mut i32,
        f: unsafe extern "C" fn(*mut c_void) -> !,
        arg: *mut c_void,
    ) -> isize {
        // x0 = flags, x1 = stack, x2 = pidfd, x3 = f, x4 = arg.
        // clone(x0 = flags, x1 = stack, x2 = ptid, x3 = tls, x4 = ctid).
        core::arch::naked_asm!(
            // `bti c`, a no-op where branch target identification is off.
            "hint #34",
            "and x1, x1, #-16",
            "stp x3, x4, [x1, #-16]!",
            "mov x3, #0",
            "mov x4, #0",
            "mov x8, {clone}",
            "svc #0",
            "cbz x0, 2f",
            "ret",
            // The child: sp is the new stack, 16-byte aligned.
            "2:",
            "mov x29, #0",
            "mov x30, #0",
            "ldp x1, x0, [sp]",
            "blr x1",
            "brk #1",
            clone = const nr::CLONE,
        )
    }

    /// See the x86_64 version.
    #[cfg(target_arch = "arm")]
    #[unsafe(naked)]
    unsafe extern "C" fn clone_vfork(
        flags: usize,
        stack: *mut u8,
        pidfd: *mut i32,
        f: unsafe extern "C" fn(*mut c_void) -> !,
        arg: *mut c_void,
    ) -> isize {
        // r0 = flags, r1 = stack, r2 = pidfd, r3 = f, [sp] = arg.
        // clone(r0 = flags, r1 = stack, r2 = ptid, r3 = tls, r4 = ctid),
        // with the number in r7. Every instruction exists in both the ARM
        // and the Thumb-2 instruction sets.
        core::arch::naked_asm!(
            "push {{r4, r7}}",
            "ldr r4, [sp, #8]",
            "bic r1, r1, #15",
            "str r4, [r1, #-4]!",
            "str r3, [r1, #-4]!",
            "mov r7, #{clone}",
            "svc 0",
            "cmp r0, #0",
            "beq 2f",
            "pop {{r4, r7}}",
            "bx lr",
            // The child: sp is the new stack, 8-byte aligned.
            "2:",
            "mov r11, #0",
            "mov lr, #0",
            "ldr r1, [sp]",
            "ldr r0, [sp, #4]",
            "blx r1",
            "udf #0",
            clone = const nr::CLONE,
        )
    }

    /// See the x86_64 version.
    #[cfg(any(target_arch = "riscv32", target_arch = "riscv64"))]
    #[unsafe(naked)]
    unsafe extern "C" fn clone_vfork(
        flags: usize,
        stack: *mut u8,
        pidfd: *mut i32,
        f: unsafe extern "C" fn(*mut c_void) -> !,
        arg: *mut c_void,
    ) -> isize {
        // a0 = flags, a1 = stack, a2 = pidfd, a3 = f, a4 = arg.
        // clone(a0 = flags, a1 = stack, a2 = ptid, a3 = tls, a4 = ctid),
        // with the number in a7.
        #[cfg(target_arch = "riscv64")]
        core::arch::naked_asm!(
            "andi a1, a1, -16",
            "addi a1, a1, -16",
            "sd a3, 0(a1)",
            "sd a4, 8(a1)",
            "li a7, {clone}",
            "ecall",
            "beqz a0, 2f",
            "ret",
            // The child: sp is the new stack, 16-byte aligned.
            "2:",
            "mv s0, zero",
            "mv ra, zero",
            "ld a1, 0(sp)",
            "ld a0, 8(sp)",
            "jalr a1",
            "unimp",
            clone = const nr::CLONE,
        );
        #[cfg(target_arch = "riscv32")]
        core::arch::naked_asm!(
            "andi a1, a1, -16",
            "addi a1, a1, -16",
            "sw a3, 0(a1)",
            "sw a4, 4(a1)",
            "li a7, {clone}",
            "ecall",
            "beqz a0, 2f",
            "ret",
            "2:",
            "mv s0, zero",
            "mv ra, zero",
            "lw a1, 0(sp)",
            "lw a0, 4(sp)",
            "jalr a1",
            "unimp",
            clone = const nr::CLONE,
        );
    }

    /// What the child runs. It shares the parent's memory: see
    /// [`clone_vfork`] for what it may do.
    ///
    /// # Safety
    ///
    /// `arg` must point to an [`Exec`] whose pointers are valid, in a
    /// process created by `clone_vfork` with every signal blocked.
    unsafe extern "C" fn child(arg: *mut c_void) -> ! {
        // SAFETY: the caller's contract.
        let exec = unsafe { &*arg.cast::<Exec>() };
        // SAFETY: as above.
        let code = unsafe { exec_program(exec) }.raw_os_error();
        // SAFETY: `code` is four readable bytes; then the child exits,
        // without running anything of the program it shares memory with.
        unsafe {
            let _ = syscall!(WRITE, exec.error, &raw const code, size_of::<i32>());
            loop {
                let _ = syscall!(EXIT_GROUP, 127);
            }
        }
    }

    /// Sets the child up and runs the program. Only returns if that failed.
    ///
    /// # Safety
    ///
    /// As for [`child`].
    unsafe fn exec_program(exec: &Exec) -> Error {
        // SAFETY: the pointers of `exec` are valid C strings and arrays;
        // the descriptors closed and replaced are the child's own copies.
        let result: Result<usize> = unsafe {
            (|| {
                // The dispositions are the child's own (no CLONE_SIGHAND).
                // Defaults for all: a handler must not run in this process
                // once signals are unblocked, and the program should not
                // start with signals ignored because its parent chose so.
                let action: DefaultAction = [0; 8];
                let mut signal = 1;
                while signal <= SIGNALS {
                    if signal != SIGKILL && signal != SIGSTOP as usize {
                        let _ = syscall!(RT_SIGACTION, signal, action.as_ptr(), 0, SIGSET_SIZE);
                    }
                    signal += 1;
                }

                if exec.session {
                    syscall!(SETSID)?;
                } else if exec.group >= 0 {
                    syscall!(SETPGID, 0, exec.group)?;
                }

                let mut target = 0;
                while target < 3 {
                    let fd = exec.stdio[target as usize];
                    if fd == target {
                        // Already in place, but close-on-exec perhaps.
                        fcntl(fd, F_SETFD, 0)?;
                    } else if fd >= 0 {
                        // The duplicate is not close-on-exec.
                        syscall!(DUP3, fd, target, 0)?;
                    }
                    target += 1;
                }

                // Nothing else passes: close every other descriptor, which
                // catches those opened without close-on-exec by code that
                // is not oscall's. The error pipe stays, and closes itself
                // when the program starts. (`close_range` is from Linux
                // 5.9; an emulator may lack it, and the close-on-exec
                // flags then do what they can.)
                if exec.error > 3 {
                    let _ = syscall!(CLOSE_RANGE, 3, exec.error - 1, 0);
                }
                let _ = syscall!(CLOSE_RANGE, exec.error + 1, u32::MAX, 0);

                if !exec.dir.is_null() {
                    syscall!(CHDIR, exec.dir)?;
                }

                let none: u64 = 0;
                syscall!(RT_SIGPROCMASK, SIG_SETMASK, &raw const none, 0, SIGSET_SIZE)?;

                syscall!(EXECVE, exec.program, exec.argv, exec.envp)
            })()
        };
        match result {
            Err(error) => error,
            // `execve` does not return when it succeeds.
            Ok(_) => Error::from_raw_os_error(errno::EIO),
        }
    }

    /// The calling process's environment for a child to inherit.
    fn inherited_environment(env: &mut CStrings) -> Result<()> {
        // The kernel hands the environment to the process once, on its
        // initial stack, and forgets it. Who keeps it afterwards is the
        // runtime: `std` knows (it asks libc where there is one).
        #[cfg(feature = "std")]
        for (name, value) in std::env::vars_os() {
            env.push(&[name.as_encoded_bytes(), b"=", value.as_encoded_bytes()])?;
        }
        // Without it, what the kernel remembers: the initial environment.
        #[cfg(not(feature = "std"))]
        {
            let path = c"/proc/self/environ";
            // SAFETY: the path is a C string.
            let fd = unsafe { syscall!(OPENAT, AT_FDCWD, path.as_ptr(), O_RDONLY | O_CLOEXEC, 0) }?;
            // SAFETY: the descriptor was just opened.
            let file = unsafe { OwnedHandle::from_raw(fd as i32) };
            let mut data = alloc::vec::Vec::<u8>::new();
            loop {
                data.try_reserve(4096).map_err(|_| ErrorKind::OutOfMemory)?;
                let spare = data.spare_capacity_mut();
                // SAFETY: `spare` is writable for its length.
                let n = unsafe { syscall!(READ, file.as_raw(), spare.as_mut_ptr(), spare.len()) }?;
                if n == 0 {
                    break;
                }
                // SAFETY: the kernel wrote `n` more bytes.
                unsafe { data.set_len(data.len() + n) };
            }
            for variable in data.split(|byte| *byte == 0) {
                if !variable.is_empty() {
                    env.push(&[variable])?;
                }
            }
        }
        Ok(())
    }

    /// A duplicate of `fd` that is not one of the standard descriptors.
    fn duplicate_above_stdio(fd: i32) -> Result<OwnedHandle> {
        // SAFETY: no memory is involved.
        let new = unsafe { fcntl(fd, F_DUPFD_CLOEXEC, 3) }?;
        // SAFETY: the descriptor was just created.
        Ok(unsafe { OwnedHandle::from_raw(new as i32) })
    }

    /// The memory the child runs on, unmapped when dropped.
    struct Stack(*mut u8);

    impl Drop for Stack {
        fn drop(&mut self) {
            // SAFETY: the mapping is ours, and the child no longer uses it:
            // it has called `execve`, or exited, or (emulated as a `fork`)
            // has its own copy.
            let _ = unsafe { mem::unmap(self.0, STACK_SIZE) };
        }
    }

    pub(crate) struct Child {
        pid: u32,
        pidfd: OwnedHandle,
    }

    pub(crate) fn spawn(command: &Command<'_>) -> Result<Child> {
        // Everything that allocates or can fail for an ordinary reason
        // happens before the child exists.
        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()?;
                // A directory out of reach of the root has no path
                // ("(unreachable)/...").
                if !here.starts_with(b"/") {
                    return Err(ErrorKind::NotFound.into());
                }
                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 => -1,
            Some(group) => i32::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();
        match command.env {
            Some(vars) => {
                for var in vars.iter() {
                    envp.push(&[var])?;
                }
            }
            None => inherited_environment(&mut envp)?,
        }
        let paths = paths.pointers()?;
        let argv = argv.pointers()?;
        let envp = envp.pointers()?;

        // The descriptors to install. One that sits on another standard
        // descriptor than its own would be overwritten while the child
        // installs them: it is moved out of the way here. These and the
        // null device are held until the child has them.
        let mut held: [Option<OwnedHandle>; 4] = [None, None, None, None];
        let mut held_count = 0;
        let mut null = None;
        let mut stdio = [-1; 3];
        for (target, source) in command.stdio.iter().enumerate() {
            let fd = match source {
                Stdio::Inherit => continue,
                Stdio::Handle(handle) => handle.as_raw(),
                Stdio::Null => match null {
                    Some(fd) => fd,
                    None => {
                        let path = c"/dev/null";
                        // SAFETY: the path is a C string.
                        let fd = unsafe {
                            syscall!(OPENAT, AT_FDCWD, path.as_ptr(), O_RDWR | O_CLOEXEC, 0)
                        }? as i32;
                        // SAFETY: the descriptor was just opened.
                        held[held_count] = Some(unsafe { OwnedHandle::from_raw(fd) });
                        held_count += 1;
                        null = Some(fd);
                        fd
                    }
                },
            };
            if fd < 0 {
                // -1 would mean "inherit" to the child.
                return Err(ErrorKind::BadHandle.into());
            }
            stdio[target] = if fd < 3 && fd != target as i32 {
                let moved = duplicate_above_stdio(fd)?;
                let fd = moved.as_raw();
                held[held_count] = Some(moved);
                held_count += 1;
                fd
            } else {
                fd
            };
        }

        // The pipe the child reports a failure through. Shared memory
        // would do on Linux itself, but not under an emulator that turns
        // this `clone` into a `fork` (qemu-user).
        let (error_read, mut error_write) = crate::sys::io::pipe()?;
        if error_write.as_raw() < 3 {
            error_write = duplicate_above_stdio(error_write.as_raw())?;
        }

        let exec = Exec {
            program: paths[0],
            argv: argv.as_ptr(),
            envp: envp.as_ptr(),
            dir: if command.current_dir.is_some() {
                paths[1]
            } else {
                core::ptr::null()
            },
            stdio,
            error: error_write.as_raw(),
            session: command.new_session,
            group,
        };
        let exec = (&raw const exec).cast_mut().cast::<c_void>();

        let stack = Stack(crate::mem::map_anonymous(
            STACK_SIZE,
            Protection::READ | Protection::WRITE,
        )?);
        // SAFETY: the end of the mapping.
        let stack_end = unsafe { stack.0.add(STACK_SIZE) };

        // No signal handler may run in the child, which shares this
        // thread's memory: block them all, including those a libc keeps
        // for itself. The child unblocks them once the dispositions are
        // back to their defaults.
        let all: u64 = !0;
        let mut saved: u64 = 0;
        // SAFETY: both sets are valid for the call.
        unsafe {
            syscall!(
                RT_SIGPROCMASK,
                SIG_SETMASK,
                &raw const all,
                &raw mut saved,
                SIGSET_SIZE
            )
        }?;

        // The signal the parent receives when the child exits is the low
        // byte of the flags.
        let flags = CLONE_VM | CLONE_VFORK | SIGCHLD as usize;
        let mut pidfd: i32 = -1;
        // SAFETY: the stack is a fresh mapping; `child` only makes system
        // calls, on what `exec` points to, which outlives it: this thread
        // does not run until the child has called `execve` or exited.
        let mut cloned = check(unsafe {
            clone_vfork(flags | CLONE_PIDFD, stack_end, &raw mut pidfd, child, exec) as usize
        });
        if matches!(cloned, Err(error) if error.raw_os_error() == errno::EINVAL) {
            // An emulator that does not know CLONE_PIDFD: the pidfd is
            // opened below.
            pidfd = -1;
            // SAFETY: as above.
            cloned = check(unsafe {
                clone_vfork(flags, stack_end, &raw mut pidfd, child, exec) as usize
            });
        }

        // 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 `execve` closed the last copy. Signals are still
        // blocked: nothing interrupts these calls.
        drop(error_write);
        let mut failure = None;
        if let Ok(pid) = cloned {
            let mut code: i32 = 0;
            // SAFETY: `code` is four writable bytes.
            let read =
                unsafe { syscall!(READ, error_read.as_raw(), &raw mut code, size_of::<i32>()) };
            if read == Ok(size_of::<i32>()) {
                failure = Some(Error::from_raw_os_error(code));
                // The child has exited, or is about to: collect it.
                // SAFETY: no memory is involved (no `siginfo` is asked for).
                let _ = unsafe { syscall!(WAITID, P_PID, pid, 0, WEXITED, 0) };
            }
        }

        // SAFETY: the set is valid for the call.
        let _ = unsafe {
            syscall!(
                RT_SIGPROCMASK,
                SIG_SETMASK,
                &raw const saved,
                0,
                SIGSET_SIZE
            )
        };
        drop(stack);
        drop(held);

        // SAFETY: when set, the descriptor was just created for us.
        let pidfd = (pidfd >= 0).then(|| unsafe { OwnedHandle::from_raw(pidfd) });
        let pid = cloned?;
        if let Some(error) = failure {
            return Err(error);
        }
        let pidfd = match pidfd {
            Some(pidfd) => pidfd,
            // The child is ours and has not been waited for: its
            // identifier cannot have been reused.
            // SAFETY: no memory is involved.
            None => match unsafe { syscall!(PIDFD_OPEN, pid, 0) } {
                // SAFETY: the descriptor was just created (close-on-exec,
                // as pidfds always are).
                Ok(fd) => unsafe { OwnedHandle::from_raw(fd as i32) },
                Err(error) => {
                    // A child that cannot be tracked cannot be returned.
                    // SAFETY: no memory is involved.
                    unsafe {
                        let _ = syscall!(KILL, pid, SIGKILL);
                        let _ = syscall!(WAITID, P_PID, pid, 0, WEXITED, 0);
                    }
                    return Err(error);
                }
            },
        };
        Ok(Child {
            pid: pid as u32,
            pidfd,
        })
    }

    /// `siginfo_t`: 128 bytes, aligned like a pointer. Three `int`s
    /// (`si_signo`, `si_errno`, `si_code`), then a union that holds
    /// pointers and is aligned accordingly; for a child, `si_pid`,
    /// `si_uid` and `si_status`.
    #[repr(C, align(8))]
    struct SigInfo([i32; 32]);

    const SI_CODE: usize = 2;
    /// The index of the first `int` of the union.
    const SI_FIELDS: usize = if cfg!(target_pointer_width = "64") {
        4
    } else {
        3
    };
    const SI_PID: usize = SI_FIELDS;
    const SI_STATUS: usize = SI_FIELDS + 2;

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

        pub(crate) fn handle(&self) -> BorrowedHandle<'_> {
            self.pidfd.as_handle()
        }

        pub(crate) fn wait(
            &self,
            block: bool,
        ) -> Result<Option<(ExitStatus, Option<ResourceUsage>)>> {
            let mut info = SigInfo([0; 32]);
            let mut usage: RUsage = [0; 18];
            let options = if block { WEXITED } else { WEXITED | WNOHANG };
            // SAFETY: `info` is a writable `siginfo_t`, `usage` a writable
            // `struct rusage`.
            unsafe {
                syscall!(
                    WAITID,
                    P_PIDFD,
                    self.pidfd.as_raw(),
                    &raw mut info,
                    options,
                    &raw mut usage
                )
            }?;
            let info = info.0;
            // With WNOHANG and a child still running, nothing is written.
            if info[SI_PID] == 0 {
                return Ok(None);
            }
            let status = info[SI_STATUS];
            let status = match info[SI_CODE] {
                CLD_EXITED => ExitStatus::exited(status),
                CLD_KILLED => ExitStatus::signaled(status, false),
                CLD_DUMPED => ExitStatus::signaled(status, true),
                _ => return Err(ErrorKind::Other.into()),
            };
            Ok(Some((status, Some(usage_from(&usage)))))
        }

        pub(crate) fn kill(&self) -> Result<()> {
            match self.send_signal(SIGKILL as i32) {
                // Collected by other code, or by the system because
                // SIGCHLD is ignored: there is nothing left to kill. (A
                // child that has exited and waits to be collected takes
                // the signal without an error.)
                Err(error) if error.raw_os_error() == errno::ESRCH => Ok(()),
                result => result,
            }
        }

        pub(crate) fn send_signal(&self, signal: i32) -> Result<()> {
            // SAFETY: no memory is involved (no `siginfo` is given).
            unsafe { syscall!(PIDFD_SEND_SIGNAL, self.pidfd.as_raw(), signal, 0, 0) }.map(drop)
        }
    }

    impl core::fmt::Debug for Child {
        fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
            f.debug_struct("Child")
                .field("pid", &self.pid)
                .field("pidfd", &self.pidfd)
                .finish()
        }
    }
}