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
//! The raw layer: each system's module, on that system.

#[cfg(any(target_os = "linux", target_os = "fullrust"))]
mod linux {
    use oscall::raw::linux::{check, errno, nr, syscall, syscall0, syscall1, syscall2, syscall6};
    use oscall::{ErrorKind, OwnedHandle};

    #[cfg(target_pointer_width = "32")]
    const MMAP: usize = nr::MMAP2; // the offset is in pages
    #[cfg(target_pointer_width = "64")]
    const MMAP: usize = nr::MMAP;

    const PROT_READ_WRITE: usize = 1 | 2;
    const MAP_PRIVATE_ANONYMOUS: usize = 0x02 | 0x20;

    #[test]
    fn functions() {
        // SAFETY: getpid takes nothing and cannot fail.
        let pid = unsafe { syscall0(nr::GETPID) };
        assert_eq!(check(pid), Ok(std::process::id() as usize));
        assert_eq!(pid as u32, oscall::process::id());

        // Six arguments: one in every argument register.
        // SAFETY: a new private mapping, wherever the kernel likes.
        let addr = unsafe {
            syscall6(
                MMAP,
                0,
                8192,
                PROT_READ_WRITE,
                MAP_PRIVATE_ANONYMOUS,
                -1i32 as usize,
                0,
            )
        };
        let addr = check(addr).unwrap();
        assert_eq!(addr % 4096, 0);
        // SAFETY: the mapping is two readable and writable pages that
        // nothing else knows of.
        unsafe {
            let p = addr as *mut u8;
            p.add(8191).write(7);
            assert_eq!(p.add(8191).read(), 7);
            assert_eq!(p.read(), 0);
        }
        // SAFETY: unmapping the mapping made above, which nothing uses.
        assert_eq!(unsafe { syscall2(nr::MUNMAP, addr, 8192) }, 0);

        // An error is the negated error number, in the raw value.
        // SAFETY: -1 is never an open descriptor, so nothing is closed.
        let ret = unsafe { syscall1(nr::CLOSE, -1i32 as usize) };
        assert_eq!(ret as isize, -(errno::EBADF as isize));
        let err = check(ret).unwrap_err();
        assert_eq!(err.raw_os_error(), errno::EBADF);
        assert_eq!(err.kind(), ErrorKind::BadHandle);

        // A number no kernel knows.
        // SAFETY: the kernel only refuses the call.
        let err = check(unsafe { syscall0(0xfff0) }).unwrap_err();
        assert_eq!(err.raw_os_error(), errno::ENOSYS);
        assert_eq!(err.kind(), ErrorKind::Unsupported);
    }

    #[test]
    fn check_splits() {
        assert_eq!(check(0), Ok(0));
        assert_eq!(check(usize::MAX - 4095), Ok(usize::MAX - 4095));
        assert_eq!(
            check(usize::MAX - 4094).unwrap_err().raw_os_error(),
            4095,
            "the first error value"
        );
        assert_eq!(check(usize::MAX).unwrap_err().raw_os_error(), errno::EPERM);
    }

    #[test]
    fn macro_and_handles() {
        // SAFETY: getpid takes nothing and cannot fail.
        assert_eq!(unsafe { syscall!(GETPID) }, Ok(std::process::id() as usize));

        // SAFETY: a new private mapping; a trailing comma is accepted.
        #[cfg(target_pointer_width = "32")]
        let map = unsafe { syscall!(MMAP2, 0, 4096, 3, 0x22, -1i32, 0,) };
        // SAFETY: as above.
        #[cfg(target_pointer_width = "64")]
        let map = unsafe { syscall!(MMAP, 0, 4096, 3, 0x22, -1i32, 0,) };
        let addr = map.unwrap();
        // SAFETY: unmapping the mapping made above, which nothing uses.
        unsafe { syscall!(MUNMAP, addr, 4096) }.unwrap();

        // A raw call next to the portable ones: a descriptor made here is
        // owned, used and closed by oscall.
        const AT_FDCWD: i32 = -100;
        const O_CLOEXEC: usize = 0o2000000;
        let fd = oscall::raw::with_cstr("/proc/self/stat", |path| {
            // SAFETY: the path is NUL-terminated; opening a file for reading
            // affects nothing but the descriptor returned.
            unsafe { syscall!(OPENAT, AT_FDCWD, path.as_ptr(), O_CLOEXEC, 0) }
        })
        .unwrap();
        // SAFETY: the descriptor was just opened and nothing else owns it.
        let file = unsafe { OwnedHandle::from_raw(fd as i32) };
        let mut buf = [0u8; 64];
        let n = oscall::io::read(&file, &mut buf).unwrap();
        let text = std::str::from_utf8(&buf[..n]).unwrap();
        assert!(text.starts_with(&format!("{} (", std::process::id())));

        let err = oscall::raw::with_cstr("/proc/self/nothing-here", |path| {
            // SAFETY: as above.
            unsafe { syscall!(OPENAT, AT_FDCWD, path.as_ptr(), O_CLOEXEC, 0) }
        })
        .unwrap_err();
        assert_eq!(err.raw_os_error(), errno::ENOENT);
        assert_eq!(err.kind(), ErrorKind::NotFound);
    }

