]> git.lizzy.rs Git - rust.git/blob - src/libstd/rt/backtrace.rs
librustc: Remove the fallback to `int` from typechecking.
[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 char::Char;
16 use collections::Collection;
17 use from_str::from_str;
18 use io::{IoResult, Writer};
19 use iter::Iterator;
20 use option::{Some, None};
21 use os;
22 use result::{Ok, Err};
23 use str::StrSlice;
24 use sync::atomics;
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: atomics::AtomicInt = atomics::INIT_ATOMIC_INT;
32     unsafe {
33         match ENABLED.load(atomics::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, atomics::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::{MutableVector};
262
263         extern {
264             fn backtrace(buf: *mut *libc::c_void, sz: libc::c_int) -> libc::c_int;
265         }
266
267         // while it doesn't requires lock for work as everything is
268         // local, it still displays much nicier backtraces when a
269         // couple of tasks fail simultaneously
270         static mut LOCK: StaticNativeMutex = NATIVE_MUTEX_INIT;
271         let _g = unsafe { LOCK.lock() };
272
273         try!(writeln!(w, "stack backtrace:"));
274         // 100 lines should be enough
275         static SIZE: libc::c_int = 100;
276         let mut buf: [*libc::c_void, ..SIZE] = unsafe {mem::zeroed()};
277         let cnt = unsafe { backtrace(buf.as_mut_ptr(), SIZE) as uint};
278
279         // skipping the first one as it is write itself
280         result::fold_(range(1, cnt).map(|i| {
281             print(w, i as int, buf[i])
282         }))
283     }
284
285     #[cfg(not(target_os = "ios", target_arch = "arm"))]
286     #[inline(never)] // if we know this is a function call, we can skip it when
287                      // tracing
288     pub fn write(w: &mut Writer) -> IoResult<()> {
289         use io::IoError;
290
291         struct Context<'a> {
292             idx: int,
293             writer: &'a mut Writer,
294             last_error: Option<IoError>,
295         }
296
297         // When using libbacktrace, we use some necessary global state, so we
298         // need to prevent more than one thread from entering this block. This
299         // is semi-reasonable in terms of printing anyway, and we know that all
300         // I/O done here is blocking I/O, not green I/O, so we don't have to
301         // worry about this being a native vs green mutex.
302         static mut LOCK: StaticNativeMutex = NATIVE_MUTEX_INIT;
303         let _g = unsafe { LOCK.lock() };
304
305         try!(writeln!(w, "stack backtrace:"));
306
307         let mut cx = Context { writer: w, last_error: None, idx: 0 };
308         return match unsafe {
309             uw::_Unwind_Backtrace(trace_fn,
310                                   &mut cx as *mut Context as *libc::c_void)
311         } {
312             uw::_URC_NO_REASON => {
313                 match cx.last_error {
314                     Some(err) => Err(err),
315                     None => Ok(())
316                 }
317             }
318             _ => Ok(()),
319         };
320
321         extern fn trace_fn(ctx: *uw::_Unwind_Context,
322                            arg: *libc::c_void) -> uw::_Unwind_Reason_Code {
323             let cx: &mut Context = unsafe { mem::transmute(arg) };
324             let ip = unsafe { uw::_Unwind_GetIP(ctx) as *libc::c_void };
325             // dladdr() on osx gets whiny when we use FindEnclosingFunction, and
326             // it appears to work fine without it, so we only use
327             // FindEnclosingFunction on non-osx platforms. In doing so, we get a
328             // slightly more accurate stack trace in the process.
329             //
330             // This is often because failure involves the last instruction of a
331             // function being "call std::rt::begin_unwind", with no ret
332             // instructions after it. This means that the return instruction
333             // pointer points *outside* of the calling function, and by
334             // unwinding it we go back to the original function.
335             let ip = if cfg!(target_os = "macos") || cfg!(target_os = "ios") {
336                 ip
337             } else {
338                 unsafe { uw::_Unwind_FindEnclosingFunction(ip) }
339             };
340
341             // Don't print out the first few frames (they're not user frames)
342             cx.idx += 1;
343             if cx.idx <= 0 { return uw::_URC_NO_REASON }
344             // Don't print ginormous backtraces
345             if cx.idx > 100 {
346                 match write!(cx.writer, " ... <frames omitted>\n") {
347                     Ok(()) => {}
348                     Err(e) => { cx.last_error = Some(e); }
349                 }
350                 return uw::_URC_FAILURE
351             }
352
353             // Once we hit an error, stop trying to print more frames
354             if cx.last_error.is_some() { return uw::_URC_FAILURE }
355
356             match print(cx.writer, cx.idx, ip) {
357                 Ok(()) => {}
358                 Err(e) => { cx.last_error = Some(e); }
359             }
360
361             // keep going
362             return uw::_URC_NO_REASON
363         }
364     }
365
366     #[cfg(target_os = "macos")]
367     #[cfg(target_os = "ios")]
368     fn print(w: &mut Writer, idx: int, addr: *libc::c_void) -> IoResult<()> {
369         use intrinsics;
370         #[repr(C)]
371         struct Dl_info {
372             dli_fname: *libc::c_char,
373             dli_fbase: *libc::c_void,
374             dli_sname: *libc::c_char,
375             dli_saddr: *libc::c_void,
376         }
377         extern {
378             fn dladdr(addr: *libc::c_void,
379                       info: *mut Dl_info) -> libc::c_int;
380         }
381
382         let mut info: Dl_info = unsafe { intrinsics::init() };
383         if unsafe { dladdr(addr, &mut info) == 0 } {
384             output(w, idx,addr, None)
385         } else {
386             output(w, idx, addr, Some(unsafe {
387                 CString::new(info.dli_sname, false)
388             }))
389         }
390     }
391
392     #[cfg(not(target_os = "macos"), not(target_os = "ios"))]
393     fn print(w: &mut Writer, idx: int, addr: *libc::c_void) -> IoResult<()> {
394         use collections::Collection;
395         use iter::Iterator;
396         use os;
397         use path::GenericPath;
398         use ptr::RawPtr;
399         use ptr;
400         use slice::{ImmutableVector, MutableVector};
401
402         ////////////////////////////////////////////////////////////////////////
403         // libbacktrace.h API
404         ////////////////////////////////////////////////////////////////////////
405         type backtrace_syminfo_callback =
406             extern "C" fn(data: *mut libc::c_void,
407                           pc: libc::uintptr_t,
408                           symname: *libc::c_char,
409                           symval: libc::uintptr_t,
410                           symsize: libc::uintptr_t);
411         type backtrace_error_callback =
412             extern "C" fn(data: *mut libc::c_void,
413                           msg: *libc::c_char,
414                           errnum: libc::c_int);
415         enum backtrace_state {}
416         #[link(name = "backtrace", kind = "static")]
417         extern {
418             fn backtrace_create_state(filename: *libc::c_char,
419                                       threaded: libc::c_int,
420                                       error: backtrace_error_callback,
421                                       data: *mut libc::c_void)
422                                             -> *mut backtrace_state;
423             fn backtrace_syminfo(state: *mut backtrace_state,
424                                  addr: libc::uintptr_t,
425                                  cb: backtrace_syminfo_callback,
426                                  error: backtrace_error_callback,
427                                  data: *mut libc::c_void) -> libc::c_int;
428         }
429
430         ////////////////////////////////////////////////////////////////////////
431         // helper callbacks
432         ////////////////////////////////////////////////////////////////////////
433
434         extern fn error_cb(_data: *mut libc::c_void, _msg: *libc::c_char,
435                            _errnum: libc::c_int) {
436             // do nothing for now
437         }
438         extern fn syminfo_cb(data: *mut libc::c_void,
439                              _pc: libc::uintptr_t,
440                              symname: *libc::c_char,
441                              _symval: libc::uintptr_t,
442                              _symsize: libc::uintptr_t) {
443             let slot = data as *mut *libc::c_char;
444             unsafe { *slot = symname; }
445         }
446
447         // The libbacktrace API supports creating a state, but it does not
448         // support destroying a state. I personally take this to mean that a
449         // state is meant to be created and then live forever.
450         //
451         // I would love to register an at_exit() handler which cleans up this
452         // state, but libbacktrace provides no way to do so.
453         //
454         // With these constraints, this function has a statically cached state
455         // that is calculated the first time this is requested. Remember that
456         // backtracing all happens serially (one global lock).
457         //
458         // An additionally oddity in this function is that we initialize the
459         // filename via self_exe_name() to pass to libbacktrace. It turns out
460         // that on linux libbacktrace seamlessly gets the filename of the
461         // current executable, but this fails on freebsd. by always providing
462         // it, we make sure that libbacktrace never has a reason to not look up
463         // the symbols. The libbacktrace API also states that the filename must
464         // be in "permanent memory", so we copy it to a static and then use the
465         // static as the pointer.
466         unsafe fn init_state() -> *mut backtrace_state {
467             static mut STATE: *mut backtrace_state = 0 as *mut backtrace_state;
468             static mut LAST_FILENAME: [libc::c_char, ..256] = [0, ..256];
469             if !STATE.is_null() { return STATE }
470             let selfname = if cfg!(target_os = "freebsd") {
471                 os::self_exe_name()
472             } else {
473                 None
474             };
475             let filename = match selfname {
476                 Some(path) => {
477                     let bytes = path.as_vec();
478                     if bytes.len() < LAST_FILENAME.len() {
479                         let i = bytes.iter();
480                         for (slot, val) in LAST_FILENAME.mut_iter().zip(i) {
481                             *slot = *val as libc::c_char;
482                         }
483                         LAST_FILENAME.as_ptr()
484                     } else {
485                         ptr::null()
486                     }
487                 }
488                 None => ptr::null(),
489             };
490             STATE = backtrace_create_state(filename, 0, error_cb,
491                                            ptr::mut_null());
492             return STATE
493         }
494
495         ////////////////////////////////////////////////////////////////////////
496         // translation
497         ////////////////////////////////////////////////////////////////////////
498
499         // backtrace errors are currently swept under the rug, only I/O
500         // errors are reported
501         let state = unsafe { init_state() };
502         if state.is_null() {
503             return output(w, idx, addr, None)
504         }
505         let mut data = 0 as *libc::c_char;
506         let data_addr = &mut data as *mut *libc::c_char;
507         let ret = unsafe {
508             backtrace_syminfo(state, addr as libc::uintptr_t,
509                               syminfo_cb, error_cb,
510                               data_addr as *mut libc::c_void)
511         };
512         if ret == 0 || data.is_null() {
513             output(w, idx, addr, None)
514         } else {
515             output(w, idx, addr, Some(unsafe { CString::new(data, false) }))
516         }
517     }
518
519     // Finally, after all that work above, we can emit a symbol.
520     fn output(w: &mut Writer, idx: int, addr: *libc::c_void,
521               s: Option<CString>) -> IoResult<()> {
522         try!(write!(w, "  {:2}: {:2$} - ", idx, addr, super::HEX_WIDTH));
523         match s.as_ref().and_then(|c| c.as_str()) {
524             Some(string) => try!(super::demangle(w, string)),
525             None => try!(write!(w, "<unknown>")),
526         }
527         w.write(['\n' as u8])
528     }
529
530     /// Unwind library interface used for backtraces
531     ///
532     /// Note that the native libraries come from librustrt, not this
533     /// module.
534     /// Note that dead code is allowed as here are just bindings
535     /// iOS doesn't use all of them it but adding more
536     /// platform-specific configs pollutes the code too much
537     #[allow(non_camel_case_types)]
538     #[allow(non_snake_case_functions)]
539     #[allow(dead_code)]
540     mod uw {
541         use libc;
542
543         #[repr(C)]
544         pub enum _Unwind_Reason_Code {
545             _URC_NO_REASON = 0,
546             _URC_FOREIGN_EXCEPTION_CAUGHT = 1,
547             _URC_FATAL_PHASE2_ERROR = 2,
548             _URC_FATAL_PHASE1_ERROR = 3,
549             _URC_NORMAL_STOP = 4,
550             _URC_END_OF_STACK = 5,
551             _URC_HANDLER_FOUND = 6,
552             _URC_INSTALL_CONTEXT = 7,
553             _URC_CONTINUE_UNWIND = 8,
554             _URC_FAILURE = 9, // used only by ARM EABI
555         }
556
557         pub enum _Unwind_Context {}
558
559         pub type _Unwind_Trace_Fn =
560                 extern fn(ctx: *_Unwind_Context,
561                           arg: *libc::c_void) -> _Unwind_Reason_Code;
562
563         extern {
564             // No native _Unwind_Backtrace on iOS
565             #[cfg(not(target_os = "ios", target_arch = "arm"))]
566             pub fn _Unwind_Backtrace(trace: _Unwind_Trace_Fn,
567                                      trace_argument: *libc::c_void)
568                         -> _Unwind_Reason_Code;
569
570             #[cfg(not(target_os = "android"),
571                   not(target_os = "linux", target_arch = "arm"))]
572             pub fn _Unwind_GetIP(ctx: *_Unwind_Context) -> libc::uintptr_t;
573             #[cfg(not(target_os = "android"),
574                   not(target_os = "linux", target_arch = "arm"))]
575             pub fn _Unwind_FindEnclosingFunction(pc: *libc::c_void)
576                 -> *libc::c_void;
577         }
578
579         // On android, the function _Unwind_GetIP is a macro, and this is the
580         // expansion of the macro. This is all copy/pasted directly from the
581         // header file with the definition of _Unwind_GetIP.
582         #[cfg(target_os = "android")]
583         #[cfg(target_os = "linux", target_arch = "arm")]
584         pub unsafe fn _Unwind_GetIP(ctx: *_Unwind_Context) -> libc::uintptr_t {
585             #[repr(C)]
586             enum _Unwind_VRS_Result {
587                 _UVRSR_OK = 0,
588                 _UVRSR_NOT_IMPLEMENTED = 1,
589                 _UVRSR_FAILED = 2,
590             }
591             #[repr(C)]
592             enum _Unwind_VRS_RegClass {
593                 _UVRSC_CORE = 0,
594                 _UVRSC_VFP = 1,
595                 _UVRSC_FPA = 2,
596                 _UVRSC_WMMXD = 3,
597                 _UVRSC_WMMXC = 4,
598             }
599             #[repr(C)]
600             enum _Unwind_VRS_DataRepresentation {
601                 _UVRSD_UINT32 = 0,
602                 _UVRSD_VFPX = 1,
603                 _UVRSD_FPAX = 2,
604                 _UVRSD_UINT64 = 3,
605                 _UVRSD_FLOAT = 4,
606                 _UVRSD_DOUBLE = 5,
607             }
608
609             type _Unwind_Word = libc::c_uint;
610             extern {
611                 fn _Unwind_VRS_Get(ctx: *_Unwind_Context,
612                                    klass: _Unwind_VRS_RegClass,
613                                    word: _Unwind_Word,
614                                    repr: _Unwind_VRS_DataRepresentation,
615                                    data: *mut libc::c_void)
616                     -> _Unwind_VRS_Result;
617             }
618
619             let mut val: _Unwind_Word = 0;
620             let ptr = &mut val as *mut _Unwind_Word;
621             let _ = _Unwind_VRS_Get(ctx, _UVRSC_CORE, 15, _UVRSD_UINT32,
622                                     ptr as *mut libc::c_void);
623             (val & !1) as libc::uintptr_t
624         }
625
626         // This function also doesn't exist on android or arm/linux, so make it
627         // a no-op
628         #[cfg(target_os = "android")]
629         #[cfg(target_os = "linux", target_arch = "arm")]
630         pub unsafe fn _Unwind_FindEnclosingFunction(pc: *libc::c_void)
631             -> *libc::c_void
632         {
633             pc
634         }
635     }
636 }
637
638 /// As always, windows has something very different than unix, we mainly want
639 /// to avoid having to depend too much on libunwind for windows.
640 ///
641 /// If you google around, you'll find a fair bit of references to built-in
642 /// functions to get backtraces on windows. It turns out that most of these are
643 /// in an external library called dbghelp. I was unable to find this library
644 /// via `-ldbghelp`, but it is apparently normal to do the `dlopen` equivalent
645 /// of it.
646 ///
647 /// You'll also find that there's a function called CaptureStackBackTrace
648 /// mentioned frequently (which is also easy to use), but sadly I didn't have a
649 /// copy of that function in my mingw install (maybe it was broken?). Instead,
650 /// this takes the route of using StackWalk64 in order to walk the stack.
651 #[cfg(windows)]
652 #[allow(dead_code, uppercase_variables)]
653 mod imp {
654     use c_str::CString;
655     use core_collections::Collection;
656     use intrinsics;
657     use io::{IoResult, Writer};
658     use libc;
659     use mem;
660     use ops::Drop;
661     use option::{Some, None};
662     use path::Path;
663     use result::{Ok, Err};
664     use rt::mutex::{StaticNativeMutex, NATIVE_MUTEX_INIT};
665     use slice::ImmutableVector;
666     use str::StrSlice;
667     use dynamic_lib::DynamicLibrary;
668
669     #[allow(non_snake_case_functions)]
670     extern "system" {
671         fn GetCurrentProcess() -> libc::HANDLE;
672         fn GetCurrentThread() -> libc::HANDLE;
673         fn RtlCaptureContext(ctx: *mut arch::CONTEXT);
674     }
675
676     type SymFromAddrFn =
677         extern "system" fn(libc::HANDLE, u64, *mut u64,
678                            *mut SYMBOL_INFO) -> libc::BOOL;
679     type SymInitializeFn =
680         extern "system" fn(libc::HANDLE, *libc::c_void,
681                            libc::BOOL) -> libc::BOOL;
682     type SymCleanupFn =
683         extern "system" fn(libc::HANDLE) -> libc::BOOL;
684
685     type StackWalk64Fn =
686         extern "system" fn(libc::DWORD, libc::HANDLE, libc::HANDLE,
687                            *mut STACKFRAME64, *mut arch::CONTEXT,
688                            *libc::c_void, *libc::c_void,
689                            *libc::c_void, *libc::c_void) -> libc::BOOL;
690
691     static MAX_SYM_NAME: uint = 2000;
692     static IMAGE_FILE_MACHINE_I386: libc::DWORD = 0x014c;
693     static IMAGE_FILE_MACHINE_IA64: libc::DWORD = 0x0200;
694     static IMAGE_FILE_MACHINE_AMD64: libc::DWORD = 0x8664;
695
696     #[packed]
697     struct SYMBOL_INFO {
698         SizeOfStruct: libc::c_ulong,
699         TypeIndex: libc::c_ulong,
700         Reserved: [u64, ..2],
701         Index: libc::c_ulong,
702         Size: libc::c_ulong,
703         ModBase: u64,
704         Flags: libc::c_ulong,
705         Value: u64,
706         Address: u64,
707         Register: libc::c_ulong,
708         Scope: libc::c_ulong,
709         Tag: libc::c_ulong,
710         NameLen: libc::c_ulong,
711         MaxNameLen: libc::c_ulong,
712         // note that windows has this as 1, but it basically just means that
713         // the name is inline at the end of the struct. For us, we just bump
714         // the struct size up to MAX_SYM_NAME.
715         Name: [libc::c_char, ..MAX_SYM_NAME],
716     }
717
718     #[repr(C)]
719     enum ADDRESS_MODE {
720         AddrMode1616,
721         AddrMode1632,
722         AddrModeReal,
723         AddrModeFlat,
724     }
725
726     struct ADDRESS64 {
727         Offset: u64,
728         Segment: u16,
729         Mode: ADDRESS_MODE,
730     }
731
732     struct STACKFRAME64 {
733         AddrPC: ADDRESS64,
734         AddrReturn: ADDRESS64,
735         AddrFrame: ADDRESS64,
736         AddrStack: ADDRESS64,
737         AddrBStore: ADDRESS64,
738         FuncTableEntry: *libc::c_void,
739         Params: [u64, ..4],
740         Far: libc::BOOL,
741         Virtual: libc::BOOL,
742         Reserved: [u64, ..3],
743         KdHelp: KDHELP64,
744     }
745
746     struct KDHELP64 {
747         Thread: u64,
748         ThCallbackStack: libc::DWORD,
749         ThCallbackBStore: libc::DWORD,
750         NextCallback: libc::DWORD,
751         FramePointer: libc::DWORD,
752         KiCallUserMode: u64,
753         KeUserCallbackDispatcher: u64,
754         SystemRangeStart: u64,
755         KiUserExceptionDispatcher: u64,
756         StackBase: u64,
757         StackLimit: u64,
758         Reserved: [u64, ..5],
759     }
760
761     #[cfg(target_arch = "x86")]
762     mod arch {
763         use libc;
764
765         static MAXIMUM_SUPPORTED_EXTENSION: uint = 512;
766
767         pub struct CONTEXT {
768             ContextFlags: libc::DWORD,
769             Dr0: libc::DWORD,
770             Dr1: libc::DWORD,
771             Dr2: libc::DWORD,
772             Dr3: libc::DWORD,
773             Dr6: libc::DWORD,
774             Dr7: libc::DWORD,
775             FloatSave: FLOATING_SAVE_AREA,
776             SegGs: libc::DWORD,
777             SegFs: libc::DWORD,
778             SegEs: libc::DWORD,
779             SegDs: libc::DWORD,
780             Edi: libc::DWORD,
781             Esi: libc::DWORD,
782             Ebx: libc::DWORD,
783             Edx: libc::DWORD,
784             Ecx: libc::DWORD,
785             Eax: libc::DWORD,
786             Ebp: libc::DWORD,
787             Eip: libc::DWORD,
788             SegCs: libc::DWORD,
789             EFlags: libc::DWORD,
790             Esp: libc::DWORD,
791             SegSs: libc::DWORD,
792             ExtendedRegisters: [u8, ..MAXIMUM_SUPPORTED_EXTENSION],
793         }
794
795         pub struct FLOATING_SAVE_AREA {
796             ControlWord: libc::DWORD,
797             StatusWord: libc::DWORD,
798             TagWord: libc::DWORD,
799             ErrorOffset: libc::DWORD,
800             ErrorSelector: libc::DWORD,
801             DataOffset: libc::DWORD,
802             DataSelector: libc::DWORD,
803             RegisterArea: [u8, ..80],
804             Cr0NpxState: libc::DWORD,
805         }
806
807         pub fn init_frame(frame: &mut super::STACKFRAME64,
808                           ctx: &CONTEXT) -> libc::DWORD {
809             frame.AddrPC.Offset = ctx.Eip as u64;
810             frame.AddrPC.Mode = super::AddrModeFlat;
811             frame.AddrStack.Offset = ctx.Esp as u64;
812             frame.AddrStack.Mode = super::AddrModeFlat;
813             frame.AddrFrame.Offset = ctx.Ebp as u64;
814             frame.AddrFrame.Mode = super::AddrModeFlat;
815             super::IMAGE_FILE_MACHINE_I386
816         }
817     }
818
819     #[cfg(target_arch = "x86_64")]
820     mod arch {
821         use libc::{c_longlong, c_ulonglong};
822         use libc::types::os::arch::extra::{WORD, DWORD, DWORDLONG};
823
824         pub struct CONTEXT {
825             P1Home: DWORDLONG,
826             P2Home: DWORDLONG,
827             P3Home: DWORDLONG,
828             P4Home: DWORDLONG,
829             P5Home: DWORDLONG,
830             P6Home: DWORDLONG,
831
832             ContextFlags: DWORD,
833             MxCsr: DWORD,
834
835             SegCs: WORD,
836             SegDs: WORD,
837             SegEs: WORD,
838             SegFs: WORD,
839             SegGs: WORD,
840             SegSs: WORD,
841             EFlags: DWORD,
842
843             Dr0: DWORDLONG,
844             Dr1: DWORDLONG,
845             Dr2: DWORDLONG,
846             Dr3: DWORDLONG,
847             Dr6: DWORDLONG,
848             Dr7: DWORDLONG,
849
850             Rax: DWORDLONG,
851             Rcx: DWORDLONG,
852             Rdx: DWORDLONG,
853             Rbx: DWORDLONG,
854             Rsp: DWORDLONG,
855             Rbp: DWORDLONG,
856             Rsi: DWORDLONG,
857             Rdi: DWORDLONG,
858             R8:  DWORDLONG,
859             R9:  DWORDLONG,
860             R10: DWORDLONG,
861             R11: DWORDLONG,
862             R12: DWORDLONG,
863             R13: DWORDLONG,
864             R14: DWORDLONG,
865             R15: DWORDLONG,
866
867             Rip: DWORDLONG,
868
869             FltSave: FLOATING_SAVE_AREA,
870
871             VectorRegister: [M128A, .. 26],
872             VectorControl: DWORDLONG,
873
874             DebugControl: DWORDLONG,
875             LastBranchToRip: DWORDLONG,
876             LastBranchFromRip: DWORDLONG,
877             LastExceptionToRip: DWORDLONG,
878             LastExceptionFromRip: DWORDLONG,
879         }
880
881         pub struct M128A {
882             Low:  c_ulonglong,
883             High: c_longlong
884         }
885
886         pub struct FLOATING_SAVE_AREA {
887             _Dummy: [u8, ..512] // FIXME: Fill this out
888         }
889
890         pub fn init_frame(frame: &mut super::STACKFRAME64,
891                           ctx: &CONTEXT) -> DWORD {
892             frame.AddrPC.Offset = ctx.Rip as u64;
893             frame.AddrPC.Mode = super::AddrModeFlat;
894             frame.AddrStack.Offset = ctx.Rsp as u64;
895             frame.AddrStack.Mode = super::AddrModeFlat;
896             frame.AddrFrame.Offset = ctx.Rbp as u64;
897             frame.AddrFrame.Mode = super::AddrModeFlat;
898             super::IMAGE_FILE_MACHINE_AMD64
899         }
900     }
901
902     struct Cleanup {
903         handle: libc::HANDLE,
904         SymCleanup: SymCleanupFn,
905     }
906
907     impl Drop for Cleanup {
908         fn drop(&mut self) { (self.SymCleanup)(self.handle); }
909     }
910
911     pub fn write(w: &mut Writer) -> IoResult<()> {
912         // According to windows documentation, all dbghelp functions are
913         // single-threaded.
914         static mut LOCK: StaticNativeMutex = NATIVE_MUTEX_INIT;
915         let _g = unsafe { LOCK.lock() };
916
917         // Open up dbghelp.dll, we don't link to it explicitly because it can't
918         // always be found. Additionally, it's nice having fewer dependencies.
919         let path = Path::new("dbghelp.dll");
920         let lib = match DynamicLibrary::open(Some(&path)) {
921             Ok(lib) => lib,
922             Err(..) => return Ok(()),
923         };
924
925         macro_rules! sym( ($e:expr, $t:ident) => (unsafe {
926             match lib.symbol($e) {
927                 Ok(f) => mem::transmute::<*u8, $t>(f),
928                 Err(..) => return Ok(())
929             }
930         }) )
931
932         // Fetch the symbols necessary from dbghelp.dll
933         let SymFromAddr = sym!("SymFromAddr", SymFromAddrFn);
934         let SymInitialize = sym!("SymInitialize", SymInitializeFn);
935         let SymCleanup = sym!("SymCleanup", SymCleanupFn);
936         let StackWalk64 = sym!("StackWalk64", StackWalk64Fn);
937
938         // Allocate necessary structures for doing the stack walk
939         let process = unsafe { GetCurrentProcess() };
940         let thread = unsafe { GetCurrentThread() };
941         let mut context: arch::CONTEXT = unsafe { intrinsics::init() };
942         unsafe { RtlCaptureContext(&mut context); }
943         let mut frame: STACKFRAME64 = unsafe { intrinsics::init() };
944         let image = arch::init_frame(&mut frame, &context);
945
946         // Initialize this process's symbols
947         let ret = SymInitialize(process, 0 as *libc::c_void, libc::TRUE);
948         if ret != libc::TRUE { return Ok(()) }
949         let _c = Cleanup { handle: process, SymCleanup: SymCleanup };
950
951         // And now that we're done with all the setup, do the stack walking!
952         let mut i = 0i;
953         try!(write!(w, "stack backtrace:\n"));
954         while StackWalk64(image, process, thread, &mut frame, &mut context,
955                           0 as *libc::c_void, 0 as *libc::c_void,
956                           0 as *libc::c_void, 0 as *libc::c_void) == libc::TRUE{
957             let addr = frame.AddrPC.Offset;
958             if addr == frame.AddrReturn.Offset || addr == 0 ||
959                frame.AddrReturn.Offset == 0 { break }
960
961             i += 1;
962             try!(write!(w, "  {:2}: {:#2$x}", i, addr, super::HEX_WIDTH));
963             let mut info: SYMBOL_INFO = unsafe { intrinsics::init() };
964             info.MaxNameLen = MAX_SYM_NAME as libc::c_ulong;
965             info.SizeOfStruct = (mem::size_of::<SYMBOL_INFO>() -
966                                  info.Name.len() + 1) as libc::c_ulong;
967
968             let mut displacement = 0u64;
969             let ret = SymFromAddr(process, addr as u64, &mut displacement,
970                                   &mut info);
971
972             if ret == libc::TRUE {
973                 try!(write!(w, " - "));
974                 let cstr = unsafe { CString::new(info.Name.as_ptr(), false) };
975                 let bytes = cstr.as_bytes();
976                 match cstr.as_str() {
977                     Some(s) => try!(super::demangle(w, s)),
978                     None => try!(w.write(bytes.slice_to(bytes.len() - 1))),
979                 }
980             }
981             try!(w.write(['\n' as u8]));
982         }
983
984         Ok(())
985     }
986 }
987
988 #[cfg(test)]
989 mod test {
990     use prelude::*;
991     use io::MemWriter;
992     use str;
993
994     macro_rules! t( ($a:expr, $b:expr) => ({
995         let mut m = MemWriter::new();
996         super::demangle(&mut m, $a).unwrap();
997         assert_eq!(str::from_utf8(m.unwrap().as_slice()).unwrap().to_owned(), $b.to_owned());
998     }) )
999
1000     #[test]
1001     fn demangle() {
1002         t!("test", "test");
1003         t!("_ZN4testE", "test");
1004         t!("_ZN4test", "_ZN4test");
1005         t!("_ZN4test1a2bcE", "test::a::bc");
1006     }
1007
1008     #[test]
1009     fn demangle_dollars() {
1010         t!("_ZN4$UP$E", "Box");
1011         t!("_ZN8$UP$testE", "Boxtest");
1012         t!("_ZN8$UP$test4foobE", "Boxtest::foob");
1013         t!("_ZN8$x20test4foobE", " test::foob");
1014     }
1015
1016     #[test]
1017     fn demangle_many_dollars() {
1018         t!("_ZN12test$x20test4foobE", "test test::foob");
1019         t!("_ZN12test$UP$test4foobE", "testBoxtest::foob");
1020     }
1021 }