oscall 0.1.0

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
//! `fs` on Linux and fullrust.

use core::ffi::CStr;

use crate::fs::{
    FileTimes, FileType, LockKind, Metadata, OpenOptions, RawDirEntry, Space, UnixMetadata,
};
use crate::path::with_cstr;
use crate::sys::{errno, syscall};
use crate::time::Timestamp;
use crate::{AsHandle, BorrowedHandle, Error, ErrorKind, OwnedHandle, Result};

// The open flags that are the same on every architecture
// (include/uapi/asm-generic/fcntl.h).
const O_WRONLY: usize = 0o1;
const O_RDWR: usize = 0o2;
const O_CREAT: usize = 0o100;
const O_EXCL: usize = 0o200;
const O_TRUNC: usize = 0o1000;
const O_APPEND: usize = 0o2000;
const O_CLOEXEC: usize = 0o2000000;

// Those that arm and aarch64 define differently
// (arch/arm/include/uapi/asm/fcntl.h, arch/arm64/include/uapi/asm/fcntl.h).
#[cfg(any(target_arch = "arm", target_arch = "aarch64"))]
mod arch_flags {
    pub(super) const O_DIRECTORY: usize = 0o40000;
    pub(super) const O_NOFOLLOW: usize = 0o100000;
    pub(super) const O_LARGEFILE: usize = 0o400000;
}
#[cfg(not(any(target_arch = "arm", target_arch = "aarch64")))]
mod arch_flags {
    pub(super) const O_DIRECTORY: usize = 0o200000;
    pub(super) const O_NOFOLLOW: usize = 0o400000;
    pub(super) const O_LARGEFILE: usize = 0o100000;
}
use arch_flags::*;

/// What every open needs: private to the process and, on 32-bit targets,
/// allowed to go past 2 GiB (64-bit kernels imply it).
const O_BASE: usize = if cfg!(target_pointer_width = "32") {
    O_CLOEXEC | O_LARGEFILE
} else {
    O_CLOEXEC
};

const AT_FDCWD: i32 = -100;
const AT_SYMLINK_NOFOLLOW: usize = 0x100;
const AT_REMOVEDIR: usize = 0x200;
const AT_EMPTY_PATH: usize = 0x1000;

const STATX_BASIC_STATS: u32 = 0x7ff;
const STATX_BTIME: u32 = 0x800;

const S_IFMT: u32 = 0o170000;
const S_IFIFO: u32 = 0o010000;
const S_IFCHR: u32 = 0o020000;
const S_IFDIR: u32 = 0o040000;
const S_IFBLK: u32 = 0o060000;
const S_IFREG: u32 = 0o100000;
const S_IFLNK: u32 = 0o120000;
const S_IFSOCK: u32 = 0o140000;

const UTIME_OMIT: i64 = (1 << 30) - 2;

const LOCK_SH: usize = 1;
const LOCK_EX: usize = 2;
const LOCK_NB: usize = 4;
const LOCK_UN: usize = 8;

/// The longest path the kernel takes, with its NUL.
const PATH_MAX: usize = 4096;
/// How many symbolic links `canonicalize` follows before it gives up, as
/// the kernel does.
const SYMLOOP_MAX: usize = 40;

/// `struct statx_timestamp`.
#[derive(Clone, Copy, Default)]
#[repr(C)]
struct StatxTimestamp {
    sec: i64,
    nsec: u32,
    reserved: i32,
}

/// `struct statx` (include/uapi/linux/stat.h): 256 bytes.
#[derive(Default)]
#[repr(C)]
struct Statx {
    mask: u32,
    blksize: u32,
    attributes: u64,
    nlink: u32,
    uid: u32,
    gid: u32,
    mode: u16,
    spare0: u16,
    ino: u64,
    size: u64,
    blocks: u64,
    attributes_mask: u64,
    atime: StatxTimestamp,
    btime: StatxTimestamp,
    ctime: StatxTimestamp,
    mtime: StatxTimestamp,
    rdev_major: u32,
    rdev_minor: u32,
    dev_major: u32,
    dev_minor: u32,
    spare: [u64; 14],
}

const _: () = assert!(size_of::<Statx>() == 256);

pub(crate) fn is_separator(c: u8) -> bool {
    c == b'/'
}

pub(crate) fn open(path: &[u8], options: &OpenOptions) -> Result<OwnedHandle> {
    open_in(AT_FDCWD, path, options)
}

pub(crate) fn open_at(
    dir: BorrowedHandle<'_>,
    path: &[u8],
    options: &OpenOptions,
) -> Result<OwnedHandle> {
    open_in(dir.as_raw(), path, options)
}

