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
//! The raw layer: what oscall itself is built on, for whatever the portable
//! modules lack.
//!
//! Nothing here is portable. There is one sub-module per system, present
//! only on that system, and each holds what a direct call to that system
//! needs:
//!
//! - `linux` (Linux and fullrust): the system call itself
//!   (`syscall0`..`syscall6`, the `syscall!` macro), the system call numbers
//!   of the target architecture and the error numbers.
//! - `apple` (macOS): `errno` and the conversions of the `-1` convention.
//!   The functions are `libSystem`'s: declare the ones you need.
//! - `windows`: `GetLastError` and `NTSTATUS` as an [`Error`](crate::Error),
//!   the conversion of paths to and from UTF-16, and `dll!` to import
//!   functions without an import library.
//! - `wasi`: the error numbers of WASI preview 1 and their conversion.
//!
//! Handles go in and out of this layer with
//! [`BorrowedHandle::as_raw`](crate::BorrowedHandle::as_raw),
//! [`OwnedHandle::from_raw`](crate::OwnedHandle::from_raw) and
//! [`OwnedHandle::into_raw`](crate::OwnedHandle::into_raw), and errors with
//! [`Error::from_raw_os_error`](crate::Error::from_raw_os_error): a raw call
//! sits next to the portable ones, on the same handles.
//!
//! ```
//! # #[cfg(any(target_os = "linux", target_os = "fullrust"))] {
//! use oscall::raw::linux::syscall;
//!
//! // SAFETY: getppid takes nothing and changes nothing.
//! let parent = unsafe { syscall!(GETPPID) }.unwrap();
//! # let _ = parent;
//! # }
//! ```

/// Calls `f` with `path` as a NUL-terminated C string, the form paths take
/// in the system calls of Linux and in the functions of `libSystem`.
///
/// The string is built on the stack when the path is shorter than 512 bytes,
/// and on the heap otherwise, which needs the `alloc` feature: without it a
/// longer path fails with [`ErrorKind::InvalidFilename`]. A path that
/// contains a NUL fails with [`ErrorKind::InvalidInput`].
///
/// The string only lives for the duration of the call to `f`.
///
/// [`ErrorKind::InvalidFilename`]: crate::ErrorKind::InvalidFilename
/// [`ErrorKind::InvalidInput`]: crate::ErrorKind::InvalidInput
#[cfg(not(any(windows, target_family = "wasm")))]
pub fn with_cstr<P: crate::AsPath + ?Sized, R>(
    path: &P,
    f: impl FnOnce(&core::ffi::CStr) -> crate::Result<R>,
) -> crate::Result<R> {
    crate::path::with_cstr(path.as_path_bytes(), f)
}

