Skip to content

Commit 93562dc

Browse files
committed
Use UnsafeCell for fast constant thread locals
1 parent c5b5713 commit 93562dc

File tree

1 file changed

+7
-5
lines changed

1 file changed

+7
-5
lines changed

library/std/src/sys/thread_local/fast_local.rs

+7-5
Original file line numberDiff line numberDiff line change
@@ -22,13 +22,15 @@ pub macro thread_local_inner {
2222
const INIT_EXPR: $t = $init;
2323
// If the platform has support for `#[thread_local]`, use it.
2424
#[thread_local]
25-
static mut VAL: $t = INIT_EXPR;
25+
// We use `UnsafeCell` here instead of `static mut` to ensure any generated TLS shims
26+
// have a nonnull attribute on their return value.
27+
static VAL: $crate::cell::UnsafeCell<$t> = $crate::cell::UnsafeCell::new(INIT_EXPR);
2628

2729
// If a dtor isn't needed we can do something "very raw" and
2830
// just get going.
2931
if !$crate::mem::needs_drop::<$t>() {
3032
unsafe {
31-
return $crate::option::Option::Some(&VAL)
33+
return $crate::option::Option::Some(&*VAL.get())
3234
}
3335
}
3436

@@ -55,15 +57,15 @@ pub macro thread_local_inner {
5557
// so now.
5658
0 => {
5759
$crate::thread::local_impl::Key::<$t>::register_dtor(
58-
$crate::ptr::addr_of_mut!(VAL) as *mut $crate::primitive::u8,
60+
VAL.get() as *mut $crate::primitive::u8,
5961
destroy,
6062
);
6163
STATE.set(1);
62-
$crate::option::Option::Some(&VAL)
64+
$crate::option::Option::Some(&*VAL.get())
6365
}
6466
// 1 == the destructor is registered and the value
6567
// is valid, so return the pointer.
66-
1 => $crate::option::Option::Some(&VAL),
68+
1 => $crate::option::Option::Some(&*VAL.get()),
6769
// otherwise the destructor has already run, so we
6870
// can't give access.
6971
_ => $crate::option::Option::None,

0 commit comments

Comments
 (0)