oscall 0.0.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
//! `fs` on WASI preview 1.
//!
//! WASI has no absolute paths and no current directory: every path is
//! relative to a directory descriptor. The host opens some directories
//! before the program starts (the "preopens", descriptors 3 and up), each
//! under a name, and a path is looked up in the one whose name is its
//! longest prefix. This is what `wasi-libc` does, and so `std`.

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

/// `prestat`: a tag (0 for a directory) and the length of the name.
#[repr(C)]
struct Prestat {
    tag: u8,
    name_len: usize,
}

/// `filestat`.
#[derive(Default)]
#[repr(C)]
struct Filestat {
    dev: u64,
    ino: u64,
    filetype: u8,
    nlink: u64,
    size: u64,
    atim: u64,
    mtim: u64,
    ctim: u64,
}

const _: () = assert!(size_of::<Filestat>() == 64);

#[link(wasm_import_module = "wasi_snapshot_preview1")]
unsafe extern "C" {
    fn fd_prestat_get(fd: i32, prestat: *mut Prestat) -> i32;
    fn fd_prestat_dir_name(fd: i32, name: *mut u8, len: usize) -> i32;
    fn path_open(
        fd: i32,
        lookup_flags: i32,
        path: *const u8,
        path_len: usize,
        open_flags: i32,
        rights_base: i64,
        rights_inheriting: i64,
        fd_flags: i32,
        opened: *mut i32,
    ) -> i32;
    fn path_filestat_get(
        fd: i32,
        lookup_flags: i32,
        path: *const u8,
        path_len: usize,
        stat: *mut Filestat,
    ) -> i32;
    fn path_filestat_set_times(
        fd: i32,
        lookup_flags: i32,
        path: *const u8,
        path_len: usize,
        atim: i64,
        mtim: i64,
        flags: i32,
    ) -> i32;
    fn fd_filestat_get(fd: i32, stat: *mut Filestat) -> i32;
    fn fd_filestat_set_size(fd: i32, size: i64) -> i32;
    fn fd_allocate(fd: i32, offset: i64, len: i64) -> i32;
    fn fd_filestat_set_times(fd: i32, atim: i64, mtim: i64, flags: i32) -> i32;
    fn fd_sync(fd: i32) -> i32;
    fn fd_datasync(fd: i32) -> i32;
    fn path_create_directory(fd: i32, path: *const u8, path_len: usize) -> i32;
    fn path_remove_directory(fd: i32, path: *const u8, path_len: usize) -> i32;
    fn path_unlink_file(fd: i32, path: *const u8, path_len: usize) -> i32;
    fn path_rename(
        fd: i32,
        path: *const u8,
        path_len: usize,
        new_fd: i32,
        new_path: *const u8,
        new_path_len: usize,
    ) -> i32;
    fn path_link(
        fd: i32,
        lookup_flags: i32,
        path: *const u8,
        path_len: usize,
        new_fd: i32,
        new_path: *const u8,
        new_path_len: usize,
    ) -> i32;
    fn path_symlink(
        target: *const u8,
        target_len: usize,
        fd: i32,
        path: *const u8,
        path_len: usize,
    ) -> i32;
    fn path_readlink(
        fd: i32,
        path: *const u8,
        path_len: usize,
        buf: *mut u8,
        buf_len: usize,
        used: *mut usize,
    ) -> i32;
    fn fd_readdir(fd: i32, buf: *mut u8, buf_len: usize, cookie: i64, used: *mut usize) -> i32;
}

const LOOKUP_SYMLINK_FOLLOW: i32 = 1;

const OFLAGS_CREAT: i32 = 1 << 0;
const OFLAGS_DIRECTORY: i32 = 1 << 1;
const OFLAGS_EXCL: i32 = 1 << 2;
const OFLAGS_TRUNC: i32 = 1 << 3;

const FDFLAGS_APPEND: i32 = 1 << 0;

const FSTFLAGS_ATIM: i32 = 1 << 0;
const FSTFLAGS_MTIM: i32 = 1 << 2;

