]> git.lizzy.rs Git - rust.git/blob - library/std/src/thread/local.rs
Auto merge of #104507 - WaffleLapkin:asderefsyou, r=wesleywiser
[rust.git] / library / std / src / thread / local.rs
1 //! Thread local storage
2
3 #![unstable(feature = "thread_local_internals", issue = "none")]
4
5 #[cfg(all(test, not(target_os = "emscripten")))]
6 mod tests;
7
8 #[cfg(test)]
9 mod dynamic_tests;
10
11 use crate::cell::{Cell, RefCell};
12 use crate::error::Error;
13 use crate::fmt;
14
15 /// A thread local storage key which owns its contents.
16 ///
17 /// This key uses the fastest possible implementation available to it for the
18 /// target platform. It is instantiated with the [`thread_local!`] macro and the
19 /// primary method is the [`with`] method.
20 ///
21 /// The [`with`] method yields a reference to the contained value which cannot be
22 /// sent across threads or escape the given closure.
23 ///
24 /// [`thread_local!`]: crate::thread_local
25 ///
26 /// # Initialization and Destruction
27 ///
28 /// Initialization is dynamically performed on the first call to [`with`]
29 /// within a thread, and values that implement [`Drop`] get destructed when a
30 /// thread exits. Some caveats apply, which are explained below.
31 ///
32 /// A `LocalKey`'s initializer cannot recursively depend on itself, and using
33 /// a `LocalKey` in this way will cause the initializer to infinitely recurse
34 /// on the first call to `with`.
35 ///
36 /// # Examples
37 ///
38 /// ```
39 /// use std::cell::RefCell;
40 /// use std::thread;
41 ///
42 /// thread_local!(static FOO: RefCell<u32> = RefCell::new(1));
43 ///
44 /// FOO.with(|f| {
45 ///     assert_eq!(*f.borrow(), 1);
46 ///     *f.borrow_mut() = 2;
47 /// });
48 ///
49 /// // each thread starts out with the initial value of 1
50 /// let t = thread::spawn(move|| {
51 ///     FOO.with(|f| {
52 ///         assert_eq!(*f.borrow(), 1);
53 ///         *f.borrow_mut() = 3;
54 ///     });
55 /// });
56 ///
57 /// // wait for the thread to complete and bail out on panic
58 /// t.join().unwrap();
59 ///
60 /// // we retain our original value of 2 despite the child thread
61 /// FOO.with(|f| {
62 ///     assert_eq!(*f.borrow(), 2);
63 /// });
64 /// ```
65 ///
66 /// # Platform-specific behavior
67 ///
68 /// Note that a "best effort" is made to ensure that destructors for types
69 /// stored in thread local storage are run, but not all platforms can guarantee
70 /// that destructors will be run for all types in thread local storage. For
71 /// example, there are a number of known caveats where destructors are not run:
72 ///
73 /// 1. On Unix systems when pthread-based TLS is being used, destructors will
74 ///    not be run for TLS values on the main thread when it exits. Note that the
75 ///    application will exit immediately after the main thread exits as well.
76 /// 2. On all platforms it's possible for TLS to re-initialize other TLS slots
77 ///    during destruction. Some platforms ensure that this cannot happen
78 ///    infinitely by preventing re-initialization of any slot that has been
79 ///    destroyed, but not all platforms have this guard. Those platforms that do
80 ///    not guard typically have a synthetic limit after which point no more
81 ///    destructors are run.
82 /// 3. When the process exits on Windows systems, TLS destructors may only be
83 ///    run on the thread that causes the process to exit. This is because the
84 ///    other threads may be forcibly terminated.
85 ///
86 /// ## Synchronization in thread-local destructors
87 ///
88 /// On Windows, synchronization operations (such as [`JoinHandle::join`]) in
89 /// thread local destructors are prone to deadlocks and so should be avoided.
90 /// This is because the [loader lock] is held while a destructor is run. The
91 /// lock is acquired whenever a thread starts or exits or when a DLL is loaded
92 /// or unloaded. Therefore these events are blocked for as long as a thread
93 /// local destructor is running.
94 ///
95 /// [loader lock]: https://docs.microsoft.com/en-us/windows/win32/dlls/dynamic-link-library-best-practices
96 /// [`JoinHandle::join`]: crate::thread::JoinHandle::join
97 /// [`with`]: LocalKey::with
98 #[cfg_attr(not(test), rustc_diagnostic_item = "LocalKey")]
99 #[stable(feature = "rust1", since = "1.0.0")]
100 pub struct LocalKey<T: 'static> {
101     // This outer `LocalKey<T>` type is what's going to be stored in statics,
102     // but actual data inside will sometimes be tagged with #[thread_local].
103     // It's not valid for a true static to reference a #[thread_local] static,
104     // so we get around that by exposing an accessor through a layer of function
105     // indirection (this thunk).
106     //
107     // Note that the thunk is itself unsafe because the returned lifetime of the
108     // slot where data lives, `'static`, is not actually valid. The lifetime
109     // here is actually slightly shorter than the currently running thread!
110     //
111     // Although this is an extra layer of indirection, it should in theory be
112     // trivially devirtualizable by LLVM because the value of `inner` never
113     // changes and the constant should be readonly within a crate. This mainly
114     // only runs into problems when TLS statics are exported across crates.
115     inner: unsafe fn(Option<&mut Option<T>>) -> Option<&'static T>,
116 }
117
118 #[stable(feature = "std_debug", since = "1.16.0")]
119 impl<T: 'static> fmt::Debug for LocalKey<T> {
120     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
121         f.debug_struct("LocalKey").finish_non_exhaustive()
122     }
123 }
124
125 /// Declare a new thread local storage key of type [`std::thread::LocalKey`].
126 ///
127 /// # Syntax
128 ///
129 /// The macro wraps any number of static declarations and makes them thread local.
130 /// Publicity and attributes for each static are allowed. Example:
131 ///
132 /// ```
133 /// use std::cell::RefCell;
134 /// thread_local! {
135 ///     pub static FOO: RefCell<u32> = RefCell::new(1);
136 ///
137 ///     #[allow(unused)]
138 ///     static BAR: RefCell<f32> = RefCell::new(1.0);
139 /// }
140 /// # fn main() {}
141 /// ```
142 ///
143 /// See [`LocalKey` documentation][`std::thread::LocalKey`] for more
144 /// information.
145 ///
146 /// [`std::thread::LocalKey`]: crate::thread::LocalKey
147 #[macro_export]
148 #[stable(feature = "rust1", since = "1.0.0")]
149 #[cfg_attr(not(test), rustc_diagnostic_item = "thread_local_macro")]
150 #[allow_internal_unstable(thread_local_internals)]
151 macro_rules! thread_local {
152     // empty (base case for the recursion)
153     () => {};
154
155     ($(#[$attr:meta])* $vis:vis static $name:ident: $t:ty = const { $init:expr }; $($rest:tt)*) => (
156         $crate::__thread_local_inner!($(#[$attr])* $vis $name, $t, const $init);
157         $crate::thread_local!($($rest)*);
158     );
159
160     ($(#[$attr:meta])* $vis:vis static $name:ident: $t:ty = const { $init:expr }) => (
161         $crate::__thread_local_inner!($(#[$attr])* $vis $name, $t, const $init);
162     );
163
164     // process multiple declarations
165     ($(#[$attr:meta])* $vis:vis static $name:ident: $t:ty = $init:expr; $($rest:tt)*) => (
166         $crate::__thread_local_inner!($(#[$attr])* $vis $name, $t, $init);
167         $crate::thread_local!($($rest)*);
168     );
169
170     // handle a single declaration
171     ($(#[$attr:meta])* $vis:vis static $name:ident: $t:ty = $init:expr) => (
172         $crate::__thread_local_inner!($(#[$attr])* $vis $name, $t, $init);
173     );
174 }
175
176 #[doc(hidden)]
177 #[unstable(feature = "thread_local_internals", reason = "should not be necessary", issue = "none")]
178 #[macro_export]
179 #[allow_internal_unstable(thread_local_internals, cfg_target_thread_local, thread_local)]
180 #[allow_internal_unsafe]
181 macro_rules! __thread_local_inner {
182     // used to generate the `LocalKey` value for const-initialized thread locals
183     (@key $t:ty, const $init:expr) => {{
184         #[cfg_attr(not(all(windows, target_thread_local)), inline)] // see comments below
185         #[cfg_attr(all(windows, target_thread_local), inline(never))]
186         #[deny(unsafe_op_in_unsafe_fn)]
187         unsafe fn __getit(
188             _init: $crate::option::Option<&mut $crate::option::Option<$t>>,
189         ) -> $crate::option::Option<&'static $t> {
190             const INIT_EXPR: $t = $init;
191
192             // wasm without atomics maps directly to `static mut`, and dtors
193             // aren't implemented because thread dtors aren't really a thing
194             // on wasm right now
195             //
196             // FIXME(#84224) this should come after the `target_thread_local`
197             // block.
198             #[cfg(all(target_family = "wasm", not(target_feature = "atomics")))]
199             {
200                 static mut VAL: $t = INIT_EXPR;
201                 unsafe { $crate::option::Option::Some(&VAL) }
202             }
203
204             // If the platform has support for `#[thread_local]`, use it.
205             #[cfg(all(
206                 target_thread_local,
207                 not(all(target_family = "wasm", not(target_feature = "atomics"))),
208             ))]
209             {
210                 #[thread_local]
211                 static mut VAL: $t = INIT_EXPR;
212
213                 // If a dtor isn't needed we can do something "very raw" and
214                 // just get going.
215                 if !$crate::mem::needs_drop::<$t>() {
216                     unsafe {
217                         return $crate::option::Option::Some(&VAL)
218                     }
219                 }
220
221                 // 0 == dtor not registered
222                 // 1 == dtor registered, dtor not run
223                 // 2 == dtor registered and is running or has run
224                 #[thread_local]
225                 static mut STATE: $crate::primitive::u8 = 0;
226
227                 unsafe extern "C" fn destroy(ptr: *mut $crate::primitive::u8) {
228                     let ptr = ptr as *mut $t;
229
230                     unsafe {
231                         $crate::debug_assert_eq!(STATE, 1);
232                         STATE = 2;
233                         $crate::ptr::drop_in_place(ptr);
234                     }
235                 }
236
237                 unsafe {
238                     match STATE {
239                         // 0 == we haven't registered a destructor, so do
240                         //   so now.
241                         0 => {
242                             $crate::thread::__FastLocalKeyInner::<$t>::register_dtor(
243                                 $crate::ptr::addr_of_mut!(VAL) as *mut $crate::primitive::u8,
244                                 destroy,
245                             );
246                             STATE = 1;
247                             $crate::option::Option::Some(&VAL)
248                         }
249                         // 1 == the destructor is registered and the value
250                         //   is valid, so return the pointer.
251                         1 => $crate::option::Option::Some(&VAL),
252                         // otherwise the destructor has already run, so we
253                         // can't give access.
254                         _ => $crate::option::Option::None,
255                     }
256                 }
257             }
258
259             // On platforms without `#[thread_local]` we fall back to the
260             // same implementation as below for os thread locals.
261             #[cfg(all(
262                 not(target_thread_local),
263                 not(all(target_family = "wasm", not(target_feature = "atomics"))),
264             ))]
265             {
266                 #[inline]
267                 const fn __init() -> $t { INIT_EXPR }
268                 static __KEY: $crate::thread::__OsLocalKeyInner<$t> =
269                     $crate::thread::__OsLocalKeyInner::new();
270                 #[allow(unused_unsafe)]
271                 unsafe {
272                     __KEY.get(move || {
273                         if let $crate::option::Option::Some(init) = _init {
274                             if let $crate::option::Option::Some(value) = init.take() {
275                                 return value;
276                             } else if $crate::cfg!(debug_assertions) {
277                                 $crate::unreachable!("missing initial value");
278                             }
279                         }
280                         __init()
281                     })
282                 }
283             }
284         }
285
286         unsafe {
287             $crate::thread::LocalKey::new(__getit)
288         }
289     }};
290
291     // used to generate the `LocalKey` value for `thread_local!`
292     (@key $t:ty, $init:expr) => {
293         {
294             #[inline]
295             fn __init() -> $t { $init }
296
297             // When reading this function you might ask "why is this inlined
298             // everywhere other than Windows?", and "why must it not be inlined
299             // on Windows?" and these are very reasonable questions to ask.
300             //
301             // The short story is that Windows doesn't support referencing
302             // `#[thread_local]` across DLL boundaries. The slightly longer
303             // story is that each module (dll or exe) has its own separate set
304             // of static thread locals, so if you try and reference a
305             // `#[thread_local]` that comes from `crate1.dll` from within one of
306             // `crate2.dll`'s functions, then it might give you a completely
307             // different thread local than what you asked for (or it might just
308             // crash).
309             //
310             // Because of this we never inline on Windows, but we do inline on
311             // other platforms (where external references to thread locals
312             // across DLLs are supported). A better fix for this would be to
313             // inline this function on Windows, but only for "statically linked"
314             // components. For example if two separately compiled rlibs end up
315             // getting linked into a DLL then it's fine to inline this function
316             // across that boundary. It's only not fine to inline this function
317             // across a DLL boundary. Unfortunately rustc doesn't currently
318             // have this sort of logic available in an attribute, and it's not
319             // clear that rustc is even equipped to answer this (it's more of a
320             // Cargo question kinda). This means that, unfortunately, Windows
321             // gets the pessimistic path for now where it's never inlined.
322             //
323             // The issue of "should improve things on Windows" is #84933
324             #[cfg_attr(not(all(windows, target_thread_local)), inline)]
325             #[cfg_attr(all(windows, target_thread_local), inline(never))]
326             unsafe fn __getit(
327                 init: $crate::option::Option<&mut $crate::option::Option<$t>>,
328             ) -> $crate::option::Option<&'static $t> {
329                 #[cfg(all(target_family = "wasm", not(target_feature = "atomics")))]
330                 static __KEY: $crate::thread::__StaticLocalKeyInner<$t> =
331                     $crate::thread::__StaticLocalKeyInner::new();
332
333                 #[thread_local]
334                 #[cfg(all(
335                     target_thread_local,
336                     not(all(target_family = "wasm", not(target_feature = "atomics"))),
337                 ))]
338                 static __KEY: $crate::thread::__FastLocalKeyInner<$t> =
339                     $crate::thread::__FastLocalKeyInner::new();
340
341                 #[cfg(all(
342                     not(target_thread_local),
343                     not(all(target_family = "wasm", not(target_feature = "atomics"))),
344                 ))]
345                 static __KEY: $crate::thread::__OsLocalKeyInner<$t> =
346                     $crate::thread::__OsLocalKeyInner::new();
347
348                 // FIXME: remove the #[allow(...)] marker when macros don't
349                 // raise warning for missing/extraneous unsafe blocks anymore.
350                 // See https://github.com/rust-lang/rust/issues/74838.
351                 #[allow(unused_unsafe)]
352                 unsafe {
353                     __KEY.get(move || {
354                         if let $crate::option::Option::Some(init) = init {
355                             if let $crate::option::Option::Some(value) = init.take() {
356                                 return value;
357                             } else if $crate::cfg!(debug_assertions) {
358                                 $crate::unreachable!("missing default value");
359                             }
360                         }
361                         __init()
362                     })
363                 }
364             }
365
366             unsafe {
367                 $crate::thread::LocalKey::new(__getit)
368             }
369         }
370     };
371     ($(#[$attr:meta])* $vis:vis $name:ident, $t:ty, $($init:tt)*) => {
372         $(#[$attr])* $vis const $name: $crate::thread::LocalKey<$t> =
373             $crate::__thread_local_inner!(@key $t, $($init)*);
374     }
375 }
376
377 /// An error returned by [`LocalKey::try_with`](struct.LocalKey.html#method.try_with).
378 #[stable(feature = "thread_local_try_with", since = "1.26.0")]
379 #[non_exhaustive]
380 #[derive(Clone, Copy, Eq, PartialEq)]
381 pub struct AccessError;
382
383 #[stable(feature = "thread_local_try_with", since = "1.26.0")]
384 impl fmt::Debug for AccessError {
385     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
386         f.debug_struct("AccessError").finish()
387     }
388 }
389
390 #[stable(feature = "thread_local_try_with", since = "1.26.0")]
391 impl fmt::Display for AccessError {
392     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
393         fmt::Display::fmt("already destroyed", f)
394     }
395 }
396
397 #[stable(feature = "thread_local_try_with", since = "1.26.0")]
398 impl Error for AccessError {}
399
400 impl<T: 'static> LocalKey<T> {
401     #[doc(hidden)]
402     #[unstable(
403         feature = "thread_local_internals",
404         reason = "recently added to create a key",
405         issue = "none"
406     )]
407     #[rustc_const_unstable(feature = "thread_local_internals", issue = "none")]
408     pub const unsafe fn new(
409         inner: unsafe fn(Option<&mut Option<T>>) -> Option<&'static T>,
410     ) -> LocalKey<T> {
411         LocalKey { inner }
412     }
413
414     /// Acquires a reference to the value in this TLS key.
415     ///
416     /// This will lazily initialize the value if this thread has not referenced
417     /// this key yet.
418     ///
419     /// # Panics
420     ///
421     /// This function will `panic!()` if the key currently has its
422     /// destructor running, and it **may** panic if the destructor has
423     /// previously been run for this thread.
424     #[stable(feature = "rust1", since = "1.0.0")]
425     pub fn with<F, R>(&'static self, f: F) -> R
426     where
427         F: FnOnce(&T) -> R,
428     {
429         self.try_with(f).expect(
430             "cannot access a Thread Local Storage value \
431              during or after destruction",
432         )
433     }
434
435     /// Acquires a reference to the value in this TLS key.
436     ///
437     /// This will lazily initialize the value if this thread has not referenced
438     /// this key yet. If the key has been destroyed (which may happen if this is called
439     /// in a destructor), this function will return an [`AccessError`].
440     ///
441     /// # Panics
442     ///
443     /// This function will still `panic!()` if the key is uninitialized and the
444     /// key's initializer panics.
445     #[stable(feature = "thread_local_try_with", since = "1.26.0")]
446     #[inline]
447     pub fn try_with<F, R>(&'static self, f: F) -> Result<R, AccessError>
448     where
449         F: FnOnce(&T) -> R,
450     {
451         unsafe {
452             let thread_local = (self.inner)(None).ok_or(AccessError)?;
453             Ok(f(thread_local))
454         }
455     }
456
457     /// Acquires a reference to the value in this TLS key, initializing it with
458     /// `init` if it wasn't already initialized on this thread.
459     ///
460     /// If `init` was used to initialize the thread local variable, `None` is
461     /// passed as the first argument to `f`. If it was already initialized,
462     /// `Some(init)` is passed to `f`.
463     ///
464     /// # Panics
465     ///
466     /// This function will panic if the key currently has its destructor
467     /// running, and it **may** panic if the destructor has previously been run
468     /// for this thread.
469     fn initialize_with<F, R>(&'static self, init: T, f: F) -> R
470     where
471         F: FnOnce(Option<T>, &T) -> R,
472     {
473         unsafe {
474             let mut init = Some(init);
475             let reference = (self.inner)(Some(&mut init)).expect(
476                 "cannot access a Thread Local Storage value \
477                  during or after destruction",
478             );
479             f(init, reference)
480         }
481     }
482 }
483
484 impl<T: 'static> LocalKey<Cell<T>> {
485     /// Sets or initializes the contained value.
486     ///
487     /// Unlike the other methods, this will *not* run the lazy initializer of
488     /// the thread local. Instead, it will be directly initialized with the
489     /// given value if it wasn't initialized yet.
490     ///
491     /// # Panics
492     ///
493     /// Panics if the key currently has its destructor running,
494     /// and it **may** panic if the destructor has previously been run for this thread.
495     ///
496     /// # Examples
497     ///
498     /// ```
499     /// #![feature(local_key_cell_methods)]
500     /// use std::cell::Cell;
501     ///
502     /// thread_local! {
503     ///     static X: Cell<i32> = panic!("!");
504     /// }
505     ///
506     /// // Calling X.get() here would result in a panic.
507     ///
508     /// X.set(123); // But X.set() is fine, as it skips the initializer above.
509     ///
510     /// assert_eq!(X.get(), 123);
511     /// ```
512     #[unstable(feature = "local_key_cell_methods", issue = "92122")]
513     pub fn set(&'static self, value: T) {
514         self.initialize_with(Cell::new(value), |value, cell| {
515             if let Some(value) = value {
516                 // The cell was already initialized, so `value` wasn't used to
517                 // initialize it. So we overwrite the current value with the
518                 // new one instead.
519                 cell.set(value.into_inner());
520             }
521         });
522     }
523
524     /// Returns a copy of the contained value.
525     ///
526     /// This will lazily initialize the value if this thread has not referenced
527     /// this key yet.
528     ///
529     /// # Panics
530     ///
531     /// Panics if the key currently has its destructor running,
532     /// and it **may** panic if the destructor has previously been run for this thread.
533     ///
534     /// # Examples
535     ///
536     /// ```
537     /// #![feature(local_key_cell_methods)]
538     /// use std::cell::Cell;
539     ///
540     /// thread_local! {
541     ///     static X: Cell<i32> = Cell::new(1);
542     /// }
543     ///
544     /// assert_eq!(X.get(), 1);
545     /// ```
546     #[unstable(feature = "local_key_cell_methods", issue = "92122")]
547     pub fn get(&'static self) -> T
548     where
549         T: Copy,
550     {
551         self.with(|cell| cell.get())
552     }
553
554     /// Takes the contained value, leaving `Default::default()` in its place.
555     ///
556     /// This will lazily initialize the value if this thread has not referenced
557     /// this key yet.
558     ///
559     /// # Panics
560     ///
561     /// Panics if the key currently has its destructor running,
562     /// and it **may** panic if the destructor has previously been run for this thread.
563     ///
564     /// # Examples
565     ///
566     /// ```
567     /// #![feature(local_key_cell_methods)]
568     /// use std::cell::Cell;
569     ///
570     /// thread_local! {
571     ///     static X: Cell<Option<i32>> = Cell::new(Some(1));
572     /// }
573     ///
574     /// assert_eq!(X.take(), Some(1));
575     /// assert_eq!(X.take(), None);
576     /// ```
577     #[unstable(feature = "local_key_cell_methods", issue = "92122")]
578     pub fn take(&'static self) -> T
579     where
580         T: Default,
581     {
582         self.with(|cell| cell.take())
583     }
584
585     /// Replaces the contained value, returning the old value.
586     ///
587     /// This will lazily initialize the value if this thread has not referenced
588     /// this key yet.
589     ///
590     /// # Panics
591     ///
592     /// Panics if the key currently has its destructor running,
593     /// and it **may** panic if the destructor has previously been run for this thread.
594     ///
595     /// # Examples
596     ///
597     /// ```
598     /// #![feature(local_key_cell_methods)]
599     /// use std::cell::Cell;
600     ///
601     /// thread_local! {
602     ///     static X: Cell<i32> = Cell::new(1);
603     /// }
604     ///
605     /// assert_eq!(X.replace(2), 1);
606     /// assert_eq!(X.replace(3), 2);
607     /// ```
608     #[unstable(feature = "local_key_cell_methods", issue = "92122")]
609     pub fn replace(&'static self, value: T) -> T {
610         self.with(|cell| cell.replace(value))
611     }
612 }
613
614 impl<T: 'static> LocalKey<RefCell<T>> {
615     /// Acquires a reference to the contained value.
616     ///
617     /// This will lazily initialize the value if this thread has not referenced
618     /// this key yet.
619     ///
620     /// # Panics
621     ///
622     /// Panics if the value is currently mutably borrowed.
623     ///
624     /// Panics if the key currently has its destructor running,
625     /// and it **may** panic if the destructor has previously been run for this thread.
626     ///
627     /// # Example
628     ///
629     /// ```
630     /// #![feature(local_key_cell_methods)]
631     /// use std::cell::RefCell;
632     ///
633     /// thread_local! {
634     ///     static X: RefCell<Vec<i32>> = RefCell::new(Vec::new());
635     /// }
636     ///
637     /// X.with_borrow(|v| assert!(v.is_empty()));
638     /// ```
639     #[unstable(feature = "local_key_cell_methods", issue = "92122")]
640     pub fn with_borrow<F, R>(&'static self, f: F) -> R
641     where
642         F: FnOnce(&T) -> R,
643     {
644         self.with(|cell| f(&cell.borrow()))
645     }
646
647     /// Acquires a mutable reference to the contained value.
648     ///
649     /// This will lazily initialize the value if this thread has not referenced
650     /// this key yet.
651     ///
652     /// # Panics
653     ///
654     /// Panics if the value is currently borrowed.
655     ///
656     /// Panics if the key currently has its destructor running,
657     /// and it **may** panic if the destructor has previously been run for this thread.
658     ///
659     /// # Example
660     ///
661     /// ```
662     /// #![feature(local_key_cell_methods)]
663     /// use std::cell::RefCell;
664     ///
665     /// thread_local! {
666     ///     static X: RefCell<Vec<i32>> = RefCell::new(Vec::new());
667     /// }
668     ///
669     /// X.with_borrow_mut(|v| v.push(1));
670     ///
671     /// X.with_borrow(|v| assert_eq!(*v, vec![1]));
672     /// ```
673     #[unstable(feature = "local_key_cell_methods", issue = "92122")]
674     pub fn with_borrow_mut<F, R>(&'static self, f: F) -> R
675     where
676         F: FnOnce(&mut T) -> R,
677     {
678         self.with(|cell| f(&mut cell.borrow_mut()))
679     }
680
681     /// Sets or initializes the contained value.
682     ///
683     /// Unlike the other methods, this will *not* run the lazy initializer of
684     /// the thread local. Instead, it will be directly initialized with the
685     /// given value if it wasn't initialized yet.
686     ///
687     /// # Panics
688     ///
689     /// Panics if the value is currently borrowed.
690     ///
691     /// Panics if the key currently has its destructor running,
692     /// and it **may** panic if the destructor has previously been run for this thread.
693     ///
694     /// # Examples
695     ///
696     /// ```
697     /// #![feature(local_key_cell_methods)]
698     /// use std::cell::RefCell;
699     ///
700     /// thread_local! {
701     ///     static X: RefCell<Vec<i32>> = panic!("!");
702     /// }
703     ///
704     /// // Calling X.with() here would result in a panic.
705     ///
706     /// X.set(vec![1, 2, 3]); // But X.set() is fine, as it skips the initializer above.
707     ///
708     /// X.with_borrow(|v| assert_eq!(*v, vec![1, 2, 3]));
709     /// ```
710     #[unstable(feature = "local_key_cell_methods", issue = "92122")]
711     pub fn set(&'static self, value: T) {
712         self.initialize_with(RefCell::new(value), |value, cell| {
713             if let Some(value) = value {
714                 // The cell was already initialized, so `value` wasn't used to
715                 // initialize it. So we overwrite the current value with the
716                 // new one instead.
717                 *cell.borrow_mut() = value.into_inner();
718             }
719         });
720     }
721
722     /// Takes the contained value, leaving `Default::default()` in its place.
723     ///
724     /// This will lazily initialize the value if this thread has not referenced
725     /// this key yet.
726     ///
727     /// # Panics
728     ///
729     /// Panics if the value is currently borrowed.
730     ///
731     /// Panics if the key currently has its destructor running,
732     /// and it **may** panic if the destructor has previously been run for this thread.
733     ///
734     /// # Examples
735     ///
736     /// ```
737     /// #![feature(local_key_cell_methods)]
738     /// use std::cell::RefCell;
739     ///
740     /// thread_local! {
741     ///     static X: RefCell<Vec<i32>> = RefCell::new(Vec::new());
742     /// }
743     ///
744     /// X.with_borrow_mut(|v| v.push(1));
745     ///
746     /// let a = X.take();
747     ///
748     /// assert_eq!(a, vec![1]);
749     ///
750     /// X.with_borrow(|v| assert!(v.is_empty()));
751     /// ```
752     #[unstable(feature = "local_key_cell_methods", issue = "92122")]
753     pub fn take(&'static self) -> T
754     where
755         T: Default,
756     {
757         self.with(|cell| cell.take())
758     }
759
760     /// Replaces the contained value, returning the old value.
761     ///
762     /// # Panics
763     ///
764     /// Panics if the value is currently borrowed.
765     ///
766     /// Panics if the key currently has its destructor running,
767     /// and it **may** panic if the destructor has previously been run for this thread.
768     ///
769     /// # Examples
770     ///
771     /// ```
772     /// #![feature(local_key_cell_methods)]
773     /// use std::cell::RefCell;
774     ///
775     /// thread_local! {
776     ///     static X: RefCell<Vec<i32>> = RefCell::new(Vec::new());
777     /// }
778     ///
779     /// let prev = X.replace(vec![1, 2, 3]);
780     /// assert!(prev.is_empty());
781     ///
782     /// X.with_borrow(|v| assert_eq!(*v, vec![1, 2, 3]));
783     /// ```
784     #[unstable(feature = "local_key_cell_methods", issue = "92122")]
785     pub fn replace(&'static self, value: T) -> T {
786         self.with(|cell| cell.replace(value))
787     }
788 }
789
790 mod lazy {
791     use crate::cell::UnsafeCell;
792     use crate::hint;
793     use crate::mem;
794
795     pub struct LazyKeyInner<T> {
796         inner: UnsafeCell<Option<T>>,
797     }
798
799     impl<T> LazyKeyInner<T> {
800         pub const fn new() -> LazyKeyInner<T> {
801             LazyKeyInner { inner: UnsafeCell::new(None) }
802         }
803
804         pub unsafe fn get(&self) -> Option<&'static T> {
805             // SAFETY: The caller must ensure no reference is ever handed out to
806             // the inner cell nor mutable reference to the Option<T> inside said
807             // cell. This make it safe to hand a reference, though the lifetime
808             // of 'static is itself unsafe, making the get method unsafe.
809             unsafe { (*self.inner.get()).as_ref() }
810         }
811
812         /// The caller must ensure that no reference is active: this method
813         /// needs unique access.
814         pub unsafe fn initialize<F: FnOnce() -> T>(&self, init: F) -> &'static T {
815             // Execute the initialization up front, *then* move it into our slot,
816             // just in case initialization fails.
817             let value = init();
818             let ptr = self.inner.get();
819
820             // SAFETY:
821             //
822             // note that this can in theory just be `*ptr = Some(value)`, but due to
823             // the compiler will currently codegen that pattern with something like:
824             //
825             //      ptr::drop_in_place(ptr)
826             //      ptr::write(ptr, Some(value))
827             //
828             // Due to this pattern it's possible for the destructor of the value in
829             // `ptr` (e.g., if this is being recursively initialized) to re-access
830             // TLS, in which case there will be a `&` and `&mut` pointer to the same
831             // value (an aliasing violation). To avoid setting the "I'm running a
832             // destructor" flag we just use `mem::replace` which should sequence the
833             // operations a little differently and make this safe to call.
834             //
835             // The precondition also ensures that we are the only one accessing
836             // `self` at the moment so replacing is fine.
837             unsafe {
838                 let _ = mem::replace(&mut *ptr, Some(value));
839             }
840
841             // SAFETY: With the call to `mem::replace` it is guaranteed there is
842             // a `Some` behind `ptr`, not a `None` so `unreachable_unchecked`
843             // will never be reached.
844             unsafe {
845                 // After storing `Some` we want to get a reference to the contents of
846                 // what we just stored. While we could use `unwrap` here and it should
847                 // always work it empirically doesn't seem to always get optimized away,
848                 // which means that using something like `try_with` can pull in
849                 // panicking code and cause a large size bloat.
850                 match *ptr {
851                     Some(ref x) => x,
852                     None => hint::unreachable_unchecked(),
853                 }
854             }
855         }
856
857         /// The other methods hand out references while taking &self.
858         /// As such, callers of this method must ensure no `&` and `&mut` are
859         /// available and used at the same time.
860         #[allow(unused)]
861         pub unsafe fn take(&mut self) -> Option<T> {
862             // SAFETY: See doc comment for this method.
863             unsafe { (*self.inner.get()).take() }
864         }
865     }
866 }
867
868 /// On some targets like wasm there's no threads, so no need to generate
869 /// thread locals and we can instead just use plain statics!
870 #[doc(hidden)]
871 #[cfg(all(target_family = "wasm", not(target_feature = "atomics")))]
872 pub mod statik {
873     use super::lazy::LazyKeyInner;
874     use crate::fmt;
875
876     pub struct Key<T> {
877         inner: LazyKeyInner<T>,
878     }
879
880     unsafe impl<T> Sync for Key<T> {}
881
882     impl<T> fmt::Debug for Key<T> {
883         fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
884             f.debug_struct("Key").finish_non_exhaustive()
885         }
886     }
887
888     impl<T> Key<T> {
889         pub const fn new() -> Key<T> {
890             Key { inner: LazyKeyInner::new() }
891         }
892
893         pub unsafe fn get(&self, init: impl FnOnce() -> T) -> Option<&'static T> {
894             // SAFETY: The caller must ensure no reference is ever handed out to
895             // the inner cell nor mutable reference to the Option<T> inside said
896             // cell. This make it safe to hand a reference, though the lifetime
897             // of 'static is itself unsafe, making the get method unsafe.
898             let value = unsafe {
899                 match self.inner.get() {
900                     Some(ref value) => value,
901                     None => self.inner.initialize(init),
902                 }
903             };
904
905             Some(value)
906         }
907     }
908 }
909
910 #[doc(hidden)]
911 #[cfg(all(target_thread_local, not(all(target_family = "wasm", not(target_feature = "atomics"))),))]
912 pub mod fast {
913     use super::lazy::LazyKeyInner;
914     use crate::cell::Cell;
915     use crate::fmt;
916     use crate::mem;
917     use crate::sys::thread_local_dtor::register_dtor;
918
919     #[derive(Copy, Clone)]
920     enum DtorState {
921         Unregistered,
922         Registered,
923         RunningOrHasRun,
924     }
925
926     // This data structure has been carefully constructed so that the fast path
927     // only contains one branch on x86. That optimization is necessary to avoid
928     // duplicated tls lookups on OSX.
929     //
930     // LLVM issue: https://bugs.llvm.org/show_bug.cgi?id=41722
931     pub struct Key<T> {
932         // If `LazyKeyInner::get` returns `None`, that indicates either:
933         //   * The value has never been initialized
934         //   * The value is being recursively initialized
935         //   * The value has already been destroyed or is being destroyed
936         // To determine which kind of `None`, check `dtor_state`.
937         //
938         // This is very optimizer friendly for the fast path - initialized but
939         // not yet dropped.
940         inner: LazyKeyInner<T>,
941
942         // Metadata to keep track of the state of the destructor. Remember that
943         // this variable is thread-local, not global.
944         dtor_state: Cell<DtorState>,
945     }
946
947     impl<T> fmt::Debug for Key<T> {
948         fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
949             f.debug_struct("Key").finish_non_exhaustive()
950         }
951     }
952
953     impl<T> Key<T> {
954         pub const fn new() -> Key<T> {
955             Key { inner: LazyKeyInner::new(), dtor_state: Cell::new(DtorState::Unregistered) }
956         }
957
958         // note that this is just a publicly-callable function only for the
959         // const-initialized form of thread locals, basically a way to call the
960         // free `register_dtor` function defined elsewhere in libstd.
961         pub unsafe fn register_dtor(a: *mut u8, dtor: unsafe extern "C" fn(*mut u8)) {
962             unsafe {
963                 register_dtor(a, dtor);
964             }
965         }
966
967         pub unsafe fn get<F: FnOnce() -> T>(&self, init: F) -> Option<&'static T> {
968             // SAFETY: See the definitions of `LazyKeyInner::get` and
969             // `try_initialize` for more information.
970             //
971             // The caller must ensure no mutable references are ever active to
972             // the inner cell or the inner T when this is called.
973             // The `try_initialize` is dependant on the passed `init` function
974             // for this.
975             unsafe {
976                 match self.inner.get() {
977                     Some(val) => Some(val),
978                     None => self.try_initialize(init),
979                 }
980             }
981         }
982
983         // `try_initialize` is only called once per fast thread local variable,
984         // except in corner cases where thread_local dtors reference other
985         // thread_local's, or it is being recursively initialized.
986         //
987         // Macos: Inlining this function can cause two `tlv_get_addr` calls to
988         // be performed for every call to `Key::get`.
989         // LLVM issue: https://bugs.llvm.org/show_bug.cgi?id=41722
990         #[inline(never)]
991         unsafe fn try_initialize<F: FnOnce() -> T>(&self, init: F) -> Option<&'static T> {
992             // SAFETY: See comment above (this function doc).
993             if !mem::needs_drop::<T>() || unsafe { self.try_register_dtor() } {
994                 // SAFETY: See comment above (this function doc).
995                 Some(unsafe { self.inner.initialize(init) })
996             } else {
997                 None
998             }
999         }
1000
1001         // `try_register_dtor` is only called once per fast thread local
1002         // variable, except in corner cases where thread_local dtors reference
1003         // other thread_local's, or it is being recursively initialized.
1004         unsafe fn try_register_dtor(&self) -> bool {
1005             match self.dtor_state.get() {
1006                 DtorState::Unregistered => {
1007                     // SAFETY: dtor registration happens before initialization.
1008                     // Passing `self` as a pointer while using `destroy_value<T>`
1009                     // is safe because the function will build a pointer to a
1010                     // Key<T>, which is the type of self and so find the correct
1011                     // size.
1012                     unsafe { register_dtor(self as *const _ as *mut u8, destroy_value::<T>) };
1013                     self.dtor_state.set(DtorState::Registered);
1014                     true
1015                 }
1016                 DtorState::Registered => {
1017                     // recursively initialized
1018                     true
1019                 }
1020                 DtorState::RunningOrHasRun => false,
1021             }
1022         }
1023     }
1024
1025     unsafe extern "C" fn destroy_value<T>(ptr: *mut u8) {
1026         let ptr = ptr as *mut Key<T>;
1027
1028         // SAFETY:
1029         //
1030         // The pointer `ptr` has been built just above and comes from
1031         // `try_register_dtor` where it is originally a Key<T> coming from `self`,
1032         // making it non-NUL and of the correct type.
1033         //
1034         // Right before we run the user destructor be sure to set the
1035         // `Option<T>` to `None`, and `dtor_state` to `RunningOrHasRun`. This
1036         // causes future calls to `get` to run `try_initialize_drop` again,
1037         // which will now fail, and return `None`.
1038         unsafe {
1039             let value = (*ptr).inner.take();
1040             (*ptr).dtor_state.set(DtorState::RunningOrHasRun);
1041             drop(value);
1042         }
1043     }
1044 }
1045
1046 #[doc(hidden)]
1047 #[cfg(all(
1048     not(target_thread_local),
1049     not(all(target_family = "wasm", not(target_feature = "atomics"))),
1050 ))]
1051 pub mod os {
1052     use super::lazy::LazyKeyInner;
1053     use crate::cell::Cell;
1054     use crate::fmt;
1055     use crate::marker;
1056     use crate::ptr;
1057     use crate::sys_common::thread_local_key::StaticKey as OsStaticKey;
1058
1059     /// Use a regular global static to store this key; the state provided will then be
1060     /// thread-local.
1061     pub struct Key<T> {
1062         // OS-TLS key that we'll use to key off.
1063         os: OsStaticKey,
1064         marker: marker::PhantomData<Cell<T>>,
1065     }
1066
1067     impl<T> fmt::Debug for Key<T> {
1068         fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1069             f.debug_struct("Key").finish_non_exhaustive()
1070         }
1071     }
1072
1073     unsafe impl<T> Sync for Key<T> {}
1074
1075     struct Value<T: 'static> {
1076         inner: LazyKeyInner<T>,
1077         key: &'static Key<T>,
1078     }
1079
1080     impl<T: 'static> Key<T> {
1081         #[rustc_const_unstable(feature = "thread_local_internals", issue = "none")]
1082         pub const fn new() -> Key<T> {
1083             Key { os: OsStaticKey::new(Some(destroy_value::<T>)), marker: marker::PhantomData }
1084         }
1085
1086         /// It is a requirement for the caller to ensure that no mutable
1087         /// reference is active when this method is called.
1088         pub unsafe fn get(&'static self, init: impl FnOnce() -> T) -> Option<&'static T> {
1089             // SAFETY: See the documentation for this method.
1090             let ptr = unsafe { self.os.get() as *mut Value<T> };
1091             if ptr.addr() > 1 {
1092                 // SAFETY: the check ensured the pointer is safe (its destructor
1093                 // is not running) + it is coming from a trusted source (self).
1094                 if let Some(ref value) = unsafe { (*ptr).inner.get() } {
1095                     return Some(value);
1096                 }
1097             }
1098             // SAFETY: At this point we are sure we have no value and so
1099             // initializing (or trying to) is safe.
1100             unsafe { self.try_initialize(init) }
1101         }
1102
1103         // `try_initialize` is only called once per os thread local variable,
1104         // except in corner cases where thread_local dtors reference other
1105         // thread_local's, or it is being recursively initialized.
1106         unsafe fn try_initialize(&'static self, init: impl FnOnce() -> T) -> Option<&'static T> {
1107             // SAFETY: No mutable references are ever handed out meaning getting
1108             // the value is ok.
1109             let ptr = unsafe { self.os.get() as *mut Value<T> };
1110             if ptr.addr() == 1 {
1111                 // destructor is running
1112                 return None;
1113             }
1114
1115             let ptr = if ptr.is_null() {
1116                 // If the lookup returned null, we haven't initialized our own
1117                 // local copy, so do that now.
1118                 let ptr: Box<Value<T>> = box Value { inner: LazyKeyInner::new(), key: self };
1119                 let ptr = Box::into_raw(ptr);
1120                 // SAFETY: At this point we are sure there is no value inside
1121                 // ptr so setting it will not affect anyone else.
1122                 unsafe {
1123                     self.os.set(ptr as *mut u8);
1124                 }
1125                 ptr
1126             } else {
1127                 // recursive initialization
1128                 ptr
1129             };
1130
1131             // SAFETY: ptr has been ensured as non-NUL just above an so can be
1132             // dereferenced safely.
1133             unsafe { Some((*ptr).inner.initialize(init)) }
1134         }
1135     }
1136
1137     unsafe extern "C" fn destroy_value<T: 'static>(ptr: *mut u8) {
1138         // SAFETY:
1139         //
1140         // The OS TLS ensures that this key contains a null value when this
1141         // destructor starts to run. We set it back to a sentinel value of 1 to
1142         // ensure that any future calls to `get` for this thread will return
1143         // `None`.
1144         //
1145         // Note that to prevent an infinite loop we reset it back to null right
1146         // before we return from the destructor ourselves.
1147         unsafe {
1148             let ptr = Box::from_raw(ptr as *mut Value<T>);
1149             let key = ptr.key;
1150             key.os.set(ptr::invalid_mut(1));
1151             drop(ptr);
1152             key.os.set(ptr::null_mut());
1153         }
1154     }
1155 }