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
//! What Linux alone has, and what containing a process is made of there:
//! namespaces, the identifier maps of a user namespace and the clocks of
//! a time namespace, process descriptors (pidfds), starting a child in a
//! cgroup, capabilities, of a thread and of a file, system call filters
//! and their supervisors ([`seccomp`]), the identity of the caller, and a
//! few process attributes (`prctl`).
//!
//! # Namespaces
//!
//! A namespace is the view a process has of one kind of system resource:
//! [`Namespaces`] names the kinds. A child is started in new ones with
//! [`CommandExt::namespaces`]; [`unshare`] gives new ones to the caller,
//! and [`setns`] moves it into those of another process.
//!
//! A **time namespace** has its own monotonic and boot-time clocks, each
//! at a fixed distance from the system's: [`TimeOffsets`], which
//! [`ConfineExt::time_offsets`] sets for a child and [`set_time_offsets`]
//! for the children to come of a thread that called [`unshare`]. They are
//! set once, before the first process is in the namespace.
//!
//! Creating a namespace needs `CAP_SYS_ADMIN`, except a **user namespace**,
//! which anyone may create where the system allows it, and whose creator
//! has every capability *inside* it: a process asks for
//! [`Namespaces::USER`] together with the others, and the kernel creates
//! the user namespace first. In a new user namespace no identifier means
//! anything until its maps are written ([`CommandExt::uid_map`],
//! [`write_uid_map`]): the process is `nobody` (65534) to itself, and loses
//! its capabilities when it runs a program.
//!
//! Systems restrict this, and answer
//! [`PermissionDenied`](crate::ErrorKind::PermissionDenied) unless said
//! otherwise:
//!
//! - `user.max_user_namespaces` may be 0: `ENOSPC`,
//!   [`StorageFull`](crate::ErrorKind::StorageFull).
//! - Debian's `kernel.unprivileged_userns_clone` switches user namespaces
//!   off for who has no privilege.
//! - Ubuntu's AppArmor restriction
//!   (`kernel.apparmor_restrict_unprivileged_userns`) lets a process
//!   without privilege create its namespaces, and
//!   its parent write maps of one identifier, but denies the process the
//!   *use* of the capabilities it has there: it is root of its namespace
//!   and may not set the host name, nor create another namespace later.
//!   What the `clone` that creates the child does is done; what the child
//!   would do itself is refused.
//! - The default system call filter of a container runtime (Docker)
//!   refuses every call that takes a namespace.
//!
//! # Memory and other limits: cgroups
//!
//! The limits of `unix::set_limit` are per process, and the one on memory
//! ([`AddressSpace`](super::unix::Resource::AddressSpace)) counts address
//! space, not memory in use. What limits the memory, the processor time or
//! the number of processes of a child *and everything it starts* is a
//! control group (cgroup v2): a directory under `/sys/fs/cgroup` whose
//! files are the settings (`memory.max`, `pids.max`, `cpu.max`...) and
//! which [`fs`](crate::fs) creates, reads and writes like any other.
//! [`CommandExt::cgroup`] starts a child in one, so that not one
//! instruction of the program runs outside it. oscall has no more than
//! that: no cgroup manager.
//!
//! # Process descriptors
//!
//! A pidfd names one process for as long as it is open, whatever becomes of
//! its identifier: [`pidfd_open`], [`pidfd_send_signal`], [`pidfd_wait`].
//! A [`Child`](super::Child) holds one and lends it
//! ([`AsHandle`]). A pidfd is readable once its process has exited:
//! [`event::unix::register`](crate::event::unix::register) takes it, with
//! [`Interest::READABLE`](crate::event::Interest::READABLE), for any
//! process (a [`Child`](super::Child) has
//! [`Poller::register_child`](crate::event::Poller::register_child)).
//!
//! # What is needed of the kernel
//!
//! oscall supports Linux 5.10 and later, which has everything here but the
//! time namespace (5.6) on kernels built without it. An emulator or a
//! system call filter may lack a call all the same, and it then fails with
//! [`Unsupported`](crate::ErrorKind::Unsupported) (`ENOSYS`): qemu-user
//! has no `clone3`, and refuses to create a child in new namespaces
//! (`EINVAL`).
//!
//! # Capabilities
//!
//! The privilege of root is divided into capabilities ([`Capability`]),
//! which a thread holds in sets: [`capabilities`] and
//! [`set_capabilities`] for the three it manages itself, [`bounding_set`]
//! and [`drop_bounding`] for the limit of what a program it runs can get,
//! [`ambient_set`] and [`raise_ambient`] for what passes to a program
//! that is not root. A child gives them up before its program starts with
//! [`ConfineExt::bounding_set`], [`ConfineExt::capabilities`] and
//! [`ConfineExt::ambient_capabilities`].
//!
//! A program file can carry capabilities too, which whoever runs it gets:
//! [`FileCapabilities`], read and written with [`file_capabilities`] and
//! [`set_file_capabilities`].
//!
//! # System call filters
//!
//! [`seccomp`] limits the system calls a thread, or a child
//! ([`ConfineExt::seccomp`]), may make from then on. A filter can also
//! hand calls to a supervisor that answers them
//! ([`seccomp::install_listener`], [`ConfineExt::seccomp_listener`]).
//!
//! # A thread, not the process
//!
//! Nearly everything here that changes the caller changes the calling
//! **thread**: namespaces, capabilities, the user and the groups, the
//! "no new privileges" flag, a system call filter. That is what the
//! kernel does. A C library hides it for the identity (its `setuid`
//! tells every thread); oscall calls the kernel and hides nothing. The
//! threads and processes the thread creates afterwards inherit what it
//! set; the threads that existed keep what they had. A process that means
//! to change as a whole does it before it creates threads, or in a child
//! it spawns, which has one.
//!
//! # Giving up access without privilege
//!
//! [`landlock`] restricts what a thread, or a child
//! ([`ConfineExt::landlock`]), may open, which ports it may use and which
//! processes it may signal, and needs no privilege to do it.
//!
//! # Tracing, and reaching into another process
//!
//! [`ptrace`] stops another thread at its system calls, its signals and
//! the calls its filter hands over, and reads and changes its registers
//! and memory; [`ConfineExt::trace_me`] starts a child that way. [`wait`]
//! is the wait that reports such stops, and any other change of state of
//! any child. [`read_memory`] and [`write_memory`] reach the memory of a
//! process that is not stopped, and [`pidfd_getfd`] its handles.
//!
//! # Not covered
//!
//! Managing cgroups (they are files); of `ptrace`, the requests that are
//! one architecture's (hardware breakpoints, `PTRACE_GETREGS` and its
//! kin, which [`ptrace::get_regset`] replaces), reading the filters of a
//! tracee, and changing a system call by `PTRACE_SET_SYSCALL_INFO`
//! (Linux 6.16): [`raw::linux`](crate::raw::linux) makes those calls.
//! Mounting and the root directory are in
//! [`fs::linux`](crate::fs::linux).

