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
//! Tests of what `oscall::process::linux` has for tracing and for
//! reaching into another process: `ptrace`, the wait that reports stops,
//! `process_vm_readv` and `process_vm_writev`, `pidfd_getfd`, and the
//! `SECCOMP_RET_TRACE` of a filter.
//!
//! This test has no harness (`harness = false` in `Cargo.toml`): tracing
//! is about a thread. The tracer of a child is the thread that created
//! it, and what it traces from the start of a program is the first
//! thread of it, where the harness runs each test, and so the helper of
//! one, on a thread of its own. `main` runs the tests one after the
//! other on the first thread, and the helpers are this binary run again
//! with `OSCALL_TEST_HELPER` set, which then does nothing else.
//!
//! qemu-user has no `ptrace` and lacks some of the other calls: the tests
//! then say what they skipped. What the environment refuses for want of
//! privilege is said too (`skipped: ...`), and is a failure in a run that
//! must skip nothing (`OSCALL_REQUIRE_PRIVILEGED`).

#[cfg(any(target_os = "linux", target_os = "fullrust"))]
mod common;

#[cfg(any(target_os = "linux", target_os = "fullrust"))]
mod linux {
    use oscall::process::linux::ptrace::{Options, Registers, Stop};
    use oscall::process::linux::seccomp::Action;
    use oscall::process::linux::{WaitEvent, WaitFlags};

    #[cfg(feature = "alloc")]
    use super::common;

    const SIGTRAP: i32 = 5;
    const SIGSTOP: i32 = 19;

    fn values() {
        assert_eq!(Stop::from_status(SIGTRAP), Stop::Signal(SIGTRAP));
        assert_eq!(Stop::from_status(11), Stop::Signal(11));
        assert_eq!(Stop::from_status(SIGTRAP | 0x80), Stop::Syscall);
        let event = |number: i32| Stop::from_status(number << 8 | SIGTRAP);
        assert_eq!(event(1), Stop::Fork);
        assert_eq!(event(2), Stop::Vfork);
        assert_eq!(event(3), Stop::Clone);
        assert_eq!(event(4), Stop::Exec);
        assert_eq!(event(5), Stop::VforkDone);
        assert_eq!(event(6), Stop::Exit);
        assert_eq!(event(7), Stop::Seccomp);
        assert_eq!(event(128), Stop::Interrupted);
        assert_eq!(
            Stop::from_status(128 << 8 | SIGSTOP),
            Stop::GroupStop(SIGSTOP)
        );
        assert_eq!(event(9), Stop::Unknown(9 << 8 | SIGTRAP));
        assert_eq!(Stop::from_status(4 << 8 | 11), Stop::Unknown(4 << 8 | 11));

        let options = [
            Options::TRACE_SYSGOOD,
            Options::TRACE_FORK,
            Options::TRACE_VFORK,
            Options::TRACE_CLONE,
            Options::TRACE_EXEC,
            Options::TRACE_VFORK_DONE,
            Options::TRACE_EXIT,
            Options::TRACE_SECCOMP,
            Options::EXIT_KILL,
            Options::SUSPEND_SECCOMP,
        ];
        let mut all = Options::empty();
        for option in options {
            assert!(!option.is_empty() && !all.intersects(option));
            all |= option;
        }
        assert_eq!(
            format!("{:?}", Options::TRACE_EXEC | Options::EXIT_KILL),
            "Options(TRACE_EXEC | EXIT_KILL)"
        );
        let flags = [
            WaitFlags::EXITED,
            WaitFlags::STOPPED,
            WaitFlags::CONTINUED,
            WaitFlags::NO_HANG,
            WaitFlags::NO_WAIT,
            WaitFlags::ALL_CHILDREN,
            WaitFlags::NO_THREAD,
        ];
        let mut all = WaitFlags::empty();
        for flag in flags {
            assert!(!flag.is_empty() && !all.intersects(flag));
            all |= flag;
        }

        // The value a filter returns to stop a call for a tracer.
        assert_eq!(Action::Trace(0).value(), 0x7ff0_0000);
        assert_eq!(Action::Trace(0xabcd).value(), 0x7ff0_abcd);

        // The registers are the kernel's structure, word for word.
        let words = size_of::<Registers>() / size_of::<usize>();
        let expected = match std::env::consts::ARCH {
            "x86_64" => 27,
            "x86" => 17,
            "aarch64" => 34,
            "arm" => 18,
            _ => 32,
        };
        assert_eq!(words, expected);
        let mut registers = Registers::default();
        assert_eq!(registers.instruction_pointer(), 0);
        registers.set_instruction_pointer(0x1234);
        assert_eq!(registers.instruction_pointer(), 0x1234);
        assert_eq!(registers.stack_pointer(), 0);

        #[cfg(feature = "alloc")]
        {
            let exited = WaitEvent::Exited(3).exit_status().unwrap();
            assert_eq!(exited.code(), Some(3));
            let killed = WaitEvent::Killed {
                signal: 9,
                core_dumped: false,
            };
            assert!(!killed.exit_status().unwrap().success());
            assert!(WaitEvent::Stopped(SIGSTOP).exit_status().is_none());
            assert!(WaitEvent::Continued.exit_status().is_none());
        }
        assert_ne!(WaitEvent::Trapped(Stop::Syscall), WaitEvent::Continued);
    }

    /// 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.
    fn helper(mode: &str) {
        #[cfg(feature = "alloc")]
        children::helper_main(mode);
        panic!("unknown helper mode {mode}");
    }