#[cfg(any(target_os = "linux", target_os = "fullrust"))]
pub mod linux {
    //! Linux and fullrust: raw system calls.
    //!
    //! The kernel is called directly, with inline assembly: no libc is involved,
    //! whether there is one in the process or not. [`syscall0`] to [`syscall6`]
    //! make the call and return the kernel's value untouched; [`check`] splits
    //! that value into a result and an error number; [`syscall!`] does both from
    //! a system call's name.
    //!
    //! # The system call interface
    //!
    //! - Every argument is a register-sized `usize`. A signed value is
    //!   sign-extended (`fd as usize` of an `i32` is, and so is what `syscall!`
    //!   does); a pointer is its address.
    //! - **Numbers and names differ between architectures.** aarch64 and riscv
    //!   have only the modern call of each family (`openat` and no `open`,
    //!   `statx` and no `stat`, `ppoll` and no `poll`...). 32-bit
    //!   architectures have `mmap2`, `_llseek` or `llseek`, `fcntl64` and the
    //!   64-bit time calls (`clock_gettime64`, `futex_time64`,
    //!   `ppoll_time64`...), which are the only time calls riscv32 has. [`nr`]
    //!   holds the calls of the target architecture alone: code for several
    //!   architectures selects with `cfg(target_arch)` or
    //!   `cfg(target_pointer_width)`.
    //! - **A 64-bit argument on a 32-bit architecture** takes two registers, low
    //!   half first (oscall supports little-endian targets only), and arm wants
    //!   the pair to start at an even argument position, with a padding argument
    //!   before it when it would not, where x86 does not.
    //! - **Structures and constants are the kernel's**, not a libc's, and some
    //!   differ between architectures (the `O_*` flags, `struct stat`,
    //!   `struct sigaction`, `struct epoll_event`). The `struct timespec` the
    //!   64-bit time calls take is two `i64`s on every architecture.
    //! - An interrupted call returns [`errno::EINTR`]: nothing restarts it for
    //!   you.
    //!
    //! # When a libc is in the process
    //!
    //! On plain Linux targets the program is linked with a libc, which knows
    //! nothing of the system calls made behind its back. Calls that do not touch
    //! what it keeps state about are fine. These are not, and are part of the
    //! contract of every function here:
    //!
    //! - **The program break** (`brk`): the allocator of libc owns it.
    //! - **Creating threads** (`clone` with `CLONE_THREAD` or `CLONE_VM`,
    //!   `clone3`): a thread libc did not create has no thread-local storage,
    //!   and neither libc functions nor most Rust code may run on it.
    //!   `set_tid_address`, `set_robust_list`, `set_thread_area` and
    //!   `arch_prctl(ARCH_SET_FS)` change what libc set up for the thread.
    //! - **`fork`-like calls**: libc's own state (locks, cached process and
    //!   thread ids) is not updated in the child, which may only make system
    //!   calls until it calls `execve` or `exit_group`. With `CLONE_VM` the
    //!   child shares the parent's memory, and with `CLONE_VFORK` its stack.
    //! - **Signals**: `rt_sigaction` wants the kernel's `struct sigaction` and
    //!   your own `sa_restorer` where the architecture needs one; libc reserves
    //!   some real-time signals for itself, and what libc believes of a
    //!   disposition or of the signal mask is not updated.
    //! - **Descriptors and memory that belong to something else**: closing or
    //!   replacing (`close`, `dup3`, `close_range`) a descriptor that other code
    //!   owns, and unmapping, remapping or changing the protection of memory you
    //!   did not map yourself.
    //! - **`exit`** ends the calling thread without running anything;
    //!   `exit_group` ends the process without flushing what libc buffers.
    //!
    //! In a fullrust program there is no libc, and the same rules protect the
    //! state of fullrust's `std` instead.

    use crate::sys;

    /// The error numbers of Linux (`EPERM`, `ENOENT`...), the same on every
    /// architecture oscall supports. They are the values
    /// [`Error::raw_os_error`](crate::Error::raw_os_error) returns.
    pub mod errno {
        pub use crate::sys::errno::*;
    }
    /// The system call numbers of the target architecture, generated from
    /// the kernel's tables.
    ///
    /// Which names exist depends on the architecture: see the
    /// [module documentation](self#the-system-call-interface).
    /// A call newer than the table can be made by its number, with
    /// [`syscall0`] and its siblings.
    pub mod nr {
        pub use crate::sys::nr::*;
    }

    /// Makes a system call by name and checks its result:
    /// `syscall!(NAME, args...)` is a [`Result<usize>`](crate::Result).
    ///
    /// `NAME` is a constant of [`nr`]; up to six arguments follow, each cast
    /// with `as usize`: a negative `i32` sign-extends (a negative literal
    /// needs its type, `-1i32`), a pointer passes as its address, and a
    /// 64-bit value on a 32-bit architecture must be split by the caller the
    /// way that system call expects.
    ///
    /// The expansion calls an `unsafe` function, [`syscall0`] to
    /// [`syscall6`], and must be used in an `unsafe` block.
    ///
    /// # Safety
    ///
    /// As for [`syscall6`].
    ///
    /// # Examples
    ///
    /// ```
    /// use oscall::ErrorKind;
    /// use oscall::raw::linux::{errno, syscall};
    ///
    /// // SAFETY: -1 is never an open descriptor, so nothing is closed.
    /// let err = unsafe { syscall!(CLOSE, -1i32) }.unwrap_err();
    /// assert_eq!(err.raw_os_error(), errno::EBADF);
    /// assert_eq!(err.kind(), ErrorKind::BadHandle);
    /// ```
    #[doc(inline)]
    pub use crate::__raw_linux_syscall as syscall;

    /// Splits the return value of a system call: the kernel reports an error
    /// as `-errno`, in the last 4095 values of the address space, and
    /// anything else is the result.
    ///
    /// ```
    /// use oscall::raw::linux::{check, errno};
    ///
    /// assert_eq!(check(3), Ok(3));
    /// let err = check(-errno::ENOENT as usize).unwrap_err();
    /// assert_eq!(err.raw_os_error(), errno::ENOENT);
    /// ```
    #[inline]
    pub fn check(ret: usize) -> crate::Result<usize> {
        sys::check(ret)
    }