/// `openat`: `path` is relative to the directory `dirfd`, unless absolute.
fn open_in(dirfd: i32, path: &[u8], options: &OpenOptions) -> Result<OwnedHandle> {
    let mut flags = O_BASE;
    flags |= match (options.read, options.write || options.append) {
        (_, false) => 0, // O_RDONLY
        (false, true) => O_WRONLY,
        (true, true) => O_RDWR,
    };
    if options.append {
        flags |= O_APPEND;
    }
    if options.create_new {
        flags |= O_CREAT | O_EXCL;
    } else {
        if options.create {
            flags |= O_CREAT;
        }
        if options.truncate {
            flags |= O_TRUNC;
        }
    }
    if options.no_follow {
        flags |= O_NOFOLLOW;
    }
    if options.directory {
        flags |= O_DIRECTORY;
    }
    with_cstr(path, |path| {
        // SAFETY: `path` is a NUL-terminated string.
        match unsafe { syscall!(OPENAT, dirfd, path.as_ptr(), flags, options.mode) } {
            // SAFETY: the descriptor was just created.
            Ok(fd) => Ok(unsafe { OwnedHandle::from_raw(fd as i32) }),
            // A link that is not followed is "not a directory" when a
            // directory is asked for: say that it is a link, as when a
            // file is asked for.
            Err(error)
                if error.raw_os_error() == errno::ENOTDIR
                    && options.directory
                    && options.no_follow
                    && statx(dirfd, path, AT_SYMLINK_NOFOLLOW)
                        .is_ok_and(|found| found.is_symlink()) =>
            {
                Err(Error::from_raw_os_error(errno::ELOOP))
            }
            Err(error) => Err(error),
        }
    })
}

fn file_type(mode: u32) -> FileType {
    match mode & S_IFMT {
        S_IFREG => FileType::File,
        S_IFDIR => FileType::Directory,
        S_IFLNK => FileType::Symlink,
        S_IFBLK => FileType::BlockDevice,
        S_IFCHR => FileType::CharDevice,
        S_IFIFO => FileType::Fifo,
        S_IFSOCK => FileType::Socket,
        _ => FileType::Unknown,
    }
}

fn statx(dirfd: i32, path: &CStr, flags: usize) -> Result<Metadata> {
    let mut stx = Statx::default();
    let mask = STATX_BASIC_STATS | STATX_BTIME;
    // SAFETY: `path` is a NUL-terminated string and `stx` the structure the
    // call fills.
    unsafe { syscall!(STATX, dirfd, path.as_ptr(), flags, mask, &raw mut stx) }?;
    let time = |t: StatxTimestamp| Timestamp {
        secs: t.sec,
        nanos: t.nsec,
    };
    // The device numbers as libc's `makedev` packs them into `st_dev` and
    // `st_rdev`, so that they compare equal to what other programs report.
    let makedev = |major: u32, minor: u32| {
        let (major, minor) = (major as u64, minor as u64);
        (major & 0xffff_f000) << 32
            | (major & 0xfff) << 8
            | (minor & 0xffff_ff00) << 12
            | (minor & 0xff)
    };
    let device = makedev(stx.dev_major, stx.dev_minor);
    let mode = stx.mode as u32;
    Ok(Metadata {
        file_type: file_type(mode),
        len: stx.size,
        mode: mode & 0o7777,
        modified: time(stx.mtime),
        accessed: time(stx.atime),
        created: (stx.mask & STATX_BTIME != 0).then(|| time(stx.btime)),
        links: stx.nlink as u64,
        device,
        inode: stx.ino,
        raw: mode,
        unix: UnixMetadata {
            uid: stx.uid,
            gid: stx.gid,
            rdev: makedev(stx.rdev_major, stx.rdev_minor),
            blocks: stx.blocks,
            block_size: stx.blksize,
        },
    })
}

pub(crate) fn metadata(path: &[u8], follow: bool) -> Result<Metadata> {
    let flags = if follow { 0 } else { AT_SYMLINK_NOFOLLOW };
    with_cstr(path, |path| statx(AT_FDCWD, path, flags))
}

pub(crate) fn metadata_at(dir: BorrowedHandle<'_>, path: &[u8], follow: bool) -> Result<Metadata> {
    let flags = if follow { 0 } else { AT_SYMLINK_NOFOLLOW };
    with_cstr(path, |path| statx(dir.as_raw(), path, flags))
}

pub(crate) fn handle_metadata(handle: BorrowedHandle<'_>) -> Result<Metadata> {
    statx(handle.as_raw(), c"", AT_EMPTY_PATH)
}

