oscall 0.1.0

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
//! Tests of `oscall::process::linux`: namespaces, identifier maps, pidfds,
//! cgroups, `prctl`.
//!
//! Much of this is up to the environment: user namespaces can be switched
//! off or restricted, a container's system call filter refuses the calls
//! that take a namespace, the cgroup hierarchy is rarely writable, and
//! qemu-user does not create a process in new namespaces. A test that
//! cannot run says so (`skipped: ...`) and passes; `refusal` is the list of
//! what counts as the environment's doing. What does not depend on any of
//! that (the checks oscall makes itself, pidfds, `prctl`) always runs.
//!
//! What needs a process with a single thread, which a test never is, is in
//! `process_linux_single.rs`.
#![cfg(any(target_os = "linux", target_os = "fullrust"))]

mod common;

/// Says what a test skipped, or found: on the standard error output
/// itself, which the test harness does not capture, so that it shows in
/// the output of a run that passes.
macro_rules! note {
    ($($arg:tt)*) => {
        crate::common::note(&format!($($arg)*))
    };
}

#[cfg(feature = "alloc")]
use oscall::Error;
use oscall::process::linux::{self, IdMap, Namespaces};
use oscall::{ErrorKind, process};

const EPERM: i32 = 1;
#[cfg(feature = "alloc")]
const ECHILD: i32 = 10;
#[cfg(feature = "alloc")]
const EACCES: i32 = 13;
const EINVAL: i32 = 22;
#[cfg(feature = "alloc")]
const ENOSPC: i32 = 28;
const ENOSYS: i32 = 38;

#[cfg(feature = "alloc")]
/// Why the environment refused something that takes a namespace, if the
/// error is one an environment answers with.
fn refusal(error: &Error) -> Option<&'static str> {
    match error.raw_os_error() {
        EPERM | EACCES => Some(
            "not permitted here (user namespaces restricted, or a container's system call filter)",
        ),
        ENOSPC => Some("no user namespace may be created (user.max_user_namespaces)"),
        ENOSYS => Some("the system call is missing (an emulator, a system call filter)"),
        EINVAL if common::emulated() => {
            Some("qemu-user does not create a process in new namespaces")
        }
        _ => None,
    }
}

/// A field of `/proc/self/status`.
fn status_field(name: &str, index: usize) -> String {
    let status = std::fs::read_to_string("/proc/self/status").unwrap();
    let line = status
        .lines()
        .find_map(|line| line.strip_prefix(name)?.strip_prefix(':'))
        .unwrap();
    line.split_whitespace().nth(index).unwrap().to_owned()
}

/// The effective user and group of the process, as it sees them.
fn effective_ids() -> (u32, u32) {
    (
        status_field("Uid", 1).parse().unwrap(),
        status_field("Gid", 1).parse().unwrap(),
    )
}

fn host_name() -> String {
    std::fs::read_to_string("/proc/sys/kernel/hostname")
        .unwrap()
        .trim()
        .to_owned()
}

/// A map of the user namespace of the process, as it reads: the three
/// numbers of each range, the ranges separated by `;`.
fn id_map(name: &str) -> String {
    let text = std::fs::read_to_string(format!("/proc/self/{name}")).unwrap_or_default();
    let ranges: Vec<String> = text
        .lines()
        .map(|line| line.split_whitespace().collect::<Vec<_>>().join(" "))
        .collect();
    ranges.join(";")
}

/// What `/proc/self/ns/<kind>` links to: the identity of a namespace.
fn namespace(kind: &str) -> Option<String> {
    let link = std::fs::read_link(format!("/proc/self/ns/{kind}")).ok()?;
    Some(link.to_string_lossy().into_owned())
}

#[test]
fn namespaces_flags() {
    let all = [
        Namespaces::MOUNT,
        Namespaces::UTS,
        Namespaces::IPC,
        Namespaces::USER,
        Namespaces::PID,
        Namespaces::NETWORK,
        Namespaces::CGROUP,
        Namespaces::TIME,
    ];
    let mut union = Namespaces::empty();
    for (i, &namespace) in all.iter().enumerate() {
        assert!(!namespace.is_empty());
        // Each is a flag of its own.
        assert!(!union.intersects(namespace), "{i}");
        union |= namespace;
    }
    assert!(union.contains(Namespaces::USER | Namespaces::PID));
    assert_eq!(
        format!("{:?}", Namespaces::USER | Namespaces::PID),
        "Namespaces(USER | PID)"
    );
    assert_eq!(Namespaces::default(), Namespaces::empty());
}

