Skip to main content

std/sys/personality/
gcc.rs

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://nicolasbrailo.github.io/blog/projects_texts/13exceptionsunderthehood.html>
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#![forbid(unsafe_op_in_unsafe_fn)]
39
40use unwind as uw;
41
42use super::dwarf::eh::{self, EHAction, EHContext};
43use crate::ffi::c_int;
44
45// Register ids were lifted from LLVM's TargetLowering::getExceptionPointerRegister()
46// and TargetLowering::getExceptionSelectorRegister() for each architecture,
47// then mapped to DWARF register numbers via register definition tables
48// (typically <arch>RegisterInfo.td, search for "DwarfRegNum").
49// See also https://llvm.org/docs/WritingAnLLVMBackend.html#defining-a-register.
50
51#[cfg(target_arch = "x86")]
52const UNWIND_DATA_REG: (i32, i32) = (0, 2); // EAX, EDX
53
54#[cfg(target_arch = "x86_64")]
55const UNWIND_DATA_REG: (i32, i32) = (0, 1); // RAX, RDX
56
57#[cfg(any(target_arch = "arm", target_arch = "aarch64"))]
58const UNWIND_DATA_REG: (i32, i32) = (0, 1); // R0, R1 / X0, X1
59
60#[cfg(target_arch = "m68k")]
61const UNWIND_DATA_REG: (i32, i32) = (0, 1); // D0, D1
62
63#[cfg(any(
64    target_arch = "mips",
65    target_arch = "mips32r6",
66    target_arch = "mips64",
67    target_arch = "mips64r6"
68))]
69const UNWIND_DATA_REG: (i32, i32) = (4, 5); // A0, A1
70
71#[cfg(target_arch = "csky")]
72const UNWIND_DATA_REG: (i32, i32) = (0, 1); // R0, R1
73
74#[cfg(any(target_arch = "powerpc", target_arch = "powerpc64"))]
75const UNWIND_DATA_REG: (i32, i32) = (3, 4); // R3, R4 / X3, X4
76
77#[cfg(target_arch = "s390x")]
78const UNWIND_DATA_REG: (i32, i32) = (6, 7); // R6, R7
79
80#[cfg(any(target_arch = "sparc", target_arch = "sparc64"))]
81const UNWIND_DATA_REG: (i32, i32) = (24, 25); // I0, I1
82
83#[cfg(target_arch = "hexagon")]
84const UNWIND_DATA_REG: (i32, i32) = (0, 1); // R0, R1
85
86#[cfg(any(target_arch = "riscv64", target_arch = "riscv32"))]
87const UNWIND_DATA_REG: (i32, i32) = (10, 11); // x10, x11
88
89#[cfg(any(target_arch = "loongarch32", target_arch = "loongarch64"))]
90const UNWIND_DATA_REG: (i32, i32) = (4, 5); // a0, a1
91
92// The following code is based on GCC's C and C++ personality routines.  For reference, see:
93// https://github.com/gcc-mirror/gcc/blob/master/libstdc++-v3/libsupc++/eh_personality.cc
94// https://github.com/gcc-mirror/gcc/blob/trunk/libgcc/unwind-c.c
95
96cfg_select! {
97    all(target_arch = "arm", not(target_vendor = "apple"), not(target_os = "netbsd")) => {
98        /// personality fn called by [ARM EHABI][armeabi-eh]
99        ///
100        /// 32-bit ARM on iOS/tvOS/watchOS does not use ARM EHABI, it uses
101        /// either "setjmp-longjmp" unwinding or DWARF CFI unwinding, which is
102        /// handled by the default routine.
103        ///
104        /// [armeabi-eh]: https://web.archive.org/web/20190728160938/https://infocenter.arm.com/help/topic/com.arm.doc.ihi0038b/IHI0038B_ehabi.pdf
105        #[lang = "eh_personality"]
106        unsafe extern "C" fn rust_eh_personality(
107            state: uw::_Unwind_State,
108            exception_object: *mut uw::_Unwind_Exception,
109            context: *mut uw::_Unwind_Context,
110        ) -> uw::_Unwind_Reason_Code {
111            unsafe {
112                let state = state as c_int;
113                let action = state & uw::_US_ACTION_MASK as c_int;
114                let search_phase = if action == uw::_US_VIRTUAL_UNWIND_FRAME as c_int {
115                    // Backtraces on ARM will call the personality routine with
116                    // state == _US_VIRTUAL_UNWIND_FRAME | _US_FORCE_UNWIND. In those cases
117                    // we want to continue unwinding the stack, otherwise all our backtraces
118                    // would end at __rust_try
119                    if state & uw::_US_FORCE_UNWIND as c_int != 0 {
120                        return continue_unwind(exception_object, context);
121                    }
122                    true
123                } else if action == uw::_US_UNWIND_FRAME_STARTING as c_int {
124                    false
125                } else if action == uw::_US_UNWIND_FRAME_RESUME as c_int {
126                    return continue_unwind(exception_object, context);
127                } else {
128                    return uw::_URC_FAILURE;
129                };
130
131                // The DWARF unwinder assumes that _Unwind_Context holds things like the function
132                // and LSDA pointers, however ARM EHABI places them into the exception object.
133                // To preserve signatures of functions like _Unwind_GetLanguageSpecificData(), which
134                // take only the context pointer, GCC personality routines stash a pointer to
135                // exception_object in the context, using location reserved for ARM's
136                // "scratch register" (r12).
137                uw::_Unwind_SetGR(
138                    context,
139                    uw::UNWIND_POINTER_REG,
140                    exception_object as uw::_Unwind_Ptr,
141                );
142                // ...A more principled approach would be to provide the full definition of ARM's
143                // _Unwind_Context in our libunwind bindings and fetch the required data from there
144                // directly, bypassing DWARF compatibility functions.
145
146                let eh_action = match find_eh_action(context) {
147                    Ok(action) => action,
148                    Err(_) => return uw::_URC_FAILURE,
149                };
150                if search_phase {
151                    match eh_action {
152                        EHAction::None | EHAction::Cleanup(_) => {
153                            return continue_unwind(exception_object, context);
154                        }
155                        EHAction::Catch(_) | EHAction::Filter(_) => {
156                            // EHABI requires the personality routine to update the
157                            // SP value in the barrier cache of the exception object.
158                            (*exception_object).private[5] =
159                                uw::_Unwind_GetGR(context, uw::UNWIND_SP_REG);
160                            return uw::_URC_HANDLER_FOUND;
161                        }
162                        EHAction::Terminate => return uw::_URC_FAILURE,
163                    }
164                } else {
165                    match eh_action {
166                        EHAction::None => return continue_unwind(exception_object, context),
167                        EHAction::Filter(_) if state & uw::_US_FORCE_UNWIND as c_int != 0 => {
168                            return continue_unwind(exception_object, context);
169                        }
170                        EHAction::Cleanup(lpad)
171                        | EHAction::Catch(lpad)
172                        | EHAction::Filter(lpad) => {
173                            uw::_Unwind_SetGR(
174                                context,
175                                UNWIND_DATA_REG.0,
176                                exception_object as uw::_Unwind_Ptr,
177                            );
178                            uw::_Unwind_SetGR(context, UNWIND_DATA_REG.1, core::ptr::null());
179                            uw::_Unwind_SetIP(context, lpad);
180                            return uw::_URC_INSTALL_CONTEXT;
181                        }
182                        EHAction::Terminate => return uw::_URC_FAILURE,
183                    }
184                }
185
186                // On ARM EHABI the personality routine is responsible for actually
187                // unwinding a single stack frame before returning (ARM EHABI Sec. 6.1).
188                unsafe fn continue_unwind(
189                    exception_object: *mut uw::_Unwind_Exception,
190                    context: *mut uw::_Unwind_Context,
191                ) -> uw::_Unwind_Reason_Code {
192                    unsafe {
193                        if __gnu_unwind_frame(exception_object, context) == uw::_URC_NO_REASON {
194                            uw::_URC_CONTINUE_UNWIND
195                        } else {
196                            uw::_URC_FAILURE
197                        }
198                    }
199                }
200                // defined in libgcc
201                unsafe extern "C" {
202                    fn __gnu_unwind_frame(
203                        exception_object: *mut uw::_Unwind_Exception,
204                        context: *mut uw::_Unwind_Context,
205                    ) -> uw::_Unwind_Reason_Code;
206                }
207            }
208        }
209    }
210    _ => {
211        #[rustc_force_inline]
212        unsafe fn sign_lpad(context: *mut uw::_Unwind_Context, lpad: *const u8) -> *const u8 {
213            cfg_select! {
214                all(target_abi = "pauthtest", target_arch = "aarch64") => {
215                    // DWARF register number for SP on AArch64.
216                    const SP_REG: i32 = 31;
217
218                    unsafe {
219                        let sp = uw::_Unwind_GetGR(context, SP_REG).addr() as u64;
220                        let mut addr = lpad.addr();
221
222                        // `pacib` corresponds to `ptrauth_key_process_dependent_code` in <ptrauth.h>.
223                        core::arch::asm!(
224                            "pacib {addr}, {sp}",
225                            addr = inout(reg) addr,
226                            sp = in(reg) sp,
227                            options(nostack, preserves_flags)
228                        );
229
230                        lpad.with_addr(addr)
231                    }
232                }
233                _ => {
234                    let _ = context;
235                    lpad
236                }
237            }
238        }
239
240        /// Default personality routine, which is used directly on most targets
241        /// and indirectly on Windows x86_64 and AArch64 via SEH.
242        unsafe extern "C" fn rust_eh_personality_impl(
243            version: c_int,
244            actions: uw::_Unwind_Action,
245            _exception_class: uw::_Unwind_Exception_Class,
246            exception_object: *mut uw::_Unwind_Exception,
247            context: *mut uw::_Unwind_Context,
248        ) -> uw::_Unwind_Reason_Code {
249            unsafe {
250                if version != 1 {
251                    return uw::_URC_FATAL_PHASE1_ERROR;
252                }
253                let eh_action = match find_eh_action(context) {
254                    Ok(action) => action,
255                    Err(_) => return uw::_URC_FATAL_PHASE1_ERROR,
256                };
257                if actions & uw::_UA_SEARCH_PHASE != 0 {
258                    match eh_action {
259                        EHAction::None | EHAction::Cleanup(_) => uw::_URC_CONTINUE_UNWIND,
260                        EHAction::Catch(_) | EHAction::Filter(_) => uw::_URC_HANDLER_FOUND,
261                        EHAction::Terminate => uw::_URC_FATAL_PHASE1_ERROR,
262                    }
263                } else {
264                    match eh_action {
265                        EHAction::None => uw::_URC_CONTINUE_UNWIND,
266                        // Forced unwinding hits a terminate action.
267                        EHAction::Filter(_) if actions & uw::_UA_FORCE_UNWIND != 0 => {
268                            uw::_URC_CONTINUE_UNWIND
269                        }
270                        EHAction::Cleanup(lpad)
271                        | EHAction::Catch(lpad)
272                        | EHAction::Filter(lpad) => {
273                            uw::_Unwind_SetGR(context, UNWIND_DATA_REG.0, exception_object.cast());
274                            uw::_Unwind_SetGR(context, UNWIND_DATA_REG.1, core::ptr::null());
275                            let maybe_signed_lpad = sign_lpad(context, lpad);
276                            uw::_Unwind_SetIP(context, maybe_signed_lpad);
277                            uw::_URC_INSTALL_CONTEXT
278                        }
279                        EHAction::Terminate => uw::_URC_FATAL_PHASE2_ERROR,
280                    }
281                }
282            }
283        }
284
285        cfg_select! {
286            any(
287                all(
288                    windows,
289                    any(target_arch = "aarch64", target_arch = "x86_64"),
290                    target_env = "gnu"
291                ),
292                target_os = "cygwin",
293            ) => {
294                /// personality fn called by [Windows Structured Exception Handling][windows-eh]
295                ///
296                /// On x86_64 and AArch64 MinGW targets, the unwinding mechanism is SEH,
297                /// however the unwind handler data (aka LSDA) uses GCC-compatible encoding
298                ///
299                /// [windows-eh]: https://learn.microsoft.com/en-us/cpp/cpp/structured-exception-handling-c-cpp?view=msvc-170
300                #[lang = "eh_personality"]
301                #[allow(nonstandard_style)]
302                unsafe extern "C" fn rust_eh_personality(
303                    exceptionRecord: *mut uw::EXCEPTION_RECORD,
304                    establisherFrame: uw::LPVOID,
305                    contextRecord: *mut uw::CONTEXT,
306                    dispatcherContext: *mut uw::DISPATCHER_CONTEXT,
307                ) -> uw::EXCEPTION_DISPOSITION {
308                    // SAFETY: the cfg is still target_os = "windows" and target_env = "gnu",
309                    // which means that this is the correct function to call, passing our impl fn
310                    // as the callback which gets actually used
311                    unsafe {
312                        uw::_GCC_specific_handler(
313                            exceptionRecord,
314                            establisherFrame,
315                            contextRecord,
316                            dispatcherContext,
317                            rust_eh_personality_impl,
318                        )
319                    }
320                }
321            }
322            _ => {
323                /// personality fn called by [Itanium C++ ABI Exception Handling][itanium-eh]
324                ///
325                /// The personality routine for most non-Windows targets. This will be called by
326                /// the unwinding library:
327                /// - "In the search phase, the framework repeatedly calls the personality routine,
328                ///   with the _UA_SEARCH_PHASE flag as described below, first for the current PC
329                ///   and register state, and then unwinding a frame to a new PC at each step..."
330                /// - "If the search phase reports success, the framework restarts in the cleanup
331                ///    phase. Again, it repeatedly calls the personality routine, with the
332                ///   _UA_CLEANUP_PHASE flag as described below, first for the current PC and
333                ///   register state, and then unwinding a frame to a new PC at each step..."i
334                ///
335                /// [itanium-eh]: https://itanium-cxx-abi.github.io/cxx-abi/abi-eh.html
336                #[lang = "eh_personality"]
337                unsafe extern "C" fn rust_eh_personality(
338                    version: c_int,
339                    actions: uw::_Unwind_Action,
340                    exception_class: uw::_Unwind_Exception_Class,
341                    exception_object: *mut uw::_Unwind_Exception,
342                    context: *mut uw::_Unwind_Context,
343                ) -> uw::_Unwind_Reason_Code {
344                    // SAFETY: the platform support must modify the cfg for the inner fn
345                    // if it needs something different than what is currently invoked.
346                    unsafe {
347                        rust_eh_personality_impl(
348                            version,
349                            actions,
350                            exception_class,
351                            exception_object,
352                            context,
353                        )
354                    }
355                }
356            }
357        }
358    }
359}
360
361unsafe fn find_eh_action(context: *mut uw::_Unwind_Context) -> Result<EHAction, ()> {
362    unsafe {
363        let lsda = uw::_Unwind_GetLanguageSpecificData(context) as *const u8;
364        let mut ip_before_instr: c_int = 0;
365        let ip = uw::_Unwind_GetIPInfo(context, &mut ip_before_instr);
366        let eh_context = EHContext {
367            // The return address points 1 byte past the call instruction,
368            // which could be in the next IP range in LSDA range table.
369            //
370            // `ip = -1` has special meaning, so use wrapping sub to allow for that
371            ip: if ip_before_instr != 0 { ip } else { ip.wrapping_sub(1) },
372            func_start: uw::_Unwind_GetRegionStart(context),
373            get_text_start: &|| uw::_Unwind_GetTextRelBase(context),
374            get_data_start: &|| uw::_Unwind_GetDataRelBase(context),
375        };
376        eh::find_eh_action(lsda, &eh_context)
377    }
378}