const RIGHTS_FD_DATASYNC: i64 = 1 << 0;
const RIGHTS_FD_READ: i64 = 1 << 1;
const RIGHTS_FD_SEEK: i64 = 1 << 2;
const RIGHTS_FD_FDSTAT_SET_FLAGS: i64 = 1 << 3;
const RIGHTS_FD_SYNC: i64 = 1 << 4;
const RIGHTS_FD_TELL: i64 = 1 << 5;
const RIGHTS_FD_WRITE: i64 = 1 << 6;
const RIGHTS_FD_ADVISE: i64 = 1 << 7;
const RIGHTS_FD_ALLOCATE: i64 = 1 << 8;
const RIGHTS_PATH_CREATE_DIRECTORY: i64 = 1 << 9;
const RIGHTS_PATH_CREATE_FILE: i64 = 1 << 10;
const RIGHTS_PATH_LINK_SOURCE: i64 = 1 << 11;
const RIGHTS_PATH_LINK_TARGET: i64 = 1 << 12;
const RIGHTS_PATH_OPEN: i64 = 1 << 13;
const RIGHTS_FD_READDIR: i64 = 1 << 14;
const RIGHTS_PATH_READLINK: i64 = 1 << 15;
const RIGHTS_PATH_RENAME_SOURCE: i64 = 1 << 16;
const RIGHTS_PATH_RENAME_TARGET: i64 = 1 << 17;
const RIGHTS_PATH_FILESTAT_GET: i64 = 1 << 18;
const RIGHTS_PATH_FILESTAT_SET_SIZE: i64 = 1 << 19;
const RIGHTS_PATH_FILESTAT_SET_TIMES: i64 = 1 << 20;
const RIGHTS_FD_FILESTAT_GET: i64 = 1 << 21;
const RIGHTS_FD_FILESTAT_SET_SIZE: i64 = 1 << 22;
const RIGHTS_FD_FILESTAT_SET_TIMES: i64 = 1 << 23;
const RIGHTS_PATH_SYMLINK: i64 = 1 << 24;
const RIGHTS_PATH_REMOVE_DIRECTORY: i64 = 1 << 25;
const RIGHTS_PATH_UNLINK_FILE: i64 = 1 << 26;
const RIGHTS_POLL_FD_READWRITE: i64 = 1 << 27;

/// The rights asked for whatever the access, as `std` does: a host grants
/// those that apply to what is opened.
const RIGHTS_COMMON: i64 = RIGHTS_FD_ADVISE
    | RIGHTS_FD_FDSTAT_SET_FLAGS
    | RIGHTS_FD_FILESTAT_GET
    | RIGHTS_FD_FILESTAT_SET_TIMES
    | RIGHTS_FD_SEEK
    | RIGHTS_FD_SYNC
    | RIGHTS_FD_TELL
    | RIGHTS_PATH_CREATE_DIRECTORY
    | RIGHTS_PATH_CREATE_FILE
    | RIGHTS_PATH_FILESTAT_GET
    | RIGHTS_PATH_FILESTAT_SET_SIZE
    | RIGHTS_PATH_FILESTAT_SET_TIMES
    | RIGHTS_PATH_LINK_SOURCE
    | RIGHTS_PATH_LINK_TARGET
    | RIGHTS_PATH_OPEN
    | RIGHTS_PATH_READLINK
    | RIGHTS_PATH_REMOVE_DIRECTORY
    | RIGHTS_PATH_RENAME_SOURCE
    | RIGHTS_PATH_RENAME_TARGET
    | RIGHTS_PATH_SYMLINK
    | RIGHTS_PATH_UNLINK_FILE
    | RIGHTS_POLL_FD_READWRITE;
const RIGHTS_READ: i64 = RIGHTS_FD_READ | RIGHTS_FD_READDIR;
const RIGHTS_WRITE: i64 =
    RIGHTS_FD_WRITE | RIGHTS_FD_DATASYNC | RIGHTS_FD_ALLOCATE | RIGHTS_FD_FILESTAT_SET_SIZE;

fn unsupported<T>() -> Result<T> {
    Err(ErrorKind::Unsupported.into())
}

/// The name of a preopened directory as paths are compared to it: without
/// the leading `/`, `./` or lone `.`, so that `.` and `/` are both the
/// empty prefix.
fn strip_prefixes(mut name: &[u8]) -> &[u8] {
    loop {
        name = match name {
            [b'/', rest @ ..] => rest,
            [b'.', b'/', rest @ ..] => rest,
            [b'.'] => &[],
            _ => return name,
        };
    }
}