/// Process descriptors of processes that are not children.
#[test]
fn pidfd_of_processes() {
    let me = match linux::pidfd_open(process::id()) {
        Ok(pidfd) => pidfd,
        Err(error) if error.raw_os_error() == ENOSYS => {
            note!("skipped: the emulator has no pidfd_open");
            return;
        }
        Err(error) => panic!("pidfd_open: {error}"),
    };
    // Nothing is sent, and the process is there.
    linux::pidfd_send_signal(&me, 0).unwrap();
    // No such signal.
    let error = linux::pidfd_send_signal(&me, 1000).unwrap_err();
    assert_eq!(error.kind(), ErrorKind::InvalidInput, "{error:?}");
    // Not a pidfd.
    let file = std::fs::File::open("/proc/self/status").unwrap();
    let error = linux::pidfd_send_signal(&common::handle_of(&file), 0).unwrap_err();
    assert_eq!(error.kind(), ErrorKind::BadHandle, "{error:?}");

    // The caller is no child of its own.
    #[cfg(feature = "alloc")]
    {
        let error = linux::pidfd_try_wait(&me).unwrap_err();
        assert_eq!(error.raw_os_error(), ECHILD, "{error:?}");
        let error = linux::pidfd_wait(&me).unwrap_err();
        assert_eq!(error.raw_os_error(), ECHILD, "{error:?}");
    }

    // Identifiers that name no process: the system has none this high.
    let error = linux::pidfd_open(i32::MAX as u32).unwrap_err();
    assert_eq!(error.kind(), ErrorKind::NoSuchProcess, "{error:?}");
    for pid in [0, i32::MAX as u32 + 1, u32::MAX] {
        let error = linux::pidfd_open(pid).unwrap_err();
        assert_eq!(error.kind(), ErrorKind::InvalidInput, "{error:?}");
    }
}

/// The files of a user namespace, where they cannot be written.
#[test]
fn id_map_errors() {
    let map = [IdMap {
        inside: 0,
        outside: 0,
        count: 1,
    }];
    // What oscall checks.
    for pid in [0, u32::MAX] {
        for result in [
            linux::write_uid_map(pid, &map),
            linux::write_gid_map(pid, &map),
            linux::allow_setgroups(pid, true),
        ] {
            assert_eq!(result.unwrap_err().kind(), ErrorKind::InvalidInput);
        }
    }
    let me = process::id();
    let error = linux::write_uid_map(me, &[]).unwrap_err();
    assert_eq!(error.kind(), ErrorKind::InvalidInput, "{error:?}");
    // 400 ranges of 33 bytes: more than a page.
    let long: Vec<IdMap> = (0..400)
        .map(|i| IdMap {
            inside: 4_000_000_000 + i,
            outside: 4_000_000_000 + i,
            count: 1_000_000_000,
        })
        .collect();
    let error = linux::write_gid_map(me, &long).unwrap_err();
    assert_eq!(error.kind(), ErrorKind::InvalidInput, "{error:?}");

    // No such process.
    if std::path::Path::new("/proc/self").exists() {
        let error = linux::write_uid_map(i32::MAX as u32, &map).unwrap_err();
        assert_eq!(error.kind(), ErrorKind::NotFound, "{error:?}");
        // The maps of the namespace this process is in were written long
        // ago, and a map is written once: root itself is refused.
        let error = linux::write_uid_map(me, &map).unwrap_err();
        assert_eq!(error.kind(), ErrorKind::PermissionDenied, "{error:?}");
        let error = linux::write_gid_map(me, &map).unwrap_err();
        assert_eq!(error.kind(), ErrorKind::PermissionDenied, "{error:?}");
    }
}

/// The host name cannot be set by who may not: either the process has no
/// privilege, or (root in a container) no capability for it. A process
/// that has it is not tried: this would rename the machine.
#[test]
fn set_host_name_refused() {
    let before = host_name();
    if status_field("CapEff", 0).trim_start_matches('0').is_empty() {
        let error = linux::set_host_name(b"oscall-test").unwrap_err();
        assert_eq!(error.kind(), ErrorKind::PermissionDenied, "{error:?}");
    } else {
        note!("skipped: the process may have the capability to rename the machine");
    }
    assert_eq!(host_name(), before);
}