    #[test]
    fn with_cstr() {
        assert_eq!(
            oscall::raw::with_cstr(b"a\0b", |_| Ok(()))
                .unwrap_err()
                .kind(),
            ErrorKind::InvalidInput
        );
        assert_eq!(
            oscall::raw::with_cstr(c"/tmp", |p| Ok(p.to_bytes_with_nul().len())),
            Ok(5)
        );
    }
}

#[cfg(target_os = "macos")]
mod apple {
    use std::ffi::{c_char, c_int};

    use oscall::ErrorKind;
    use oscall::raw::apple::{cvt, cvt_long, errno, last_error, set_errno};

    unsafe extern "C" {
        fn getpid() -> c_int;
        fn close(fd: c_int) -> c_int;
        fn access(path: *const c_char, mode: c_int) -> c_int;
        fn lseek(fd: c_int, offset: i64, whence: c_int) -> i64;
    }

    #[test]
    fn errno_and_cvt() {
        // SAFETY: getpid takes nothing and cannot fail.
        let pid = cvt(unsafe { getpid() }).unwrap();
        assert_eq!(pid as u32, std::process::id());

        // SAFETY: -1 is never an open descriptor, so nothing is closed.
        let err = cvt(unsafe { close(-1) }).unwrap_err();
        assert_eq!(err.raw_os_error(), errno::EBADF);
        assert_eq!(err.kind(), ErrorKind::BadHandle);
        assert_eq!(last_error().raw_os_error(), errno::EBADF);

        // SAFETY: as above, for a function that returns an `off_t`.
        let err = cvt_long(unsafe { lseek(-1, 0, 0) }).unwrap_err();
        assert_eq!(err.raw_os_error(), errno::EBADF);
        assert_eq!(cvt_long(5), Ok(5));

        set_errno(0);
        assert_eq!(last_error().raw_os_error(), 0);
        set_errno(errno::ENOTSUP);
        assert_eq!(last_error().raw_os_error(), errno::ENOTSUP);
        assert_eq!(last_error().kind(), ErrorKind::Unsupported);
    }

    #[test]
    fn with_cstr() {
        // SAFETY: the path is NUL-terminated and only read.
        oscall::raw::with_cstr("/", |path| cvt(unsafe { access(path.as_ptr(), 0) })).unwrap();
        let err = oscall::raw::with_cstr("/nothing-here/at-all", |path| {
            // SAFETY: as above.
            cvt(unsafe { access(path.as_ptr(), 0) })
        })
        .unwrap_err();
        assert_eq!(err.raw_os_error(), errno::ENOENT);
        assert_eq!(err.kind(), ErrorKind::NotFound);
        assert_eq!(
            oscall::raw::with_cstr(b"a\0b", |_| Ok(()))
                .unwrap_err()
                .kind(),
            ErrorKind::InvalidInput
        );
    }
}

#[cfg(windows)]
mod windows {
    use std::ffi::c_void;

    use oscall::ErrorKind;
    use oscall::raw::windows::{cvt, dll, last_error, nt_error, wide_to_wtf8, with_wide};

    // A plain import, resolved through the toolchain's import library.
    #[link(name = "kernel32")]
    unsafe extern "system" {
        fn GetCurrentProcessId() -> u32;
        fn GetFileType(handle: *mut c_void) -> u32;
        fn SetLastError(code: u32);
    }

    // The same DLL through `dll!`, which needs no import library.
    dll!(unsafe "kernel32.dll" {
        fn GetFileAttributesW(name: *const u16) -> u32;
        /// Documented, and visible to the whole crate.
        pub(crate) fn GetCurrentThreadId() -> u32;
        fn CloseHandle(handle: *mut c_void) -> i32;
    });

    dll!(unsafe "ntdll.dll" {
        fn NtClose(handle: *mut c_void) -> i32;
    });

    const INVALID_FILE_ATTRIBUTES: u32 = u32::MAX;
    const FILE_ATTRIBUTE_DIRECTORY: u32 = 0x10;
    const ERROR_FILE_NOT_FOUND: i32 = 2;
    const ERROR_INVALID_HANDLE: i32 = 6;

