Debian Codegraph @

third_party/rust/pe-unwind-info/src/x86_64.rs

raw
1 //! Unwind information for x86_64 (usually called x64 in microsoft documentation).
2 //!
3 //! The high-level API is accessed through `FunctionTableEntries::unwind_frame`. This function
4 //! allows you to unwind a frame to get the return address and all updated contextual registers.
5
6 use arrayvec::ArrayVec;
7 use std::ops::ControlFlow;
8 use thiserror::Error;
9 use zerocopy::{FromBytes, Ref, Unaligned, LE};
10 use zerocopy_derive::{FromBytes, FromZeroes, Unaligned};
11
12 type U16 = zerocopy::U16<LE>;
13
14 /// Little-endian u32.
15 pub type U32 = zerocopy::U32<LE>;
16
17 /// A view over function table entries in the `.pdata` section.
18 #[derive(Debug, Clone, Copy)]
19 pub struct FunctionTableEntries<'a> {
20 data: &'a [u8],
21 }
22
23 /// A runtime function record in the function table.
24 #[derive(Unaligned, FromZeroes, FromBytes, Debug, Clone, Copy)]
25 #[repr(C)]
26 pub struct RuntimeFunction {
27 /// The start relative virtual address of the function.
28 pub begin_address: U32,
29 /// The end relative virtual address of the function.
30 pub end_address: U32,
31 /// The relative virtual address of the unwind information related to the function.
32 pub unwind_info_address: U32,
33 }
34
35 impl<'a> FunctionTableEntries<'a> {
36 /// Parse function table entries from the given `.pdata` section contents.
37 pub fn parse(data: &'a [u8]) -> Self {
38 FunctionTableEntries { data }
39 }
40
41 /// Get the number of `RuntimeFunction` stored in the function table.
42 pub fn functions_len(&self) -> usize {
43 self.data.len() / std::mem::size_of::<RuntimeFunction>()
44 }
45
46 /// Get the `RuntimeFunction`s in the function table, if the parsed data is well-aligned and
47 /// sized.
48 pub fn functions(&self) -> Option<&'a [RuntimeFunction]> {
49 Ref::new_slice_unaligned(self.data).map(|lv| lv.into_slice())
50 }
51
52 /// Lookup the runtime function that contains the given relative virtual address.
53 pub fn lookup(&self, address: u32) -> Option<&'a RuntimeFunction> {
54 let functions = self.functions()?;
55 match functions.binary_search_by_key(&address, |f| f.begin_address.get()) {
56 Ok(i) => Some(&functions[i]),
57 Err(i) if i > 0 && address < functions[i - 1].end_address.get() => {
58 Some(&functions[i - 1])
59 }
60 _ => None,
61 }
62 }
63
64 pub fn unwind_frame<'m, S: UnwindState, M>(
65 &self,
66 state: &mut S,
67 mut memory_at_rva: M,
68 address: u32,
69 ) -> Option<u64>
70 where
71 M: FnMut(u32) -> Option<&'m [u8]> + 'm,
72 {
73 // This implements the procedure found
74 // [here](https://learn.microsoft.com/en-us/cpp/build/exception-handling-x64?view=msvc-170#unwind-procedure).
75 if let Some(mut function) = self.lookup(address) {
76 let offset = address - function.begin_address.get();
77 let mut is_chained = false;
78 loop {
79 let unwind_info =
80 UnwindInfo::parse(memory_at_rva(function.unwind_info_address.get())?)?;
81
82 if !is_chained {
83 // Check whether the address is in the function epilog. If so, we need to
84 // simulate the remaining epilog instructions (unwind codes don't account for
85 // unwinding from the epilog).
86 let bytes = (function.end_address.get() - address) as usize;
87 let instruction = &memory_at_rva(address)?[..bytes];
88 if let Ok(epilog_instructions) = FunctionEpilogInstruction::parse_sequence(
89 instruction,
90 unwind_info.frame_register(),
91 ) {
92 for instruction in epilog_instructions.iter() {
93 match instruction {
94 FunctionEpilogInstruction::AddSP(offset) => {
95 let rsp = state.read_register(Register::RSP);
96 state.write_register(Register::RSP, rsp + *offset as u64);
97 }
98 FunctionEpilogInstruction::AddSPFromFP(offset) => {
99 let fp = unwind_info
100 .frame_register()
101 .expect("invalid fp register offset");
102 let fp = state.read_register(fp);
103 state.write_register(Register::RSP, fp + *offset as u64);
104 }
105 FunctionEpilogInstruction::Pop(reg) => {
106 let rsp = state.read_register(Register::RSP);
107 let val = state.read_stack(rsp)?;
108 state.write_register(*reg, val);
109 state.write_register(Register::RSP, rsp + 8);
110 }
111 }
112 }
113 break;
114 }
115 }
116
117 for (_, op) in unwind_info
118 .unwind_operations()
119 .skip_while(|(o, _)| !is_chained && *o as u32 > offset)
120 {
121 if let ControlFlow::Break(rip) = unwind_info.resolve_operation(state, &op)? {
122 return Some(rip);
123 }
124 }
125 if let Some(UnwindInfoTrailer::ChainedUnwindInfo { chained }) =
126 unwind_info.trailer()
127 {
128 is_chained = true;
129 function = chained;
130 } else {
131 break;
132 }
133 }
134 }
135 let rsp = state.read_register(Register::RSP);
136 let rip = state.read_stack(rsp)?;
137 state.write_register(Register::RSP, rsp + 8);
138 Some(rip)
139 }
140
141 /// Unwind a single frame at the given relative virtual address.
142 ///
143 /// This does not attempt to invoke any exception or termination handlers.
144 ///
145 /// Returns `None` if `UnwindInfo` could not be parsed, a stack value could not be read, or a
146 /// memory offset in the binary could not be read (whether when parsing the section table or
147 /// when reading memory pointed to by the section table).
148 pub fn unwind_frame_with_image<S: UnwindState>(
149 &self,
150 state: &mut S,
151 image: &[u8],
152 address: u32,
153 ) -> Option<u64> {
154 let sections = Sections::parse(image)?;
155 self.unwind_frame(state, |addr| sections.memory_at_rva(addr), address)
156 }
157 }
158
159 impl<'a> Iterator for FunctionTableEntries<'a> {
160 type Item = &'a RuntimeFunction;
161
162 fn next(&mut self) -> Option<Self::Item> {
163 let (rf, rest) = Ref::<_, RuntimeFunction>::new_unaligned_from_prefix(self.data)?;
164 self.data = rest;
165 Some(rf.into_ref())
166 }
167 }
168
169 #[derive(Debug, Clone, Copy)]
170 struct Sections<'a> {
171 image: &'a [u8],
172 sections: &'a [Section],
173 }
174
175 impl<'a> Sections<'a> {
176 pub fn parse(image: &'a [u8]) -> Option<Self> {
177 let sig_offset = Ref::<_, U32>::new_unaligned(image.get(0x3c..0x40)?)?.get() as usize;
178 // Offset to the COFF header
179 let coff_image = image.get(sig_offset + 4..)?;
180 let section_count = Ref::<_, U16>::new_unaligned(coff_image.get(2..4)?)?.get() as usize;
181 let size_of_optional_header =
182 Ref::<_, U16>::new_unaligned(coff_image.get(16..18)?)?.get() as usize;
183 let sections = Ref::<_, [Section]>::new_slice_unaligned_from_prefix(
184 &coff_image[20 + size_of_optional_header..],
185 section_count,
186 )?
187 .0
188 .into_slice();
189 Some(Sections { image, sections })
190 }
191
192 pub fn memory_at_rva(&self, rva: u32) -> Option<&'a [u8]> {
193 let section_index = match self
194 .sections
195 .binary_search_by_key(&rva, |s| s.virtual_address.get())
196 {
197 Ok(i) => i,
198 Err(i)
199 if i > 0
200 && rva
201 < self.sections[i - 1].virtual_address.get()
202 + self.sections[i - 1].virtual_size.get() =>
203 {
204 i - 1
205 }
206 Err(_) => return None,
207 };
208 let section = &self.sections[section_index];
209 let start = section.pointer_to_raw_data.get() as usize;
210 let offset = (rva - section.virtual_address.get()) as usize;
211 Some(&self.image[start + offset..])
212 }
213 }
214
215 #[derive(Unaligned, FromZeroes, FromBytes, Debug, Clone, Copy)]
216 #[repr(C)]
217 struct Section {
218 _name: [u8; 8],
219 virtual_size: U32,
220 virtual_address: U32,
221 _size_of_raw_data: U32,
222 pointer_to_raw_data: U32,
223 _pointer_to_relocations: U32,
224 _pointer_to_line_numbers: U32,
225 _number_of_relocations: U16,
226 _number_of_line_numbers: U16,
227 _characteristics: U32,
228 }
229
230 /// A general-purpose register.
231 ///
232 /// If converted to a u8, the resulting value matches those in the x86_64 spec for register
233 /// operands as well as the operation info bits in unwind codes.
234 #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
235 #[repr(u8)]
236 pub enum Register {
237 RAX,
238 RCX,
239 RDX,
240 RBX,
241 RSP,
242 RBP,
243 RSI,
244 RDI,
245 R8,
246 R9,
247 R10,
248 R11,
249 R12,
250 R13,
251 R14,
252 R15,
253 }
254
255 impl TryFrom<u8> for Register {
256 type Error = ();
257 #[inline(always)]
258 fn try_from(reg: u8) -> Result<Self, ()> {
259 let reg = match reg {
260 0 => Self::RAX,
261 1 => Self::RCX,
262 2 => Self::RDX,
263 3 => Self::RBX,
264 4 => Self::RSP,
265 5 => Self::RBP,
266 6 => Self::RSI,
267 7 => Self::RDI,
268 8 => Self::R8,
269 9 => Self::R9,
270 10 => Self::R10,
271 11 => Self::R11,
272 12 => Self::R12,
273 13 => Self::R13,
274 14 => Self::R14,
275 15 => Self::R15,
276 _ => return Err(()),
277 };
278 Ok(reg)
279 }
280 }
281
282 /// A 128-bit XMM register.
283 #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
284 #[repr(u8)]
285 pub enum XmmRegister {
286 XMM0,
287 XMM1,
288 XMM2,
289 XMM3,
290 XMM4,
291 XMM5,
292 XMM6,
293 XMM7,
294 XMM8,
295 XMM9,
296 XMM10,
297 XMM11,
298 XMM12,
299 XMM13,
300 XMM14,
301 XMM15,
302 }
303
304 impl TryFrom<u8> for XmmRegister {
305 type Error = ();
306 #[inline(always)]
307 fn try_from(reg: u8) -> Result<Self, ()> {
308 let reg = match reg {
309 0 => Self::XMM0,
310 1 => Self::XMM1,
311 2 => Self::XMM2,
312 3 => Self::XMM3,
313 4 => Self::XMM4,
314 5 => Self::XMM5,
315 6 => Self::XMM6,
316 7 => Self::XMM7,
317 8 => Self::XMM8,
318 9 => Self::XMM9,
319 10 => Self::XMM10,
320 11 => Self::XMM11,
321 12 => Self::XMM12,
322 13 => Self::XMM13,
323 14 => Self::XMM14,
324 15 => Self::XMM15,
325 _ => return Err(()),
326 };
327 Ok(reg)
328 }
329 }
330
331 /// Fixed data at the start of [PE UnwindInfo][unwindinfo].
332 ///
333 /// [unwindinfo]: https://learn.microsoft.com/en-us/cpp/build/exception-handling-x64?view=msvc-170#struct-unwind_info
334 #[derive(Unaligned, FromZeroes, FromBytes, Debug, Clone, Copy)]
335 #[repr(C)]
336 pub struct UnwindInfoHeader {
337 /// The unwind information version and flags.
338 pub version_and_flags: u8,
339 /// The length of the function prolog, in bytes.
340 pub prolog_size: u8,
341 /// The number of u16 slots in the unwind codes array.
342 pub unwind_codes_len: u8,
343 /// The frame register and offset.
344 pub frame_register_and_offset: u8,
345 }
346
347 bitflags::bitflags! {
348 /// The unwind info bit flags.
349 ///
350 /// Note that while they are individual bits, it seems as if they can only be
351 /// mutually-exclusive.
352 #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
353 pub struct UnwindInfoFlags: u8 {
354 /// The function has an exception handler that should be called when looking for functions
355 /// that need to examine exceptions.
356 const EHANDLER = 0x1;
357 /// The function has a termination handler that should be called when unwinding an
358 /// exception.
359 const UHANDLER = 0x2;
360 /// This unwind info structure is not the primary one for the procedure. Instead, the
361 /// chained unwind info entry is the contents of a previous RuntimeFunction entry. If this
362 /// flag is set, then the EHANDLER and UHANDLER flags must be cleared. Also, the frame
363 /// register and fixed-stack allocation fields must have the same values as in the primary
364 /// unwind info.
365 const CHAININFO = 0x4;
366 }
367 }
368
369 impl UnwindInfoHeader {
370 /// The UnwindInfo version. Should be `1`.
371 #[inline]
372 pub fn version(&self) -> u8 {
373 self.version_and_flags & 0x7
374 }
375
376 /// The raw flags bits.
377 #[inline]
378 pub fn flags_raw(&self) -> u8 {
379 self.version_and_flags >> 3
380 }
381
382 /// The raw frame register value.
383 #[inline]
384 pub fn frame_register_raw(&self) -> u8 {
385 self.frame_register_and_offset & 0xf
386 }
387
388 /// The raw frame register offset value.
389 #[inline]
390 pub fn frame_register_offset_raw(&self) -> u8 {
391 self.frame_register_and_offset >> 4
392 }
393
394 /// The unwind info flags.
395 pub fn flags(&self) -> UnwindInfoFlags {
396 UnwindInfoFlags::from_bits_truncate(self.flags_raw())
397 }
398
399 /// The frame register, if any.
400 pub fn frame_register(&self) -> Option<Register> {
401 let reg = self.frame_register_raw();
402 (reg != 0).then_some(
403 reg.try_into()
404 .expect("reg is <= 15 so this always succeeds"),
405 )
406 }
407
408 /// The scaled frame register offset.
409 pub fn frame_register_offset(&self) -> u8 {
410 // u8 is appropriate as the maximum value is 15 * 16 = 240
411 self.frame_register_offset_raw() * 16
412 }
413
414 /// Get an absolute address from the given StackFrameOffset.
415 pub fn resolve_offset<F>(&self, read_register: F, offset: StackFrameOffset) -> u64
416 where
417 F: FnOnce(Register) -> u64,
418 {
419 match self.frame_register() {
420 Some(reg) => read_register(reg) - self.frame_register_offset() as u64 + offset.0 as u64,
421 None => read_register(Register::RSP) + offset.0 as u64,
422 }
423 }
424
425 /// Perform the given UnwindOperation, changing `state` appropriately.
426 ///
427 /// Returns `None` when reading the stack fails.
428 pub fn resolve_operation<S: UnwindState>(
429 &self,
430 state: &mut S,
431 op: &UnwindOperation,
432 ) -> Option<ControlFlow<u64>> {
433 match op {
434 UnwindOperation::PopNonVolatile(reg) => {
435 let rsp = state.read_register(Register::RSP);
436 let value = state.read_stack(rsp)?;
437 state.write_register(*reg, value);
438 state.write_register(Register::RSP, rsp + 8);
439 }
440 UnwindOperation::UnStackAlloc(bytes) => {
441 let rsp = state.read_register(Register::RSP);
442 state.write_register(Register::RSP, rsp + *bytes as u64);
443 }
444 UnwindOperation::RestoreSPFromFP => {
445 if let Some(reg) = self.frame_register() {
446 let value = state.read_register(reg) - self.frame_register_offset() as u64;
447 state.write_register(Register::RSP, value);
448 }
449 }
450 UnwindOperation::ReadNonVolatile(reg, offset) => {
451 let addr = self.resolve_offset(|reg| state.read_register(reg), *offset);
452 let value = state.read_stack(addr)?;
453 state.write_register(*reg, value);
454 }
455 UnwindOperation::ReadXMM(reg, offset) => {
456 let addr = self.resolve_offset(|reg| state.read_register(reg), *offset);
457 let value =
458 state.read_stack(addr)? as u128 | ((state.read_stack(addr + 8)? as u128) << 64);
459 state.write_xmm_register(*reg, value);
460 }
461 UnwindOperation::PopMachineFrame { error_code } => {
462 let offset = if *error_code { 8 } else { 0 };
463 let rsp = state.read_register(Register::RSP);
464 let return_address = state.read_stack(rsp + offset)?;
465 let rsp = state.read_stack(rsp + offset + 24)?;
466 state.write_register(Register::RSP, rsp);
467 return Some(ControlFlow::Break(return_address));
468 }
469 }
470
471 Some(ControlFlow::Continue(()))
472 }
473 }
474
475 /// A virtual instruction in the function epilog, interpreted from x86_64 instructions.
476 #[derive(Debug, Clone, Copy)]
477 pub enum FunctionEpilogInstruction {
478 /// Add the given offset to the stack pointer.
479 AddSP(u32),
480 /// Add the given offset to the frame pointer to recover the stack pointer.
481 AddSPFromFP(u32),
482 /// Pop a value from the stack into the given register.
483 Pop(Register),
484 }
485
486 /// An error resulting from an attempt at parsing an epilog instruction.
487 #[derive(Error, Debug)]
488 pub enum InstructionParseError {
489 #[error("not enough data")]
490 NotEnoughData,
491 #[error("invalid instruction found")]
492 InvalidInstruction,
493 #[error("too many instructions for epilog")]
494 TooManyInstructions,
495 }
496
497 /// The maximum number of instructions to allow when parsing a function epilog.
498 ///
499 /// There is at most one AddSP/AddSPFromFP, and only 8 caller-saved registers (disregarding the
500 /// implicit RSP). We give a bit of extra space just in case, but it shouldn't be necessary.
501 pub const FUNCTION_EPILOG_LIMIT: usize = 12;
502
503 impl FunctionEpilogInstruction {
504 /// Parse a function epilog instruction.
505 ///
506 /// Returns Ok(None) if the instruction is an epilog terminator (`ret` or `jmp`).
507 ///
508 /// `allow_add_sp` should only be true for the (potential) first instruction in an epilog.
509 pub fn parse(
510 ip: &[u8],
511 fpreg: Option<Register>,
512 allow_add_sp: bool,
513 ) -> Result<Option<(Self, &[u8])>, InstructionParseError> {
514 if ip.is_empty() {
515 return Err(InstructionParseError::NotEnoughData);
516 }
517
518 // Read REX instruction byte if present.
519 let (rex, ip) = if ip[0] & 0xf0 == 0x40 {
520 (ip[0] & 0x0f, &ip[1..])
521 } else {
522 (0, &ip[0..])
523 };
524
525 // Both add and lea need at least 3 bytes after REX
526 if allow_add_sp && ip.len() >= 3 {
527 // add RSP,imm32
528 if rex & 0x8 != 0 && ip[0] == 0x81 && ip[1] == 0xc4 {
529 let (val, rest) = Ref::<_, U32>::new_unaligned_from_prefix(&ip[2..])
530 .ok_or(InstructionParseError::NotEnoughData)?;
531 return Ok(Some((FunctionEpilogInstruction::AddSP(val.get()), rest)));
532 }
533 // add RSP,imm8
534 if rex & 0x8 != 0 && ip[0] == 0x83 && ip[1] == 0xc4 {
535 return Ok(Some((
536 FunctionEpilogInstruction::AddSP(ip[2] as u32),
537 &ip[3..],
538 )));
539 }
540
541 if let Some(fpreg) = fpreg {
542 let fpreg = fpreg as u8;
543 if rex & 0x8 != 0 && (rex & 0x1 == fpreg >> 3) && ip[0] == 0x8d {
544 if ip[1] & 0x3f == (0x20 | (fpreg & 0b0111)) {
545 let op_mod = ip[1] >> 6;
546 // lea RSP,disp8[FP]
547 if op_mod == 0b01 {
548 return Ok(Some((
549 FunctionEpilogInstruction::AddSPFromFP(ip[2] as u32),
550 &ip[3..],
551 )));
552 // lea RSP,disp32[FP]
553 } else if op_mod == 0b10 {
554 let (val, rest) = Ref::<_, U32>::new_unaligned_from_prefix(&ip[2..])
555 .ok_or(InstructionParseError::NotEnoughData)?;
556 return Ok(Some((
557 FunctionEpilogInstruction::AddSPFromFP(val.get()),
558 rest,
559 )));
560 } else {
561 // Invalid op_mod
562 return Err(InstructionParseError::InvalidInstruction);
563 }
564 } else {
565 // Invalid lea
566 return Err(InstructionParseError::InvalidInstruction);
567 }
568 }
569 }
570 }
571
572 // pop r/m64
573 if ip.len() >= 2 && ip[0] == 0x8f && ip[1] & 0xf8 == 0xc0 {
574 let reg = ip[1] & 0x7 | ((rex & 1) << 3);
575 return Ok(Some((
576 FunctionEpilogInstruction::Pop(
577 reg.try_into().expect(
578 "`reg` is between 0 and 15, which are defined values of `Register`.",
579 ),
580 ),
581 &ip[2..],
582 )));
583 }
584 // pop r64
585 if !ip.is_empty() && ip[0] & 0xf8 == 0x58 {
586 let reg = ip[0] & 0x7 | ((rex & 1) << 3);
587 debug_assert!(reg <= 15);
588 return Ok(Some((
589 FunctionEpilogInstruction::Pop(
590 reg.try_into().expect(
591 "`reg` is between 0 and 15, which are defined values of `Register`.",
592 ),
593 ),
594 &ip[1..],
595 )));
596 }
597
598 // ret
599 if !ip.is_empty() && ip[0] == 0xc3 {
600 return Ok(None);
601 }
602
603 if ip.len() >= 2 {
604 // jmp with relative displacements
605 //
606 // The MS docs say epilogs only have jmp instructions with a ModRM byte, but I've seen
607 // relative displacement jmps too (tail calls).
608 if ip[0] == 0xeb || ip[0] == 0xe9 {
609 return Ok(None);
610 }
611 // jmp with ModRM and mod bits as 00
612 if ip[0] == 0xff {
613 let mod_opcode = ip[1] & 0xf8;
614 if mod_opcode == 0x20 || mod_opcode == 0x28 {
615 return Ok(None);
616 } else {
617 return Err(InstructionParseError::InvalidInstruction);
618 }
619 }
620 }
621
622 // not a valid epilog instruction
623 Err(InstructionParseError::InvalidInstruction)
624 }
625
626 /// Check whether a series of instructions are a tail of a function epilog
627 /// and parse them into a limited sequence of epilog instructions.
628 ///
629 /// This function does not allocate memory; the result is stored in a
630 /// fixed-capacity `ArrayVec`.
631 ///
632 /// Returns `Err` if too many instructions were encountered or if the
633 /// instructions do not appear to be a function epilog.
634 ///
635 /// [Epilogs][] look like:
636 /// * `add RSP,<constant>` or `lea RSP,constant[FPReg]`
637 /// * zero or more `pop <GPREG>`
638 /// * `ret` or `jmp` with a ModRM argument with mod field 00
639 ///
640 /// [Epilogs]: https://learn.microsoft.com/en-us/cpp/build/prolog-and-epilog?view=msvc-170#epilog-code
641 pub fn parse_sequence(
642 ip: &[u8],
643 frame_register: Option<Register>,
644 ) -> Result<ArrayVec<Self, FUNCTION_EPILOG_LIMIT>, InstructionParseError> {
645 let mut buffer = ArrayVec::new();
646 let mut instruction_and_rest = Self::parse(ip, frame_register, true)?;
647
648 while let Some((instruction, rest)) = instruction_and_rest {
649 buffer
650 .try_push(instruction)
651 .map_err(|_| InstructionParseError::TooManyInstructions)?;
652
653 instruction_and_rest = Self::parse(rest, frame_register, false)?
654 }
655
656 Ok(buffer)
657 }
658 }
659
660 /// An interface over state needed for unwinding stack frames.
661 pub trait UnwindState {
662 /// Return the value of the given register.
663 fn read_register(&mut self, register: Register) -> u64;
664 /// Return the 8-byte value at the given address on the stack, if any.
665 fn read_stack(&mut self, addr: u64) -> Option<u64>;
666 /// Write a new value to the given register, updating the unwind context.
667 fn write_register(&mut self, register: Register, value: u64);
668 /// Write a new value to the given xmm register, updating the unwind context.
669 fn write_xmm_register(&mut self, register: XmmRegister, value: u128);
670 }
671
672 /// Optional information at the end of UnwindInfo.
673 pub enum UnwindInfoTrailer<'a> {
674 /// There is an exception handler associated with this unwind info.
675 ExceptionHandler {
676 handler_address: &'a U32,
677 handler_data: &'a [u8],
678 },
679 /// There is a termination handler associated with this unwind info.
680 TerminationHandler {
681 handler_address: &'a U32,
682 handler_data: &'a [u8],
683 },
684 /// There is a chained unwind info entry associated with this unwind info.
685 ChainedUnwindInfo { chained: &'a RuntimeFunction },
686 }
687
688 /// A function's unwind information.
689 #[derive(Clone, Copy)]
690 pub struct UnwindInfo<'a> {
691 header: &'a UnwindInfoHeader,
692 unwind_codes: &'a [u8],
693 rest: &'a [u8],
694 }
695
696 impl std::fmt::Debug for UnwindInfo<'_> {
697 fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
698 f.debug_struct("UnwindInfo")
699 .field("header", self.header)
700 .field("unwind_codes", &self.unwind_codes)
701 .finish_non_exhaustive()
702 }
703 }
704
705 impl<'a> UnwindInfo<'a> {
706 /// Read the unwind info from the given buffer.
707 ///
708 /// Returns None if there aren't enough bytes or the alignment is incorrect.
709 pub fn parse(data: &'a [u8]) -> Option<Self> {
710 let (header, rest) = Ref::<_, UnwindInfoHeader>::new_unaligned_from_prefix(data)?;
711 if header.version() != 1 {
712 return None;
713 }
714 let (unwind_codes, rest) =
715 Ref::new_slice_unaligned_from_prefix(rest, header.unwind_codes_len as usize * 2)?;
716 Some(UnwindInfo {
717 header: header.into_ref(),
718 unwind_codes: unwind_codes.into_slice(),
719 rest,
720 })
721 }
722
723 /// Get an iterator over the unwind operations.
724 pub fn unwind_operations(&self) -> UnwindOperations<'a> {
725 UnwindOperations(self.unwind_codes)
726 }
727
728 /// Get the trailing information of the unwind info, if any.
729 pub fn trailer(&self) -> Option<UnwindInfoTrailer<'a>> {
730 let flags = self.flags();
731 if flags.contains(UnwindInfoFlags::EHANDLER) {
732 let (handler_address, handler_data) =
733 Ref::<_, U32>::new_unaligned_from_prefix(self.rest)?;
734 Some(UnwindInfoTrailer::ExceptionHandler {
735 handler_address: handler_address.into_ref(),
736 handler_data,
737 })
738 } else if flags.contains(UnwindInfoFlags::UHANDLER) {
739 let (handler_address, handler_data) =
740 Ref::<_, U32>::new_unaligned_from_prefix(self.rest)?;
741 Some(UnwindInfoTrailer::TerminationHandler {
742 handler_address: handler_address.into_ref(),
743 handler_data,
744 })
745 } else if flags.contains(UnwindInfoFlags::CHAININFO) {
746 let (chained, _) = Ref::<_, RuntimeFunction>::new_unaligned_from_prefix(self.rest)?;
747 Some(UnwindInfoTrailer::ChainedUnwindInfo {
748 chained: chained.into_ref(),
749 })
750 } else {
751 None
752 }
753 }
754 }
755
756 impl std::ops::Deref for UnwindInfo<'_> {
757 type Target = UnwindInfoHeader;
758
759 fn deref(&self) -> &Self::Target {
760 self.header
761 }
762 }
763
764 /// An iterator over `UnwindOperation`s.
765 ///
766 /// This iterator parses the operations as it iterates, since it needs to parse them to know how
767 /// many slots each takes up.
768 #[derive(Clone, Copy, Debug)]
769 pub struct UnwindOperations<'a>(&'a [u8]);
770
771 impl<'a> UnwindOperations<'a> {
772 /// Get the current `UnwindCode`.
773 pub fn unwind_code(&self) -> Option<&'a UnwindCode> {
774 let mut c = *self;
775 c.read::<UnwindCode>()
776 }
777
778 fn read<T: Unaligned + FromBytes>(&mut self) -> Option<&'a T> {
779 let (v, rest) = Ref::<_, T>::new_unaligned_from_prefix(self.0)?;
780 self.0 = rest;
781 Some(v.into_ref())
782 }
783 }
784
785 impl<'a> Iterator for UnwindOperations<'a> {
786 type Item = (u8, UnwindOperation);
787
788 fn next(&mut self) -> Option<Self::Item> {
789 let unwind_code = self.read::<UnwindCode>()?;
790 let op = match unwind_code.operation_code()? {
791 UnwindOperationCode::PushNonvol => {
792 UnwindOperation::PopNonVolatile(unwind_code.operation_info_as_register())
793 }
794 UnwindOperationCode::AllocLarge => match unwind_code.operation_info() {
795 0 => UnwindOperation::UnStackAlloc(self.read::<U16>()?.get() as u32 * 8),
796 1 => UnwindOperation::UnStackAlloc(self.read::<U32>()?.get()),
797 _ => return None,
798 },
799 UnwindOperationCode::AllocSmall => {
800 UnwindOperation::UnStackAlloc((unwind_code.operation_info() as u32 + 1) * 8)
801 }
802 UnwindOperationCode::SetFPReg => UnwindOperation::RestoreSPFromFP,
803 UnwindOperationCode::SaveNonvol => UnwindOperation::ReadNonVolatile(
804 unwind_code.operation_info_as_register(),
805 StackFrameOffset(self.read::<U16>()?.get() as u32 * 8),
806 ),
807 UnwindOperationCode::SaveNonvolFar => UnwindOperation::ReadNonVolatile(
808 unwind_code.operation_info_as_register(),
809 StackFrameOffset(self.read::<U32>()?.get()),
810 ),
811 UnwindOperationCode::SaveXmm128 => UnwindOperation::ReadXMM(
812 unwind_code.operation_info_as_xmm(),
813 StackFrameOffset(self.read::<U16>()?.get() as u32 * 16),
814 ),
815 UnwindOperationCode::SaveXmm128Far => UnwindOperation::ReadXMM(
816 unwind_code.operation_info_as_xmm(),
817 StackFrameOffset(self.read::<U32>()?.get()),
818 ),
819 UnwindOperationCode::PushMachframe => UnwindOperation::PopMachineFrame {
820 error_code: unwind_code.operation_info() == 1,
821 },
822 };
823
824 Some((unwind_code.prolog_offset, op))
825 }
826 }
827
828 /// An offset relative to the local stack frame.
829 #[derive(Debug, Clone, Copy)]
830 pub struct StackFrameOffset(u32);
831
832 /// An unwind operation to perform.
833 ///
834 /// These generally correspond to `UnwindOperationCode`s, however they are named based on the
835 /// operation that needs to be done to unwind.
836 #[derive(Debug, Clone, Copy)]
837 pub enum UnwindOperation {
838 /// Restore a register's value by popping from the stack (incrementing RSP by 8).
839 PopNonVolatile(Register),
840 /// Undo a stack allocation of the given size (incrementing RSP).
841 UnStackAlloc(u32),
842 /// Use the frame pointer register to restore RSP. The stack pointer should be restored from
843 /// the frame pointer minus UnwindInfo::frame_register_offset().
844 RestoreSPFromFP,
845 /// Restore a register's value from the given stack frame offset.
846 ReadNonVolatile(Register, StackFrameOffset),
847 /// Restore an XMM register's value from the given stack frame offset.
848 ReadXMM(XmmRegister, StackFrameOffset),
849 /// Pop a machine frame. This restores from the stack an optional error code, and then (in
850 /// order from lowest to highest addresses) IP, CS, EFLAGS, the old SP, and SS.
851 PopMachineFrame { error_code: bool },
852 }
853
854 /// An operation represented by an `UnwindCode`.
855 #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
856 #[repr(u8)]
857 pub enum UnwindOperationCode {
858 PushNonvol,
859 AllocLarge,
860 AllocSmall,
861 SetFPReg,
862 SaveNonvol,
863 SaveNonvolFar,
864 SaveXmm128 = 8,
865 SaveXmm128Far,
866 PushMachframe,
867 }
868
869 /// A single step to unwind operations done in a frame's prolog.
870 #[derive(Unaligned, FromZeroes, FromBytes, Debug, Clone, Copy)]
871 #[repr(C)]
872 pub struct UnwindCode {
873 /// The byte offset into the prolog where the operation was done.
874 pub prolog_offset: u8,
875 /// The operation code and info.
876 pub opcode_and_opinfo: u8,
877 }
878
879 impl UnwindCode {
880 /// Get the raw operation code.
881 #[inline]
882 pub fn operation_code_raw(&self) -> u8 {
883 self.opcode_and_opinfo & 0xf
884 }
885
886 /// Get the operation information bits.
887 #[inline]
888 pub fn operation_info(&self) -> u8 {
889 self.opcode_and_opinfo >> 4
890 }
891
892 /// Get the operation code.
893 pub fn operation_code(&self) -> Option<UnwindOperationCode> {
894 match self.operation_code_raw() {
895 0 => Some(UnwindOperationCode::PushNonvol),
896 1 => Some(UnwindOperationCode::AllocLarge),
897 2 => Some(UnwindOperationCode::AllocSmall),
898 3 => Some(UnwindOperationCode::SetFPReg),
899 4 => Some(UnwindOperationCode::SaveNonvol),
900 5 => Some(UnwindOperationCode::SaveNonvolFar),
901 8 => Some(UnwindOperationCode::SaveXmm128),
902 9 => Some(UnwindOperationCode::SaveXmm128Far),
903 10 => Some(UnwindOperationCode::PushMachframe),
904 _ => None,
905 }
906 }
907
908 /// Interpret the operation info as a register.
909 #[inline]
910 fn operation_info_as_register(&self) -> Register {
911 let op_info = self.operation_info();
912 op_info
913 .try_into()
914 .expect("`op_info` is between 0 and 15, which are defined values of `Register`.")
915 }
916
917 /// Interpret the operation info as an Xmm register.
918 #[inline]
919 fn operation_info_as_xmm(&self) -> XmmRegister {
920 let op_info = self.operation_info();
921 op_info
922 .try_into()
923 .expect("`op_info` is between 0 and 15, which are defined values of `XmmRegister`.")
924 }
925 }
926
927 #[cfg(test)]
928 mod tests {
929 use super::*;
930
931 use hex_literal::hex;
932 use memmap2::Mmap;
933 use object::read::{File, Object, ObjectSection};
934 use std::sync::OnceLock;
935
936 static FIXTURE: OnceLock<Mmap> = OnceLock::new();
937 const FIXTURE_ADDRESS: u64 = 0x7ff725bf0000;
938
939 fn get_fixture() -> &'static [u8] {
940 FIXTURE.get_or_init(|| unsafe {
941 Mmap::map(
942 &std::fs::File::open(concat!(
943 env!("CARGO_MANIFEST_DIR"),
944 "/fixture/binary/x86_64.exe"
945 ))
946 .unwrap(),
947 )
948 .unwrap()
949 })
950 }
951
952 struct FrameContext {
953 registers: [u64; 16],
954 ip: u64,
955 stack: &'static [u8],
956 stack_base: u64,
957
958 pub changes: RegisterChanges,
959 }
960
961 #[derive(Default, Debug, Clone, PartialEq, Eq)]
962 struct RegisterChanges {
963 changes: [Option<u64>; 16],
964 }
965
966 impl RegisterChanges {
967 pub fn new() -> Self {
968 Self::default()
969 }
970
971 pub fn set(mut self, reg: Register, value: u64) -> Self {
972 self.changes[reg as usize] = Some(value);
973 self
974 }
975 }
976
977 impl UnwindState for FrameContext {
978 fn read_register(&mut self, register: Register) -> u64 {
979 self.registers[register as usize]
980 }
981
982 fn read_stack(&mut self, addr: u64) -> Option<u64> {
983 if addr > self.stack_base {
984 return None;
985 }
986 let offset = self.stack_base - addr;
987 let offset = offset as usize;
988 if offset < 8 || offset > self.stack.len() {
989 return None;
990 }
991 let index = self.stack.len() - offset;
992 Some(u64::from_le_bytes(
993 (&self.stack[index..index + 8]).try_into().unwrap(),
994 ))
995 }
996
997 fn write_register(&mut self, register: Register, value: u64) {
998 self.registers[register as usize] = value;
999 self.changes.changes[register as usize] = Some(value);
1000 }
1001
1002 fn write_xmm_register(&mut self, _register: XmmRegister, _value: u128) {
1003 unimplemented!()
1004 }
1005 }
1006
1007 macro_rules! windbg_frame_context {
1008 ( rax = $rax:literal rbx = $rbx:literal rcx = $rcx:literal
1009 rdx = $rdx:literal rsi = $rsi:literal rdi = $rdi:literal
1010 rip = $rip:literal rsp = $rsp:literal rbp = $rbp:literal
1011 r8 = $r8:literal r9 = $r9:literal r10 = $r10:literal
1012 r11 = $r11:literal r12 = $r12:literal r13 = $r13:literal
1013 r14 = $r14:literal r15 = $r15:literal
1014 stack_base = $stack_base:literal
1015 stack = $stack:literal
1016 ) => {
1017 FrameContext {
1018 registers: [
1019 $rax, $rcx, $rdx, $rbx, $rsp, $rbp, $rsi, $rdi, $r8, $r9, $r10, $r11, $r12,
1020 $r13, $r14, $r15,
1021 ],
1022 ip: $rip,
1023 stack: &hex!($stack),
1024 stack_base: $stack_base,
1025 changes: Default::default(),
1026 }
1027 };
1028 }
1029
1030 fn assert_fixture_unwind(mut context: FrameContext, ra: u64, changes: RegisterChanges) {
1031 let file = File::parse(get_fixture()).unwrap();
1032 let pdata_section = file.section_by_name(".pdata").unwrap();
1033 let entries = FunctionTableEntries::parse(pdata_section.data().unwrap());
1034 let ip_offset = (context.ip - FIXTURE_ADDRESS) as u32;
1035 let result = entries.unwind_frame_with_image(&mut context, get_fixture(), ip_offset);
1036 assert_eq!(result, Some(ra), "mismatched return address");
1037 assert_eq!(context.changes, changes, "mismatched register changes");
1038 }
1039
1040 fn assert_fixture_frames(mut context: FrameContext, return_addrs: &[u64]) {
1041 let file = File::parse(get_fixture()).unwrap();
1042 let pdata_section = file.section_by_name(".pdata").unwrap();
1043 let entries = FunctionTableEntries::parse(pdata_section.data().unwrap());
1044
1045 let mut ip = context.ip;
1046 for ra in return_addrs {
1047 let ip_offset = (ip - FIXTURE_ADDRESS) as u32;
1048 let result = entries.unwind_frame_with_image(&mut context, get_fixture(), ip_offset);
1049 assert_eq!(result, Some(*ra), "mismatched return address");
1050 ip = ra - 1;
1051 }
1052 }
1053
1054 #[test]
1055 fn unwind_frame_1() {
1056 let context = windbg_frame_context! {
1057 rax=0x000000000000001e rbx=0x0000020891345770 rcx=0x000000000000000a
1058 rdx=0x0000000000000001 rsi=0x0000000000000001 rdi=0x0000020891349e40
1059 rip=0x00007ff725bf1084 rsp=0x00000070c7d3fb38 rbp=0x0000000000000000
1060 r8=0x0000020891349e40 r9=0x0000000000000630 r10=0x0000000000000630
1061 r11=0x00000070c7d3f7f0 r12=0x0000000000000000 r13=0x0000000000000000
1062 r14=0x0000000000000000 r15=0x0000000000000000
1063 stack_base = 0x70c7d3fba0
1064 stack = "21 10 BF 25 F7 7F 00 00
1065 01 00 00 00 00 00 00 00 03 00 00 00 00 00 00 00
1066 02 00 00 00 00 00 00 00 39 72 C0 25 F7 7F 00 00
1067 70 57 34 91 08 02 00 00 40 9E 34 91 08 02 00 00
1068 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
1069 00 00 00 00 00 00 00 00 90 6F C0 25 F7 7F 00 00
1070 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00"
1071 };
1072 assert_fixture_unwind(
1073 context,
1074 0x7ff725bf1021,
1075 RegisterChanges::new().set(Register::RSP, 0x70c7d3fb38 + 8),
1076 );
1077 }
1078
1079 #[test]
1080 fn unwind_frame_2() {
1081 let context = windbg_frame_context! {
1082 rax=0x0000000000000026 rbx=0x000000000000006b rcx=0x0000000000000002
1083 rdx=0x0000000000000026 rsi=0x0000000000000001 rdi=0x000000000000001f
1084 rip=0x00007ff725bf10b6 rsp=0x00000070c7d3fb38 rbp=0x0000000000000000
1085 r8=0x0000000000000002 r9=0x0000000000000000 r10=0x000000000000001f
1086 r11=0x00000070c7d3f7f0 r12=0x0000000000000000 r13=0x0000000000000000
1087 r14=0x0000000000000026 r15=0x0000000000000003
1088 stack_base = 0x70c7d3fba0
1089 stack = "4F 10 BF 25 F7 7F 00 00
1090 01 00 00 00 00 00 00 00 03 00 00 00 00 00 00 00
1091 02 00 00 00 00 00 00 00 39 72 C0 25 F7 7F 00 00
1092 70 57 34 91 08 02 00 00 40 9E 34 91 08 02 00 00
1093 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
1094 00 00 00 00 00 00 00 00 90 6F C0 25 F7 7F 00 00
1095 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00"
1096 };
1097 assert_fixture_unwind(
1098 context,
1099 0x7ff725bf104f,
1100 RegisterChanges::new().set(Register::RSP, 0x70c7d3fb38 + 8),
1101 );
1102 }
1103
1104 #[test]
1105 fn unwind_frame_in_prolog() {
1106 let context = windbg_frame_context! {
1107 rax=0x00007ffa222c07a8 rbx=0x0000020891345770 rcx=0x0000000000000001
1108 rdx=0x0000020891345770 rsi=0x0000000000000000 rdi=0x0000020891349e40
1109 rip=0x00007ff725bf1005 rsp=0x00000070c7d3fb70 rbp=0x0000000000000000
1110 r8=0x0000020891349e40 r9=0x0000000000000630 r10=0x0000000000000630
1111 r11=0x00000070c7d3f7f0 r12=0x0000000000000000 r13=0x0000000000000000
1112 r14=0x0000000000000000 r15=0x0000000000000000
1113 stack_base = 0x70c7d3fba0
1114 stack = "
1115 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
1116 00 00 00 00 00 00 00 00 90 6F C0 25 F7 7F 00 00
1117 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00"
1118 };
1119 assert_fixture_unwind(
1120 context,
1121 0x7ff725c06f90,
1122 RegisterChanges::new()
1123 .set(Register::RSI, 0)
1124 .set(Register::R14, 0)
1125 .set(Register::R15, 0)
1126 .set(Register::RSP, 0x70c7d3fb70 + 8 * 4),
1127 );
1128 }
1129
1130 #[test]
1131 fn unwind_frame_in_epilog_beginning() {
1132 let context = windbg_frame_context! {
1133 rax=0xf47e69ea626ba5db rbx=0x82bcd1c6ad5f6936 rcx=0x82bcd1c6ad5f6936
1134 rdx=0x0000000000000001 rsi=0x0000000000000001 rdi=0x000000000000001f
1135 rip=0x00007ff725bf1068 rsp=0x00000070c7d3fb40 rbp=0x0000000000000000
1136 r8=0x82bcd1c6ad5f6936 r9=0x0000000000000003 r10=0x0000000000000045
1137 r11=0x00000070c7d3f7f0 r12=0x0000000000000000 r13=0x0000000000000000
1138 r14=0x0000000000000026 r15=0x0000000000000064
1139 stack_base = 0x70c7d3fba0
1140 stack = "
1141 01 00 00 00 00 00 00 00 03 00 00 00 00 00 00 00
1142 02 00 00 00 00 00 00 00 39 72 C0 25 F7 7F 00 00
1143 70 57 34 91 08 02 00 00 40 9E 34 91 08 02 00 00
1144 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
1145 00 00 00 00 00 00 00 00 90 6F C0 25 F7 7F 00 00
1146 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00"
1147 };
1148 assert_fixture_unwind(
1149 context,
1150 0x7ff725c06f90,
1151 RegisterChanges::new()
1152 .set(Register::RBX, 0x20891345770)
1153 .set(Register::RDI, 0x20891349e40)
1154 .set(Register::RSI, 0)
1155 .set(Register::R14, 0)
1156 .set(Register::R15, 0)
1157 .set(Register::RSP, 0x70c7d3fb40 + 0x20 + 8 * 6),
1158 );
1159 }
1160
1161 #[test]
1162 fn unwind_frame_in_epilog_middle() {
1163 let context = windbg_frame_context! {
1164 rax=0xf47e69ea626ba5db rbx=0x0000020891345770 rcx=0x82bcd1c6ad5f6936
1165 rdx=0x0000000000000001 rsi=0x0000000000000000 rdi=0x0000020891349e40
1166 rip=0x00007ff725bf106f rsp=0x00000070c7d3fb78 rbp=0x0000000000000000
1167 r8=0x82bcd1c6ad5f6936 r9=0x0000000000000003 r10=0x0000000000000045
1168 r11=0x00000070c7d3f7f0 r12=0x0000000000000000 r13=0x0000000000000000
1169 r14=0x0000000000000026 r15=0x0000000000000064
1170 stack_base = 0x70c7d3fba0
1171 stack = "00 00 00 00 00 00 00 00
1172 00 00 00 00 00 00 00 00 90 6F C0 25 F7 7F 00 00
1173 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00"
1174 };
1175 assert_fixture_unwind(
1176 context,
1177 0x7ff725c06f90,
1178 RegisterChanges::new()
1179 .set(Register::R14, 0)
1180 .set(Register::R15, 0)
1181 .set(Register::RSP, 0x70c7d3fb78 + 8 * 3),
1182 );
1183 }
1184
1185 #[test]
1186 fn multiple_frames() {
1187 let context = windbg_frame_context! {
1188 rax=0x0000000000000026 rbx=0x000000000000006b rcx=0x0000000000000002
1189 rdx=0x0000000000000026 rsi=0x0000000000000001 rdi=0x000000000000001f
1190 rip=0x00007ff725bf10b6 rsp=0x00000070c7d3fb38 rbp=0x0000000000000000
1191 r8=0x0000000000000002 r9=0x0000000000000000 r10=0x000000000000001f
1192 r11=0x00000070c7d3f7f0 r12=0x0000000000000000 r13=0x0000000000000000
1193 r14=0x0000000000000026 r15=0x0000000000000003
1194 stack_base = 0x70c7d3fba0
1195 stack = "4F 10 BF 25 F7 7F 00 00
1196 01 00 00 00 00 00 00 00 03 00 00 00 00 00 00 00
1197 02 00 00 00 00 00 00 00 39 72 C0 25 F7 7F 00 00
1198 70 57 34 91 08 02 00 00 40 9E 34 91 08 02 00 00
1199 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
1200 00 00 00 00 00 00 00 00 90 6F C0 25 F7 7F 00 00
1201 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00"
1202 };
1203 assert_fixture_frames(context, &[0x7ff725bf104f, 0x7ff725c06f90]);
1204 }
1205 }