Skip to main content

std/sys/thread_local/key/
unix.rs

1use crate::mem;
2
3// For WASI add a few symbols not in upstream `libc` just yet.
4#[cfg(all(target_os = "wasi", target_env = "p1", target_feature = "atomics"))]
5mod libc {
6    use crate::ffi;
7
8    #[allow(non_camel_case_types)]
9    pub type pthread_key_t = ffi::c_uint;
10
11    unsafe extern "C" {
12        pub fn pthread_key_create(
13            key: *mut pthread_key_t,
14            destructor: unsafe extern "C" fn(*mut ffi::c_void),
15        ) -> ffi::c_int;
16        #[allow(dead_code)]
17        pub fn pthread_getspecific(key: pthread_key_t) -> *mut ffi::c_void;
18        pub fn pthread_setspecific(key: pthread_key_t, value: *const ffi::c_void) -> ffi::c_int;
19        pub fn pthread_key_delete(key: pthread_key_t) -> ffi::c_int;
20    }
21}
22
23pub type Key = libc::pthread_key_t;
24
25#[inline]
26pub fn create(dtor: Option<unsafe extern "C" fn(*mut u8)>) -> Key {
27    let mut key = 0;
28    if unsafe { libc::pthread_key_create(&mut key, mem::transmute(dtor)) } != 0 {
29        {
    if let Some(mut out) = crate::sys::stdio::panic_output() {
        let _ =
            crate::io::Write::write_fmt(&mut out,
                format_args!("fatal runtime error: {0}, aborting\n",
                    format_args!("out of TLS keys")));
    };
    crate::process::abort();
};rtabort!("out of TLS keys");
30    }
31    key
32}
33
34#[cold]
35fn fail() -> ! {
36    {
    if let Some(mut out) = crate::sys::stdio::panic_output() {
        let _ =
            crate::io::Write::write_fmt(&mut out,
                format_args!("fatal runtime error: {0}, aborting\n",
                    format_args!("Unexpected TLS failure")));
    };
    crate::process::abort();
}rtabort!("Unexpected TLS failure")
37}
38
39#[inline]
40pub unsafe fn set(key: Key, value: *mut u8) {
41    let r = unsafe { libc::pthread_setspecific(key, value as *mut _) };
42    // May happen on memory exhaustion
43    if r != 0 {
44        fail()
45    }
46}
47
48#[inline]
49#[cfg(any(not(target_thread_local), test))]
50pub unsafe fn get(key: Key) -> *mut u8 {
51    unsafe { libc::pthread_getspecific(key) as *mut u8 }
52}
53
54#[inline]
55pub unsafe fn destroy(key: Key) {
56    let r = unsafe { libc::pthread_key_delete(key) };
57    // only documented error is for invalid keys
58    if r != 0 {
59        fail()
60    }
61}