    /// The tests, by name.
    const TESTS: &[(&str, fn())] = &[
        ("values", values),
        #[cfg(feature = "alloc")]
        ("stopped_and_continued", children::stopped_and_continued),
        #[cfg(feature = "alloc")]
        ("trace_child", children::trace_child),
        #[cfg(feature = "alloc")]
        ("seize_and_attach", children::seize_and_attach),
        #[cfg(feature = "alloc")]
        ("trace_family", children::trace_family),
        #[cfg(feature = "alloc")]
        ("memory_and_handles", children::memory_and_handles),
        #[cfg(feature = "alloc")]
        ("filter_and_tracer", children::filter_and_tracer),
    ];

    /// Runs the helper the environment asks for, or the tests the arguments
    /// select: what `cargo test` passes on is options, which are ignored, and
    /// parts of the names of the tests to run, if not all.
    pub fn main() {
        if let Some(mode) = std::env::var_os("OSCALL_TEST_HELPER") {
            helper(&mode.into_string().unwrap());
            return;
        }
        if std::env::args().any(|arg| arg == "--list") {
            return;
        }
        let filters: Vec<String> = std::env::args()
            .skip(1)
            .filter(|arg| !arg.starts_with('-'))
            .collect();
        let mut failed = 0;
        for (name, test) in TESTS {
            if !filters.is_empty() && !filters.iter().any(|filter| name.contains(filter.as_str())) {
                continue;
            }
            let result = std::panic::catch_unwind(test);
            println!(
                "test {name} ... {}",
                if result.is_ok() { "ok" } else { "FAILED" }
            );
            failed += usize::from(result.is_err());
        }
        if failed != 0 {
            println!("{failed} failed");
            std::process::exit(1);
        }
    }

    #[cfg(feature = "alloc")]
    mod children {
        use std::sync::atomic::{AtomicUsize, Ordering};
        use std::time::{Duration, Instant};

        use oscall::io::{self, IoSlice, IoSliceMut};
        use oscall::process::linux::ptrace::{self, Options, Stop, SyscallStop};
        use oscall::process::linux::seccomp::{self, Action, FilterFlags};
        use oscall::process::linux::{
            self, CommandExt as _, ConfineExt as _, RemoteSlice, WaitEvent, WaitFlags, WaitFor,
            Waited,
        };
        use oscall::process::unix::{ChildExt as _, CommandExt as _, SIGCONT, SIGUSR1};
        use oscall::process::{Child, Command, Stdio};
        use oscall::raw::linux::{nr, syscall};
        use oscall::{AsHandle as _, Error, ErrorKind, OwnedHandle};

        use super::{SIGSTOP, SIGTRAP, common};

        const EPERM: i32 = 1;
        const EIO: i32 = 5;
        const ENOEXEC: i32 = 8;
        const ECHILD: i32 = 10;
        const EFAULT: i32 = 14;
        const EINVAL: i32 = 22;
        const ENOSYS: i32 = 38;

        /// What the helper writes before a line that is for its parent, on an
        /// output the test harness writes to as well.
        const MARK: &str = "oscall-helper:";

        /// The words a tracer reads and writes in the helper `traced`.
        static WORDS: [AtomicUsize; 4] = [
            AtomicUsize::new(0x1111),
            AtomicUsize::new(0x2222),
            AtomicUsize::new(0x3333),
            AtomicUsize::new(0x4444),
        ];

        /// This test binary, run as the helper `mode`, with pipes to its
        /// standard input and from its standard output.
        struct Helper {
            child: Child,
            /// Closed to let a helper that waits go on.
            input: Option<OwnedHandle>,
            output: OwnedHandle,
            /// What was read of the output and not yet used.
            pending: Vec<u8>,
        }

        /// How a helper is started.
        #[derive(Clone, Copy, Default)]
        struct Setup<'p> {
            trace: bool,
            own_group: bool,
            filter: Option<&'p [seccomp::Instruction]>,
        }

        impl<'p> Setup<'p> {
            fn new() -> Self {
                Self::default()
            }

            /// As a tracee of the caller.
            fn trace(mut self) -> Self {
                self.trace = true;
                self
            }

            /// In a process group of its own.
            fn own_group(mut self) -> Self {
                self.own_group = true;
                self
            }

            /// Under this system call filter.
            fn filter(mut self, program: &'p [seccomp::Instruction]) -> Self {
                self.filter = Some(program);
                self
            }
        }

        impl Helper {
            /// `Err` with the error of `spawn`; `None`, having said why,
            /// where the system cannot run the helper at all.
            fn spawn(mode: &str, setup: Setup<'_>) -> Option<Result<Self, Error>> {
                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 (input_read, input_write) = io::pipe().unwrap();
                let (output_read, output_write) = io::pipe().unwrap();
                // Three arguments that mean nothing: a tracer counts them.
                let mut command = Command::new(exe.as_os_str().as_encoded_bytes())
                    .args(&["one", "two", "three"])
                    .env(&env)
                    .stdin(Stdio::Handle(input_read.as_handle()))
                    .stdout(Stdio::Handle(output_write.as_handle()));
                if setup.trace {
                    command = command.trace_me();
                }
                if setup.own_group {
                    command = command.process_group(0);
                }
                if let Some(program) = setup.filter {
                    command = command
                        .no_new_privileges()
                        .seccomp(program, FilterFlags::empty());
                }
                match command.spawn() {
                    Ok(child) => Some(Ok(Self {
                        child,
                        input: Some(input_write),
                        output: output_read,
                        pending: Vec::new(),
                    })),
                    // 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 => {
                        common::skip(&format!("the system cannot execute {}", exe.display()));
                        None
                    }
                    Err(error) => Some(Err(error)),
                }
            }