/// The child half of the tests that run this binary again: does what the
/// `OSCALL_TEST_HELPER` variable says, and nothing in an ordinary run.
#[test]
fn helper_child_process() {
    let Some(mode) = std::env::var_os("OSCALL_TEST_HELPER") else {
        return;
    };
    let mode = mode.into_string().unwrap();
    if let Some(file) = mode.strip_prefix("report:") {
        // What the process is, to itself.
        let (uid, gid) = effective_ids();
        let report = format!(
            "pid={}\nppid={}\nuid={uid}\ngid={gid}\nnnp={}\nuser={}\npidns={}\nuts={}\ntime={}\ncaps={}\nuidmap={}\ngidmap={}\ncgroup={}\n",
            process::id(),
            process::parent_id(),
            linux::no_new_privileges().unwrap(),
            namespace("user").unwrap_or_default(),
            namespace("pid").unwrap_or_default(),
            namespace("uts").unwrap_or_default(),
            namespace("time").unwrap_or_default(),
            status_field("CapEff", 0),
            id_map("uid_map"),
            id_map("gid_map"),
            std::fs::read_to_string("/proc/self/cgroup")
                .unwrap_or_default()
                .trim(),
        );
        std::fs::write(file, report).unwrap();
        process::exit(0);
    } else if mode == "uts" {
        helper_uts();
        process::exit(0);
    } else if mode == "prctl" {
        helper_prctl();
        process::exit(0);
    } else if mode == "threads" {
        // This process has a main thread and this one: the kernel does not
        // give one thread of several a user namespace of its own. (A
        // container's filter refuses before the kernel is asked.)
        let error = linux::unshare(Namespaces::USER).unwrap_err();
        assert!(
            matches!(error.raw_os_error(), EINVAL | EPERM),
            "unshare: {error:?}"
        );
        let me = std::fs::File::open("/proc/self/ns/user").unwrap();
        let error = linux::setns(&common::handle_of(&me), Namespaces::USER).unwrap_err();
        assert!(
            matches!(error.raw_os_error(), EINVAL | EPERM),
            "setns: {error:?}"
        );
        // Nor may a process without privilege have the others.
        if status_field("CapEff", 0).trim_start_matches('0').is_empty() {
            for namespaces in [Namespaces::UTS, Namespaces::NETWORK | Namespaces::IPC] {
                let error = linux::unshare(namespaces).unwrap_err();
                assert_eq!(error.kind(), ErrorKind::PermissionDenied, "{error:?}");
            }
        }
        // A file that is no namespace, a kind that is not the handle's.
        let file = std::fs::File::open("/proc/self/status").unwrap();
        let error = linux::setns(&common::handle_of(&file), Namespaces::empty()).unwrap_err();
        assert!(
            matches!(error.raw_os_error(), EINVAL | EPERM),
            "setns: {error:?}"
        );
        process::exit(0);
    }
    panic!("unknown helper mode {mode}");
}

/// Run as root of a new user namespace, in a new UTS namespace: host names
/// that are this thread's own, and moving between namespaces.
fn helper_uts() {
    // The namespace of this thread, where `/proc/self` is the first's.
    let thread_uts = || std::fs::read_link("/proc/thread-self/ns/uts").unwrap();
    let started = thread_uts();
    if let Err(error) = linux::set_host_name(b"oscall-one") {
        // Root of its namespace, with every capability on paper (the test
        // of the namespace checks that), and denied their use: what
        // Ubuntu's AppArmor restriction of user namespaces does.
        assert_eq!(error.kind(), ErrorKind::PermissionDenied, "{error:?}");
        note!(
            "skipped (uts): no use of capabilities in the user namespace ({})",
            common::confinement()
        );
        return;
    }
    assert_eq!(host_name(), "oscall-one");
    // Too long for the system.
    let error = linux::set_host_name(&[b'x'; 65]).unwrap_err();
    assert_eq!(error.kind(), ErrorKind::InvalidInput, "{error:?}");

    // A handle of the namespace, then another namespace for this thread.
    let first = std::fs::File::open("/proc/thread-self/ns/uts").unwrap();
    let (go, wait) = std::sync::mpsc::channel::<()>();
    let elsewhere = std::thread::spawn(move || {
        let _ = wait.recv();
        host_name()
    });
    linux::unshare(Namespaces::UTS).unwrap();
    assert_ne!(thread_uts(), started);
    // It starts as a copy.
    assert_eq!(host_name(), "oscall-one");
    linux::set_host_name(b"oscall-two").unwrap();
    assert_eq!(host_name(), "oscall-two");
    // A thread that existed is where it was; one created now is here.
    drop(go);
    assert_eq!(elsewhere.join().unwrap(), "oscall-one");
    let here = std::thread::spawn(host_name).join().unwrap();
    assert_eq!(here, "oscall-two");

    // Back, by the handle. It must be of the kind asked for.
    let handle = common::handle_of(&first);
    let error = linux::setns(&handle, Namespaces::NETWORK).unwrap_err();
    assert_eq!(error.kind(), ErrorKind::InvalidInput, "{error:?}");
    assert_eq!(host_name(), "oscall-two");
    linux::setns(&handle, Namespaces::UTS).unwrap();
    assert_eq!(host_name(), "oscall-one");
    // Any kind.
    linux::unshare(Namespaces::UTS | Namespaces::IPC).unwrap();
    linux::set_host_name(b"oscall-three").unwrap();
    linux::setns(&handle, Namespaces::empty()).unwrap();
    assert_eq!(host_name(), "oscall-one");

    // By a pidfd: the namespaces of a process, this one's main thread.
    linux::unshare(Namespaces::UTS).unwrap();
    linux::set_host_name(b"oscall-four").unwrap();
    let me = linux::pidfd_open(process::id()).unwrap();
    // A pidfd is not a namespace: it needs the kinds.
    let error = linux::setns(&me, Namespaces::empty()).unwrap_err();
    assert_eq!(error.kind(), ErrorKind::InvalidInput, "{error:?}");
    linux::setns(&me, Namespaces::UTS).unwrap();
    assert_eq!(host_name(), "oscall-one");

    // Back where it started.
    assert_eq!(thread_uts(), started);
}

