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.
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.
11 //! Simple backtrace functionality (to print on failure)
13 #![allow(non_camel_case_types)]
15 use collections::Collection;
16 use from_str::from_str;
17 use io::{IoResult, Writer};
19 use option::{Some, None};
21 use result::{Ok, Err};
24 use unicode::char::UnicodeChar;
26 pub use self::imp::write;
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;
33 match ENABLED.load(atomic::SeqCst) {
40 let val = match os::getenv("RUST_BACKTRACE") {
44 unsafe { ENABLED.store(val, atomic::SeqCst); }
48 #[cfg(target_word_size = "64")] static HEX_WIDTH: uint = 18;
49 #[cfg(target_word_size = "32")] static HEX_WIDTH: uint = 10;
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:
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"
59 // For example, "_ZN4testE" => "test" and "_ZN3foo3bar" => "foo::bar".
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.
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.
73 if s.len() > 4 && s.starts_with("_ZN") && s.ends_with("E") {
74 let mut chars = s.slice(3, s.len() - 1).chars();
79 i = i * 10 + c as uint - '0' as uint;
85 valid = chars.next().is_none();
87 } else if chars.by_ref().take(i - 1).count() != i - 1 {
95 // Alright, let's do this.
97 try!(writer.write_str(s));
99 let mut s = s.slice_from(3);
100 let mut first = true;
103 try!(writer.write_str("::"));
108 while rest.char_at(0).is_digit() {
109 rest = rest.slice_from(1);
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());
123 try!(writer.write_str(rest));
129 // see src/librustc/back/link.rs for these mappings
141 // in theory we can demangle any unicode code point, but
142 // for simplicity we just catch the common ones.
149 let idx = match rest.find('$') {
153 try!(writer.write_str(rest.slice_to(idx)));
154 rest = rest.slice_from(idx);
163 /// Backtrace support built on libgcc with some extra OS-specific support
165 /// Some methods of getting a backtrace:
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.
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.
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.
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.
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.
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
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
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.
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.
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.
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.
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.
240 use io::{IoResult, Writer};
243 use option::{Some, None, Option};
244 use result::{Ok, Err};
245 use rt::mutex::{StaticNativeMutex, NATIVE_MUTEX_INIT};
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
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")]
258 pub fn write(w: &mut Writer) -> IoResult<()> {
259 use iter::{Iterator, range};
261 use slice::{MutableSlice};
264 fn backtrace(buf: *mut *mut libc::c_void,
265 sz: libc::c_int) -> libc::c_int;
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() };
274 try!(writeln!(w, "stack backtrace:"));
275 // 100 lines should be enough
276 static SIZE: libc::c_int = 100;
277 let mut buf: [*mut libc::c_void, ..SIZE] = unsafe {mem::zeroed()};
278 let cnt = unsafe { backtrace(buf.as_mut_ptr(), SIZE) as uint};
280 // skipping the first one as it is write itself
281 result::fold_(range(1, cnt).map(|i| {
282 print(w, i as int, buf[i])
286 #[cfg(not(target_os = "ios", target_arch = "arm"))]
287 #[inline(never)] // if we know this is a function call, we can skip it when
289 pub fn write(w: &mut Writer) -> IoResult<()> {
294 writer: &'a mut Writer,
295 last_error: Option<IoError>,
298 // When using libbacktrace, we use some necessary global state, so we
299 // need to prevent more than one thread from entering this block. This
300 // is semi-reasonable in terms of printing anyway, and we know that all
301 // I/O done here is blocking I/O, not green I/O, so we don't have to
302 // worry about this being a native vs green mutex.
303 static mut LOCK: StaticNativeMutex = NATIVE_MUTEX_INIT;
304 let _g = unsafe { LOCK.lock() };
306 try!(writeln!(w, "stack backtrace:"));
308 let mut cx = Context { writer: w, last_error: None, idx: 0 };
309 return match unsafe {
310 uw::_Unwind_Backtrace(trace_fn,
311 &mut cx as *mut Context as *mut libc::c_void)
313 uw::_URC_NO_REASON => {
314 match cx.last_error {
315 Some(err) => Err(err),
322 extern fn trace_fn(ctx: *mut uw::_Unwind_Context,
323 arg: *mut libc::c_void) -> uw::_Unwind_Reason_Code {
324 let cx: &mut Context = unsafe { mem::transmute(arg) };
325 let ip = unsafe { uw::_Unwind_GetIP(ctx) as *mut libc::c_void };
326 // dladdr() on osx gets whiny when we use FindEnclosingFunction, and
327 // it appears to work fine without it, so we only use
328 // FindEnclosingFunction on non-osx platforms. In doing so, we get a
329 // slightly more accurate stack trace in the process.
331 // This is often because failure involves the last instruction of a
332 // function being "call std::rt::begin_unwind", with no ret
333 // instructions after it. This means that the return instruction
334 // pointer points *outside* of the calling function, and by
335 // unwinding it we go back to the original function.
336 let ip = if cfg!(target_os = "macos") || cfg!(target_os = "ios") {
339 unsafe { uw::_Unwind_FindEnclosingFunction(ip) }
342 // Don't print out the first few frames (they're not user frames)
344 if cx.idx <= 0 { return uw::_URC_NO_REASON }
345 // Don't print ginormous backtraces
347 match write!(cx.writer, " ... <frames omitted>\n") {
349 Err(e) => { cx.last_error = Some(e); }
351 return uw::_URC_FAILURE
354 // Once we hit an error, stop trying to print more frames
355 if cx.last_error.is_some() { return uw::_URC_FAILURE }
357 match print(cx.writer, cx.idx, ip) {
359 Err(e) => { cx.last_error = Some(e); }
363 return uw::_URC_NO_REASON
367 #[cfg(target_os = "macos")]
368 #[cfg(target_os = "ios")]
369 fn print(w: &mut Writer, idx: int, addr: *mut libc::c_void) -> IoResult<()> {
373 dli_fname: *const libc::c_char,
374 dli_fbase: *mut libc::c_void,
375 dli_sname: *const libc::c_char,
376 dli_saddr: *mut libc::c_void,
379 fn dladdr(addr: *const libc::c_void,
380 info: *mut Dl_info) -> libc::c_int;
383 let mut info: Dl_info = unsafe { intrinsics::init() };
384 if unsafe { dladdr(addr as *const libc::c_void, &mut info) == 0 } {
385 output(w, idx,addr, None)
387 output(w, idx, addr, Some(unsafe {
388 CString::new(info.dli_sname, false)
393 #[cfg(not(target_os = "macos"), not(target_os = "ios"))]
394 fn print(w: &mut Writer, idx: int, addr: *mut libc::c_void) -> IoResult<()> {
395 use collections::Collection;
398 use path::GenericPath;
401 use slice::{ImmutableSlice, MutableSlice};
403 ////////////////////////////////////////////////////////////////////////
404 // libbacktrace.h API
405 ////////////////////////////////////////////////////////////////////////
406 type backtrace_syminfo_callback =
407 extern "C" fn(data: *mut libc::c_void,
409 symname: *const libc::c_char,
410 symval: libc::uintptr_t,
411 symsize: libc::uintptr_t);
412 type backtrace_error_callback =
413 extern "C" fn(data: *mut libc::c_void,
414 msg: *const libc::c_char,
415 errnum: libc::c_int);
416 enum backtrace_state {}
417 #[link(name = "backtrace", kind = "static")]
422 fn backtrace_create_state(filename: *const libc::c_char,
423 threaded: libc::c_int,
424 error: backtrace_error_callback,
425 data: *mut libc::c_void)
426 -> *mut backtrace_state;
427 fn backtrace_syminfo(state: *mut backtrace_state,
428 addr: libc::uintptr_t,
429 cb: backtrace_syminfo_callback,
430 error: backtrace_error_callback,
431 data: *mut libc::c_void) -> libc::c_int;
434 ////////////////////////////////////////////////////////////////////////
436 ////////////////////////////////////////////////////////////////////////
438 extern fn error_cb(_data: *mut libc::c_void, _msg: *const libc::c_char,
439 _errnum: libc::c_int) {
440 // do nothing for now
442 extern fn syminfo_cb(data: *mut libc::c_void,
443 _pc: libc::uintptr_t,
444 symname: *const libc::c_char,
445 _symval: libc::uintptr_t,
446 _symsize: libc::uintptr_t) {
447 let slot = data as *mut *const libc::c_char;
448 unsafe { *slot = symname; }
451 // The libbacktrace API supports creating a state, but it does not
452 // support destroying a state. I personally take this to mean that a
453 // state is meant to be created and then live forever.
455 // I would love to register an at_exit() handler which cleans up this
456 // state, but libbacktrace provides no way to do so.
458 // With these constraints, this function has a statically cached state
459 // that is calculated the first time this is requested. Remember that
460 // backtracing all happens serially (one global lock).
462 // An additionally oddity in this function is that we initialize the
463 // filename via self_exe_name() to pass to libbacktrace. It turns out
464 // that on linux libbacktrace seamlessly gets the filename of the
465 // current executable, but this fails on freebsd. by always providing
466 // it, we make sure that libbacktrace never has a reason to not look up
467 // the symbols. The libbacktrace API also states that the filename must
468 // be in "permanent memory", so we copy it to a static and then use the
469 // static as the pointer.
471 // FIXME: We also call self_exe_name() on DragonFly BSD. I haven't
472 // tested if this is required or not.
473 unsafe fn init_state() -> *mut backtrace_state {
474 static mut STATE: *mut backtrace_state = 0 as *mut backtrace_state;
475 static mut LAST_FILENAME: [libc::c_char, ..256] = [0, ..256];
476 if !STATE.is_null() { return STATE }
477 let selfname = if cfg!(target_os = "freebsd") ||
478 cfg!(target_os = "dragonfly") {
483 let filename = match selfname {
485 let bytes = path.as_vec();
486 if bytes.len() < LAST_FILENAME.len() {
487 let i = bytes.iter();
488 for (slot, val) in LAST_FILENAME.mut_iter().zip(i) {
489 *slot = *val as libc::c_char;
491 LAST_FILENAME.as_ptr()
498 STATE = backtrace_create_state(filename, 0, error_cb,
503 ////////////////////////////////////////////////////////////////////////
505 ////////////////////////////////////////////////////////////////////////
507 // backtrace errors are currently swept under the rug, only I/O
508 // errors are reported
509 let state = unsafe { init_state() };
511 return output(w, idx, addr, None)
513 let mut data = 0 as *const libc::c_char;
514 let data_addr = &mut data as *mut *const libc::c_char;
516 backtrace_syminfo(state, addr as libc::uintptr_t,
517 syminfo_cb, error_cb,
518 data_addr as *mut libc::c_void)
520 if ret == 0 || data.is_null() {
521 output(w, idx, addr, None)
523 output(w, idx, addr, Some(unsafe { CString::new(data, false) }))
527 // Finally, after all that work above, we can emit a symbol.
528 fn output(w: &mut Writer, idx: int, addr: *mut libc::c_void,
529 s: Option<CString>) -> IoResult<()> {
530 try!(write!(w, " {:2}: {:2$} - ", idx, addr, super::HEX_WIDTH));
531 match s.as_ref().and_then(|c| c.as_str()) {
532 Some(string) => try!(super::demangle(w, string)),
533 None => try!(write!(w, "<unknown>")),
535 w.write(['\n' as u8])
538 /// Unwind library interface used for backtraces
540 /// Note that the native libraries come from librustrt, not this
542 /// Note that dead code is allowed as here are just bindings
543 /// iOS doesn't use all of them it but adding more
544 /// platform-specific configs pollutes the code too much
545 #[allow(non_camel_case_types)]
546 #[allow(non_snake_case_functions)]
552 pub enum _Unwind_Reason_Code {
554 _URC_FOREIGN_EXCEPTION_CAUGHT = 1,
555 _URC_FATAL_PHASE2_ERROR = 2,
556 _URC_FATAL_PHASE1_ERROR = 3,
557 _URC_NORMAL_STOP = 4,
558 _URC_END_OF_STACK = 5,
559 _URC_HANDLER_FOUND = 6,
560 _URC_INSTALL_CONTEXT = 7,
561 _URC_CONTINUE_UNWIND = 8,
562 _URC_FAILURE = 9, // used only by ARM EABI
565 pub enum _Unwind_Context {}
567 pub type _Unwind_Trace_Fn =
568 extern fn(ctx: *mut _Unwind_Context,
569 arg: *mut libc::c_void) -> _Unwind_Reason_Code;
572 // No native _Unwind_Backtrace on iOS
573 #[cfg(not(target_os = "ios", target_arch = "arm"))]
574 pub fn _Unwind_Backtrace(trace: _Unwind_Trace_Fn,
575 trace_argument: *mut libc::c_void)
576 -> _Unwind_Reason_Code;
578 #[cfg(not(target_os = "android"),
579 not(target_os = "linux", target_arch = "arm"))]
580 pub fn _Unwind_GetIP(ctx: *mut _Unwind_Context) -> libc::uintptr_t;
581 #[cfg(not(target_os = "android"),
582 not(target_os = "linux", target_arch = "arm"))]
583 pub fn _Unwind_FindEnclosingFunction(pc: *mut libc::c_void)
584 -> *mut libc::c_void;
587 // On android, the function _Unwind_GetIP is a macro, and this is the
588 // expansion of the macro. This is all copy/pasted directly from the
589 // header file with the definition of _Unwind_GetIP.
590 #[cfg(target_os = "android")]
591 #[cfg(target_os = "linux", target_arch = "arm")]
592 pub unsafe fn _Unwind_GetIP(ctx: *mut _Unwind_Context) -> libc::uintptr_t {
594 enum _Unwind_VRS_Result {
596 _UVRSR_NOT_IMPLEMENTED = 1,
600 enum _Unwind_VRS_RegClass {
608 enum _Unwind_VRS_DataRepresentation {
617 type _Unwind_Word = libc::c_uint;
619 fn _Unwind_VRS_Get(ctx: *mut _Unwind_Context,
620 klass: _Unwind_VRS_RegClass,
622 repr: _Unwind_VRS_DataRepresentation,
623 data: *mut libc::c_void)
624 -> _Unwind_VRS_Result;
627 let mut val: _Unwind_Word = 0;
628 let ptr = &mut val as *mut _Unwind_Word;
629 let _ = _Unwind_VRS_Get(ctx, _UVRSC_CORE, 15, _UVRSD_UINT32,
630 ptr as *mut libc::c_void);
631 (val & !1) as libc::uintptr_t
634 // This function also doesn't exist on android or arm/linux, so make it
636 #[cfg(target_os = "android")]
637 #[cfg(target_os = "linux", target_arch = "arm")]
638 pub unsafe fn _Unwind_FindEnclosingFunction(pc: *mut libc::c_void)
646 /// As always, windows has something very different than unix, we mainly want
647 /// to avoid having to depend too much on libunwind for windows.
649 /// If you google around, you'll find a fair bit of references to built-in
650 /// functions to get backtraces on windows. It turns out that most of these are
651 /// in an external library called dbghelp. I was unable to find this library
652 /// via `-ldbghelp`, but it is apparently normal to do the `dlopen` equivalent
655 /// You'll also find that there's a function called CaptureStackBackTrace
656 /// mentioned frequently (which is also easy to use), but sadly I didn't have a
657 /// copy of that function in my mingw install (maybe it was broken?). Instead,
658 /// this takes the route of using StackWalk64 in order to walk the stack.
660 #[allow(dead_code, uppercase_variables)]
663 use core_collections::Collection;
665 use io::{IoResult, Writer};
669 use option::{Some, None};
671 use result::{Ok, Err};
672 use rt::mutex::{StaticNativeMutex, NATIVE_MUTEX_INIT};
673 use slice::ImmutableSlice;
675 use dynamic_lib::DynamicLibrary;
677 #[allow(non_snake_case_functions)]
679 fn GetCurrentProcess() -> libc::HANDLE;
680 fn GetCurrentThread() -> libc::HANDLE;
681 fn RtlCaptureContext(ctx: *mut arch::CONTEXT);
685 extern "system" fn(libc::HANDLE, u64, *mut u64,
686 *mut SYMBOL_INFO) -> libc::BOOL;
687 type SymInitializeFn =
688 extern "system" fn(libc::HANDLE, *mut libc::c_void,
689 libc::BOOL) -> libc::BOOL;
691 extern "system" fn(libc::HANDLE) -> libc::BOOL;
694 extern "system" fn(libc::DWORD, libc::HANDLE, libc::HANDLE,
695 *mut STACKFRAME64, *mut arch::CONTEXT,
696 *mut libc::c_void, *mut libc::c_void,
697 *mut libc::c_void, *mut libc::c_void) -> libc::BOOL;
699 static MAX_SYM_NAME: uint = 2000;
700 static IMAGE_FILE_MACHINE_I386: libc::DWORD = 0x014c;
701 static IMAGE_FILE_MACHINE_IA64: libc::DWORD = 0x0200;
702 static IMAGE_FILE_MACHINE_AMD64: libc::DWORD = 0x8664;
706 SizeOfStruct: libc::c_ulong,
707 TypeIndex: libc::c_ulong,
708 Reserved: [u64, ..2],
709 Index: libc::c_ulong,
712 Flags: libc::c_ulong,
715 Register: libc::c_ulong,
716 Scope: libc::c_ulong,
718 NameLen: libc::c_ulong,
719 MaxNameLen: libc::c_ulong,
720 // note that windows has this as 1, but it basically just means that
721 // the name is inline at the end of the struct. For us, we just bump
722 // the struct size up to MAX_SYM_NAME.
723 Name: [libc::c_char, ..MAX_SYM_NAME],
740 struct STACKFRAME64 {
742 AddrReturn: ADDRESS64,
743 AddrFrame: ADDRESS64,
744 AddrStack: ADDRESS64,
745 AddrBStore: ADDRESS64,
746 FuncTableEntry: *mut libc::c_void,
750 Reserved: [u64, ..3],
756 ThCallbackStack: libc::DWORD,
757 ThCallbackBStore: libc::DWORD,
758 NextCallback: libc::DWORD,
759 FramePointer: libc::DWORD,
761 KeUserCallbackDispatcher: u64,
762 SystemRangeStart: u64,
763 KiUserExceptionDispatcher: u64,
766 Reserved: [u64, ..5],
769 #[cfg(target_arch = "x86")]
773 static MAXIMUM_SUPPORTED_EXTENSION: uint = 512;
776 ContextFlags: libc::DWORD,
783 FloatSave: FLOATING_SAVE_AREA,
800 ExtendedRegisters: [u8, ..MAXIMUM_SUPPORTED_EXTENSION],
803 pub struct FLOATING_SAVE_AREA {
804 ControlWord: libc::DWORD,
805 StatusWord: libc::DWORD,
806 TagWord: libc::DWORD,
807 ErrorOffset: libc::DWORD,
808 ErrorSelector: libc::DWORD,
809 DataOffset: libc::DWORD,
810 DataSelector: libc::DWORD,
811 RegisterArea: [u8, ..80],
812 Cr0NpxState: libc::DWORD,
815 pub fn init_frame(frame: &mut super::STACKFRAME64,
816 ctx: &CONTEXT) -> libc::DWORD {
817 frame.AddrPC.Offset = ctx.Eip as u64;
818 frame.AddrPC.Mode = super::AddrModeFlat;
819 frame.AddrStack.Offset = ctx.Esp as u64;
820 frame.AddrStack.Mode = super::AddrModeFlat;
821 frame.AddrFrame.Offset = ctx.Ebp as u64;
822 frame.AddrFrame.Mode = super::AddrModeFlat;
823 super::IMAGE_FILE_MACHINE_I386
827 #[cfg(target_arch = "x86_64")]
829 use libc::{c_longlong, c_ulonglong};
830 use libc::types::os::arch::extra::{WORD, DWORD, DWORDLONG};
877 FltSave: FLOATING_SAVE_AREA,
879 VectorRegister: [M128A, .. 26],
880 VectorControl: DWORDLONG,
882 DebugControl: DWORDLONG,
883 LastBranchToRip: DWORDLONG,
884 LastBranchFromRip: DWORDLONG,
885 LastExceptionToRip: DWORDLONG,
886 LastExceptionFromRip: DWORDLONG,
894 pub struct FLOATING_SAVE_AREA {
895 _Dummy: [u8, ..512] // FIXME: Fill this out
898 pub fn init_frame(frame: &mut super::STACKFRAME64,
899 ctx: &CONTEXT) -> DWORD {
900 frame.AddrPC.Offset = ctx.Rip as u64;
901 frame.AddrPC.Mode = super::AddrModeFlat;
902 frame.AddrStack.Offset = ctx.Rsp as u64;
903 frame.AddrStack.Mode = super::AddrModeFlat;
904 frame.AddrFrame.Offset = ctx.Rbp as u64;
905 frame.AddrFrame.Mode = super::AddrModeFlat;
906 super::IMAGE_FILE_MACHINE_AMD64
911 handle: libc::HANDLE,
912 SymCleanup: SymCleanupFn,
915 impl Drop for Cleanup {
916 fn drop(&mut self) { (self.SymCleanup)(self.handle); }
919 pub fn write(w: &mut Writer) -> IoResult<()> {
920 // According to windows documentation, all dbghelp functions are
922 static mut LOCK: StaticNativeMutex = NATIVE_MUTEX_INIT;
923 let _g = unsafe { LOCK.lock() };
925 // Open up dbghelp.dll, we don't link to it explicitly because it can't
926 // always be found. Additionally, it's nice having fewer dependencies.
927 let path = Path::new("dbghelp.dll");
928 let lib = match DynamicLibrary::open(Some(&path)) {
930 Err(..) => return Ok(()),
933 macro_rules! sym( ($e:expr, $t:ident) => (unsafe {
934 match lib.symbol($e) {
935 Ok(f) => mem::transmute::<*mut u8, $t>(f),
936 Err(..) => return Ok(())
940 // Fetch the symbols necessary from dbghelp.dll
941 let SymFromAddr = sym!("SymFromAddr", SymFromAddrFn);
942 let SymInitialize = sym!("SymInitialize", SymInitializeFn);
943 let SymCleanup = sym!("SymCleanup", SymCleanupFn);
944 let StackWalk64 = sym!("StackWalk64", StackWalk64Fn);
946 // Allocate necessary structures for doing the stack walk
947 let process = unsafe { GetCurrentProcess() };
948 let thread = unsafe { GetCurrentThread() };
949 let mut context: arch::CONTEXT = unsafe { intrinsics::init() };
950 unsafe { RtlCaptureContext(&mut context); }
951 let mut frame: STACKFRAME64 = unsafe { intrinsics::init() };
952 let image = arch::init_frame(&mut frame, &context);
954 // Initialize this process's symbols
955 let ret = SymInitialize(process, 0 as *mut libc::c_void, libc::TRUE);
956 if ret != libc::TRUE { return Ok(()) }
957 let _c = Cleanup { handle: process, SymCleanup: SymCleanup };
959 // And now that we're done with all the setup, do the stack walking!
961 try!(write!(w, "stack backtrace:\n"));
962 while StackWalk64(image, process, thread, &mut frame, &mut context,
963 0 as *mut libc::c_void,
964 0 as *mut libc::c_void,
965 0 as *mut libc::c_void,
966 0 as *mut libc::c_void) == libc::TRUE{
967 let addr = frame.AddrPC.Offset;
968 if addr == frame.AddrReturn.Offset || addr == 0 ||
969 frame.AddrReturn.Offset == 0 { break }
972 try!(write!(w, " {:2}: {:#2$x}", i, addr, super::HEX_WIDTH));
973 let mut info: SYMBOL_INFO = unsafe { intrinsics::init() };
974 info.MaxNameLen = MAX_SYM_NAME as libc::c_ulong;
975 info.SizeOfStruct = (mem::size_of::<SYMBOL_INFO>() -
976 info.Name.len() + 1) as libc::c_ulong;
978 let mut displacement = 0u64;
979 let ret = SymFromAddr(process, addr as u64, &mut displacement,
982 if ret == libc::TRUE {
983 try!(write!(w, " - "));
984 let cstr = unsafe { CString::new(info.Name.as_ptr(), false) };
985 let bytes = cstr.as_bytes();
986 match cstr.as_str() {
987 Some(s) => try!(super::demangle(w, s)),
988 None => try!(w.write(bytes.slice_to(bytes.len() - 1))),
991 try!(w.write(['\n' as u8]));
1003 macro_rules! t( ($a:expr, $b:expr) => ({
1004 let mut m = MemWriter::new();
1005 super::demangle(&mut m, $a).unwrap();
1006 assert_eq!(String::from_utf8(m.unwrap()).unwrap(), $b.to_string());
1012 t!("_ZN4testE", "test");
1013 t!("_ZN4test", "_ZN4test");
1014 t!("_ZN4test1a2bcE", "test::a::bc");
1018 fn demangle_dollars() {
1019 t!("_ZN4$UP$E", "Box");
1020 t!("_ZN8$UP$testE", "Boxtest");
1021 t!("_ZN8$UP$test4foobE", "Boxtest::foob");
1022 t!("_ZN8$x20test4foobE", " test::foob");
1026 fn demangle_many_dollars() {
1027 t!("_ZN12test$x20test4foobE", "test test::foob");
1028 t!("_ZN12test$UP$test4foobE", "testBoxtest::foob");