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