Debian Codegraph @

third_party/rust/framehop/src/x86_64/pe.rs

raw
1 use super::{
2 arch::ArchX86_64,
3 unwind_rule::{OffsetOrPop, UnwindRuleX86_64},
4 unwindregs::Reg,
5 };
6 use crate::arch::Arch;
7 use crate::pe::{PeSections, PeUnwinderError, PeUnwinding};
8 use crate::unwind_result::UnwindResult;
9 use core::ops::ControlFlow;
10
11 use alloc::vec::Vec;
12 use pe_unwind_info::x86_64::{
13 FunctionEpilogInstruction, FunctionTableEntries, Register, UnwindInfo, UnwindInfoTrailer,
14 UnwindOperation, UnwindState,
15 };
16
17 struct State<'a, F> {
18 regs: &'a mut <ArchX86_64 as Arch>::UnwindRegs,
19 read_stack: &'a mut F,
20 }
21
22 impl<F> UnwindState for State<'_, F>
23 where
24 F: FnMut(u64) -> Result<u64, ()>,
25 {
26 fn read_register(&mut self, register: Register) -> u64 {
27 self.regs.get(convert_pe_register(register))
28 }
29
30 fn read_stack(&mut self, addr: u64) -> Option<u64> {
31 (self.read_stack)(addr).ok()
32 }
33
34 fn write_register(&mut self, register: Register, value: u64) {
35 self.regs.set(convert_pe_register(register), value)
36 }
37
38 fn write_xmm_register(&mut self, _register: pe_unwind_info::x86_64::XmmRegister, _value: u128) {
39 // Ignore
40 }
41 }
42
43 fn convert_pe_register(r: Register) -> Reg {
44 match r {
45 Register::RAX => Reg::RAX,
46 Register::RCX => Reg::RCX,
47 Register::RDX => Reg::RDX,
48 Register::RBX => Reg::RBX,
49 Register::RSP => Reg::RSP,
50 Register::RBP => Reg::RBP,
51 Register::RSI => Reg::RSI,
52 Register::RDI => Reg::RDI,
53 Register::R8 => Reg::R8,
54 Register::R9 => Reg::R9,
55 Register::R10 => Reg::R10,
56 Register::R11 => Reg::R11,
57 Register::R12 => Reg::R12,
58 Register::R13 => Reg::R13,
59 Register::R14 => Reg::R14,
60 Register::R15 => Reg::R15,
61 }
62 }
63
64 impl From<&'_ FunctionEpilogInstruction> for OffsetOrPop {
65 fn from(value: &'_ FunctionEpilogInstruction) -> Self {
66 match value {
67 FunctionEpilogInstruction::AddSP(offset) => {
68 if let Ok(v) = (offset / 8).try_into() {
69 OffsetOrPop::OffsetBy8(v)
70 } else {
71 OffsetOrPop::None
72 }
73 }
74 FunctionEpilogInstruction::Pop(reg) => OffsetOrPop::Pop(convert_pe_register(*reg)),
75 _ => OffsetOrPop::None,
76 }
77 }
78 }
79
80 impl From<&'_ UnwindOperation> for OffsetOrPop {
81 fn from(value: &'_ UnwindOperation) -> Self {
82 match value {
83 UnwindOperation::UnStackAlloc(offset) => {
84 if let Ok(v) = (offset / 8).try_into() {
85 OffsetOrPop::OffsetBy8(v)
86 } else {
87 OffsetOrPop::None
88 }
89 }
90 UnwindOperation::PopNonVolatile(reg) => OffsetOrPop::Pop(convert_pe_register(*reg)),
91 _ => OffsetOrPop::None,
92 }
93 }
94 }
95
96 impl PeUnwinding for ArchX86_64 {
97 fn unwind_frame<F, D>(
98 sections: PeSections<D>,
99 address: u32,
100 regs: &mut Self::UnwindRegs,
101 is_first_frame: bool,
102 read_stack: &mut F,
103 ) -> Result<UnwindResult<Self::UnwindRule>, PeUnwinderError>
104 where
105 F: FnMut(u64) -> Result<u64, ()>,
106 D: core::ops::Deref<Target = [u8]>,
107 {
108 let entries = FunctionTableEntries::parse(sections.pdata);
109 let Some(function) = entries.lookup(address) else {
110 return Ok(UnwindResult::ExecRule(UnwindRuleX86_64::JustReturn));
111 };
112
113 let read_stack_err = |read_stack: &mut F, addr| {
114 read_stack(addr).map_err(|()| PeUnwinderError::MissingStackData(Some(addr)))
115 };
116
117 let unwind_info_address = function.unwind_info_address.get();
118 let unwind_info =
119 UnwindInfo::parse(sections.unwind_info_memory_at_rva(unwind_info_address)?)
120 .ok_or(PeUnwinderError::UnwindInfoParseError)?;
121
122 if is_first_frame {
123 // Check whether the address is in the function epilog. If so, we need to
124 // simulate the remaining epilog instructions (unwind codes don't account for
125 // unwinding from the epilog). We only need to check this for the first unwind info (if
126 // there are chained infos).
127 let bytes = (function.end_address.get() - address) as usize;
128 let instruction = &sections.text_memory_at_rva(address)?[..bytes];
129 if let Ok(epilog_instructions) =
130 FunctionEpilogInstruction::parse_sequence(instruction, unwind_info.frame_register())
131 {
132 // If the epilog is an optional AddSP followed by Pops, we can return a cache
133 // rule.
134 if let Some(rule) =
135 UnwindRuleX86_64::for_sequence_of_offset_or_pop(epilog_instructions.iter())
136 {
137 return Ok(UnwindResult::ExecRule(rule));
138 }
139
140 for instruction in epilog_instructions.iter() {
141 match instruction {
142 FunctionEpilogInstruction::AddSP(offset) => {
143 let rsp = regs.get(Reg::RSP);
144 regs.set(Reg::RSP, rsp + *offset as u64);
145 }
146 FunctionEpilogInstruction::AddSPFromFP(offset) => {
147 let fp = unwind_info
148 .frame_register()
149 .expect("invalid fp register offset");
150 let fp = convert_pe_register(fp);
151 let fp = regs.get(fp);
152 regs.set(Reg::RSP, fp + *offset as u64);
153 }
154 FunctionEpilogInstruction::Pop(reg) => {
155 let rsp = regs.get(Reg::RSP);
156 let val = read_stack_err(read_stack, rsp)?;
157 regs.set(convert_pe_register(*reg), val);
158 regs.set(Reg::RSP, rsp + 8);
159 }
160 }
161 }
162
163 let rsp = regs.get(Reg::RSP);
164 let ra = read_stack_err(read_stack, rsp)?;
165 regs.set(Reg::RSP, rsp + 8);
166
167 return Ok(UnwindResult::Uncacheable(ra));
168 }
169 }
170
171 // Get all chained UnwindInfo and resolve errors when collecting.
172 let chained_info = core::iter::successors(Some(Ok(unwind_info)), |info| {
173 let Ok(info) = info else {
174 return None;
175 };
176 if let Some(UnwindInfoTrailer::ChainedUnwindInfo { chained }) = info.trailer() {
177 let unwind_info_address = chained.unwind_info_address.get();
178 Some(
179 sections
180 .unwind_info_memory_at_rva(unwind_info_address)
181 .and_then(|data| {
182 UnwindInfo::parse(data).ok_or(PeUnwinderError::UnwindInfoParseError)
183 }),
184 )
185 } else {
186 None
187 }
188 })
189 .collect::<Result<Vec<_>, _>>()?;
190
191 // Get all operations across chained UnwindInfo. The first should be filtered to only those
192 // operations which are before the offset in the function.
193 let offset = address - function.begin_address.get();
194 let operations = chained_info.into_iter().enumerate().flat_map(|(i, info)| {
195 info.unwind_operations()
196 .skip_while(move |(o, _)| i == 0 && *o as u32 > offset)
197 .map(|(_, op)| op)
198 });
199
200 // We need to collect operations to first check (without losing ownership) whether an
201 // unwind rule can be returned.
202 let operations = operations.collect::<Vec<_>>();
203 if let Some(rule) = UnwindRuleX86_64::for_sequence_of_offset_or_pop(operations.iter()) {
204 return Ok(UnwindResult::ExecRule(rule));
205 }
206
207 // Resolve operations to get the return address.
208 let mut state = State { regs, read_stack };
209 for op in operations {
210 if let ControlFlow::Break(ra) = unwind_info
211 .resolve_operation(&mut state, &op)
212 .ok_or(PeUnwinderError::MissingStackData(None))?
213 {
214 return Ok(UnwindResult::Uncacheable(ra));
215 }
216 }
217
218 let rsp = regs.get(Reg::RSP);
219 let ra = read_stack_err(read_stack, rsp)?;
220 regs.set(Reg::RSP, rsp + 8);
221
222 Ok(UnwindResult::Uncacheable(ra))
223 }
224 }