]> git.lizzy.rs Git - rust.git/blob - src/libstd/sys/windows/backtrace.rs
80ff0cb0453ad1570c6cc14f275daa540f57edb4
[rust.git] / src / libstd / sys / windows / 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 //! As always, windows has something very different than unix, we mainly want
12 //! to avoid having to depend too much on libunwind for windows.
13 //!
14 //! If you google around, you'll find a fair bit of references to built-in
15 //! functions to get backtraces on windows. It turns out that most of these are
16 //! in an external library called dbghelp. I was unable to find this library
17 //! via `-ldbghelp`, but it is apparently normal to do the `dlopen` equivalent
18 //! of it.
19 //!
20 //! You'll also find that there's a function called CaptureStackBackTrace
21 //! mentioned frequently (which is also easy to use), but sadly I didn't have a
22 //! copy of that function in my mingw install (maybe it was broken?). Instead,
23 //! this takes the route of using StackWalk64 in order to walk the stack.
24
25 #![allow(deprecated)] // dynamic_lib
26
27 use io::prelude::*;
28
29 use dynamic_lib::DynamicLibrary;
30 use io;
31 use libc::c_void;
32 use mem;
33 use path::Path;
34 use ptr;
35 use sync::StaticMutex;
36 use sys::c;
37
38 macro_rules! sym{ ($lib:expr, $e:expr, $t:ident) => (unsafe {
39     let lib = $lib;
40     match lib.symbol($e) {
41         Ok(f) => $crate::mem::transmute::<*mut u8, $t>(f),
42         Err(..) => return Ok(())
43     }
44 }) }
45
46 #[cfg(target_env = "msvc")]
47 #[path = "printing/msvc.rs"]
48 mod printing;
49
50 #[cfg(target_env = "gnu")]
51 #[path = "printing/gnu.rs"]
52 mod printing;
53
54 type SymInitializeFn =
55     extern "system" fn(c::HANDLE, *mut c_void,
56                        c::BOOL) -> c::BOOL;
57 type SymCleanupFn =
58     extern "system" fn(c::HANDLE) -> c::BOOL;
59
60 type StackWalk64Fn =
61     extern "system" fn(c::DWORD, c::HANDLE, c::HANDLE,
62                        *mut c::STACKFRAME64, *mut c::CONTEXT,
63                        *mut c_void, *mut c_void,
64                        *mut c_void, *mut c_void) -> c::BOOL;
65
66 #[cfg(target_arch = "x86")]
67 pub fn init_frame(frame: &mut c::STACKFRAME64,
68                   ctx: &c::CONTEXT) -> c::DWORD {
69     frame.AddrPC.Offset = ctx.Eip as u64;
70     frame.AddrPC.Mode = c::ADDRESS_MODE::AddrModeFlat;
71     frame.AddrStack.Offset = ctx.Esp as u64;
72     frame.AddrStack.Mode = c::ADDRESS_MODE::AddrModeFlat;
73     frame.AddrFrame.Offset = ctx.Ebp as u64;
74     frame.AddrFrame.Mode = c::ADDRESS_MODE::AddrModeFlat;
75     c::IMAGE_FILE_MACHINE_I386
76 }
77
78 #[cfg(target_arch = "x86_64")]
79 pub fn init_frame(frame: &mut c::STACKFRAME64,
80                   ctx: &c::CONTEXT) -> c::DWORD {
81     frame.AddrPC.Offset = ctx.Rip as u64;
82     frame.AddrPC.Mode = c::ADDRESS_MODE::AddrModeFlat;
83     frame.AddrStack.Offset = ctx.Rsp as u64;
84     frame.AddrStack.Mode = c::ADDRESS_MODE::AddrModeFlat;
85     frame.AddrFrame.Offset = ctx.Rbp as u64;
86     frame.AddrFrame.Mode = c::ADDRESS_MODE::AddrModeFlat;
87     c::IMAGE_FILE_MACHINE_AMD64
88 }
89
90 struct Cleanup {
91     handle: c::HANDLE,
92     SymCleanup: SymCleanupFn,
93 }
94
95 impl Drop for Cleanup {
96     fn drop(&mut self) { (self.SymCleanup)(self.handle); }
97 }
98
99 pub fn write(w: &mut Write) -> io::Result<()> {
100     // According to windows documentation, all dbghelp functions are
101     // single-threaded.
102     static LOCK: StaticMutex = StaticMutex::new();
103     let _g = LOCK.lock();
104
105     // Open up dbghelp.dll, we don't link to it explicitly because it can't
106     // always be found. Additionally, it's nice having fewer dependencies.
107     let path = Path::new("dbghelp.dll");
108     let dbghelp = match DynamicLibrary::open(Some(&path)) {
109         Ok(lib) => lib,
110         Err(..) => return Ok(()),
111     };
112
113     // Fetch the symbols necessary from dbghelp.dll
114     let SymInitialize = sym!(&dbghelp, "SymInitialize", SymInitializeFn);
115     let SymCleanup = sym!(&dbghelp, "SymCleanup", SymCleanupFn);
116     let StackWalk64 = sym!(&dbghelp, "StackWalk64", StackWalk64Fn);
117
118     // Allocate necessary structures for doing the stack walk
119     let process = unsafe { c::GetCurrentProcess() };
120     let thread = unsafe { c::GetCurrentThread() };
121     let mut context: c::CONTEXT = unsafe { mem::zeroed() };
122     unsafe { c::RtlCaptureContext(&mut context); }
123     let mut frame: c::STACKFRAME64 = unsafe { mem::zeroed() };
124     let image = init_frame(&mut frame, &context);
125
126     // Initialize this process's symbols
127     let ret = SymInitialize(process, ptr::null_mut(), c::TRUE);
128     if ret != c::TRUE { return Ok(()) }
129     let _c = Cleanup { handle: process, SymCleanup: SymCleanup };
130
131     // And now that we're done with all the setup, do the stack walking!
132     // Start from -1 to avoid printing this stack frame, which will
133     // always be exactly the same.
134     let mut i = -1;
135     try!(write!(w, "stack backtrace:\n"));
136     while StackWalk64(image, process, thread, &mut frame, &mut context,
137                       ptr::null_mut(),
138                       ptr::null_mut(),
139                       ptr::null_mut(),
140                       ptr::null_mut()) == c::TRUE {
141         let addr = frame.AddrPC.Offset;
142         if addr == frame.AddrReturn.Offset || addr == 0 ||
143            frame.AddrReturn.Offset == 0 { break }
144
145         i += 1;
146
147         if i >= 0 {
148             try!(printing::print(w, i, addr-1, &dbghelp, process));
149         }
150     }
151
152     Ok(())
153 }