cosca 0.10.0

Unified cross-platform subprocess management: spawning, stdio, process trees, stable identity, and elevation.
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
//! The walk of a leaf's descendant cgroups, on real cgroups: the cgroup lane (the `cgroup` group,
//! as root). Each test makes a scratch cgroup under the lane's own, and removes what it made.

use std::os::fd::{AsFd as _, OwnedFd};
use std::path::{Path, PathBuf};

use super::{cgroup_id, find_descendant, procs_under, Swept, Walked};
use crate::containment::cgroup::fault::fail_walk_step;
use crate::containment::cgroup::WalkStep;
use crate::test_groups::{cgroup, pidfd_get_info, Group};

/// A cgroup under the lane's own, removed with every cgroup made under it when dropped. Removal is
/// by `rmdir` alone, deepest first: nothing is deleted through a mount.
pub(crate) struct Scratch(PathBuf);

impl Scratch {
    pub(crate) fn new(tag: &str) -> Scratch {
        let own = std::fs::read_to_string("/proc/self/cgroup").expect("read /proc/self/cgroup");
        let own = own
            .lines()
            .find_map(|l| l.strip_prefix("0::/"))
            .expect("a unified line");
        let path = Path::new("/sys/fs/cgroup")
            .join(own)
            .join(format!("cosca-{}-{tag}", std::process::id()));
        std::fs::create_dir(&path).unwrap_or_else(|e| panic!("make {}: {e}", path.display()));
        Scratch(path)
    }

    pub(crate) fn path(&self) -> &Path {
        &self.0
    }

    /// Make the cgroup `rel` under the scratch cgroup, and its parents.
    pub(crate) fn make(&self, rel: &str) -> PathBuf {
        let path = self.0.join(rel);
        std::fs::create_dir_all(&path).unwrap_or_else(|e| panic!("make {}: {e}", path.display()));
        path
    }

    /// The scratch cgroup, held as the walk holds a leaf.
    pub(crate) fn fd(&self) -> OwnedFd {
        open_path(&self.0)
    }
}

impl Drop for Scratch {
    fn drop(&mut self) {
        let mut dirs = Vec::new();
        let mut pending = vec![self.0.clone()];
        while let Some(dir) = pending.pop() {
            if let Ok(entries) = std::fs::read_dir(&dir) {
                pending.extend(
                    entries
                        .flatten()
                        .filter(|e| e.file_type().is_ok_and(|t| t.is_dir()))
                        .map(|e| e.path()),
                );
            }
            dirs.push(dir);
        }
        for dir in dirs.iter().rev() {
            if let Err(e) = std::fs::remove_dir(dir) {
                if e.kind() != std::io::ErrorKind::NotFound && !std::thread::panicking() {
                    panic!("remove the scratch cgroup {}: {e}", dir.display());
                }
            }
        }
    }
}

/// A chain of cgroups, one inside the next, made level by level through held descriptors, as a
/// path to its bottom may exceed `PATH_MAX`. Removes what is left of it, deepest first, when
/// dropped.
pub(crate) struct DeepTree {
    root: OwnedFd,
    names: Vec<String>,
    /// `levels[0]` is the chain's first cgroup.
    levels: Vec<OwnedFd>,
}

impl DeepTree {
    /// `depth` levels, each named `name`.
    pub(crate) fn new(root: &OwnedFd, name: &str, depth: usize) -> DeepTree {
        DeepTree::with_names(root, vec![name.to_owned(); depth])
    }

    /// One level for each of `names`, outermost first.
    pub(crate) fn with_names(root: &OwnedFd, names: Vec<String>) -> DeepTree {
        use rustix::fs::{Mode, OFlags};
        let mut tree = DeepTree {
            root: rustix::io::fcntl_dupfd_cloexec(root, 3).expect("dup the root"),
            names,
            levels: Vec::new(),
        };
        for name in &tree.names.clone() {
            let parent = tree.levels.last().unwrap_or(&tree.root);
            rustix::fs::mkdirat(parent, name.as_str(), Mode::from_raw_mode(0o777)).expect("make a level");
            let level = rustix::fs::openat(
                parent,
                name.as_str(),
                OFlags::PATH | OFlags::DIRECTORY | OFlags::NOFOLLOW | OFlags::CLOEXEC,
                Mode::empty(),
            )
            .expect("hold a level");
            tree.levels.push(level);
        }
        tree
    }

