Debian Codegraph @

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

raw
1 // Copyright 2015 Ted Mielczarek. See the COPYRIGHT
2 // file at the top-level directory of this distribution.
3
4 // Note since x86 and Amd64 have basically the same ABI, this implementation
5 // is written to largely erase the details of the two wherever possible,
6 // so that it can be copied between the two with minimal changes. It's not
7 // worth the effort to *actually* unify the implementations.
8
9 use super::impl_prelude::*;
10 use minidump::format::CONTEXT_AMD64;
11 use minidump::system_info::Os;
12 use minidump::{
13 MinidumpContext, MinidumpContextValidity, MinidumpModuleList, MinidumpRawContext, UnifiedMemory,
14 };
15 use std::collections::HashSet;
16 use tracing::trace;
17
18 type Pointer = u64;
19 const POINTER_WIDTH: Pointer = 8;
20 const INSTRUCTION_REGISTER: &str = "rip";
21 const STACK_POINTER_REGISTER: &str = "rsp";
22 const FRAME_POINTER_REGISTER: &str = "rbp";
23 // FIXME: rdi and rsi are also preserved on windows (but not in sysv) -- we should handle that?
24 const CALLEE_SAVED_REGS: &[&str] = &["rbx", "rbp", "r12", "r13", "r14", "r15"];
25
26 async fn get_caller_by_cfi<P>(
27 ctx: &CONTEXT_AMD64,
28 args: &GetCallerFrameArgs<'_, P>,
29 ) -> Option<StackFrame>
30 where
31 P: SymbolProvider + Sync,
32 {
33 trace!("trying cfi");
34
35 if let MinidumpContextValidity::Some(ref which) = args.valid() {
36 if !which.contains(STACK_POINTER_REGISTER) {
37 return None;
38 }
39 }
40
41 let mut stack_walker = CfiStackWalker::from_ctx_and_args(ctx, args, callee_forwarded_regs)?;
42
43 args.symbol_provider
44 .walk_frame(stack_walker.module, &mut stack_walker)
45 .await?;
46 let caller_ip = stack_walker.caller_ctx.rip;
47 let caller_sp = stack_walker.caller_ctx.rsp;
48
49 trace!(
50 "cfi evaluation was successful -- caller_ip: 0x{:016x}, caller_sp: 0x{:016x}",
51 caller_ip,
52 caller_sp,
53 );
54
55 // Do absolutely NO validation! Yep! As long as CFI evaluation succeeds
56 // (which does include ip and sp resolving), just blindly assume the
57 // values are correct. I Don't Like This, but it's what breakpad does and
58 // we should start with a baseline of parity.
59
60 trace!("cfi result seems valid");
61
62 let context = MinidumpContext {
63 raw: MinidumpRawContext::Amd64(stack_walker.caller_ctx),
64 valid: MinidumpContextValidity::Some(stack_walker.caller_validity),
65 };
66 Some(StackFrame::from_context(context, FrameTrust::CallFrameInfo))
67 }
68
69 fn callee_forwarded_regs(valid: &MinidumpContextValidity) -> HashSet<&'static str> {
70 match valid {
71 MinidumpContextValidity::All => CALLEE_SAVED_REGS.iter().copied().collect(),
72 MinidumpContextValidity::Some(ref which) => CALLEE_SAVED_REGS
73 .iter()
74 .filter(|&reg| which.contains(reg))
75 .copied()
76 .collect(),
77 }
78 }
79
80 fn get_caller_by_frame_pointer<P>(
81 ctx: &CONTEXT_AMD64,
82 args: &GetCallerFrameArgs<'_, P>,
83 ) -> Option<StackFrame>
84 where
85 P: SymbolProvider + Sync,
86 {
87 let stack_memory = args.stack_memory;
88 // On Windows x64, frame-pointer unwinding purely with the data on the stack
89 // is not possible, as proper unwinding requires access to `UNWIND_INFO`,
90 // because the frame pointer does not necessarily point to the end of the
91 // frame.
92 // In particular, the docs state that:
93 // > [The frame register] offset permits pointing the FP register into the
94 // > middle of the local stack allocation [...]
95 // https://docs.microsoft.com/en-us/cpp/build/exception-handling-x64
96 if args.system_info.os == Os::Windows {
97 return None;
98 }
99
100 trace!("trying frame pointer");
101 if let MinidumpContextValidity::Some(ref which) = args.valid() {
102 if !which.contains(FRAME_POINTER_REGISTER) {
103 return None;
104 }
105 if !which.contains(STACK_POINTER_REGISTER) {
106 return None;
107 }
108 }
109
110 let last_bp = ctx.rbp;
111 let last_sp = ctx.rsp;
112 // Assume that the standard %bp-using x64 calling convention is in
113 // use.
114 //
115 // The typical x64 calling convention, when frame pointers are present,
116 // is for the calling procedure to use CALL, which pushes the return
117 // address onto the stack and sets the instruction pointer (%ip) to
118 // the entry point of the called routine. The called routine then
119 // PUSHes the calling routine's frame pointer (%bp) onto the stack
120 // before copying the stack pointer (%sp) to the frame pointer (%bp).
121 // Therefore, the calling procedure's frame pointer is always available
122 // by dereferencing the called procedure's frame pointer, and the return
123 // address is always available at the memory location immediately above
124 // the address pointed to by the called procedure's frame pointer. The
125 // calling procedure's stack pointer (%sp) is 2 pointers higher than the
126 // value of the called procedure's frame pointer at the time the calling
127 // procedure made the CALL: 1 pointer for the return address pushed by the
128 // CALL itself, and 1 pointer for the callee's` PUSH of the caller's frame
129 // pointer.
130 //
131 // %ip_new = *(%bp_old + ptr)
132 // %bp_new = *(%bp_old)
133 // %sp_new = %bp_old + ptr*2
134
135 if last_bp >= u64::MAX - POINTER_WIDTH * 2 {
136 // Although this code generally works fine if the pointer math overflows,
137 // debug builds will still panic, and this guard protects against it without
138 // drowning the rest of the code in checked_add.
139 return None;
140 }
141 let caller_ip = stack_memory.get_memory_at_address(last_bp + POINTER_WIDTH)?;
142 let caller_bp = stack_memory.get_memory_at_address(last_bp)?;
143 let caller_sp = last_bp + POINTER_WIDTH * 2;
144
145 // If the recovered ip is not a canonical address it can't be
146 // the return address, so bp must not have been a frame pointer.
147
148 // Since we're assuming coherent frame pointers, check that the frame pointers
149 // and stack pointers are well-ordered.
150 if caller_sp <= last_bp || caller_bp < caller_sp {
151 trace!("rejecting frame pointer result for unreasonable frame pointer");
152 return None;
153 }
154 // Since we're assuming coherent frame pointers, check that the resulting
155 // frame pointer is still inside stack memory.
156 let _unused: Pointer = stack_memory.get_memory_at_address(caller_bp)?;
157 // Don't accept obviously wrong instruction pointers.
158 if is_non_canonical(caller_ip) {
159 trace!("rejecting frame pointer result for unreasonable instruction pointer");
160 return None;
161 }
162 // Don't accept obviously wrong stack pointers.
163 if !stack_seems_valid(caller_sp, last_sp, stack_memory) {
164 trace!("rejecting frame pointer result for unreasonable stack pointer");
165 return None;
166 }
167
168 trace!(
169 "frame pointer seems valid -- caller_ip: 0x{:016x}, caller_sp: 0x{:016x}",
170 caller_ip,
171 caller_sp,
172 );
173
174 let caller_ctx = CONTEXT_AMD64 {
175 rip: caller_ip,
176 rsp: caller_sp,
177 rbp: caller_bp,
178 ..CONTEXT_AMD64::default()
179 };
180 let mut valid = HashSet::new();
181 valid.insert(INSTRUCTION_REGISTER);
182 valid.insert(STACK_POINTER_REGISTER);
183 valid.insert(FRAME_POINTER_REGISTER);
184 let context = MinidumpContext {
185 raw: MinidumpRawContext::Amd64(caller_ctx),
186 valid: MinidumpContextValidity::Some(valid),
187 };
188 Some(StackFrame::from_context(context, FrameTrust::FramePointer))
189 }
190
191 async fn get_caller_by_scan<P>(
192 ctx: &CONTEXT_AMD64,
193 args: &GetCallerFrameArgs<'_, P>,
194 ) -> Option<StackFrame>
195 where
196 P: SymbolProvider + Sync,
197 {
198 trace!("trying scan");
199 let stack_memory = args.stack_memory;
200
201 // Stack scanning is just walking from the end of the frame until we encounter
202 // a value on the stack that looks like a pointer into some code (it's an address
203 // in a range covered by one of our modules). If we find such an instruction,
204 // we assume it's an ip value that was pushed by the CALL instruction that created
205 // the current frame. The next frame is then assumed to end just before that
206 // ip value.
207 let last_bp = match args.valid() {
208 MinidumpContextValidity::All => Some(ctx.rbp),
209 MinidumpContextValidity::Some(ref which) => {
210 if !which.contains(STACK_POINTER_REGISTER) {
211 trace!("cannot scan without stack pointer");
212 return None;
213 }
214 if which.contains(FRAME_POINTER_REGISTER) {
215 Some(ctx.rbp)
216 } else {
217 None
218 }
219 }
220 };
221 let last_sp = ctx.rsp;
222
223 // Number of pointer-sized values to scan through in our search.
224 let default_scan_range = 40;
225 let extended_scan_range = default_scan_range * 4;
226
227 // Breakpad devs found that the first frame of an unwind can be really messed up,
228 // and therefore benefits from a longer scan. Let's do it too.
229 let scan_range = if let FrameTrust::Context = args.callee_frame.trust {
230 extended_scan_range
231 } else {
232 default_scan_range
233 };
234
235 for i in 0..scan_range {
236 let address_of_ip = last_sp.checked_add(i * POINTER_WIDTH)?;
237 let caller_ip = stack_memory.get_memory_at_address(address_of_ip)?;
238 if instruction_seems_valid(caller_ip, args.modules, args.symbol_provider).await {
239 // ip is pushed by CALL, so sp is just address_of_ip + ptr
240 let caller_sp = address_of_ip.checked_add(POINTER_WIDTH)?;
241
242 // Try to restore bp as well. This can be possible in two cases:
243 //
244 // 1. This function has the standard prologue that pushes bp and
245 // sets bp = sp. If this is the case, then the current bp should be
246 // immediately after (before in memory) address_of_ip.
247 //
248 // 2. This function does not use bp, and has just preserved it
249 // from the caller. If this is the case, bp should be before
250 // (after in memory) address_of_ip.
251 //
252 // We then try our best to eliminate bogus-looking bp's with some
253 // simple heuristics like "is a valid stack address".
254 let mut caller_bp = None;
255
256 // This value was specifically computed for x86 frames (see the x86
257 // impl for details), but 128 KB is still an extremely generous
258 // frame size on x64.
259 const MAX_REASONABLE_GAP_BETWEEN_FRAMES: Pointer = 128 * 1024;
260
261 // NOTE: minor divergence from the x86 impl here: for whatever
262 // reason the x64 breakpad tests only work if we gate option (1) on
263 // having a valid `bp` that points next to address_of_ip already.
264 // It's unclear why, perhaps the test is buggy, but for now we
265 // preserve that behaviour.
266 if let Some(last_bp) = last_bp {
267 // If we're on the first iteration of the scan, there can't possibly be a
268 // frame pointer, because the entire stack frame is taken up by the return
269 // pointer. And if we're not on the first iteration, then the last iteration
270 // already loaded the location we expect the frame pointer to be in, so we can
271 // unconditionally load it here.
272 if i > 0 {
273 let address_of_bp = address_of_ip - POINTER_WIDTH;
274 // Can assume this resolves because we already walked over it when
275 // checking address_of_ip values.
276 let bp = stack_memory.get_memory_at_address(address_of_bp)?;
277 if last_bp == address_of_bp
278 && bp > address_of_ip
279 && bp - address_of_bp <= MAX_REASONABLE_GAP_BETWEEN_FRAMES
280 {
281 // Final sanity check that resulting bp is still inside stack memory.
282 if stack_memory.get_memory_at_address::<Pointer>(bp).is_some() {
283 caller_bp = Some(bp);
284 }
285 } else if last_bp >= caller_sp {
286 // Don't sanity check that the address is inside the stack? Hmm.
287 caller_bp = Some(last_bp);
288 }
289 }
290 }
291
292 trace!(
293 "scan seems valid -- caller_ip: 0x{:08x}, caller_sp: 0x{:08x}",
294 caller_ip,
295 caller_sp,
296 );
297
298 let caller_ctx = CONTEXT_AMD64 {
299 rip: caller_ip,
300 rsp: caller_sp,
301 rbp: caller_bp.unwrap_or(0),
302 ..CONTEXT_AMD64::default()
303 };
304 let mut valid = HashSet::new();
305 valid.insert(INSTRUCTION_REGISTER);
306 valid.insert(STACK_POINTER_REGISTER);
307 if caller_bp.is_some() {
308 valid.insert(FRAME_POINTER_REGISTER);
309 }
310 let context = MinidumpContext {
311 raw: MinidumpRawContext::Amd64(caller_ctx),
312 valid: MinidumpContextValidity::Some(valid),
313 };
314 return Some(StackFrame::from_context(context, FrameTrust::Scan));
315 }
316 }
317
318 None
319 }
320
321 /// The most strict validation we have for instruction pointers.
322 ///
323 /// This is only used for stack-scanning, because it's explicitly
324 /// trying to distinguish between total garbage and correct values.
325 /// cfi and frame_pointer approaches do not use this validation
326 /// because by default they're working with plausible/trustworthy
327 /// data.
328 ///
329 /// Specifically, not using this validation allows cfi/fp methods
330 /// to unwind through frames we don't have mapped modules for (such as
331 /// OS APIs). This may seem confusing since we obviously don't have cfi
332 /// for unmapped modules!
333 ///
334 /// The way this works is that we will use cfi to unwind some frame we
335 /// know about and *end up* in a function we know nothing about, but with
336 /// all the right register values. At this point, frame pointers will
337 /// often do the correct thing even though we don't know what code we're
338 /// in -- until we get back into code we do know about and cfi kicks back in.
339 /// At worst, this sets scanning up in a better position for success!
340 ///
341 /// If we applied this more rigorous validation to cfi/fp methods, we
342 /// would just discard the correct register values from the known frame
343 /// and immediately start doing unreliable scans.
344 async fn instruction_seems_valid<P>(
345 instruction: Pointer,
346 modules: &MinidumpModuleList,
347 symbol_provider: &P,
348 ) -> bool
349 where
350 P: SymbolProvider + Sync,
351 {
352 if is_non_canonical(instruction) || instruction == 0 {
353 return false;
354 }
355
356 super::instruction_seems_valid_by_symbols(instruction, modules, symbol_provider).await
357 }
358
359 fn stack_seems_valid(
360 caller_sp: Pointer,
361 callee_sp: Pointer,
362 stack_memory: UnifiedMemory<'_, '_>,
363 ) -> bool {
364 // The stack shouldn't *grow* when we unwind
365 if caller_sp <= callee_sp {
366 return false;
367 }
368
369 // The stack pointer should be in the stack
370 stack_memory
371 .get_memory_at_address::<Pointer>(caller_sp)
372 .is_some()
373 }
374
375 fn is_non_canonical(ptr: Pointer) -> bool {
376 // x64 has the notion of a "canonical address", as a result of only 48 bits
377 // of a pointer actually being used, because this is all that a 4-level page
378 // table can support. A canonical address copies bit 47 to all the otherwise
379 // unused high bits. This creates two ranges where no valid pointers should
380 // ever exist.
381 //
382 // Note that as of this writing, 5-level page tables *do* exist, and when enabled
383 // 57 bits are used. However modern JS engines rely on only 48 bits being used
384 // to perform "NaN boxing" optimizations, so it's reasonable to assume
385 // by default that only 4-level page tables are used. (Even if enabled at
386 // the system level, Linux only exposes non-48-bit pointers to a process
387 // if that process explicitly opts in with a special operation.)
388 ptr > 0x7FFFFFFFFFFF && ptr < 0xFFFF800000000000
389 }
390
391 pub async fn get_caller_frame<P>(
392 ctx: &CONTEXT_AMD64,
393 args: &GetCallerFrameArgs<'_, P>,
394 ) -> Option<StackFrame>
395 where
396 P: SymbolProvider + Sync,
397 {
398 // .await doesn't like closures, so don't use Option chaining
399 let mut frame = None;
400 if frame.is_none() {
401 frame = get_caller_by_cfi(ctx, args).await;
402 }
403 if frame.is_none() {
404 frame = get_caller_by_frame_pointer(ctx, args);
405 }
406 if frame.is_none() {
407 frame = get_caller_by_scan(ctx, args).await;
408 }
409 let mut frame = frame?;
410
411 // We now check the frame to see if it looks like unwinding is complete,
412 // based on the frame we computed having a nonsense value. Returning
413 // None signals to the unwinder to stop unwinding.
414
415 // if the instruction is within the first ~page of memory, it's basically
416 // null, and we can assume unwinding is complete.
417 if frame.context.get_instruction_pointer() < 4096 {
418 trace!("instruction pointer was nullish, assuming unwind complete");
419 return None;
420 }
421 // If the new stack pointer is at a lower address than the old,
422 // then that's clearly incorrect. Treat this as end-of-stack to
423 // enforce progress and avoid infinite loops.
424 if frame.context.get_stack_pointer() <= ctx.rsp {
425 trace!("stack pointer went backwards, assuming unwind complete");
426 return None;
427 }
428
429 // Ok, the frame now seems well and truly valid, do final cleanup.
430
431 // A caller's ip is the return address, which is the instruction
432 // *after* the CALL that caused us to arrive at the callee. Set
433 // the value to one less than that, so it points within the
434 // CALL instruction. This is important because we use this value
435 // to lookup the CFI we need to unwind the next frame.
436 let ip = frame.context.get_instruction_pointer();
437 frame.instruction = ip - 1;
438
439 Some(frame)
440 }