pub(crate) fn set_len(handle: BorrowedHandle<'_>, len: u64) -> Result<()> {
    let fd = handle.as_raw();
    #[cfg(target_pointer_width = "64")]
    // SAFETY: no memory is involved.
    unsafe { syscall!(FTRUNCATE, fd, len) }?;
    // On 32-bit targets the length takes two registers, low half first on
    // these little-endian architectures. arm wants a 64-bit argument to
    // start on an even register, hence the padding; x86 and riscv32 do not.
    #[cfg(all(target_pointer_width = "32", target_arch = "arm"))]
    // SAFETY: no memory is involved.
    unsafe { syscall!(FTRUNCATE64, fd, 0, len as u32, (len >> 32) as u32) }?;
    #[cfg(all(target_pointer_width = "32", not(target_arch = "arm")))]
    // SAFETY: no memory is involved.
    unsafe { syscall!(FTRUNCATE64, fd, len as u32, (len >> 32) as u32) }?;
    Ok(())
}

pub(crate) fn allocate(handle: BorrowedHandle<'_>, len: u64) -> Result<()> {
    let fd = handle.as_raw();
    // Mode 0: allocate, and extend the file if it is shorter.
    #[cfg(target_pointer_width = "64")]
    // SAFETY: no memory is involved.
    unsafe { syscall!(FALLOCATE, fd, 0, 0, len) }?;
    // On 32-bit targets the offset and the length take two registers each,
    // low half first. After two arguments, the offset starts on an even
    // register: arm needs no padding here, and the call is the same on
    // every architecture.
    #[cfg(target_pointer_width = "32")]
    // SAFETY: no memory is involved.
    unsafe { syscall!(FALLOCATE, fd, 0, 0, 0, len as u32, (len >> 32) as u32) }?;
    Ok(())
}

/// `struct statfs` on 64-bit targets (include/uapi/asm-generic/statfs.h).
#[cfg(target_pointer_width = "64")]
#[derive(Default)]
#[repr(C)]
struct Statfs {
    kind: i64,
    bsize: i64,
    blocks: u64,
    bfree: u64,
    bavail: u64,
    files: u64,
    ffree: u64,
    fsid: [i32; 2],
    namelen: i64,
    frsize: i64,
    flags: i64,
    spare: [i64; 4],
}

/// `struct statfs64` on 32-bit targets. arm packs it, to have no padding at
/// its end; x86 aligns 64-bit integers on 4 bytes and has none either;
/// riscv32 has it, and the kernel checks the size it is given.
#[cfg(target_pointer_width = "32")]
#[derive(Default)]
#[cfg_attr(target_arch = "arm", repr(C, packed(4)))]
#[cfg_attr(not(target_arch = "arm"), repr(C))]
struct Statfs {
    kind: u32,
    bsize: u32,
    blocks: u64,
    bfree: u64,
    bavail: u64,
    files: u64,
    ffree: u64,
    fsid: [i32; 2],
    namelen: u32,
    frsize: u32,
    flags: u32,
    spare: [u32; 4],
}

#[cfg(target_pointer_width = "64")]
const _: () = assert!(size_of::<Statfs>() == 120);
#[cfg(all(target_pointer_width = "32", not(target_arch = "riscv32")))]
const _: () = assert!(size_of::<Statfs>() == 84);
#[cfg(target_arch = "riscv32")]
const _: () = assert!(size_of::<Statfs>() == 88);

fn to_space(stat: &Statfs) -> Space {
    // Blocks are counted in fragments, which is what `f_frsize` is; a
    // filesystem that does not fill it has blocks of `f_bsize`.
    let (frsize, bsize) = (stat.frsize, stat.bsize);
    let unit = if frsize > 0 { frsize } else { bsize } as u64;
    let (blocks, bfree, bavail) = (stat.blocks, stat.bfree, stat.bavail);
    Space {
        total: blocks.saturating_mul(unit),
        free: bfree.saturating_mul(unit),
        available: bavail.saturating_mul(unit),
    }
}

pub(crate) fn space(path: &[u8]) -> Result<Space> {
    with_cstr(path, |path| {
        let mut stat = Statfs::default();
        #[cfg(target_pointer_width = "64")]
        // SAFETY: `path` is a NUL-terminated string and `stat` the
        // structure the call fills.
        unsafe { syscall!(STATFS, path.as_ptr(), &raw mut stat) }?;
        #[cfg(target_pointer_width = "32")]
        // SAFETY: as above, with the size of the structure.
        unsafe { syscall!(STATFS64, path.as_ptr(), size_of::<Statfs>(), &raw mut stat) }?;
        Ok(to_space(&stat))
    })
}

pub(crate) fn handle_space(handle: BorrowedHandle<'_>) -> Result<Space> {
    let fd = handle.as_raw();
    let mut stat = Statfs::default();
    #[cfg(target_pointer_width = "64")]
    // SAFETY: `stat` is the structure the call fills.
    unsafe { syscall!(FSTATFS, fd, &raw mut stat) }?;
    #[cfg(target_pointer_width = "32")]
    // SAFETY: as above, with the size of the structure.
    unsafe { syscall!(FSTATFS64, fd, size_of::<Statfs>(), &raw mut stat) }?;
    Ok(to_space(&stat))
}

