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
//! The calling thread: its identity, its name, yielding the processor, and
//! how many processors there are to share.
//!
//! oscall does not create threads: a thread made behind the back of the
//! runtime has no thread-local storage that runtime knows of.
//! `std::thread` owns that, and everything here acts on the thread that
//! calls it.
//!
//! Processor affinity exists on Linux and Windows in different shapes, and
//! not on macOS: it lives in the extension modules `linux` and `windows` of
//! this module, each present on its own system only.

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

/// The identifier the system gives the calling thread.
///
/// It is unique among the threads that exist at the same time, in the whole
/// system on Linux, macOS and Windows; the system may give it to a new
/// thread once this one has exited. It is the number the system's own tools
/// show (`ps -L`, `/proc/<pid>/task/<tid>`, debuggers, Process Explorer).
///
/// Linux: `gettid`, which is the process id in the first thread of a
/// process. macOS: `pthread_threadid_np`. Windows: `GetCurrentThreadId`.
/// WebAssembly has one thread, and the identifier is always 1.
///
/// This is a system call on Linux: keep the result rather than asking in a
/// loop.
#[must_use]
pub fn id() -> u64 {
    sys::thread::id()
}

/// Offers the processor to another thread that is ready to run. Returns at
/// once if there is none.
///
/// This is a hint to the scheduler, and useful only for spinning a few
/// times before blocking: to wait for something, block on it
/// ([`sync::wait`](crate::sync::wait)).
///
/// Linux, macOS and WASI: `sched_yield`. Windows: `SwitchToThread`. Does
/// nothing on WebAssembly without WASI.
pub fn yield_now() {
    sys::thread::yield_now();
}

/// The number of threads that can run at the same time: the count of
/// logical processors available.
///
/// Linux: the processors the calling thread is allowed to run on
/// (`sched_getaffinity`), which accounts for `taskset` and for the CPU sets
/// of containers, but not for CPU-time quotas (cgroup `cpu.max`), which
/// `std::thread::available_parallelism` also reads. macOS: the processors
/// currently active (`sysctl hw.activecpu`). Windows: the active processors
/// of all processor groups (`GetActiveProcessorCount`), whatever the
/// affinity of the process. WebAssembly: 1.
///
/// The result is at least 1.
pub fn available_parallelism() -> Result<usize> {
    match sys::thread::available_parallelism()? {
        0 => Err(ErrorKind::Other.into()),
        count => Ok(count),
    }
}

/// Names the calling thread, for debuggers, profilers and the system's
/// process listings.
///
/// The systems keep names of different lengths: 15 bytes on Linux, 63 on
/// macOS, and oscall passes at most 255 on Windows. A longer name is cut to
/// the limit, at a character boundary. A name with a NUL character in it
/// fails with [`InvalidInput`](ErrorKind::InvalidInput).
///
/// Linux: `prctl(PR_SET_NAME)`; in the first thread of a process this also
/// changes the name of the process that `ps` and `top` show (`comm`).
/// macOS: `pthread_setname_np`. Windows: `SetThreadDescription`, which
/// Windows 10 has since version 1607; before that the call fails with
/// [`Unsupported`](ErrorKind::Unsupported).
///
/// Fails with [`Unsupported`](ErrorKind::Unsupported) on WebAssembly.
pub fn set_name(name: &str) -> Result<()> {
    if name.as_bytes().contains(&0) {
        return Err(ErrorKind::InvalidInput.into());
    }
    let end = name.floor_char_boundary(sys::thread::NAME_MAX);
    sys::thread::set_name(&name[..end])
}

/// Reads the name of the calling thread into `buf`, and returns it.
///
/// A thread that was never named has the name the system gave it: that of
/// the program on Linux, none (an empty string) on macOS and Windows.
///
/// If `buf` is too small for the name the call fails with
/// [`BufferTooSmall`](ErrorKind::BufferTooSmall); 64 bytes are enough on Linux
/// and macOS, and 256 for any name set through [`set_name`]. A name that
/// is not valid UTF-8, which only another library can have set, is returned
/// up to its first invalid byte.
///
/// Linux: `prctl(PR_GET_NAME)`. macOS: `pthread_getname_np`. Windows:
/// `GetThreadDescription`, with the same condition as [`set_name`].
///
/// Fails with [`Unsupported`](ErrorKind::Unsupported) on WebAssembly.
pub fn name(buf: &mut [u8]) -> Result<&str> {
    let len = sys::thread::name(buf)?;
    let bytes = buf.get(..len).ok_or(ErrorKind::Other)?;
    Ok(match core::str::from_utf8(bytes) {
        Ok(name) => name,
        Err(error) => {
            let valid = &bytes[..error.valid_up_to()];
            // SAFETY: `valid_up_to` bytes were just checked to be UTF-8.
            unsafe { core::str::from_utf8_unchecked(valid) }
        }
    })
}

/// What Linux alone offers for threads.
#[cfg(any(target_os = "linux", target_os = "fullrust"))]
pub mod linux {
    use crate::Result;
    use crate::sys;

    /// Reads the set of processors the calling thread may run on
    /// (`sched_getaffinity`).
    ///
    /// The set is a bit mask: processor `n` is bit `n % usize::BITS` of
    /// `mask[n / usize::BITS]`. The whole of `mask` is written, with zeros
    /// beyond the processors the system has.
    ///
    /// Fails with [`InvalidInput`](crate::ErrorKind::InvalidInput) if `mask`
    /// has fewer bits than the system has possible processors: 1024 bits
    /// (`[usize; 1024 / usize::BITS as usize]`) suit all but the largest
    /// machines, and 8192 any kernel.
    pub fn affinity(mask: &mut [usize]) -> Result<()> {
        sys::thread::affinity(mask)
    }

    /// Restricts the calling thread to the processors of `mask`
    /// (`sched_setaffinity`), in the layout [`affinity`] describes. The
    /// thread moves to one of them if it is running on another.
    ///
    /// Bits for processors the system does not have are ignored. Fails with
    /// [`InvalidInput`](crate::ErrorKind::InvalidInput) if the mask has none
    /// of the processors the thread is permitted (by its cgroup's CPU set,
    /// among others).
    ///
    /// Threads created afterwards by this one inherit the mask.
    pub fn set_affinity(mask: &[usize]) -> Result<()> {
        sys::thread::set_affinity(mask)
    }
}

/// What Windows alone offers for threads.
#[cfg(windows)]
pub mod windows {
    use crate::Result;
    use crate::sys;

    /// Reads the set of processors the calling thread may run on, within
    /// its processor group (`GetThreadGroupAffinity`): processor `n` of the
    /// group is bit `n`.
    ///
    /// A group has at most 64 processors (32 on 32-bit Windows); systems
    /// with more have several groups, and a thread runs in one.
    pub fn affinity() -> Result<usize> {
        sys::thread::affinity()
    }

    /// Restricts the calling thread to the processors of `mask`, within its
    /// processor group (`SetThreadAffinityMask`), in the layout
    /// [`affinity`] describes.
    ///
    /// Fails with [`InvalidInput`](crate::ErrorKind::InvalidInput) if the
    /// mask is empty or has a processor that the process may not use.
    pub fn set_affinity(mask: usize) -> Result<()> {
        sys::thread::set_affinity(mask)
    }
}