Skip to content

Commit a83b79e

Browse files
committed
Finished documenting all unsafe op inside unsafe fn
1 parent 8c9cb06 commit a83b79e

File tree

1 file changed

+17
-5
lines changed

1 file changed

+17
-5
lines changed

library/std/src/thread/local.rs

+17-5
Original file line numberDiff line numberDiff line change
@@ -539,20 +539,28 @@ pub mod os {
539539
}
540540

541541
pub unsafe fn get(&'static self, init: fn() -> T) -> Option<&'static T> {
542-
let ptr = self.os.get() as *mut Value<T>;
542+
// SAFETY: No mutable references are ever handed out meaning getting
543+
// the value is ok.
544+
let ptr = unsafe { self.os.get() as *mut Value<T> };
543545
if ptr as usize > 1 {
544-
if let Some(ref value) = (*ptr).inner.get() {
546+
// SAFETY: the check ensured the pointer is safe (its destructor
547+
// is not running) + it is coming from a trusted source (self).
548+
if let Some(ref value) = unsafe { (*ptr).inner.get() } {
545549
return Some(value);
546550
}
547551
}
548-
self.try_initialize(init)
552+
// SAFETY: At this point we are sure we have no value and so
553+
// initializing (or trying to) is safe.
554+
unsafe { self.try_initialize(init) }
549555
}
550556

551557
// `try_initialize` is only called once per os thread local variable,
552558
// except in corner cases where thread_local dtors reference other
553559
// thread_local's, or it is being recursively initialized.
554560
unsafe fn try_initialize(&'static self, init: fn() -> T) -> Option<&'static T> {
555-
let ptr = self.os.get() as *mut Value<T>;
561+
// SAFETY: No mutable references are ever handed out meaning getting
562+
// the value is ok.
563+
let ptr = unsafe { self.os.get() as *mut Value<T> };
556564
if ptr as usize == 1 {
557565
// destructor is running
558566
return None;
@@ -563,7 +571,11 @@ pub mod os {
563571
// local copy, so do that now.
564572
let ptr: Box<Value<T>> = box Value { inner: LazyKeyInner::new(), key: self };
565573
let ptr = Box::into_raw(ptr);
566-
self.os.set(ptr as *mut u8);
574+
// SAFETY: At this point we are sure there is no value inside
575+
// ptr so setting it will not affect anyone else.
576+
unsafe {
577+
self.os.set(ptr as *mut u8);
578+
}
567579
ptr
568580
} else {
569581
// recursive initialization

0 commit comments

Comments
 (0)