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
//! WASI preview 1: the `wasi_snapshot_preview1` imports, declared next to
//! their users:
//!
//! ```ignore
//! #[link(wasm_import_module = "wasi_snapshot_preview1")]
//! unsafe extern "C" {
//!     fn fd_close(fd: i32) -> i32;
//! }
//! ```
//!
//! Every import returns an `errno` (0 for success) and writes its results
//! through pointer arguments; 64-bit arguments are plain `i64`.
//!
//! WASI has no memory mapping, no processes, no threads and no way to create
//! a socket: the portable functions for those fail with `Unsupported`.
//!
//! # The calls of preview 1, and what uses each
//!
//! Every one of the 46 is listed, so that a portable function that fails
//! here can be seen to fail for want of a call and not of a look.
//!
//! | Call | Used by |
//! |---|---|
//! | `args_get`, `args_sizes_get` | `process::args` |
//! | `environ_get`, `environ_sizes_get` | `process::vars` |
//! | `clock_res_get`, `clock_time_get` | `time` |
//! | `fd_allocate`, `fd_filestat_set_size` | `fs::allocate`, `fs::set_len` |
//! | `fd_close` | closing a handle |
//! | `fd_datasync`, `fd_sync` | `fs::sync_data`, `fs::sync_all` |
//! | `fd_fdstat_get` | `io::is_terminal`, `io::set_nonblocking`, the kind of a socket |
//! | `fd_fdstat_set_flags` | `net::set_nonblocking`, `io::set_nonblocking` |
//! | `fd_filestat_get`, `path_filestat_get` | metadata |
//! | `fd_filestat_set_times`, `path_filestat_set_times` | file times |
//! | `fd_pread`, `fd_pwrite`, `fd_read`, `fd_write`, `fd_seek` | `io` |
//! | `fd_prestat_get`, `fd_prestat_dir_name` | finding the directory of a path |
//! | `fd_readdir` | directory listing |
//! | `path_create_directory`, `path_remove_directory`, `path_unlink_file` | `fs` |
//! | `path_link`, `path_symlink`, `path_readlink`, `path_rename`, `path_open` | `fs` |
//! | `poll_oneoff` | `event`, `time::sleep` |
//! | `proc_exit` | `process::exit` |
//! | `random_get` | `rand` |
//! | `sched_yield` | `thread::yield_now` |
//! | `sock_accept`, `sock_recv`, `sock_send`, `sock_shutdown` | `net`, on sockets the host opened |
//!
//! Five are used by nothing, for want of a portable function to stand
//! behind:
//!
//! - `fd_advise`: oscall has no advice about a file's access pattern (it
//!   has for memory, which WASI lacks).
//! - `fd_renumber`: it moves a descriptor onto a number and closes what
//!   was there. Nothing in `io` assigns numbers, and `io::duplicate` wants
//!   a second descriptor for the same file, which this does not make.
//! - `fd_tell`: `fd_seek` by nothing answers the same.
//! - `fd_fdstat_set_rights`: oscall has no notion of rights, and the call
//!   was deprecated before preview 1 was final.
//! - `proc_raise`: there is no portable way to raise a signal, and
//!   `process::abort` is a trap (`unreachable`), which every host turns
//!   into an abnormal end. Hosts disagree about this call: some refuse it,
//!   and one that implements it does so by signalling the host process.

pub mod errno;

pub(crate) mod env;
pub(crate) mod event;
pub(crate) mod fs;
pub(crate) mod io;
pub(crate) mod mem;
pub(crate) mod net;
pub(crate) mod process;
pub(crate) mod rand;
pub(crate) mod resolve;
pub(crate) mod sync;
pub(crate) mod thread;
pub(crate) mod time;

use crate::{Error, ErrorKind, Result};

pub(crate) type RawHandle = i32;

#[link(wasm_import_module = "wasi_snapshot_preview1")]
unsafe extern "C" {
    fn fd_close(fd: i32) -> i32;
}

/// Converts a WASI `errno` return value to a `Result`.
#[inline]
pub(crate) fn cvt(errno: i32) -> Result<()> {
    if errno == 0 {
        Ok(())
    } else {
        Err(Error::from_raw_os_error(errno))
    }
}

/// # Safety
///
/// `fd` must be an open descriptor that nothing uses afterwards.
pub(crate) unsafe fn close(fd: RawHandle) {
    // SAFETY: closing a descriptor the caller owns.
    let _ = cvt(unsafe { fd_close(fd) });
}

/// The generic I/O error.
pub(crate) const OTHER_ERROR: i32 = errno::EIO;

/// The classification of error codes. The first entry of a kind is the code
/// `Error::from(kind)` produces.
pub(crate) const ERRORS: &[(i32, ErrorKind)] = {
    use ErrorKind::*;
    use errno::*;
    &[
        (ENOENT, NotFound),
        (EACCES, PermissionDenied),
        (EPERM, PermissionDenied),
        (ENOTCAPABLE, PermissionDenied),
        (EEXIST, AlreadyExists),
        (EAGAIN, WouldBlock),
        (EINPROGRESS, InProgress),
        (EALREADY, InProgress),
        (EINTR, Interrupted),
        (EINVAL, InvalidInput),
        (ETIMEDOUT, TimedOut),
        (ENOTSUP, Unsupported),
        (ENOSYS, Unsupported),
        (EAFNOSUPPORT, Unsupported),
        (EPROTONOSUPPORT, Unsupported),
        (ENOMEM, OutOfMemory),
        (EBADF, BadHandle),
        (ENOTSOCK, BadHandle),
        (EPIPE, BrokenPipe),
        (ENOTDIR, NotADirectory),
        (EISDIR, IsADirectory),
        (ENOTEMPTY, DirectoryNotEmpty),
        (ENAMETOOLONG, InvalidFilename),
        (ERANGE, BufferTooSmall),
        (ELOOP, FilesystemLoop),
        (ENOSPC, StorageFull),
        (EDQUOT, QuotaExceeded),
        (EFBIG, FileTooLarge),
        (EROFS, ReadOnlyFilesystem),
        (EXDEV, CrossesDevices),
        (EMLINK, TooManyLinks),
        (EMFILE, TooManyOpenFiles),
        (ENFILE, TooManyOpenFiles),
        (EBUSY, ResourceBusy),
        (EDEADLK, Deadlock),
        (ESPIPE, NotSeekable),
        (ETXTBSY, ExecutableFileBusy),
        (ECONNREFUSED, ConnectionRefused),
        (ECONNRESET, ConnectionReset),
        (ECONNABORTED, ConnectionAborted),
        (ENOTCONN, NotConnected),
        (EISCONN, AlreadyConnected),
        (EADDRINUSE, AddrInUse),
        (EADDRNOTAVAIL, AddrNotAvailable),
        (ENETDOWN, NetworkDown),
        (ENETUNREACH, NetworkUnreachable),
        (EHOSTUNREACH, HostUnreachable),
        (EMSGSIZE, MessageTooLong),
        (ESRCH, NoSuchProcess),
        (ECANCELED, Canceled),
    ]
};

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn calls() {
        // SAFETY: closing a descriptor that is not open only fails.
        let err = cvt(unsafe { fd_close(12345) }).unwrap_err();
        assert_eq!(err.raw_os_error(), errno::EBADF);
        assert_eq!(err.kind(), ErrorKind::BadHandle);
    }
}