dope_sys/thread/raw.rs
1use std::{mem, num::NonZero, ptr};
2
3use o3::base::marker::ThreadBound;
4
5use crate::{Errno, kernel};
6
7pub(super) fn entropy<S: kernel::raw::Source + ?Sized, const N: usize>(
8 bytes: &mut mem::MaybeUninit<[u8; N]>,
9) -> Result<&mut [u8; N], Errno> {
10 const { assert!(N <= 256) };
11 // SAFETY: bytes provides N writable bytes, within getentropy's 256-byte limit.
12 let result = unsafe { libc::getentropy(bytes.as_mut_ptr().cast(), N) };
13 // SAFETY: getentropy handles interruptions internally and returns zero or -1
14 // with unchanged native errno; success initializes the complete requested extent.
15 unsafe { kernel::raw::Status::new(result).try_zero::<S, Errno>() }?;
16 // SAFETY: success initializes all N bytes, including the empty array.
17 Ok(unsafe { bytes.assume_init_mut() })
18}
19
20/// # Safety
21/// Implementors access only their admitted context and resources, with the promised thread exclusivity.
22pub unsafe trait Task: Sized {
23 /// # Safety
24 /// The context and all resources it uses must retain their admitted access rights through this execution.
25 unsafe fn run(context: ptr::NonNull<Self>);
26}
27
28/// Native thread attributes carrying one validated stack extent.
29pub struct Attrs(libc::pthread_attr_t);
30
31impl Attrs {
32 /// Initializes attributes for a thread with the exact requested stack.
33 pub fn with_stack(stack: NonZero<usize>) -> Result<Self, Errno> {
34 let mut raw = mem::MaybeUninit::uninit();
35 // SAFETY: raw has the native attribute size and is initialized on success.
36 let result = unsafe { libc::pthread_attr_init(raw.as_mut_ptr()) };
37 // SAFETY: pthread_attr_init returns zero or a positive error code directly.
38 unsafe { kernel::raw::Status::new(result).try_pthread() }?;
39 // SAFETY: pthread_attr_init completed, so this value is initialized and
40 // owned here until its Drop destroys it.
41 let mut attr = Self(unsafe { raw.assume_init() });
42 let result = unsafe { libc::pthread_attr_setstacksize(&mut attr.0, stack.get()) };
43 // SAFETY: pthread_attr_setstacksize returns zero or a positive error code.
44 unsafe { kernel::raw::Status::new(result).try_pthread() }?;
45 Ok(attr)
46 }
47
48 /// # Safety
49 /// Retain the initialized context and its borrowed resources at stable addresses through creation
50 /// failure or successful join. Preserve T's exclusive access even if the handle is forgotten.
51 pub unsafe fn spawn<T: Task>(&self, context: ptr::NonNull<T>) -> Result<Handle, Errno> {
52 let mut thread = mem::MaybeUninit::uninit();
53 // SAFETY: attrs and the writable handle outlive this call. The caller retains
54 // T's context and access rights through join. pthread_create returns the exact errno.
55 unsafe {
56 kernel::raw::Status::new(libc::pthread_create(
57 thread.as_mut_ptr(),
58 &self.0,
59 run::<T>,
60 context.as_ptr().cast(),
61 ))
62 .try_pthread()
63 }?;
64 // SAFETY: pthread_create wrote the handle before returning success.
65 Ok(Handle(unsafe { thread.assume_init() }, ThreadBound::NEW))
66 }
67}
68
69/// Destroys the uniquely owned attributes; no caller can invalidate them first.
70impl Drop for Attrs {
71 fn drop(&mut self) {
72 // SAFETY: these initialized attributes are exclusively owned and destroyed
73 // once. Only stack size was changed, so no work-interval port is retained;
74 // destruction returns exactly zero on the admitted native implementations.
75 unsafe { libc::pthread_attr_destroy(&mut self.0) };
76 }
77}
78
79/// One joinable native thread, joined on drop by its creating thread.
80#[repr(transparent)]
81pub struct Handle(libc::pthread_t, ThreadBound);
82
83impl Drop for Handle {
84 fn drop(&mut self) {
85 // SAFETY: successful spawn created this unique joinable handle, retained
86 // by its creating thread. pthread_join returns zero or a positive error
87 // code, which is checked before the owner can reclaim worker storage.
88 if let Err(cause) = unsafe {
89 kernel::raw::Status::new(libc::pthread_join(self.0, ptr::null_mut())).try_pthread()
90 } {
91 kernel::Fatal::Join(cause).terminate()
92 }
93 }
94}
95
96extern "C" fn run<T: Task>(context: *mut std::ffi::c_void) -> *mut std::ffi::c_void {
97 // SAFETY: spawn passes this admitted nonnull T context exactly once.
98 unsafe { T::run(ptr::NonNull::new_unchecked(context.cast())) };
99 ptr::null_mut()
100}