/// The attributes of `prctl`, in a process of their own: they do not come
/// back.
fn helper_prctl() {
    assert!(!linux::is_child_subreaper().unwrap());
    linux::set_child_subreaper(true).unwrap();
    assert!(linux::is_child_subreaper().unwrap());
    linux::set_child_subreaper(false).unwrap();
    assert!(!linux::is_child_subreaper().unwrap());

    assert!(linux::is_dumpable().unwrap());
    linux::set_dumpable(false).unwrap();
    assert!(!linux::is_dumpable().unwrap());
    linux::set_dumpable(true).unwrap();
    assert!(linux::is_dumpable().unwrap());

    // Of the thread, and of those it creates afterwards.
    if linux::no_new_privileges().unwrap() {
        note!("skipped: whoever started the tests may gain no privileges already");
        return;
    }
    let before = std::thread::spawn(|| {
        std::thread::park();
        linux::no_new_privileges().unwrap()
    });
    linux::set_no_new_privileges().unwrap();
    assert!(linux::no_new_privileges().unwrap());
    // Again is no error.
    linux::set_no_new_privileges().unwrap();
    let after = std::thread::spawn(|| linux::no_new_privileges().unwrap());
    assert!(after.join().unwrap());
    before.thread().unpark();
    assert!(!before.join().unwrap());
}

#[cfg(feature = "alloc")]
mod children {
    use std::collections::HashMap;
    use std::path::Path;
    use std::time::{Duration, Instant};

    use oscall::event::{self, Event, Interest, Mode, Poller};
    use oscall::process::linux::{self, CommandExt as _, IdMap, Namespaces};
    use oscall::process::unix::{ChildExt as _, ExitStatusExt as _, SIGKILL, SIGTERM};
    use oscall::process::{self, Child, Command, ExitStatus, Stdio};
    use oscall::{AsHandle, BorrowedHandle, Error, ErrorKind, OwnedHandle, io};

    use super::common::{handle_of, tmp_dir};
    use super::{ECHILD, ENOSYS, effective_ids, namespace, refusal};

    const ENOEXEC: i32 = 8;

    /// Waits for the child, for a limited time.
    fn wait(child: &mut Child) -> ExitStatus {
        let start = Instant::now();
        loop {
            if let Some(status) = child.try_wait().unwrap() {
                return status;
            }
            if start.elapsed() > Duration::from_secs(60) {
                child.kill().unwrap();
                panic!("the child did not exit");
            }
            std::thread::sleep(Duration::from_millis(2));
        }
    }

    /// A shell that waits for a line on its standard input, which is the
    /// other end of the handle returned.
    fn blocked(configure: impl FnOnce(Command<'_>) -> Command<'_>) -> (Child, OwnedHandle) {
        let (input, feed) = io::pipe().unwrap();
        let command = Command::new("/bin/sh")
            .args(&["-c", "read line"])
            .stdin(Stdio::Handle(input.as_handle()))
            .stdout(Stdio::Null)
            .stderr(Stdio::Null);
        (configure(command).spawn().unwrap(), feed)
    }

    /// What to add to the command of a helper.
    #[derive(Default)]
    struct Setup<'a> {
        namespaces: Namespaces,
        uid_map: Option<&'a [IdMap]>,
        gid_map: Option<&'a [IdMap]>,
        deny_setgroups: bool,
        cgroup: Option<BorrowedHandle<'a>>,
        no_new_privileges: bool,
    }

    impl<'a> Setup<'a> {
        /// The caller as root of a new user namespace, and `namespaces`.
        fn root(namespaces: Namespaces, ids: &'a ([IdMap; 1], [IdMap; 1])) -> Self {
            Self {
                namespaces: Namespaces::USER | namespaces,
                uid_map: Some(&ids.0),
                gid_map: Some(&ids.1),
                deny_setgroups: true,
                ..Self::default()
            }
        }

        fn apply(&self, mut command: Command<'a>) -> Command<'a> {
            command = command.namespaces(self.namespaces);
            if let Some(map) = self.uid_map {
                command = command.uid_map(map);
            }
            if let Some(map) = self.gid_map {
                command = command.gid_map(map);
            }
            if self.deny_setgroups {
                command = command.deny_setgroups();
            }
            if let Some(cgroup) = self.cgroup {
                command = command.cgroup(cgroup);
            }
            if self.no_new_privileges {
                command = command.no_new_privileges();
            }
            command
        }
    }