pub(crate) fn copy(from: &[u8], to: &[u8]) -> Result<u64> {
    const READ: OpenOptions = OpenOptions::new().read(true);
    /// What one call is asked to copy: it may copy less.
    const CHUNK: usize = 1 << 30;

    let source = open(from, &READ)?;
    let source_meta = handle_metadata(source.as_handle())?;
    if source_meta.is_dir() {
        return Err(Error::from_raw_os_error(errno::EISDIR));
    }
    // The file is only emptied once it is known not to be the source.
    let options = OpenOptions::new()
        .write(true)
        .create(true)
        .mode(source_meta.mode);
    let dest = open(to, &options)?;
    let dest_meta = handle_metadata(dest.as_handle())?;
    if (source_meta.device, source_meta.inode) == (dest_meta.device, dest_meta.inode) {
        return Err(ErrorKind::InvalidInput.into());
    }
    // A device or a FIFO is written to, and nothing else.
    if dest_meta.is_file() {
        set_len(dest.as_handle(), 0)?;
        // Whatever the umask says, and also when the file existed.
        set_handle_permissions(dest.as_handle(), source_meta.mode)?;
    }

    let mut total = 0u64;
    loop {
        // SAFETY: without offsets, the call uses the positions of the two
        // descriptors: no memory is involved.
        let result = unsafe {
            syscall!(
                COPY_FILE_RANGE,
                source.as_raw(),
                0,
                dest.as_raw(),
                0,
                CHUNK,
                0
            )
        };
        match result {
            // The end of the file. Some files have content the kernel does
            // not know the length of (those of procfs): when nothing at all
            // was copied, reading is the way to know.
            Ok(0) if total == 0 => break,
            Ok(0) => return Ok(total),
            Ok(copied) => total += copied as u64,
            Err(error) if error.raw_os_error() == errno::EINTR => {}
            // What the call does not do, it refuses before copying
            // anything: another filesystem (before Linux 5.19, or between
            // two types of them), a filesystem without it, a file that is
            // not a regular one, a sandbox that knows nothing of the call.
            Err(error)
                if total == 0
                    && matches!(
                        error.raw_os_error(),
                        errno::EXDEV
                            | errno::ENOSYS
                            | errno::EINVAL
                            | errno::EPERM
                            | errno::EOPNOTSUPP
                    ) =>
            {
                break;
            }
            Err(error) => return Err(error),
        }
    }
    crate::fs::copy_loop(source.as_handle(), dest.as_handle())
}

pub(crate) fn chown(path: &[u8], uid: u32, gid: u32, follow: bool) -> Result<()> {
    let flags = if follow { 0 } else { AT_SYMLINK_NOFOLLOW };
    with_cstr(path, |path| {
        // SAFETY: `path` is a NUL-terminated string.
        unsafe { syscall!(FCHOWNAT, AT_FDCWD, path.as_ptr(), uid, gid, flags) }?;
        Ok(())
    })
}

pub(crate) fn fchown(handle: BorrowedHandle<'_>, uid: u32, gid: u32) -> Result<()> {
    // `fchown` itself takes 16-bit identifiers on the oldest architectures,
    // which have `fchown32` next to it: this call is the same everywhere.
    // SAFETY: the path is an empty NUL-terminated string.
    unsafe {
        syscall!(
            FCHOWNAT,
            handle.as_raw(),
            c"".as_ptr(),
            uid,
            gid,
            AT_EMPTY_PATH
        )
    }?;
    Ok(())
}

pub(crate) fn mkfifo(path: &[u8], mode: u32) -> Result<()> {
    with_cstr(path, |path| {
        // SAFETY: `path` is a NUL-terminated string.
        unsafe { syscall!(MKNODAT, AT_FDCWD, path.as_ptr(), S_IFIFO | mode, 0) }?;
        Ok(())
    })
}

pub(crate) fn sync(handle: BorrowedHandle<'_>, data_only: bool) -> Result<()> {
    if data_only {
        // SAFETY: no memory is involved.
        unsafe { syscall!(FDATASYNC, handle.as_raw()) }?;
    } else {
        // SAFETY: no memory is involved.
        unsafe { syscall!(FSYNC, handle.as_raw()) }?;
    }
    Ok(())
}

pub(crate) fn set_permissions(path: &[u8], mode: u32) -> Result<()> {
    chmod_in(AT_FDCWD, path, mode)
}

pub(crate) fn set_permissions_at(dir: BorrowedHandle<'_>, path: &[u8], mode: u32) -> Result<()> {
    chmod_in(dir.as_raw(), path, mode)
}