/// Whether `path`, which has no leading slash, is in the preopened
/// directory named `prefix`.
fn prefix_matches(prefix: &[u8], path: &[u8]) -> bool {
    // The empty prefix is the directory relative paths are relative to.
    if prefix.is_empty() {
        return true;
    }
    if !path.starts_with(prefix) {
        return false;
    }
    // Only whole components match: `/data` holds `/data/x`, not `/database`.
    let mut end = prefix.len();
    while end > 0 && prefix[end - 1] == b'/' {
        end -= 1;
    }
    matches!(path.get(end), None | Some(b'/'))
}

/// Finds the preopened directory `path` is in, and calls `f` with its
/// descriptor and the path relative to it.
///
/// The preopens are asked for at every call: they are few, and oscall keeps
/// no global state.
fn resolve<R>(path: &[u8], f: impl FnOnce(i32, &[u8]) -> Result<R>) -> Result<R> {
    if path.contains(&0) {
        return Err(ErrorKind::InvalidInput.into());
    }
    // As everywhere else: the empty path names nothing.
    if path.is_empty() {
        return Err(ErrorKind::NotFound.into());
    }
    let mut path = path;
    while let [b'/', rest @ ..] = path {
        path = rest;
    }

    let mut best = None;
    let mut name = [0u8; 512];
    // Preopens come right after the standard descriptors, in a row.
    for fd in 3.. {
        let mut prestat = Prestat {
            tag: 0,
            name_len: 0,
        };
        // SAFETY: `prestat` is the structure the call fills.
        if unsafe { fd_prestat_get(fd, &raw mut prestat) } != 0 {
            // EBADF: there are no more of them.
            break;
        }
        let len = prestat.name_len;
        if prestat.tag != 0 || len > name.len() {
            continue;
        }
        // SAFETY: `name` is writable for `len` bytes.
        if unsafe { fd_prestat_dir_name(fd, name.as_mut_ptr(), len) } != 0 {
            continue;
        }
        // Some hosts count a NUL at the end of the name.
        let prefix = name[..len].split(|&c| c == 0).next().unwrap_or(&[]);
        let prefix = strip_prefixes(prefix);
        // The longest prefix wins, and the latest of equals.
        if best.is_none_or(|(_, len)| prefix.len() >= len) && prefix_matches(prefix, path) {
            best = Some((fd, prefix.len()));
        }
    }

    let (fd, len) = best.ok_or(ErrorKind::NotFound)?;
    let mut relative = &path[len..];
    while let [b'/', rest @ ..] = relative {
        relative = rest;
    }
    // The directory itself has to be named somehow.
    if relative.is_empty() {
        relative = b".";
    }
    f(fd, relative)
}

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

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

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

/// `path_open`, with `path` relative to the directory `dir`.
fn open_in(dir: i32, path: &[u8], options: &OpenOptions) -> Result<OwnedHandle> {
    let mut open_flags = 0;
    if options.create_new {
        open_flags |= OFLAGS_CREAT | OFLAGS_EXCL;
    } else {
        if options.create {
            open_flags |= OFLAGS_CREAT;
        }
        if options.truncate {
            open_flags |= OFLAGS_TRUNC;
        }
    }
    if options.directory {
        open_flags |= OFLAGS_DIRECTORY;
    }
    let mut rights = RIGHTS_COMMON;
    if options.read {
        rights |= RIGHTS_READ;
    }
    if options.write || options.append {
        rights |= RIGHTS_WRITE;
    }
    let fd_flags = if options.append { FDFLAGS_APPEND } else { 0 };
    let lookup_flags = if options.no_follow || options.create_new {
        0
    } else {
        LOOKUP_SYMLINK_FOLLOW
    };
    // Hosts disagree on a link that is not to be followed: most refuse it
    // as they should, some say "not a directory" when a directory is asked
    // for, and Node opens what it points to. Look first.
    if options.no_follow && filestat(dir, path, 0).is_ok_and(|found| found.is_symlink()) {
        return Err(Error::from_raw_os_error(errno::ELOOP));
    }
    let mut fd = -1;
    // SAFETY: `path` is readable for its length and `fd` is written by the
    // call.
    let result = cvt(unsafe {
        path_open(
            dir,
            lookup_flags,
            path.as_ptr(),
            path.len(),
            open_flags,
            rights,
            // What is opened from a directory opened here may be opened
            // for anything: a directory handle does not limit `open_at`.
            RIGHTS_COMMON | RIGHTS_READ | RIGHTS_WRITE,
            fd_flags,
            &raw mut fd,
        )
    });
    result?;
    // SAFETY: the descriptor was just created.
    Ok(unsafe { OwnedHandle::from_raw(fd) })
}

