1 //! A module to assist in managing dbghelp bindings on Windows
3 //! Backtraces on Windows (at least for MSVC) are largely powered through
4 //! `dbghelp.dll` and the various functions that it contains. These functions
5 //! are currently loaded *dynamically* rather than linking to `dbghelp.dll`
6 //! statically. This is currently done by the standard library (and is in theory
7 //! required there), but is an effort to help reduce the static dll dependencies
8 //! of a library since backtraces are typically pretty optional. That being
9 //! said, `dbghelp.dll` almost always successfully loads on Windows.
11 //! Note though that since we're loading all this support dynamically we can't
12 //! actually use the raw definitions in `winapi`, but rather we need to define
13 //! the function pointer types ourselves and use that. We don't really want to
14 //! be in the business of duplicating winapi, so we have a Cargo feature
15 //! `verify-winapi` which asserts that all bindings match those in winapi and
16 //! this feature is enabled on CI.
18 //! Finally, you'll note here that the dll for `dbghelp.dll` is never unloaded,
19 //! and that's currently intentional. The thinking is that we can globally cache
20 //! it and use it between calls to the API, avoiding expensive loads/unloads. If
21 //! this is a problem for leak detectors or something like that we can cross the
22 //! bridge when we get there.
24 #![allow(non_snake_case)]
26 use crate::windows
::*;
30 // Work around `SymGetOptions` and `SymSetOptions` not being present in winapi
31 // itself. Otherwise this is only used when we're double-checking types against
33 #[cfg(feature = "verify-winapi")]
35 use crate::windows
::*;
36 pub use winapi
::um
::dbghelp
::{
37 StackWalk64
, SymCleanup
, SymFromAddrW
, SymFunctionTableAccess64
, SymGetLineFromAddrW64
,
38 SymGetModuleBase64
, SymInitializeW
,
42 // Not defined in winapi yet
43 pub fn SymGetOptions() -> u32;
44 pub fn SymSetOptions(_
: u32);
46 // This is defined in winapi, but it's incorrect (FIXME winapi-rs#768)
51 StackFrame
: LPSTACKFRAME_EX
,
53 ReadMemoryRoutine
: PREAD_PROCESS_MEMORY_ROUTINE64
,
54 FunctionTableAccessRoutine
: PFUNCTION_TABLE_ACCESS_ROUTINE64
,
55 GetModuleBaseRoutine
: PGET_MODULE_BASE_ROUTINE64
,
56 TranslateAddress
: PTRANSLATE_ADDRESS_ROUTINE64
,
60 // Not defined in winapi yet
61 pub fn SymFromInlineContextW(
65 Displacement
: PDWORD64
,
66 Symbol
: PSYMBOL_INFOW
,
68 pub fn SymGetLineFromInlineContextW(
72 qwModuleBaseAddress
: DWORD64
,
73 pdwDisplacement
: PDWORD
,
74 Line
: PIMAGEHLP_LINEW64
,
78 pub fn assert_equal_types
<T
>(a
: T
, _b
: T
) -> T
{
83 // This macro is used to define a `Dbghelp` structure which internally contains
84 // all the function pointers that we might load.
85 macro_rules
! dbghelp
{
87 $
(fn $name
:ident($
($arg
:ident
: $argty
:ty
),*) -> $ret
: ty
;)*
90 /// The loaded DLL for `dbghelp.dll`
93 // Each function pointer for each function we might use
97 static mut DBGHELP
: Dbghelp
= Dbghelp
{
98 // Initially we haven't loaded the DLL
100 // Initiall all functions are set to zero to say they need to be
101 // dynamically loaded.
105 // Convenience typedef for each function type.
106 $
(pub type $name
= unsafe extern "system" fn($
($argty
),*) -> $ret
;)*
109 /// Attempts to open `dbghelp.dll`. Returns success if it works or
110 /// error if `LoadLibraryW` fails.
112 /// Panics if library is already loaded.
113 fn ensure_open(&mut self) -> Result
<(), ()> {
114 if !self.dll
.is_null() {
117 let lib
= b
"dbghelp.dll\0";
119 self.dll
= LoadLibraryA(lib
.as_ptr() as *const i8);
120 if self.dll
.is_null() {
128 // Function for each method we'd like to use. When called it will
129 // either read the cached function pointer or load it and return the
130 // loaded value. Loads are asserted to succeed.
131 $
(pub fn $
name(&mut self) -> Option
<$name
> {
134 let name
= concat
!(stringify
!($name
), "\0");
135 self.$name
= self.symbol(name
.as_bytes())?
;
137 let ret
= mem
::transmute
::<usize, $name
>(self.$name
);
138 #[cfg(feature = "verify-winapi")]
139 dbghelp
::assert_equal_types(ret
, dbghelp
::$name
);
144 fn symbol(&self, symbol
: &[u8]) -> Option
<usize> {
146 match GetProcAddress(self.dll
, symbol
.as_ptr() as *const _
) as usize {
154 // Convenience proxy to use the cleanup locks to reference dbghelp
158 $
(pub fn $
name(&self) -> $name
{
160 DBGHELP
.$
name().unwrap()
164 pub fn dbghelp(&self) -> *mut Dbghelp
{
174 const SYMOPT_DEFERRED_LOADS
: DWORD
= 0x00000004;
178 fn SymGetOptions() -> DWORD
;
179 fn SymSetOptions(options
: DWORD
) -> ();
185 fn SymCleanup(handle
: HANDLE
) -> BOOL
;
190 StackFrame
: LPSTACKFRAME64
,
191 ContextRecord
: PVOID
,
192 ReadMemoryRoutine
: PREAD_PROCESS_MEMORY_ROUTINE64
,
193 FunctionTableAccessRoutine
: PFUNCTION_TABLE_ACCESS_ROUTINE64
,
194 GetModuleBaseRoutine
: PGET_MODULE_BASE_ROUTINE64
,
195 TranslateAddress
: PTRANSLATE_ADDRESS_ROUTINE64
197 fn SymFunctionTableAccess64(
201 fn SymGetModuleBase64(
208 Displacement
: PDWORD64
,
209 Symbol
: PSYMBOL_INFOW
211 fn SymGetLineFromAddrW64(
214 pdwDisplacement
: PDWORD
,
215 Line
: PIMAGEHLP_LINEW64
221 StackFrame
: LPSTACKFRAME_EX
,
222 ContextRecord
: PVOID
,
223 ReadMemoryRoutine
: PREAD_PROCESS_MEMORY_ROUTINE64
,
224 FunctionTableAccessRoutine
: PFUNCTION_TABLE_ACCESS_ROUTINE64
,
225 GetModuleBaseRoutine
: PGET_MODULE_BASE_ROUTINE64
,
226 TranslateAddress
: PTRANSLATE_ADDRESS_ROUTINE64
,
229 fn SymFromInlineContextW(
232 InlineContext
: ULONG
,
233 Displacement
: PDWORD64
,
234 Symbol
: PSYMBOL_INFOW
236 fn SymGetLineFromInlineContextW(
239 InlineContext
: ULONG
,
240 qwModuleBaseAddress
: DWORD64
,
241 pdwDisplacement
: PDWORD
,
242 Line
: PIMAGEHLP_LINEW64
251 /// Initialize all support necessary to access `dbghelp` API functions from this
254 /// Note that this function is **safe**, it internally has its own
255 /// synchronization. Also note that it is safe to call this function multiple
256 /// times recursively.
257 pub fn init() -> Result
<Init
, ()> {
258 use core
::sync
::atomic
::{AtomicUsize, Ordering::SeqCst}
;
261 // First thing we need to do is to synchronize this function. This can
262 // be called concurrently from other threads or recursively within one
263 // thread. Note that it's trickier than that though because what we're
264 // using here, `dbghelp`, *also* needs to be synchronized with all other
265 // callers to `dbghelp` in this process.
267 // Typically there aren't really that many calls to `dbghelp` within the
268 // same process and we can probably safely assume that we're the only
269 // ones accessing it. There is, however, one primary other user we have
270 // to worry about which is ironically ourselves, but in the standard
271 // library. The Rust standard library depends on this crate for
272 // backtrace support, and this crate also exists on crates.io. This
273 // means that if the standard library is printing a panic backtrace it
274 // may race with this crate coming from crates.io, causing segfaults.
276 // To help solve this synchronization problem we employ a
277 // Windows-specific trick here (it is, after all, a Windows-specific
278 // restriction about synchronization). We create a *session-local* named
279 // mutex to protect this call. The intention here is that the standard
280 // library and this crate don't have to share Rust-level APIs to
281 // synchronize here but can instead work behind the scenes to make sure
282 // they're synchronizing with one another. That way when this function
283 // is called through the standard library or through crates.io we can be
284 // sure that the same mutex is being acquired.
286 // So all of that is to say that the first thing we do here is we
287 // atomically create a `HANDLE` which is a named mutex on Windows. We
288 // synchronize a bit with other threads sharing this function
289 // specifically and ensure that only one handle is created per instance
290 // of this function. Note that the handle is never closed once it's
291 // stored in the global.
293 // After we've actually go the lock we simply acquire it, and our `Init`
294 // handle we hand out will be responsible for dropping it eventually.
295 static LOCK
: AtomicUsize
= AtomicUsize
::new(0);
296 let mut lock
= LOCK
.load(SeqCst
);
301 "Local\\RustBacktraceMutex\0".as_ptr() as _
,
306 if let Err(other
) = LOCK
.compare_exchange(0, lock
, SeqCst
, SeqCst
) {
307 debug_assert
!(other
!= 0);
308 CloseHandle(lock
as HANDLE
);
312 debug_assert
!(lock
!= 0);
313 let lock
= lock
as HANDLE
;
314 let r
= WaitForSingleObjectEx(lock
, INFINITE
, FALSE
);
315 debug_assert_eq
!(r
, 0);
316 let ret
= Init { lock }
;
318 // Ok, phew! Now that we're all safely synchronized, let's actually
319 // start processing everything. First up we need to ensure that
320 // `dbghelp.dll` is actually loaded in this process. We do this
321 // dynamically to avoid a static dependency. This has historically been
322 // done to work around weird linking issues and is intended at making
323 // binaries a bit more portable since this is largely just a debugging
326 // Once we've opened `dbghelp.dll` we need to call some initialization
327 // functions in it, and that's detailed more below. We only do this
328 // once, though, so we've got a global boolean indicating whether we're
330 DBGHELP
.ensure_open()?
;
332 static mut INITIALIZED
: bool
= false;
337 let orig
= DBGHELP
.SymGetOptions().unwrap()();
339 // Ensure that the `SYMOPT_DEFERRED_LOADS` flag is set, because
340 // according to MSVC's own docs about this: "This is the fastest, most
341 // efficient way to use the symbol handler.", so let's do that!
342 DBGHELP
.SymSetOptions().unwrap()(orig
| SYMOPT_DEFERRED_LOADS
);
344 // Actually initialize symbols with MSVC. Note that this can fail, but we
345 // ignore it. There's not a ton of prior art for this per se, but LLVM
346 // internally seems to ignore the return value here and one of the
347 // sanitizer libraries in LLVM prints a scary warning if this fails but
348 // basically ignores it in the long run.
350 // One case this comes up a lot for Rust is that the standard library and
351 // this crate on crates.io both want to compete for `SymInitializeW`. The
352 // standard library historically wanted to initialize then cleanup most of
353 // the time, but now that it's using this crate it means that someone will
354 // get to initialization first and the other will pick up that
356 DBGHELP
.SymInitializeW().unwrap()(GetCurrentProcess(), ptr
::null_mut(), TRUE
);
365 let r
= ReleaseMutex(self.lock
);
366 debug_assert
!(r
!= 0);