oscall 0.1.0

Low-level cross-platform interface to operating system services: files, memory mapping, networking and more, with no libc on Linux
Documentation
//! `thread` on Windows.

use core::ffi::{CStr, c_void};

use crate::sys::{OTHER_ERROR, cvt, dll, last_error};
use crate::{Error, ErrorKind, Result};

/// oscall's own limit, in UTF-8 bytes: the system has none.
pub(crate) const NAME_MAX: usize = 255;

const ALL_PROCESSOR_GROUPS: u16 = 0xFFFF;
const FACILITY_WIN32: u32 = 7;

/// `GROUP_AFFINITY`.
#[repr(C)]
#[derive(Default)]
struct GroupAffinity {
    mask: usize,
    group: u16,
    reserved: [u16; 3],
}

dll!("kernel32.dll" {
    fn GetCurrentThreadId() -> u32;
    fn GetCurrentThread() -> *mut c_void;
    fn SwitchToThread() -> i32;
    fn GetActiveProcessorCount(group: u16) -> u32;
    fn GetThreadGroupAffinity(thread: *mut c_void, affinity: *mut GroupAffinity) -> i32;
    fn SetThreadAffinityMask(thread: *mut c_void, mask: usize) -> usize;
    fn GetModuleHandleW(name: *const u16) -> *mut c_void;
    fn GetProcAddress(module: *mut c_void, name: *const u8) -> *mut c_void;
    fn LocalFree(memory: *mut c_void) -> *mut c_void;
});

type SetThreadDescription = unsafe extern "system" fn(thread: *mut c_void, name: *const u16) -> i32;
type GetThreadDescription =
    unsafe extern "system" fn(thread: *mut c_void, name: *mut *mut u16) -> i32;

/// `"kernel32.dll"`, NUL-terminated.
static KERNEL32: [u16; 13] = {
    let ascii = b"kernel32.dll\0";
    let mut wide = [0; 13];
    let mut i = 0;
    while i < wide.len() {
        wide[i] = ascii[i] as u16;
        i += 1;
    }
    wide
};

/// Looks up a function of kernel32 that not every Windows 10 has, so that
/// importing it would keep the program from starting there.
fn optional(name: &CStr) -> Result<*mut c_void> {
    // SAFETY: both names are NUL-terminated; kernel32 is always loaded, and
    // never unloaded.
    let function = unsafe {
        let kernel32 = GetModuleHandleW(KERNEL32.as_ptr());
        if kernel32.is_null() {
            return Err(last_error());
        }
        GetProcAddress(kernel32, name.as_ptr().cast())
    };
    if function.is_null() {
        Err(ErrorKind::Unsupported.into())
    } else {
        Ok(function)
    }
}

/// Converts a failed `HRESULT` to the error code it wraps, if it does.
fn hresult(result: i32) -> Result<()> {
    if result >= 0 {
        return Ok(());
    }
    let result = result as u32;
    Err(Error::from_raw_os_error(
        if (result >> 16) & 0x1FFF == FACILITY_WIN32 {
            (result & 0xFFFF) as i32
        } else {
            OTHER_ERROR
        },
    ))
}

pub(crate) fn id() -> u64 {
    // SAFETY: takes nothing and cannot fail.
    unsafe { GetCurrentThreadId() }.into()
}

pub(crate) fn yield_now() {
    // SAFETY: takes nothing; the result only says whether a switch happened.
    unsafe { SwitchToThread() };
}

pub(crate) fn available_parallelism() -> Result<usize> {
    // SAFETY: takes a group number, or all of them.
    match unsafe { GetActiveProcessorCount(ALL_PROCESSOR_GROUPS) } {
        0 => Err(last_error()),
        count => Ok(count as usize),
    }
}

pub(crate) fn affinity() -> Result<usize> {
    let mut affinity = GroupAffinity::default();
    // SAFETY: the pseudo-handle of the calling thread is always valid, and
    // the function writes one `GROUP_AFFINITY`.
    cvt(unsafe { GetThreadGroupAffinity(GetCurrentThread(), &raw mut affinity) })?;
    Ok(affinity.mask)
}

pub(crate) fn set_affinity(mask: usize) -> Result<()> {
    // SAFETY: the pseudo-handle of the calling thread is always valid.
    // The function returns the previous mask, which is never empty.
    match unsafe { SetThreadAffinityMask(GetCurrentThread(), mask) } {
        0 => Err(last_error()),
        _ => Ok(()),
    }
}

pub(crate) fn set_name(name: &str) -> Result<()> {
    let function = optional(c"SetThreadDescription")?;
    // SAFETY: that is the signature of the function of this name.
    let function = unsafe { core::mem::transmute::<*mut c_void, SetThreadDescription>(function) };
    // The caller cut the name to `NAME_MAX` bytes, which are no more UTF-16
    // units: there is a NUL after them.
    let mut wide = [0u16; NAME_MAX + 1];
    for (unit, slot) in name.encode_utf16().zip(&mut wide[..NAME_MAX]) {
        *slot = unit;
    }
    // SAFETY: the pseudo-handle of the calling thread is always valid, and
    // the name is NUL-terminated.
    hresult(unsafe { function(GetCurrentThread(), wide.as_ptr()) })
}

pub(crate) fn name(buf: &mut [u8]) -> Result<usize> {
    let function = optional(c"GetThreadDescription")?;
    // SAFETY: that is the signature of the function of this name.
    let function = unsafe { core::mem::transmute::<*mut c_void, GetThreadDescription>(function) };
    let mut wide = core::ptr::null_mut::<u16>();
    // SAFETY: the pseudo-handle of the calling thread is always valid, and
    // the function writes one pointer.
    hresult(unsafe { function(GetCurrentThread(), &raw mut wide) })?;
    if wide.is_null() {
        return Ok(0);
    }
    // SAFETY: on success the pointer is to a NUL-terminated string, which
    // is read up to its NUL and no further.
    let units = (0..)
        .map(|i| unsafe { wide.add(i).read() })
        .take_while(|&unit| unit != 0);
    let mut len = 0;
    let mut result = Ok(());
    for c in char::decode_utf16(units) {
        let c = c.unwrap_or(char::REPLACEMENT_CHARACTER);
        match buf.get_mut(len..len + c.len_utf8()) {
            Some(slot) => len += c.encode_utf8(slot).len(),
            None => {
                result = Err(ErrorKind::BufferTooSmall.into());
                break;
            }
        }
    }
    // SAFETY: the string was allocated by the function for the caller to
    // free with LocalFree, and is not used afterwards.
    unsafe { LocalFree(wide.cast()) };
    result.map(|()| len)
}