1 //! Implementation of panics backed by libgcc/libunwind (in some form).
3 //! For background on exception handling and stack unwinding please see
4 //! "Exception Handling in LLVM" (llvm.org/docs/ExceptionHandling.html) and
5 //! documents linked from it.
6 //! These are also good reads:
7 //! * <https://itanium-cxx-abi.github.io/cxx-abi/abi-eh.html>
8 //! * <https://monoinfinito.wordpress.com/series/exception-handling-in-c/>
9 //! * <https://www.airs.com/blog/index.php?s=exception+frames>
11 //! ## A brief summary
13 //! Exception handling happens in two phases: a search phase and a cleanup
16 //! In both phases the unwinder walks stack frames from top to bottom using
17 //! information from the stack frame unwind sections of the current process's
18 //! modules ("module" here refers to an OS module, i.e., an executable or a
21 //! For each stack frame, it invokes the associated "personality routine", whose
22 //! address is also stored in the unwind info section.
24 //! In the search phase, the job of a personality routine is to examine
25 //! exception object being thrown, and to decide whether it should be caught at
26 //! that stack frame. Once the handler frame has been identified, cleanup phase
29 //! In the cleanup phase, the unwinder invokes each personality routine again.
30 //! This time it decides which (if any) cleanup code needs to be run for
31 //! the current stack frame. If so, the control is transferred to a special
32 //! branch in the function body, the "landing pad", which invokes destructors,
33 //! frees memory, etc. At the end of the landing pad, control is transferred
34 //! back to the unwinder and unwinding resumes.
36 //! Once stack has been unwound down to the handler frame level, unwinding stops
37 //! and the last personality routine transfers control to the catch block.
39 use super::dwarf::eh::{self, EHAction, EHContext};
40 use libc::{c_int, uintptr_t};
43 // Register ids were lifted from LLVM's TargetLowering::getExceptionPointerRegister()
44 // and TargetLowering::getExceptionSelectorRegister() for each architecture,
45 // then mapped to DWARF register numbers via register definition tables
46 // (typically <arch>RegisterInfo.td, search for "DwarfRegNum").
47 // See also https://llvm.org/docs/WritingAnLLVMBackend.html#defining-a-register.
49 #[cfg(target_arch = "x86")]
50 const UNWIND_DATA_REG: (i32, i32) = (0, 2); // EAX, EDX
52 #[cfg(target_arch = "x86_64")]
53 const UNWIND_DATA_REG: (i32, i32) = (0, 1); // RAX, RDX
55 #[cfg(any(target_arch = "arm", target_arch = "aarch64"))]
56 const UNWIND_DATA_REG: (i32, i32) = (0, 1); // R0, R1 / X0, X1
58 #[cfg(target_arch = "m68k")]
59 const UNWIND_DATA_REG: (i32, i32) = (0, 1); // D0, D1
61 #[cfg(any(target_arch = "mips", target_arch = "mips64"))]
62 const UNWIND_DATA_REG: (i32, i32) = (4, 5); // A0, A1
64 #[cfg(any(target_arch = "powerpc", target_arch = "powerpc64"))]
65 const UNWIND_DATA_REG: (i32, i32) = (3, 4); // R3, R4 / X3, X4
67 #[cfg(target_arch = "s390x")]
68 const UNWIND_DATA_REG: (i32, i32) = (6, 7); // R6, R7
70 #[cfg(any(target_arch = "sparc", target_arch = "sparc64"))]
71 const UNWIND_DATA_REG: (i32, i32) = (24, 25); // I0, I1
73 #[cfg(target_arch = "hexagon")]
74 const UNWIND_DATA_REG: (i32, i32) = (0, 1); // R0, R1
76 #[cfg(any(target_arch = "riscv64", target_arch = "riscv32"))]
77 const UNWIND_DATA_REG: (i32, i32) = (10, 11); // x10, x11
79 // The following code is based on GCC's C and C++ personality routines. For reference, see:
80 // https://github.com/gcc-mirror/gcc/blob/master/libstdc++-v3/libsupc++/eh_personality.cc
81 // https://github.com/gcc-mirror/gcc/blob/trunk/libgcc/unwind-c.c
84 if #[cfg(all(target_arch = "arm", not(target_os = "ios"), not(target_os = "watchos"), not(target_os = "netbsd")))] {
85 // ARM EHABI personality routine.
86 // https://infocenter.arm.com/help/topic/com.arm.doc.ihi0038b/IHI0038B_ehabi.pdf
88 // iOS uses the default routine instead since it uses SjLj unwinding.
89 #[lang = "eh_personality"]
90 unsafe extern "C" fn rust_eh_personality(
91 state: uw::_Unwind_State,
92 exception_object: *mut uw::_Unwind_Exception,
93 context: *mut uw::_Unwind_Context,
94 ) -> uw::_Unwind_Reason_Code {
95 let state = state as c_int;
96 let action = state & uw::_US_ACTION_MASK as c_int;
97 let search_phase = if action == uw::_US_VIRTUAL_UNWIND_FRAME as c_int {
98 // Backtraces on ARM will call the personality routine with
99 // state == _US_VIRTUAL_UNWIND_FRAME | _US_FORCE_UNWIND. In those cases
100 // we want to continue unwinding the stack, otherwise all our backtraces
101 // would end at __rust_try
102 if state & uw::_US_FORCE_UNWIND as c_int != 0 {
103 return continue_unwind(exception_object, context);
106 } else if action == uw::_US_UNWIND_FRAME_STARTING as c_int {
108 } else if action == uw::_US_UNWIND_FRAME_RESUME as c_int {
109 return continue_unwind(exception_object, context);
111 return uw::_URC_FAILURE;
114 // The DWARF unwinder assumes that _Unwind_Context holds things like the function
115 // and LSDA pointers, however ARM EHABI places them into the exception object.
116 // To preserve signatures of functions like _Unwind_GetLanguageSpecificData(), which
117 // take only the context pointer, GCC personality routines stash a pointer to
118 // exception_object in the context, using location reserved for ARM's
119 // "scratch register" (r12).
120 uw::_Unwind_SetGR(context, uw::UNWIND_POINTER_REG, exception_object as uw::_Unwind_Ptr);
121 // ...A more principled approach would be to provide the full definition of ARM's
122 // _Unwind_Context in our libunwind bindings and fetch the required data from there
123 // directly, bypassing DWARF compatibility functions.
125 let eh_action = match find_eh_action(context) {
126 Ok(action) => action,
127 Err(_) => return uw::_URC_FAILURE,
131 EHAction::None | EHAction::Cleanup(_) => {
132 return continue_unwind(exception_object, context);
134 EHAction::Catch(_) => {
135 // EHABI requires the personality routine to update the
136 // SP value in the barrier cache of the exception object.
137 (*exception_object).private[5] =
138 uw::_Unwind_GetGR(context, uw::UNWIND_SP_REG);
139 return uw::_URC_HANDLER_FOUND;
141 EHAction::Terminate => return uw::_URC_FAILURE,
145 EHAction::None => return continue_unwind(exception_object, context),
146 EHAction::Cleanup(lpad) | EHAction::Catch(lpad) => {
150 exception_object as uintptr_t,
152 uw::_Unwind_SetGR(context, UNWIND_DATA_REG.1, 0);
153 uw::_Unwind_SetIP(context, lpad);
154 return uw::_URC_INSTALL_CONTEXT;
156 EHAction::Terminate => return uw::_URC_FAILURE,
160 // On ARM EHABI the personality routine is responsible for actually
161 // unwinding a single stack frame before returning (ARM EHABI Sec. 6.1).
162 unsafe fn continue_unwind(
163 exception_object: *mut uw::_Unwind_Exception,
164 context: *mut uw::_Unwind_Context,
165 ) -> uw::_Unwind_Reason_Code {
166 if __gnu_unwind_frame(exception_object, context) == uw::_URC_NO_REASON {
167 uw::_URC_CONTINUE_UNWIND
174 fn __gnu_unwind_frame(
175 exception_object: *mut uw::_Unwind_Exception,
176 context: *mut uw::_Unwind_Context,
177 ) -> uw::_Unwind_Reason_Code;
181 // Default personality routine, which is used directly on most targets
182 // and indirectly on Windows x86_64 via SEH.
183 unsafe extern "C" fn rust_eh_personality_impl(
185 actions: uw::_Unwind_Action,
186 _exception_class: uw::_Unwind_Exception_Class,
187 exception_object: *mut uw::_Unwind_Exception,
188 context: *mut uw::_Unwind_Context,
189 ) -> uw::_Unwind_Reason_Code {
191 return uw::_URC_FATAL_PHASE1_ERROR;
193 let eh_action = match find_eh_action(context) {
194 Ok(action) => action,
195 Err(_) => return uw::_URC_FATAL_PHASE1_ERROR,
197 if actions as i32 & uw::_UA_SEARCH_PHASE as i32 != 0 {
199 EHAction::None | EHAction::Cleanup(_) => uw::_URC_CONTINUE_UNWIND,
200 EHAction::Catch(_) => uw::_URC_HANDLER_FOUND,
201 EHAction::Terminate => uw::_URC_FATAL_PHASE1_ERROR,
205 EHAction::None => uw::_URC_CONTINUE_UNWIND,
206 EHAction::Cleanup(lpad) | EHAction::Catch(lpad) => {
210 exception_object as uintptr_t,
212 uw::_Unwind_SetGR(context, UNWIND_DATA_REG.1, 0);
213 uw::_Unwind_SetIP(context, lpad);
214 uw::_URC_INSTALL_CONTEXT
216 EHAction::Terminate => uw::_URC_FATAL_PHASE2_ERROR,
222 if #[cfg(all(windows, target_arch = "x86_64", target_env = "gnu"))] {
223 // On x86_64 MinGW targets, the unwinding mechanism is SEH however the unwind
224 // handler data (aka LSDA) uses GCC-compatible encoding.
225 #[lang = "eh_personality"]
226 #[allow(nonstandard_style)]
227 unsafe extern "C" fn rust_eh_personality(
228 exceptionRecord: *mut uw::EXCEPTION_RECORD,
229 establisherFrame: uw::LPVOID,
230 contextRecord: *mut uw::CONTEXT,
231 dispatcherContext: *mut uw::DISPATCHER_CONTEXT,
232 ) -> uw::EXCEPTION_DISPOSITION {
233 uw::_GCC_specific_handler(
238 rust_eh_personality_impl,
242 // The personality routine for most of our targets.
243 #[lang = "eh_personality"]
244 unsafe extern "C" fn rust_eh_personality(
246 actions: uw::_Unwind_Action,
247 exception_class: uw::_Unwind_Exception_Class,
248 exception_object: *mut uw::_Unwind_Exception,
249 context: *mut uw::_Unwind_Context,
250 ) -> uw::_Unwind_Reason_Code {
251 rust_eh_personality_impl(
264 unsafe fn find_eh_action(context: *mut uw::_Unwind_Context) -> Result<EHAction, ()> {
265 let lsda = uw::_Unwind_GetLanguageSpecificData(context) as *const u8;
266 let mut ip_before_instr: c_int = 0;
267 let ip = uw::_Unwind_GetIPInfo(context, &mut ip_before_instr);
268 let eh_context = EHContext {
269 // The return address points 1 byte past the call instruction,
270 // which could be in the next IP range in LSDA range table.
272 // `ip = -1` has special meaning, so use wrapping sub to allow for that
273 ip: if ip_before_instr != 0 { ip } else { ip.wrapping_sub(1) },
274 func_start: uw::_Unwind_GetRegionStart(context),
275 get_text_start: &|| uw::_Unwind_GetTextRelBase(context),
276 get_data_start: &|| uw::_Unwind_GetDataRelBase(context),
278 eh::find_eh_action(lsda, &eh_context)