oscall 0.0.2

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

use oscall::{ErrorKind, thread};

/// Runs `f` on a new thread, so that what it does to its thread (name,
/// affinity) does not leak into the other tests. On WASI, which has no
/// threads, it runs in place.
#[cfg_attr(target_family = "wasm", allow(dead_code))]
fn on_new_thread<T: Send>(f: impl FnOnce() -> T + Send) -> T {
    if cfg!(target_os = "wasi") {
        f()
    } else {
        std::thread::scope(|s| s.spawn(f).join().unwrap())
    }
}

#[test]
fn id() {
    let mine = thread::id();
    assert_ne!(mine, 0);
    assert_eq!(thread::id(), mine);
    if cfg!(target_family = "wasm") {
        assert_eq!(mine, 1);
        return; // no other threads
    }

    // Threads alive at the same time have different ids.
    let barrier = std::sync::Barrier::new(4);
    let mut ids = std::thread::scope(|s| {
        let threads: Vec<_> = (0..4)
            .map(|_| {
                s.spawn(|| {
                    let id = thread::id();
                    barrier.wait();
                    assert_eq!(thread::id(), id);
                    id
                })
            })
            .collect();
        threads
            .into_iter()
            .map(|t| t.join().unwrap())
            .collect::<Vec<_>>()
    });
    ids.push(mine);
    assert!(ids.iter().all(|&id| id != 0));
    ids.sort_unstable();
    ids.dedup();
    assert_eq!(ids.len(), 5);
}

// The system's own view of the thread id: the entries of the task directory
// of the process. Not under an emulator, whose /proc is the host's.
#[cfg(all(target_os = "linux", any(target_arch = "x86_64", target_arch = "x86")))]
#[test]
fn id_is_the_systems() {
    on_new_thread(|| {
        let id = thread::id();
        assert_ne!(id, u64::from(std::process::id()), "not the first thread");
        let task = format!("/proc/self/task/{id}/comm");
        if std::path::Path::new("/proc/self/task").exists() {
            assert!(std::path::Path::new(&task).exists(), "{task}");
        }
    });
}

#[test]
fn yield_now() {
    for _ in 0..1000 {
        thread::yield_now();
    }
}

#[test]
fn available_parallelism() {
    let count = thread::available_parallelism().unwrap();
    assert!(count >= 1);
    if cfg!(target_family = "wasm") {
        assert_eq!(count, 1);
    }
    // std counts the same processors, less what a CPU quota takes away (on
    // Linux), or those of one processor group only (on Windows).
    if let Ok(std_count) = std::thread::available_parallelism() {
        assert!(count >= std_count.get(), "{count} < {std_count}");
        if cfg!(target_os = "macos") {
            assert_eq!(count, std_count.get());
        }
    }
}

#[cfg(not(target_family = "wasm"))]
#[test]
fn name() {
    on_new_thread(|| {
        let mut buf = [0u8; 256];
        thread::set_name("oscall-worker").unwrap();
        assert_eq!(thread::name(&mut buf).unwrap(), "oscall-worker");

        // Renaming, to something shorter, and to nothing.
        thread::set_name("é").unwrap();
        assert_eq!(thread::name(&mut buf).unwrap(), "é");
        thread::set_name("").unwrap();
        assert_eq!(thread::name(&mut buf).unwrap(), "");

        // A buffer of exactly the size, and one byte short.
        thread::set_name("exact").unwrap();
        assert_eq!(thread::name(&mut buf[..5]).unwrap(), "exact");
        assert_eq!(
            thread::name(&mut buf[..4]).unwrap_err(),
            ErrorKind::BufferTooSmall
        );
        assert_eq!(
            thread::name(&mut []).unwrap_err(),
            ErrorKind::BufferTooSmall
        );

        // A NUL is refused, and the name stays.
        assert_eq!(
            thread::set_name("a\0b").unwrap_err(),
            ErrorKind::InvalidInput
        );
        assert_eq!(thread::name(&mut buf).unwrap(), "exact");
    });
}

