oscall 0.1.1

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

/// Says what the environment kept a test from doing: see `common::skip`.
macro_rules! skip {
    ($($arg:tt)*) => {
        crate::common::skip(&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 => {
            skip!("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();
    #[cfg(feature = "alloc")]
    if let Some(file) = mode.strip_prefix("nested:") {
        // What this process starts says what it is.
        children::helper_nested(file);
        process::exit(0);
    } else if mode == "no-clone3" {
        children::helper_no_clone3();
        process::exit(0);
    }
    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={}\nmonotonic={}\nboot={}\nuptime={}\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(),
            // The clocks a time namespace moves, as this process reads
            // them (through the vDSO where there is one), in nanoseconds,
            // and what the kernel says of the second one in a file.
            oscall::time::Clock::Monotonic.now().unwrap().as_nanos(),
            oscall::time::Clock::Boottime.now().unwrap().as_nanos(),
            std::fs::read_to_string("/proc/uptime")
                .unwrap_or_default()
                .split_whitespace()
                .next()
                .unwrap_or_default(),
        );
        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 == "block" {
        // Waits for a line, and says whether one came.
        let mut line = String::new();
        let read = std::io::stdin().read_line(&mut line).unwrap_or(0);
        process::exit(if read == 0 { 1 } else { 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:?}");
        skip!(
            "(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, ClockOffset, CommandExt as _, ConfineExt as _, IdMap, Namespaces, TimeOffsets,
    };
    use oscall::process::unix::{
        ChildExt as _, CommandExt as _, ExitStatusExt as _, SIGKILL, SIGTERM,
    };
    use oscall::process::{self, Child, Command, ExitStatus, Stdio};
    use oscall::time::Clock;
    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));
        }
    }

    /// This test binary, to run again as the helper of a mode.
    struct Program {
        exe: std::path::PathBuf,
        env: Vec<Vec<u8>>,
    }

    impl Program {
        fn new(mode: &str) -> Self {
            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());
            Self {
                exe: std::env::current_exe().unwrap(),
                env,
            }
        }

        /// The command that runs it, with nothing on its standard input
        /// and output.
        fn command(&self) -> Command<'_> {
            const ARGS: &[&str] = &["--exact", "--nocapture", "helper_child_process"];
            Command::new(self.exe.as_os_str().as_encoded_bytes())
                .args(ARGS)
                .env(&self.env)
                .stdin(Stdio::Null)
                .stdout(Stdio::Null)
        }
    }

    /// A program that waits for a line on its standard input, which is
    /// the other end of the handle returned, and has no handler for any
    /// signal: the helper `block`. It fails if its input ends first.
    ///
    /// Where the system cannot execute this binary (it is for another
    /// architecture, and runs under an emulator the kernel knows nothing
    /// about), a shell does the same.
    fn blocked() -> (Child, OwnedHandle) {
        match Program::new("block").command().spawn_blocked() {
            Ok(spawned) => spawned,
            Err(error) if error.raw_os_error() == ENOEXEC => Command::new("/bin/sh")
                .args(&["-c", "read line"])
                .stdout(Stdio::Null)
                .stderr(Stdio::Null)
                .spawn_blocked()
                .unwrap(),
            Err(error) => panic!("spawn: {error:?}"),
        }
    }

    /// 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,
        time_offsets: Option<TimeOffsets>,
        /// Sets the user and the group of the child, to those it has: a
        /// child that does is given a copy of the memory of its parent.
        identity: 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();
            }
            if let Some(offsets) = self.time_offsets {
                command = command.time_offsets(offsets);
            }
            if self.identity {
                command = command.uid(0).gid(0);
            }
            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 program = Program::new(mode);
        match setup.apply(program.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 => {
                skip!("the system cannot execute {}", program.exe.display());
                None
            }
            Err(error) => match refusal(&error) {
                Some(reason) => {
                    skip!("({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();
        let pidfd = match linux::pidfd_open(child.id()) {
            Ok(pidfd) => pidfd,
            Err(error) if error.raw_os_error() == ENOSYS => {
                skip!("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];
        // Under qemu-user a wait is now and then interrupted where the
        // kernel interrupts nothing, this process having no signal
        // handler (measured: 10 runs of 240 on two processors, with qemu
        // 10.0.13; presumably by the signal for a child of another test,
        // which the emulator handles on behalf of the program). There the
        // wait is made again; on a kernel, an interruption is a failure.
        let wait = |events: &mut [Event], timeout| loop {
            match poller.wait(events, timeout) {
                Err(error)
                    if error.kind() == ErrorKind::Interrupted && super::common::emulated() => {}
                result => break result.unwrap(),
            }
        };
        let short = Some(Duration::from_millis(50));
        assert_eq!(wait(&mut events, short), 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!(wait(&mut events, long), 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!(wait(&mut events, short), 1);
        event::unix::deregister(&poller, &pidfd).unwrap();

        // The pidfd a `Child` lends is one like another.
        let (child, feed) = blocked();
        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();
        // It found the end of its input.
        assert_eq!(status.code(), Some(1), "{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()
            },
            // Offsets of no namespace, and offsets that are none.
            Setup {
                namespaces: Namespaces::USER | Namespaces::PID,
                time_offsets: Some(TimeOffsets {
                    monotonic: Some(ClockOffset::new(1, 0)),
                    boot_time: None,
                }),
                ..Setup::default()
            },
            Setup {
                namespaces: Namespaces::USER | Namespaces::TIME,
                time_offsets: Some(TimeOffsets::default()),
                ..Setup::default()
            },
            Setup {
                namespaces: Namespaces::USER | Namespaces::TIME,
                time_offsets: Some(TimeOffsets {
                    monotonic: None,
                    boot_time: Some(ClockOffset::new(0, 1_000_000_000)),
                }),
                ..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 {
            skip!("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) => skip!("{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 program = Program::new("block");
        let (mut child, feed) = match setup.apply(program.command()).spawn_blocked() {
            Ok(spawned) => spawned,
            Err(error) => match refusal(&error) {
                Some(reason) => {
                    skip!("{reason}: {error}");
                    return;
                }
                None => panic!("spawn: {error:?}"),
            },
        };
        // The program 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 {
            super::common::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 clock_offsets() {
        let second = Duration::from_secs(1);
        assert_eq!(ClockOffset::ahead(Duration::ZERO), ClockOffset::new(0, 0));
        assert_eq!(ClockOffset::behind(Duration::ZERO), ClockOffset::new(0, 0));
        assert_eq!(
            ClockOffset::ahead(second * 5 / 2),
            ClockOffset::new(2, 500_000_000)
        );
        assert_eq!(ClockOffset::behind(second * 3), ClockOffset::new(-3, 0));
        // Two and a quarter back is three back and three quarters forth.
        assert_eq!(
            ClockOffset::behind(second * 9 / 4),
            ClockOffset::new(-3, 750_000_000)
        );
        assert_eq!(
            ClockOffset::behind(second / 1_000_000_000),
            ClockOffset::new(-1, 999_999_999)
        );
        assert_eq!(
            ClockOffset::ahead(Duration::MAX),
            ClockOffset::new(i64::MAX, 999_999_999)
        );
        assert_eq!(ClockOffset::behind(Duration::MAX).seconds, i64::MIN);
        assert_eq!(TimeOffsets::default().monotonic, None);
        // Who has no time namespace of their own to fill is refused: the
        // one this process is in has processes.
        if namespace("time").is_some() {
            let offsets = TimeOffsets {
                monotonic: Some(ClockOffset::new(1, 0)),
                boot_time: None,
            };
            let error = linux::write_time_offsets(process::id(), &offsets).unwrap_err();
            assert_eq!(error.kind(), ErrorKind::PermissionDenied, "{error:?}");
            let error = linux::set_time_offsets(&offsets).unwrap_err();
            assert_eq!(error.kind(), ErrorKind::PermissionDenied, "{error:?}");
        }
        let error = linux::write_time_offsets(process::id(), &TimeOffsets::default()).unwrap_err();
        assert_eq!(error.kind(), ErrorKind::InvalidInput, "{error:?}");
        let error = linux::write_time_offsets(0, &TimeOffsets::default()).unwrap_err();
        assert_eq!(error.kind(), ErrorKind::InvalidInput, "{error:?}");
    }

    /// The clocks of a child in a time namespace, moved before its
    /// program starts: the child reads them shifted.
    #[test]
    fn time_namespace_offsets() {
        const ERANGE: i32 = 34;
        if namespace("time").is_none() {
            super::common::no_time_namespaces();
            return;
        }
        let ids = root_maps();
        let ahead = (
            Duration::new(1_000_000, 250_000_000),
            Duration::new(2_000_000, 0),
        );
        let offsets = TimeOffsets {
            monotonic: Some(ClockOffset::ahead(ahead.0)),
            boot_time: Some(ClockOffset::ahead(ahead.1)),
        };
        // A child that shares the memory of its parent is created in the
        // namespace; one that changes its identity makes it itself.
        let shared = Setup {
            time_offsets: Some(offsets),
            ..Setup::root(Namespaces::TIME, &ids)
        };
        let copied = Setup {
            time_offsets: Some(offsets),
            identity: true,
            ..Setup::root(Namespaces::TIME, &ids)
        };
        let nanos = |report: &HashMap<String, String>, name: &str| {
            Duration::from_nanos(report[name].parse::<u64>().unwrap())
        };
        for (name, setup) in [
            ("process_linux_offsets", shared),
            ("process_linux_offsets_copy", copied),
        ] {
            let before = (
                Clock::Monotonic.now().unwrap(),
                Clock::Boottime.now().unwrap(),
            );
            let Some(inside) = report(name, &setup) else {
                // Nowhere at all, or not for a child that has to make
                // its namespace itself.
                if setup.identity {
                    continue;
                }
                return;
            };
            let after = (
                Clock::Monotonic.now().unwrap(),
                Clock::Boottime.now().unwrap(),
            );
            assert_ne!(inside["time"], namespace("time").unwrap());
            let monotonic = nanos(&inside, "monotonic");
            assert!(
                before.0 + ahead.0 <= monotonic && monotonic <= after.0 + ahead.0,
                "{name}: {monotonic:?} is not {:?} after {before:?}..{after:?}",
                ahead.0
            );
            let boot = nanos(&inside, "boot");
            assert!(
                before.1 + ahead.1 <= boot && boot <= after.1 + ahead.1,
                "{name}: {boot:?} is not {:?} after {before:?}..{after:?}",
                ahead.1
            );
            // The kernel's own account of the second clock, to a
            // hundredth of a second.
            let uptime = Duration::from_secs_f64(inside["uptime"].parse().unwrap());
            let slack = Duration::from_millis(20);
            assert!(
                before.1 + ahead.1 <= uptime + slack && uptime <= after.1 + ahead.1 + slack,
                "{name}: /proc/uptime says {uptime:?}"
            );
        }

        // One clock alone, and backwards, by less than it has counted.
        let behind = Clock::Monotonic.now().unwrap() / 2;
        let setup = Setup {
            time_offsets: Some(TimeOffsets {
                monotonic: Some(ClockOffset::behind(behind)),
                boot_time: None,
            }),
            ..Setup::root(Namespaces::TIME, &ids)
        };
        let before = (
            Clock::Monotonic.now().unwrap(),
            Clock::Boottime.now().unwrap(),
        );
        let inside = report("process_linux_offsets_behind", &setup).unwrap();
        let after = (
            Clock::Monotonic.now().unwrap(),
            Clock::Boottime.now().unwrap(),
        );
        let monotonic = nanos(&inside, "monotonic");
        assert!(
            before.0 - behind <= monotonic && monotonic <= after.0 - behind,
            "{monotonic:?} is not {behind:?} before {before:?}..{after:?}"
        );
        let boot = nanos(&inside, "boot");
        assert!(before.1 <= boot && boot <= after.1, "{boot:?}");

        // A clock cannot be made negative: the write is refused, and with
        // it the child.
        let setup = Setup {
            time_offsets: Some(TimeOffsets {
                monotonic: None,
                boot_time: Some(ClockOffset::behind(Duration::from_secs(1 << 40))),
            }),
            ..Setup::root(Namespaces::TIME, &ids)
        };
        let error = setup
            .apply(Program::new("block").command())
            .spawn()
            .unwrap_err();
        assert_eq!(error.raw_os_error(), ERANGE, "{error:?}");
    }

    #[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());
        }
    }

    /// Whether there is a `clone3` to create a child with: the kernel
    /// refuses arguments of no size, where an emulator or a system call
    /// filter says there is no such call.
    fn has_clone3() -> bool {
        // SAFETY: a size of 0 is refused before anything is read.
        let result = unsafe { oscall::raw::linux::syscall!(CLONE3, 0usize, 0usize) };
        result.unwrap_err().raw_os_error() != ENOSYS
    }

    /// A child started in a cgroup.
    #[test]
    fn cgroup() {
        // The runs that exist to cover it have the call, on every
        // architecture: this is where the child side of it executes.
        if super::common::privileged_required() {
            assert!(has_clone3(), "no clone3 in a run that must cover it");
        }
        cgroup_checks("process_linux_cgroup");
    }

    /// The same where there is no `clone3`, and the child moves itself:
    /// what the default system call filter of a container runtime
    /// answers, and qemu-user. Here a filter of the helper's own answers
    /// it, so that this way is taken wherever the first one is.
    #[test]
    fn cgroup_without_clone3() {
        if let Some(status) = helper("no-clone3", &Setup::default()) {
            assert!(status.success(), "{status}");
        }
    }

    /// What the helper of the test above does.
    pub(super) fn helper_no_clone3() {
        use oscall::process::linux::seccomp::{self, Action, FilterFlags, Instruction};

        // Written by hand, without the check of the architecture that
        // `seccomp::build` starts with: the shell the test runs may be of
        // another one (a 64-bit `/bin/sh` under a 32-bit test), and would
        // be ended by it. `clone3` has one number on every architecture.
        let clone3 = oscall::raw::linux::nr::CLONE3 as u32;
        let program = [
            Instruction::load(seccomp::DATA_NUMBER),
            Instruction::jump_if_equal(clone3, 0, 1),
            Instruction::ret(Action::Errno(ENOSYS as u16)),
            Instruction::ret(Action::Allow),
        ];
        let program = &program[..];
        linux::set_no_new_privileges().unwrap();
        if let Err(error) = seccomp::install(program, FilterFlags::empty()) {
            // qemu-user has no `seccomp`, and no `clone3` either.
            assert!(super::common::emulated(), "install: {error:?}");
            skip!("(no-clone3) qemu-user has no seccomp: {error}");
            return;
        }
        assert!(!has_clone3());
        // What only `clone3` can do is no longer done.
        let command = Command::new("/bin/sh").args(&["-c", "exit 0"]);
        let error = command
            .namespaces(Namespaces::USER | Namespaces::TIME)
            .spawn()
            .unwrap_err();
        assert_eq!(error.kind(), ErrorKind::Unsupported, "{error:?}");
        cgroup_checks("process_linux_cgroup_fallback");
    }

    /// `name` is that of a directory for the test.
    fn cgroup_checks(name: &str) {
        // Not a cgroup: refused, whichever way the child was to get there.
        let dir = tmp_dir(name);
        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 {
            skip!("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) {
            skip!("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 program = Program::new("block");
        let (mut child, feed) = match program.command().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 => {
                skip!("may not move a process to the new cgroup: {error}");
                return;
            }
            Err(error) if error.raw_os_error() == ENOEXEC => {
                skip!("the system cannot execute {}", program.exe.display());
                return;
            }
            Err(error) => panic!("spawn: {error:?}"),
        };
        // There from the start, and alone.
        assert_eq!(members().trim(), child.id().to_string());
        note!(
            "the child was put in its cgroup by {}",
            if has_clone3() {
                "clone3"
            } else {
                "itself: there is no clone3"
            }
        );
        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()
        };
        let own = cgroup.0.file_name().unwrap().to_str().unwrap();
        if let Some(inside) = report(&format!("{name}_report"), &setup) {
            assert!(inside["cgroup"].ends_with(own), "{}", inside["cgroup"]);
        }
        let dir = tmp_dir(&format!("{name}_nested"));
        let file = std::path::absolute(dir.join("report")).unwrap();
        let status = helper(&format!("nested:{}", file.display()), &setup).unwrap();
        assert!(status.success(), "{status}");
        let text = std::fs::read_to_string(file).unwrap();
        let line = text.lines().find_map(|line| line.strip_prefix("cgroup="));
        assert!(line.unwrap().ends_with(own), "{text}");
    }

    /// What the helper `nested` does: has a helper of its own write its
    /// report to `file`.
    pub(super) fn helper_nested(file: &str) {
        let status = helper(&format!("report:{file}"), &Setup::default()).unwrap();
        assert!(status.success(), "{status}");
    }

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