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
//! `fs::linux`: mounting, unmounting and the root directory.
//!
//! The constants are those of `include/uapi/linux/mount.h` and
//! `include/linux/fs.h`, which every architecture shares.

use core::ffi::c_char;

use crate::fs::linux::{
    FsConfig, FsPickFlags, ListMountFlags, MountAttributes, MountFlags, MountSetAttr,
    MountSetAttrFlags, MoveMountFlags, OpenTreeFlags, Propagation, StatMountFields, UnmountFlags,
};
use crate::path::with_cstr;
use crate::sys::syscall;
use crate::{BorrowedHandle, ErrorKind, OwnedHandle, Result};

const MS_RDONLY: usize = 1;
const MS_NOSUID: usize = 2;
const MS_NODEV: usize = 4;
const MS_NOEXEC: usize = 8;
const MS_SYNCHRONOUS: usize = 16;
const MS_REMOUNT: usize = 32;
const MS_DIRSYNC: usize = 128;
const MS_NOSYMFOLLOW: usize = 256;
const MS_NOATIME: usize = 1024;
const MS_NODIRATIME: usize = 2048;
const MS_BIND: usize = 4096;
const MS_MOVE: usize = 8192;
const MS_REC: usize = 16384;
const MS_SILENT: usize = 32768;
const MS_UNBINDABLE: usize = 1 << 17;
const MS_PRIVATE: usize = 1 << 18;
const MS_SLAVE: usize = 1 << 19;
const MS_SHARED: usize = 1 << 20;
const MS_RELATIME: usize = 1 << 21;
const MS_STRICTATIME: usize = 1 << 24;
const MS_LAZYTIME: usize = 1 << 25;

const MNT_FORCE: usize = 1;
const MNT_DETACH: usize = 2;
const MNT_EXPIRE: usize = 4;
const UMOUNT_NOFOLLOW: usize = 8;

/// The `MS_*` flags of `flags`.
fn mount_flags(flags: MountFlags) -> usize {
    let table = [
        (MountFlags::READ_ONLY, MS_RDONLY),
        (MountFlags::NO_SUID, MS_NOSUID),
        (MountFlags::NO_DEV, MS_NODEV),
        (MountFlags::NO_EXEC, MS_NOEXEC),
        (MountFlags::SYNCHRONOUS, MS_SYNCHRONOUS),
        (MountFlags::DIR_SYNC, MS_DIRSYNC),
        (MountFlags::NO_SYMLINK_FOLLOW, MS_NOSYMFOLLOW),
        (MountFlags::NO_ATIME, MS_NOATIME),
        (MountFlags::NO_DIR_ATIME, MS_NODIRATIME),
        (MountFlags::REL_ATIME, MS_RELATIME),
        (MountFlags::STRICT_ATIME, MS_STRICTATIME),
        (MountFlags::LAZY_TIME, MS_LAZYTIME),
        (MountFlags::SILENT, MS_SILENT),
    ];
    let mut raw = 0;
    for (flag, value) in table {
        if flags.contains(flag) {
            raw |= value;
        }
    }
    raw
}

/// Calls `f` with `text` as a C string, or with a null pointer if it is
/// empty: what `mount` takes for an argument it is to ignore.
fn with_optional<R>(text: &[u8], f: impl FnOnce(*const c_char) -> Result<R>) -> Result<R> {
    if text.is_empty() {
        f(core::ptr::null())
    } else {
        with_cstr(text, |text| f(text.as_ptr()))
    }
}

/// `mount(source, target, fstype, flags, data)`, an empty string being no
/// argument, except for the target.
fn mount_raw(source: &[u8], target: &[u8], fstype: &[u8], flags: usize, data: &[u8]) -> Result<()> {
    with_cstr(target, |target| {
        with_optional(source, |source| {
            with_optional(fstype, |fstype| {
                with_optional(data, |data| {
                    // SAFETY: each pointer is null or a NUL-terminated
                    // string, which is what the kernel reads of all four
                    // (the data of the filesystems that take a structure
                    // is not something this function is given).
                    unsafe { syscall!(MOUNT, source, target.as_ptr(), fstype, flags, data) }
                        .map(drop)
                })
            })
        })
    })
}