#[cfg(not(target_family = "wasm"))]
#[test]
fn name_is_cut_at_the_limit() {
    // The limit in bytes, with two-byte characters: the cut falls on a
    // character boundary, one byte below an odd limit.
    let limit = if cfg!(windows) {
        255
    } else if cfg!(target_os = "macos") {
        63
    } else {
        15
    };
    on_new_thread(|| {
        let mut buf = [0u8; 256];
        let long = "é".repeat(200);
        thread::set_name(&long).unwrap();
        let name = thread::name(&mut buf).unwrap();
        assert_eq!(name, "é".repeat(limit / 2));

        // And a name of exactly the limit is kept whole.
        let exact = "x".repeat(limit);
        thread::set_name(&exact).unwrap();
        assert_eq!(thread::name(&mut buf).unwrap(), exact);
        let over = "x".repeat(limit + 1);
        thread::set_name(&over).unwrap();
        assert_eq!(thread::name(&mut buf).unwrap(), exact);
    });
}

// std names the thread with the same system call: each sees the other's.
// (fullrust's std keeps thread names to itself.)
#[cfg(any(target_os = "linux", target_os = "macos", windows))]
#[test]
fn name_matches_std() {
    std::thread::Builder::new()
        .name("oscall-by-std".into())
        .spawn(|| {
            let mut buf = [0u8; 64];
            assert_eq!(thread::name(&mut buf).unwrap(), "oscall-by-std");
        })
        .unwrap()
        .join()
        .unwrap();
}

#[cfg(target_family = "wasm")]
#[test]
fn name_is_unsupported() {
    let mut buf = [0u8; 64];
    assert_eq!(
        thread::set_name("name").unwrap_err(),
        ErrorKind::Unsupported
    );
    assert_eq!(thread::name(&mut buf).unwrap_err(), ErrorKind::Unsupported);
}

#[cfg(any(target_os = "linux", target_os = "fullrust"))]
#[test]
fn linux_affinity() {
    use oscall::thread::linux;

    const WORDS: usize = 8192 / usize::BITS as usize;
    on_new_thread(|| {
        let mut mask = [usize::MAX; WORDS];
        linux::affinity(&mut mask).unwrap();
        let count: usize = mask.iter().map(|w| w.count_ones() as usize).sum();
        assert_eq!(count, thread::available_parallelism().unwrap());

        // An empty set is refused.
        assert_eq!(
            linux::set_affinity(&[0; WORDS]).unwrap_err(),
            ErrorKind::InvalidInput
        );
        assert_eq!(
            linux::set_affinity(&[]).unwrap_err(),
            ErrorKind::InvalidInput
        );

        // Pin the thread to the last processor it is allowed.
        let word = mask.iter().rposition(|&w| w != 0).unwrap();
        let bit = usize::BITS - 1 - mask[word].leading_zeros();
        let mut one = [0usize; WORDS];
        one[word] = 1 << bit;
        // A short mask is enough to set, if it reaches the processor.
        linux::set_affinity(&one[..=word]).unwrap();

        let mut now = [usize::MAX; WORDS];
        linux::affinity(&mut now).unwrap();
        assert_eq!(now, one);
        assert_eq!(thread::available_parallelism().unwrap(), 1);

        // Threads created from here inherit the mask.
        let inherited = std::thread::scope(|s| {
            s.spawn(|| {
                let mut mask = [0usize; WORDS];
                linux::affinity(&mut mask).unwrap();
                mask
            })
            .join()
            .unwrap()
        });
        assert_eq!(inherited, one);

        // And back to the whole set.
        linux::set_affinity(&mask).unwrap();
        linux::affinity(&mut now).unwrap();
        assert_eq!(now, mask);
    });
}

#[cfg(windows)]
#[test]
fn windows_affinity() {
    use oscall::thread::windows;

    on_new_thread(|| {
        let mask = windows::affinity().unwrap();
        assert_ne!(mask, 0);
        assert!(mask.count_ones() as usize <= thread::available_parallelism().unwrap());

        // An empty set is refused.
        assert_eq!(
            windows::set_affinity(0).unwrap_err(),
            ErrorKind::InvalidInput
        );

        // Pin the thread to the last processor it is allowed.
        let one = 1 << (usize::BITS - 1 - mask.leading_zeros());
        windows::set_affinity(one).unwrap();
        assert_eq!(windows::affinity().unwrap(), one);

        // And back to the whole set.
        windows::set_affinity(mask).unwrap();
        assert_eq!(windows::affinity().unwrap(), mask);
    });
}