            fn pid(&self) -> u32 {
                self.child.id()
            }

            /// The next line the helper wrote for its parent, without the
            /// mark.
            fn line(&mut self) -> String {
                loop {
                    while let Some(end) = self.pending.iter().position(|&byte| byte == b'\n') {
                        let line: Vec<u8> = self.pending.drain(..=end).collect();
                        let line = String::from_utf8_lossy(&line[..end]).into_owned();
                        if let Some(rest) = line.strip_prefix(MARK) {
                            return rest.to_owned();
                        }
                    }
                    let mut buf = [0u8; 256];
                    let read = io::read(&self.output, &mut buf).unwrap();
                    assert!(read > 0, "the helper said nothing more");
                    self.pending.extend_from_slice(&buf[..read]);
                }
            }

            /// The numbers of the next line.
            fn numbers(&mut self) -> Vec<usize> {
                let line = self.line();
                line.split_whitespace()
                    .map(|word| word.parse().unwrap())
                    .collect()
            }

            /// The next change of state of the helper, for a limited time.
            fn event(&self, flags: WaitFlags) -> Waited {
                let start = Instant::now();
                loop {
                    let who = WaitFor::Process(self.pid());
                    if let Some(waited) = linux::wait(who, flags | WaitFlags::NO_HANG).unwrap() {
                        assert_eq!(waited.pid, self.pid());
                        return waited;
                    }
                    if start.elapsed() > Duration::from_secs(60) {
                        let _ = self.child.kill();
                        panic!("the helper did not change state");
                    }
                    std::thread::sleep(Duration::from_millis(1));
                }
            }

            /// The next stop of the traced helper.
            fn stop(&self) -> Stop {
                let flags = WaitFlags::EXITED | WaitFlags::STOPPED | WaitFlags::ALL_CHILDREN;
                match self.event(flags).event {
                    WaitEvent::Trapped(stop) => stop,
                    other => panic!("the helper did not stop: {other:?}"),
                }
            }