mod caps;
mod filecaps;
mod inspect;
pub mod landlock;
pub mod ptrace;
pub mod seccomp;

pub use caps::*;
pub use filecaps::*;
pub use inspect::*;

use crate::{AsHandle, Result, sys};

#[cfg(feature = "alloc")]
use super::{Command, ExitStatus};
#[cfg(feature = "alloc")]
use crate::BorrowedHandle;

crate::macros::flags! {
    /// Kinds of namespaces: `CLONE_NEW*`.
    pub struct Namespaces: u32 {
        /// Mount points (`CLONE_NEWNS`): the new namespace starts as a
        /// copy of the old one, and what is mounted or unmounted in it
        /// afterwards is its own.
        const MOUNT = 1;
        /// The host name and the domain name (`CLONE_NEWUTS`): see
        /// [`set_host_name`].
        const UTS = 1 << 1;
        /// System V IPC objects and POSIX message queues (`CLONE_NEWIPC`).
        const IPC = 1 << 2;
        /// User and group identifiers, and capabilities (`CLONE_NEWUSER`):
        /// see the [module documentation](self#namespaces).
        const USER = 1 << 3;
        /// Process identifiers (`CLONE_NEWPID`). The first process of the
        /// new namespace is its process 1: see
        /// [`CommandExt::namespaces`].
        const PID = 1 << 4;
        /// Network devices, addresses, routes, ports (`CLONE_NEWNET`): a
        /// new one has a loopback device, which is down, and nothing else.
        const NETWORK = 1 << 5;
        /// The root of the cgroup hierarchy the process sees
        /// (`CLONE_NEWCGROUP`).
        const CGROUP = 1 << 6;
        /// The offsets of the monotonic and boot-time clocks
        /// (`CLONE_NEWTIME`, Linux 5.6).
        const TIME = 1 << 7;
    }
}

/// Gives the calling **thread** new namespaces of the kinds in
/// `namespaces`, which it stops sharing with the rest of the system:
/// `unshare`.
///
/// Namespaces belong to threads, not to processes. The threads and
/// processes created afterwards by this thread are in its namespaces; the
/// other threads of the process stay where they were. Two kinds do not
/// take the caller along:
///
/// - [`PID`](Namespaces::PID): the caller keeps its identifier and its
///   namespace. The next process it creates is process 1 of the new one
///   (see [`CommandExt::namespaces`] for what that means), and when that
///   one has exited no other can be created: spawning then fails with
///   [`OutOfMemory`](crate::ErrorKind::OutOfMemory) (`ENOMEM`).
/// - [`TIME`](Namespaces::TIME): likewise, the processes created
///   afterwards are in the new namespace, as is the caller once it runs
///   another program.
///
/// # Errors
///
/// [`PermissionDenied`](crate::ErrorKind::PermissionDenied) without
/// `CAP_SYS_ADMIN` in the user namespace of the caller, which a new
/// [`USER`](Namespaces::USER) namespace asked for in the same call gives
/// (see the [module documentation](self#namespaces) for what may forbid
/// that one). [`InvalidInput`](crate::ErrorKind::InvalidInput) for
/// [`USER`](Namespaces::USER) in a process that has several threads: the
/// kernel refuses it, and a Rust test, which runs on a thread of its own,
/// is such a process.
pub fn unshare(namespaces: Namespaces) -> Result<()> {
    sys::process::contain::unshare(namespaces)
}

/// Moves the calling thread into existing namespaces: `setns`.
///
/// `handle` is either:
///
/// - a namespace: one of the files of `/proc/<pid>/ns` (`uts`, `net`,
///   `mnt`, `ipc`, `user`, `pid`, `cgroup`, `time`), opened for reading
///   with [`fs`](crate::fs). `namespaces` is then the kind it must be, or
///   empty for any;
/// - a pidfd ([`pidfd_open`], a [`Child`](super::Child)): the thread joins
///   the namespaces of that process, of all the kinds in `namespaces` or of
///   none (Linux 5.8).
///
/// As with [`unshare`], [`PID`](Namespaces::PID) and
/// [`TIME`](Namespaces::TIME) change where the processes created afterwards
/// are, not the caller.
///
/// # Errors
///
/// [`PermissionDenied`](crate::ErrorKind::PermissionDenied) without
/// `CAP_SYS_ADMIN` in the user namespace that owns the target, and in the
/// caller's own. [`InvalidInput`](crate::ErrorKind::InvalidInput) when the
/// handle is not of the kind asked for, for a pidfd with no kind, and to
/// join a [`USER`](Namespaces::USER) namespace from a process that has
/// several threads, or the one the caller is in already.
pub fn setns<H: AsHandle + ?Sized>(handle: &H, namespaces: Namespaces) -> Result<()> {
    sys::process::contain::setns(handle.as_handle().as_raw(), namespaces)
}

/// Sets the host name of the UTS namespace of the caller: `sethostname`.
/// For a namespace of one's own ([`Namespaces::UTS`]); in the initial one
/// this renames the machine.
///
/// The name is at most 64 bytes; `/proc/sys/kernel/hostname` reads it
/// back.
///
/// # Errors
///
/// [`PermissionDenied`](crate::ErrorKind::PermissionDenied) without
/// `CAP_SYS_ADMIN` in the user namespace that owns the UTS namespace;
/// [`InvalidInput`](crate::ErrorKind::InvalidInput) if the name is too
/// long.
pub fn set_host_name(name: &[u8]) -> Result<()> {
    sys::process::contain::set_host_name(name)
}