pub(crate) fn mount(
    source: &[u8],
    target: &[u8],
    fstype: &[u8],
    flags: MountFlags,
    data: &[u8],
) -> Result<()> {
    // Without a type the kernel would take the call for something else,
    // or for nothing.
    if fstype.is_empty() {
        return Err(ErrorKind::InvalidInput.into());
    }
    mount_raw(source, target, fstype, mount_flags(flags), data)
}

pub(crate) fn bind(source: &[u8], target: &[u8], recursive: bool) -> Result<()> {
    let flags = MS_BIND | if recursive { MS_REC } else { 0 };
    mount_raw(source, target, b"", flags, b"")
}

pub(crate) fn remount(target: &[u8], flags: MountFlags, data: &[u8]) -> Result<()> {
    mount_raw(b"", target, b"", MS_REMOUNT | mount_flags(flags), data)
}

pub(crate) fn remount_bind(target: &[u8], flags: MountFlags) -> Result<()> {
    let flags = MS_REMOUNT | MS_BIND | mount_flags(flags);
    mount_raw(b"", target, b"", flags, b"")
}

/// The `MS_*` flag of `propagation`.
fn propagation_flag(propagation: Propagation) -> usize {
    match propagation {
        Propagation::Private => MS_PRIVATE,
        Propagation::Slave => MS_SLAVE,
        Propagation::Shared => MS_SHARED,
        Propagation::Unbindable => MS_UNBINDABLE,
    }
}

pub(crate) fn set_propagation(
    target: &[u8],
    propagation: Propagation,
    recursive: bool,
) -> Result<()> {
    let kind = propagation_flag(propagation);
    let flags = kind | if recursive { MS_REC } else { 0 };
    mount_raw(b"", target, b"", flags, b"")
}

pub(crate) fn move_mount(from: &[u8], to: &[u8]) -> Result<()> {
    mount_raw(from, to, b"", MS_MOVE, b"")
}

pub(crate) fn unmount(target: &[u8], flags: UnmountFlags) -> Result<()> {
    let table = [
        (UnmountFlags::FORCE, MNT_FORCE),
        (UnmountFlags::DETACH, MNT_DETACH),
        (UnmountFlags::EXPIRE, MNT_EXPIRE),
        (UnmountFlags::NO_FOLLOW, UMOUNT_NOFOLLOW),
    ];
    let mut raw = 0;
    for (flag, value) in table {
        if flags.contains(flag) {
            raw |= value;
        }
    }
    with_cstr(target, |target| {
        // SAFETY: `target` is a NUL-terminated string.
        unsafe { syscall!(UMOUNT2, target.as_ptr(), raw) }.map(drop)
    })
}

pub(crate) fn pivot_root(new_root: &[u8], put_old: &[u8]) -> Result<()> {
    with_cstr(new_root, |new_root| {
        with_cstr(put_old, |put_old| {
            // SAFETY: both paths are NUL-terminated strings.
            unsafe { syscall!(PIVOT_ROOT, new_root.as_ptr(), put_old.as_ptr()) }.map(drop)
        })
    })
}

pub(crate) fn chroot(path: &[u8]) -> Result<()> {
    with_cstr(path, |path| {
        // SAFETY: `path` is a NUL-terminated string.
        unsafe { syscall!(CHROOT, path.as_ptr()) }.map(drop)
    })
}

// The mount API of Linux 5.2, and `mount_setattr` of 5.12.

const AT_FDCWD: i32 = -100;
const AT_SYMLINK_NOFOLLOW: usize = 0x100;
const AT_NO_AUTOMOUNT: usize = 0x800;
const AT_EMPTY_PATH: usize = 0x1000;
const AT_RECURSIVE: usize = 0x8000;
/// The same on every architecture.
const O_CLOEXEC: usize = 0o2000000;

const FSOPEN_CLOEXEC: usize = 1;
const FSMOUNT_CLOEXEC: usize = 1;
const FSPICK_CLOEXEC: usize = 1;
const FSPICK_SYMLINK_NOFOLLOW: usize = 2;
const FSPICK_NO_AUTOMOUNT: usize = 4;
const FSPICK_EMPTY_PATH: usize = 8;