    /// The deepest cgroup of the chain.
    pub(crate) fn bottom(&self) -> &OwnedFd {
        self.levels.last().expect("a chain with a level")
    }
}

impl Drop for DeepTree {
    fn drop(&mut self) {
        for i in (0..self.levels.len()).rev() {
            let parent = if i == 0 { &self.root } else { &self.levels[i - 1] };
            match rustix::fs::unlinkat(parent, self.names[i].as_str(), rustix::fs::AtFlags::REMOVEDIR) {
                Ok(()) | Err(rustix::io::Errno::NOENT) => {}
                Err(e) if std::thread::panicking() => eprintln!("remove a level of the chain: {e}"),
                Err(e) => panic!("remove a level of the chain: {e}"),
            }
        }
    }
}

pub(crate) fn open_path(path: &Path) -> OwnedFd {
    rustix::fs::open(
        path,
        rustix::fs::OFlags::PATH | rustix::fs::OFlags::DIRECTORY | rustix::fs::OFlags::CLOEXEC,
        rustix::fs::Mode::empty(),
    )
    .unwrap_or_else(|e| panic!("open {}: {e}", path.display()))
}

/// The cgroup id of the cgroup at `path`.
pub(crate) fn id_at(path: &Path) -> u64 {
    cgroup_id(open_path(path).as_fd()).unwrap_or_else(|e| panic!("the cgroup id of {}: {e}", path.display()))
}

/// A leaf's id is the cgroup id its members read through their pidfds (6.13 and later).
#[skuld::test]
fn cgroup_a_leaf_id_is_the_cgroup_id_its_members_read(
    #[fixture(cgroup)] _group: &Group,
    #[fixture(pidfd_get_info)] _info: &Group,
) {
    let own = std::fs::read_to_string("/proc/self/cgroup").expect("read /proc/self/cgroup");
    let own = own
        .lines()
        .find_map(|l| l.strip_prefix("0::/"))
        .expect("a unified line");
    let pidfd = rustix::process::pidfd_open(rustix::process::getpid(), rustix::process::PidfdFlags::empty())
        .expect("pidfd_open");
    let read = crate::containment::cgroup::pidfd_cgroup_id(pidfd.as_fd())
        .expect("PIDFD_GET_INFO")
        .expect("the pidfd_get_info group promised a kernel that answers PIDFD_GET_INFO");
    assert_eq!(id_at(&Path::new("/sys/fs/cgroup").join(own)), read);
}

/// The walk finds a cgroup at any depth under its root, and neither the root itself nor a cgroup
/// elsewhere. It needs no recursion: a chain 200 deep is walked.
#[skuld::test]
fn cgroup_the_walk_finds_a_cgroup_at_any_depth_and_only_under_its_root(#[fixture(cgroup)] _group: &Group) {
    let scratch = Scratch::new("walk-depth");
    let deep: String = ["d"; 200].join("/");
    let found = [scratch.make(&deep), scratch.make("wide/x"), scratch.path().join("wide")];
    let root = scratch.fd();
    for path in &found {
        assert!(
            matches!(find_descendant(root.as_fd(), id_at(path)), Walked::Found),
            "{}",
            path.display()
        );
    }
    let elsewhere = scratch.path().parent().expect("the lane's cgroup");
    for path in [scratch.path(), elsewhere] {
        let walked = find_descendant(root.as_fd(), id_at(path));
        assert!(matches!(walked, Walked::Absent), "{}: {walked:?}", path.display());
    }
}