fn chmod_in(dirfd: i32, path: &[u8], mode: u32) -> Result<()> {
    with_cstr(path, |path| {
        // SAFETY: `path` is a NUL-terminated string.
        unsafe { syscall!(FCHMODAT, dirfd, path.as_ptr(), mode) }?;
        Ok(())
    })
}

pub(crate) fn set_handle_permissions(handle: BorrowedHandle<'_>, mode: u32) -> Result<()> {
    // SAFETY: no memory is involved.
    unsafe { syscall!(FCHMOD, handle.as_raw(), mode) }?;
    Ok(())
}

/// `struct __kernel_timespec`: two 64-bit fields on every architecture,
/// which is also what `struct timespec` is on the 64-bit ones.
#[repr(C)]
struct Timespec {
    sec: i64,
    nsec: i64,
}

fn utimens(dirfd: i32, path: *const u8, times: &FileTimes) -> Result<()> {
    let spec = |time: Option<Timestamp>| match time {
        Some(time) => Timespec {
            sec: time.secs,
            nsec: time.nanos as i64,
        },
        None => Timespec {
            sec: 0,
            nsec: UTIME_OMIT,
        },
    };
    let times = [spec(times.accessed), spec(times.modified)];
    // 32-bit targets have a call of their own for 64-bit times.
    #[cfg(target_pointer_width = "32")]
    // SAFETY: `path` is null or a NUL-terminated string; `times` is the two
    // structures the call reads.
    unsafe { syscall!(UTIMENSAT_TIME64, dirfd, path, times.as_ptr(), 0) }?;
    #[cfg(target_pointer_width = "64")]
    // SAFETY: as above.
    unsafe { syscall!(UTIMENSAT, dirfd, path, times.as_ptr(), 0) }?;
    Ok(())
}

pub(crate) fn set_times(path: &[u8], times: &FileTimes) -> Result<()> {
    with_cstr(path, |path| utimens(AT_FDCWD, path.as_ptr().cast(), times))
}

pub(crate) fn set_times_at(dir: BorrowedHandle<'_>, path: &[u8], times: &FileTimes) -> Result<()> {
    with_cstr(path, |path| {
        utimens(dir.as_raw(), path.as_ptr().cast(), times)
    })
}

pub(crate) fn set_handle_times(handle: BorrowedHandle<'_>, times: &FileTimes) -> Result<()> {
    // Without a path, the call applies to the descriptor itself.
    utimens(handle.as_raw(), core::ptr::null(), times)
}

pub(crate) fn lock(handle: BorrowedHandle<'_>, kind: LockKind, wait: bool) -> Result<bool> {
    let mut operation = match kind {
        LockKind::Shared => LOCK_SH,
        LockKind::Exclusive => LOCK_EX,
    };
    if !wait {
        operation |= LOCK_NB;
    }
    // SAFETY: no memory is involved.
    match unsafe { syscall!(FLOCK, handle.as_raw(), operation) } {
        Ok(_) => Ok(true),
        Err(error) if !wait && error.raw_os_error() == errno::EAGAIN => Ok(false),
        Err(error) => Err(error),
    }
}

pub(crate) fn unlock(handle: BorrowedHandle<'_>) -> Result<()> {
    // SAFETY: no memory is involved.
    unsafe { syscall!(FLOCK, handle.as_raw(), LOCK_UN) }?;
    Ok(())
}

pub(crate) fn create_dir(path: &[u8], mode: u32) -> Result<()> {
    mkdir_in(AT_FDCWD, path, mode)
}

pub(crate) fn create_dir_at(dir: BorrowedHandle<'_>, path: &[u8], mode: u32) -> Result<()> {
    mkdir_in(dir.as_raw(), path, mode)
}

fn mkdir_in(dirfd: i32, path: &[u8], mode: u32) -> Result<()> {
    with_cstr(path, |path| {
        // SAFETY: `path` is a NUL-terminated string.
        unsafe { syscall!(MKDIRAT, dirfd, path.as_ptr(), mode) }?;
        Ok(())
    })
}

pub(crate) fn remove_dir(path: &[u8]) -> Result<()> {
    unlink_in(AT_FDCWD, path, AT_REMOVEDIR)
}

pub(crate) fn remove_dir_at(dir: BorrowedHandle<'_>, path: &[u8]) -> Result<()> {
    unlink_in(dir.as_raw(), path, AT_REMOVEDIR)
}

pub(crate) fn remove_file(path: &[u8]) -> Result<()> {
    unlink_in(AT_FDCWD, path, 0)
}

pub(crate) fn remove_file_at(dir: BorrowedHandle<'_>, path: &[u8]) -> Result<()> {
    unlink_in(dir.as_raw(), path, 0)
}