/// A range of a user namespace's identifier map: one line of `uid_map` or
/// `gid_map`. The `count` identifiers from `inside`, as the processes of
/// the namespace see them, are the `count` identifiers from `outside` in
/// the namespace of whoever writes the map.
///
/// `IdMap { inside: 0, outside: uid, count: 1 }` makes the process root in
/// its namespace, and itself to the rest of the system.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub struct IdMap {
    /// The first identifier of the range inside the namespace.
    pub inside: u32,
    /// The first identifier of the range outside of it.
    pub outside: u32,
    /// How many identifiers the range has; not 0.
    pub count: u32,
}

/// Writes the user map of the user namespace the process `pid` is in:
/// `/proc/<pid>/uid_map`. `pid` may be the caller
/// ([`id`](super::id)) after [`unshare`], or a child created in a new
/// namespace; [`CommandExt::uid_map`] does it for a child before its
/// program starts.
///
/// A map is written once, whole, and never changes. The writer must be in
/// the namespace or in its parent. Without `CAP_SETUID` in the parent
/// namespace, the map can only be one range of one identifier, `outside`
/// being the effective user of the writer (who must be the user that
/// created the namespace). A process that writes its own map is always in
/// that case, root included: its capabilities are those of the new
/// namespace. Larger maps are written from outside, by the parent.
///
/// # Errors
///
/// [`PermissionDenied`](crate::ErrorKind::PermissionDenied) when the rules
/// above are not met, or the map was already written;
/// [`InvalidInput`](crate::ErrorKind::InvalidInput) for an empty map, one
/// whose text is not shorter than 4096 bytes, and what the kernel finds
/// wrong with it (overlapping ranges, a count of 0, more than 340 ranges);
/// [`NotFound`](crate::ErrorKind::NotFound) when there is no such process,
/// or no `/proc`.
pub fn write_uid_map(pid: u32, map: &[IdMap]) -> Result<()> {
    sys::process::contain::write_id_map(super::checked_pid(pid)?, b"uid_map", map)
}

/// Writes the group map of the user namespace the process `pid` is in:
/// `/proc/<pid>/gid_map`. As [`write_uid_map`], with `CAP_SETGID` and the
/// effective group of the writer, and one more rule: without the
/// capability, `setgroups` must have been denied first
/// ([`allow_setgroups`]).
pub fn write_gid_map(pid: u32, map: &[IdMap]) -> Result<()> {
    sys::process::contain::write_id_map(super::checked_pid(pid)?, b"gid_map", map)
}

/// Says whether the processes of the user namespace the process `pid` is
/// in may call `setgroups`, which drops supplementary groups:
/// `/proc/<pid>/setgroups`, `allow` (the default) or `deny`.
///
/// Dropping a group can *give* access, to files that deny it to the group:
/// this is why a process without privilege must deny `setgroups` before it
/// may write a group map. It can only be set before the group map is
/// written, and once denied stays so, in that namespace and those created
/// inside it.
pub fn allow_setgroups(pid: u32, allow: bool) -> Result<()> {
    sys::process::contain::allow_setgroups(super::checked_pid(pid)?, allow)
}

/// How far a clock of a time namespace is from the same clock outside of
/// any: `seconds` and `nanoseconds` are added to it. The offset is
/// `seconds + nanoseconds / 1e9`, with `nanoseconds` below a thousand
/// million: half a second back is `-1` and `500_000_000`.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
pub struct ClockOffset {
    /// Whole seconds, negative for a clock that is behind.
    pub seconds: i64,
    /// Nanoseconds to add to them: less than 1 000 000 000.
    pub nanoseconds: u32,
}

impl ClockOffset {
    /// An offset from its two parts.
    pub const fn new(seconds: i64, nanoseconds: u32) -> Self {
        Self {
            seconds,
            nanoseconds,
        }
    }

    /// A clock that is `by` ahead. A duration of more seconds than the
    /// kernel counts becomes the most it counts, which it refuses.
    pub const fn ahead(by: core::time::Duration) -> Self {
        let seconds = by.as_secs();
        Self {
            seconds: if seconds > i64::MAX as u64 {
                i64::MAX
            } else {
                seconds as i64
            },
            nanoseconds: by.subsec_nanos(),
        }
    }

    /// A clock that is `by` behind.
    pub const fn behind(by: core::time::Duration) -> Self {
        let ahead = Self::ahead(by);
        if ahead.nanoseconds == 0 {
            Self {
                seconds: -ahead.seconds,
                nanoseconds: 0,
            }
        } else {
            // One second further back, and the rest of it forward.
            Self {
                seconds: (-ahead.seconds).saturating_sub(1),
                nanoseconds: 1_000_000_000 - ahead.nanoseconds,
            }
        }
    }
}

/// The offsets of the two clocks a time namespace has its own of: the
/// lines of `/proc/<pid>/timens_offsets`. `None` leaves a clock as it is
/// (not moved, in a new namespace).
///
/// The wall clock ([`time::now`](crate::time::now)) has no offset: a time
/// namespace does not change the date.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
pub struct TimeOffsets {
    /// For the monotonic clock (`CLOCK_MONOTONIC`, and with it
    /// `CLOCK_MONOTONIC_RAW` and `CLOCK_MONOTONIC_COARSE`):
    /// [`Clock::Monotonic`](crate::time::Clock::Monotonic).
    pub monotonic: Option<ClockOffset>,
    /// For the clock that also counts the time the system was suspended
    /// (`CLOCK_BOOTTIME`): [`Clock::Boottime`](crate::time::Clock::Boottime). What
    /// `/proc/uptime` says follows it.
    pub boot_time: Option<ClockOffset>,
}