const FSCONFIG_SET_FLAG: usize = 0;
const FSCONFIG_SET_STRING: usize = 1;
const FSCONFIG_SET_BINARY: usize = 2;
const FSCONFIG_SET_PATH: usize = 3;
const FSCONFIG_SET_PATH_EMPTY: usize = 4;
const FSCONFIG_SET_FD: usize = 5;
const FSCONFIG_CMD_CREATE: usize = 6;
const FSCONFIG_CMD_RECONFIGURE: usize = 7;
const FSCONFIG_CMD_CREATE_EXCL: usize = 8;

const OPEN_TREE_CLONE: usize = 1;
const OPEN_TREE_CLOEXEC: usize = O_CLOEXEC;

const MOVE_MOUNT_F_SYMLINKS: usize = 0x1;
const MOVE_MOUNT_F_AUTOMOUNTS: usize = 0x2;
const MOVE_MOUNT_F_EMPTY_PATH: usize = 0x4;
const MOVE_MOUNT_T_SYMLINKS: usize = 0x10;
const MOVE_MOUNT_T_AUTOMOUNTS: usize = 0x20;
const MOVE_MOUNT_T_EMPTY_PATH: usize = 0x40;
const MOVE_MOUNT_SET_GROUP: usize = 0x100;
const MOVE_MOUNT_BENEATH: usize = 0x200;

const MOUNT_ATTR_RDONLY: u64 = 0x1;
const MOUNT_ATTR_NOSUID: u64 = 0x2;
const MOUNT_ATTR_NODEV: u64 = 0x4;
const MOUNT_ATTR_NOEXEC: u64 = 0x8;
/// The three bits that say how access times are kept: one value, of
/// which "relative" is 0.
const MOUNT_ATTR_ATIME: u64 = 0x70;
const MOUNT_ATTR_NOATIME: u64 = 0x10;
const MOUNT_ATTR_STRICTATIME: u64 = 0x20;
const MOUNT_ATTR_NODIRATIME: u64 = 0x80;
const MOUNT_ATTR_IDMAP: u64 = 0x10_0000;
const MOUNT_ATTR_NOSYMFOLLOW: u64 = 0x20_0000;

/// `struct mount_attr`, as of Linux 5.12 (`MOUNT_ATTR_SIZE_VER0`): four
/// 64-bit numbers, laid out the same on every architecture.
#[repr(C)]
struct MountAttr {
    attr_set: u64,
    attr_clr: u64,
    propagation: u64,
    userns_fd: u64,
}

const _: () = assert!(size_of::<MountAttr>() == 32);

/// The descriptor a path is relative to.
fn dir_fd(dir: Option<BorrowedHandle<'_>>) -> i32 {
    dir.map_or(AT_FDCWD, |dir| dir.as_raw())
}

/// The bits of `flags` that `table` names.
fn translate<F: Copy, R: Copy + core::ops::BitOr<Output = R>>(
    zero: R,
    table: &[(F, R)],
    has: impl Fn(F) -> bool,
) -> R {
    let mut raw = zero;
    for &(flag, value) in table {
        if has(flag) {
            raw = raw | value;
        }
    }
    raw
}

/// The `MOUNT_ATTR_*` bits of `attributes`, and whether they say how
/// access times are kept.
fn attribute_bits(attributes: MountAttributes) -> (u64, bool) {
    let table = [
        (MountAttributes::READ_ONLY, MOUNT_ATTR_RDONLY),
        (MountAttributes::NO_SUID, MOUNT_ATTR_NOSUID),
        (MountAttributes::NO_DEV, MOUNT_ATTR_NODEV),
        (MountAttributes::NO_EXEC, MOUNT_ATTR_NOEXEC),
        (MountAttributes::NO_ATIME, MOUNT_ATTR_NOATIME),
        (MountAttributes::STRICT_ATIME, MOUNT_ATTR_STRICTATIME),
        (MountAttributes::NO_DIR_ATIME, MOUNT_ATTR_NODIRATIME),
        (MountAttributes::NO_SYMLINK_FOLLOW, MOUNT_ATTR_NOSYMFOLLOW),
    ];
    let bits = translate(0, &table, |flag| attributes.contains(flag));
    let times =
        MountAttributes::NO_ATIME | MountAttributes::STRICT_ATIME | MountAttributes::REL_ATIME;
    (bits, attributes.intersects(times))
}