fn unlink_in(dirfd: i32, path: &[u8], flags: usize) -> Result<()> {
    with_cstr(path, |path| {
        // SAFETY: `path` is a NUL-terminated string.
        unsafe { syscall!(UNLINKAT, dirfd, path.as_ptr(), flags) }?;
        Ok(())
    })
}

pub(crate) fn rename(from: &[u8], to: &[u8]) -> Result<()> {
    rename_in(AT_FDCWD, from, AT_FDCWD, to)
}

pub(crate) fn rename_at(
    from_dir: BorrowedHandle<'_>,
    from: &[u8],
    to_dir: BorrowedHandle<'_>,
    to: &[u8],
) -> Result<()> {
    rename_in(from_dir.as_raw(), from, to_dir.as_raw(), to)
}

fn rename_in(from_dir: i32, from: &[u8], to_dir: i32, to: &[u8]) -> Result<()> {
    with_cstr(from, |from| {
        with_cstr(to, |to| {
            // `renameat` does not exist on the newer architectures.
            // SAFETY: both paths are NUL-terminated strings.
            unsafe { syscall!(RENAMEAT2, from_dir, from.as_ptr(), to_dir, to.as_ptr(), 0) }?;
            Ok(())
        })
    })
}

pub(crate) fn hard_link(original: &[u8], link: &[u8]) -> Result<()> {
    link_in(AT_FDCWD, original, AT_FDCWD, link)
}

pub(crate) fn hard_link_at(
    original_dir: BorrowedHandle<'_>,
    original: &[u8],
    link_dir: BorrowedHandle<'_>,
    link: &[u8],
) -> Result<()> {
    link_in(original_dir.as_raw(), original, link_dir.as_raw(), link)
}

fn link_in(original_dir: i32, original: &[u8], link_dir: i32, link: &[u8]) -> Result<()> {
    with_cstr(original, |original| {
        with_cstr(link, |link| {
            // SAFETY: both paths are NUL-terminated strings.
            unsafe {
                syscall!(
                    LINKAT,
                    original_dir,
                    original.as_ptr(),
                    link_dir,
                    link.as_ptr(),
                    0
                )
            }?;
            Ok(())
        })
    })
}

pub(crate) fn symlink(target: &[u8], link: &[u8]) -> Result<()> {
    symlink_in(target, AT_FDCWD, link)
}

pub(crate) fn symlink_at(target: &[u8], dir: BorrowedHandle<'_>, link: &[u8]) -> Result<()> {
    symlink_in(target, dir.as_raw(), link)
}

fn symlink_in(target: &[u8], dirfd: i32, link: &[u8]) -> Result<()> {
    with_cstr(target, |target| {
        with_cstr(link, |link| {
            // SAFETY: both paths are NUL-terminated strings.
            unsafe { syscall!(SYMLINKAT, target.as_ptr(), dirfd, link.as_ptr()) }?;
            Ok(())
        })
    })
}

fn readlink_in(dirfd: i32, path: &CStr, buf: &mut [u8]) -> Result<usize> {
    // SAFETY: `path` is a NUL-terminated string and `buf` is writable for
    // its length.
    unsafe {
        syscall!(
            READLINKAT,
            dirfd,
            path.as_ptr(),
            buf.as_mut_ptr(),
            buf.len()
        )
    }
}

fn readlink(path: &CStr, buf: &mut [u8]) -> Result<usize> {
    readlink_in(AT_FDCWD, path, buf)
}

pub(crate) fn read_link(path: &[u8], buf: &mut [u8]) -> Result<usize> {
    read_link_in(AT_FDCWD, path, buf)
}

pub(crate) fn read_link_at(dir: BorrowedHandle<'_>, path: &[u8], buf: &mut [u8]) -> Result<usize> {
    read_link_in(dir.as_raw(), path, buf)
}

fn read_link_in(dirfd: i32, path: &[u8], buf: &mut [u8]) -> Result<usize> {
    with_cstr(path, |path| {
        if buf.is_empty() {
            // The kernel refuses an empty buffer as an invalid argument,
            // which would read as "not a link": find out what the path is
            // with a buffer of our own.
            readlink_in(dirfd, path, &mut [0])?;
            return Err(ErrorKind::BufferTooSmall.into());
        }
        let len = readlink_in(dirfd, path, buf)?;
        // The target is cut to fit without a word: a full buffer may be a
        // target that was cut.
        if len >= buf.len() {
            return Err(ErrorKind::BufferTooSmall.into());
        }
        Ok(len)
    })
}

fn getcwd(buf: &mut [u8]) -> Result<usize> {
    // SAFETY: `buf` is writable for its length.
    let len = unsafe { syscall!(GETCWD, buf.as_mut_ptr(), buf.len()) }?;
    // The length counts the NUL that ends the path.
    Ok(len.saturating_sub(1))
}