fn file_type(filetype: u8) -> FileType {
    match filetype {
        1 => FileType::BlockDevice,
        2 => FileType::CharDevice,
        3 => FileType::Directory,
        4 => FileType::File,
        5 | 6 => FileType::Socket,
        7 => FileType::Symlink,
        _ => FileType::Unknown,
    }
}

fn to_metadata(stat: &Filestat) -> Metadata {
    let time = |ns: u64| Timestamp {
        secs: (ns / 1_000_000_000) as i64,
        nanos: (ns % 1_000_000_000) as u32,
    };
    let file_type = file_type(stat.filetype);
    Metadata {
        file_type,
        len: stat.size,
        // There are no permissions: everything is as accessible as the
        // host lets it be.
        mode: if file_type == FileType::Directory {
            0o777
        } else {
            0o666
        },
        modified: time(stat.mtim),
        accessed: time(stat.atim),
        created: None,
        links: stat.nlink,
        device: stat.dev,
        inode: stat.ino,
        raw: 0,
        unix: UnixMetadata::default(),
    }
}

/// The metadata of `path` in the directory `dir`.
fn filestat(dir: i32, path: &[u8], flags: i32) -> Result<Metadata> {
    let mut stat = Filestat::default();
    // SAFETY: `path` is readable for its length and `stat` is the structure
    // the call fills.
    cvt(unsafe { path_filestat_get(dir, flags, path.as_ptr(), path.len(), &raw mut stat) })?;
    Ok(to_metadata(&stat))
}

pub(crate) fn metadata(path: &[u8], follow: bool) -> Result<Metadata> {
    let flags = if follow { LOOKUP_SYMLINK_FOLLOW } else { 0 };
    resolve(path, |dir, path| filestat(dir, path, flags))
}

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

pub(crate) fn handle_metadata(handle: BorrowedHandle<'_>) -> Result<Metadata> {
    let mut stat = Filestat::default();
    // SAFETY: `stat` is the structure the call fills.
    cvt(unsafe { fd_filestat_get(handle.as_raw(), &raw mut stat) })?;
    Ok(to_metadata(&stat))
}

pub(crate) fn set_len(handle: BorrowedHandle<'_>, len: u64) -> Result<()> {
    // SAFETY: no memory is involved.
    cvt(unsafe { fd_filestat_set_size(handle.as_raw(), len as i64) })
}

pub(crate) fn allocate(handle: BorrowedHandle<'_>, len: u64) -> Result<()> {
    // SAFETY: no memory is involved.
    cvt(unsafe { fd_allocate(handle.as_raw(), 0, len as i64) })
}

pub(crate) fn space(_: &[u8]) -> Result<Space> {
    unsupported()
}

pub(crate) fn handle_space(_: BorrowedHandle<'_>) -> Result<Space> {
    unsupported()
}