/// Sets the offsets of the clocks of the time namespace the *children* of
/// the process `pid` will be in: `/proc/<pid>/timens_offsets`. That
/// namespace is the one [`unshare`] with [`Namespaces::TIME`] made, which
/// no process has entered yet; `pid` may also be a child that waits to
/// run its program, which is how [`ConfineExt::time_offsets`] does it.
///
/// **The offsets can only be written while the namespace is empty.** Once
/// a process is in it (the first child created after the [`unshare`], or
/// the program a child was spawned to run), they are fixed:
/// [`PermissionDenied`](crate::ErrorKind::PermissionDenied) (`EACCES`).
///
/// For the calling thread after [`unshare`], use [`set_time_offsets`]:
/// `pid` names a process by its first thread, and `unshare` changes the
/// thread that called it.
///
/// # Errors
///
/// [`PermissionDenied`](crate::ErrorKind::PermissionDenied) without
/// `CAP_SYS_TIME` in the user namespace that owns the time namespace
/// (`EPERM`), and for a namespace that has a process (`EACCES`);
/// [`InvalidInput`](crate::ErrorKind::InvalidInput) for offsets that name
/// no clock, and for nanoseconds that are not below 1 000 000 000;
/// `ERANGE` (which reads as
/// [`BufferTooSmall`](crate::ErrorKind::BufferTooSmall)) for an offset
/// that would make the clock negative, or larger than the kernel counts;
/// [`NotFound`](crate::ErrorKind::NotFound) when there is no such process,
/// no `/proc`, or a kernel without time namespaces.
pub fn write_time_offsets(pid: u32, offsets: &TimeOffsets) -> Result<()> {
    sys::process::contain::write_time_offsets(super::checked_pid(pid)?, offsets)
}

/// Sets the offsets of the clocks of the time namespace the calling
/// **thread** made with [`unshare`]`(`[`Namespaces::TIME`]`)`, which the
/// processes it creates from then on will be in: [`write_time_offsets`]
/// for the calling thread. Before the first of them is created.
///
/// The caller itself stays in the namespace it was in, with the clocks it
/// had.
pub fn set_time_offsets(offsets: &TimeOffsets) -> Result<()> {
    sys::process::contain::write_time_offsets(sys::thread::id() as u32, offsets)
}

/// Opens a descriptor of the process `pid`: `pidfd_open` (Linux 5.3).
///
/// The descriptor names that process even after it has exited and its
/// identifier was given to another. That holds from the moment it is
/// opened: `pid` itself is only safe to use while it cannot have been
/// reused, which is the case of a child not yet waited for, and of the
/// caller.
///
/// The handle is close-on-exec, becomes readable when the process exits
/// (see the [module documentation](self#process-descriptors)), and is
/// what [`pidfd_send_signal`], [`pidfd_wait`] and [`setns`] take.
///
/// # Errors
///
/// [`NoSuchProcess`](crate::ErrorKind::NoSuchProcess);
/// [`InvalidInput`](crate::ErrorKind::InvalidInput) if `pid` is 0 or does
/// not fit in the system's type, or names a thread that is not the first
/// of its process; [`Unsupported`](crate::ErrorKind::Unsupported) under an
/// emulator that lacks the call.
pub fn pidfd_open(pid: u32) -> Result<crate::OwnedHandle> {
    sys::process::contain::pidfd_open(super::checked_pid(pid)?)
}

/// Sends a signal to the process of a pidfd: `pidfd_send_signal`
/// (Linux 5.1). `signal` is the system's number, as for
/// `unix::send_signal`; 0 sends nothing and checks that the process is
/// there.
///
/// # Errors
///
/// [`NoSuchProcess`](crate::ErrorKind::NoSuchProcess) once the process has
/// been waited for (one that has exited and was not yet collected takes
/// the signal without an error);
/// [`PermissionDenied`](crate::ErrorKind::PermissionDenied);
/// [`BadHandle`](crate::ErrorKind::BadHandle) if the handle is not a
/// pidfd; [`InvalidInput`](crate::ErrorKind::InvalidInput) if the system
/// has no such signal.
pub fn pidfd_send_signal<H: AsHandle + ?Sized>(pidfd: &H, signal: i32) -> Result<()> {
    sys::process::contain::pidfd_send_signal(pidfd.as_handle().as_raw(), signal)
}

/// Waits for the process of a pidfd, which must be a child of the caller,
/// to exit, and collects it: `waitid(P_PIDFD)` (Linux 5.4).
///
/// The status of a child can be collected once. A
/// [`Child`](super::Child) for the same process then finds it gone (see
/// there): wait for a child through one or the other.
///
/// # Errors
///
/// `ECHILD` when the process is not a child of the caller, or was
/// collected already; [`Interrupted`](crate::ErrorKind::Interrupted) when
/// a signal handler runs during the wait.
#[cfg(feature = "alloc")]
pub fn pidfd_wait<H: AsHandle + ?Sized>(pidfd: &H) -> Result<ExitStatus> {
    match sys::process::wait_pidfd(pidfd.as_handle().as_raw(), true)? {
        Some((status, _)) => Ok(status),
        // The system returned from a blocking wait with no child.
        None => Err(crate::ErrorKind::Other.into()),
    }
}

/// As [`pidfd_wait`], without waiting: `None` if the process is still
/// running.
#[cfg(feature = "alloc")]
pub fn pidfd_try_wait<H: AsHandle + ?Sized>(pidfd: &H) -> Result<Option<ExitStatus>> {
    Ok(sys::process::wait_pidfd(pidfd.as_handle().as_raw(), false)?.map(|(status, _)| status))
}

/// Forbids the calling **thread** to gain privileges by running a program:
/// `prctl(PR_SET_NO_NEW_PRIVS)`. From then on set-user-ID and set-group-ID
/// bits and file capabilities are ignored by `execve`. It cannot be
/// undone, and the threads and processes created afterwards by this thread
/// inherit it; the other threads of the process are not affected.
///
/// A process without privilege needs this before it may install a
/// [`seccomp`] filter. [`CommandExt::no_new_privileges`] sets it for a
/// child alone.
pub fn set_no_new_privileges() -> Result<()> {
    sys::process::contain::set_no_new_privileges()
}

