Skip to content

Commit 3a22b21

Browse files
committed
Finished documenting all unsafe op inside unsafe fn
1 parent b1375cd commit 3a22b21

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
@@ -536,20 +536,28 @@ pub mod os {
536536
}
537537

538538
pub unsafe fn get(&'static self, init: fn() -> T) -> Option<&'static T> {
539-
let ptr = self.os.get() as *mut Value<T>;
539+
// SAFETY: No mutable references are ever handed out meaning getting
540+
// the value is ok.
541+
let ptr = unsafe { self.os.get() as *mut Value<T> };
540542
if ptr as usize > 1 {
541-
if let Some(ref value) = (*ptr).inner.get() {
543+
// SAFETY: the check ensured the pointer is safe (its destructor
544+
// is not running) + it is coming from a trusted source (self).
545+
if let Some(ref value) = unsafe { (*ptr).inner.get() } {
542546
return Some(value);
543547
}
544548
}
545-
self.try_initialize(init)
549+
// SAFETY: At this point we are sure we have no value and so
550+
// initializing (or trying to) is safe.
551+
unsafe { self.try_initialize(init) }
546552
}
547553

548554
// `try_initialize` is only called once per os thread local variable,
549555
// except in corner cases where thread_local dtors reference other
550556
// thread_local's, or it is being recursively initialized.
551557
unsafe fn try_initialize(&'static self, init: fn() -> T) -> Option<&'static T> {
552-
let ptr = self.os.get() as *mut Value<T>;
558+
// SAFETY: No mutable references are ever handed out meaning getting
559+
// the value is ok.
560+
let ptr = unsafe { self.os.get() as *mut Value<T> };
553561
if ptr as usize == 1 {
554562
// destructor is running
555563
return None;
@@ -560,7 +568,11 @@ pub mod os {
560568
// local copy, so do that now.
561569
let ptr: Box<Value<T>> = box Value { inner: LazyKeyInner::new(), key: self };
562570
let ptr = Box::into_raw(ptr);
563-
self.os.set(ptr as *mut u8);
571+
// SAFETY: At this point we are sure there is no value inside
572+
// ptr so setting it will not affect anyone else.
573+
unsafe {
574+
self.os.set(ptr as *mut u8);
575+
}
564576
ptr
565577
} else {
566578
// recursive initialization

0 commit comments

Comments
 (0)