/// A descriptor the kernel has just created.
fn new_handle(fd: usize) -> OwnedHandle {
    // SAFETY: the descriptor was just created, close-on-exec, for us.
    unsafe { OwnedHandle::from_raw(fd as i32) }
}

pub(crate) fn fsopen(fstype: &[u8]) -> Result<OwnedHandle> {
    with_cstr(fstype, |fstype| {
        // SAFETY: the name is a NUL-terminated string.
        unsafe { syscall!(FSOPEN, fstype.as_ptr(), FSOPEN_CLOEXEC) }.map(new_handle)
    })
}

pub(crate) fn fsconfig(fs: BorrowedHandle<'_>, command: &FsConfig<'_>) -> Result<()> {
    let fd = fs.as_raw();
    let null = core::ptr::null::<u8>();
    match *command {
        FsConfig::SetFlag(key) => with_cstr(key.as_bytes(), |key| {
            // SAFETY: the key is a NUL-terminated string.
            unsafe { syscall!(FSCONFIG, fd, FSCONFIG_SET_FLAG, key.as_ptr(), null, 0) }.map(drop)
        }),
        FsConfig::SetString(key, value) => with_cstr(key.as_bytes(), |key| {
            with_cstr(value.as_bytes(), |value| {
                let (key, value) = (key.as_ptr(), value.as_ptr());
                // SAFETY: both are NUL-terminated strings.
                unsafe { syscall!(FSCONFIG, fd, FSCONFIG_SET_STRING, key, value, 0) }.map(drop)
            })
        }),
        FsConfig::SetBinary(key, value) => with_cstr(key.as_bytes(), |key| {
            let (key, data, len) = (key.as_ptr(), value.as_ptr(), value.len());
            // SAFETY: the key is a NUL-terminated string, and the kernel
            // reads `len` bytes of `value`.
            unsafe { syscall!(FSCONFIG, fd, FSCONFIG_SET_BINARY, key, data, len) }.map(drop)
        }),
        FsConfig::SetHandle(key, handle) => with_cstr(key.as_bytes(), |key| {
            let (key, handle) = (key.as_ptr(), handle.as_raw());
            // SAFETY: the key is a NUL-terminated string.
            unsafe { syscall!(FSCONFIG, fd, FSCONFIG_SET_FD, key, null, handle) }.map(drop)
        }),
        // SAFETY: no memory is involved.
        FsConfig::Create => {
            unsafe { syscall!(FSCONFIG, fd, FSCONFIG_CMD_CREATE, null, null, 0) }.map(drop)
        }
        FsConfig::Reconfigure => {
            // SAFETY: no memory is involved.
            unsafe { syscall!(FSCONFIG, fd, FSCONFIG_CMD_RECONFIGURE, null, null, 0) }.map(drop)
        }
        FsConfig::SetPath(key, dir, path) => with_cstr(key.as_bytes(), |key| {
            with_cstr(path, |path| {
                let (key, path, dir) = (key.as_ptr(), path.as_ptr(), dir_fd(dir));
                // SAFETY: both are NUL-terminated strings.
                unsafe { syscall!(FSCONFIG, fd, FSCONFIG_SET_PATH, key, path, dir) }.map(drop)
            })
        }),
        FsConfig::SetPathEmpty(key, handle) => with_cstr(key.as_bytes(), |key| {
            let (key, empty, handle) = (key.as_ptr(), c"".as_ptr(), handle.as_raw());
            // SAFETY: both are NUL-terminated strings.
            unsafe { syscall!(FSCONFIG, fd, FSCONFIG_SET_PATH_EMPTY, key, empty, handle) }.map(drop)
        }),
        FsConfig::CreateExclusive => {
            // SAFETY: no memory is involved.
            unsafe { syscall!(FSCONFIG, fd, FSCONFIG_CMD_CREATE_EXCL, null, null, 0) }.map(drop)
        }
    }
}

