Debian Codegraph @

third_party/rust/framehop/src/dwarf.rs

raw
1 use core::marker::PhantomData;
2
3 use alloc::vec::Vec;
4 use gimli::{
5 CfaRule, CieOrFde, DebugFrame, EhFrame, EhFrameHdr, Encoding, EndianSlice, Evaluation,
6 EvaluationResult, EvaluationStorage, Expression, LittleEndian, Location, ParsedEhFrameHdr,
7 Reader, ReaderOffset, Register, RegisterRule, UnwindContext, UnwindContextStorage,
8 UnwindOffset, UnwindSection, UnwindTableRow, Value,
9 };
10
11 pub(crate) use gimli::BaseAddresses;
12
13 use crate::{arch::Arch, unwind_result::UnwindResult, ModuleSectionInfo};
14
15 #[derive(Debug, Clone, Copy, PartialEq, Eq)]
16 pub enum DwarfUnwinderError {
17 FdeFromOffsetFailed(gimli::Error),
18 UnwindInfoForAddressFailed(gimli::Error),
19 StackPointerMovedBackwards,
20 DidNotAdvance,
21 CouldNotRecoverCfa,
22 CouldNotRecoverReturnAddress,
23 CouldNotRecoverFramePointer,
24 }
25
26 impl core::fmt::Display for DwarfUnwinderError {
27 fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
28 match self {
29 Self::FdeFromOffsetFailed(err) => {
30 write!(f, "Could not get the FDE for the supplied offset: {err}")
31 }
32 Self::UnwindInfoForAddressFailed(err) => write!(
33 f,
34 "Could not find DWARF unwind info for the requested address: {err}"
35 ),
36 Self::StackPointerMovedBackwards => write!(f, "Stack pointer moved backwards"),
37 Self::DidNotAdvance => write!(f, "Did not advance"),
38 Self::CouldNotRecoverCfa => write!(f, "Could not recover the CFA"),
39 Self::CouldNotRecoverReturnAddress => write!(f, "Could not recover the return address"),
40 Self::CouldNotRecoverFramePointer => write!(f, "Could not recover the frame pointer"),
41 }
42 }
43 }
44
45 #[cfg(feature = "std")]
46 impl std::error::Error for DwarfUnwinderError {
47 fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
48 match self {
49 Self::FdeFromOffsetFailed(e) => Some(e),
50 Self::UnwindInfoForAddressFailed(e) => Some(e),
51 _ => None,
52 }
53 }
54 }
55
56 #[derive(Clone, Debug)]
57 pub enum ConversionError {
58 CfaIsExpression,
59 CfaIsOffsetFromUnknownRegister,
60 ReturnAddressRuleWithUnexpectedOffset,
61 ReturnAddressRuleWasWeird,
62 SpOffsetDoesNotFit,
63 RegisterNotStoredRelativeToCfa,
64 RestoringFpButNotLr,
65 LrStorageOffsetDoesNotFit,
66 FpStorageOffsetDoesNotFit,
67 SpOffsetFromFpDoesNotFit,
68 FramePointerRuleDoesNotRestoreLr,
69 FramePointerRuleDoesNotRestoreFp,
70 FramePointerRuleDoesNotRestoreBp,
71 FramePointerRuleHasStrangeBpOffset,
72 }
73
74 pub trait DwarfUnwinding: Arch {
75 fn unwind_frame<F, R, UCS, ES>(
76 section: &impl UnwindSection<R>,
77 unwind_info: &UnwindTableRow<R::Offset, UCS>,
78 encoding: Encoding,
79 regs: &mut Self::UnwindRegs,
80 is_first_frame: bool,
81 read_stack: &mut F,
82 ) -> Result<UnwindResult<Self::UnwindRule>, DwarfUnwinderError>
83 where
84 F: FnMut(u64) -> Result<u64, ()>,
85 R: Reader,
86 UCS: UnwindContextStorage<R::Offset>,
87 ES: EvaluationStorage<R>;
88
89 fn rule_if_uncovered_by_fde() -> Self::UnwindRule;
90 }
91
92 pub enum UnwindSectionType {
93 EhFrame,
94 DebugFrame,
95 }
96
97 pub struct DwarfUnwinder<'a, R, A, UCS>
98 where
99 R: Reader,
100 A: DwarfUnwinding,
101 UCS: UnwindContextStorage<R::Offset>,
102 {
103 unwind_section_data: R,
104 unwind_section_type: UnwindSectionType,
105 eh_frame_hdr: Option<ParsedEhFrameHdr<EndianSlice<'a, R::Endian>>>,
106 unwind_context: &'a mut UnwindContext<R::Offset, UCS>,
107 base_svma: u64,
108 bases: BaseAddresses,
109 _arch: PhantomData<A>,
110 }
111
112 impl<'a, R, A, UCS> DwarfUnwinder<'a, R, A, UCS>
113 where
114 R: Reader,
115 A: DwarfUnwinding,
116 UCS: UnwindContextStorage<R::Offset>,
117 {
118 pub fn new(
119 unwind_section_data: R,
120 unwind_section_type: UnwindSectionType,
121 eh_frame_hdr_data: Option<&'a [u8]>,
122 unwind_context: &'a mut UnwindContext<R::Offset, UCS>,
123 bases: BaseAddresses,
124 base_svma: u64,
125 ) -> Self {
126 let eh_frame_hdr = match eh_frame_hdr_data {
127 Some(eh_frame_hdr_data) => {
128 let hdr = EhFrameHdr::new(eh_frame_hdr_data, unwind_section_data.endian());
129 match hdr.parse(&bases, 8) {
130 Ok(hdr) => Some(hdr),
131 Err(_) => None,
132 }
133 }
134 None => None,
135 };
136 Self {
137 unwind_section_data,
138 unwind_section_type,
139 eh_frame_hdr,
140 unwind_context,
141 bases,
142 base_svma,
143 _arch: PhantomData,
144 }
145 }
146
147 pub fn get_fde_offset_for_relative_address(&self, rel_lookup_address: u32) -> Option<u32> {
148 let lookup_svma = self.base_svma + rel_lookup_address as u64;
149 let eh_frame_hdr = self.eh_frame_hdr.as_ref()?;
150 let table = eh_frame_hdr.table()?;
151 let fde_ptr = table.lookup(lookup_svma, &self.bases).ok()?;
152 let fde_offset = table.pointer_to_offset(fde_ptr).ok()?;
153 fde_offset.0.into_u64().try_into().ok()
154 }
155
156 pub fn unwind_frame_with_fde<F, ES>(
157 &mut self,
158 regs: &mut A::UnwindRegs,
159 is_first_frame: bool,
160 rel_lookup_address: u32,
161 fde_offset: u32,
162 read_stack: &mut F,
163 ) -> Result<UnwindResult<A::UnwindRule>, DwarfUnwinderError>
164 where
165 F: FnMut(u64) -> Result<u64, ()>,
166 ES: EvaluationStorage<R>,
167 {
168 let lookup_svma = self.base_svma + rel_lookup_address as u64;
169 let unwind_section_data = self.unwind_section_data.clone();
170 match self.unwind_section_type {
171 UnwindSectionType::EhFrame => {
172 let mut eh_frame = EhFrame::from(unwind_section_data);
173 eh_frame.set_address_size(8);
174 let unwind_info = self.unwind_info_for_fde(&eh_frame, lookup_svma, fde_offset);
175 if let Err(DwarfUnwinderError::UnwindInfoForAddressFailed(_)) = unwind_info {
176 return Ok(UnwindResult::ExecRule(A::rule_if_uncovered_by_fde()));
177 }
178 let (unwind_info, encoding) = unwind_info?;
179 A::unwind_frame::<F, R, UCS, ES>(
180 &eh_frame,
181 unwind_info,
182 encoding,
183 regs,
184 is_first_frame,
185 read_stack,
186 )
187 }
188 UnwindSectionType::DebugFrame => {
189 let mut debug_frame = DebugFrame::from(unwind_section_data);
190 debug_frame.set_address_size(8);
191 let unwind_info = self.unwind_info_for_fde(&debug_frame, lookup_svma, fde_offset);
192 if let Err(DwarfUnwinderError::UnwindInfoForAddressFailed(_)) = unwind_info {
193 return Ok(UnwindResult::ExecRule(A::rule_if_uncovered_by_fde()));
194 }
195 let (unwind_info, encoding) = unwind_info?;
196 A::unwind_frame::<F, R, UCS, ES>(
197 &debug_frame,
198 unwind_info,
199 encoding,
200 regs,
201 is_first_frame,
202 read_stack,
203 )
204 }
205 }
206 }
207
208 fn unwind_info_for_fde<US: UnwindSection<R>>(
209 &mut self,
210 unwind_section: &US,
211 lookup_svma: u64,
212 fde_offset: u32,
213 ) -> Result<(&UnwindTableRow<R::Offset, UCS>, Encoding), DwarfUnwinderError> {
214 let fde = unwind_section.fde_from_offset(
215 &self.bases,
216 US::Offset::from(R::Offset::from_u32(fde_offset)),
217 US::cie_from_offset,
218 );
219 let fde = fde.map_err(DwarfUnwinderError::FdeFromOffsetFailed)?;
220 let encoding = fde.cie().encoding();
221 let unwind_info: &UnwindTableRow<_, _> = fde
222 .unwind_info_for_address(
223 unwind_section,
224 &self.bases,
225 self.unwind_context,
226 lookup_svma,
227 )
228 .map_err(DwarfUnwinderError::UnwindInfoForAddressFailed)?;
229 Ok((unwind_info, encoding))
230 }
231 }
232
233 pub(crate) fn base_addresses_for_sections<D>(
234 section_info: &mut impl ModuleSectionInfo<D>,
235 ) -> BaseAddresses {
236 let mut start_addr = |names: &[&[u8]]| -> u64 {
237 names
238 .iter()
239 .find_map(|name| section_info.section_svma_range(name))
240 .map(|r| r.start)
241 .unwrap_or_default()
242 };
243 BaseAddresses::default()
244 .set_eh_frame(start_addr(&[b"__eh_frame", b".eh_frame"]))
245 .set_eh_frame_hdr(start_addr(&[b"__eh_frame_hdr", b".eh_frame_hdr"]))
246 .set_text(start_addr(&[b"__text", b".text"]))
247 .set_got(start_addr(&[b"__got", b".got"]))
248 }
249
250 #[derive(Debug, Clone, Copy, PartialEq, Eq)]
251 pub enum DwarfCfiIndexError {
252 Gimli(gimli::Error),
253 CouldNotSubtractBaseAddress,
254 RelativeAddressTooBig,
255 FdeOffsetTooBig,
256 }
257
258 impl core::fmt::Display for DwarfCfiIndexError {
259 fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
260 match self {
261 Self::Gimli(e) => write!(f, "EhFrame processing failed: {e}"),
262 Self::CouldNotSubtractBaseAddress => {
263 write!(f, "Could not subtract base address to create relative pc")
264 }
265 Self::RelativeAddressTooBig => write!(f, "Relative address did not fit into u32"),
266 Self::FdeOffsetTooBig => write!(f, "FDE offset did not fit into u32"),
267 }
268 }
269 }
270
271 impl From<gimli::Error> for DwarfCfiIndexError {
272 fn from(e: gimli::Error) -> Self {
273 Self::Gimli(e)
274 }
275 }
276
277 #[cfg(feature = "std")]
278 impl std::error::Error for DwarfCfiIndexError {
279 fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
280 match self {
281 Self::Gimli(e) => Some(e),
282 _ => None,
283 }
284 }
285 }
286
287 /// A binary search table for eh_frame FDEs. We generate this whenever a module
288 /// without eh_frame_hdr is added.
289 pub struct DwarfCfiIndex {
290 /// Contains the initial address for every FDE, relative to the base address.
291 /// This vector is sorted so that it can be used for binary search.
292 /// It has the same length as `fde_offsets`.
293 sorted_fde_pc_starts: Vec<u32>,
294 /// Contains the FDE offset for every FDE. The FDE at offset `fde_offsets[i]`
295 /// has a PC range which starts at `sorted_fde_pc_starts[i]`.
296 fde_offsets: Vec<u32>,
297 }
298
299 impl DwarfCfiIndex {
300 pub fn try_new<R, US>(
301 unwind_section: US,
302 bases: BaseAddresses,
303 base_svma: u64,
304 ) -> Result<Self, DwarfCfiIndexError>
305 where
306 R: Reader,
307 R::Offset: TryInto<u32>,
308 US: UnwindSection<R>,
309 {
310 let mut fde_pc_and_offset = Vec::new();
311
312 let mut cur_cie = None;
313 let mut entries_iter = unwind_section.entries(&bases);
314 while let Some(entry) = entries_iter.next()? {
315 let fde = match entry {
316 CieOrFde::Cie(cie) => {
317 cur_cie = Some(cie);
318 continue;
319 }
320 CieOrFde::Fde(partial_fde) => {
321 partial_fde.parse(|unwind_section, bases, cie_offset| {
322 if let Some(cie) = &cur_cie {
323 if cie.offset()
324 == <US::Offset as UnwindOffset<R::Offset>>::into(cie_offset)
325 {
326 return Ok(cie.clone());
327 }
328 }
329 let cie = unwind_section.cie_from_offset(bases, cie_offset);
330 if let Ok(cie) = &cie {
331 cur_cie = Some(cie.clone());
332 }
333 cie
334 })?
335 }
336 };
337 let pc = fde.initial_address();
338 let relative_pc = pc
339 .checked_sub(base_svma)
340 .ok_or(DwarfCfiIndexError::CouldNotSubtractBaseAddress)?;
341 let relative_pc = u32::try_from(relative_pc)
342 .map_err(|_| DwarfCfiIndexError::RelativeAddressTooBig)?;
343 let fde_offset = <R::Offset as TryInto<u32>>::try_into(fde.offset())
344 .map_err(|_| DwarfCfiIndexError::FdeOffsetTooBig)?;
345 fde_pc_and_offset.push((relative_pc, fde_offset));
346 }
347 fde_pc_and_offset.sort_by_key(|(pc, _)| *pc);
348 let sorted_fde_pc_starts = fde_pc_and_offset.iter().map(|(pc, _)| *pc).collect();
349 let fde_offsets = fde_pc_and_offset.into_iter().map(|(_, fde)| fde).collect();
350 Ok(Self {
351 sorted_fde_pc_starts,
352 fde_offsets,
353 })
354 }
355
356 pub fn try_new_eh_frame<D>(
357 eh_frame_data: &[u8],
358 section_info: &mut impl ModuleSectionInfo<D>,
359 ) -> Result<Self, DwarfCfiIndexError> {
360 let bases = base_addresses_for_sections(section_info);
361 let mut eh_frame = EhFrame::from(EndianSlice::new(eh_frame_data, LittleEndian));
362 eh_frame.set_address_size(8);
363
364 Self::try_new(eh_frame, bases, section_info.base_svma())
365 }
366
367 pub fn try_new_debug_frame<D>(
368 debug_frame_data: &[u8],
369 section_info: &mut impl ModuleSectionInfo<D>,
370 ) -> Result<Self, DwarfCfiIndexError> {
371 let bases = base_addresses_for_sections(section_info);
372 let mut debug_frame = DebugFrame::from(EndianSlice::new(debug_frame_data, LittleEndian));
373 debug_frame.set_address_size(8);
374
375 Self::try_new(debug_frame, bases, section_info.base_svma())
376 }
377
378 pub fn fde_offset_for_relative_address(&self, rel_lookup_address: u32) -> Option<u32> {
379 let i = match self.sorted_fde_pc_starts.binary_search(&rel_lookup_address) {
380 Err(0) => return None,
381 Ok(i) => i,
382 Err(i) => i - 1,
383 };
384 Some(self.fde_offsets[i])
385 }
386 }
387
388 pub trait DwarfUnwindRegs {
389 fn get(&self, register: Register) -> Option<u64>;
390 }
391
392 pub fn eval_cfa_rule<R: Reader, UR: DwarfUnwindRegs, S: EvaluationStorage<R>>(
393 section: &impl UnwindSection<R>,
394 rule: &CfaRule<R::Offset>,
395 encoding: Encoding,
396 regs: &UR,
397 ) -> Option<u64> {
398 match rule {
399 CfaRule::RegisterAndOffset { register, offset } => {
400 let val = regs.get(*register)?;
401 u64::try_from(i64::try_from(val).ok()?.checked_add(*offset)?).ok()
402 }
403 CfaRule::Expression(expr) => {
404 let expr = expr.get(section).ok()?;
405 eval_expr::<R, UR, S>(expr, encoding, regs)
406 }
407 }
408 }
409
410 fn eval_expr<R: Reader, UR: DwarfUnwindRegs, S: EvaluationStorage<R>>(
411 expr: Expression<R>,
412 encoding: Encoding,
413 regs: &UR,
414 ) -> Option<u64> {
415 let mut eval = Evaluation::<R, S>::new_in(expr.0, encoding);
416 let mut result = eval.evaluate().ok()?;
417 loop {
418 match result {
419 EvaluationResult::Complete => break,
420 EvaluationResult::RequiresRegister { register, .. } => {
421 let value = regs.get(register)?;
422 result = eval.resume_with_register(Value::Generic(value as _)).ok()?;
423 }
424 _ => return None,
425 }
426 }
427 let x = &eval.as_result().last()?.location;
428 if let Location::Address { address } = x {
429 Some(*address)
430 } else {
431 None
432 }
433 }
434
435 pub fn eval_register_rule<R, F, UR, S>(
436 section: &impl UnwindSection<R>,
437 rule: RegisterRule<R::Offset>,
438 cfa: u64,
439 encoding: Encoding,
440 val: u64,
441 regs: &UR,
442 read_stack: &mut F,
443 ) -> Option<u64>
444 where
445 R: Reader,
446 F: FnMut(u64) -> Result<u64, ()>,
447 UR: DwarfUnwindRegs,
448 S: EvaluationStorage<R>,
449 {
450 match rule {
451 RegisterRule::Undefined => None,
452 RegisterRule::SameValue => Some(val),
453 RegisterRule::Offset(offset) => {
454 let cfa_plus_offset =
455 u64::try_from(i64::try_from(cfa).ok()?.checked_add(offset)?).ok()?;
456 read_stack(cfa_plus_offset).ok()
457 }
458 RegisterRule::ValOffset(offset) => {
459 u64::try_from(i64::try_from(cfa).ok()?.checked_add(offset)?).ok()
460 }
461 RegisterRule::Register(register) => regs.get(register),
462 RegisterRule::Expression(expr) => {
463 let expr = expr.get(section).ok()?;
464 let val = eval_expr::<R, UR, S>(expr, encoding, regs)?;
465 read_stack(val).ok()
466 }
467 RegisterRule::ValExpression(expr) => {
468 let expr = expr.get(section).ok()?;
469 eval_expr::<R, UR, S>(expr, encoding, regs)
470 }
471 RegisterRule::Architectural => {
472 // Unimplemented
473 // TODO: Find out what the architectural rules for x86_64 and for aarch64 are, if any.
474 None
475 }
476 _ => None,
477 }
478 }