Debian Codegraph @

third_party/rust/minidump-unwind/src/arm64.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::{
9 CpuContext, MinidumpContext, MinidumpContextValidity, MinidumpModuleList, MinidumpRawContext,
10 Module,
11 };
12 use std::collections::HashSet;
13 use tracing::trace;
14
15 type ArmContext = minidump::format::CONTEXT_ARM64;
16 type Pointer = <ArmContext as CpuContext>::Register;
17 type Registers = minidump::format::Arm64RegisterNumbers;
18
19 const POINTER_WIDTH: Pointer = std::mem::size_of::<Pointer>() as Pointer;
20 const FRAME_POINTER: &str = Registers::FramePointer.name();
21 const LINK_REGISTER: &str = Registers::LinkRegister.name();
22 const STACK_POINTER: &str = "sp";
23 const PROGRAM_COUNTER: &str = "pc";
24 const CALLEE_SAVED_REGS: &[&str] = &[
25 "x19", "x20", "x21", "x22", "x23", "x24", "x25", "x26", "x27", "x28", "fp",
26 ];
27
28 async fn get_caller_by_cfi<P>(
29 ctx: &ArmContext,
30 args: &GetCallerFrameArgs<'_, P>,
31 ) -> Option<StackFrame>
32 where
33 P: SymbolProvider + Sync,
34 {
35 trace!("trying cfi");
36
37 let _last_sp = ctx.get_register(STACK_POINTER, args.valid())?;
38
39 let mut stack_walker = CfiStackWalker::from_ctx_and_args(ctx, args, callee_forwarded_regs)?;
40
41 args.symbol_provider
42 .walk_frame(stack_walker.module, &mut stack_walker)
43 .await?;
44
45 let caller_pc = stack_walker.caller_ctx.get_register_always(PROGRAM_COUNTER);
46 let caller_sp = stack_walker.caller_ctx.get_register_always(STACK_POINTER);
47 let new_valid = MinidumpContextValidity::Some(stack_walker.caller_validity);
48
49 // Apply ptr auth stripping
50 let caller_pc = ptr_auth_strip(args.modules, caller_pc);
51 stack_walker
52 .caller_ctx
53 .set_register(PROGRAM_COUNTER, caller_pc);
54 // Nothing should really ever restore lr, but CFI is more magic so whatever sure
55 if let Some(lr) = stack_walker
56 .caller_ctx
57 .get_register(LINK_REGISTER, &new_valid)
58 {
59 stack_walker
60 .caller_ctx
61 .set_register(LINK_REGISTER, ptr_auth_strip(args.modules, lr));
62 }
63 if let Some(fp) = stack_walker
64 .caller_ctx
65 .get_register(FRAME_POINTER, &new_valid)
66 {
67 stack_walker
68 .caller_ctx
69 .set_register(FRAME_POINTER, ptr_auth_strip(args.modules, fp));
70 }
71
72 trace!(
73 "cfi evaluation was successful -- caller_pc: 0x{:016x}, caller_sp: 0x{:016x}",
74 caller_pc,
75 caller_sp,
76 );
77
78 // Do absolutely NO validation! Yep! As long as CFI evaluation succeeds
79 // (which does include pc and sp resolving), just blindly assume the
80 // values are correct. I Don't Like This, but it's what breakpad does and
81 // we should start with a baseline of parity.
82
83 // FIXME?: for whatever reason breakpad actually does block on the address
84 // being canonical *ONLY* for arm64, which actually rejects null pc early!
85 // Let's not do that to keep our code more uniform.
86
87 let context = MinidumpContext {
88 raw: MinidumpRawContext::Arm64(stack_walker.caller_ctx),
89 valid: new_valid,
90 };
91 Some(StackFrame::from_context(context, FrameTrust::CallFrameInfo))
92 }
93
94 fn callee_forwarded_regs(valid: &MinidumpContextValidity) -> HashSet<&'static str> {
95 match valid {
96 MinidumpContextValidity::All => CALLEE_SAVED_REGS.iter().copied().collect(),
97 MinidumpContextValidity::Some(ref which) => CALLEE_SAVED_REGS
98 .iter()
99 .filter(|&reg| which.contains(reg))
100 .copied()
101 .collect(),
102 }
103 }
104
105 fn get_caller_by_frame_pointer<P>(
106 ctx: &ArmContext,
107 args: &GetCallerFrameArgs<'_, P>,
108 ) -> Option<StackFrame>
109 where
110 P: SymbolProvider + Sync,
111 {
112 trace!("trying frame pointer");
113 // Ok so there exists 3 kinds of stackframes in ARM64:
114 //
115 // * stackless leaves
116 // * stackful leaves
117 // * normal frames
118 //
119 //
120 // # Normal Frames
121 //
122 // Let's start with normal frames. In the standard calling convention, the following happens:
123 //
124 // lr := return_address (performed implicitly by ARM's function call instruction)
125 // PUSH fp, lr (save fp and lr to the stack -- ARM64 pushes in pairs)
126 // fp := sp (update the frame pointer to the current stack pointer)
127 //
128 // So to restore the caller's registers, we have:
129 //
130 // pc := *(fp + ptr) (this will get the return address, usual offset caveats apply)
131 // sp := fp + ptr*2
132 // fp := *fp
133 //
134 // Note that although we push lr, we don't restore lr. That's because lr is just our
135 // return address, and is therefore essentially a "saved" pc. lr is caller-saved *and*
136 // automatically overwritten by every CALL, so the callee (the frame we're unwinding right now)
137 // has no business ever knowing it, let alone restoring it. lr is generally just saved
138 // immediately and then used as a free general purpose register, and therefore will generally
139 // contain random garbage unrelated to unwinding.
140 //
141 //
142 // # Leaf Functions
143 //
144 // Now leaf functions are a bit messier. These are functions which don't call other functions
145 // and therefore don't actually ever need to save lr or fp. As such, they can be entirely
146 // stackless, although they don't have to be. So calling a leaf function is just:
147 //
148 // lr := return_address
149 // <possibly some pushes, but maybe not>
150 //
151 // And to restore the caller's registers, we have:
152 //
153 // pc := lr
154 // sp := sp - <some arbitrary value>
155 // fp := fp
156 //
157 // Unfortunately, we're unaware of any way to "detect" that a function is a leaf or not
158 // without symbols/cfi just telling you that. Since we're in frame pointer unwinding,
159 // we probably don't have those available! And even if we did, we still wouldn't know if
160 // the frame was stackless or not, so we wouldn't know how to restore sp reliably and might
161 // get the stack in a weird state for subsequent (possibly CFI-based) frames.
162 // Also, if we incorrectly guess a frame is a leaf, we'll also use a probably-random-garbage
163 // lr as a pc and potentially halluncinate a bunch.
164 //
165 //
166 // # Conclusion
167 //
168 // At the moment we think it's safest/best to just always assume we're unwinding a normal
169 // frame. Statistically this is true (most frames are, even if they happen to be at the
170 // top of the stack when we crash), and if the frame *is* a leaf then our `fp` is likely
171 // to be the correct fp of the next frame. This will effectively result in us unwinding
172 // our caller instead of ourselves, causing the caller to be omitted from the backtrace
173 // but otherwise perfectly syncing up for the rest of the frames.
174 let last_fp = ctx.get_register(FRAME_POINTER, args.valid())?;
175 let last_sp = ctx.get_register(STACK_POINTER, args.valid())?;
176
177 if last_fp >= u64::MAX - POINTER_WIDTH * 2 {
178 // Although this code generally works fine if the pointer math overflows,
179 // debug builds will still panic, and this guard protects against it without
180 // drowning the rest of the code in checked_add.
181 return None;
182 }
183
184 let (caller_fp, caller_pc, caller_sp) = if last_fp == 0 {
185 // In this case we want unwinding to stop. One of the termination conditions in get_caller_frame
186 // is that caller_sp <= last_sp. Therefore we can force termination by setting caller_sp = last_sp.
187 (0, 0, last_sp)
188 } else {
189 (
190 args.stack_memory.get_memory_at_address(last_fp)?,
191 args.stack_memory
192 .get_memory_at_address(last_fp + POINTER_WIDTH)?,
193 last_fp + POINTER_WIDTH * 2,
194 )
195 };
196 let caller_fp = ptr_auth_strip(args.modules, caller_fp);
197 let caller_pc = ptr_auth_strip(args.modules, caller_pc);
198
199 // Don't accept obviously wrong instruction pointers.
200 if is_non_canonical(caller_pc) {
201 trace!("rejecting frame pointer result for unreasonable instruction pointer");
202 return None;
203 }
204
205 // Don't actually validate that the stack makes sense (duplicating breakpad behaviour).
206
207 trace!(
208 "frame pointer seems valid -- caller_pc: 0x{:016x}, caller_sp: 0x{:016x}",
209 caller_pc,
210 caller_sp,
211 );
212
213 let mut caller_ctx = ArmContext::default();
214 caller_ctx.set_register(PROGRAM_COUNTER, caller_pc);
215 caller_ctx.set_register(FRAME_POINTER, caller_fp);
216 caller_ctx.set_register(STACK_POINTER, caller_sp);
217
218 let mut valid = HashSet::new();
219 valid.insert(PROGRAM_COUNTER);
220 valid.insert(FRAME_POINTER);
221 valid.insert(STACK_POINTER);
222
223 let context = MinidumpContext {
224 raw: MinidumpRawContext::Arm64(caller_ctx),
225 valid: MinidumpContextValidity::Some(valid),
226 };
227 Some(StackFrame::from_context(context, FrameTrust::FramePointer))
228 }
229
230 fn ptr_auth_strip(modules: &MinidumpModuleList, ptr: Pointer) -> Pointer {
231 // ARMv8.3 introduced a code hardening system called "Pointer Authentication"
232 // which is used on Apple platforms. It adds some extra high bits to the
233 // several pointers when they get pushed to memory, including the return
234 // address (lr) and frame pointer (fp), which both get pushed at the start
235 // of most non-leaf functions.
236 //
237 // We lack some of the proper context to implement the "strip" primitive, because
238 // the amount of bits that are "real" pointer depends on various extensions like
239 // pointer tagging and how big page tables are. If we allocate too many bits to
240 // "real" then we can get ptr_auth bits in our pointers, and if we allocate too
241 // few we can end up truncating our pointers. Thankfully we'll usually have a bit
242 // of margin from pointers not having the highest real bits set.
243 //
244 // To help us guess, we have a few pieces of information:
245 //
246 // * Apple seems to default to a 17/47 split, so 47 bits for "real" is a good baseline
247 // * We know the address ranges of various loaded (and unloaded modules)
248 // * We know the address range of the stacks
249 // * We *can* know the address range of some sections of the heap (MemoryList)
250 // * We *can* know the page mappings (MemoryInfo)
251 //
252 // Right now we only incorporate the first two. Ideally we would process all those sources
253 // once at the start of stack walking and pass it down to the ARM stackwalker but that's
254 // a lot of annoying rewiring that won't necessarily improve results.
255 let apple_default_max_addr = (1 << 47) - 1;
256 let max_module_addr = modules
257 .by_addr()
258 .next_back()
259 .map(|last_module| {
260 last_module
261 .base_address()
262 .saturating_add(last_module.size())
263 })
264 .unwrap_or(0);
265 let max_addr = u64::max(apple_default_max_addr, max_module_addr);
266
267 // We can convert a "highest" address into a suitable mask by getting the next_power_of_two
268 // (a single bit >= the max) and subtracting one from it (producing all 1's <= that bit).
269 // There are two corner cases to this:
270 //
271 // * the next_power_of_two being 2^65, in which case our mask should be !0 (all ones)
272 // * the max addr being a power of two already means we will actually lose that one value
273 //
274 // The first case is handled by using checked_next_power_of_two. The second case isn't really
275 // handled by it very improbable. We do however make sure the apple max isn't a power of two.
276 let mask = max_addr
277 .checked_next_power_of_two()
278 .map(|high_bit| high_bit - 1)
279 .unwrap_or(!0);
280
281 // In principle, if we've done a good job of computing the mask, we can apply it regardless
282 // of if there's any ptr auth bits. Either it will clear the auth or be a noop. We don't
283 // check if this messes up, because there's too many subtleties like JITed code to reliably
284 // detect this going awry.
285 ptr & mask
286 }
287
288 async fn get_caller_by_scan<P>(
289 ctx: &ArmContext,
290 args: &GetCallerFrameArgs<'_, P>,
291 ) -> Option<StackFrame>
292 where
293 P: SymbolProvider + Sync,
294 {
295 trace!("trying scan");
296 // Stack scanning is just walking from the end of the frame until we encounter
297 // a value on the stack that looks like a pointer into some code (it's an address
298 // in a range covered by one of our modules). If we find such an instruction,
299 // we assume it's an pc value that was pushed by the CALL instruction that created
300 // the current frame. The next frame is then assumed to end just before that
301 // pc value.
302 let last_sp = ctx.get_register(STACK_POINTER, args.valid())?;
303
304 // Number of pointer-sized values to scan through in our search.
305 let default_scan_range = 40;
306 let extended_scan_range = default_scan_range * 4;
307
308 // Breakpad devs found that the first frame of an unwind can be really messed up,
309 // and therefore benefits from a longer scan. Let's do it too.
310 let scan_range = if let FrameTrust::Context = args.callee_frame.trust {
311 extended_scan_range
312 } else {
313 default_scan_range
314 };
315
316 for i in 0..scan_range {
317 let address_of_pc = last_sp.checked_add(i * POINTER_WIDTH)?;
318 let caller_pc = args.stack_memory.get_memory_at_address(address_of_pc)?;
319 if instruction_seems_valid(caller_pc, args.modules, args.symbol_provider).await {
320 // pc is pushed by CALL, so sp is just address_of_pc + ptr
321 let caller_sp = address_of_pc.checked_add(POINTER_WIDTH)?;
322
323 // Don't do any more validation, and don't try to restore fp
324 // (that's what breakpad does!)
325
326 trace!(
327 "scan seems valid -- caller_pc: 0x{:08x}, caller_sp: 0x{:08x}",
328 caller_pc,
329 caller_sp,
330 );
331
332 let mut caller_ctx = ArmContext::default();
333 caller_ctx.set_register(PROGRAM_COUNTER, caller_pc);
334 caller_ctx.set_register(STACK_POINTER, caller_sp);
335
336 let mut valid = HashSet::new();
337 valid.insert(PROGRAM_COUNTER);
338 valid.insert(STACK_POINTER);
339
340 let context = MinidumpContext {
341 raw: MinidumpRawContext::Arm64(caller_ctx),
342 valid: MinidumpContextValidity::Some(valid),
343 };
344 return Some(StackFrame::from_context(context, FrameTrust::Scan));
345 }
346 }
347
348 None
349 }
350
351 /// The most strict validation we have for instruction pointers.
352 ///
353 /// This is only used for stack-scanning, because it's explicitly
354 /// trying to distinguish between total garbage and correct values.
355 /// cfi and frame_pointer approaches do not use this validation
356 /// because by default they're working with plausible/trustworthy
357 /// data.
358 ///
359 /// Specifically, not using this validation allows cfi/fp methods
360 /// to unwind through frames we don't have mapped modules for (such as
361 /// OS APIs). This may seem confusing since we obviously don't have cfi
362 /// for unmapped modules!
363 ///
364 /// The way this works is that we will use cfi to unwind some frame we
365 /// know about and *end up* in a function we know nothing about, but with
366 /// all the right register values. At this point, frame pointers will
367 /// often do the correct thing even though we don't know what code we're
368 /// in -- until we get back into code we do know about and cfi kicks back in.
369 /// At worst, this sets scanning up in a better position for success!
370 ///
371 /// If we applied this more rigorous validation to cfi/fp methods, we
372 /// would just discard the correct register values from the known frame
373 /// and immediately start doing unreliable scans.
374 async fn instruction_seems_valid<P>(
375 instruction: Pointer,
376 modules: &MinidumpModuleList,
377 symbol_provider: &P,
378 ) -> bool
379 where
380 P: SymbolProvider + Sync,
381 {
382 if is_non_canonical(instruction) || instruction == 0 {
383 return false;
384 }
385
386 super::instruction_seems_valid_by_symbols(instruction, modules, symbol_provider).await
387 }
388
389 fn is_non_canonical(instruction: Pointer) -> bool {
390 // Reject instructions in the first page or above the user-space threshold.
391 !(0x1000..=0x000fffffffffffff).contains(&instruction)
392 }
393
394 /*
395 // ARM64 is currently hyper-permissive, so we don't use this,
396 // but here it is in case we change our minds!
397 fn stack_seems_valid(
398 caller_sp: Pointer,
399 callee_sp: Pointer,
400 stack_memory: UnifiedMemory<'_, '_>,
401 ) -> bool {
402 // The stack shouldn't *grow* when we unwind
403 if caller_sp < callee_sp {
404 return false;
405 }
406
407 // The stack pointer should be in the stack
408 stack_memory
409 .get_memory_at_address::<Pointer>(caller_sp as u64)
410 .is_some()
411 }
412 */
413
414 pub async fn get_caller_frame<P>(
415 ctx: &ArmContext,
416 args: &GetCallerFrameArgs<'_, P>,
417 ) -> Option<StackFrame>
418 where
419 P: SymbolProvider + Sync,
420 {
421 // .await doesn't like closures, so don't use Option chaining
422 let mut frame = None;
423 if frame.is_none() {
424 frame = get_caller_by_cfi(ctx, args).await;
425 }
426 if frame.is_none() {
427 frame = get_caller_by_frame_pointer(ctx, args);
428 }
429 if frame.is_none() {
430 frame = get_caller_by_scan(ctx, args).await;
431 }
432 let mut frame = frame?;
433
434 // We now check the frame to see if it looks like unwinding is complete,
435 // based on the frame we computed having a nonsense value. Returning
436 // None signals to the unwinder to stop unwinding.
437
438 // if the instruction is within the first ~page of memory, it's basically
439 // null, and we can assume unwinding is complete.
440 if frame.context.get_instruction_pointer() < 4096 {
441 trace!("instruction pointer was nullish, assuming unwind complete");
442 return None;
443 }
444
445 // If the new stack pointer is at a lower address than the old,
446 // then that's clearly incorrect. Treat this as end-of-stack to
447 // enforce progress and avoid infinite loops.
448
449 let sp = frame.context.get_stack_pointer();
450 let last_sp = ctx.get_register_always("sp");
451 if sp <= last_sp {
452 // Arm leaf functions may not actually touch the stack (thanks
453 // to the link register allowing you to "push" the return address
454 // to a register), so we need to permit the stack pointer to not
455 // change for the first frame of the unwind. After that we need
456 // more strict validation to avoid infinite loops.
457 let is_leaf = args.callee_frame.trust == FrameTrust::Context && sp == last_sp;
458 if !is_leaf {
459 trace!("stack pointer went backwards, assuming unwind complete");
460 return None;
461 }
462 }
463
464 // Ok, the frame now seems well and truly valid, do final cleanup.
465
466 // A caller's ip is the return address, which is the instruction
467 // *after* the CALL that caused us to arrive at the callee. Set
468 // the value to 4 less than that, so it points to the CALL instruction
469 // (arm64 instructions are all 4 bytes wide). This is important because
470 // we use this value to lookup the CFI we need to unwind the next frame.
471 let ip = frame.context.get_instruction_pointer();
472 frame.instruction = ip - 4;
473
474 Some(frame)
475 }