• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 //! Implementation of panics backed by libgcc/libunwind (in some form).
2 //!
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>
10 //!
11 //! ## A brief summary
12 //!
13 //! Exception handling happens in two phases: a search phase and a cleanup
14 //! phase.
15 //!
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
19 //! dynamic library).
20 //!
21 //! For each stack frame, it invokes the associated "personality routine", whose
22 //! address is also stored in the unwind info section.
23 //!
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
27 //! begins.
28 //!
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.
35 //!
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.
38 
39 use super::dwarf::eh::{self, EHAction, EHContext};
40 use crate::ffi::c_int;
41 use libc::uintptr_t;
42 use unwind as uw;
43 
44 // Register ids were lifted from LLVM's TargetLowering::getExceptionPointerRegister()
45 // and TargetLowering::getExceptionSelectorRegister() for each architecture,
46 // then mapped to DWARF register numbers via register definition tables
47 // (typically <arch>RegisterInfo.td, search for "DwarfRegNum").
48 // See also https://llvm.org/docs/WritingAnLLVMBackend.html#defining-a-register.
49 
50 #[cfg(target_arch = "x86")]
51 const UNWIND_DATA_REG: (i32, i32) = (0, 2); // EAX, EDX
52 
53 #[cfg(target_arch = "x86_64")]
54 const UNWIND_DATA_REG: (i32, i32) = (0, 1); // RAX, RDX
55 
56 #[cfg(any(target_arch = "arm", target_arch = "aarch64"))]
57 const UNWIND_DATA_REG: (i32, i32) = (0, 1); // R0, R1 / X0, X1
58 
59 #[cfg(target_arch = "m68k")]
60 const UNWIND_DATA_REG: (i32, i32) = (0, 1); // D0, D1
61 
62 #[cfg(any(target_arch = "mips", target_arch = "mips64"))]
63 const UNWIND_DATA_REG: (i32, i32) = (4, 5); // A0, A1
64 
65 #[cfg(any(target_arch = "powerpc", target_arch = "powerpc64"))]
66 const UNWIND_DATA_REG: (i32, i32) = (3, 4); // R3, R4 / X3, X4
67 
68 #[cfg(target_arch = "s390x")]
69 const UNWIND_DATA_REG: (i32, i32) = (6, 7); // R6, R7
70 
71 #[cfg(any(target_arch = "sparc", target_arch = "sparc64"))]
72 const UNWIND_DATA_REG: (i32, i32) = (24, 25); // I0, I1
73 
74 #[cfg(target_arch = "hexagon")]
75 const UNWIND_DATA_REG: (i32, i32) = (0, 1); // R0, R1
76 
77 #[cfg(any(target_arch = "riscv64", target_arch = "riscv32"))]
78 const UNWIND_DATA_REG: (i32, i32) = (10, 11); // x10, x11
79 
80 #[cfg(target_arch = "loongarch64")]
81 const UNWIND_DATA_REG: (i32, i32) = (4, 5); // a0, a1
82 
83 // The following code is based on GCC's C and C++ personality routines.  For reference, see:
84 // https://github.com/gcc-mirror/gcc/blob/master/libstdc++-v3/libsupc++/eh_personality.cc
85 // https://github.com/gcc-mirror/gcc/blob/trunk/libgcc/unwind-c.c
86 
87 cfg_if::cfg_if! {
88     if #[cfg(all(target_arch = "arm", not(target_os = "ios"), not(target_os = "tvos"), not(target_os = "watchos"), not(target_os = "netbsd")))] {
89         // ARM EHABI personality routine.
90         // https://infocenter.arm.com/help/topic/com.arm.doc.ihi0038b/IHI0038B_ehabi.pdf
91         //
92         // iOS uses the default routine instead since it uses SjLj unwinding.
93         #[lang = "eh_personality"]
94         unsafe extern "C" fn rust_eh_personality(
95             state: uw::_Unwind_State,
96             exception_object: *mut uw::_Unwind_Exception,
97             context: *mut uw::_Unwind_Context,
98         ) -> uw::_Unwind_Reason_Code {
99             let state = state as c_int;
100             let action = state & uw::_US_ACTION_MASK as c_int;
101             let search_phase = if action == uw::_US_VIRTUAL_UNWIND_FRAME as c_int {
102                 // Backtraces on ARM will call the personality routine with
103                 // state == _US_VIRTUAL_UNWIND_FRAME | _US_FORCE_UNWIND. In those cases
104                 // we want to continue unwinding the stack, otherwise all our backtraces
105                 // would end at __rust_try
106                 if state & uw::_US_FORCE_UNWIND as c_int != 0 {
107                     return continue_unwind(exception_object, context);
108                 }
109                 true
110             } else if action == uw::_US_UNWIND_FRAME_STARTING as c_int {
111                 false
112             } else if action == uw::_US_UNWIND_FRAME_RESUME as c_int {
113                 return continue_unwind(exception_object, context);
114             } else {
115                 return uw::_URC_FAILURE;
116             };
117 
118             // The DWARF unwinder assumes that _Unwind_Context holds things like the function
119             // and LSDA pointers, however ARM EHABI places them into the exception object.
120             // To preserve signatures of functions like _Unwind_GetLanguageSpecificData(), which
121             // take only the context pointer, GCC personality routines stash a pointer to
122             // exception_object in the context, using location reserved for ARM's
123             // "scratch register" (r12).
124             uw::_Unwind_SetGR(context, uw::UNWIND_POINTER_REG, exception_object as uw::_Unwind_Ptr);
125             // ...A more principled approach would be to provide the full definition of ARM's
126             // _Unwind_Context in our libunwind bindings and fetch the required data from there
127             // directly, bypassing DWARF compatibility functions.
128 
129             let eh_action = match find_eh_action(context) {
130                 Ok(action) => action,
131                 Err(_) => return uw::_URC_FAILURE,
132             };
133             if search_phase {
134                 match eh_action {
135                     EHAction::None | EHAction::Cleanup(_) => {
136                         return continue_unwind(exception_object, context);
137                     }
138                     EHAction::Catch(_) | EHAction::Filter(_) => {
139                         // EHABI requires the personality routine to update the
140                         // SP value in the barrier cache of the exception object.
141                         (*exception_object).private[5] =
142                             uw::_Unwind_GetGR(context, uw::UNWIND_SP_REG);
143                         return uw::_URC_HANDLER_FOUND;
144                     }
145                     EHAction::Terminate => return uw::_URC_FAILURE,
146                 }
147             } else {
148                 match eh_action {
149                     EHAction::None => return continue_unwind(exception_object, context),
150                     EHAction::Filter(_) if state & uw::_US_FORCE_UNWIND as c_int != 0 => return continue_unwind(exception_object, context),
151                     EHAction::Cleanup(lpad) | EHAction::Catch(lpad) | EHAction::Filter(lpad) => {
152                         uw::_Unwind_SetGR(
153                             context,
154                             UNWIND_DATA_REG.0,
155                             exception_object as uintptr_t,
156                         );
157                         uw::_Unwind_SetGR(context, UNWIND_DATA_REG.1, 0);
158                         uw::_Unwind_SetIP(context, lpad);
159                         return uw::_URC_INSTALL_CONTEXT;
160                     }
161                     EHAction::Terminate => return uw::_URC_FAILURE,
162                 }
163             }
164 
165             // On ARM EHABI the personality routine is responsible for actually
166             // unwinding a single stack frame before returning (ARM EHABI Sec. 6.1).
167             unsafe fn continue_unwind(
168                 exception_object: *mut uw::_Unwind_Exception,
169                 context: *mut uw::_Unwind_Context,
170             ) -> uw::_Unwind_Reason_Code {
171                 if __gnu_unwind_frame(exception_object, context) == uw::_URC_NO_REASON {
172                     uw::_URC_CONTINUE_UNWIND
173                 } else {
174                     uw::_URC_FAILURE
175                 }
176             }
177             // defined in libgcc
178             extern "C" {
179                 fn __gnu_unwind_frame(
180                     exception_object: *mut uw::_Unwind_Exception,
181                     context: *mut uw::_Unwind_Context,
182                 ) -> uw::_Unwind_Reason_Code;
183             }
184         }
185     } else {
186         // Default personality routine, which is used directly on most targets
187         // and indirectly on Windows x86_64 via SEH.
188         unsafe extern "C" fn rust_eh_personality_impl(
189             version: c_int,
190             actions: uw::_Unwind_Action,
191             _exception_class: uw::_Unwind_Exception_Class,
192             exception_object: *mut uw::_Unwind_Exception,
193             context: *mut uw::_Unwind_Context,
194         ) -> uw::_Unwind_Reason_Code {
195             if version != 1 {
196                 return uw::_URC_FATAL_PHASE1_ERROR;
197             }
198             let eh_action = match find_eh_action(context) {
199                 Ok(action) => action,
200                 Err(_) => return uw::_URC_FATAL_PHASE1_ERROR,
201             };
202             if actions as i32 & uw::_UA_SEARCH_PHASE as i32 != 0 {
203                 match eh_action {
204                     EHAction::None | EHAction::Cleanup(_) => uw::_URC_CONTINUE_UNWIND,
205                     EHAction::Catch(_) | EHAction::Filter(_) => uw::_URC_HANDLER_FOUND,
206                     EHAction::Terminate => uw::_URC_FATAL_PHASE1_ERROR,
207                 }
208             } else {
209                 match eh_action {
210                     EHAction::None => uw::_URC_CONTINUE_UNWIND,
211                     // Forced unwinding hits a terminate action.
212                     EHAction::Filter(_) if actions as i32 & uw::_UA_FORCE_UNWIND as i32 != 0 => uw::_URC_CONTINUE_UNWIND,
213                     EHAction::Cleanup(lpad) | EHAction::Catch(lpad) | EHAction::Filter(lpad) => {
214                         uw::_Unwind_SetGR(
215                             context,
216                             UNWIND_DATA_REG.0,
217                             exception_object as uintptr_t,
218                         );
219                         uw::_Unwind_SetGR(context, UNWIND_DATA_REG.1, 0);
220                         uw::_Unwind_SetIP(context, lpad);
221                         uw::_URC_INSTALL_CONTEXT
222                     }
223                     EHAction::Terminate => uw::_URC_FATAL_PHASE2_ERROR,
224                 }
225             }
226         }
227 
228         cfg_if::cfg_if! {
229             if #[cfg(all(windows, any(target_arch = "aarch64", target_arch = "x86_64"), target_env = "gnu"))] {
230                 // On x86_64 MinGW targets, the unwinding mechanism is SEH however the unwind
231                 // handler data (aka LSDA) uses GCC-compatible encoding.
232                 #[lang = "eh_personality"]
233                 #[allow(nonstandard_style)]
234                 unsafe extern "C" fn rust_eh_personality(
235                     exceptionRecord: *mut uw::EXCEPTION_RECORD,
236                     establisherFrame: uw::LPVOID,
237                     contextRecord: *mut uw::CONTEXT,
238                     dispatcherContext: *mut uw::DISPATCHER_CONTEXT,
239                 ) -> uw::EXCEPTION_DISPOSITION {
240                     uw::_GCC_specific_handler(
241                         exceptionRecord,
242                         establisherFrame,
243                         contextRecord,
244                         dispatcherContext,
245                         rust_eh_personality_impl,
246                     )
247                 }
248             } else {
249                 // The personality routine for most of our targets.
250                 #[lang = "eh_personality"]
251                 unsafe extern "C" fn rust_eh_personality(
252                     version: c_int,
253                     actions: uw::_Unwind_Action,
254                     exception_class: uw::_Unwind_Exception_Class,
255                     exception_object: *mut uw::_Unwind_Exception,
256                     context: *mut uw::_Unwind_Context,
257                 ) -> uw::_Unwind_Reason_Code {
258                     rust_eh_personality_impl(
259                         version,
260                         actions,
261                         exception_class,
262                         exception_object,
263                         context,
264                     )
265                 }
266             }
267         }
268     }
269 }
270 
find_eh_action(context: *mut uw::_Unwind_Context) -> Result<EHAction, ()>271 unsafe fn find_eh_action(context: *mut uw::_Unwind_Context) -> Result<EHAction, ()> {
272     let lsda = uw::_Unwind_GetLanguageSpecificData(context) as *const u8;
273     let mut ip_before_instr: c_int = 0;
274     let ip = uw::_Unwind_GetIPInfo(context, &mut ip_before_instr);
275     let eh_context = EHContext {
276         // The return address points 1 byte past the call instruction,
277         // which could be in the next IP range in LSDA range table.
278         //
279         // `ip = -1` has special meaning, so use wrapping sub to allow for that
280         ip: if ip_before_instr != 0 { ip } else { ip.wrapping_sub(1) },
281         func_start: uw::_Unwind_GetRegionStart(context),
282         get_text_start: &|| uw::_Unwind_GetTextRelBase(context),
283         get_data_start: &|| uw::_Unwind_GetDataRelBase(context),
284     };
285     eh::find_eh_action(lsda, &eh_context)
286 }
287