/// A tree whose path to the bottom is longer than `PATH_MAX` is walked whole: the walk finds the
/// bottom, and answers `Absent` for a cgroup that is not there, never `Unknown`. It holds the
/// descriptors it held before the walk each time it is about to open a cgroup. Mutant: "a path past
/// `PATH_MAX` is opened in one piece".
#[skuld::test]
fn cgroup_the_walk_of_a_path_longer_than_path_max_finds_the_bottom(#[fixture(cgroup)] _group: &Group) {
    let scratch = Scratch::new("walk-long");
    let root = scratch.fd();
    let chain = DeepTree::new(&root, &"n".repeat(200), 30);
    let bottom = cgroup_id(chain.bottom().as_fd()).expect("the bottom's id");
    let open_fds = || std::fs::read_dir("/proc/self/fd").expect("list fds").count();
    let before = open_fds();
    let counts = std::rc::Rc::new(std::cell::RefCell::new(Vec::new()));
    let _hook = crate::containment::cgroup::fault::set_before_walk_open({
        let counts = std::rc::Rc::clone(&counts);
        move |_| counts.borrow_mut().push(open_fds())
    });
    let walked = find_descendant(root.as_fd(), bottom);
    assert!(matches!(walked, Walked::Found), "{walked:?}");
    let walked = find_descendant(root.as_fd(), 1);
    assert!(matches!(walked, Walked::Absent), "{walked:?}");
    let counts = counts.borrow();
    assert_eq!(counts.len(), 31 + 31, "the walk visits every cgroup once");
    assert!(
        counts.iter().all(|&n| n == before),
        "{before} before the walk, then {counts:?}"
    );
}

/// A cgroup removed during the walk is skipped: what was under it is not found, and the rest is.
#[skuld::test]
fn cgroup_the_walk_skips_a_cgroup_removed_mid_walk(#[fixture(cgroup)] _group: &Group) {
    let scratch = Scratch::new("walk-removed");
    let target = id_at(&scratch.make("kept/target"));
    let root = scratch.fd();
    // Removes `gone` as the walk is about to open it, and says whether it did.
    let removing = || {
        let under = scratch.make("gone/under");
        let id = id_at(&under);
        let gone = scratch.path().join("gone");
        let removed = std::rc::Rc::new(std::cell::Cell::new(false));
        let hook = crate::containment::cgroup::fault::set_before_walk_open({
            let removed = std::rc::Rc::clone(&removed);
            move |path| {
                if path == Path::new("./gone") {
                    std::fs::remove_dir(gone.join("under")).expect("remove `gone/under` mid-walk");
                    std::fs::remove_dir(&gone).expect("remove `gone` mid-walk");
                    removed.set(true);
                }
            }
        });
        (hook, removed, id)
    };
    let (hook, removed, _) = removing();
    assert!(matches!(find_descendant(root.as_fd(), target), Walked::Found));
    assert!(
        removed.get(),
        "the walk reached `gone` before it found the target, and skipped it once removed"
    );
    drop(hook);
    let (_hook, removed, under) = removing();
    let walked = find_descendant(root.as_fd(), under);
    assert!(matches!(walked, Walked::Absent), "{walked:?}");
    assert!(removed.get(), "the walk reached `gone`, and skipped it once removed");
}

/// A listing of the cgroups under a root records the id of every cgroup it visits, however deep, in
/// the set it is given, and not the root's own. Mutant: only the cgroups whose `cgroup.procs` lists
/// a member are recorded.
#[skuld::test]
fn cgroup_a_listing_records_the_id_of_every_cgroup_it_visits(#[fixture(cgroup)] _group: &Group) {
    let scratch = Scratch::new("list-ids");
    let ids: Vec<_> = ["a", "a/b", "c"].map(|rel| id_at(&scratch.make(rel))).into();
    let known = Swept::default();

    let (lines, failure) = procs_under(scratch.fd().as_fd(), &known);

    assert!(failure.is_none(), "{failure:?}");
    assert_eq!(lines, Vec::<String>::new(), "no member");
    assert!(
        ids.iter().all(|&id| known.holds(id)),
        "every cgroup visited is recorded"
    );
    assert!(!known.holds(id_at(scratch.path())), "the root is not under itself");
}