pub(crate) fn fsmount(fs: BorrowedHandle<'_>, attributes: MountAttributes) -> Result<OwnedHandle> {
    let (attributes, _) = attribute_bits(attributes);
    // SAFETY: no memory is involved.
    unsafe { syscall!(FSMOUNT, fs.as_raw(), FSMOUNT_CLOEXEC, attributes as usize) }.map(new_handle)
}

pub(crate) fn fspick(
    dir: Option<BorrowedHandle<'_>>,
    path: &[u8],
    flags: FsPickFlags,
) -> Result<OwnedHandle> {
    let table = [
        (FsPickFlags::NO_FOLLOW, FSPICK_SYMLINK_NOFOLLOW),
        (FsPickFlags::NO_AUTOMOUNT, FSPICK_NO_AUTOMOUNT),
        (FsPickFlags::EMPTY_PATH, FSPICK_EMPTY_PATH),
    ];
    let flags = translate(FSPICK_CLOEXEC, &table, |flag| flags.contains(flag));
    with_cstr(path, |path| {
        // SAFETY: the path is a NUL-terminated string.
        unsafe { syscall!(FSPICK, dir_fd(dir), path.as_ptr(), flags) }.map(new_handle)
    })
}

/// The flags of `open_tree` for `flags`, close-on-exec.
fn open_tree_flags(flags: OpenTreeFlags) -> usize {
    let table = [
        (OpenTreeFlags::CLONE, OPEN_TREE_CLONE),
        (OpenTreeFlags::RECURSIVE, AT_RECURSIVE),
        (OpenTreeFlags::EMPTY_PATH, AT_EMPTY_PATH),
        (OpenTreeFlags::NO_FOLLOW, AT_SYMLINK_NOFOLLOW),
        (OpenTreeFlags::NO_AUTOMOUNT, AT_NO_AUTOMOUNT),
    ];
    translate(OPEN_TREE_CLOEXEC, &table, |flag| flags.contains(flag))
}

pub(crate) fn open_tree(
    dir: Option<BorrowedHandle<'_>>,
    path: &[u8],
    flags: OpenTreeFlags,
) -> Result<OwnedHandle> {
    let flags = open_tree_flags(flags);
    with_cstr(path, |path| {
        // SAFETY: the path is a NUL-terminated string.
        unsafe { syscall!(OPEN_TREE, dir_fd(dir), path.as_ptr(), flags) }.map(new_handle)
    })
}

pub(crate) fn move_mount_at(
    from_dir: Option<BorrowedHandle<'_>>,
    from: &[u8],
    to_dir: Option<BorrowedHandle<'_>>,
    to: &[u8],
    flags: MoveMountFlags,
) -> Result<()> {
    let table = [
        (MoveMountFlags::FROM_SYMLINKS, MOVE_MOUNT_F_SYMLINKS),
        (MoveMountFlags::FROM_AUTOMOUNTS, MOVE_MOUNT_F_AUTOMOUNTS),
        (MoveMountFlags::FROM_EMPTY_PATH, MOVE_MOUNT_F_EMPTY_PATH),
        (MoveMountFlags::TO_SYMLINKS, MOVE_MOUNT_T_SYMLINKS),
        (MoveMountFlags::TO_AUTOMOUNTS, MOVE_MOUNT_T_AUTOMOUNTS),
        (MoveMountFlags::TO_EMPTY_PATH, MOVE_MOUNT_T_EMPTY_PATH),
        (MoveMountFlags::SET_GROUP, MOVE_MOUNT_SET_GROUP),
        (MoveMountFlags::BENEATH, MOVE_MOUNT_BENEATH),
    ];
    let flags = translate(0, &table, |flag| flags.contains(flag));
    with_cstr(from, |from| {
        with_cstr(to, |to| {
            let (from_dir, to_dir) = (dir_fd(from_dir), dir_fd(to_dir));
            // SAFETY: both paths are NUL-terminated strings.
            unsafe {
                syscall!(
                    MOVE_MOUNT,
                    from_dir,
                    from.as_ptr(),
                    to_dir,
                    to.as_ptr(),
                    flags
                )
            }
            .map(drop)
        })
    })
}