/// Whether the calling thread may no longer gain privileges
/// (`PR_GET_NO_NEW_PRIVS`): see [`set_no_new_privileges`].
pub fn no_new_privileges() -> Result<bool> {
    sys::process::contain::no_new_privileges()
}

/// Makes the calling process the one that adopts its orphaned descendants,
/// or stops it being so: `prctl(PR_SET_CHILD_SUBREAPER)`.
///
/// When a process exits, its children are normally adopted by process 1.
/// With this they go to the nearest ancestor that asked for them, which is
/// told when they exit (`SIGCHLD`) and must wait for them, as for its own
/// children: this is how a supervisor keeps track of every process a
/// program left behind: [`wait`] with [`WaitFor::Any`] waits for any of
/// them.
///
/// The setting is not inherited by children.
pub fn set_child_subreaper(on: bool) -> Result<()> {
    sys::process::contain::set_child_subreaper(on)
}

/// Whether the calling process adopts its orphaned descendants
/// (`PR_GET_CHILD_SUBREAPER`): see [`set_child_subreaper`].
pub fn is_child_subreaper() -> Result<bool> {
    sys::process::contain::is_child_subreaper()
}

/// Says whether the calling process may be dumped and inspected:
/// `prctl(PR_SET_DUMPABLE)`.
///
/// A process that is not dumpable writes no core dump, cannot be attached
/// to with `ptrace` by a process without privilege, and its files under
/// `/proc/<pid>` belong to root: other processes of the same user, and
/// the process itself where it is not root, can no longer open most of
/// them (which includes `/proc/self/environ`, `maps`, `mem` and the
/// namespace files of `ns`). The kernel clears the flag by itself when a
/// process changes identity, and sets it again when a program is run.
pub fn set_dumpable(on: bool) -> Result<()> {
    sys::process::contain::set_dumpable(on)
}

/// Whether the calling process may be dumped (`PR_GET_DUMPABLE`): see
/// [`set_dumpable`]. `false` also for a process the system only lets root
/// dump (`fs.suid_dumpable = 2`).
pub fn is_dumpable() -> Result<bool> {
    sys::process::contain::is_dumpable()
}

/// What [`CommandExt`] sets.
#[cfg(feature = "alloc")]
#[derive(Clone, Copy, Default)]
pub(crate) struct Options<'a> {
    pub(crate) namespaces: Namespaces,
    pub(crate) uid_map: Option<&'a [IdMap]>,
    pub(crate) gid_map: Option<&'a [IdMap]>,
    pub(crate) deny_setgroups: bool,
    pub(crate) time_offsets: Option<TimeOffsets>,
    pub(crate) cgroup: Option<BorrowedHandle<'a>>,
    pub(crate) no_new_privileges: bool,
    pub(crate) parent_death_signal: Option<i32>,
    pub(crate) bounding: Option<CapabilitySet>,
    pub(crate) capabilities: Option<Capabilities>,
    pub(crate) ambient: Option<CapabilitySet>,
    pub(crate) seccomp: Option<(&'a [seccomp::Instruction], seccomp::FilterFlags)>,
    pub(crate) seccomp_listener: bool,
    pub(crate) landlock: Option<BorrowedHandle<'a>>,
    pub(crate) trace_me: bool,
}