            /// Lets the helper end, and wants it to have succeeded.
            fn finish(mut self) {
                self.input = None;
                let flags = WaitFlags::EXITED | WaitFlags::ALL_CHILDREN;
                assert_eq!(self.event(flags).event, WaitEvent::Exited(0));
            }
        }

        impl Drop for Helper {
            fn drop(&mut self) {
                // Whatever state the test left it in.
                let _ = self.child.kill();
            }
        }

        /// Writes a line for the parent.
        fn say(line: &str) {
            let line = format!("{MARK}{line}\n");
            let out = io::stdout().unwrap();
            assert_eq!(io::write(out, line.as_bytes()), Ok(line.len()));
        }

        /// Waits until the parent closes its end of the standard input.
        fn wait_for_parent() {
            let mut byte = [0u8; 1];
            let input = io::stdin().unwrap();
            while io::read(input, &mut byte).unwrap() != 0 {}
        }

        pub(super) fn helper_main(mode: &str) {
            // Tracing is about a thread, and these helpers are traced by
            // their first one.
            assert_eq!(
                oscall::thread::id(),
                u64::from(oscall::process::id()),
                "the helper does not run on the first thread of its process"
            );
            match mode {
                "wait" => wait_for_parent(),
                "traced" => helper_traced(),
                "memory" => helper_memory(),
                "parent" => helper_parent(false),
                "parent-refused" => helper_parent(true),
                "family" => helper_family(),
                _ => panic!("unknown helper mode {mode}"),
            }
            oscall::process::exit(0);
        }

        /// Whether the error is that of a system without the call: an
        /// emulator of programs, which the test then says.
        fn missing(what: &str, error: &Error) -> bool {
            if common::emulated() && matches!(error.raw_os_error(), ENOSYS | EINVAL | EIO) {
                common::note(&format!("skipped: no {what} under an emulator: {error}"));
                return true;
            }
            false
        }

        /// Changes of state that are no end: a stop, what follows it, and
        /// what a wait says of a child that has ended.
        pub(super) fn stopped_and_continued() {
            let Some(helper) = Helper::spawn("wait", Setup::new().own_group()) else {
                return;
            };
            let helper = helper.unwrap();
            let pid = helper.pid();
            // Nothing yet, and a wait says what it is for.
            let any = WaitFlags::EXITED | WaitFlags::STOPPED | WaitFlags::CONTINUED;
            let who = WaitFor::Process(pid);
            assert_eq!(linux::wait(who, any | WaitFlags::NO_HANG), Ok(None));
            let error = linux::wait(who, WaitFlags::NO_HANG).unwrap_err();
            assert_eq!(error.kind(), ErrorKind::InvalidInput, "{error:?}");
            let error = linux::wait(WaitFor::Process(0), any).unwrap_err();
            assert_eq!(error.kind(), ErrorKind::InvalidInput, "{error:?}");

            helper.child.send_signal(SIGSTOP).unwrap();
            let waited = helper.event(WaitFlags::STOPPED | WaitFlags::NO_WAIT);
            assert_eq!(waited.event, WaitEvent::Stopped(SIGSTOP));
            assert_eq!(waited.uid, linux::user_id());
            // Not taken: it is there for a wait by the group, which the
            // helper is the whole of.
            let by_group = linux::wait(WaitFor::Group(pid), WaitFlags::STOPPED).unwrap();
            assert_eq!(by_group, Some(waited));
            assert_eq!(linux::wait(who, any | WaitFlags::NO_HANG), Ok(None));
            helper.child.send_signal(SIGCONT).unwrap();
            let by_handle = WaitFor::PidFd(helper.child.as_handle());
            let start = Instant::now();
            let waited = loop {
                let flags = WaitFlags::CONTINUED | WaitFlags::NO_HANG;
                match linux::wait(by_handle, flags) {
                    Ok(Some(waited)) => break waited,
                    Ok(None) => assert!(start.elapsed() < Duration::from_secs(60)),
                    // An emulator that does not know the pidfd of a wait.
                    Err(error) if missing("waitid(P_PIDFD)", &error) => {
                        break helper.event(WaitFlags::CONTINUED);
                    }
                    Err(error) => panic!("wait: {error:?}"),
                }
                std::thread::sleep(Duration::from_millis(1));
            };
            assert_eq!((waited.pid, waited.event), (pid, WaitEvent::Continued));

            // Its end, looked at and left there; then taken, once.
            let mut helper = helper;
            helper.input = None;
            let waited = helper.event(WaitFlags::EXITED | WaitFlags::NO_WAIT);
            assert_eq!(waited.event, WaitEvent::Exited(0));
            assert!(waited.event.exit_status().unwrap().success());
            // It will not stop any more: a wait for that alone has no
            // child to wait for.
            let error = linux::wait(who, WaitFlags::STOPPED | WaitFlags::NO_HANG).unwrap_err();
            assert_eq!(error.raw_os_error(), ECHILD, "{error:?}");
            let error = linux::wait(who, WaitFlags::STOPPED).unwrap_err();
            assert_eq!(error.raw_os_error(), ECHILD, "{error:?}");
            let waited = helper.event(WaitFlags::EXITED);
            assert_eq!(waited.event, WaitEvent::Exited(0));
            let error = linux::wait(who, WaitFlags::EXITED).unwrap_err();
            assert_eq!(error.raw_os_error(), ECHILD, "{error:?}");
        }

        /// The helper of `trace_child`: says where its words are, stops
        /// itself with a signal the tracer swallows, makes a system call the
        /// tracer watches, and checks what the tracer wrote.
        fn helper_traced() {
            let pid = oscall::process::id();
            let at: Vec<String> = WORDS
                .iter()
                .map(|word| word.as_ptr().addr().to_string())
                .collect();
            say(&at.join(" "));
            // SAFETY: no memory is involved. The signal would end the
            // process: the tracer does not let it through.
            unsafe { syscall!(KILL, pid, SIGUSR1) }.unwrap();
            // SAFETY: no argument.
            let parent = unsafe { syscall!(GETPPID) }.unwrap();
            assert_eq!(parent as u32, oscall::process::parent_id());
            assert_eq!(WORDS[0].load(Ordering::SeqCst), 0x1111);
            assert_eq!(WORDS[1].load(Ordering::SeqCst), 0xaaaa);
            assert_eq!(WORDS[2].load(Ordering::SeqCst), 0xbbbb);
            assert_eq!(WORDS[3].load(Ordering::SeqCst), 0xcccc);
        }

        /// The number of the system call the registers are those of a thread
        /// stopped at the entry of.
        fn syscall_register(registers: &ptrace::Registers) -> u64 {
            #[cfg(target_arch = "x86_64")]
            return registers.orig_rax;
            #[cfg(target_arch = "x86")]
            return u64::from(registers.orig_eax);
            #[cfg(target_arch = "aarch64")]
            return registers.regs[8];
            #[cfg(target_arch = "arm")]
            return u64::from(registers.r[7]);
            #[cfg(any(target_arch = "riscv64", target_arch = "riscv32"))]
            return registers.a7 as u64;
        }

        /// A child traced from its first instruction: its stops, its
        /// registers, its memory, its system calls, its end.
        pub(super) fn trace_child() {
            let Some(helper) = Helper::spawn("traced", Setup::new().trace()) else {
                return;
            };
            let mut helper = match helper {
                Ok(helper) => helper,
                Err(error) if missing("ptrace", &error) => return,
                Err(error) if error.raw_os_error() == EPERM => {
                    common::skip(&format!("ptrace is refused here: {error}"));
                    return;
                }
                Err(error) => panic!("spawn: {error:?}"),
            };
            let pid = helper.pid();
            // The program is stopped before its first instruction.
            assert_eq!(helper.stop(), Stop::Signal(SIGTRAP));
            let info = ptrace::signal_info(pid).unwrap();
            assert_eq!((info.signal, info.errno), (SIGTRAP, 0), "{info:?}");
            // The kernel sent it, as the process itself would have.
            assert_eq!(info.code, 0, "{info:?}");
            assert_eq!(info.sender_pid(), pid, "{info:?}");
            assert_eq!(info.sender_uid(), linux::user_id(), "{info:?}");
            let registers = ptrace::registers(pid).unwrap();
            let (ip, sp) = (registers.instruction_pointer(), registers.stack_pointer());
            assert!(ip != 0 && sp != 0, "{registers:?}");
            // The same registers, as bytes.
            let mut bytes = [0u8; 512];
            let len = ptrace::get_regset(pid, ptrace::REGSET_GENERAL, &mut bytes).unwrap();
            assert_eq!(len, size_of::<ptrace::Registers>());
            // SAFETY: a `Registers` is that many bytes, all of them data.
            let raw =
                unsafe { std::slice::from_raw_parts((&raw const registers).cast::<u8>(), len) };
            assert_eq!(&bytes[..len], raw);
            ptrace::set_regset(pid, ptrace::REGSET_GENERAL, &bytes[..len]).unwrap();
            ptrace::set_registers(pid, &registers).unwrap();
            assert_eq!(ptrace::registers(pid).unwrap(), registers);
            // A set that is cut, and one there is none of.
            assert_eq!(
                ptrace::get_regset(pid, ptrace::REGSET_GENERAL, &mut bytes[..8]),
                Ok(8)
            );
            let error = ptrace::get_regset(pid, 0x7fff_fff0, &mut bytes).unwrap_err();
            assert_eq!(error.kind(), ErrorKind::InvalidInput, "{error:?}");
            // The first word of the stack of a program is the number of its
            // arguments: its name and three more.
            assert_eq!(ptrace::peek(pid, sp), Ok(4));
            let mut word = [0u8; size_of::<usize>()];
            match linux::read_memory(pid, sp, &mut word) {
                Ok(read) => assert_eq!((read, usize::from_ne_bytes(word)), (word.len(), 4)),
                Err(error) => assert!(missing("process_vm_readv", &error), "{error:?}"),
            }
            // Only the thread that traces may ask, and only of a tracee that
            // is stopped.
            let error = std::thread::spawn(move || ptrace::registers(pid))
                .join()
                .unwrap()
                .unwrap_err();
            assert_eq!(error.kind(), ErrorKind::NoSuchProcess, "{error:?}");
            let error = ptrace::cont(pid, 9999).unwrap_err();
            assert_eq!(error.raw_os_error(), EIO, "{error:?}");
            // There is no event to have a number.
            assert_eq!(ptrace::event_message(pid), Ok(0));

            let options = Options::TRACE_SYSGOOD | Options::TRACE_EXIT | Options::EXIT_KILL;
            ptrace::set_options(pid, options).unwrap();
            ptrace::cont(pid, 0).unwrap();
            let error = ptrace::registers(u32::MAX >> 1).unwrap_err();
            assert_eq!(error.kind(), ErrorKind::NoSuchProcess, "{error:?}");

            // It runs until the signal it sends itself.
            let words = helper.numbers();
            assert_eq!(helper.stop(), Stop::Signal(SIGUSR1));
            let info = ptrace::signal_info(pid).unwrap();
            assert_eq!(
                (info.signal, info.code, info.sender_pid()),
                (SIGUSR1, 0, pid)
            );
            assert_eq!(ptrace::peek(pid, words[0]), Ok(0x1111));
            assert_eq!(ptrace::peek(pid, words[1]), Ok(0x2222));
            ptrace::poke(pid, words[1], 0xaaaa).unwrap();
            assert_eq!(ptrace::peek(pid, words[1]), Ok(0xaaaa));
            let error = ptrace::peek(pid, 0).unwrap_err();
            assert!(matches!(error.raw_os_error(), EIO | EFAULT), "{error:?}");
            let error = ptrace::poke(pid, 0, 1).unwrap_err();
            assert!(matches!(error.raw_os_error(), EIO | EFAULT), "{error:?}");
            // Its memory, without `ptrace`.
            let size = size_of::<usize>();
            match linux::write_memory(pid, words[2], &0xbbbb_usize.to_ne_bytes()) {
                Ok(written) => {
                    assert_eq!(written, size);
                    // Two words that are not next to each other, into one
                    // buffer; and one buffer, cut in two, back to one place.
                    let far = [
                        RemoteSlice {
                            address: words[0],
                            len: size,
                        },
                        RemoteSlice {
                            address: words[2],
                            len: size,
                        },
                    ];
                    let mut both = [0u8; 2 * size_of::<usize>()];
                    let read =
                        linux::read_memory_vectored(pid, &mut [IoSliceMut::new(&mut both)], &far);
                    assert_eq!(read, Ok(2 * size));
                    assert_eq!(both[..size], 0x1111_usize.to_ne_bytes());
                    assert_eq!(both[size..], 0xbbbb_usize.to_ne_bytes());
                    let value = 0xcccc_usize.to_ne_bytes();
                    let (low, high) = value.split_at(1);
                    let near = [RemoteSlice {
                        address: words[3],
                        len: size,
                    }];
                    let parts = [IoSlice::new(low), IoSlice::new(high)];
                    assert_eq!(linux::write_memory_vectored(pid, &parts, &near), Ok(size));
                    assert_eq!(ptrace::peek(pid, words[3]), Ok(0xcccc));
                    // Nothing there, and nobody there.
                    let error = linux::read_memory(pid, 0, &mut word).unwrap_err();
                    assert_eq!(error.raw_os_error(), EFAULT, "{error:?}");
                    let error = linux::read_memory(0, words[0], &mut word).unwrap_err();
                    assert_eq!(error.kind(), ErrorKind::InvalidInput, "{error:?}");
                }
                Err(error) => {
                    assert!(missing("process_vm_writev", &error), "{error:?}");
                    ptrace::poke(pid, words[2], 0xbbbb).unwrap();
                    ptrace::poke(pid, words[3], 0xcccc).unwrap();
                }
            }

            // One instruction, where the kernel can.
            let before = ptrace::registers(pid).unwrap();
            match ptrace::single_step(pid, 0) {
                Ok(()) => {
                    assert_eq!(helper.stop(), Stop::Signal(SIGTRAP));
                    let after = ptrace::registers(pid).unwrap();
                    assert_ne!(after.instruction_pointer(), before.instruction_pointer());
                    common::note("ptrace: single-stepped one instruction");
                }
                Err(error) => {
                    // 32-bit ARM and RISC-V kernels have no such request.
                    assert_eq!(error.raw_os_error(), EIO, "{error:?}");
                    let arch = std::env::consts::ARCH;
                    assert!(!matches!(arch, "x86_64" | "x86" | "aarch64"), "{error:?}");
                    common::note(&format!("ptrace: no single step for {arch}: {error}"));
                }
            }

            // The system call it makes next: its entry, then its exit. The
            // signal was not delivered.
            ptrace::syscall(pid, 0).unwrap();
            assert_eq!(helper.stop(), Stop::Syscall);
            assert_eq!(ptrace::event_message(pid), Ok(1));
            let info = ptrace::syscall_info(pid).unwrap();
            assert_eq!(info.arch, seccomp::AUDIT_ARCH, "{info:?}");
            let SyscallStop::Entry { number, .. } = info.stop else {
                panic!("{info:?}");
            };
            assert_eq!(number, nr::GETPPID as u64);
            // The registers say the same.
            let registers = ptrace::registers(pid).unwrap();
            assert_eq!(syscall_register(&registers), number, "{registers:?}");
            assert_eq!(
                registers.instruction_pointer() as u64,
                info.instruction_pointer
            );
            assert_eq!(registers.stack_pointer() as u64, info.stack_pointer);
            ptrace::syscall(pid, 0).unwrap();
            assert_eq!(helper.stop(), Stop::Syscall);
            assert_eq!(ptrace::event_message(pid), Ok(2));
            let info = ptrace::syscall_info(pid).unwrap();
            let expected = SyscallStop::Exit {
                value: i64::from(oscall::process::id()),
                is_error: false,
            };
            assert_eq!(info.stop, expected, "{info:?}");

            // Its end, seen before it is over, and then over.
            ptrace::cont(pid, 0).unwrap();
            loop {
                match helper.stop() {
                    Stop::Exit => break,
                    // A signal of the runtime's own, which it gets.
                    Stop::Signal(signal) => ptrace::cont(pid, signal).unwrap(),
                    other => panic!("{other:?}"),
                }
            }
            // The status, as the older calls encode it: the code, eight bits
            // up.
            assert_eq!(ptrace::event_message(pid), Ok(0));
            let info = ptrace::syscall_info(pid).unwrap();
            assert_eq!(info.stop, SyscallStop::None, "{info:?}");
            ptrace::cont(pid, 0).unwrap();
            helper.finish();
        }

        /// A process that runs, taken and let go: by `seize`, which stops
        /// nothing, and by `attach`.
        pub(super) fn seize_and_attach() {
            let Some(helper) = Helper::spawn("wait", Setup::new()) else {
                return;
            };
            let helper = helper.unwrap();
            let pid = helper.pid();
            match ptrace::seize(pid, Options::TRACE_SYSGOOD) {
                Ok(()) => {}
                Err(error) if missing("ptrace", &error) => return,
                Err(error) if error.raw_os_error() == EPERM => {
                    common::skip(&format!("ptrace is refused here: {error}"));
                    return;
                }
                Err(error) => panic!("seize: {error:?}"),
            }
            // Once.
            let error = ptrace::seize(pid, Options::empty()).unwrap_err();
            assert_eq!(error.kind(), ErrorKind::PermissionDenied, "{error:?}");
            let error = ptrace::attach(pid).unwrap_err();
            assert_eq!(error.kind(), ErrorKind::PermissionDenied, "{error:?}");
            // It runs: nothing to report, and nothing to ask.
            let stops = WaitFlags::STOPPED | WaitFlags::ALL_CHILDREN | WaitFlags::NO_HANG;
            assert_eq!(linux::wait(WaitFor::Process(pid), stops), Ok(None));
            let error = ptrace::registers(pid).unwrap_err();
            assert_eq!(error.kind(), ErrorKind::NoSuchProcess, "{error:?}");
            ptrace::interrupt(pid).unwrap();
            assert_eq!(helper.stop(), Stop::Interrupted);
            assert!(ptrace::registers(pid).unwrap().stack_pointer() != 0);
            ptrace::cont(pid, 0).unwrap();

            // A signal that stops: seen as it comes, and then, let through,
            // as the stop of the whole process.
            helper.child.send_signal(SIGSTOP).unwrap();
            assert_eq!(helper.stop(), Stop::Signal(SIGSTOP));
            assert_eq!(ptrace::signal_info(pid).unwrap().signal, SIGSTOP);
            ptrace::cont(pid, SIGSTOP).unwrap();
            assert_eq!(helper.stop(), Stop::GroupStop(SIGSTOP));
            // No signal is behind this one: what is said of it is the
            // stop itself.
            let info = ptrace::signal_info(pid).unwrap();
            assert_eq!((info.signal, info.code), (SIGSTOP, 128 << 8 | SIGSTOP));
            // Left stopped, it says when that ends.
            ptrace::listen(pid).unwrap();
            assert_eq!(linux::wait(WaitFor::Process(pid), stops), Ok(None));
            helper.child.send_signal(SIGCONT).unwrap();
            assert_eq!(helper.stop(), Stop::Interrupted);
            ptrace::cont(pid, 0).unwrap();
            assert_eq!(helper.stop(), Stop::Signal(SIGCONT));
            // Let go, with the signal it was about to get.
            ptrace::detach(pid, SIGCONT).unwrap();
            let error = ptrace::interrupt(pid).unwrap_err();
            assert_eq!(error.kind(), ErrorKind::NoSuchProcess, "{error:?}");

            // The older way: a `SIGSTOP`, which is how the tracee is found.
            ptrace::attach(pid).unwrap();
            assert_eq!(helper.stop(), Stop::Signal(SIGSTOP));
            // What only a seized tracee takes.
            let error = ptrace::interrupt(pid).unwrap_err();
            assert_eq!(error.raw_os_error(), EIO, "{error:?}");
            let error = ptrace::listen(pid).unwrap_err();
            assert_eq!(error.raw_os_error(), EIO, "{error:?}");
            // Let through, the signal stops the process, and that stop
            // looks like the signal coming again: that no signal is
            // behind it is the one way to tell them apart.
            ptrace::cont(pid, SIGSTOP).unwrap();
            assert_eq!(helper.stop(), Stop::Signal(SIGSTOP));
            let error = ptrace::signal_info(pid).unwrap_err();
            assert_eq!(error.kind(), ErrorKind::InvalidInput, "{error:?}");
            // Nothing says that the process may go on, until the tracee
            // is restarted and gets the signal that says so.
            helper.child.send_signal(SIGCONT).unwrap();
            ptrace::cont(pid, 0).unwrap();
            assert_eq!(helper.stop(), Stop::Signal(SIGCONT));
            ptrace::detach(pid, 0).unwrap();
            helper.finish();
        }

        /// The helper of `trace_family`: runs this program once more, as a
        /// helper that does nothing, and waits for it.
        fn helper_family() {
            let exe = std::env::current_exe().unwrap();
            let mut child = Command::new(exe.as_os_str().as_encoded_bytes())
                .env(&["OSCALL_TEST_HELPER=wait"])
                .stdin(Stdio::Null)
                .spawn()
                .unwrap();
            assert!(child.wait().unwrap().success());
        }

        /// What a tracee creates is traced with it, when asked: the
        /// events of a child that is created, runs a program and ends,
        /// and of its parent that is let go and ends.
        pub(super) fn trace_family() {
            let Some(helper) = Helper::spawn("family", Setup::new().trace()) else {
                return;
            };
            let helper = match helper {
                Ok(helper) => helper,
                Err(error) if missing("ptrace", &error) => return,
                Err(error) if error.raw_os_error() == EPERM => {
                    common::skip(&format!("ptrace is refused here: {error}"));
                    return;
                }
                Err(error) => panic!("spawn: {error:?}"),
            };
            let parent = helper.pid();
            assert_eq!(helper.stop(), Stop::Signal(SIGTRAP));
            // `spawn` creates its child as `vfork` does.
            let options = Options::TRACE_VFORK
                | Options::TRACE_VFORK_DONE
                | Options::TRACE_EXEC
                | Options::TRACE_EXIT
                | Options::EXIT_KILL;
            ptrace::set_options(parent, options).unwrap();
            ptrace::cont(parent, 0).unwrap();

            // Two tracees from here on, each waited for by its name.
            let flags = WaitFlags::EXITED
                | WaitFlags::STOPPED
                | WaitFlags::ALL_CHILDREN
                | WaitFlags::NO_HANG;
            let mut child = None;
            let mut seen: [Vec<Stop>; 2] = [Vec::new(), Vec::new()];
            let mut ended = [None, None];
            let start = Instant::now();
            while ended[0].is_none() {
                assert!(start.elapsed() < Duration::from_secs(60), "{seen:?}");
                let mut idle = true;
                for (index, pid) in [Some(parent), child].into_iter().enumerate() {
                    let Some(pid) = pid else { continue };
                    if ended[index].is_some() {
                        continue;
                    }
                    let Some(waited) = linux::wait(WaitFor::Process(pid), flags).unwrap() else {
                        continue;
                    };
                    idle = false;
                    match waited.event {
                        WaitEvent::Trapped(stop) => {
                            if stop == Stop::Vfork {
                                // The number of the event is the child.
                                let created = ptrace::event_message(pid).unwrap();
                                child = Some(u32::try_from(created).unwrap());
                            }
                            seen[index].push(stop);
                            // A signal goes through, except the one a
                            // new tracee starts stopped by.
                            let signal = match stop {
                                Stop::Signal(SIGSTOP) => 0,
                                Stop::Signal(signal) => signal,
                                _ => 0,
                            };
                            ptrace::cont(pid, signal).unwrap();
                        }
                        event => ended[index] = Some(event),
                    }
                }
                if idle {
                    std::thread::sleep(Duration::from_millis(1));
                }
            }
            assert_eq!(
                ended,
                [Some(WaitEvent::Exited(0)), Some(WaitEvent::Exited(0))]
            );
            let [of_parent, of_child] = seen;
            // The parent: its child made, then running its own program,
            // then its own end. (Signals of its own may come between:
            // that of the child that ended, for one.)
            let events = |stops: &[Stop]| -> Vec<Stop> {
                stops
                    .iter()
                    .copied()
                    .filter(|stop| !matches!(stop, Stop::Signal(_)))
                    .collect()
            };
            assert_eq!(
                events(&of_parent),
                [Stop::Vfork, Stop::VforkDone, Stop::Exit],
                "{of_parent:?}"
            );
            // The child: stopped as it starts, for its tracer to find;
            // then the program it runs, and its end. It had the options
            // of its parent from the start.
            assert_eq!(
                of_child.first(),
                Some(&Stop::Signal(SIGSTOP)),
                "{of_child:?}"
            );
            assert_eq!(events(&of_child), [Stop::Exec, Stop::Exit], "{of_child:?}");
        }

        /// The helper of `memory_and_handles`: says where its words are, and
        /// checks what was written to them once its parent lets it.
        fn helper_memory() {
            say(&format!(
                "{} {}",
                WORDS[0].as_ptr().addr(),
                WORDS[1].as_ptr().addr()
            ));
            wait_for_parent();
            assert_eq!(WORDS[0].load(Ordering::SeqCst), 0x1111);
            assert_eq!(WORDS[1].load(Ordering::SeqCst), 0x5555);
        }

        /// The memory and the handles of a process that is neither stopped
        /// nor traced.
        pub(super) fn memory_and_handles() {
            let Some(helper) = Helper::spawn("memory", Setup::new()) else {
                return;
            };
            let mut helper = helper.unwrap();
            let pid = helper.pid();
            let words = helper.numbers();
            let mut word = [0u8; size_of::<usize>()];
            match linux::read_memory(pid, words[0], &mut word) {
                Ok(read) => {
                    assert_eq!((read, usize::from_ne_bytes(word)), (word.len(), 0x1111));
                    let written = linux::write_memory(pid, words[1], &0x5555_usize.to_ne_bytes());
                    assert_eq!(written, Ok(word.len()));
                    assert_eq!(linux::read_memory(pid, words[1], &mut word), Ok(word.len()));
                    assert_eq!(usize::from_ne_bytes(word), 0x5555);
                    // Nothing to read is nothing read.
                    assert_eq!(linux::read_memory(pid, words[0], &mut []), Ok(0));
                }
                Err(error) if missing("process_vm_readv", &error) => return,
                Err(error) if error.raw_os_error() == EPERM => {
                    common::skip(&format!("no access to another process here: {error}"));
                    return;
                }
                Err(error) => panic!("read_memory: {error:?}"),
            }

            // Its standard output is a pipe this process has the other end
            // of: what is written to the handle taken from it comes back.
            match linux::pidfd_getfd(&helper.child, 1) {
                Ok(output) => {
                    assert_eq!(io::is_inheritable(&output), Ok(false));
                    let line = format!("{MARK}through its own handle\n");
                    assert_eq!(io::write(&output, line.as_bytes()), Ok(line.len()));
                    assert_eq!(helper.line(), "through its own handle");
                    let error = linux::pidfd_getfd(&helper.child, 999_999).unwrap_err();
                    assert_eq!(error.kind(), ErrorKind::BadHandle, "{error:?}");
                    // A handle that names no process.
                    let error = linux::pidfd_getfd(&output, 1).unwrap_err();
                    assert_eq!(error.kind(), ErrorKind::BadHandle, "{error:?}");
                }
                Err(error) if missing("pidfd_getfd", &error) => {}
                // The system call filter of a container that is older than
                // the call.
                Err(error) if error.raw_os_error() == EPERM => {
                    common::skip(&format!("pidfd_getfd is refused here: {error}"));
                }
                Err(error) => panic!("pidfd_getfd: {error:?}"),
            }
            helper.finish();
        }

        /// The helper of `filter_and_tracer`: asks who its parent is, by the
        /// call its filter hands to a tracer.
        fn helper_parent(refused: bool) {
            // SAFETY: no argument.
            let parent = unsafe { syscall!(GETPPID) };
            if refused {
                // No tracer asked to be told.
                assert_eq!(parent.unwrap_err().raw_os_error(), ENOSYS);
            } else {
                // Asking again would be another call for the tracer.
                say(&parent.unwrap().to_string());
            }
        }

        /// A filter that stops a call for the tracer, and what becomes of
        /// the call without one.
        pub(super) fn filter_and_tracer() {
            let mut buf = [seccomp::Instruction::default(); seccomp::len_for(1)];
            let rules = [(nr::GETPPID, Action::Trace(0x1234))];
            let program = seccomp::build(&mut buf, &rules, Action::Allow).unwrap();
            let unsupported = |error: &Error| {
                missing("seccomp", error) || {
                    let refused = error.raw_os_error() == EPERM;
                    if refused {
                        common::skip(&format!("ptrace is refused here: {error}"));
                    }
                    refused
                }
            };

            // Without a tracer, the call is not made.
            let helper = Helper::spawn("parent-refused", Setup::new().filter(program));
            let Some(helper) = helper else {
                return;
            };
            match helper {
                Ok(helper) => helper.finish(),
                Err(error) if unsupported(&error) => return,
                Err(error) => panic!("spawn: {error:?}"),
            }

            let helper = Helper::spawn("parent", Setup::new().trace().filter(program));
            let helper = match helper.unwrap() {
                Ok(helper) => helper,
                Err(error) if unsupported(&error) => return,
                Err(error) => panic!("spawn: {error:?}"),
            };
            let pid = helper.pid();
            assert_eq!(helper.stop(), Stop::Signal(SIGTRAP));
            ptrace::set_options(pid, Options::TRACE_SECCOMP | Options::EXIT_KILL).unwrap();
            ptrace::cont(pid, 0).unwrap();
            loop {
                match helper.stop() {
                    Stop::Seccomp => break,
                    Stop::Signal(signal) => ptrace::cont(pid, signal).unwrap(),
                    other => panic!("{other:?}"),
                }
            }
            // What the filter gave, and the call it stopped.
            assert_eq!(ptrace::event_message(pid), Ok(0x1234));
            let info = ptrace::syscall_info(pid).unwrap();
            let SyscallStop::Seccomp { number, data, .. } = info.stop else {
                panic!("{info:?}");
            };
            assert_eq!((number, data), (nr::GETPPID as u64, 0x1234));
            // Let be, it is made.
            ptrace::cont(pid, 0).unwrap();
            let mut helper = helper;
            assert_eq!(helper.numbers(), [oscall::process::id() as usize]);
            helper.finish();
        }
    }
}

fn main() {
    #[cfg(any(target_os = "linux", target_os = "fullrust"))]
    linux::main();
}