pub(crate) fn mount_setattr(
    dir: Option<BorrowedHandle<'_>>,
    path: &[u8],
    flags: MountSetAttrFlags,
    change: &MountSetAttr<'_>,
) -> Result<()> {
    let table = [
        (MountSetAttrFlags::RECURSIVE, AT_RECURSIVE),
        (MountSetAttrFlags::EMPTY_PATH, AT_EMPTY_PATH),
        (MountSetAttrFlags::NO_FOLLOW, AT_SYMLINK_NOFOLLOW),
        (MountSetAttrFlags::NO_AUTOMOUNT, AT_NO_AUTOMOUNT),
    ];
    let flags = translate(0, &table, |flag| flags.contains(flag));
    let attr = mount_attr(change)?;
    with_cstr(path, |path| {
        let (path, attr, size) = (path.as_ptr(), &raw const attr, size_of::<MountAttr>());
        // SAFETY: the path is a NUL-terminated string, and the kernel
        // reads `size` bytes of the structure.
        unsafe { syscall!(MOUNT_SETATTR, dir_fd(dir), path, flags, attr, size) }.map(drop)
    })
}

/// The `struct mount_attr` of `change`.
fn mount_attr(change: &MountSetAttr<'_>) -> Result<MountAttr> {
    let (set, set_times) = attribute_bits(change.set);
    let (clear, clear_times) = attribute_bits(change.clear);
    let mut attr = MountAttr {
        attr_set: set,
        // How access times are kept is one value: the kernel wants all
        // of it cleared when it is set, and takes clearing it for a
        // return to "relative", which is 0. Clearing one of its values
        // means the same.
        attr_clr: clear & !MOUNT_ATTR_ATIME
            | if set_times || clear_times {
                MOUNT_ATTR_ATIME
            } else {
                0
            },
        propagation: change
            .propagation
            .map_or(0, |kind| propagation_flag(kind) as u64),
        userns_fd: 0,
    };
    if let Some(namespace) = change.id_map {
        // A descriptor that is not one cannot be told from "none" in an
        // unsigned field: it is refused here, as the kernel would.
        attr.userns_fd = u64::try_from(namespace.as_raw()).map_err(|_| ErrorKind::BadHandle)?;
        attr.attr_set |= MOUNT_ATTR_IDMAP;
    }
    Ok(attr)
}

pub(crate) fn open_tree_attr(
    dir: Option<BorrowedHandle<'_>>,
    path: &[u8],
    flags: OpenTreeFlags,
    change: &MountSetAttr<'_>,
) -> Result<OwnedHandle> {
    let flags = open_tree_flags(flags);
    let attr = mount_attr(change)?;
    with_cstr(path, |path| {
        let (path, attr, size) = (path.as_ptr(), &raw const attr, size_of::<MountAttr>());
        // SAFETY: the path is a NUL-terminated string, and the kernel
        // reads `size` bytes of the structure.
        unsafe { syscall!(OPEN_TREE_ATTR, dir_fd(dir), path, flags, attr, size) }.map(new_handle)
    })
}

// What is mounted: `statmount` and `listmount` of Linux 6.8.

/// `LSMT_ROOT`.
pub(crate) const LSMT_ROOT: u64 = u64::MAX;
const LISTMOUNT_REVERSE: usize = 1;
/// `MNT_ID_REQ_SIZE_VER0`: the request without a mount namespace, which
/// is the one every kernel that has the calls takes.
const MNT_ID_REQ_SIZE_VER0: u32 = 24;

const STATX_MNT_ID_UNIQUE: u32 = 0x4000;

/// `struct mnt_id_req`.
#[repr(C)]
struct MntIdReq {
    size: u32,
    mnt_ns_fd: u32,
    mnt_id: u64,
    param: u64,
    mnt_ns_id: u64,
}

