1//! Parsing of GCC-style Language-Specific Data Area (LSDA)
2//! For details see:
3//! * <https://refspecs.linuxfoundation.org/LSB_3.0.0/LSB-PDA/LSB-PDA/ehframechpt.html>
4//! * <https://refspecs.linuxfoundation.org/LSB_5.0.0/LSB-Core-generic/LSB-Core-generic/dwarfext.html>
5//! * <https://itanium-cxx-abi.github.io/cxx-abi/exceptions.pdf>
6//! * <https://www.airs.com/blog/archives/460>
7//! * <https://www.airs.com/blog/archives/464>
8//!
9//! A reference implementation may be found in the GCC source tree
10//! (`<root>/libgcc/unwind-c.c` as of this writing).
1112#![allow(non_upper_case_globals)]
13#![allow(unused)]
1415use core::ptr;
1617use super::DwarfReader;
1819pub const DW_EH_PE_omit: u8 = 0xFF;
20pub const DW_EH_PE_absptr: u8 = 0x00;
2122pub const DW_EH_PE_uleb128: u8 = 0x01;
23pub const DW_EH_PE_udata2: u8 = 0x02;
24pub const DW_EH_PE_udata4: u8 = 0x03;
25pub const DW_EH_PE_udata8: u8 = 0x04;
26pub const DW_EH_PE_sleb128: u8 = 0x09;
27pub const DW_EH_PE_sdata2: u8 = 0x0A;
28pub const DW_EH_PE_sdata4: u8 = 0x0B;
29pub const DW_EH_PE_sdata8: u8 = 0x0C;
3031pub const DW_EH_PE_pcrel: u8 = 0x10;
32pub const DW_EH_PE_textrel: u8 = 0x20;
33pub const DW_EH_PE_datarel: u8 = 0x30;
34pub const DW_EH_PE_funcrel: u8 = 0x40;
35pub const DW_EH_PE_aligned: u8 = 0x50;
3637pub const DW_EH_PE_indirect: u8 = 0x80;
3839#[derive(#[automatically_derived]
impl<'a> ::core::marker::Copy for EHContext<'a> { }Copy, #[automatically_derived]
#[doc(hidden)]
unsafe impl<'a> ::core::clone::TrivialClone for EHContext<'a> { }
#[automatically_derived]
impl<'a> ::core::clone::Clone for EHContext<'a> {
#[inline]
fn clone(&self) -> EHContext<'a> {
let _: ::core::clone::AssertParamIsClone<*const u8>;
let _: ::core::clone::AssertParamIsClone<*const u8>;
let _: ::core::clone::AssertParamIsClone<&'a dyn Fn() -> *const u8>;
let _: ::core::clone::AssertParamIsClone<&'a dyn Fn() -> *const u8>;
*self
}
}Clone)]
40pub struct EHContext<'a> {
41pub ip: *const u8, // Current instruction pointer
42pub func_start: *const u8, // Pointer to the current function
43pub get_text_start: &'a dyn Fn() -> *const u8, // Get pointer to the code section
44pub get_data_start: &'a dyn Fn() -> *const u8, // Get pointer to the data section
45}
4647/// Landing pad.
48type LPad = *const u8;
49pub enum EHAction {
50None,
51/// Destructors should be executed when stack unwinds.
52Cleanup(LPad),
53/// Stack unwind should be stopped as the exception is going to be caught by `catch_unwind`.
54Catch(LPad),
55/// Stack unwind should be stopped for termination (`UnwindAction::Terminate`).
56 ///
57 /// Note that due to inlining the landing pad can execute destructors before terminating. So
58 /// this is different from `Terminate`.
59 ///
60 /// Handling of this is mostly identical to `Catch`; except that Rust frames that have no
61 /// destructors but only `UnwindAction::Terminate` is considered as plain-old-frame (POF) and
62 /// forced unwind is allowed to unwind past it; so this is treated as `None` during forced unwind.
63Filter(LPad),
64/// Process should be terminated as the call site does not permit unwinding.
65Terminate,
66}
6768/// 32-bit ARM Darwin platforms uses SjLj exceptions.
69///
70/// The exception is watchOS armv7k (specifically that subarchitecture), which
71/// instead uses DWARF Call Frame Information (CFI) unwinding.
72///
73/// <https://github.com/llvm/llvm-project/blob/llvmorg-18.1.4/clang/lib/Driver/ToolChains/Darwin.cpp#L3107-L3119>
74pub const USING_SJLJ_EXCEPTIONS: bool =
75falsecfg!(all(target_vendor = "apple", not(target_os = "watchos"), target_arch = "arm"));
7677pub unsafe fn find_eh_action(lsda: *const u8, context: &EHContext<'_>) -> Result<EHAction, ()> {
78if lsda.is_null() {
79return Ok(EHAction::None);
80 }
8182let func_start = context.func_start;
83let mut reader = DwarfReader::new(lsda);
84let lpad_base = unsafe {
85let start_encoding = reader.read::<u8>();
86// base address for landing pad offsets
87if start_encoding != DW_EH_PE_omit {
88 read_encoded_pointer(&mut reader, context, start_encoding)?
89} else {
90func_start91 }
92 };
93let call_site_encoding = unsafe {
94let ttype_encoding = reader.read::<u8>();
95if ttype_encoding != DW_EH_PE_omit {
96// Rust doesn't analyze exception types, so we don't care about the type table
97reader.read_uleb128();
98 }
99100reader.read::<u8>()
101 };
102let action_table = unsafe {
103let call_site_table_length = reader.read_uleb128();
104reader.ptr.add(call_site_table_lengthas usize)
105 };
106let ip = context.ip;
107108if !USING_SJLJ_EXCEPTIONS {
109// read the callsite table
110while reader.ptr < action_table {
111unsafe {
112// these are offsets rather than pointers;
113let cs_start = read_encoded_offset(&mut reader, call_site_encoding)?;
114let cs_len = read_encoded_offset(&mut reader, call_site_encoding)?;
115let cs_lpad = read_encoded_offset(&mut reader, call_site_encoding)?;
116let cs_action_entry = reader.read_uleb128();
117// Callsite table is sorted by cs_start, so if we've passed the ip, we
118 // may stop searching.
119if ip < func_start.wrapping_add(cs_start) {
120break;
121 }
122if ip < func_start.wrapping_add(cs_start + cs_len) {
123if cs_lpad == 0 {
124return Ok(EHAction::None);
125 } else {
126let lpad = lpad_base.wrapping_add(cs_lpad);
127return Ok(interpret_cs_action(action_table, cs_action_entry, lpad));
128 }
129 }
130 }
131 }
132// Ip is not present in the table. This indicates a nounwind call.
133Ok(EHAction::Terminate)
134 } else {
135// SjLj version:
136 // The "IP" is an index into the call-site table, with two exceptions:
137 // -1 means 'no-action', and 0 means 'terminate'.
138match ip.addr() as isize {
139 -1 => return Ok(EHAction::None),
1400 => return Ok(EHAction::Terminate),
141_ => (),
142 }
143let mut idx = ip.addr();
144loop {
145let cs_lpad = unsafe { reader.read_uleb128() };
146let cs_action_entry = unsafe { reader.read_uleb128() };
147idx -= 1;
148if idx == 0 {
149// Can never have null landing pad for sjlj -- that would have
150 // been indicated by a -1 call site index.
151 // FIXME(strict provenance)
152let lpad = ptr::with_exposed_provenance((cs_lpad + 1) as usize);
153return Ok(unsafe { interpret_cs_action(action_table, cs_action_entry, lpad) });
154 }
155 }
156 }
157}
158159unsafe fn interpret_cs_action(
160 action_table: *const u8,
161 cs_action_entry: u64,
162 lpad: LPad,
163) -> EHAction {
164if cs_action_entry == 0 {
165// If cs_action_entry is 0 then this is a cleanup (Drop::drop). We run these
166 // for both Rust panics and foreign exceptions.
167EHAction::Cleanup(lpad)
168 } else {
169// If lpad != 0 and cs_action_entry != 0, we have to check ttype_index.
170 // If ttype_index == 0 under the condition, we take cleanup action.
171let action_record = unsafe { action_table.offset(cs_action_entryas isize - 1) };
172let mut action_reader = DwarfReader::new(action_record);
173let ttype_index = unsafe { action_reader.read_sleb128() };
174let next_action = unsafe { action_reader.read_sleb128() };
175if next_action != 0 {
176// We observed multiple actions. Action records contain no duplicates (at least that is
177 // true for both LLVM/GCC), and as Rust does not have exception specification, this
178 // indicates that we have at least 2 of "cleanup", "catch" and "filter", so we should
179 // catch all exceptions.
180 //
181 // Note that even for the case of "cleanup" + "filter", decoding them as "catch" is
182 // fine: "filter" behaves identically to "catch" except for forced unwind; in case of
183 // forced unwind, hitting a "cleanup" landing pad is UB as it indicates that we're
184 // unwinding past a non-POF Rust frame.
185EHAction::Catch(lpad)
186 } else if ttype_index == 0 {
187 EHAction::Cleanup(lpad)
188 } else if ttype_index > 0 {
189// Stop unwinding Rust panics at catch_unwind.
190EHAction::Catch(lpad)
191 } else {
192 EHAction::Filter(lpad)
193 }
194 }
195}
196197#[inline]
198fn round_up(unrounded: usize, align: usize) -> Result<usize, ()> {
199if align.is_power_of_two() { Ok((unrounded + align - 1) & !(align - 1)) } else { Err(()) }
200}
201202/// Reads an offset (`usize`) from `reader` whose encoding is described by `encoding`.
203///
204/// `encoding` must be a [DWARF Exception Header Encoding as described by the LSB spec][LSB-dwarf-ext].
205/// In addition the upper ("application") part must be zero.
206///
207/// # Errors
208/// Returns `Err` if `encoding`
209/// * is not a valid DWARF Exception Header Encoding,
210/// * is `DW_EH_PE_omit`, or
211/// * has a non-zero application part.
212///
213/// [LSB-dwarf-ext]: https://refspecs.linuxfoundation.org/LSB_5.0.0/LSB-Core-generic/LSB-Core-generic/dwarfext.html
214unsafe fn read_encoded_offset(reader: &mut DwarfReader, encoding: u8) -> Result<usize, ()> {
215if encoding == DW_EH_PE_omit || encoding & 0xF0 != 0 {
216return Err(());
217 }
218let result = unsafe {
219match encoding & 0x0F {
220// despite the name, LLVM also uses absptr for offsets instead of pointers
221DW_EH_PE_absptr => reader.read::<usize>(),
222DW_EH_PE_uleb128 => reader.read_uleb128() as usize,
223DW_EH_PE_udata2 => reader.read::<u16>() as usize,
224DW_EH_PE_udata4 => reader.read::<u32>() as usize,
225DW_EH_PE_udata8 => reader.read::<u64>() as usize,
226DW_EH_PE_sleb128 => reader.read_sleb128() as usize,
227DW_EH_PE_sdata2 => reader.read::<i16>() as usize,
228DW_EH_PE_sdata4 => reader.read::<i32>() as usize,
229DW_EH_PE_sdata8 => reader.read::<i64>() as usize,
230_ => return Err(()),
231 }
232 };
233Ok(result)
234}
235236/// Reads a pointer from `reader` whose encoding is described by `encoding`.
237///
238/// `encoding` must be a [DWARF Exception Header Encoding as described by the LSB spec][LSB-dwarf-ext].
239///
240/// # Errors
241/// Returns `Err` if `encoding`
242/// * is not a valid DWARF Exception Header Encoding,
243/// * is `DW_EH_PE_omit`, or
244/// * combines `DW_EH_PE_absptr` or `DW_EH_PE_aligned` application part with an integer encoding
245/// (not `DW_EH_PE_absptr`) in the value format part.
246///
247/// [LSB-dwarf-ext]: https://refspecs.linuxfoundation.org/LSB_5.0.0/LSB-Core-generic/LSB-Core-generic/dwarfext.html
248unsafe fn read_encoded_pointer(
249 reader: &mut DwarfReader,
250 context: &EHContext<'_>,
251 encoding: u8,
252) -> Result<*const u8, ()> {
253if encoding == DW_EH_PE_omit {
254return Err(());
255 }
256257let base_ptr = match encoding & 0x70 {
258DW_EH_PE_absptr => core::ptr::null(),
259// relative to address of the encoded value, despite the name
260DW_EH_PE_pcrel => reader.ptr,
261DW_EH_PE_funcrel => {
262if context.func_start.is_null() {
263return Err(());
264 }
265context.func_start
266 }
267DW_EH_PE_textrel => (*context.get_text_start)(),
268DW_EH_PE_datarel => (*context.get_data_start)(),
269// aligned means the value is aligned to the size of a pointer
270DW_EH_PE_aligned => {
271reader.ptr = reader.ptr.with_addr(round_up(reader.ptr.addr(), size_of::<*const u8>())?);
272 core::ptr::null()
273 }
274_ => return Err(()),
275 };
276277let mut ptr = if base_ptr.is_null() {
278// any value encoding other than absptr would be nonsensical here;
279 // there would be no source of pointer provenance
280if encoding & 0x0F != DW_EH_PE_absptr {
281return Err(());
282 }
283unsafe { reader.read::<*const u8>() }
284 } else {
285let offset = unsafe { read_encoded_offset(reader, encoding & 0x0F)? };
286base_ptr.wrapping_add(offset)
287 };
288289if encoding & DW_EH_PE_indirect != 0 {
290ptr = unsafe { *(ptr.cast::<*const u8>()) };
291 }
292293Ok(ptr)
294}