/// A cgroup whose id read finds it gone is skipped with what is under it: it is no member's place,
/// and is not recorded. Mutant: a gone cgroup ends the listing, or its children are visited.
#[skuld::test]
fn cgroup_a_cgroup_gone_at_its_id_read_is_skipped_with_what_is_under_it(#[fixture(cgroup)] _group: &Group) {
    let scratch = Scratch::new("list-gone");
    let a = id_at(&scratch.make("a"));
    let under = id_at(&scratch.make("a/b"));
    let c = id_at(&scratch.make("c"));
    let known = Swept::default();
    let _gone = fail_walk_step("./a", WalkStep::Id, libc::ENOENT);

    let (_, failure) = procs_under(scratch.fd().as_fd(), &known);

    assert!(failure.is_none(), "{failure:?}");
    assert!(
        !known.holds(a) && !known.holds(under),
        "the gone cgroup and what is under it"
    );
    assert!(known.holds(c), "the listing went on");
}

/// A cgroup whose id cannot be read is left out of the set and fails nothing: what is under it is
/// listed and recorded. Mutant: an unreadable id ends the listing.
#[skuld::test]
fn cgroup_a_cgroup_whose_id_cannot_be_read_is_left_out_of_the_set_alone(#[fixture(cgroup)] _group: &Group) {
    let scratch = Scratch::new("list-unreadable");
    let a = id_at(&scratch.make("a"));
    let under = id_at(&scratch.make("a/b"));
    let known = Swept::default();
    let _refused = fail_walk_step("./a", WalkStep::Id, libc::EIO);

    let (_, failure) = procs_under(scratch.fd().as_fd(), &known);

    assert!(failure.is_none(), "{failure:?}");
    assert!(!known.holds(a), "an id that could not be read");
    assert!(known.holds(under), "what is under it is recorded");
}

/// A root removed before the walk lists anything leaves nothing listed, so nothing is known of the
/// cgroup sought: `Unknown`, never `Absent`. Mutant: "a gone root is skipped like any gone cgroup".
#[skuld::test]
fn cgroup_a_walk_of_a_removed_root_cannot_tell(#[fixture(cgroup)] _group: &Group) {
    let scratch = Scratch::new("walk-gone-root");
    let root = scratch.fd();
    std::fs::remove_dir(scratch.path()).expect("remove the root");
    let walked = find_descendant(root.as_fd(), 1);
    assert!(matches!(walked, Walked::Unknown(_)), "{walked:?}");
}

/// The same for a root that goes at any step: nothing, or not everything, of it was listed.
/// Mutant: as above.
#[skuld::test]
fn cgroup_a_walk_of_a_root_gone_at_any_step_cannot_tell(#[fixture(cgroup)] _group: &Group) {
    let scratch = Scratch::new("walk-gone-root-steps");
    scratch.make("under");
    let root = scratch.fd();
    for step in [WalkStep::Open, WalkStep::List, WalkStep::Entries, WalkStep::Alive] {
        for errno in [libc::ENOENT, libc::ENODEV] {
            let _failing = fail_walk_step(".", step, errno);
            let walked = find_descendant(root.as_fd(), 1);
            assert!(matches!(walked, Walked::Unknown(_)), "{step:?} {errno}: {walked:?}");
        }
    }
}