/// `struct statmount`, without the strings that follow it. Every 64-bit
/// member is at a multiple of eight: one layout for the six
/// architectures.
#[repr(C)]
#[derive(Clone, Copy)]
pub(crate) struct StatMount {
    pub(crate) size: u32,
    pub(crate) mnt_opts: u32,
    pub(crate) mask: u64,
    pub(crate) sb_dev_major: u32,
    pub(crate) sb_dev_minor: u32,
    pub(crate) sb_magic: u64,
    pub(crate) sb_flags: u32,
    pub(crate) fs_type: u32,
    pub(crate) mnt_id: u64,
    pub(crate) mnt_parent_id: u64,
    pub(crate) mnt_id_old: u32,
    pub(crate) mnt_parent_id_old: u32,
    pub(crate) mnt_attr: u64,
    pub(crate) mnt_propagation: u64,
    pub(crate) mnt_peer_group: u64,
    pub(crate) mnt_master: u64,
    pub(crate) propagate_from: u64,
    pub(crate) mnt_root: u32,
    pub(crate) mnt_point: u32,
    pub(crate) mnt_ns_id: u64,
    pub(crate) fs_subtype: u32,
    pub(crate) sb_source: u32,
    pub(crate) opt_num: u32,
    pub(crate) opt_array: u32,
    pub(crate) opt_sec_num: u32,
    pub(crate) opt_sec_array: u32,
    pub(crate) supported_mask: u64,
    pub(crate) mnt_uidmap_num: u32,
    pub(crate) mnt_uidmap: u32,
    pub(crate) mnt_gidmap_num: u32,
    pub(crate) mnt_gidmap: u32,
    spare: [u64; 43],
}

const _: () = assert!(
    size_of::<MntIdReq>() == 32
        && core::mem::offset_of!(MntIdReq, mnt_ns_id) == MNT_ID_REQ_SIZE_VER0 as usize
        && size_of::<StatMount>() == 512
        && core::mem::offset_of!(StatMount, mnt_id) == 40
        && core::mem::offset_of!(StatMount, mnt_ns_id) == 112
        && core::mem::offset_of!(StatMount, supported_mask) == 144
        && core::mem::offset_of!(StatMount, mnt_gidmap) == 164
);

/// The size of `struct statmount`: the least a buffer for it holds.
pub(crate) const STATMOUNT_SIZE: usize = size_of::<StatMount>();

/// `statmount`: the structure, and the strings its offsets are in.
pub(crate) fn statmount(
    id: u64,
    fields: StatMountFields,
    buf: &mut [u8],
) -> Result<(StatMount, &[u8])> {
    // The kernel would say `EOVERFLOW` of this one too.
    if buf.len() < STATMOUNT_SIZE {
        return Err(ErrorKind::BufferTooSmall.into());
    }
    let request = MntIdReq {
        size: MNT_ID_REQ_SIZE_VER0,
        mnt_ns_fd: 0,
        mnt_id: id,
        param: fields.bits(),
        mnt_ns_id: 0,
    };
    let (request, out, len) = (&raw const request, buf.as_mut_ptr(), buf.len());
    // SAFETY: the kernel reads `size` bytes of the request and writes at
    // most `len` bytes, at any alignment.
    unsafe { syscall!(STATMOUNT, request, out, len, 0) }.map_err(|error| {
        // What the kernel says of a buffer its answer does not fit in.
        if error.raw_os_error() == crate::sys::errno::EOVERFLOW {
            ErrorKind::BufferTooSmall.into()
        } else {
            error
        }
    })?;
    // SAFETY: the buffer holds that many bytes, and any bytes are a
    // value of the structure.
    let stat = unsafe { buf.as_ptr().cast::<StatMount>().read_unaligned() };
    let end = (stat.size as usize).clamp(STATMOUNT_SIZE, buf.len());
    Ok((stat, &buf[STATMOUNT_SIZE..end]))
}

pub(crate) fn listmount(
    parent: u64,
    after: u64,
    flags: ListMountFlags,
    ids: &mut [u64],
) -> Result<usize> {
    let request = MntIdReq {
        size: MNT_ID_REQ_SIZE_VER0,
        mnt_ns_fd: 0,
        mnt_id: parent,
        param: after,
        mnt_ns_id: 0,
    };
    let flags = if flags.contains(ListMountFlags::REVERSE) {
        LISTMOUNT_REVERSE
    } else {
        0
    };
    let (request, out, len) = (&raw const request, ids.as_mut_ptr(), ids.len());
    // SAFETY: the kernel reads `size` bytes of the request and writes at
    // most `len` numbers of 64 bits.
    unsafe { syscall!(LISTMOUNT, request, out, len, flags) }
}

