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
//! Windows: `kernel32`, `ntdll` and `ws2_32`.
//!
//! Functions are imported with [`dll!`], next to their users. Handles are
//! `*mut c_void`; `BOOL` is `i32`; `DWORD` is `u32`; strings are
//! NUL-terminated UTF-16 (see `crate::path::with_wide`).

#[cfg(not(any(
    target_arch = "x86",
    target_arch = "x86_64",
    target_arch = "arm",
    target_arch = "aarch64",
)))]
compile_error!("oscall does not support this architecture on Windows");

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 overlapped;
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 core::ffi::c_void;

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

pub(crate) type RawHandle = *mut c_void;

/// Declares functions imported from a system DLL:
///
/// ```ignore
/// dll!("kernel32.dll" {
///     fn CloseHandle(handle: *mut c_void) -> i32;
/// });
/// ```
///
/// The import is `raw-dylib`: no import library is needed, whatever the
/// toolchain. The functions are `extern "system"` (stdcall on x86, where
/// the DLLs export the undecorated names).
macro_rules! dll {
    ($dll:literal { $($item:tt)* }) => {
        #[cfg_attr(
            target_arch = "x86",
            link(
                name = $dll,
                kind = "raw-dylib",
                modifiers = "+verbatim",
                import_name_type = "undecorated"
            )
        )]
        #[cfg_attr(
            not(target_arch = "x86"),
            link(name = $dll, kind = "raw-dylib", modifiers = "+verbatim")
        )]
        unsafe extern "system" {
            $($item)*
        }
    };
}
#[allow(unused_imports)]
pub(crate) use dll;

dll!("kernel32.dll" {
    fn CloseHandle(handle: *mut c_void) -> i32;
    fn GetLastError() -> u32;
});

/// The calling thread's last error code, as an [`Error`].
#[inline]
pub(crate) fn last_error() -> Error {
    // SAFETY: GetLastError only reads thread-local state.
    Error::from_raw_os_error(unsafe { GetLastError() } as i32)
}

/// Converts a `BOOL` return value (zero for failure, with the reason in
/// `GetLastError`) to a `Result`.
#[inline]
#[allow(dead_code)]
pub(crate) fn cvt(ret: i32) -> Result<()> {
    if ret == 0 { Err(last_error()) } else { Ok(()) }
}

dll!("ntdll.dll" {
    fn RtlNtStatusToDosError(status: i32) -> u32;
});

/// The error for an `NTSTATUS`: the code Win32 reports for it.
#[inline]
#[allow(dead_code)]
pub(crate) fn nt_error(status: i32) -> Error {
    // SAFETY: no memory is involved.
    Error::from_raw_os_error(unsafe { RtlNtStatusToDosError(status) } as i32)
}

/// # Safety
///
/// `handle` must be an open handle that nothing uses afterwards.
pub(crate) unsafe fn close(handle: RawHandle) {
    // SAFETY: closing a handle the caller owns.
    unsafe { CloseHandle(handle) };
}

/// `ERROR_GEN_FAILURE`.
pub(crate) const OTHER_ERROR: i32 = 31;