/// A refusal the walk cannot get past (`EACCES` from a cgroup this process may not read, or `EIO`)
/// is `Unknown`, never `Absent`, at any step, and the error keeps its `errno`. Mutants: "the refusal
/// is skipped like a removed cgroup"; "the error is rebuilt without its `errno`".
#[skuld::test]
fn cgroup_a_walk_that_is_refused_cannot_tell(#[fixture(cgroup)] _group: &Group) {
    let scratch = Scratch::new("walk-refused");
    scratch.make("a/b");
    let root = scratch.fd();
    for step in [WalkStep::Open, WalkStep::Id, WalkStep::List, WalkStep::Entries] {
        for errno in [libc::EIO, libc::EACCES] {
            let _failing = fail_walk_step("./a", step, errno);
            let walked = find_descendant(root.as_fd(), 1);
            match walked {
                Walked::Unknown(e) => assert_eq!(e.raw_os_error(), Some(errno), "{step:?} {errno}: {e}"),
                other => panic!("{step:?} {errno}: {other:?}"),
            }
        }
    }
}

/// A cgroup that is gone at a step after the walk's open of it (its id read, the open for its
/// listing, its `getdents`) is skipped, as one gone at the open is: the rest of the tree is still
/// searched. Mutant: "a gone cgroup after the open is an error".
#[skuld::test]
fn cgroup_a_walk_skips_a_cgroup_gone_after_its_open(#[fixture(cgroup)] _group: &Group) {
    let scratch = Scratch::new("walk-gone-late");
    scratch.make("a");
    let target = id_at(&scratch.make("z/target"));
    let root = scratch.fd();
    for step in [WalkStep::Id, WalkStep::List, WalkStep::Entries] {
        for errno in [libc::ENODEV, libc::ENOENT] {
            let _failing = fail_walk_step("./a", step, errno);
            let walked = find_descendant(root.as_fd(), target);
            assert!(matches!(walked, Walked::Found), "{step:?} {errno}: {walked:?}");
            let walked = find_descendant(root.as_fd(), 1);
            assert!(matches!(walked, Walked::Absent), "{step:?} {errno}: {walked:?}");
        }
    }
}

/// The walk holds no descriptor from one cgroup to the next, however wide or deep the tree: each
/// time it is about to open a cgroup, this process holds the descriptors it held before the walk.
#[skuld::test]
fn cgroup_the_walk_holds_no_descriptor_between_cgroups(#[fixture(cgroup)] _group: &Group) {
    let scratch = Scratch::new("walk-fds");
    for i in 0..20 {
        scratch.make(&format!("w{i}/{}", ["d"; 10].join("/")));
    }
    let root = scratch.fd();
    let open_fds = || std::fs::read_dir("/proc/self/fd").expect("list fds").count();
    let before = open_fds();
    let counts = std::rc::Rc::new(std::cell::RefCell::new(Vec::new()));
    let _hook = crate::containment::cgroup::fault::set_before_walk_open({
        let counts = std::rc::Rc::clone(&counts);
        move |_| counts.borrow_mut().push(open_fds())
    });
    let walked = find_descendant(root.as_fd(), 0);
    assert!(matches!(walked, Walked::Absent), "{walked:?}");
    let counts = counts.borrow();
    assert_eq!(counts.len(), 1 + 20 * 11, "the walk visits every cgroup once");
    assert!(
        counts.iter().all(|&n| n == before),
        "{before} before the walk, then {counts:?}"
    );
}

/// A walk that fails at a later entry of a listing than the first, after cgroups were queued from
/// the entries before it, cannot tell: `Unknown`, not the target of a queued cgroup, and not
/// `Absent`. Mutant: "the entries fault fires at the first entry only".
#[skuld::test]
fn cgroup_a_walk_that_fails_after_entries_were_queued_cannot_tell(#[fixture(cgroup)] _group: &Group) {
    let scratch = Scratch::new("walk-late-entry");
    let queued = id_at(&scratch.make("a/x"));
    scratch.make("b");
    let root = scratch.fd();
    // Entries of the root: `.`, `..`, and what `read_dir` lists; the last of them is the one to fail.
    let entries = std::fs::read_dir(scratch.path()).expect("list the root").count() + 2;
    let failing =
        crate::containment::cgroup::fault::fail_walk_step_after(".", WalkStep::Entries, libc::EIO, entries - 1);
    match find_descendant(root.as_fd(), queued) {
        Walked::Unknown(e) => assert_eq!(e.raw_os_error(), Some(libc::EIO), "{e}"),
        other => panic!("{other:?}"),
    }
    drop(failing);
    let _past = crate::containment::cgroup::fault::fail_walk_step_after(".", WalkStep::Entries, libc::EIO, entries);
    let walked = find_descendant(root.as_fd(), queued);
    assert!(matches!(walked, Walked::Found), "no entry past the last: {walked:?}");
}