/// The unique identifier of the mount a path is on: `statx` with
/// `STATX_MNT_ID_UNIQUE`.
pub(crate) fn mount_id(dir: Option<BorrowedHandle<'_>>, path: &[u8], follow: bool) -> Result<u64> {
    // `struct statx`: 256 bytes, `stx_mask` first and `stx_mnt_id` at 144.
    let mut stat = [0u64; 32];
    let mut flags = AT_NO_AUTOMOUNT;
    if !follow {
        flags |= AT_SYMLINK_NOFOLLOW;
    }
    if path.is_empty() {
        flags |= AT_EMPTY_PATH;
    }
    with_cstr(path, |path| {
        let (path, mask) = (path.as_ptr(), STATX_MNT_ID_UNIQUE);
        // SAFETY: the path is a NUL-terminated string, and the kernel
        // writes one `struct statx`.
        unsafe { syscall!(STATX, dir_fd(dir), path, flags, mask, &raw mut stat) }.map(drop)
    })?;
    // A kernel older than these identifiers (6.8) leaves the bit out, and
    // writes the old kind of identifier, or nothing. `stx_mask` is the
    // first 32 bits, on a little-endian machine the low half.
    if stat[0] as u32 & STATX_MNT_ID_UNIQUE == 0 {
        return Err(ErrorKind::Unsupported.into());
    }
    Ok(stat[18])
}

/// The settings `MOUNT_ATTR_*` bits say, and whether the mount maps
/// identifiers.
pub(crate) fn attributes_from(bits: u64) -> (MountAttributes, bool) {
    let table = [
        (MountAttributes::READ_ONLY, MOUNT_ATTR_RDONLY),
        (MountAttributes::NO_SUID, MOUNT_ATTR_NOSUID),
        (MountAttributes::NO_DEV, MOUNT_ATTR_NODEV),
        (MountAttributes::NO_EXEC, MOUNT_ATTR_NOEXEC),
        (MountAttributes::NO_ATIME, MOUNT_ATTR_NOATIME),
        (MountAttributes::STRICT_ATIME, MOUNT_ATTR_STRICTATIME),
        (MountAttributes::NO_DIR_ATIME, MOUNT_ATTR_NODIRATIME),
        (MountAttributes::NO_SYMLINK_FOLLOW, MOUNT_ATTR_NOSYMFOLLOW),
    ];
    let mut attributes = MountAttributes::empty();
    for (flag, value) in table {
        if bits & value != 0 {
            attributes |= flag;
        }
    }
    // "Relative" is the value 0 of the three bits.
    if bits & MOUNT_ATTR_ATIME == 0 {
        attributes |= MountAttributes::REL_ATIME;
    }
    (attributes, bits & MOUNT_ATTR_IDMAP != 0)
}

/// The flags of a filesystem `SB_*` bits say: the same numbers as `MS_*`.
pub(crate) fn filesystem_flags_from(bits: u32) -> MountFlags {
    let table = [
        (MountFlags::READ_ONLY, MS_RDONLY),
        (MountFlags::SYNCHRONOUS, MS_SYNCHRONOUS),
        (MountFlags::DIR_SYNC, MS_DIRSYNC),
        (MountFlags::LAZY_TIME, MS_LAZYTIME),
    ];
    let mut flags = MountFlags::empty();
    for (flag, value) in table {
        if bits as usize & value != 0 {
            flags |= flag;
        }
    }
    flags
}

/// How a mount propagates, from the `MS_*` bits `statmount` gives.
pub(crate) fn propagation_from(bits: u64) -> Propagation {
    let bits = bits as usize;
    if bits & MS_SHARED != 0 {
        Propagation::Shared
    } else if bits & MS_SLAVE != 0 {
        Propagation::Slave
    } else if bits & MS_UNBINDABLE != 0 {
        Propagation::Unbindable
    } else {
        Propagation::Private
    }
}