]> git.lizzy.rs Git - rust.git/blob - src/librustrt/stack.rs
Add a few more derivings to AST types
[rust.git] / src / librustrt / stack.rs
1 // Copyright 2013 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 //! Rust stack-limit management
12 //!
13 //! Currently Rust uses a segmented-stack-like scheme in order to detect stack
14 //! overflow for rust tasks. In this scheme, the prologue of all functions are
15 //! preceded with a check to see whether the current stack limits are being
16 //! exceeded.
17 //!
18 //! This module provides the functionality necessary in order to manage these
19 //! stack limits (which are stored in platform-specific locations). The
20 //! functions here are used at the borders of the task lifetime in order to
21 //! manage these limits.
22 //!
23 //! This function is an unstable module because this scheme for stack overflow
24 //! detection is not guaranteed to continue in the future. Usage of this module
25 //! is discouraged unless absolutely necessary.
26
27 // iOS related notes
28 //
29 // It is possible to implement it using idea from
30 // http://www.opensource.apple.com/source/Libc/Libc-825.40.1/pthreads/pthread_machdep.h
31 //
32 // In short: _pthread_{get,set}_specific_direct allows extremely fast
33 // access, exactly what is required for segmented stack
34 // There is a pool of reserved slots for Apple internal use (0..119)
35 // First dynamic allocated pthread key starts with 257 (on iOS7)
36 // So using slot 149 should be pretty safe ASSUMING space is reserved
37 // for every key < first dynamic key
38 //
39 // There is also an opportunity to steal keys reserved for Garbage Collection
40 // ranges 80..89 and 110..119, especially considering the fact Garbage Collection
41 // never supposed to work on iOS. But as everybody knows it - there is a chance
42 // that those slots will be re-used, like it happened with key 95 (moved from
43 // JavaScriptCore to CoreText)
44 //
45 // Unfortunately Apple rejected patch to LLVM which generated
46 // corresponding prolog, decision was taken to disable segmented
47 // stack support on iOS.
48
49 pub static RED_ZONE: uint = 20 * 1024;
50
51 /// This function is invoked from rust's current __morestack function. Segmented
52 /// stacks are currently not enabled as segmented stacks, but rather one giant
53 /// stack segment. This means that whenever we run out of stack, we want to
54 /// truly consider it to be stack overflow rather than allocating a new stack.
55 #[cfg(not(test))] // in testing, use the original libstd's version
56 #[lang = "stack_exhausted"]
57 extern fn stack_exhausted() {
58     use core::prelude::*;
59     use alloc::boxed::Box;
60     use local::Local;
61     use task::Task;
62     use core::intrinsics;
63
64     unsafe {
65         // We're calling this function because the stack just ran out. We need
66         // to call some other rust functions, but if we invoke the functions
67         // right now it'll just trigger this handler being called again. In
68         // order to alleviate this, we move the stack limit to be inside of the
69         // red zone that was allocated for exactly this reason.
70         let limit = get_sp_limit();
71         record_sp_limit(limit - RED_ZONE / 2);
72
73         // This probably isn't the best course of action. Ideally one would want
74         // to unwind the stack here instead of just aborting the entire process.
75         // This is a tricky problem, however. There's a few things which need to
76         // be considered:
77         //
78         //  1. We're here because of a stack overflow, yet unwinding will run
79         //     destructors and hence arbitrary code. What if that code overflows
80         //     the stack? One possibility is to use the above allocation of an
81         //     extra 10k to hope that we don't hit the limit, and if we do then
82         //     abort the whole program. Not the best, but kind of hard to deal
83         //     with unless we want to switch stacks.
84         //
85         //  2. LLVM will optimize functions based on whether they can unwind or
86         //     not. It will flag functions with 'nounwind' if it believes that
87         //     the function cannot trigger unwinding, but if we do unwind on
88         //     stack overflow then it means that we could unwind in any function
89         //     anywhere. We would have to make sure that LLVM only places the
90         //     nounwind flag on functions which don't call any other functions.
91         //
92         //  3. The function that overflowed may have owned arguments. These
93         //     arguments need to have their destructors run, but we haven't even
94         //     begun executing the function yet, so unwinding will not run the
95         //     any landing pads for these functions. If this is ignored, then
96         //     the arguments will just be leaked.
97         //
98         // Exactly what to do here is a very delicate topic, and is possibly
99         // still up in the air for what exactly to do. Some relevant issues:
100         //
101         //  #3555 - out-of-stack failure leaks arguments
102         //  #3695 - should there be a stack limit?
103         //  #9855 - possible strategies which could be taken
104         //  #9854 - unwinding on windows through __morestack has never worked
105         //  #2361 - possible implementation of not using landing pads
106
107         let task: Option<Box<Task>> = Local::try_take();
108         let name = match task {
109             Some(ref task) => {
110                 task.name.as_ref().map(|n| n.as_slice())
111             }
112             None => None
113         };
114         let name = name.unwrap_or("<unknown>");
115
116         // See the message below for why this is not emitted to the
117         // task's logger. This has the additional conundrum of the
118         // logger may not be initialized just yet, meaning that an FFI
119         // call would happen to initialized it (calling out to libuv),
120         // and the FFI call needs 2MB of stack when we just ran out.
121         rterrln!("task '{}' has overflowed its stack", name);
122
123         intrinsics::abort();
124     }
125 }
126
127 #[inline(always)]
128 pub unsafe fn record_stack_bounds(stack_lo: uint, stack_hi: uint) {
129     // When the old runtime had segmented stacks, it used a calculation that was
130     // "limit + RED_ZONE + FUDGE". The red zone was for things like dynamic
131     // symbol resolution, llvm function calls, etc. In theory this red zone
132     // value is 0, but it matters far less when we have gigantic stacks because
133     // we don't need to be so exact about our stack budget. The "fudge factor"
134     // was because LLVM doesn't emit a stack check for functions < 256 bytes in
135     // size. Again though, we have giant stacks, so we round all these
136     // calculations up to the nice round number of 20k.
137     record_sp_limit(stack_lo + RED_ZONE);
138
139     return target_record_stack_bounds(stack_lo, stack_hi);
140
141     #[cfg(not(windows))] #[cfg(not(target_arch = "x86_64"))] #[inline(always)]
142     unsafe fn target_record_stack_bounds(_stack_lo: uint, _stack_hi: uint) {}
143     #[cfg(windows, target_arch = "x86_64")] #[inline(always)]
144     unsafe fn target_record_stack_bounds(stack_lo: uint, stack_hi: uint) {
145         // Windows compiles C functions which may check the stack bounds. This
146         // means that if we want to perform valid FFI on windows, then we need
147         // to ensure that the stack bounds are what they truly are for this
148         // task. More info can be found at:
149         //   https://github.com/rust-lang/rust/issues/3445#issuecomment-26114839
150         //
151         // stack range is at TIB: %gs:0x08 (top) and %gs:0x10 (bottom)
152         asm!("mov $0, %gs:0x08" :: "r"(stack_hi) :: "volatile");
153         asm!("mov $0, %gs:0x10" :: "r"(stack_lo) :: "volatile");
154     }
155 }
156
157 /// Records the current limit of the stack as specified by `end`.
158 ///
159 /// This is stored in an OS-dependent location, likely inside of the thread
160 /// local storage. The location that the limit is stored is a pre-ordained
161 /// location because it's where LLVM has emitted code to check.
162 ///
163 /// Note that this cannot be called under normal circumstances. This function is
164 /// changing the stack limit, so upon returning any further function calls will
165 /// possibly be triggering the morestack logic if you're not careful.
166 ///
167 /// Also note that this and all of the inside functions are all flagged as
168 /// "inline(always)" because they're messing around with the stack limits.  This
169 /// would be unfortunate for the functions themselves to trigger a morestack
170 /// invocation (if they were an actual function call).
171 #[inline(always)]
172 pub unsafe fn record_sp_limit(limit: uint) {
173     return target_record_sp_limit(limit);
174
175     // x86-64
176     #[cfg(target_arch = "x86_64", target_os = "macos")]
177     #[cfg(target_arch = "x86_64", target_os = "ios")] #[inline(always)]
178     unsafe fn target_record_sp_limit(limit: uint) {
179         asm!("movq $$0x60+90*8, %rsi
180               movq $0, %gs:(%rsi)" :: "r"(limit) : "rsi" : "volatile")
181     }
182     #[cfg(target_arch = "x86_64", target_os = "linux")] #[inline(always)]
183     unsafe fn target_record_sp_limit(limit: uint) {
184         asm!("movq $0, %fs:112" :: "r"(limit) :: "volatile")
185     }
186     #[cfg(target_arch = "x86_64", target_os = "win32")] #[inline(always)]
187     unsafe fn target_record_sp_limit(limit: uint) {
188         // see: http://en.wikipedia.org/wiki/Win32_Thread_Information_Block
189         // store this inside of the "arbitrary data slot", but double the size
190         // because this is 64 bit instead of 32 bit
191         asm!("movq $0, %gs:0x28" :: "r"(limit) :: "volatile")
192     }
193     #[cfg(target_arch = "x86_64", target_os = "freebsd")] #[inline(always)]
194     unsafe fn target_record_sp_limit(limit: uint) {
195         asm!("movq $0, %fs:24" :: "r"(limit) :: "volatile")
196     }
197
198     // x86
199     #[cfg(target_arch = "x86", target_os = "macos")]
200     #[cfg(target_arch = "x86", target_os = "ios")] #[inline(always)]
201     unsafe fn target_record_sp_limit(limit: uint) {
202         asm!("movl $$0x48+90*4, %eax
203               movl $0, %gs:(%eax)" :: "r"(limit) : "eax" : "volatile")
204     }
205     #[cfg(target_arch = "x86", target_os = "linux")]
206     #[cfg(target_arch = "x86", target_os = "freebsd")] #[inline(always)]
207     unsafe fn target_record_sp_limit(limit: uint) {
208         asm!("movl $0, %gs:48" :: "r"(limit) :: "volatile")
209     }
210     #[cfg(target_arch = "x86", target_os = "win32")] #[inline(always)]
211     unsafe fn target_record_sp_limit(limit: uint) {
212         // see: http://en.wikipedia.org/wiki/Win32_Thread_Information_Block
213         // store this inside of the "arbitrary data slot"
214         asm!("movl $0, %fs:0x14" :: "r"(limit) :: "volatile")
215     }
216
217     // mips, arm - Some brave soul can port these to inline asm, but it's over
218     //             my head personally
219     #[cfg(target_arch = "mips")]
220     #[cfg(target_arch = "mipsel")]
221     #[cfg(target_arch = "arm", not(target_os = "ios"))] #[inline(always)]
222     unsafe fn target_record_sp_limit(limit: uint) {
223         use libc::c_void;
224         return record_sp_limit(limit as *const c_void);
225         extern {
226             fn record_sp_limit(limit: *const c_void);
227         }
228     }
229
230     // iOS segmented stack is disabled for now, see related notes
231     #[cfg(target_arch = "arm", target_os = "ios")] #[inline(always)]
232     unsafe fn target_record_sp_limit(_: uint) {
233     }
234 }
235
236 /// The counterpart of the function above, this function will fetch the current
237 /// stack limit stored in TLS.
238 ///
239 /// Note that all of these functions are meant to be exact counterparts of their
240 /// brethren above, except that the operands are reversed.
241 ///
242 /// As with the setter, this function does not have a __morestack header and can
243 /// therefore be called in a "we're out of stack" situation.
244 #[inline(always)]
245 pub unsafe fn get_sp_limit() -> uint {
246     return target_get_sp_limit();
247
248     // x86-64
249     #[cfg(target_arch = "x86_64", target_os = "macos")]
250     #[cfg(target_arch = "x86_64", target_os = "ios")] #[inline(always)]
251     unsafe fn target_get_sp_limit() -> uint {
252         let limit;
253         asm!("movq $$0x60+90*8, %rsi
254               movq %gs:(%rsi), $0" : "=r"(limit) :: "rsi" : "volatile");
255         return limit;
256     }
257     #[cfg(target_arch = "x86_64", target_os = "linux")] #[inline(always)]
258     unsafe fn target_get_sp_limit() -> uint {
259         let limit;
260         asm!("movq %fs:112, $0" : "=r"(limit) ::: "volatile");
261         return limit;
262     }
263     #[cfg(target_arch = "x86_64", target_os = "win32")] #[inline(always)]
264     unsafe fn target_get_sp_limit() -> uint {
265         let limit;
266         asm!("movq %gs:0x28, $0" : "=r"(limit) ::: "volatile");
267         return limit;
268     }
269     #[cfg(target_arch = "x86_64", target_os = "freebsd")] #[inline(always)]
270     unsafe fn target_get_sp_limit() -> uint {
271         let limit;
272         asm!("movq %fs:24, $0" : "=r"(limit) ::: "volatile");
273         return limit;
274     }
275
276     // x86
277     #[cfg(target_arch = "x86", target_os = "macos")]
278     #[cfg(target_arch = "x86", target_os = "ios")] #[inline(always)]
279     unsafe fn target_get_sp_limit() -> uint {
280         let limit;
281         asm!("movl $$0x48+90*4, %eax
282               movl %gs:(%eax), $0" : "=r"(limit) :: "eax" : "volatile");
283         return limit;
284     }
285     #[cfg(target_arch = "x86", target_os = "linux")]
286     #[cfg(target_arch = "x86", target_os = "freebsd")] #[inline(always)]
287     unsafe fn target_get_sp_limit() -> uint {
288         let limit;
289         asm!("movl %gs:48, $0" : "=r"(limit) ::: "volatile");
290         return limit;
291     }
292     #[cfg(target_arch = "x86", target_os = "win32")] #[inline(always)]
293     unsafe fn target_get_sp_limit() -> uint {
294         let limit;
295         asm!("movl %fs:0x14, $0" : "=r"(limit) ::: "volatile");
296         return limit;
297     }
298
299     // mips, arm - Some brave soul can port these to inline asm, but it's over
300     //             my head personally
301     #[cfg(target_arch = "mips")]
302     #[cfg(target_arch = "mipsel")]
303     #[cfg(target_arch = "arm", not(target_os = "ios"))] #[inline(always)]
304     unsafe fn target_get_sp_limit() -> uint {
305         use libc::c_void;
306         return get_sp_limit() as uint;
307         extern {
308             fn get_sp_limit() -> *const c_void;
309         }
310     }
311
312     // iOS doesn't support segmented stacks yet. This function might
313     // be called by runtime though so it is unsafe to mark it as
314     // unreachable, let's return a fixed constant.
315     #[cfg(target_arch = "arm", target_os = "ios")] #[inline(always)]
316     unsafe fn target_get_sp_limit() -> uint {
317         1024
318     }
319 }