pub(crate) fn current_dir(buf: &mut [u8]) -> Result<usize> {
    // The kernel fails with ERANGE, which is `BufferTooSmall`, by itself.
    getcwd(buf)
}

pub(crate) fn set_current_dir(path: &[u8]) -> Result<()> {
    with_cstr(path, |path| {
        // SAFETY: `path` is a NUL-terminated string.
        unsafe { syscall!(CHDIR, path.as_ptr()) }?;
        Ok(())
    })
}

/// Resolves `path` to an absolute path without links, `.` or `..`.
///
/// The kernel has no call for this. The algorithm is the one of musl's
/// `realpath` (MIT license, Rich Felker): `stack` holds what remains to be
/// resolved, at its end, and `output` what is resolved so far. Each
/// component moves from the first to the second, unless it is a symbolic
/// link, whose target is then pushed back on the stack.
pub(crate) fn canonicalize(path: &[u8], buf: &mut [u8]) -> Result<usize> {
    // The last byte of the stack is a NUL that is never overwritten, so
    // that `stack[p]` is zero once everything has been consumed.
    const END: usize = PATH_MAX;
    let too_long = || Error::from_raw_os_error(errno::ENAMETOOLONG);

    if path.contains(&0) {
        return Err(ErrorKind::InvalidInput.into());
    }
    if path.is_empty() {
        return Err(ErrorKind::NotFound.into());
    }
    if path.len() >= PATH_MAX {
        return Err(too_long());
    }
    let mut stack = [0u8; PATH_MAX + 1];
    let mut output = [0u8; PATH_MAX];
    // `stack[p..END]` is what remains; `output[..q]` is resolved.
    let mut p = END - path.len();
    let mut q = 0;
    stack[p..END].copy_from_slice(path);
    // How many links were followed.
    let mut links = 0;
    // How many `..` lead a relative result, to apply to the current
    // directory at the end.
    let mut nup = 0;
    // Whether the last component must be checked to be a directory: it was
    // followed by a slash.
    let mut check_dir = false;
    // Whether to skip the slashes that follow the component just consumed.
    let mut skip_slashes = false;

    loop {
        if skip_slashes {
            while stack[p] == b'/' {
                p += 1;
            }
        }
        skip_slashes = true;

        // A slash here is the start of an absolute path, the one given or
        // a link's target: the result starts over.
        if stack[p] == b'/' {
            check_dir = false;
            nup = 0;
            output[0] = b'/';
            q = 1;
            p += 1;
            // (musl keeps exactly two leading slashes, which POSIX allows
            // a meaning of their own. On Linux they have none.)
            continue;
        }

        // The next component: up to a slash or to the end.
        let l0 = stack[p..END]
            .iter()
            .position(|&c| c == b'/')
            .unwrap_or(END - p);
        let mut l = l0;
        if l == 0 && !check_dir {
            break;
        }
        if l == 1 && stack[p] == b'.' {
            p += l;
            continue;
        }

        // Append it to the output, for now: the position only advances once
        // it is known not to be a link.
        if q > 0 && output[q - 1] != b'/' {
            if p == 0 {
                return Err(too_long());
            }
            p -= 1;
            stack[p] = b'/';
            l += 1;
        }
        if q + l >= PATH_MAX {
            return Err(too_long());
        }
        output[q..q + l].copy_from_slice(&stack[p..p + l]);
        output[q + l] = 0;
        p += l;

        let mut up = false;
        let mut is_link = None;
        let mut ask = true;
        if l0 == 2 && stack[p - 2] == b'.' && stack[p - 1] == b'.' {
            up = true;
            // With nothing but `..` so far in a relative result, there is
            // nothing to cancel: keep it for the current directory.
            if q <= 3 * nup {
                nup += 1;
                q += l;
                continue;
            }
            // What precedes is known to be a directory: no need to ask.
            ask = check_dir;
        }
        if ask {
            // `output[..q + l]` holds no NUL (it was copied from paths that
            // have none) and one follows it.
            let name = CStr::from_bytes_with_nul(&output[..=q + l])
                .map_err(|_| Error::from(ErrorKind::InvalidInput))?;
            match readlink(name, &mut stack[..p]) {
                Ok(k) => is_link = Some(k),
                // Not a symbolic link: it stays in the output.
                Err(error) if error.raw_os_error() == errno::EINVAL => {}
                Err(error) => return Err(error),
            }
        }

        let Some(k) = is_link else {
            check_dir = false;
            if up {
                // Drop the `..` and the component before it.
                while q > 0 && output[q - 1] != b'/' {
                    q -= 1;
                }
                if q > 1 {
                    q -= 1;
                }
                continue;
            }
            if l0 > 0 {
                q += l;
            }
            check_dir = stack[p] != 0;
            continue;
        };

        // A link: its target, read at the start of the stack, replaces it
        // in front of what remains.
        if k == p {
            return Err(too_long());
        }
        if k == 0 {
            return Err(ErrorKind::NotFound.into());
        }
        links += 1;
        if links == SYMLOOP_MAX {
            return Err(Error::from_raw_os_error(errno::ELOOP));
        }
        // A target that ends with a slash already has the one that
        // separates it from the rest.
        if stack[k - 1] == b'/' {
            while stack[p] == b'/' {
                p += 1;
            }
        }
        p -= k;
        stack.copy_within(0..k, p);
        // The target may be absolute: look at its first byte as it is.
        skip_slashes = false;
    }

    if q == 0 || output[0] != b'/' {
        // A relative result: put the current directory in front of it, less
        // one component for each leading `..`.
        let mut l = match getcwd(&mut stack) {
            Ok(l) => l,
            Err(error) if error.raw_os_error() == errno::ERANGE => return Err(too_long()),
            Err(error) => return Err(error),
        };
        if l == 0 {
            return Err(ErrorKind::NotFound.into());
        }
        let mut p = 0;
        for _ in 0..nup {
            while l > 1 && stack[l - 1] != b'/' {
                l -= 1;
            }
            if l > 1 {
                l -= 1;
            }
            p += 2;
            if p < q {
                p += 1;
            }
        }
        if q > p && stack[l - 1] != b'/' {
            stack[l] = b'/';
            l += 1;
        }
        if l + (q - p) + 1 >= PATH_MAX {
            return Err(too_long());
        }
        output.copy_within(p..q, l);
        output[..l].copy_from_slice(&stack[..l]);
        q = l + q - p;
    }

    let out = buf.get_mut(..q).ok_or(ErrorKind::BufferTooSmall)?;
    out.copy_from_slice(&output[..q]);
    Ok(q)
}