    /// The maps that make the caller root of a namespace.
    fn root_maps() -> ([IdMap; 1], [IdMap; 1]) {
        let (uid, gid) = effective_ids();
        let map = |outside| {
            [IdMap {
                inside: 0,
                outside,
                count: 1,
            }]
        };
        (map(uid), map(gid))
    }

    /// Runs this test binary as the helper `mode`. `None`, having said
    /// why, where the environment does not let it.
    fn helper(mode: &str, setup: &Setup<'_>) -> Option<ExitStatus> {
        let exe = std::env::current_exe().unwrap();
        let mut env: Vec<Vec<u8>> = std::env::vars_os()
            .filter(|(name, _)| name != "OSCALL_TEST_HELPER")
            .map(|(name, value)| [name.as_encoded_bytes(), b"=", value.as_encoded_bytes()].concat())
            .collect();
        env.push(format!("OSCALL_TEST_HELPER={mode}").into_bytes());
        let args = ["--exact", "--nocapture", "helper_child_process"];
        let command = Command::new(exe.as_os_str().as_encoded_bytes())
            .args(&args)
            .env(&env)
            .stdin(Stdio::Null)
            .stdout(Stdio::Null);
        match setup.apply(command).spawn() {
            Ok(mut child) => Some(wait(&mut child)),
            // The binary is for another architecture, and runs here under
            // an emulator the kernel knows nothing about.
            Err(error) if error.raw_os_error() == ENOEXEC => {
                note!("skipped: the system cannot execute {}", exe.display());
                None
            }
            Err(error) => match refusal(&error) {
                Some(reason) => {
                    note!("skipped ({mode}): {reason}: {error}");
                    None
                }
                None => panic!("cannot run the helper {mode}: {error:?}"),
            },
        }
    }

    /// Runs the helper that says what it is, and returns what it said.
    fn report(name: &str, setup: &Setup<'_>) -> Option<HashMap<String, String>> {
        let dir = tmp_dir(name);
        let file = std::path::absolute(dir.join("report")).unwrap();
        let status = helper(&format!("report:{}", file.display()), setup)?;
        assert!(status.success(), "{status}");
        let text = std::fs::read_to_string(file).unwrap();
        Some(
            text.lines()
                .map(|line| {
                    let (name, value) = line.split_once('=').unwrap();
                    (name.to_owned(), value.to_owned())
                })
                .collect(),
        )
    }

    /// A pidfd of a child: signals, waiting, and the poller.
    #[test]
    fn pidfd_of_a_child() {
        let (mut child, feed) = blocked(|command| command);
        let pidfd = match linux::pidfd_open(child.id()) {
            Ok(pidfd) => pidfd,
            Err(error) if error.raw_os_error() == ENOSYS => {
                note!("skipped: the emulator has no pidfd_open");
                drop(feed);
                wait(&mut child);
                return;
            }
            Err(error) => panic!("pidfd_open: {error}"),
        };
        // Close-on-exec, like every handle.
        assert!(!io::is_inheritable(&pidfd).unwrap());

        // Readable when the process has exited, and not before.
        let poller = Poller::new().unwrap();
        event::unix::register(&poller, &pidfd, 7, Interest::READABLE, Mode::LEVEL).unwrap();
        let mut events = [Event::EMPTY; 4];
        let short = Some(Duration::from_millis(50));
        assert_eq!(poller.wait(&mut events, short).unwrap(), 0);
        assert_eq!(linux::pidfd_try_wait(&pidfd).unwrap(), None);
        linux::pidfd_send_signal(&pidfd, 0).unwrap();

        linux::pidfd_send_signal(&pidfd, SIGTERM).unwrap();
        let long = Some(Duration::from_secs(60));
        assert_eq!(poller.wait(&mut events, long).unwrap(), 1);
        assert_eq!(events[0].token(), 7);
        assert!(events[0].readiness().is_readable(), "{:?}", events[0]);

        // Exited and not collected: it takes signals still.
        linux::pidfd_send_signal(&pidfd, SIGKILL).unwrap();
        let status = linux::pidfd_wait(&pidfd).unwrap();
        assert_eq!(status.signal(), Some(SIGTERM), "{status}");
        assert_eq!(status.code(), None);

        // Collected: it is gone, for the pidfd and for the `Child`.
        let error = linux::pidfd_send_signal(&pidfd, 0).unwrap_err();
        assert_eq!(error.kind(), ErrorKind::NoSuchProcess, "{error:?}");
        let error = linux::pidfd_wait(&pidfd).unwrap_err();
        assert_eq!(error.raw_os_error(), ECHILD, "{error:?}");
        let error = child.try_wait().unwrap_err();
        assert_eq!(error.raw_os_error(), ECHILD, "{error:?}");
        // Level-triggered: readable for good.
        assert_eq!(poller.wait(&mut events, short).unwrap(), 1);
        event::unix::deregister(&poller, &pidfd).unwrap();

        // The pidfd a `Child` lends is one like another.
        let (child, feed) = blocked(|command| command);
        assert_eq!(linux::pidfd_try_wait(&child).unwrap(), None);
        linux::pidfd_send_signal(&child, 0).unwrap();
        drop(feed);
        let status = linux::pidfd_wait(&child).unwrap();
        // `read` found the end of its input.
        assert!(!status.success() && status.signal().is_none(), "{status}");
        let error = child.send_signal(0).unwrap_err();
        assert_eq!(error.kind(), ErrorKind::NoSuchProcess, "{error:?}");
    }

