std/sys/personality/dwarf/eh.rs
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).
11
12#![allow(non_upper_case_globals)]
13#![allow(unused)]
14
15use core::ptr;
16
17use super::DwarfReader;
18
19pub const DW_EH_PE_omit: u8 = 0xFF;
20pub const DW_EH_PE_absptr: u8 = 0x00;
21
22pub 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;
30
31pub 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;
36
37pub const DW_EH_PE_indirect: u8 = 0x80;
38
39#[derive(Copy, Clone)]
40pub struct EHContext<'a> {
41 pub ip: *const u8, // Current instruction pointer
42 pub func_start: *const u8, // Pointer to the current function
43 pub get_text_start: &'a dyn Fn() -> *const u8, // Get pointer to the code section
44 pub get_data_start: &'a dyn Fn() -> *const u8, // Get pointer to the data section
45}
46
47/// Landing pad.
48type LPad = *const u8;
49pub enum EHAction {
50 None,
51 /// Destructors should be executed when stack unwinds.
52 Cleanup(LPad),
53 /// Stack unwind should be stopped as the exception is going to be caught by `catch_unwind`.
54 Catch(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.
63 Filter(LPad),
64 /// Process should be terminated as the call site does not permit unwinding.
65 Terminate,
66}
67
68/// 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 =
75 cfg!(all(target_vendor = "apple", not(target_os = "watchos"), target_arch = "arm"));
76
77pub unsafe fn find_eh_action(lsda: *const u8, context: &EHContext<'_>) -> Result<EHAction, ()> {
78 if lsda.is_null() {
79 return Ok(EHAction::None);
80 }
81
82 let func_start = context.func_start;
83 let mut reader = DwarfReader::new(lsda);
84 let lpad_base = unsafe {
85 let start_encoding = reader.read::<u8>();
86 // base address for landing pad offsets
87 if start_encoding != DW_EH_PE_omit {
88 read_encoded_pointer(&mut reader, context, start_encoding)?
89 } else {
90 func_start
91 }
92 };
93 let call_site_encoding = unsafe {
94 let ttype_encoding = reader.read::<u8>();
95 if ttype_encoding != DW_EH_PE_omit {
96 // Rust doesn't analyze exception types, so we don't care about the type table
97 reader.read_uleb128();
98 }
99
100 reader.read::<u8>()
101 };
102 let action_table = unsafe {
103 let call_site_table_length = reader.read_uleb128();
104 reader.ptr.add(call_site_table_length as usize)
105 };
106 let ip = context.ip;
107
108 if !USING_SJLJ_EXCEPTIONS {
109 // read the callsite table
110 while reader.ptr < action_table {
111 unsafe {
112 // these are offsets rather than pointers;
113 let cs_start = read_encoded_offset(&mut reader, call_site_encoding)?;
114 let cs_len = read_encoded_offset(&mut reader, call_site_encoding)?;
115 let cs_lpad = read_encoded_offset(&mut reader, call_site_encoding)?;
116 let 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.
119 if ip < func_start.wrapping_add(cs_start) {
120 break;
121 }
122 if ip < func_start.wrapping_add(cs_start + cs_len) {
123 if cs_lpad == 0 {
124 return Ok(EHAction::None);
125 } else {
126 let lpad = lpad_base.wrapping_add(cs_lpad);
127 return 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.
133 Ok(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'.
138 match ip.addr() as isize {
139 -1 => return Ok(EHAction::None),
140 0 => return Ok(EHAction::Terminate),
141 _ => (),
142 }
143 let mut idx = ip.addr();
144 loop {
145 let cs_lpad = unsafe { reader.read_uleb128() };
146 let cs_action_entry = unsafe { reader.read_uleb128() };
147 idx -= 1;
148 if 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)
152 let lpad = ptr::with_exposed_provenance((cs_lpad + 1) as usize);
153 return Ok(unsafe { interpret_cs_action(action_table, cs_action_entry, lpad) });
154 }
155 }
156 }
157}
158
159unsafe fn interpret_cs_action(
160 action_table: *const u8,
161 cs_action_entry: u64,
162 lpad: LPad,
163) -> EHAction {
164 if 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.
167 EHAction::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.
171 let action_record = unsafe { action_table.offset(cs_action_entry as isize - 1) };
172 let mut action_reader = DwarfReader::new(action_record);
173 let ttype_index = unsafe { action_reader.read_sleb128() };
174 let next_action = unsafe { action_reader.read_sleb128() };
175 if 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.
185 EHAction::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.
190 EHAction::Catch(lpad)
191 } else {
192 EHAction::Filter(lpad)
193 }
194 }
195}
196
197#[inline]
198fn round_up(unrounded: usize, align: usize) -> Result<usize, ()> {
199 if align.is_power_of_two() { Ok((unrounded + align - 1) & !(align - 1)) } else { Err(()) }
200}
201
202/// 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, ()> {
215 if encoding == DW_EH_PE_omit || encoding & 0xF0 != 0 {
216 return Err(());
217 }
218 let result = unsafe {
219 match encoding & 0x0F {
220 // despite the name, LLVM also uses absptr for offsets instead of pointers
221 DW_EH_PE_absptr => reader.read::<usize>(),
222 DW_EH_PE_uleb128 => reader.read_uleb128() as usize,
223 DW_EH_PE_udata2 => reader.read::<u16>() as usize,
224 DW_EH_PE_udata4 => reader.read::<u32>() as usize,
225 DW_EH_PE_udata8 => reader.read::<u64>() as usize,
226 DW_EH_PE_sleb128 => reader.read_sleb128() as usize,
227 DW_EH_PE_sdata2 => reader.read::<i16>() as usize,
228 DW_EH_PE_sdata4 => reader.read::<i32>() as usize,
229 DW_EH_PE_sdata8 => reader.read::<i64>() as usize,
230 _ => return Err(()),
231 }
232 };
233 Ok(result)
234}
235
236/// 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, ()> {
253 if encoding == DW_EH_PE_omit {
254 return Err(());
255 }
256
257 let base_ptr = match encoding & 0x70 {
258 DW_EH_PE_absptr => core::ptr::null(),
259 // relative to address of the encoded value, despite the name
260 DW_EH_PE_pcrel => reader.ptr,
261 DW_EH_PE_funcrel => {
262 if context.func_start.is_null() {
263 return Err(());
264 }
265 context.func_start
266 }
267 DW_EH_PE_textrel => (*context.get_text_start)(),
268 DW_EH_PE_datarel => (*context.get_data_start)(),
269 // aligned means the value is aligned to the size of a pointer
270 DW_EH_PE_aligned => {
271 reader.ptr = reader.ptr.with_addr(round_up(reader.ptr.addr(), size_of::<*const u8>())?);
272 core::ptr::null()
273 }
274 _ => return Err(()),
275 };
276
277 let 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
280 if encoding & 0x0F != DW_EH_PE_absptr {
281 return Err(());
282 }
283 unsafe { reader.read::<*const u8>() }
284 } else {
285 let offset = unsafe { read_encoded_offset(reader, encoding & 0x0F)? };
286 base_ptr.wrapping_add(offset)
287 };
288
289 if encoding & DW_EH_PE_indirect != 0 {
290 ptr = unsafe { *(ptr.cast::<*const u8>()) };
291 }
292
293 Ok(ptr)
294}