/// The classification of error codes (`ERROR_*` up to 9999, `WSAE*` from
/// 10000). The first entry of a kind is the code `Error::from(kind)`
/// produces.
pub(crate) const ERRORS: &[(i32, ErrorKind)] = {
    use ErrorKind::*;
    &[
        (2, NotFound),               // ERROR_FILE_NOT_FOUND
        (3, NotFound),               // ERROR_PATH_NOT_FOUND
        (15, NotFound),              // ERROR_INVALID_DRIVE
        (53, NotFound),              // ERROR_BAD_NETPATH
        (67, NotFound),              // ERROR_BAD_NET_NAME
        (5, PermissionDenied),       // ERROR_ACCESS_DENIED
        (1314, PermissionDenied),    // ERROR_PRIVILEGE_NOT_HELD
        (1300, PermissionDenied),    // ERROR_NOT_ALL_ASSIGNED
        (10013, PermissionDenied),   // WSAEACCES
        (183, AlreadyExists),        // ERROR_ALREADY_EXISTS
        (80, AlreadyExists),         // ERROR_FILE_EXISTS
        (10035, WouldBlock),         // WSAEWOULDBLOCK
        (10036, InProgress),         // WSAEINPROGRESS
        (10037, InProgress),         // WSAEALREADY
        (997, InProgress),           // ERROR_IO_PENDING
        (10004, Interrupted),        // WSAEINTR
        (87, InvalidInput),          // ERROR_INVALID_PARAMETER
        (131, InvalidInput),         // ERROR_NEGATIVE_SEEK
        (10022, InvalidInput),       // WSAEINVAL
        (10014, InvalidInput),       // WSAEFAULT
        (1460, TimedOut),            // ERROR_TIMEOUT
        (121, TimedOut),             // ERROR_SEM_TIMEOUT
        (258, TimedOut),             // WAIT_TIMEOUT
        (10060, TimedOut),           // WSAETIMEDOUT
        (50, Unsupported),           // ERROR_NOT_SUPPORTED
        (120, Unsupported),          // ERROR_CALL_NOT_IMPLEMENTED
        (1, Unsupported),            // ERROR_INVALID_FUNCTION
        (10045, Unsupported),        // WSAEOPNOTSUPP
        (10047, Unsupported),        // WSAEAFNOSUPPORT
        (10043, Unsupported),        // WSAEPROTONOSUPPORT
        (10044, Unsupported),        // WSAESOCKTNOSUPPORT
        (14, OutOfMemory),           // ERROR_OUTOFMEMORY
        (8, OutOfMemory),            // ERROR_NOT_ENOUGH_MEMORY
        (1455, OutOfMemory),         // ERROR_COMMITMENT_LIMIT
        (6, BadHandle),              // ERROR_INVALID_HANDLE
        (10009, BadHandle),          // WSAEBADF
        (10038, BadHandle),          // WSAENOTSOCK
        (109, BrokenPipe),           // ERROR_BROKEN_PIPE
        (232, BrokenPipe),           // ERROR_NO_DATA
        (10058, BrokenPipe),         // WSAESHUTDOWN
        (267, NotADirectory),        // ERROR_DIRECTORY
        (336, IsADirectory),         // ERROR_DIRECTORY_NOT_SUPPORTED
        (145, DirectoryNotEmpty),    // ERROR_DIR_NOT_EMPTY
        (123, InvalidFilename),      // ERROR_INVALID_NAME
        (206, InvalidFilename),      // ERROR_FILENAME_EXCED_RANGE
        (161, InvalidFilename),      // ERROR_BAD_PATHNAME
        (122, BufferTooSmall),       // ERROR_INSUFFICIENT_BUFFER
        (1921, FilesystemLoop),      // ERROR_CANT_RESOLVE_FILENAME
        (112, StorageFull),          // ERROR_DISK_FULL
        (39, StorageFull),           // ERROR_HANDLE_DISK_FULL
        (1295, QuotaExceeded),       // ERROR_DISK_QUOTA_EXCEEDED
        (223, FileTooLarge),         // ERROR_FILE_TOO_LARGE
        (19, ReadOnlyFilesystem),    // ERROR_WRITE_PROTECT
        (17, CrossesDevices),        // ERROR_NOT_SAME_DEVICE
        (1142, TooManyLinks),        // ERROR_TOO_MANY_LINKS
        (4, TooManyOpenFiles),       // ERROR_TOO_MANY_OPEN_FILES
        (10024, TooManyOpenFiles),   // WSAEMFILE
        (170, ResourceBusy),         // ERROR_BUSY
        (32, ResourceBusy),          // ERROR_SHARING_VIOLATION
        (33, ResourceBusy),          // ERROR_LOCK_VIOLATION
        (231, ResourceBusy),         // ERROR_PIPE_BUSY
        (1131, Deadlock),            // ERROR_POSSIBLE_DEADLOCK
        (132, NotSeekable),          // ERROR_SEEK_ON_DEVICE
        (10061, ConnectionRefused),  // WSAECONNREFUSED
        (1225, ConnectionRefused),   // ERROR_CONNECTION_REFUSED
        (10054, ConnectionReset),    // WSAECONNRESET
        (64, ConnectionReset),       // ERROR_NETNAME_DELETED
        (10053, ConnectionAborted),  // WSAECONNABORTED
        (1236, ConnectionAborted),   // ERROR_CONNECTION_ABORTED
        (10057, NotConnected),       // WSAENOTCONN
        (233, NotConnected),         // ERROR_PIPE_NOT_CONNECTED
        (10056, AlreadyConnected),   // WSAEISCONN
        (10048, AddrInUse),          // WSAEADDRINUSE
        (10049, AddrNotAvailable),   // WSAEADDRNOTAVAIL
        (10050, NetworkDown),        // WSAENETDOWN
        (10051, NetworkUnreachable), // WSAENETUNREACH
        (1231, NetworkUnreachable),  // ERROR_NETWORK_UNREACHABLE
        (10065, HostUnreachable),    // WSAEHOSTUNREACH
        (1232, HostUnreachable),     // ERROR_HOST_UNREACHABLE
        (10040, MessageTooLong),     // WSAEMSGSIZE
        (234, MessageTooLong),       // ERROR_MORE_DATA
        (995, Canceled),             // ERROR_OPERATION_ABORTED
        (1223, Canceled),            // ERROR_CANCELLED
        // What the resolver says (`GetAddrInfoW`), after every code that
        // is the first of its kind.
        (11001, NotFound), // WSAHOST_NOT_FOUND
        (11004, NotFound), // WSANO_DATA
        (11002, TimedOut), // WSATRY_AGAIN
    ]
};

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

    dll!("kernel32.dll" {
        fn GetCurrentProcessId() -> u32;
        fn GetFileType(handle: *mut c_void) -> u32;
    });

    #[test]
    fn calls() {
        // SAFETY: takes nothing and cannot fail.
        let pid = unsafe { GetCurrentProcessId() };
        assert!(pid > 0);
        #[cfg(feature = "std")]
        assert_eq!(pid, std::process::id());

        // An argument and an error, to exercise the calling convention.
        // SAFETY: an invalid handle only makes the call fail.
        let kind = unsafe { GetFileType(usize::MAX as *mut c_void) };
        assert_eq!(kind, 0);
        let err = last_error();
        assert_eq!(err.raw_os_error(), 6);
        assert_eq!(err.kind(), ErrorKind::BadHandle);
    }
}