    /// What `spawn` refuses before it creates anything.
    #[test]
    fn spawn_checks() {
        let ids = root_maps();
        let empty: &[IdMap] = &[];
        let long: Vec<IdMap> = (0..400)
            .map(|i| IdMap {
                inside: 4_000_000_000 + i,
                outside: 4_000_000_000 + i,
                count: 1_000_000_000,
            })
            .collect();
        let cases = [
            // Maps of no namespace.
            Setup {
                uid_map: Some(&ids.0),
                ..Setup::default()
            },
            Setup {
                namespaces: Namespaces::PID | Namespaces::UTS,
                gid_map: Some(&ids.1),
                ..Setup::default()
            },
            Setup {
                deny_setgroups: true,
                ..Setup::default()
            },
            // Maps that cannot be written.
            Setup {
                namespaces: Namespaces::USER,
                uid_map: Some(empty),
                ..Setup::default()
            },
            Setup {
                namespaces: Namespaces::USER,
                gid_map: Some(&long),
                ..Setup::default()
            },
        ];
        for setup in cases {
            let error = setup.apply(Command::new("/bin/sh")).spawn().unwrap_err();
            assert_eq!(error.kind(), ErrorKind::InvalidInput, "{error:?}");
        }
    }

    /// A child that is root, and process 1, of namespaces of its own.
    #[test]
    fn user_and_pid_namespaces() {
        let ids = root_maps();
        let setup = Setup::root(Namespaces::PID, &ids);
        let Some(inside) = report("process_linux_user_pid", &setup) else {
            return;
        };
        assert_eq!(inside["pid"], "1");
        assert_eq!(inside["ppid"], "0");
        // The maps were there before the program started.
        assert_eq!(inside["uid"], "0");
        assert_eq!(inside["gid"], "0");
        assert_ne!(inside["user"], namespace("user").unwrap());
        assert_ne!(inside["pidns"], namespace("pid").unwrap());
        assert_eq!(inside["uts"], namespace("uts").unwrap());
        // Every capability, in its namespace.
        assert_ne!(inside["caps"].trim_start_matches('0'), "");
        assert_eq!(inside["uidmap"], format!("0 {} 1", ids.0[0].outside));
        assert_eq!(inside["gidmap"], format!("0 {} 1", ids.1[0].outside));
    }

    /// Maps of several ranges, which only who has the capabilities outside
    /// may write: the parent, where the child itself never could.
    #[test]
    fn maps_of_several_ranges() {
        let (uid, _) = effective_ids();
        if uid != 0 {
            note!("skipped: only root may map identifiers that are not its own");
            return;
        }
        let range = |inside, outside, count| IdMap {
            inside,
            outside,
            count,
        };
        let users = [range(0, 0, 1), range(1, 100_000, 1000)];
        let groups = [
            range(0, 0, 1),
            range(5, 200_000, 10),
            range(100, 300_000, 1),
        ];
        // With the capability, `setgroups` may stay allowed.
        let setup = Setup {
            namespaces: Namespaces::USER,
            uid_map: Some(&users),
            gid_map: Some(&groups),
            ..Setup::default()
        };
        let Some(inside) = report("process_linux_ranges", &setup) else {
            return;
        };
        assert_eq!(inside["uid"], "0");
        assert_eq!(inside["gid"], "0");
        assert_eq!(inside["uidmap"], "0 0 1;1 100000 1000");
        assert_eq!(inside["gidmap"], "0 0 1;5 200000 10;100 300000 1");
    }

