]> git.lizzy.rs Git - rust.git/blob - src/libstd/sys/windows/thread_local.rs
rollup merge of #20642: michaelwoerister/sane-source-locations-pt1
[rust.git] / src / libstd / sys / windows / thread_local.rs
1 // Copyright 2014 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
4 //
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
10
11 use prelude::v1::*;
12
13 use libc::types::os::arch::extra::{DWORD, LPVOID, BOOL};
14
15 use mem;
16 use ptr;
17 use rt;
18 use sys_common::mutex::{MUTEX_INIT, Mutex};
19
20 pub type Key = DWORD;
21 pub type Dtor = unsafe extern fn(*mut u8);
22
23 // Turns out, like pretty much everything, Windows is pretty close the
24 // functionality that Unix provides, but slightly different! In the case of
25 // TLS, Windows does not provide an API to provide a destructor for a TLS
26 // variable. This ends up being pretty crucial to this implementation, so we
27 // need a way around this.
28 //
29 // The solution here ended up being a little obscure, but fear not, the
30 // internet has informed me [1][2] that this solution is not unique (no way
31 // I could have thought of it as well!). The key idea is to insert some hook
32 // somewhere to run arbitrary code on thread termination. With this in place
33 // we'll be able to run anything we like, including all TLS destructors!
34 //
35 // To accomplish this feat, we perform a number of tasks, all contained
36 // within this module:
37 //
38 // * All TLS destructors are tracked by *us*, not the windows runtime. This
39 //   means that we have a global list of destructors for each TLS key that
40 //   we know about.
41 // * When a TLS key is destroyed, we're sure to remove it from the dtor list
42 //   if it's in there.
43 // * When a thread exits, we run over the entire list and run dtors for all
44 //   non-null keys. This attempts to match Unix semantics in this regard.
45 //
46 // This ends up having the overhead of using a global list, having some
47 // locks here and there, and in general just adding some more code bloat. We
48 // attempt to optimize runtime by forgetting keys that don't have
49 // destructors, but this only gets us so far.
50 //
51 // For more details and nitty-gritty, see the code sections below!
52 //
53 // [1]: http://www.codeproject.com/Articles/8113/Thread-Local-Storage-The-C-Way
54 // [2]: https://github.com/ChromiumWebApps/chromium/blob/master/base
55 //                        /threading/thread_local_storage_win.cc#L42
56
57 // NB these are specifically not types from `std::sync` as they currently rely
58 // on poisoning and this module needs to operate at a lower level than requiring
59 // the thread infrastructure to be in place (useful on the borders of
60 // initialization/destruction).
61 static DTOR_LOCK: Mutex = MUTEX_INIT;
62 static mut DTORS: *mut Vec<(Key, Dtor)> = 0 as *mut _;
63
64 // -------------------------------------------------------------------------
65 // Native bindings
66 //
67 // This section is just raw bindings to the native functions that Windows
68 // provides, There's a few extra calls to deal with destructors.
69
70 #[inline]
71 pub unsafe fn create(dtor: Option<Dtor>) -> Key {
72     const TLS_OUT_OF_INDEXES: DWORD = 0xFFFFFFFF;
73     let key = TlsAlloc();
74     assert!(key != TLS_OUT_OF_INDEXES);
75     match dtor {
76         Some(f) => register_dtor(key, f),
77         None => {}
78     }
79     return key;
80 }
81
82 #[inline]
83 pub unsafe fn set(key: Key, value: *mut u8) {
84     let r = TlsSetValue(key, value as LPVOID);
85     debug_assert!(r != 0);
86 }
87
88 #[inline]
89 pub unsafe fn get(key: Key) -> *mut u8 {
90     TlsGetValue(key) as *mut u8
91 }
92
93 #[inline]
94 pub unsafe fn destroy(key: Key) {
95     if unregister_dtor(key) {
96         // FIXME: Currently if a key has a destructor associated with it we
97         // can't actually ever unregister it. If we were to
98         // unregister it, then any key destruction would have to be
99         // serialized with respect to actually running destructors.
100         //
101         // We want to avoid a race where right before run_dtors runs
102         // some destructors TlsFree is called. Allowing the call to
103         // TlsFree would imply that the caller understands that *all
104         // known threads* are not exiting, which is quite a difficult
105         // thing to know!
106         //
107         // For now we just leak all keys with dtors to "fix" this.
108         // Note that source [2] above shows precedent for this sort
109         // of strategy.
110     } else {
111         let r = TlsFree(key);
112         debug_assert!(r != 0);
113     }
114 }
115
116 extern "system" {
117     fn TlsAlloc() -> DWORD;
118     fn TlsFree(dwTlsIndex: DWORD) -> BOOL;
119     fn TlsGetValue(dwTlsIndex: DWORD) -> LPVOID;
120     fn TlsSetValue(dwTlsIndex: DWORD, lpTlsvalue: LPVOID) -> BOOL;
121 }
122
123 // -------------------------------------------------------------------------
124 // Dtor registration
125 //
126 // These functions are associated with registering and unregistering
127 // destructors. They're pretty simple, they just push onto a vector and scan
128 // a vector currently.
129 //
130 // FIXME: This could probably be at least a little faster with a BTree.
131
132 unsafe fn init_dtors() {
133     if !DTORS.is_null() { return }
134
135     let dtors = box Vec::<(Key, Dtor)>::new();
136     DTORS = mem::transmute(dtors);
137
138     rt::at_exit(move|| {
139         DTOR_LOCK.lock();
140         let dtors = DTORS;
141         DTORS = ptr::null_mut();
142         mem::transmute::<_, Box<Vec<(Key, Dtor)>>>(dtors);
143         assert!(DTORS.is_null()); // can't re-init after destructing
144         DTOR_LOCK.unlock();
145     });
146 }
147
148 unsafe fn register_dtor(key: Key, dtor: Dtor) {
149     DTOR_LOCK.lock();
150     init_dtors();
151     (*DTORS).push((key, dtor));
152     DTOR_LOCK.unlock();
153 }
154
155 unsafe fn unregister_dtor(key: Key) -> bool {
156     DTOR_LOCK.lock();
157     init_dtors();
158     let ret = {
159         let dtors = &mut *DTORS;
160         let before = dtors.len();
161         dtors.retain(|&(k, _)| k != key);
162         dtors.len() != before
163     };
164     DTOR_LOCK.unlock();
165     ret
166 }
167
168 // -------------------------------------------------------------------------
169 // Where the Magic (TM) Happens
170 //
171 // If you're looking at this code, and wondering "what is this doing?",
172 // you're not alone! I'll try to break this down step by step:
173 //
174 // # What's up with CRT$XLB?
175 //
176 // For anything about TLS destructors to work on Windows, we have to be able
177 // to run *something* when a thread exits. To do so, we place a very special
178 // static in a very special location. If this is encoded in just the right
179 // way, the kernel's loader is apparently nice enough to run some function
180 // of ours whenever a thread exits! How nice of the kernel!
181 //
182 // Lots of detailed information can be found in source [1] above, but the
183 // gist of it is that this is leveraging a feature of Microsoft's PE format
184 // (executable format) which is not actually used by any compilers today.
185 // This apparently translates to any callbacks in the ".CRT$XLB" section
186 // being run on certain events.
187 //
188 // So after all that, we use the compiler's #[link_section] feature to place
189 // a callback pointer into the magic section so it ends up being called.
190 //
191 // # What's up with this callback?
192 //
193 // The callback specified receives a number of parameters from... someone!
194 // (the kernel? the runtime? I'm not qute sure!) There are a few events that
195 // this gets invoked for, but we're currently only interested on when a
196 // thread or a process "detaches" (exits). The process part happens for the
197 // last thread and the thread part happens for any normal thread.
198 //
199 // # Ok, what's up with running all these destructors?
200 //
201 // This will likely need to be improved over time, but this function
202 // attempts a "poor man's" destructor callback system. To do this we clone a
203 // local copy of the dtor list to start out with. This is our fudgy attempt
204 // to not hold the lock while destructors run and not worry about the list
205 // changing while we're looking at it.
206 //
207 // Once we've got a list of what to run, we iterate over all keys, check
208 // their values, and then run destructors if the values turn out to be non
209 // null (setting them to null just beforehand). We do this a few times in a
210 // loop to basically match Unix semantics. If we don't reach a fixed point
211 // after a short while then we just inevitably leak something most likely.
212 //
213 // # The article mentions crazy stuff about "/INCLUDE"?
214 //
215 // It sure does! This seems to work for now, so maybe we'll just run into
216 // that if we start linking with msvc?
217
218 #[link_section = ".CRT$XLB"]
219 #[linkage = "external"]
220 #[allow(warnings)]
221 pub static p_thread_callback: unsafe extern "system" fn(LPVOID, DWORD,
222                                                         LPVOID) =
223         on_tls_callback;
224
225 #[allow(warnings)]
226 unsafe extern "system" fn on_tls_callback(h: LPVOID,
227                                           dwReason: DWORD,
228                                           pv: LPVOID) {
229     const DLL_THREAD_DETACH: DWORD = 3;
230     const DLL_PROCESS_DETACH: DWORD = 0;
231     if dwReason == DLL_THREAD_DETACH || dwReason == DLL_PROCESS_DETACH {
232         run_dtors();
233     }
234 }
235
236 unsafe fn run_dtors() {
237     let mut any_run = true;
238     for _ in range(0, 5i) {
239         if !any_run { break }
240         any_run = false;
241         let dtors = {
242             DTOR_LOCK.lock();
243             let ret = if DTORS.is_null() {
244                 Vec::new()
245             } else {
246                 (*DTORS).iter().map(|s| *s).collect()
247             };
248             DTOR_LOCK.unlock();
249             ret
250         };
251         for &(key, dtor) in dtors.iter() {
252             let ptr = TlsGetValue(key);
253             if !ptr.is_null() {
254                 TlsSetValue(key, ptr::null_mut());
255                 dtor(ptr as *mut _);
256                 any_run = true;
257             }
258         }
259     }
260 }