1 use crate::error::Error;
6 use crate::sys_common::backtrace::Frame;
10 pub struct BacktraceContext;
14 frames: &'a mut [Frame],
18 struct UnwindError(uw::_Unwind_Reason_Code);
20 impl Error for UnwindError {
21 fn description(&self) -> &'static str {
22 "unexpected return value while unwinding"
26 impl fmt::Display for UnwindError {
27 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
28 write!(f, "{}: {:?}", self.description(), self.0)
32 #[inline(never)] // if we know this is a function call, we can skip it when
34 pub fn unwind_backtrace(frames: &mut [Frame]) -> io::Result<(usize, BacktraceContext)> {
35 let mut cx = Context { idx: 0, frames };
37 unsafe { uw::_Unwind_Backtrace(trace_fn, &mut cx as *mut Context as *mut libc::c_void) };
38 // See libunwind:src/unwind/Backtrace.c for the return values.
39 // No, there is no doc.
41 // These return codes seem to be benign and need to be ignored for backtraces
42 // to show up properly on all tested platforms.
43 uw::_URC_END_OF_STACK | uw::_URC_FATAL_PHASE1_ERROR | uw::_URC_FAILURE => {
44 Ok((cx.idx, BacktraceContext))
46 _ => Err(io::Error::new(
48 UnwindError(result_unwind),
53 extern "C" fn trace_fn(
54 ctx: *mut uw::_Unwind_Context,
55 arg: *mut libc::c_void,
56 ) -> uw::_Unwind_Reason_Code {
57 let cx = unsafe { &mut *(arg as *mut Context) };
58 if cx.idx >= cx.frames.len() {
59 return uw::_URC_NORMAL_STOP;
62 let mut ip_before_insn = 0;
63 let mut ip = unsafe { uw::_Unwind_GetIPInfo(ctx, &mut ip_before_insn) as *mut libc::c_void };
64 if !ip.is_null() && ip_before_insn == 0 {
65 // this is a non-signaling frame, so `ip` refers to the address
66 // after the calling instruction. account for that.
67 ip = (ip as usize - 1) as *mut _;
70 let symaddr = unsafe { uw::_Unwind_FindEnclosingFunction(ip) };
71 cx.frames[cx.idx] = Frame {
72 symbol_addr: symaddr as *mut u8,
73 exact_position: ip as *mut u8,
81 pub fn foreach_symbol_fileline<F>(_: Frame, _: F, _: &BacktraceContext) -> io::Result<bool>
83 F: FnMut(&[u8], u32) -> io::Result<()>,
85 // No way to obtain this information on CloudABI.
89 pub fn resolve_symname<F>(frame: Frame, callback: F, _: &BacktraceContext) -> io::Result<()>
91 F: FnOnce(Option<&str>) -> io::Result<()>,
94 let mut info: Dl_info = intrinsics::init();
96 if dladdr(frame.exact_position as *mut _, &mut info) == 0 || info.dli_sname.is_null() {
99 CStr::from_ptr(info.dli_sname).to_str().ok()
107 dli_fname: *const libc::c_char,
108 dli_fbase: *mut libc::c_void,
109 dli_sname: *const libc::c_char,
110 dli_saddr: *mut libc::c_void,
114 fn dladdr(addr: *const libc::c_void, info: *mut Dl_info) -> libc::c_int;