Debian Codegraph @

third_party/rust/minidump-unwind/src/arm.rs

raw
1 // Copyright 2015 Ted Mielczarek. See the COPYRIGHT
2 // file at the top-level directory of this distribution.
3
4 // NOTE: arm64_old.rs and arm64.rs should be identical except for the names of
5 // their context types.
6
7 use super::impl_prelude::*;
8 use minidump::system_info::Os;
9 use minidump::{
10 CpuContext, MinidumpContext, MinidumpContextValidity, MinidumpModuleList, MinidumpRawContext,
11 };
12 use std::collections::HashSet;
13 use tracing::trace;
14
15 type ArmContext = minidump::format::CONTEXT_ARM;
16 type Pointer = <ArmContext as CpuContext>::Register;
17 type Registers = minidump::format::ArmRegisterNumbers;
18
19 const POINTER_WIDTH: Pointer = std::mem::size_of::<Pointer>() as Pointer;
20 const FRAME_POINTER: &str = Registers::FramePointer.name();
21 const STACK_POINTER: &str = Registers::StackPointer.name();
22 const PROGRAM_COUNTER: &str = Registers::ProgramCounter.name();
23 const _LINK_REGISTER: &str = Registers::LinkRegister.name();
24 const CALLEE_SAVED_REGS: &[&str] = &["r4", "r5", "r6", "r7", "r8", "r9", "r10", "fp"];
25
26 async fn get_caller_by_cfi<P>(
27 ctx: &ArmContext,
28 args: &GetCallerFrameArgs<'_, P>,
29 ) -> Option<StackFrame>
30 where
31 P: SymbolProvider + Sync,
32 {
33 trace!("trying cfi");
34
35 let _last_sp = ctx.get_register(STACK_POINTER, args.valid())?;
36
37 let mut stack_walker = CfiStackWalker::from_ctx_and_args(ctx, args, callee_forwarded_regs)?;
38
39 args.symbol_provider
40 .walk_frame(stack_walker.module, &mut stack_walker)
41 .await?;
42 let caller_pc = stack_walker.caller_ctx.get_register_always(PROGRAM_COUNTER);
43 let caller_sp = stack_walker.caller_ctx.get_register_always(STACK_POINTER);
44
45 trace!(
46 "cfi evaluation was successful -- caller_pc: 0x{:016x}, caller_sp: 0x{:016x}",
47 caller_pc,
48 caller_sp,
49 );
50
51 // Do absolutely NO validation! Yep! As long as CFI evaluation succeeds
52 // (which does include pc and sp resolving), just blindly assume the
53 // values are correct. I Don't Like This, but it's what breakpad does and
54 // we should start with a baseline of parity.
55
56 let context = MinidumpContext {
57 raw: MinidumpRawContext::Arm(stack_walker.caller_ctx),
58 valid: MinidumpContextValidity::Some(stack_walker.caller_validity),
59 };
60 Some(StackFrame::from_context(context, FrameTrust::CallFrameInfo))
61 }
62
63 fn callee_forwarded_regs(valid: &MinidumpContextValidity) -> HashSet<&'static str> {
64 match valid {
65 MinidumpContextValidity::All => CALLEE_SAVED_REGS.iter().copied().collect(),
66 MinidumpContextValidity::Some(ref which) => CALLEE_SAVED_REGS
67 .iter()
68 .filter(|&reg| which.contains(reg))
69 .copied()
70 .collect(),
71 }
72 }
73
74 fn get_caller_by_frame_pointer<P>(
75 ctx: &ArmContext,
76 args: &GetCallerFrameArgs<'_, P>,
77 ) -> Option<StackFrame>
78 where
79 P: SymbolProvider + Sync,
80 {
81 // The ARM manual states that:
82 // > LR can be used for other purposes when it is not required to support
83 // > a return from a subroutine.
84 // In other words, we need to be conservative and treat it as a general
85 // purpose register. Except on iOS, which has stricter conventions around
86 // register use, and does guarantee that LR contains a valid return addr.
87 if args.system_info.os != Os::Ios {
88 return None;
89 }
90
91 trace!("trying frame pointer");
92 // Assume that the standard %fp-using ARM calling convention is in use.
93 // The main quirk of this ABI is that the return address doesn't need to
94 // be restored from the stack -- it's already in the link register (lr).
95 // But that means we need to save/restore lr itself so that the *caller's*
96 // return address can be recovered.
97 //
98 // In the standard calling convention, the following happens:
99 //
100 // lr := return_address (done implicitly by a call)
101 // PUSH fp, lr (save fp and lr to the stack -- ARM pushes in pairs)
102 // fp := sp (update the frame pointer to the current stack pointer)
103 //
104 // So to restore the caller's registers, we have:
105 //
106 // sp := fp + ptr*2
107 // pc := *(fp + ptr)
108 // fp := *fp
109 let last_fp = ctx.get_register(FRAME_POINTER, args.valid())?;
110 let last_sp = ctx.get_register(STACK_POINTER, args.valid())?;
111
112 if last_fp >= u32::MAX - POINTER_WIDTH * 2 {
113 // Although this code generally works fine if the pointer math overflows,
114 // debug builds will still panic, and this guard protects against it without
115 // drowning the rest of the code in checked_add.
116 return None;
117 }
118 let (caller_fp, caller_pc, caller_sp) = if last_fp == 0 {
119 // In this case we want unwinding to stop. One of the termination conditions in get_caller_frame
120 // is that caller_sp <= last_sp. Therefore we can force termination by setting caller_sp = last_sp.
121 (0, 0, last_sp)
122 } else {
123 (
124 args.stack_memory.get_memory_at_address(last_fp as u64)?,
125 args.stack_memory
126 .get_memory_at_address(last_fp as u64 + POINTER_WIDTH as u64)?,
127 last_fp + POINTER_WIDTH * 2,
128 )
129 };
130
131 // Don't do any more validation, just assume it worked.
132
133 trace!(
134 "frame pointer seems valid -- caller_pc: 0x{:016x}, caller_sp: 0x{:016x}",
135 caller_pc,
136 caller_sp,
137 );
138
139 let mut caller_ctx = ArmContext::default();
140 caller_ctx.set_register(PROGRAM_COUNTER, caller_pc);
141 caller_ctx.set_register(FRAME_POINTER, caller_fp);
142 caller_ctx.set_register(STACK_POINTER, caller_sp);
143
144 let mut valid = HashSet::new();
145 valid.insert(PROGRAM_COUNTER);
146 valid.insert(FRAME_POINTER);
147 valid.insert(STACK_POINTER);
148
149 let context = MinidumpContext {
150 raw: MinidumpRawContext::Arm(caller_ctx),
151 valid: MinidumpContextValidity::Some(valid),
152 };
153 Some(StackFrame::from_context(context, FrameTrust::FramePointer))
154 }
155
156 async fn get_caller_by_scan<P>(
157 ctx: &ArmContext,
158 args: &GetCallerFrameArgs<'_, P>,
159 ) -> Option<StackFrame>
160 where
161 P: SymbolProvider + Sync,
162 {
163 trace!("trying scan");
164 // Stack scanning is just walking from the end of the frame until we encounter
165 // a value on the stack that looks like a pointer into some code (it's an address
166 // in a range covered by one of our modules). If we find such an instruction,
167 // we assume it's an pc value that was pushed by the CALL instruction that created
168 // the current frame. The next frame is then assumed to end just before that
169 // pc value.
170 let last_sp = ctx.get_register(STACK_POINTER, args.valid())?;
171
172 // Number of pointer-sized values to scan through in our search.
173 let default_scan_range = 40;
174 let extended_scan_range = default_scan_range * 4;
175
176 // Breakpad devs found that the first frame of an unwind can be really messed up,
177 // and therefore benefits from a longer scan. Let's do it too.
178 let scan_range = if let FrameTrust::Context = args.callee_frame.trust {
179 extended_scan_range
180 } else {
181 default_scan_range
182 };
183
184 for i in 0..scan_range {
185 let address_of_pc = last_sp.checked_add(i * POINTER_WIDTH)?;
186 let caller_pc = args
187 .stack_memory
188 .get_memory_at_address(address_of_pc as u64)?;
189 if instruction_seems_valid(caller_pc, args.modules, args.symbol_provider).await {
190 // pc is pushed by CALL, so sp is just address_of_pc + ptr
191 let caller_sp = address_of_pc.checked_add(POINTER_WIDTH)?;
192
193 // Don't do any more validation, and don't try to restore fp
194 // (that's what breakpad does!)
195
196 trace!(
197 "scan seems valid -- caller_pc: 0x{:08x}, caller_sp: 0x{:08x}",
198 caller_pc,
199 caller_sp,
200 );
201
202 let mut caller_ctx = ArmContext::default();
203 caller_ctx.set_register(PROGRAM_COUNTER, caller_pc);
204 caller_ctx.set_register(STACK_POINTER, caller_sp);
205
206 let mut valid = HashSet::new();
207 valid.insert(PROGRAM_COUNTER);
208 valid.insert(STACK_POINTER);
209
210 let context = MinidumpContext {
211 raw: MinidumpRawContext::Arm(caller_ctx),
212 valid: MinidumpContextValidity::Some(valid),
213 };
214 return Some(StackFrame::from_context(context, FrameTrust::Scan));
215 }
216 }
217
218 None
219 }
220
221 /// The most strict validation we have for instruction pointers.
222 ///
223 /// This is only used for stack-scanning, because it's explicitly
224 /// trying to distinguish between total garbage and correct values.
225 /// cfi and frame_pointer approaches do not use this validation
226 /// because by default they're working with plausible/trustworthy
227 /// data.
228 ///
229 /// Specifically, not using this validation allows cfi/fp methods
230 /// to unwind through frames we don't have mapped modules for (such as
231 /// OS APIs). This may seem confusing since we obviously don't have cfi
232 /// for unmapped modules!
233 ///
234 /// The way this works is that we will use cfi to unwind some frame we
235 /// know about and *end up* in a function we know nothing about, but with
236 /// all the right register values. At this point, frame pointers will
237 /// often do the correct thing even though we don't know what code we're
238 /// in -- until we get back into code we do know about and cfi kicks back in.
239 /// At worst, this sets scanning up in a better position for success!
240 ///
241 /// If we applied this more rigorous validation to cfi/fp methods, we
242 /// would just discard the correct register values from the known frame
243 /// and immediately start doing unreliable scans.
244 async fn instruction_seems_valid<P>(
245 instruction: Pointer,
246 modules: &MinidumpModuleList,
247 symbol_provider: &P,
248 ) -> bool
249 where
250 P: SymbolProvider + Sync,
251 {
252 super::instruction_seems_valid_by_symbols(instruction as u64, modules, symbol_provider).await
253 }
254
255 /*
256 // ARM is currently hyper-permissive, so we don't use this,
257 // but here it is in case we change our minds!
258 fn stack_seems_valid(
259 caller_sp: Pointer,
260 callee_sp: Pointer,
261 stack_memory: UnifiedMemory<'_, '_>,
262 ) -> bool {
263 // The stack shouldn't *grow* when we unwind
264 if caller_sp < callee_sp {
265 return false;
266 }
267
268 // The stack pointer should be in the stack
269 stack_memory
270 .get_memory_at_address::<Pointer>(caller_sp as u64)
271 .is_some()
272 }
273 */
274
275 pub async fn get_caller_frame<P>(
276 ctx: &ArmContext,
277 args: &GetCallerFrameArgs<'_, P>,
278 ) -> Option<StackFrame>
279 where
280 P: SymbolProvider + Sync,
281 {
282 // .await doesn't like closures, so don't use Option chaining
283 let mut frame = None;
284 if frame.is_none() {
285 frame = get_caller_by_cfi(ctx, args).await;
286 }
287 if frame.is_none() {
288 frame = get_caller_by_frame_pointer(ctx, args);
289 }
290 if frame.is_none() {
291 frame = get_caller_by_scan(ctx, args).await;
292 }
293 let mut frame = frame?;
294
295 // We now check the frame to see if it looks like unwinding is complete,
296 // based on the frame we computed having a nonsense value. Returning
297 // None signals to the unwinder to stop unwinding.
298
299 // if the instruction is within the first ~page of memory, it's basically
300 // null, and we can assume unwinding is complete.
301 if frame.context.get_instruction_pointer() < 4096 {
302 trace!("instruction pointer was nullish, assuming unwind complete");
303 return None;
304 }
305 // If the new stack pointer is at a lower address than the old,
306 // then that's clearly incorrect. Treat this as end-of-stack to
307 // enforce progress and avoid infinite loops.
308 let sp = frame.context.get_stack_pointer();
309 let last_sp = ctx.get_register_always("sp") as u64;
310 if sp <= last_sp {
311 // Arm leaf functions may not actually touch the stack (thanks
312 // to the link register allowing you to "push" the return address
313 // to a register), so we need to permit the stack pointer to not
314 // change for the first frame of the unwind. After that we need
315 // more strict validation to avoid infinite loops.
316 let is_leaf = args.callee_frame.trust == FrameTrust::Context && sp == last_sp;
317 if !is_leaf {
318 trace!("stack pointer went backwards, assuming unwind complete");
319 return None;
320 }
321 }
322
323 // Ok, the frame now seems well and truly valid, do final cleanup.
324
325 // A caller's ip is the return address, which is the instruction
326 // *after* the CALL that caused us to arrive at the callee. Set
327 // the value to 2 less than that, so it points to the CALL instruction
328 // (arm instructions are all 2 bytes wide). This is important because
329 // we use this value to lookup the CFI we need to unwind the next frame.
330 let ip = frame.context.get_instruction_pointer();
331 frame.instruction = ip - 2;
332
333 Some(frame)
334 }