/// A cgroup behind a mount cannot be listed, so a walk that meets one cannot tell what is under
/// it: it answers `Unknown`, never `Absent`, whether the cgroup sought is behind the mount or
/// nowhere. The walking thread has its own mount namespace, the mount's, in which it holds the
/// leaf, as a process holds its leaves in its own; the mount is gone with the thread.
#[skuld::test]
fn cgroup_the_walk_cannot_tell_behind_a_mount(#[fixture(cgroup)] _group: &Group) {
    let scratch = Scratch::new("walk-mount");
    let hidden = id_at(&scratch.make("sub/x"));
    let elsewhere = id_at(scratch.path().parent().expect("the lane's cgroup"));
    let sub = scratch.path().join("sub");
    let walked = std::thread::scope(|scope| {
        scope
            .spawn(|| {
                enter_private_mount_ns();
                let root = scratch.fd();
                let _mounted = TmpfsOver::new(&sub);
                [hidden, elsewhere].map(|id| find_descendant(root.as_fd(), id))
            })
            .join()
            .expect("the walking thread")
    });
    for walked in walked {
        match walked {
            Walked::Unknown(e) => assert_eq!(e.raw_os_error(), Some(libc::EXDEV), "{e}"),
            other => panic!("{other:?}"),
        }
    }
    let root = scratch.fd();
    assert!(matches!(find_descendant(root.as_fd(), hidden), Walked::Found));
}

/// Give this thread its own private mount namespace: a mount made in it stays in it, and goes with
/// the thread.
pub(crate) fn enter_private_mount_ns() {
    let root = std::ffi::CString::new("/").expect("no NUL");
    // SAFETY: plain syscalls on a valid NUL-terminated string. `unshare` gives this thread alone a
    // mount namespace; making it private keeps what is mounted in it there.
    unsafe {
        assert_eq!(
            libc::unshare(libc::CLONE_NEWNS),
            0,
            "unshare: {}",
            std::io::Error::last_os_error()
        );
        assert_eq!(
            libc::mount(
                std::ptr::null(),
                root.as_ptr(),
                std::ptr::null(),
                libc::MS_REC | libc::MS_PRIVATE,
                std::ptr::null()
            ),
            0,
            "make / private: {}",
            std::io::Error::last_os_error()
        );
    }
}

/// A tmpfs mounted over a directory, unmounted when dropped. Made only in a thread that called
/// [`enter_private_mount_ns`]. A failed unmount panics: nothing is removed through a mount.
pub(crate) struct TmpfsOver(std::ffi::CString);

impl TmpfsOver {
    pub(crate) fn new(target: &Path) -> TmpfsOver {
        let target = std::ffi::CString::new(target.as_os_str().as_encoded_bytes()).expect("no NUL");
        // SAFETY: `mount` on valid NUL-terminated strings.
        let rc = unsafe {
            libc::mount(
                c"none".as_ptr(),
                target.as_ptr(),
                c"tmpfs".as_ptr(),
                0,
                std::ptr::null(),
            )
        };
        assert_eq!(
            rc,
            0,
            "mount a tmpfs over the cgroup: {}",
            std::io::Error::last_os_error()
        );
        TmpfsOver(target)
    }
}

impl Drop for TmpfsOver {
    fn drop(&mut self) {
        // SAFETY: `umount2` on a valid NUL-terminated string.
        let rc = unsafe { libc::umount2(self.0.as_ptr(), 0) };
        assert_eq!(rc, 0, "unmount the tmpfs: {}", std::io::Error::last_os_error());
    }
}