    /// Without maps the child is nobody, and has no capability once its
    /// program runs.
    #[test]
    fn user_namespace_without_maps() {
        let setup = Setup {
            namespaces: Namespaces::USER,
            ..Setup::default()
        };
        let Some(inside) = report("process_linux_user_unmapped", &setup) else {
            return;
        };
        let overflow = |name: &str| {
            let text = std::fs::read_to_string(format!("/proc/sys/kernel/{name}")).unwrap();
            text.trim().to_owned()
        };
        assert_eq!(inside["uid"], overflow("overflowuid"));
        assert_eq!(inside["gid"], overflow("overflowgid"));
        assert_ne!(inside["user"], namespace("user").unwrap());
        assert_eq!(inside["pidns"], namespace("pid").unwrap());
        assert_eq!(inside["caps"].trim_start_matches('0'), "");
        assert_ne!(inside["pid"], "1");
        assert_eq!(inside["ppid"], process::id().to_string());
    }

    /// A map the caller may not write: `spawn` fails with the reason, and
    /// leaves no child.
    #[test]
    fn map_refused() {
        let (uid, _) = effective_ids();
        // Someone else's identifier; root may map any, and is not tried.
        if uid == 0 {
            note!("skipped: root may write any map");
            return;
        }
        let other = [IdMap {
            inside: 0,
            outside: uid + 1,
            count: 1,
        }];
        let setup = Setup {
            namespaces: Namespaces::USER,
            uid_map: Some(&other),
            ..Setup::default()
        };
        let error = setup
            .apply(Command::new("/bin/sh").args(&["-c", "exit 0"]))
            .spawn()
            .unwrap_err();
        // The kernel's answer to the map, which is also what an
        // environment that allows no namespace says.
        if error.kind() != ErrorKind::PermissionDenied {
            match refusal(&error) {
                Some(reason) => note!("skipped: {reason}: {error}"),
                None => panic!("spawn: {error:?}"),
            }
        }
    }

    /// Process 1 of a namespace only takes the signals it handles, and
    /// `SIGKILL` from outside.
    #[test]
    fn pid_namespace_init() {
        let ids = root_maps();
        let setup = Setup::root(Namespaces::PID, &ids);
        let (input, feed) = io::pipe().unwrap();
        let command = Command::new("/bin/sh")
            .args(&["-c", "read line"])
            .stdin(Stdio::Handle(input.as_handle()))
            .stdout(Stdio::Null)
            .stderr(Stdio::Null);
        let mut child = match setup.apply(command).spawn() {
            Ok(child) => child,
            Err(error) => match refusal(&error) {
                Some(reason) => {
                    note!("skipped: {reason}: {error}");
                    return;
                }
                None => panic!("spawn: {error:?}"),
            },
        };
        // The shell has no handler for it: not delivered.
        child.send_signal(SIGTERM).unwrap();
        std::thread::sleep(Duration::from_millis(100));
        assert_eq!(child.try_wait().unwrap(), None);
        child.kill().unwrap();
        let status = wait(&mut child);
        assert_eq!(status.signal(), Some(SIGKILL), "{status}");
        drop(feed);
    }

    /// Host names, `unshare` and `setns`, by a child with the capability
    /// for them.
    #[test]
    fn uts_namespace() {
        let before = super::host_name();
        let ids = root_maps();
        let setup = Setup::root(Namespaces::UTS, &ids);
        if let Some(status) = helper("uts", &setup) {
            assert!(status.success(), "{status}");
        }
        assert_eq!(super::host_name(), before);
    }

    /// What a process with several threads, and without privilege, cannot
    /// do.
    #[test]
    fn unshare_refused() {
        if let Some(status) = helper("threads", &Setup::default()) {
            assert!(status.success(), "{status}");
        }
    }

    /// A time namespace, which takes `clone3`.
    #[test]
    fn time_namespace() {
        let Some(outside) = namespace("time") else {
            note!("skipped: the kernel has no time namespaces");
            return;
        };
        let ids = root_maps();
        // With maps the child waits for its parent; without, it does not.
        let waiting = Setup::root(Namespaces::TIME, &ids);
        let direct = Setup {
            namespaces: Namespaces::USER | Namespaces::TIME,
            ..Setup::default()
        };
        for (name, setup) in [
            ("process_linux_time_maps", waiting),
            ("process_linux_time", direct),
        ] {
            let mapped = setup.uid_map.is_some();
            let Some(inside) = report(name, &setup) else {
                return;
            };
            assert_ne!(inside["time"], outside);
            assert_ne!(inside["user"], namespace("user").unwrap());
            assert_eq!(inside["uid"] == "0", mapped);
        }
    }

    #[test]
    fn no_new_privileges() {
        let setup = Setup {
            no_new_privileges: true,
            ..Setup::default()
        };
        let Some(inside) = report("process_linux_nnp", &setup) else {
            return;
        };
        assert_eq!(inside["nnp"], "true");
        // Otherwise the child is as the caller, which was not touched.
        let here = linux::no_new_privileges().unwrap();
        if here {
            note!("whoever started the tests may gain no privileges already");
        }
        let inside = report("process_linux_nnp_default", &Setup::default()).unwrap();
        assert_eq!(inside["nnp"], here.to_string());
    }