/// More to set on a [`Command`] on Linux.
#[cfg(feature = "alloc")]
pub trait CommandExt<'a> {
    /// Starts the child in new namespaces of these kinds: the `CLONE_NEW*`
    /// flags of the `clone` that creates it. Unlike with [`unshare`], the
    /// child itself is in every one of them, from its first instruction.
    ///
    /// What [`unshare`] says of privilege holds: without `CAP_SYS_ADMIN`,
    /// ask for [`USER`](Namespaces::USER) too. With a new user namespace
    /// and no map ([`uid_map`](Self::uid_map)), the program runs as
    /// `nobody` and without capabilities.
    ///
    /// With [`PID`](Namespaces::PID) the child is **process 1** of its
    /// namespace, which the kernel treats as an `init`:
    ///
    /// - [`id`](super::id) is 1 in the child and
    ///   [`parent_id`](super::parent_id) 0; [`Child::id`](super::Child::id)
    ///   is its identifier in the namespace of the caller.
    /// - A signal the program has no handler for is *not delivered*, even
    ///   one whose default action is to terminate: `SIGTERM` does nothing
    ///   to a program that does not handle it. Only `SIGKILL` and
    ///   `SIGSTOP` sent from outside the namespace always work, so
    ///   [`Child::kill`](super::Child::kill) does.
    /// - It adopts the orphans of its namespace and should wait for them.
    /// - When it exits, every other process of the namespace is killed.
    /// - `/proc` still shows the processes of the namespace it was mounted
    ///   in, until the child mounts its own (in a new
    ///   [`MOUNT`](Namespaces::MOUNT) namespace).
    ///
    /// With [`TIME`](Namespaces::TIME) the child enters the new namespace
    /// when the program starts, and the offsets of its clocks, which can
    /// only be written before that, are zero unless
    /// [`time_offsets`](ConfineExt::time_offsets) sets them. It also needs
    /// `clone3`, which an emulator or a system call filter may lack:
    /// [`spawn`](Command::spawn) then fails with
    /// [`Unsupported`](crate::ErrorKind::Unsupported).
    ///
    /// # Errors
    ///
    /// [`spawn`](Command::spawn) fails as [`unshare`] does. qemu-user
    /// refuses to create a process in new namespaces, with
    /// [`InvalidInput`](crate::ErrorKind::InvalidInput).
    fn namespaces(self, namespaces: Namespaces) -> Self;

    /// Sets the user map of the child's new user namespace
    /// ([`Namespaces::USER`] must be asked for): what [`write_uid_map`]
    /// writes, written by the caller **before the program starts**. The
    /// child is created, waits while the caller writes
    /// `/proc/<pid>/setgroups`, `gid_map` and `uid_map` as the command
    /// says, and only then sets itself up and runs the program; if a write
    /// fails, [`spawn`](Command::spawn) fails with its error and the child
    /// is gone. The files are those of `/proc`, which must be mounted.
    ///
    /// The rules of [`write_uid_map`] apply to the caller: without
    /// privilege, one range of one identifier, its own effective user.
    ///
    /// # Errors
    ///
    /// [`spawn`](Command::spawn) fails with
    /// [`InvalidInput`](crate::ErrorKind::InvalidInput) for a map without
    /// a new user namespace, for an empty map and for one too long to
    /// write.
    fn uid_map(self, map: &'a [IdMap]) -> Self;

    /// Sets the group map of the child's new user namespace: as
    /// [`uid_map`](Self::uid_map), for what [`write_gid_map`] writes.
    /// Without privilege it needs
    /// [`deny_setgroups`](Self::deny_setgroups).
    fn gid_map(self, map: &'a [IdMap]) -> Self;

    /// Denies `setgroups` in the child's new user namespace
    /// ([`allow_setgroups`]), before the group map is written.
    fn deny_setgroups(self) -> Self;

    /// Starts the child in the cgroup (version 2) whose directory `cgroup`
    /// is an open handle of (borrowed as for
    /// [`Stdio::Handle`](super::Stdio::Handle): `directory.as_handle()`):
    /// `clone3` with `CLONE_INTO_CGROUP` (Linux 5.7). The child is in the cgroup from its creation, and so is
    /// everything it starts: this is how the memory of a child and its
    /// descendants is limited (see the
    /// [module documentation](self#memory-and-other-limits-cgroups)).
    ///
    /// The caller must be allowed to move a process there: write access to
    /// the `cgroup.procs` of the directory, and, for a caller that is not
    /// root, of the closest common ancestor with its own cgroup. A cgroup
    /// that has controllers enabled for its children
    /// (`cgroup.subtree_control`) takes no process itself.
    ///
    /// Where there is no `clone3` (qemu-user; the default system call
    /// filter of Docker, which answers `ENOSYS` to it), the child is
    /// created the usual way and moves itself, by writing to `cgroup.procs`
    /// before anything else: the same rights are needed and the program
    /// starts in the cgroup all the same.
    ///
    /// # Errors
    ///
    /// [`spawn`](Command::spawn) fails with
    /// [`PermissionDenied`](crate::ErrorKind::PermissionDenied) without
    /// the rights above; [`BadHandle`](crate::ErrorKind::BadHandle) if the
    /// handle is not a cgroup directory
    /// ([`NotFound`](crate::ErrorKind::NotFound) where the child moves
    /// itself).
    fn cgroup(self, cgroup: BorrowedHandle<'a>) -> Self;

    /// Forbids the child to gain privileges by running a program, starting
    /// with its own: [`set_no_new_privileges`], in the child, just before
    /// the program is run.
    fn no_new_privileges(self) -> Self;

    /// Has the system send `signal` to the child when its parent goes
    /// away: `prctl(PR_SET_PDEATHSIG)` in the child, once its identity is
    /// set. With `unix::SIGKILL`, a child that cannot outlive the caller;
    /// with a signal the program handles, one that is told.
    ///
    /// What the system means by "the parent" is **the thread that called
    /// [`spawn`](Command::spawn)**, not the process: the signal is sent
    /// when that thread ends, even if the process lives on. Spawn such a
    /// child from a thread that lasts as long as the child should.
    ///
    /// The setting belongs to the child process alone: the processes it
    /// creates do not have it. The system clears it when the program is
    /// set-user-ID, set-group-ID or has file capabilities, and whenever
    /// the child later changes its effective user or group; the child can
    /// change or clear it itself.
    ///
    /// If the caller is already gone by the time the child asks, which a
    /// process killed while it spawns can be, the child notices that its
    /// parent is no longer the caller and sends itself the signal. (A
    /// child that cannot see its parent, because it is in another process
    /// namespace, cannot check.)
    ///
    /// A number that is no signal makes `spawn` fail with
    /// [`InvalidInput`](crate::ErrorKind::InvalidInput).
    ///
    /// macOS has nothing of the kind, which is why this is not in `unix`:
    /// a child there finds out by itself, by watching for its parent's
    /// exit or for the end of a pipe the parent holds. On Windows, a job
    /// object that is closed with the parent does it
    /// (`process::windows::Job`).
    fn parent_death_signal(self, signal: i32) -> Self;
}

#[cfg(feature = "alloc")]
mod sealed {
    /// What keeps a trait of this module from being implemented
    /// elsewhere, so that it can grow.
    pub trait Sealed {}
    #[cfg(feature = "alloc")]
    impl Sealed for crate::process::Command<'_> {}
    #[cfg(feature = "alloc")]
    impl Sealed for crate::process::Child {}
}

/// What confines the child of a [`Command`] on Linux, and the clocks it
/// reads: capabilities, a system call filter, the offsets of a time
/// namespace.
///
/// This is the rest of [`CommandExt`], in a trait of its own that only
/// [`Command`] implements: [`CommandExt`] was published open to other
/// implementations, and a trait that is cannot be given a method without
/// breaking them.
#[cfg(feature = "alloc")]
pub trait ConfineExt<'a>: sealed::Sealed {
    /// Sets the offsets of the clocks of the child's new time namespace
    /// ([`Namespaces::TIME`] must be asked for): what
    /// [`write_time_offsets`] writes, written by the caller **before the
    /// program starts**, the only moment they can be. As for
    /// [`uid_map`](CommandExt::uid_map), the child waits while the caller
    /// writes `/proc/<pid>/timens_offsets`, after the maps if there are
    /// any; the program then reads its monotonic and boot-time clocks
    /// shifted, and so does everything it starts.
    ///
    /// The caller needs `CAP_SYS_TIME` in the user namespace that owns
    /// the time namespace: it has it when the child is also given a new
    /// user namespace ([`Namespaces::USER`]), which the caller owns, and
    /// must be root otherwise.
    ///
    /// A child that is given a copy of the memory of the caller (one that
    /// changes its user or group, or has a [`seccomp`](Self::seccomp)
    /// filter) makes the time namespace itself, with `unshare`, instead
    /// of being created in it: the result is the same, with one more
    /// thing the child must be allowed to do, and no need for `clone3`.
    ///
    /// # Errors
    ///
    /// [`spawn`](Command::spawn) fails as [`write_time_offsets`] does,
    /// and with [`InvalidInput`](crate::ErrorKind::InvalidInput) for
    /// offsets without a new time namespace, and for offsets that name no
    /// clock.
    fn time_offsets(self, offsets: TimeOffsets) -> Self;

    /// Leaves in the bounding set of the child the capabilities of `keep`
    /// alone: [`drop_bounding`] for every other, in the child, before it
    /// changes its user. The program then cannot have a capability
    /// outside of `keep`, whoever runs it and whatever its file says:
    /// this is how capabilities are kept from a program run as root,
    /// which otherwise gets them all back when it starts.
    ///
    /// The child needs `CAP_SETPCAP`, as the caller has it: as root, or as
    /// root of the new user namespace it is created in
    /// ([`namespaces`](CommandExt::namespaces) with a user map).
    /// [`spawn`](Command::spawn) fails with
    /// [`PermissionDenied`](crate::ErrorKind::PermissionDenied)
    /// otherwise.
    fn bounding_set(self, keep: CapabilitySet) -> Self;

    /// Sets the capability sets of the child: [`set_capabilities`], in
    /// the child, just before the program is run, after the change of
    /// user if there is one. When the child changes user
    /// (`unix::CommandExt::uid`), its permitted set is kept across the
    /// change for this ([`set_keep_capabilities`]), so that a child of
    /// root that becomes another user can be left with a few
    /// capabilities.
    ///
    /// The program does not simply inherit these sets: see
    /// [`set_capabilities`] for what `execve` makes of them. In short, a
    /// program run as root is limited by
    /// [`bounding_set`](Self::bounding_set), and a program run as another
    /// user only has what
    /// [`ambient_capabilities`](Self::ambient_capabilities) passes.
    ///
    /// # Errors
    ///
    /// [`spawn`](Command::spawn) fails with
    /// [`PermissionDenied`](crate::ErrorKind::PermissionDenied) for sets
    /// the child may not have.
    fn capabilities(self, capabilities: Capabilities) -> Self;

    /// Makes `ambient` the ambient set of the child: the capabilities its
    /// program keeps although it is neither root nor a file with
    /// capabilities. In the child, after
    /// [`capabilities`](Self::capabilities): the set is emptied, then
    /// [`raise_ambient`] for each.
    ///
    /// Each capability must be in the permitted and inheritable sets of
    /// the child at that point, which [`capabilities`](Self::capabilities)
    /// sets: a child that becomes another user and is to keep
    /// `CAP_NET_BIND_SERVICE` is given `Capabilities::all_three(set)` and
    /// the same set here.
    ///
    /// # Errors
    ///
    /// [`spawn`](Command::spawn) fails with
    /// [`PermissionDenied`](crate::ErrorKind::PermissionDenied) for a
    /// capability that is not in both sets.
    fn ambient_capabilities(self, ambient: CapabilitySet) -> Self;

    /// Installs a system call filter in the child:
    /// [`seccomp::install`], as the last thing the child does before it
    /// runs the program. The program, and everything it starts, runs
    /// under the filter; nothing of what [`spawn`](Command::spawn) does
    /// to set the child up is subject to it.
    ///
    /// The filter must allow `execve`, which comes after it: a child
    /// whose filter forbids it never starts its program. It should also
    /// allow `write` and `exit_group`, which is how the child says that
    /// `execve` failed, by the filter or for an ordinary reason, and
    /// ends: [`spawn`](Command::spawn) then fails with that error. When
    /// the filter does not let the child say it (it forbids `write`, or
    /// its answer to `execve` is to end the process),
    /// [`spawn`](Command::spawn) succeeds, and waiting for the child
    /// finds it ended by a signal: `SIGSYS` when the filter did it, and
    /// `SIGILL` when the child, refused every call that ends a process,
    /// had to do it itself.
    ///
    /// A child with a filter is given a copy of the memory of the
    /// caller, as `unix::fork` would, instead of sharing it.
    ///
    /// As for [`seccomp::install`], the child needs
    /// [`no_new_privileges`](CommandExt::no_new_privileges), which a caller
    /// without privilege must ask for too, or `CAP_SYS_ADMIN`.
    /// [`seccomp::FilterFlags::ALL_THREADS`] means nothing here: the
    /// child has one thread.
    ///
    /// # Errors
    ///
    /// [`spawn`](Command::spawn) fails as [`seccomp::install`] does, with
    /// [`InvalidInput`](crate::ErrorKind::InvalidInput) for an empty or
    /// oversized program before any child is created.
    fn seccomp(self, program: &'a [seccomp::Instruction], flags: seccomp::FilterFlags) -> Self;

    /// Installs a system call filter in the child as
    /// [`seccomp`](Self::seccomp) does, and brings its *listener* back to
    /// the caller: [`seccomp::install_listener`] in the child, and
    /// [`ChildExt::take_seccomp_listener`] on the [`Child`](super::Child)
    /// that [`spawn`](Command::spawn) returns. The caller, or whoever it
    /// gives the handle to, then answers the calls of the program that
    /// the filter hands over with [`seccomp::Action::UserNotify`]: see
    /// the
    /// [module documentation](seccomp#a-supervisor-that-answers-for-the-kernel).
    ///
    /// The listener is with the caller before the program has made its
    /// first call, and nothing of how it gets there is subject to the
    /// filter: the filter may notify for any call, `execve` aside, which
    /// is the one that starts the program and must be allowed as for
    /// [`seccomp`](Self::seccomp). (A filter that notifies for `execve`
    /// makes [`spawn`](Command::spawn) wait for an answer no one can give
    /// yet.)
    ///
    /// **A short-lived process is left behind for this.** The listener
    /// only exists once the filter is installed, when the child may no
    /// longer be trusted to make a call; it is sent by a process the
    /// child creates beforehand, which shares its handles, waits for the
    /// program to start, sends, and exits. That process is an orphan: the
    /// `init` of the process namespace collects it, as it does any other.
    /// When the child is itself that `init`
    /// ([`Namespaces::PID`]), or the caller adopts orphans
    /// ([`set_child_subreaper`]), the process shows as a child that
    /// exited, to be waited for like the orphans such a process expects.
    ///
    /// # Errors
    ///
    /// [`spawn`](Command::spawn) fails as for [`seccomp`](Self::seccomp).
    fn seccomp_listener(
        self,
        program: &'a [seccomp::Instruction],
        flags: seccomp::FilterFlags,
    ) -> Self;

    /// Restricts the child with the Landlock ruleset `ruleset`
    /// ([`landlock::create_ruleset`], borrowed as for
    /// [`cgroup`](CommandExt::cgroup)): [`landlock::restrict_self`] in
    /// the child, among the last things it does before it runs the
    /// program, ahead of its capabilities and of a
    /// [`seccomp`](Self::seccomp) filter. The program, and everything it
    /// starts, is refused the access the ruleset handles and no rule of
    /// it allows; the caller is not restricted.
    ///
    /// Running the program comes after: a ruleset that handles
    /// [`landlock::AccessFs::EXECUTE`] must allow it for the program
    /// file, and for the interpreter and the libraries of a program that
    /// has them, or [`spawn`](Command::spawn) fails with
    /// [`PermissionDenied`](crate::ErrorKind::PermissionDenied).
    ///
    /// As for [`landlock::restrict_self`], the child needs
    /// [`no_new_privileges`](CommandExt::no_new_privileges), which a
    /// caller without privilege must ask for too, or `CAP_SYS_ADMIN`.
    ///
    /// # Errors
    ///
    /// [`spawn`](Command::spawn) fails as [`landlock::restrict_self`]
    /// does.
    fn landlock(self, ruleset: BorrowedHandle<'a>) -> Self;

    /// Starts the child as a tracee of the calling **thread**:
    /// [`ptrace::trace_me`] in the child, before it runs the program
    /// (and before a [`seccomp`](Self::seccomp) filter is installed,
    /// which need not allow it).
    ///
    /// The program is then stopped before its first instruction, with a
    /// `SIGTRAP`: [`spawn`](Command::spawn) returns, and the first
    /// [`wait`] for the child (with [`WaitFlags::STOPPED`]) reports
    /// [`ptrace::Stop::Signal`]`(5)`. The caller sets its options
    /// ([`ptrace::set_options`]) and restarts it. See [`ptrace`] for the
    /// rest, and for why it is the thread that called
    /// [`spawn`](Command::spawn) that must make the requests.
    ///
    /// A child that is traced and whose tracer never waits for it stays
    /// stopped: [`Child::wait`](super::Child::wait) alone does not see
    /// stops, and waits for good.
    ///
    /// # Errors
    ///
    /// [`spawn`](Command::spawn) fails with
    /// [`Unsupported`](crate::ErrorKind::Unsupported) under an emulator
    /// that has no `ptrace` (qemu-user).
    fn trace_me(self) -> Self;
}

/// More to do with a [`Child`](super::Child) on Linux.
#[cfg(feature = "alloc")]
pub trait ChildExt: sealed::Sealed {
    /// The listener of the filter the child was given with
    /// [`ConfineExt::seccomp_listener`]: the handle to
    /// [`seccomp::receive`] its system calls on. `None` for a child that
    /// has no such filter, and once the listener was taken.
    ///
    /// The filter has this one listener: while it is open, the calls the
    /// filter hands over wait for it, and once it is closed they fail
    /// with `ENOSYS`. Dropping the [`Child`](super::Child) closes a
    /// listener that was not taken.
    fn take_seccomp_listener(&mut self) -> Option<crate::OwnedHandle>;
}

#[cfg(feature = "alloc")]
impl ChildExt for super::Child {
    fn take_seccomp_listener(&mut self) -> Option<crate::OwnedHandle> {
        self.inner.take_listener()
    }
}

#[cfg(feature = "alloc")]
impl<'a> CommandExt<'a> for Command<'a> {
    fn namespaces(mut self, namespaces: Namespaces) -> Self {
        self.linux.namespaces = namespaces;
        self
    }

    fn uid_map(mut self, map: &'a [IdMap]) -> Self {
        self.linux.uid_map = Some(map);
        self
    }

    fn gid_map(mut self, map: &'a [IdMap]) -> Self {
        self.linux.gid_map = Some(map);
        self
    }

    fn deny_setgroups(mut self) -> Self {
        self.linux.deny_setgroups = true;
        self
    }

    fn cgroup(mut self, cgroup: BorrowedHandle<'a>) -> Self {
        self.linux.cgroup = Some(cgroup);
        self
    }

    fn no_new_privileges(mut self) -> Self {
        self.linux.no_new_privileges = true;
        self
    }

    fn parent_death_signal(mut self, signal: i32) -> Self {
        self.linux.parent_death_signal = Some(signal);
        self
    }
}

#[cfg(feature = "alloc")]
impl<'a> ConfineExt<'a> for Command<'a> {
    fn time_offsets(mut self, offsets: TimeOffsets) -> Self {
        self.linux.time_offsets = Some(offsets);
        self
    }

    fn bounding_set(mut self, keep: CapabilitySet) -> Self {
        self.linux.bounding = Some(keep);
        self
    }

    fn capabilities(mut self, capabilities: Capabilities) -> Self {
        self.linux.capabilities = Some(capabilities);
        self
    }

    fn ambient_capabilities(mut self, ambient: CapabilitySet) -> Self {
        self.linux.ambient = Some(ambient);
        self
    }

    fn seccomp(mut self, program: &'a [seccomp::Instruction], flags: seccomp::FilterFlags) -> Self {
        self.linux.seccomp = Some((program, flags));
        self.linux.seccomp_listener = false;
        self
    }

    fn seccomp_listener(
        mut self,
        program: &'a [seccomp::Instruction],
        flags: seccomp::FilterFlags,
    ) -> Self {
        self.linux.seccomp = Some((program, flags));
        self.linux.seccomp_listener = true;
        self
    }

    fn landlock(mut self, ruleset: BorrowedHandle<'a>) -> Self {
        self.linux.landlock = Some(ruleset);
        self
    }

    fn trace_me(mut self) -> Self {
        self.linux.trace_me = true;
        self
    }
}