|
| 1 | +//! wasm32-wasip1 has pthreads support. |
| 2 | +
|
| 3 | +use crate::cell::Cell; |
| 4 | +use crate::sync::atomic::{AtomicBool, Ordering}; |
| 5 | +use crate::sys::thread_local::destructors; |
| 6 | +use crate::{ffi, ptr}; |
| 7 | + |
| 8 | +// Add a few symbols not in upstream `libc` just yet. |
| 9 | +mod libc { |
| 10 | + pub use libc::*; |
| 11 | + |
| 12 | + use crate::ffi; |
| 13 | + |
| 14 | + #[allow(non_camel_case_types)] |
| 15 | + pub type pthread_key_t = ffi::c_uint; |
| 16 | + |
| 17 | + extern "C" { |
| 18 | + pub fn pthread_key_create( |
| 19 | + key: *mut pthread_key_t, |
| 20 | + destructor: unsafe extern "C" fn(*mut ffi::c_void), |
| 21 | + ) -> ffi::c_int; |
| 22 | + |
| 23 | + pub fn pthread_setspecific(key: pthread_key_t, value: *const ffi::c_void) -> ffi::c_int; |
| 24 | + } |
| 25 | +} |
| 26 | + |
| 27 | +pub fn enable() { |
| 28 | + enable_main(); |
| 29 | + enable_thread(); |
| 30 | +} |
| 31 | + |
| 32 | +fn enable_main() { |
| 33 | + static REGISTERED: AtomicBool = AtomicBool::new(false); |
| 34 | + |
| 35 | + if !REGISTERED.swap(true, Ordering::AcqRel) { |
| 36 | + unsafe { |
| 37 | + assert_eq!(libc::atexit(run_main_dtors), 0); |
| 38 | + } |
| 39 | + } |
| 40 | + |
| 41 | + extern "C" fn run_main_dtors() { |
| 42 | + unsafe { |
| 43 | + destructors::run(); |
| 44 | + crate::rt::thread_cleanup(); |
| 45 | + } |
| 46 | + } |
| 47 | +} |
| 48 | + |
| 49 | +fn enable_thread() { |
| 50 | + #[thread_local] |
| 51 | + static REGISTERED: Cell<bool> = Cell::new(false); |
| 52 | + |
| 53 | + if !REGISTERED.replace(true) { |
| 54 | + unsafe { |
| 55 | + let mut key: libc::pthread_key_t = 0; |
| 56 | + assert_eq!(libc::pthread_key_create(&mut key, run_thread_dtors), 0); |
| 57 | + |
| 58 | + // We must set the value to a non-NULL pointer value so that |
| 59 | + // the destructor is run on thread exit. The pointer is only |
| 60 | + // passed to run_dtors and never dereferenced. |
| 61 | + assert_eq!(libc::pthread_setspecific(key, ptr::without_provenance(1)), 0); |
| 62 | + } |
| 63 | + } |
| 64 | + |
| 65 | + extern "C" fn run_thread_dtors(_: *mut ffi::c_void) { |
| 66 | + unsafe { |
| 67 | + destructors::run(); |
| 68 | + crate::rt::thread_cleanup(); |
| 69 | + } |
| 70 | + } |
| 71 | +} |
0 commit comments