Skip to content

Commit 4a914fa

Browse files
surbangitbot
authored and
gitbot
committed
Run TLS destructors for wasm32-wasip1-threads
The target has support for pthreads and allows registration of TLS destructors.
1 parent 84d3123 commit 4a914fa

File tree

2 files changed

+74
-0
lines changed

2 files changed

+74
-0
lines changed
+71
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,71 @@
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+
}

std/src/sys/thread_local/mod.rs

+3
Original file line numberDiff line numberDiff line change
@@ -85,6 +85,9 @@ pub(crate) mod guard {
8585
} else if #[cfg(target_os = "windows")] {
8686
mod windows;
8787
pub(crate) use windows::enable;
88+
} else if #[cfg(all(target_os = "wasi"))] {
89+
mod wasi;
90+
pub(crate) use wasi::enable;
8891
} else if #[cfg(any(
8992
target_family = "wasm",
9093
target_os = "uefi",

0 commit comments

Comments
 (0)