Skip to content

Commit

Permalink
Finished documenting all unsafe op inside unsafe fn
Browse files Browse the repository at this point in the history
  • Loading branch information
poliorcetics committed Aug 10, 2020
1 parent b1375cd commit 3a22b21
Showing 1 changed file with 17 additions and 5 deletions.
22 changes: 17 additions & 5 deletions library/std/src/thread/local.rs
Original file line number Diff line number Diff line change
Expand Up @@ -536,20 +536,28 @@ pub mod os {
}

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

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

0 comments on commit 3a22b21

Please sign in to comment.