2 use crate::error::Error;
4 use crate::sys_common::backtrace::Frame;
5 use crate::sys::sgx::abi::mem::image_base;
9 pub struct BacktraceContext;
13 frames: &'a mut [Frame],
17 struct UnwindError(uw::_Unwind_Reason_Code);
19 impl Error for UnwindError {
20 fn description(&self) -> &'static str {
21 "unexpected return value while unwinding"
25 impl fmt::Display for UnwindError {
26 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
27 write!(f, "{}: {:?}", self.description(), self.0)
31 #[inline(never)] // this function call can be skipped it when tracing.
32 pub fn unwind_backtrace(frames: &mut [Frame]) -> io::Result<(usize, BacktraceContext)> {
33 let mut cx = Context { idx: 0, frames };
35 unsafe { uw::_Unwind_Backtrace(trace_fn, &mut cx as *mut Context as *mut libc::c_void) };
36 // See libunwind:src/unwind/Backtrace.c for the return values.
37 // No, there is no doc.
38 let res = match result_unwind {
39 // These return codes seem to be benign and need to be ignored for backtraces
40 // to show up properly on all tested platforms.
41 uw::_URC_END_OF_STACK | uw::_URC_FATAL_PHASE1_ERROR | uw::_URC_FAILURE => {
42 Ok((cx.idx, BacktraceContext))
44 _ => Err(io::Error::new(
46 UnwindError(result_unwind),
52 extern "C" fn trace_fn(
53 ctx: *mut uw::_Unwind_Context,
54 arg: *mut libc::c_void,
55 ) -> uw::_Unwind_Reason_Code {
56 let cx = unsafe { &mut *(arg as *mut Context) };
57 if cx.idx >= cx.frames.len() {
58 return uw::_URC_NORMAL_STOP;
61 let mut ip_before_insn = 0;
62 let mut ip = unsafe { uw::_Unwind_GetIPInfo(ctx, &mut ip_before_insn) as *mut libc::c_void };
63 if !ip.is_null() && ip_before_insn == 0 {
64 // this is a non-signaling frame, so `ip` refers to the address
65 // after the calling instruction. account for that.
66 ip = (ip as usize - 1) as *mut _;
69 let symaddr = unsafe { uw::_Unwind_FindEnclosingFunction(ip) };
70 cx.frames[cx.idx] = Frame {
71 symbol_addr: symaddr as *mut u8,
72 exact_position: ip as *mut u8,
80 // To reduce TCB size in Sgx enclave, we do not want to implement resolve_symname functionality.
81 // Rather, we print the offset of the address here, which could be later mapped to correct function.
82 pub fn resolve_symname<F>(frame: Frame,
84 _: &BacktraceContext) -> io::Result<()>
85 where F: FnOnce(Option<&str>) -> io::Result<()>
87 callback(Some(&format!("0x{:x}",
88 (frame.symbol_addr.wrapping_offset_from(image_base() as _)))))
91 pub fn foreach_symbol_fileline<F>(_: Frame,
93 _: &BacktraceContext) -> io::Result<bool>
94 where F: FnMut(&[u8], u32) -> io::Result<()>