    #[test]
    fn imports_and_errors() {
        // SAFETY: takes nothing and cannot fail.
        assert_eq!(unsafe { GetCurrentProcessId() }, std::process::id());
        // SAFETY: as above.
        assert_ne!(unsafe { GetCurrentThreadId() }, 0);

        // 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(), ERROR_INVALID_HANDLE);
        assert_eq!(err.kind(), ErrorKind::BadHandle);

        // SAFETY: a value that is not a handle only makes the call fail.
        let err = cvt(unsafe { CloseHandle(0x7fff_fff0 as *mut c_void) }).unwrap_err();
        assert_eq!(err.raw_os_error(), ERROR_INVALID_HANDLE);
        assert_eq!(cvt(1), Ok(()));

        // SAFETY: only writes the thread's last error code.
        unsafe { SetLastError(ERROR_FILE_NOT_FOUND as u32) };
        assert_eq!(last_error().raw_os_error(), ERROR_FILE_NOT_FOUND);
        assert_eq!(last_error().kind(), ErrorKind::NotFound);
    }

    #[test]
    fn ntstatus() {
        // SAFETY: a value that is not a handle only makes the call fail.
        let status = unsafe { NtClose(0x7fff_fff0 as *mut c_void) };
        assert_eq!(status as u32, 0xC000_0008, "STATUS_INVALID_HANDLE");
        let err = nt_error(status);
        assert_eq!(err.raw_os_error(), ERROR_INVALID_HANDLE);
        assert_eq!(err.kind(), ErrorKind::BadHandle);
        // STATUS_OBJECT_NAME_NOT_FOUND
        assert_eq!(
            nt_error(0xC000_0034u32 as i32).raw_os_error(),
            ERROR_FILE_NOT_FOUND
        );
    }

    #[test]
    fn wide() {
        let dir = std::env::temp_dir();
        let attributes = with_wide(dir.to_str().unwrap(), |name| {
            assert_eq!(name.last(), Some(&0));
            // SAFETY: the name is NUL-terminated UTF-16 and only read.
            match unsafe { GetFileAttributesW(name.as_ptr()) } {
                INVALID_FILE_ATTRIBUTES => Err(last_error()),
                attributes => Ok(attributes),
            }
        })
        .unwrap();
        assert_ne!(attributes & FILE_ATTRIBUTE_DIRECTORY, 0);

        let missing = dir.join("oscall-raw-nothing-here-\u{e9}\u{1f600}");
        let err = with_wide(missing.to_str().unwrap(), |name| {
            // The conversion is the one `std` makes.
            let expected: Vec<u16> =
                std::os::windows::ffi::OsStrExt::encode_wide(missing.as_os_str())
                    .chain([0])
                    .collect();
            assert_eq!(name, expected);
            // And back.
            let mut bytes = vec![0u8; name.len() * 3];
            let len = wide_to_wtf8(&name[..name.len() - 1], &mut bytes).unwrap();
            assert_eq!(&bytes[..len], missing.to_str().unwrap().as_bytes());
            // SAFETY: the name is NUL-terminated UTF-16 and only read.
            match unsafe { GetFileAttributesW(name.as_ptr()) } {
                INVALID_FILE_ATTRIBUTES => Err(last_error()),
                attributes => Ok(attributes),
            }
        })
        .unwrap_err();
        assert_eq!(err.raw_os_error(), ERROR_FILE_NOT_FOUND);

        assert_eq!(
            with_wide("a\0b", |_| Ok(())).unwrap_err().kind(),
            ErrorKind::InvalidInput
        );
        assert_eq!(wide_to_wtf8(&[0x4e16], &mut [0u8; 2]), None);
        let mut lone = [0u8; 3];
        assert_eq!(wide_to_wtf8(&[0xd800], &mut lone), Some(3));
        assert_eq!(lone, [0xed, 0xa0, 0x80]);
    }
}

#[cfg(target_os = "wasi")]
mod wasi {
    use oscall::ErrorKind;
    use oscall::raw::wasi::{cvt, errno};

    #[link(wasm_import_module = "wasi_snapshot_preview1")]
    unsafe extern "C" {
        fn fd_close(fd: i32) -> i32;
        fn fd_fdstat_get(fd: i32, stat: *mut [u64; 3]) -> i32;
        fn sched_yield() -> i32;
    }

    #[test]
    fn imports_and_errno() {
        // SAFETY: takes nothing.
        cvt(unsafe { sched_yield() }).unwrap();

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

        // A call that succeeds and writes a result: standard output is
        // open. `fdstat` is 24 bytes, aligned to 8.
        let mut stat = [0u64; 3];
        // SAFETY: the system writes one `fdstat` to `stat`.
        cvt(unsafe { fd_fdstat_get(1, &raw mut stat) }).unwrap();
        // SAFETY: as above, on a descriptor that is not open.
        let err = cvt(unsafe { fd_fdstat_get(12345, &raw mut stat) }).unwrap_err();
        assert_eq!(err.raw_os_error(), errno::EBADF);
    }
}