pub(crate) fn copy(from: &[u8], to: &[u8]) -> Result<u64> {
    const READ: OpenOptions = OpenOptions::new().read(true);
    const WRITE: OpenOptions = OpenOptions::new().write(true).create(true);

    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. (A
    // host that numbers no file cannot tell.)
    let dest = open(to, &WRITE)?;
    let dest_meta = handle_metadata(dest.as_handle())?;
    if source_meta.inode != 0
        && (source_meta.device, source_meta.inode) == (dest_meta.device, dest_meta.inode)
    {
        return Err(ErrorKind::InvalidInput.into());
    }
    if dest_meta.is_file() {
        set_len(dest.as_handle(), 0)?;
    }
    crate::fs::copy_loop(source.as_handle(), dest.as_handle())
}

pub(crate) fn sync(handle: BorrowedHandle<'_>, data_only: bool) -> Result<()> {
    // SAFETY: no memory is involved.
    cvt(unsafe {
        if data_only {
            fd_datasync(handle.as_raw())
        } else {
            fd_sync(handle.as_raw())
        }
    })
}

pub(crate) fn set_permissions(_: &[u8], _: u32) -> Result<()> {
    unsupported()
}

pub(crate) fn set_permissions_at(_: BorrowedHandle<'_>, _: &[u8], _: u32) -> Result<()> {
    unsupported()
}

pub(crate) fn set_handle_permissions(_: BorrowedHandle<'_>, _: u32) -> Result<()> {
    unsupported()
}

/// The two timestamps in nanoseconds since the epoch, and which are set.
fn times_args(times: &FileTimes) -> Result<(i64, i64, i32)> {
    // A WASI timestamp is unsigned: nothing before 1970.
    let nanos = |time: Option<Timestamp>| match time {
        None => Ok(0),
        Some(time) => u64::try_from(time.secs)
            .ok()
            .and_then(|secs| secs.checked_mul(1_000_000_000))
            .and_then(|ns| ns.checked_add(time.nanos as u64))
            .map(|ns| ns as i64)
            .ok_or(Error::from(ErrorKind::InvalidInput)),
    };
    let mut flags = 0;
    if times.accessed.is_some() {
        flags |= FSTFLAGS_ATIM;
    }
    if times.modified.is_some() {
        flags |= FSTFLAGS_MTIM;
    }
    Ok((nanos(times.accessed)?, nanos(times.modified)?, flags))
}

pub(crate) fn set_times(path: &[u8], times: &FileTimes) -> Result<()> {
    resolve(path, |dir, path| set_times_in(dir, path, times))
}

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

fn set_times_in(dir: i32, path: &[u8], times: &FileTimes) -> Result<()> {
    let (atim, mtim, flags) = times_args(times)?;
    // SAFETY: `path` is readable for its length.
    cvt(unsafe {
        path_filestat_set_times(
            dir,
            LOOKUP_SYMLINK_FOLLOW,
            path.as_ptr(),
            path.len(),
            atim,
            mtim,
            flags,
        )
    })
}

pub(crate) fn set_handle_times(handle: BorrowedHandle<'_>, times: &FileTimes) -> Result<()> {
    let (atim, mtim, flags) = times_args(times)?;
    // SAFETY: no memory is involved.
    cvt(unsafe { fd_filestat_set_times(handle.as_raw(), atim, mtim, flags) })
}

pub(crate) fn lock(_: BorrowedHandle<'_>, _: LockKind, _: bool) -> Result<bool> {
    unsupported()
}

pub(crate) fn unlock(_: BorrowedHandle<'_>) -> Result<()> {
    unsupported()
}

pub(crate) fn create_dir(path: &[u8], _mode: u32) -> Result<()> {
    resolve(path, create_dir_in)
}

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

fn create_dir_in(dir: i32, path: &[u8]) -> Result<()> {
    // SAFETY: `path` is readable for its length.
    cvt(unsafe { path_create_directory(dir, path.as_ptr(), path.len()) })
}

pub(crate) fn remove_dir(path: &[u8]) -> Result<()> {
    resolve(path, remove_dir_in)
}

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

fn remove_dir_in(dir: i32, path: &[u8]) -> Result<()> {
    // SAFETY: `path` is readable for its length.
    cvt(unsafe { path_remove_directory(dir, path.as_ptr(), path.len()) })
}

pub(crate) fn remove_file(path: &[u8]) -> Result<()> {
    resolve(path, remove_file_in)
}

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

fn remove_file_in(dir: i32, path: &[u8]) -> Result<()> {
    // SAFETY: `path` is readable for its length.
    cvt(unsafe { path_unlink_file(dir, path.as_ptr(), path.len()) })
}

pub(crate) fn rename(from: &[u8], to: &[u8]) -> Result<()> {
    resolve(from, |from_dir, from| {
        resolve(to, |to_dir, to| rename_in(from_dir, from, to_dir, 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<()> {
    // SAFETY: both paths are readable for their lengths.
    cvt(unsafe {
        path_rename(
            from_dir,
            from.as_ptr(),
            from.len(),
            to_dir,
            to.as_ptr(),
            to.len(),
        )
    })
}

pub(crate) fn hard_link(original: &[u8], link: &[u8]) -> Result<()> {
    resolve(original, |original_dir, original| {
        resolve(link, |link_dir, link| {
            hard_link_in(original_dir, original, link_dir, link)
        })
    })
}

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

fn hard_link_in(original_dir: i32, original: &[u8], link_dir: i32, link: &[u8]) -> Result<()> {
    // SAFETY: both paths are readable for their lengths.
    cvt(unsafe {
        path_link(
            original_dir,
            0,
            original.as_ptr(),
            original.len(),
            link_dir,
            link.as_ptr(),
            link.len(),
        )
    })
}

pub(crate) fn symlink(target: &[u8], link: &[u8]) -> Result<()> {
    // The target is stored as it is: only the link is looked up.
    resolve(link, |dir, link| symlink_in(target, dir, 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], dir: i32, link: &[u8]) -> Result<()> {
    if target.contains(&0) {
        return Err(ErrorKind::InvalidInput.into());
    }
    // SAFETY: both paths are readable for their lengths.
    cvt(unsafe {
        path_symlink(
            target.as_ptr(),
            target.len(),
            dir,
            link.as_ptr(),
            link.len(),
        )
    })
}

pub(crate) fn read_link(path: &[u8], buf: &mut [u8]) -> Result<usize> {
    resolve(path, |dir, path| read_link_in(dir, 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(dir: i32, path: &[u8], buf: &mut [u8]) -> Result<usize> {
    let readlink = |buf: &mut [u8]| -> Result<usize> {
        let mut used = 0;
        // SAFETY: `path` is readable and `buf` writable for their lengths;
        // `used` is written by the call.
        let result = cvt(unsafe {
            path_readlink(
                dir,
                path.as_ptr(),
                path.len(),
                buf.as_mut_ptr(),
                buf.len(),
                &raw mut used,
            )
        });
        match result {
            Ok(()) => Ok(used),
            // Some hosts say that the target does not fit.
            Err(error) if error.raw_os_error() == errno::ENOBUFS => {
                Err(ErrorKind::BufferTooSmall.into())
            }
            Err(error) => Err(error),
        }
    };
    if buf.is_empty() {
        // Find out what the path is with a buffer of our own.
        readlink(&mut [0])?;
        return Err(ErrorKind::BufferTooSmall.into());
    }
    let len = readlink(buf)?;
    // The others cut the target 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)
}

pub(crate) fn canonicalize(_: &[u8], _: &mut [u8]) -> Result<usize> {
    unsupported()
}

pub(crate) fn current_dir(_: &mut [u8]) -> Result<usize> {
    unsupported()
}

pub(crate) fn set_current_dir(_: &[u8]) -> Result<()> {
    unsupported()
}

/// The size of the buffer `fd_readdir` fills.
const DIR_BUF: usize = 4096;
/// The size of a `dirent`, which the name follows: `d_next` and `d_ino`
/// (8 bytes each), `d_namlen` (4), `d_type` (1) and padding.
const DIRENT_SIZE: usize = 24;

pub(crate) struct Dir {
    handle: OwnedHandle,
    buf: [u8; DIR_BUF],
    /// Where the next entry starts in `buf`.
    pos: usize,
    /// Where what the host wrote ends.
    end: usize,
    /// Where the listing goes on: the `d_next` of the last entry returned.
    cookie: u64,
    /// Whether the host had nothing more to write after `buf[..end]`.
    done: bool,
}

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

    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>> {
        let mut refilled = false;
        loop {
            // A whole entry in the buffer? The host fills the buffer to the
            // brim: its last entry is usually cut short.
            let left = &self.buf[self.pos..self.end];
            if let Some((header, rest)) = left.split_first_chunk::<DIRENT_SIZE>() {
                let field = |at: usize| {
                    let mut bytes = [0u8; 8];
                    bytes.copy_from_slice(&header[at..at + 8]);
                    u64::from_le_bytes(bytes)
                };
                let name_len =
                    u32::from_le_bytes([header[16], header[17], header[18], header[19]]) as usize;
                if name_len <= rest.len() {
                    let start = self.pos + DIRENT_SIZE;
                    self.pos = start + name_len;
                    self.cookie = field(0);
                    return Ok(Some(RawDirEntry {
                        name: (start, start + name_len),
                        file_type: match header[20] {
                            0 => None,
                            kind => Some(file_type(kind)),
                        },
                        inode: field(8),
                    }));
                }
                if DIRENT_SIZE + name_len > DIR_BUF {
                    // It will never fit.
                    return Err(Error::from_raw_os_error(errno::ENAMETOOLONG));
                }
            }
            if self.done {
                return Ok(None);
            }
            if refilled {
                // A buffer that starts at an entry and does not hold it.
                return Err(ErrorKind::Other.into());
            }
            let mut used = 0;
            self.pos = 0;
            self.end = 0;
            // SAFETY: `buf` is writable for its length and `used` is
            // written by the call.
            cvt(unsafe {
                fd_readdir(
                    self.handle.as_raw(),
                    self.buf.as_mut_ptr(),
                    DIR_BUF,
                    self.cookie as i64,
                    &raw mut used,
                )
            })?;
            self.end = used.min(DIR_BUF);
            // A buffer that is not full is the end of the directory.
            self.done = used < DIR_BUF;
            refilled = true;
        }
    }
}