]> git.lizzy.rs Git - rust.git/blob - src/libstd/rt/backtrace.rs
Removed some unnecessary RefCells from resolve
[rust.git] / src / libstd / rt / backtrace.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 //! Simple backtrace functionality (to print on failure)
12
13 #![allow(non_camel_case_types)]
14
15 use collections::Collection;
16 use from_str::from_str;
17 use io::{IoResult, Writer};
18 use iter::Iterator;
19 use option::{Some, None};
20 use os;
21 use result::{Ok, Err};
22 use str::StrSlice;
23 use sync::atomic;
24 use unicode::char::UnicodeChar;
25
26 pub use self::imp::write;
27
28 // For now logging is turned off by default, and this function checks to see
29 // whether the magical environment variable is present to see if it's turned on.
30 pub fn log_enabled() -> bool {
31     static mut ENABLED: atomic::AtomicInt = atomic::INIT_ATOMIC_INT;
32     unsafe {
33         match ENABLED.load(atomic::SeqCst) {
34             1 => return false,
35             2 => return true,
36             _ => {}
37         }
38     }
39
40     let val = match os::getenv("RUST_BACKTRACE") {
41         Some(..) => 2,
42         None => 1,
43     };
44     unsafe { ENABLED.store(val, atomic::SeqCst); }
45     val == 2
46 }
47
48 #[cfg(target_word_size = "64")] static HEX_WIDTH: uint = 18;
49 #[cfg(target_word_size = "32")] static HEX_WIDTH: uint = 10;
50
51 // All rust symbols are in theory lists of "::"-separated identifiers. Some
52 // assemblers, however, can't handle these characters in symbol names. To get
53 // around this, we use C++-style mangling. The mangling method is:
54 //
55 // 1. Prefix the symbol with "_ZN"
56 // 2. For each element of the path, emit the length plus the element
57 // 3. End the path with "E"
58 //
59 // For example, "_ZN4testE" => "test" and "_ZN3foo3bar" => "foo::bar".
60 //
61 // We're the ones printing our backtraces, so we can't rely on anything else to
62 // demangle our symbols. It's *much* nicer to look at demangled symbols, so
63 // this function is implemented to give us nice pretty output.
64 //
65 // Note that this demangler isn't quite as fancy as it could be. We have lots
66 // of other information in our symbols like hashes, version, type information,
67 // etc. Additionally, this doesn't handle glue symbols at all.
68 fn demangle(writer: &mut Writer, s: &str) -> IoResult<()> {
69     // First validate the symbol. If it doesn't look like anything we're
70     // expecting, we just print it literally. Note that we must handle non-rust
71     // symbols because we could have any function in the backtrace.
72     let mut valid = true;
73     if s.len() > 4 && s.starts_with("_ZN") && s.ends_with("E") {
74         let mut chars = s.slice(3, s.len() - 1).chars();
75         while valid {
76             let mut i = 0;
77             for c in chars {
78                 if c.is_digit() {
79                     i = i * 10 + c as uint - '0' as uint;
80                 } else {
81                     break
82                 }
83             }
84             if i == 0 {
85                 valid = chars.next().is_none();
86                 break
87             } else if chars.by_ref().take(i - 1).count() != i - 1 {
88                 valid = false;
89             }
90         }
91     } else {
92         valid = false;
93     }
94
95     // Alright, let's do this.
96     if !valid {
97         try!(writer.write_str(s));
98     } else {
99         let mut s = s.slice_from(3);
100         let mut first = true;
101         while s.len() > 1 {
102             if !first {
103                 try!(writer.write_str("::"));
104             } else {
105                 first = false;
106             }
107             let mut rest = s;
108             while rest.char_at(0).is_digit() {
109                 rest = rest.slice_from(1);
110             }
111             let i: uint = from_str(s.slice_to(s.len() - rest.len())).unwrap();
112             s = rest.slice_from(i);
113             rest = rest.slice_to(i);
114             while rest.len() > 0 {
115                 if rest.starts_with("$") {
116                     macro_rules! demangle(
117                         ($($pat:expr => $demangled:expr),*) => ({
118                             $(if rest.starts_with($pat) {
119                                 try!(writer.write_str($demangled));
120                                 rest = rest.slice_from($pat.len());
121                               } else)*
122                             {
123                                 try!(writer.write_str(rest));
124                                 break;
125                             }
126
127                         })
128                     )
129                     // see src/librustc/back/link.rs for these mappings
130                     demangle! (
131                         "$SP$" => "@",
132                         "$UP$" => "Box",
133                         "$RP$" => "*",
134                         "$BP$" => "&",
135                         "$LT$" => "<",
136                         "$GT$" => ">",
137                         "$LP$" => "(",
138                         "$RP$" => ")",
139                         "$C$"  => ",",
140
141                         // in theory we can demangle any Unicode code point, but
142                         // for simplicity we just catch the common ones.
143                         "$x20" => " ",
144                         "$x27" => "'",
145                         "$x5b" => "[",
146                         "$x5d" => "]"
147                     )
148                 } else {
149                     let idx = match rest.find('$') {
150                         None => rest.len(),
151                         Some(i) => i,
152                     };
153                     try!(writer.write_str(rest.slice_to(idx)));
154                     rest = rest.slice_from(idx);
155                 }
156             }
157         }
158     }
159
160     Ok(())
161 }
162
163 /// Backtrace support built on libgcc with some extra OS-specific support
164 ///
165 /// Some methods of getting a backtrace:
166 ///
167 /// * The backtrace() functions on unix. It turns out this doesn't work very
168 ///   well for green threads on OSX, and the address to symbol portion of it
169 ///   suffers problems that are described below.
170 ///
171 /// * Using libunwind. This is more difficult than it sounds because libunwind
172 ///   isn't installed everywhere by default. It's also a bit of a hefty library,
173 ///   so possibly not the best option. When testing, libunwind was excellent at
174 ///   getting both accurate backtraces and accurate symbols across platforms.
175 ///   This route was not chosen in favor of the next option, however.
176 ///
177 /// * We're already using libgcc_s for exceptions in rust (triggering task
178 ///   unwinding and running destructors on the stack), and it turns out that it
179 ///   conveniently comes with a function that also gives us a backtrace. All of
180 ///   these functions look like _Unwind_*, but it's not quite the full
181 ///   repertoire of the libunwind API. Due to it already being in use, this was
182 ///   the chosen route of getting a backtrace.
183 ///
184 /// After choosing libgcc_s for backtraces, the sad part is that it will only
185 /// give us a stack trace of instruction pointers. Thankfully these instruction
186 /// pointers are accurate (they work for green and native threads), but it's
187 /// then up to us again to figure out how to translate these addresses to
188 /// symbols. As with before, we have a few options. Before, that, a little bit
189 /// of an interlude about symbols. This is my very limited knowledge about
190 /// symbol tables, and this information is likely slightly wrong, but the
191 /// general idea should be correct.
192 ///
193 /// When talking about symbols, it's helpful to know a few things about where
194 /// symbols are located. Some symbols are located in the dynamic symbol table
195 /// of the executable which in theory means that they're available for dynamic
196 /// linking and lookup. Other symbols end up only in the local symbol table of
197 /// the file. This loosely corresponds to pub and priv functions in Rust.
198 ///
199 /// Armed with this knowledge, we know that our solution for address to symbol
200 /// translation will need to consult both the local and dynamic symbol tables.
201 /// With that in mind, here's our options of translating an address to
202 /// a symbol.
203 ///
204 /// * Use dladdr(). The original backtrace()-based idea actually uses dladdr()
205 ///   behind the scenes to translate, and this is why backtrace() was not used.
206 ///   Conveniently, this method works fantastically on OSX. It appears dladdr()
207 ///   uses magic to consult the local symbol table, or we're putting everything
208 ///   in the dynamic symbol table anyway. Regardless, for OSX, this is the
209 ///   method used for translation. It's provided by the system and easy to do.o
210 ///
211 ///   Sadly, all other systems have a dladdr() implementation that does not
212 ///   consult the local symbol table. This means that most functions are blank
213 ///   because they don't have symbols. This means that we need another solution.
214 ///
215 /// * Use unw_get_proc_name(). This is part of the libunwind api (not the
216 ///   libgcc_s version of the libunwind api), but involves taking a dependency
217 ///   to libunwind. We may pursue this route in the future if we bundle
218 ///   libunwind, but libunwind was unwieldy enough that it was not chosen at
219 ///   this time to provide this functionality.
220 ///
221 /// * Shell out to a utility like `readelf`. Crazy though it may sound, it's a
222 ///   semi-reasonable solution. The stdlib already knows how to spawn processes,
223 ///   so in theory it could invoke readelf, parse the output, and consult the
224 ///   local/dynamic symbol tables from there. This ended up not getting chosen
225 ///   due to the craziness of the idea plus the advent of the next option.
226 ///
227 /// * Use `libbacktrace`. It turns out that this is a small library bundled in
228 ///   the gcc repository which provides backtrace and symbol translation
229 ///   functionality. All we really need from it is the backtrace functionality,
230 ///   and we only really need this on everything that's not OSX, so this is the
231 ///   chosen route for now.
232 ///
233 /// In summary, the current situation uses libgcc_s to get a trace of stack
234 /// pointers, and we use dladdr() or libbacktrace to translate these addresses
235 /// to symbols. This is a bit of a hokey implementation as-is, but it works for
236 /// all unix platforms we support right now, so it at least gets the job done.
237 #[cfg(unix)]
238 mod imp {
239     use c_str::CString;
240     use io::{IoResult, Writer};
241     use libc;
242     use mem;
243     use option::{Some, None, Option};
244     use result::{Ok, Err};
245     use rt::mutex::{StaticNativeMutex, NATIVE_MUTEX_INIT};
246
247     /// As always - iOS on arm uses SjLj exceptions and
248     /// _Unwind_Backtrace is even not available there. Still,
249     /// backtraces could be extracted using a backtrace function,
250     /// which thanks god is public
251     ///
252     /// As mentioned in a huge comment block above, backtrace doesn't
253     /// play well with green threads, so while it is extremely nice
254     /// and simple to use it should be used only on iOS devices as the
255     /// only viable option.
256     #[cfg(target_os = "ios", target_arch = "arm")]
257     #[inline(never)]
258     pub fn write(w: &mut Writer) -> IoResult<()> {
259         use iter::{Iterator, range};
260         use result;
261         use slice::{MutableSlice};
262
263         extern {
264             fn backtrace(buf: *mut *mut libc::c_void,
265                          sz: libc::c_int) -> libc::c_int;
266         }
267
268         // while it doesn't requires lock for work as everything is
269         // local, it still displays much nicer backtraces when a
270         // couple of tasks fail simultaneously
271         static mut LOCK: StaticNativeMutex = NATIVE_MUTEX_INIT;
272         let _g = unsafe { LOCK.lock() };
273
274         try!(writeln!(w, "stack backtrace:"));
275         // 100 lines should be enough
276         static SIZE: uint = 100;
277         let mut buf: [*mut libc::c_void, ..SIZE] = unsafe {mem::zeroed()};
278         let cnt = unsafe { backtrace(buf.as_mut_ptr(), SIZE as libc::c_int) as uint};
279
280         // skipping the first one as it is write itself
281         let iter = range(1, cnt).map(|i| {
282             print(w, i as int, buf[i])
283         });
284         result::fold(iter, (), |_, _| ())
285     }
286
287     #[cfg(not(target_os = "ios", target_arch = "arm"))]
288     #[inline(never)] // if we know this is a function call, we can skip it when
289                      // tracing
290     pub fn write(w: &mut Writer) -> IoResult<()> {
291         use io::IoError;
292
293         struct Context<'a> {
294             idx: int,
295             writer: &'a mut Writer+'a,
296             last_error: Option<IoError>,
297         }
298
299         // When using libbacktrace, we use some necessary global state, so we
300         // need to prevent more than one thread from entering this block. This
301         // is semi-reasonable in terms of printing anyway, and we know that all
302         // I/O done here is blocking I/O, not green I/O, so we don't have to
303         // worry about this being a native vs green mutex.
304         static mut LOCK: StaticNativeMutex = NATIVE_MUTEX_INIT;
305         let _g = unsafe { LOCK.lock() };
306
307         try!(writeln!(w, "stack backtrace:"));
308
309         let mut cx = Context { writer: w, last_error: None, idx: 0 };
310         return match unsafe {
311             uw::_Unwind_Backtrace(trace_fn,
312                                   &mut cx as *mut Context as *mut libc::c_void)
313         } {
314             uw::_URC_NO_REASON => {
315                 match cx.last_error {
316                     Some(err) => Err(err),
317                     None => Ok(())
318                 }
319             }
320             _ => Ok(()),
321         };
322
323         extern fn trace_fn(ctx: *mut uw::_Unwind_Context,
324                            arg: *mut libc::c_void) -> uw::_Unwind_Reason_Code {
325             let cx: &mut Context = unsafe { mem::transmute(arg) };
326             let ip = unsafe { uw::_Unwind_GetIP(ctx) as *mut libc::c_void };
327             // dladdr() on osx gets whiny when we use FindEnclosingFunction, and
328             // it appears to work fine without it, so we only use
329             // FindEnclosingFunction on non-osx platforms. In doing so, we get a
330             // slightly more accurate stack trace in the process.
331             //
332             // This is often because failure involves the last instruction of a
333             // function being "call std::rt::begin_unwind", with no ret
334             // instructions after it. This means that the return instruction
335             // pointer points *outside* of the calling function, and by
336             // unwinding it we go back to the original function.
337             let ip = if cfg!(target_os = "macos") || cfg!(target_os = "ios") {
338                 ip
339             } else {
340                 unsafe { uw::_Unwind_FindEnclosingFunction(ip) }
341             };
342
343             // Don't print out the first few frames (they're not user frames)
344             cx.idx += 1;
345             if cx.idx <= 0 { return uw::_URC_NO_REASON }
346             // Don't print ginormous backtraces
347             if cx.idx > 100 {
348                 match write!(cx.writer, " ... <frames omitted>\n") {
349                     Ok(()) => {}
350                     Err(e) => { cx.last_error = Some(e); }
351                 }
352                 return uw::_URC_FAILURE
353             }
354
355             // Once we hit an error, stop trying to print more frames
356             if cx.last_error.is_some() { return uw::_URC_FAILURE }
357
358             match print(cx.writer, cx.idx, ip) {
359                 Ok(()) => {}
360                 Err(e) => { cx.last_error = Some(e); }
361             }
362
363             // keep going
364             return uw::_URC_NO_REASON
365         }
366     }
367
368     #[cfg(target_os = "macos")]
369     #[cfg(target_os = "ios")]
370     fn print(w: &mut Writer, idx: int, addr: *mut libc::c_void) -> IoResult<()> {
371         use intrinsics;
372         #[repr(C)]
373         struct Dl_info {
374             dli_fname: *const libc::c_char,
375             dli_fbase: *mut libc::c_void,
376             dli_sname: *const libc::c_char,
377             dli_saddr: *mut libc::c_void,
378         }
379         extern {
380             fn dladdr(addr: *const libc::c_void,
381                       info: *mut Dl_info) -> libc::c_int;
382         }
383
384         let mut info: Dl_info = unsafe { intrinsics::init() };
385         if unsafe { dladdr(addr as *const libc::c_void, &mut info) == 0 } {
386             output(w, idx,addr, None)
387         } else {
388             output(w, idx, addr, Some(unsafe {
389                 CString::new(info.dli_sname, false)
390             }))
391         }
392     }
393
394     #[cfg(not(target_os = "macos"), not(target_os = "ios"))]
395     fn print(w: &mut Writer, idx: int, addr: *mut libc::c_void) -> IoResult<()> {
396         use collections::Collection;
397         use iter::Iterator;
398         use os;
399         use path::GenericPath;
400         use ptr::RawPtr;
401         use ptr;
402         use slice::{ImmutableSlice, MutableSlice};
403
404         ////////////////////////////////////////////////////////////////////////
405         // libbacktrace.h API
406         ////////////////////////////////////////////////////////////////////////
407         type backtrace_syminfo_callback =
408             extern "C" fn(data: *mut libc::c_void,
409                           pc: libc::uintptr_t,
410                           symname: *const libc::c_char,
411                           symval: libc::uintptr_t,
412                           symsize: libc::uintptr_t);
413         type backtrace_error_callback =
414             extern "C" fn(data: *mut libc::c_void,
415                           msg: *const libc::c_char,
416                           errnum: libc::c_int);
417         enum backtrace_state {}
418         #[link(name = "backtrace", kind = "static")]
419         #[cfg(not(test))]
420         extern {}
421
422         extern {
423             fn backtrace_create_state(filename: *const libc::c_char,
424                                       threaded: libc::c_int,
425                                       error: backtrace_error_callback,
426                                       data: *mut libc::c_void)
427                                             -> *mut backtrace_state;
428             fn backtrace_syminfo(state: *mut backtrace_state,
429                                  addr: libc::uintptr_t,
430                                  cb: backtrace_syminfo_callback,
431                                  error: backtrace_error_callback,
432                                  data: *mut libc::c_void) -> libc::c_int;
433         }
434
435         ////////////////////////////////////////////////////////////////////////
436         // helper callbacks
437         ////////////////////////////////////////////////////////////////////////
438
439         extern fn error_cb(_data: *mut libc::c_void, _msg: *const libc::c_char,
440                            _errnum: libc::c_int) {
441             // do nothing for now
442         }
443         extern fn syminfo_cb(data: *mut libc::c_void,
444                              _pc: libc::uintptr_t,
445                              symname: *const libc::c_char,
446                              _symval: libc::uintptr_t,
447                              _symsize: libc::uintptr_t) {
448             let slot = data as *mut *const libc::c_char;
449             unsafe { *slot = symname; }
450         }
451
452         // The libbacktrace API supports creating a state, but it does not
453         // support destroying a state. I personally take this to mean that a
454         // state is meant to be created and then live forever.
455         //
456         // I would love to register an at_exit() handler which cleans up this
457         // state, but libbacktrace provides no way to do so.
458         //
459         // With these constraints, this function has a statically cached state
460         // that is calculated the first time this is requested. Remember that
461         // backtracing all happens serially (one global lock).
462         //
463         // An additionally oddity in this function is that we initialize the
464         // filename via self_exe_name() to pass to libbacktrace. It turns out
465         // that on Linux libbacktrace seamlessly gets the filename of the
466         // current executable, but this fails on freebsd. by always providing
467         // it, we make sure that libbacktrace never has a reason to not look up
468         // the symbols. The libbacktrace API also states that the filename must
469         // be in "permanent memory", so we copy it to a static and then use the
470         // static as the pointer.
471         //
472         // FIXME: We also call self_exe_name() on DragonFly BSD. I haven't
473         //        tested if this is required or not.
474         unsafe fn init_state() -> *mut backtrace_state {
475             static mut STATE: *mut backtrace_state = 0 as *mut backtrace_state;
476             static mut LAST_FILENAME: [libc::c_char, ..256] = [0, ..256];
477             if !STATE.is_null() { return STATE }
478             let selfname = if cfg!(target_os = "freebsd") ||
479                               cfg!(target_os = "dragonfly") {
480                 os::self_exe_name()
481             } else {
482                 None
483             };
484             let filename = match selfname {
485                 Some(path) => {
486                     let bytes = path.as_vec();
487                     if bytes.len() < LAST_FILENAME.len() {
488                         let i = bytes.iter();
489                         for (slot, val) in LAST_FILENAME.iter_mut().zip(i) {
490                             *slot = *val as libc::c_char;
491                         }
492                         LAST_FILENAME.as_ptr()
493                     } else {
494                         ptr::null()
495                     }
496                 }
497                 None => ptr::null(),
498             };
499             STATE = backtrace_create_state(filename, 0, error_cb,
500                                            ptr::null_mut());
501             return STATE
502         }
503
504         ////////////////////////////////////////////////////////////////////////
505         // translation
506         ////////////////////////////////////////////////////////////////////////
507
508         // backtrace errors are currently swept under the rug, only I/O
509         // errors are reported
510         let state = unsafe { init_state() };
511         if state.is_null() {
512             return output(w, idx, addr, None)
513         }
514         let mut data = 0 as *const libc::c_char;
515         let data_addr = &mut data as *mut *const libc::c_char;
516         let ret = unsafe {
517             backtrace_syminfo(state, addr as libc::uintptr_t,
518                               syminfo_cb, error_cb,
519                               data_addr as *mut libc::c_void)
520         };
521         if ret == 0 || data.is_null() {
522             output(w, idx, addr, None)
523         } else {
524             output(w, idx, addr, Some(unsafe { CString::new(data, false) }))
525         }
526     }
527
528     // Finally, after all that work above, we can emit a symbol.
529     fn output(w: &mut Writer, idx: int, addr: *mut libc::c_void,
530               s: Option<CString>) -> IoResult<()> {
531         try!(write!(w, "  {:2}: {:2$} - ", idx, addr, super::HEX_WIDTH));
532         match s.as_ref().and_then(|c| c.as_str()) {
533             Some(string) => try!(super::demangle(w, string)),
534             None => try!(write!(w, "<unknown>")),
535         }
536         w.write(['\n' as u8])
537     }
538
539     /// Unwind library interface used for backtraces
540     ///
541     /// Note that the native libraries come from librustrt, not this
542     /// module.
543     /// Note that dead code is allowed as here are just bindings
544     /// iOS doesn't use all of them it but adding more
545     /// platform-specific configs pollutes the code too much
546     #[allow(non_camel_case_types)]
547     #[allow(non_snake_case)]
548     #[allow(dead_code)]
549     mod uw {
550         use libc;
551
552         #[repr(C)]
553         pub enum _Unwind_Reason_Code {
554             _URC_NO_REASON = 0,
555             _URC_FOREIGN_EXCEPTION_CAUGHT = 1,
556             _URC_FATAL_PHASE2_ERROR = 2,
557             _URC_FATAL_PHASE1_ERROR = 3,
558             _URC_NORMAL_STOP = 4,
559             _URC_END_OF_STACK = 5,
560             _URC_HANDLER_FOUND = 6,
561             _URC_INSTALL_CONTEXT = 7,
562             _URC_CONTINUE_UNWIND = 8,
563             _URC_FAILURE = 9, // used only by ARM EABI
564         }
565
566         pub enum _Unwind_Context {}
567
568         pub type _Unwind_Trace_Fn =
569                 extern fn(ctx: *mut _Unwind_Context,
570                           arg: *mut libc::c_void) -> _Unwind_Reason_Code;
571
572         extern {
573             // No native _Unwind_Backtrace on iOS
574             #[cfg(not(target_os = "ios", target_arch = "arm"))]
575             pub fn _Unwind_Backtrace(trace: _Unwind_Trace_Fn,
576                                      trace_argument: *mut libc::c_void)
577                         -> _Unwind_Reason_Code;
578
579             #[cfg(not(target_os = "android"),
580                   not(target_os = "linux", target_arch = "arm"))]
581             pub fn _Unwind_GetIP(ctx: *mut _Unwind_Context) -> libc::uintptr_t;
582             #[cfg(not(target_os = "android"),
583                   not(target_os = "linux", target_arch = "arm"))]
584             pub fn _Unwind_FindEnclosingFunction(pc: *mut libc::c_void)
585                 -> *mut libc::c_void;
586         }
587
588         // On android, the function _Unwind_GetIP is a macro, and this is the
589         // expansion of the macro. This is all copy/pasted directly from the
590         // header file with the definition of _Unwind_GetIP.
591         #[cfg(target_os = "android")]
592         #[cfg(target_os = "linux", target_arch = "arm")]
593         pub unsafe fn _Unwind_GetIP(ctx: *mut _Unwind_Context) -> libc::uintptr_t {
594             #[repr(C)]
595             enum _Unwind_VRS_Result {
596                 _UVRSR_OK = 0,
597                 _UVRSR_NOT_IMPLEMENTED = 1,
598                 _UVRSR_FAILED = 2,
599             }
600             #[repr(C)]
601             enum _Unwind_VRS_RegClass {
602                 _UVRSC_CORE = 0,
603                 _UVRSC_VFP = 1,
604                 _UVRSC_FPA = 2,
605                 _UVRSC_WMMXD = 3,
606                 _UVRSC_WMMXC = 4,
607             }
608             #[repr(C)]
609             enum _Unwind_VRS_DataRepresentation {
610                 _UVRSD_UINT32 = 0,
611                 _UVRSD_VFPX = 1,
612                 _UVRSD_FPAX = 2,
613                 _UVRSD_UINT64 = 3,
614                 _UVRSD_FLOAT = 4,
615                 _UVRSD_DOUBLE = 5,
616             }
617
618             type _Unwind_Word = libc::c_uint;
619             extern {
620                 fn _Unwind_VRS_Get(ctx: *mut _Unwind_Context,
621                                    klass: _Unwind_VRS_RegClass,
622                                    word: _Unwind_Word,
623                                    repr: _Unwind_VRS_DataRepresentation,
624                                    data: *mut libc::c_void)
625                     -> _Unwind_VRS_Result;
626             }
627
628             let mut val: _Unwind_Word = 0;
629             let ptr = &mut val as *mut _Unwind_Word;
630             let _ = _Unwind_VRS_Get(ctx, _UVRSC_CORE, 15, _UVRSD_UINT32,
631                                     ptr as *mut libc::c_void);
632             (val & !1) as libc::uintptr_t
633         }
634
635         // This function also doesn't exist on Android or ARM/Linux, so make it
636         // a no-op
637         #[cfg(target_os = "android")]
638         #[cfg(target_os = "linux", target_arch = "arm")]
639         pub unsafe fn _Unwind_FindEnclosingFunction(pc: *mut libc::c_void)
640             -> *mut libc::c_void
641         {
642             pc
643         }
644     }
645 }
646
647 /// As always, windows has something very different than unix, we mainly want
648 /// to avoid having to depend too much on libunwind for windows.
649 ///
650 /// If you google around, you'll find a fair bit of references to built-in
651 /// functions to get backtraces on windows. It turns out that most of these are
652 /// in an external library called dbghelp. I was unable to find this library
653 /// via `-ldbghelp`, but it is apparently normal to do the `dlopen` equivalent
654 /// of it.
655 ///
656 /// You'll also find that there's a function called CaptureStackBackTrace
657 /// mentioned frequently (which is also easy to use), but sadly I didn't have a
658 /// copy of that function in my mingw install (maybe it was broken?). Instead,
659 /// this takes the route of using StackWalk64 in order to walk the stack.
660 #[cfg(windows)]
661 #[allow(dead_code, non_snake_case)]
662 mod imp {
663     use c_str::CString;
664     use core_collections::Collection;
665     use intrinsics;
666     use io::{IoResult, Writer};
667     use libc;
668     use mem;
669     use ops::Drop;
670     use option::{Some, None};
671     use path::Path;
672     use result::{Ok, Err};
673     use rt::mutex::{StaticNativeMutex, NATIVE_MUTEX_INIT};
674     use slice::ImmutableSlice;
675     use str::StrSlice;
676     use dynamic_lib::DynamicLibrary;
677
678     #[allow(non_snake_case)]
679     extern "system" {
680         fn GetCurrentProcess() -> libc::HANDLE;
681         fn GetCurrentThread() -> libc::HANDLE;
682         fn RtlCaptureContext(ctx: *mut arch::CONTEXT);
683     }
684
685     type SymFromAddrFn =
686         extern "system" fn(libc::HANDLE, u64, *mut u64,
687                            *mut SYMBOL_INFO) -> libc::BOOL;
688     type SymInitializeFn =
689         extern "system" fn(libc::HANDLE, *mut libc::c_void,
690                            libc::BOOL) -> libc::BOOL;
691     type SymCleanupFn =
692         extern "system" fn(libc::HANDLE) -> libc::BOOL;
693
694     type StackWalk64Fn =
695         extern "system" fn(libc::DWORD, libc::HANDLE, libc::HANDLE,
696                            *mut STACKFRAME64, *mut arch::CONTEXT,
697                            *mut libc::c_void, *mut libc::c_void,
698                            *mut libc::c_void, *mut libc::c_void) -> libc::BOOL;
699
700     static MAX_SYM_NAME: uint = 2000;
701     static IMAGE_FILE_MACHINE_I386: libc::DWORD = 0x014c;
702     static IMAGE_FILE_MACHINE_IA64: libc::DWORD = 0x0200;
703     static IMAGE_FILE_MACHINE_AMD64: libc::DWORD = 0x8664;
704
705     #[repr(C)]
706     struct SYMBOL_INFO {
707         SizeOfStruct: libc::c_ulong,
708         TypeIndex: libc::c_ulong,
709         Reserved: [u64, ..2],
710         Index: libc::c_ulong,
711         Size: libc::c_ulong,
712         ModBase: u64,
713         Flags: libc::c_ulong,
714         Value: u64,
715         Address: u64,
716         Register: libc::c_ulong,
717         Scope: libc::c_ulong,
718         Tag: libc::c_ulong,
719         NameLen: libc::c_ulong,
720         MaxNameLen: libc::c_ulong,
721         // note that windows has this as 1, but it basically just means that
722         // the name is inline at the end of the struct. For us, we just bump
723         // the struct size up to MAX_SYM_NAME.
724         Name: [libc::c_char, ..MAX_SYM_NAME],
725     }
726
727
728     #[repr(C)]
729     enum ADDRESS_MODE {
730         AddrMode1616,
731         AddrMode1632,
732         AddrModeReal,
733         AddrModeFlat,
734     }
735
736     struct ADDRESS64 {
737         Offset: u64,
738         Segment: u16,
739         Mode: ADDRESS_MODE,
740     }
741
742     struct STACKFRAME64 {
743         AddrPC: ADDRESS64,
744         AddrReturn: ADDRESS64,
745         AddrFrame: ADDRESS64,
746         AddrStack: ADDRESS64,
747         AddrBStore: ADDRESS64,
748         FuncTableEntry: *mut libc::c_void,
749         Params: [u64, ..4],
750         Far: libc::BOOL,
751         Virtual: libc::BOOL,
752         Reserved: [u64, ..3],
753         KdHelp: KDHELP64,
754     }
755
756     struct KDHELP64 {
757         Thread: u64,
758         ThCallbackStack: libc::DWORD,
759         ThCallbackBStore: libc::DWORD,
760         NextCallback: libc::DWORD,
761         FramePointer: libc::DWORD,
762         KiCallUserMode: u64,
763         KeUserCallbackDispatcher: u64,
764         SystemRangeStart: u64,
765         KiUserExceptionDispatcher: u64,
766         StackBase: u64,
767         StackLimit: u64,
768         Reserved: [u64, ..5],
769     }
770
771     #[cfg(target_arch = "x86")]
772     mod arch {
773         use libc;
774
775         static MAXIMUM_SUPPORTED_EXTENSION: uint = 512;
776
777         #[repr(C)]
778         pub struct CONTEXT {
779             ContextFlags: libc::DWORD,
780             Dr0: libc::DWORD,
781             Dr1: libc::DWORD,
782             Dr2: libc::DWORD,
783             Dr3: libc::DWORD,
784             Dr6: libc::DWORD,
785             Dr7: libc::DWORD,
786             FloatSave: FLOATING_SAVE_AREA,
787             SegGs: libc::DWORD,
788             SegFs: libc::DWORD,
789             SegEs: libc::DWORD,
790             SegDs: libc::DWORD,
791             Edi: libc::DWORD,
792             Esi: libc::DWORD,
793             Ebx: libc::DWORD,
794             Edx: libc::DWORD,
795             Ecx: libc::DWORD,
796             Eax: libc::DWORD,
797             Ebp: libc::DWORD,
798             Eip: libc::DWORD,
799             SegCs: libc::DWORD,
800             EFlags: libc::DWORD,
801             Esp: libc::DWORD,
802             SegSs: libc::DWORD,
803             ExtendedRegisters: [u8, ..MAXIMUM_SUPPORTED_EXTENSION],
804         }
805
806         #[repr(C)]
807         pub struct FLOATING_SAVE_AREA {
808             ControlWord: libc::DWORD,
809             StatusWord: libc::DWORD,
810             TagWord: libc::DWORD,
811             ErrorOffset: libc::DWORD,
812             ErrorSelector: libc::DWORD,
813             DataOffset: libc::DWORD,
814             DataSelector: libc::DWORD,
815             RegisterArea: [u8, ..80],
816             Cr0NpxState: libc::DWORD,
817         }
818
819         pub fn init_frame(frame: &mut super::STACKFRAME64,
820                           ctx: &CONTEXT) -> libc::DWORD {
821             frame.AddrPC.Offset = ctx.Eip as u64;
822             frame.AddrPC.Mode = super::AddrModeFlat;
823             frame.AddrStack.Offset = ctx.Esp as u64;
824             frame.AddrStack.Mode = super::AddrModeFlat;
825             frame.AddrFrame.Offset = ctx.Ebp as u64;
826             frame.AddrFrame.Mode = super::AddrModeFlat;
827             super::IMAGE_FILE_MACHINE_I386
828         }
829     }
830
831     #[cfg(target_arch = "x86_64")]
832     mod arch {
833         use libc::{c_longlong, c_ulonglong};
834         use libc::types::os::arch::extra::{WORD, DWORD, DWORDLONG};
835         use simd;
836
837         #[repr(C)]
838         pub struct CONTEXT {
839             _align_hack: [simd::u64x2, ..0], // FIXME align on 16-byte
840             P1Home: DWORDLONG,
841             P2Home: DWORDLONG,
842             P3Home: DWORDLONG,
843             P4Home: DWORDLONG,
844             P5Home: DWORDLONG,
845             P6Home: DWORDLONG,
846
847             ContextFlags: DWORD,
848             MxCsr: DWORD,
849
850             SegCs: WORD,
851             SegDs: WORD,
852             SegEs: WORD,
853             SegFs: WORD,
854             SegGs: WORD,
855             SegSs: WORD,
856             EFlags: DWORD,
857
858             Dr0: DWORDLONG,
859             Dr1: DWORDLONG,
860             Dr2: DWORDLONG,
861             Dr3: DWORDLONG,
862             Dr6: DWORDLONG,
863             Dr7: DWORDLONG,
864
865             Rax: DWORDLONG,
866             Rcx: DWORDLONG,
867             Rdx: DWORDLONG,
868             Rbx: DWORDLONG,
869             Rsp: DWORDLONG,
870             Rbp: DWORDLONG,
871             Rsi: DWORDLONG,
872             Rdi: DWORDLONG,
873             R8:  DWORDLONG,
874             R9:  DWORDLONG,
875             R10: DWORDLONG,
876             R11: DWORDLONG,
877             R12: DWORDLONG,
878             R13: DWORDLONG,
879             R14: DWORDLONG,
880             R15: DWORDLONG,
881
882             Rip: DWORDLONG,
883
884             FltSave: FLOATING_SAVE_AREA,
885
886             VectorRegister: [M128A, .. 26],
887             VectorControl: DWORDLONG,
888
889             DebugControl: DWORDLONG,
890             LastBranchToRip: DWORDLONG,
891             LastBranchFromRip: DWORDLONG,
892             LastExceptionToRip: DWORDLONG,
893             LastExceptionFromRip: DWORDLONG,
894         }
895
896         #[repr(C)]
897         pub struct M128A {
898             _align_hack: [simd::u64x2, ..0], // FIXME align on 16-byte
899             Low:  c_ulonglong,
900             High: c_longlong
901         }
902
903         #[repr(C)]
904         pub struct FLOATING_SAVE_AREA {
905             _align_hack: [simd::u64x2, ..0], // FIXME align on 16-byte
906             _Dummy: [u8, ..512] // FIXME: Fill this out
907         }
908
909         pub fn init_frame(frame: &mut super::STACKFRAME64,
910                           ctx: &CONTEXT) -> DWORD {
911             frame.AddrPC.Offset = ctx.Rip as u64;
912             frame.AddrPC.Mode = super::AddrModeFlat;
913             frame.AddrStack.Offset = ctx.Rsp as u64;
914             frame.AddrStack.Mode = super::AddrModeFlat;
915             frame.AddrFrame.Offset = ctx.Rbp as u64;
916             frame.AddrFrame.Mode = super::AddrModeFlat;
917             super::IMAGE_FILE_MACHINE_AMD64
918         }
919     }
920
921     #[repr(C)]
922     struct Cleanup {
923         handle: libc::HANDLE,
924         SymCleanup: SymCleanupFn,
925     }
926
927     impl Drop for Cleanup {
928         fn drop(&mut self) { (self.SymCleanup)(self.handle); }
929     }
930
931     pub fn write(w: &mut Writer) -> IoResult<()> {
932         // According to windows documentation, all dbghelp functions are
933         // single-threaded.
934         static mut LOCK: StaticNativeMutex = NATIVE_MUTEX_INIT;
935         let _g = unsafe { LOCK.lock() };
936
937         // Open up dbghelp.dll, we don't link to it explicitly because it can't
938         // always be found. Additionally, it's nice having fewer dependencies.
939         let path = Path::new("dbghelp.dll");
940         let lib = match DynamicLibrary::open(Some(&path)) {
941             Ok(lib) => lib,
942             Err(..) => return Ok(()),
943         };
944
945         macro_rules! sym( ($e:expr, $t:ident) => (unsafe {
946             match lib.symbol($e) {
947                 Ok(f) => mem::transmute::<*mut u8, $t>(f),
948                 Err(..) => return Ok(())
949             }
950         }) )
951
952         // Fetch the symbols necessary from dbghelp.dll
953         let SymFromAddr = sym!("SymFromAddr", SymFromAddrFn);
954         let SymInitialize = sym!("SymInitialize", SymInitializeFn);
955         let SymCleanup = sym!("SymCleanup", SymCleanupFn);
956         let StackWalk64 = sym!("StackWalk64", StackWalk64Fn);
957
958         // Allocate necessary structures for doing the stack walk
959         let process = unsafe { GetCurrentProcess() };
960         let thread = unsafe { GetCurrentThread() };
961         let mut context: arch::CONTEXT = unsafe { intrinsics::init() };
962         unsafe { RtlCaptureContext(&mut context); }
963         let mut frame: STACKFRAME64 = unsafe { intrinsics::init() };
964         let image = arch::init_frame(&mut frame, &context);
965
966         // Initialize this process's symbols
967         let ret = SymInitialize(process, 0 as *mut libc::c_void, libc::TRUE);
968         if ret != libc::TRUE { return Ok(()) }
969         let _c = Cleanup { handle: process, SymCleanup: SymCleanup };
970
971         // And now that we're done with all the setup, do the stack walking!
972         let mut i = 0i;
973         try!(write!(w, "stack backtrace:\n"));
974         while StackWalk64(image, process, thread, &mut frame, &mut context,
975                           0 as *mut libc::c_void,
976                           0 as *mut libc::c_void,
977                           0 as *mut libc::c_void,
978                           0 as *mut libc::c_void) == libc::TRUE{
979             let addr = frame.AddrPC.Offset;
980             if addr == frame.AddrReturn.Offset || addr == 0 ||
981                frame.AddrReturn.Offset == 0 { break }
982
983             i += 1;
984             try!(write!(w, "  {:2}: {:#2$x}", i, addr, super::HEX_WIDTH));
985             let mut info: SYMBOL_INFO = unsafe { intrinsics::init() };
986             info.MaxNameLen = MAX_SYM_NAME as libc::c_ulong;
987             // the struct size in C.  the value is different to
988             // `size_of::<SYMBOL_INFO>() - MAX_SYM_NAME + 1` (== 81)
989             // due to struct alignment.
990             info.SizeOfStruct = 88;
991
992             let mut displacement = 0u64;
993             let ret = SymFromAddr(process, addr as u64, &mut displacement,
994                                   &mut info);
995
996             if ret == libc::TRUE {
997                 try!(write!(w, " - "));
998                 let cstr = unsafe { CString::new(info.Name.as_ptr(), false) };
999                 let bytes = cstr.as_bytes();
1000                 match cstr.as_str() {
1001                     Some(s) => try!(super::demangle(w, s)),
1002                     None => try!(w.write(bytes.slice_to(bytes.len() - 1))),
1003                 }
1004             }
1005             try!(w.write(['\n' as u8]));
1006         }
1007
1008         Ok(())
1009     }
1010 }
1011
1012 #[cfg(test)]
1013 mod test {
1014     use prelude::*;
1015     use io::MemWriter;
1016
1017     macro_rules! t( ($a:expr, $b:expr) => ({
1018         let mut m = MemWriter::new();
1019         super::demangle(&mut m, $a).unwrap();
1020         assert_eq!(String::from_utf8(m.unwrap()).unwrap(), $b.to_string());
1021     }) )
1022
1023     #[test]
1024     fn demangle() {
1025         t!("test", "test");
1026         t!("_ZN4testE", "test");
1027         t!("_ZN4test", "_ZN4test");
1028         t!("_ZN4test1a2bcE", "test::a::bc");
1029     }
1030
1031     #[test]
1032     fn demangle_dollars() {
1033         t!("_ZN4$UP$E", "Box");
1034         t!("_ZN8$UP$testE", "Boxtest");
1035         t!("_ZN8$UP$test4foobE", "Boxtest::foob");
1036         t!("_ZN8$x20test4foobE", " test::foob");
1037     }
1038
1039     #[test]
1040     fn demangle_many_dollars() {
1041         t!("_ZN12test$x20test4foobE", "test test::foob");
1042         t!("_ZN12test$UP$test4foobE", "testBoxtest::foob");
1043     }
1044 }