/// The size of the buffer `getdents64` fills: room for a dozen entries with
/// the longest names, and for a hundred ordinary ones.
const DIR_BUF: usize = 4096;
/// `offsetof(struct linux_dirent64, d_name)`: `d_ino` and `d_off` (8 bytes
/// each), `d_reclen` (2) and `d_type` (1) come before it.
const DIRENT_NAME: usize = 19;

pub(crate) struct Dir {
    handle: OwnedHandle,
    buf: [u8; DIR_BUF],
    /// Where the next entry starts in `buf`.
    pos: usize,
    /// Where what the kernel wrote ends.
    end: usize,
}

impl Dir {
    pub(crate) fn new(handle: OwnedHandle) -> Self {
        Self {
            handle,
            buf: [0; DIR_BUF],
            pos: 0,
            end: 0,
        }
    }

    pub(crate) fn handle(&self) -> BorrowedHandle<'_> {
        self.handle.as_handle()
    }

    pub(crate) fn name(&self, entry: &RawDirEntry) -> &[u8] {
        &self.buf[entry.name.0..entry.name.1]
    }

    pub(crate) fn next(&mut self) -> Result<Option<RawDirEntry>> {
        if self.pos >= self.end {
            self.pos = 0;
            self.end = 0;
            // SAFETY: `buf` is writable for its length.
            let len = unsafe {
                syscall!(
                    GETDENTS64,
                    self.handle.as_raw(),
                    self.buf.as_mut_ptr(),
                    DIR_BUF
                )
            }?;
            if len == 0 {
                return Ok(None);
            }
            self.end = len.min(DIR_BUF);
        }
        // What the kernel wrote is not trusted to be well formed: a record
        // that does not fit in what was written is an error, not a panic.
        let malformed = || Error::from(ErrorKind::Other);
        let record = &self.buf[self.pos..self.end];
        if record.len() <= DIRENT_NAME {
            self.pos = self.end;
            return Err(malformed());
        }
        let inode = u64::from_ne_bytes(record[..8].try_into().map_err(|_| malformed())?);
        let reclen = u16::from_ne_bytes([record[16], record[17]]) as usize;
        let kind = record[18];
        if reclen <= DIRENT_NAME || reclen > record.len() {
            self.pos = self.end;
            return Err(malformed());
        }
        let name = &record[DIRENT_NAME..reclen];
        let name_len = name.iter().position(|&c| c == 0).unwrap_or(name.len());
        let start = self.pos + DIRENT_NAME;
        self.pos += reclen;
        Ok(Some(RawDirEntry {
            name: (start, start + name_len),
            // `DT_*`: the file type bits of `st_mode`, shifted.
            file_type: match kind {
                0 => None, // DT_UNKNOWN
                kind => Some(file_type((kind as u32) << 12)),
            },
            inode,
        }))
    }
}