    macro_rules! define {
        ($(#[$doc:meta])* $name:ident $(, $arg:ident)*) => {
            $(#[$doc])*
            ///
            /// Returns what the kernel returned: see [`check`].
            ///
            /// # Safety
            ///
            /// As for [`syscall6`].
            #[inline]
            pub unsafe fn $name(nr: usize $(, $arg: usize)*) -> usize {
                // SAFETY: the caller upholds the system call's contract.
                unsafe { sys::arch::$name(nr $(, $arg)*) }
            }
        };
    }

    define!(
        /// Makes the system call `nr`, with no argument.
        syscall0
    );
    define!(
        /// Makes the system call `nr` with one argument.
        syscall1,
        a
    );
    define!(
        /// Makes the system call `nr` with two arguments.
        syscall2,
        a,
        b
    );
    define!(
        /// Makes the system call `nr` with three arguments.
        syscall3,
        a,
        b,
        c
    );
    define!(
        /// Makes the system call `nr` with four arguments.
        syscall4,
        a,
        b,
        c,
        d
    );
    define!(
        /// Makes the system call `nr` with five arguments.
        syscall5,
        a,
        b,
        c,
        d,
        e
    );

    /// Makes the system call `nr` with six arguments, the most a system call
    /// takes.
    ///
    /// Returns what the kernel returned: see [`check`]. A number the kernel
    /// does not know returns `-ENOSYS`; a call that takes fewer arguments
    /// ignores the others.
    ///
    /// # Safety
    ///
    /// A system call can do anything to the process. The caller must uphold:
    ///
    /// - **The contract of that system call**, as the kernel defines it for
    ///   the target architecture: the number of arguments and their
    ///   meaning, pointers valid for the reads and writes the kernel makes
    ///   through them and for as long as it makes them, structures in the
    ///   kernel's own layout.
    /// - **Rust's rules for everything the call affects**: memory the kernel
    ///   writes must be writable and not borrowed elsewhere; memory that is
    ///   unmapped, remapped or made inaccessible must not be in use; a
    ///   descriptor that is closed or replaced must not be owned by
    ///   anything else (an [`OwnedHandle`](crate::OwnedHandle), a `std`
    ///   file).
    /// - **The state of the runtime in the process** (libc, or fullrust's
    ///   `std`), which is not told of the call: the program break, the
    ///   creation of threads and their thread-local storage, what runs in a
    ///   child process before `execve`, signal dispositions and masks. See
    ///   the [module documentation](self#when-a-libc-is-in-the-process).
    #[inline]
    pub unsafe fn syscall6(
        nr: usize,
        a: usize,
        b: usize,
        c: usize,
        d: usize,
        e: usize,
        f: usize,
    ) -> usize {
        // SAFETY: the caller upholds the system call's contract.
        unsafe { sys::arch::syscall6(nr, a, b, c, d, e, f) }
    }
}

/// The implementation of [`raw::linux::syscall!`](crate::raw::linux::syscall).
#[cfg(any(target_os = "linux", target_os = "fullrust"))]
#[doc(hidden)]
#[macro_export]
macro_rules! __raw_linux_syscall {
    ($nr:ident $(,)?) => {
        $crate::raw::linux::check($crate::raw::linux::syscall0($crate::raw::linux::nr::$nr))
    };
    ($nr:ident, $a:expr $(,)?) => {
        $crate::raw::linux::check($crate::raw::linux::syscall1(
            $crate::raw::linux::nr::$nr,
            $a as usize,
        ))
    };
    ($nr:ident, $a:expr, $b:expr $(,)?) => {
        $crate::raw::linux::check($crate::raw::linux::syscall2(
            $crate::raw::linux::nr::$nr,
            $a as usize,
            $b as usize,
        ))
    };
    ($nr:ident, $a:expr, $b:expr, $c:expr $(,)?) => {
        $crate::raw::linux::check($crate::raw::linux::syscall3(
            $crate::raw::linux::nr::$nr,
            $a as usize,
            $b as usize,
            $c as usize,
        ))
    };
    ($nr:ident, $a:expr, $b:expr, $c:expr, $d:expr $(,)?) => {
        $crate::raw::linux::check($crate::raw::linux::syscall4(
            $crate::raw::linux::nr::$nr,
            $a as usize,
            $b as usize,
            $c as usize,
            $d as usize,
        ))
    };
    ($nr:ident, $a:expr, $b:expr, $c:expr, $d:expr, $e:expr $(,)?) => {
        $crate::raw::linux::check($crate::raw::linux::syscall5(
            $crate::raw::linux::nr::$nr,
            $a as usize,
            $b as usize,
            $c as usize,
            $d as usize,
            $e as usize,
        ))
    };
    ($nr:ident, $a:expr, $b:expr, $c:expr, $d:expr, $e:expr, $f:expr $(,)?) => {
        $crate::raw::linux::check($crate::raw::linux::syscall6(
            $crate::raw::linux::nr::$nr,
            $a as usize,
            $b as usize,
            $c as usize,
            $d as usize,
            $e as usize,
            $f as usize,
        ))
    };
}

#[cfg(target_os = "macos")]
pub mod apple {
    //! macOS: `errno`, for the functions of `libSystem`.
    //!
    //! The kernel's own system call interface is private to Apple and changes
    //! between releases: `libSystem` is the boundary, and every Rust program
    //! links it already. A raw call is therefore a function you declare
    //! yourself, and this module turns its result into a
    //! [`Result`](crate::Result):
    //!
    //! ```
    //! use core::ffi::c_int;
    //! use oscall::raw::apple::{cvt, errno};
    //!
    //! unsafe extern "C" {
    //!     fn close(fd: c_int) -> c_int;
    //! }
    //!
    //! // 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);
    //! ```
    //!
    //! # Declaring functions
    //!
    //! - **Declare variadic functions as variadic** (`fn open(path: *const
    //!   c_char, flags: c_int, ...) -> c_int;`, and likewise `openat`, `fcntl`,
    //!   `ioctl`): aarch64 passes variadic arguments on the stack, and a
    //!   declaration with fixed arguments silently passes garbage.
    //! - **On x86_64, some functions have several versions** under one name and
    //!   the plain symbol is the oldest: what takes or returns a `struct stat`,
    //!   `dirent` or `statfs` must be linked as `name$INODE64`
    //!   (`#[cfg_attr(target_arch = "x86_64", link_name = "fstat$INODE64")]`).
    //!   aarch64 has only the current ones.
    //! - Take structure layouts and constants from Apple's headers.
    //! - A function newer than the oldest macOS the program runs on must be
    //!   looked up with `dlsym`, not declared.

    use core::ffi::c_int;

    use crate::sys;

    /// The error numbers of macOS (`<sys/errno.h>`). They are the values
    /// [`Error::raw_os_error`](crate::Error::raw_os_error) returns.
    pub mod errno {
        pub use crate::sys::errno::*;
    }

    /// The calling thread's `errno`, as an [`Error`](crate::Error).
    ///
    /// Only meaningful right after a function failed, and only for the
    /// functions that report through `errno` (the `pthread_*` and `posix_*`
    /// families return the error number instead: pass it to
    /// [`Error::from_raw_os_error`](crate::Error::from_raw_os_error)).
    #[inline]
    pub fn last_error() -> crate::Error {
        sys::last_error()
    }

    /// Sets the calling thread's `errno`.
    ///
    /// For the few functions whose failure value is also a valid result
    /// (`getpriority`, `sysconf`, `readdir`): set `errno` to zero before the
    /// call, and read it with [`last_error`] after.
    #[inline]
    pub fn set_errno(value: i32) {
        sys::set_errno(value);
    }

    /// Converts the result of a function that returns `-1` and sets `errno`
    /// on failure: `-1` becomes [`last_error`], anything else is the result.
    #[inline]
    pub fn cvt(ret: c_int) -> crate::Result<c_int> {
        sys::cvt(ret)
    }

    /// As [`cvt`], for the functions that return a `ssize_t` or an `off_t`.
    #[inline]
    pub fn cvt_long(ret: i64) -> crate::Result<i64> {
        sys::cvt_long(ret)
    }
}

#[cfg(windows)]
pub mod windows {
    //! Windows: error codes, UTF-16 strings and imports.
    //!
    //! A raw call is a function of a system DLL that you declare yourself, with
    //! [`dll!`] or with an `extern "system"` block of your own:
    //!
    //! ```
    //! use oscall::raw::windows::{dll, last_error};
    //!
    //! dll!(unsafe "kernel32.dll" {
    //!     fn GetCurrentProcessId() -> u32;
    //!     fn GetFileType(handle: *mut core::ffi::c_void) -> u32;
    //! });
    //!
    //! // SAFETY: takes nothing and cannot fail.
    //! assert_eq!(unsafe { GetCurrentProcessId() }, std::process::id());
    //! // SAFETY: an invalid handle only makes the call fail.
    //! assert_eq!(unsafe { GetFileType(usize::MAX as _) }, 0);
    //! assert_eq!(last_error().raw_os_error(), 6); // ERROR_INVALID_HANDLE
    //! ```
    //!
    //! # Conventions
    //!
    //! - `HANDLE` is `*mut c_void` ([`RawHandle`](crate::RawHandle)), `BOOL` is
    //!   `i32`, `DWORD` is `u32`, `NTSTATUS` is `i32`; a `SOCKET` is a `usize`.
    //! - Use the wide (`W`) functions: strings are NUL-terminated UTF-16, which
    //!   [`with_wide`] makes from a path and [`wide_to_wtf8`] converts back.
    //! - Functions that return a `BOOL` report through `GetLastError`
    //!   ([`cvt`], [`last_error`]); the `Nt*` functions of `ntdll` return an
    //!   `NTSTATUS` ([`nt_error`]); Winsock reports through `WSAGetLastError`,
    //!   whose codes [`Error::from_raw_os_error`](crate::Error::from_raw_os_error)
    //!   takes as they are, and needs `WSAStartup` once per process.
    //! - Mind the structure layouts on 32-bit targets.
    //! - A handle oscall opened is synchronous. One it did not open may be open
    //!   for overlapped operation, and then `ReadFile`, `WriteFile`,
    //!   `DeviceIoControl` and the `Nt` calls that start an operation return
    //!   while it is pending and the system writes the buffers later: do not let
    //!   them go out of scope before the operation completed.
    //!
    //! # Declaring imports without `dll!`
    //!
    //! A plain declaration works wherever the toolchain has an import library
    //! for the DLL (the Windows SDK or MinGW's, for the usual system DLLs):
    //!
    //! ```
    //! #[link(name = "kernel32")]
    //! unsafe extern "system" {
    //!     fn GetTickCount64() -> u64;
    //! }
    //! # let _ = unsafe { GetTickCount64() };
    //! ```
    //!
    //! `#[link(name = "kernel32.dll", kind = "raw-dylib", modifiers =
    //! "+verbatim")]` needs no import library at all; on 32-bit x86 add
    //! `import_name_type = "undecorated"`, since the system DLLs export
    //! `stdcall` functions under their plain names. That is all [`dll!`] does.

    use crate::sys;

    /// Declares functions imported from a DLL, with no import library:
    ///
    /// ```
    /// use core::ffi::c_void;
    ///
    /// oscall::raw::windows::dll!(unsafe "kernel32.dll" {
    ///     /// Attributes and visibility are kept.
    ///     pub(crate) fn GetStdHandle(which: u32) -> *mut c_void;
    ///     fn SetLastError(code: u32);
    /// });
    ///
    /// // SAFETY: both only read or write the thread's own state.
    /// unsafe {
    ///     SetLastError(0);
    ///     let _ = GetStdHandle(-11i32 as u32);
    /// }
    /// ```
    ///
    /// The functions are declared in an `unsafe extern "system"` block
    /// (`stdcall` on 32-bit x86, the C convention elsewhere), linked as
    /// `raw-dylib`: the import is generated by the compiler from the DLL's
    /// name, written in full, and from the function's name, so it works the
    /// same with the MSVC and the GNU toolchains and for DLLs that have no
    /// import library. Every function declared is `unsafe` to call.
    ///
    /// # Safety
    ///
    /// The `unsafe` keyword in the invocation is the one of the `unsafe
    /// extern` block it stands for: the declarations are not checked against
    /// anything, and you assert that the DLL exports each function with
    /// exactly that signature. A wrong one is undefined behaviour when the
    /// function is called. On 32-bit x86 the size of the arguments is also
    /// part of the convention: a function declared with the wrong arguments
    /// corrupts the stack even if it ignores them.
    #[doc(inline)]
    pub use crate::__raw_windows_dll as dll;

    /// The calling thread's last error code (`GetLastError`), as an
    /// [`Error`](crate::Error).
    ///
    /// Only meaningful right after a function failed, before anything else
    /// is called.
    #[inline]
    pub fn last_error() -> crate::Error {
        sys::last_error()
    }

    /// Converts a `BOOL` result: zero becomes [`last_error`].
    #[inline]
    pub fn cvt(ret: i32) -> crate::Result<()> {
        sys::cvt(ret)
    }

    /// The error for an `NTSTATUS`: the code Win32 reports for it
    /// (`RtlNtStatusToDosError`), so that errors of `Nt*` functions compare
    /// and classify like every other.
    ///
    /// Call it for a failure only (a negative status): success and
    /// informational statuses are not errors, and several of them have no
    /// Win32 code.
    #[inline]
    pub fn nt_error(status: i32) -> crate::Error {
        sys::nt_error(status)
    }

    /// Calls `f` with `path` converted to NUL-terminated UTF-16; the slice
    /// includes the NUL, so `wide.as_ptr()` is what a `W` function takes.
    ///
    /// The path is UTF-8, or WTF-8 for names that are not valid Unicode (see
    /// [`AsPath`](crate::AsPath)). It is converted on the stack when shorter
    /// than 512 bytes, and on the heap otherwise, which needs the `alloc`
    /// feature: without it a longer path fails with
    /// [`ErrorKind::InvalidFilename`](crate::ErrorKind::InvalidFilename). A
    /// path that contains a NUL or is not WTF-8 fails with
    /// [`ErrorKind::InvalidInput`](crate::ErrorKind::InvalidInput).
    ///
    /// The path is not otherwise changed: no `\\?\` prefix is added, and
    /// the usual `MAX_PATH` limit of the function called applies.
    pub fn with_wide<P: crate::AsPath + ?Sized, R>(
        path: &P,
        f: impl FnOnce(&[u16]) -> crate::Result<R>,
    ) -> crate::Result<R> {
        crate::path::with_wide(path.as_path_bytes(), f)
    }

    /// Converts UTF-16 (without its terminating NUL) to UTF-8 and returns
    /// the number of bytes written, or `None` if `out` is too small. Three
    /// bytes per unit always suffice.
    ///
    /// A lone surrogate, which Windows allows in names, is encoded like any
    /// other code point (WTF-8): the result is valid UTF-8 exactly when the
    /// input is valid UTF-16, and converts back with [`with_wide`] in every
    /// case.
    pub fn wide_to_wtf8(src: &[u16], out: &mut [u8]) -> Option<usize> {
        crate::path::wide_to_wtf8(src, out)
    }
}

/// The implementation of [`raw::windows::dll!`](crate::raw::windows::dll).
#[cfg(windows)]
#[doc(hidden)]
#[macro_export]
macro_rules! __raw_windows_dll {
    (unsafe $dll:literal {
        $(
            $(#[$attr:meta])*
            $vis:vis fn $name:ident($($arg:ident: $ty:ty),* $(,)?) $(-> $ret:ty)?;
        )*
    }) => {
        #[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" {
            $(
                $(#[$attr])*
                $vis fn $name($($arg: $ty),*) $(-> $ret)?;
            )*
        }
    };
}

#[cfg(target_os = "wasi")]
pub mod wasi {
    //! WASI preview 1: error numbers.
    //!
    //! A raw call is an import of the `wasi_snapshot_preview1` module that you
    //! declare yourself. Every one returns an `errno`, zero for success, and
    //! writes its results through pointer arguments; 64-bit arguments are plain
    //! `i64`, and strings are passed as a pointer and a length:
    //!
    //! ```
    //! use oscall::raw::wasi::{cvt, errno};
    //!
    //! #[link(wasm_import_module = "wasi_snapshot_preview1")]
    //! unsafe extern "C" {
    //!     fn fd_sync(fd: i32) -> i32;
    //! }
    //!
    //! // SAFETY: a descriptor that is not open only makes the call fail.
    //! let err = cvt(unsafe { fd_sync(12345) }).unwrap_err();
    //! assert_eq!(err.raw_os_error(), errno::EBADF);
    //! ```

    use crate::sys;

    /// The error numbers of WASI preview 1 (`errno` in its witx definition).
    /// They are the values
    /// [`Error::raw_os_error`](crate::Error::raw_os_error) returns, and are
    /// not those of any Unix.
    pub mod errno {
        pub use crate::sys::errno::*;
    }

    /// Converts the `errno` an import returned: zero is success.
    #[inline]
    pub fn cvt(errno: i32) -> crate::Result<()> {
        sys::cvt(errno)
    }
}