    #[test]
    fn prctl() {
        if let Some(status) = helper("prctl", &Setup::default()) {
            assert!(status.success(), "{status}");
        }
    }

    /// The directory of the cgroup this process is in, where the cgroup
    /// file system (version 2) is mounted the usual way.
    fn own_cgroup() -> Option<std::path::PathBuf> {
        let text = std::fs::read_to_string("/proc/self/cgroup").ok()?;
        let path = text.lines().find_map(|line| line.strip_prefix("0::"))?;
        let dir = Path::new("/sys/fs/cgroup").join(path.trim_start_matches('/'));
        dir.join("cgroup.procs").exists().then_some(dir)
    }

    /// A cgroup made for the test, removed when dropped.
    struct Cgroup(std::path::PathBuf);

    impl Drop for Cgroup {
        fn drop(&mut self) {
            // It can only be removed once empty, which a process that has
            // just been collected leaves it a moment later.
            for _ in 0..500 {
                if std::fs::remove_dir(&self.0).is_ok() {
                    return;
                }
                std::thread::sleep(Duration::from_millis(10));
            }
            note!("could not remove {}", self.0.display());
        }
    }

    /// A child started in a cgroup.
    #[test]
    fn cgroup() {
        // Not a cgroup: refused, whichever way the child was to get there.
        let dir = tmp_dir("process_linux_cgroup");
        let not_cgroup = std::fs::File::open(&dir).unwrap();
        let error = Command::new("/bin/sh")
            .args(&["-c", "exit 0"])
            .cgroup(handle_of(&not_cgroup))
            .spawn()
            .unwrap_err();
        assert!(
            matches!(error.kind(), ErrorKind::BadHandle | ErrorKind::NotFound),
            "{error:?}"
        );

        let Some(parent) = own_cgroup() else {
            note!("skipped: no cgroup file system (version 2) at /sys/fs/cgroup");
            return;
        };
        let path = parent.join(format!("oscall-test-{}", process::id()));
        if let Err(error) = std::fs::create_dir(&path) {
            note!(
                "skipped: cannot create a cgroup in {}: {error}",
                parent.display()
            );
            return;
        }
        let cgroup = Cgroup(path);
        let directory = std::fs::File::open(&cgroup.0).unwrap();
        let handle = handle_of(&directory);
        let members = || std::fs::read_to_string(cgroup.0.join("cgroup.procs")).unwrap();
        assert_eq!(members(), "");

        let (mut child, feed) = match Command::new("/bin/sh")
            .args(&["-c", "read line"])
            .stdout(Stdio::Null)
            .cgroup(handle)
            .spawn_blocked()
        {
            Ok(spawned) => spawned,
            // Created, and yet not ours to fill: a hierarchy delegated in
            // part.
            Err(error) if error.kind() == ErrorKind::PermissionDenied => {
                note!("skipped: may not move a process to the new cgroup: {error}");
                return;
            }
            Err(error) => panic!("spawn: {error:?}"),
        };
        // There from the start, and alone.
        assert_eq!(members().trim(), child.id().to_string());
        drop(feed);
        wait(&mut child);

        // What the child says of itself, and what it starts is there too.
        let setup = Setup {
            cgroup: Some(handle),
            ..Setup::default()
        };
        if let Some(inside) = report("process_linux_cgroup_report", &setup) {
            let name = cgroup.0.file_name().unwrap().to_str().unwrap();
            assert!(inside["cgroup"].ends_with(name), "{}", inside["cgroup"]);
        }
        let (output, write) = io::pipe().unwrap();
        let mut child = Command::new("/bin/sh")
            .args(&["-c", "/bin/sh -c 'cat /proc/self/cgroup'"])
            .stdin(Stdio::Null)
            .stdout(Stdio::Handle(write.as_handle()))
            .cgroup(handle)
            .spawn()
            .unwrap();
        drop(write);
        let mut text = Vec::new();
        let mut buf = [0u8; 256];
        loop {
            match io::read(&output, &mut buf).unwrap() {
                0 => break,
                n => text.extend_from_slice(&buf[..n]),
            }
        }
        assert!(wait(&mut child).success());
        let text = String::from_utf8(text).unwrap();
        let name = cgroup.0.file_name().unwrap().to_str().unwrap();
        assert!(text.trim().ends_with(name), "{text}");
    }

    /// `spawn` with a pipe to the child's standard input.
    trait SpawnBlocked {
        fn spawn_blocked(self) -> Result<(Child, OwnedHandle), Error>;
    }

    impl SpawnBlocked for Command<'_> {
        fn spawn_blocked(self) -> Result<(Child, OwnedHandle), Error> {
            let (input, feed) = io::pipe()?;
            let child = self.stdin(Stdio::Handle(input.as_handle())).spawn()?;
            Ok((child, feed))
        }
    }
}