Debian Codegraph @

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

raw
1 use super::impl_prelude::*;
2 use minidump::format::ContextFlagsCpu;
3 use minidump::{
4 CpuContext, Endian, MinidumpContext, MinidumpContextValidity, MinidumpModuleList,
5 MinidumpRawContext,
6 };
7 use scroll::ctx::{SizeWith, TryFromCtx};
8 use std::collections::HashSet;
9 use std::convert::TryFrom;
10 use tracing::trace;
11
12 type MipsContext = minidump::format::CONTEXT_MIPS;
13 type Pointer = <MipsContext as CpuContext>::Register;
14
15 const STACK_POINTER: &str = "sp";
16 const PROGRAM_COUNTER: &str = "pc";
17 const CALLEE_SAVED_REGS: &[&str] = &[
18 "s0", "s1", "s2", "s3", "s4", "s5", "s6", "s7", "gp", "sp", "fp",
19 ];
20
21 async fn get_caller_by_cfi<'a, C, P>(
22 ctx: &'a C,
23 args: &'a GetCallerFrameArgs<'a, P>,
24 ) -> Option<StackFrame>
25 where
26 P: SymbolProvider + Sync,
27 // all these bounds are essentially duplicated from `CfiStackWalker` :-(
28 C: CpuContext + IntoRawContext + Clone + Send + Sync,
29 C::Register: TryFrom<u64>,
30 u64: TryFrom<C::Register>,
31 C::Register: TryFromCtx<'a, Endian, [u8], Error = scroll::Error> + SizeWith<Endian>,
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{caller_pc:016x}, caller_sp: 0x{caller_sp:016x}"
47 );
48
49 // Do absolutely NO validation! Yep! As long as CFI evaluation succeeds
50 // (which does include pc and sp resolving), just blindly assume the
51 // values are correct. I Don't Like This, but it's what breakpad does and
52 // we should start with a baseline of parity.
53
54 let context = MinidumpContext {
55 raw: stack_walker.caller_ctx.into_ctx(),
56 valid: MinidumpContextValidity::Some(stack_walker.caller_validity),
57 };
58 Some(StackFrame::from_context(context, FrameTrust::CallFrameInfo))
59 }
60
61 fn callee_forwarded_regs(valid: &MinidumpContextValidity) -> HashSet<&'static str> {
62 match valid {
63 MinidumpContextValidity::All => CALLEE_SAVED_REGS.iter().copied().collect(),
64 MinidumpContextValidity::Some(ref which) => CALLEE_SAVED_REGS
65 .iter()
66 .filter(|&reg| which.contains(reg))
67 .copied()
68 .collect(),
69 }
70 }
71
72 async fn get_caller_by_scan32<P>(
73 ctx: &Mips32Context,
74 args: &GetCallerFrameArgs<'_, P>,
75 ) -> Option<StackFrame>
76 where
77 P: SymbolProvider + Sync,
78 {
79 const MAX_STACK_SIZE: u32 = 1024;
80 const MIN_ARGS: u32 = 4;
81 const POINTER_WIDTH: u32 = 4;
82 trace!("trying scan");
83 // Stack scanning is just walking from the end of the frame until we encounter
84 // a value on the stack that looks like a pointer into some code (it's an address
85 // in a range covered by one of our modules). If we find such an instruction,
86 // we assume it's a `ra` value that was saved on the stack by the callee in
87 // its function prologue, following a `jal` (call) instruction of the caller.
88 // The next frame is then assumed to end just before that `ra` value.
89 let mut last_sp = ctx.get_register(STACK_POINTER, args.valid())?;
90
91 let mut count = MAX_STACK_SIZE / POINTER_WIDTH;
92 // In case of mips32 ABI the stack frame of a non-leaf function
93 // must have a minimum stack frame size for 4 arguments (4 words).
94 // Move stack pointer for 4 words to avoid reporting non-existing frames
95 // for all frames except the topmost one.
96 // There is no way of knowing if topmost frame belongs to a leaf or
97 // a non-leaf function.
98 if args.callee_frame.trust != FrameTrust::Context {
99 last_sp = last_sp.checked_add(MIN_ARGS * POINTER_WIDTH)?;
100 count -= MIN_ARGS;
101 }
102
103 for i in 0..count {
104 let address_of_pc = last_sp.checked_add(i * POINTER_WIDTH)?;
105 let caller_pc: u32 = args
106 .stack_memory
107 .get_memory_at_address(address_of_pc as u64)?;
108 //trace!("unwind: trying addr 0x{address_of_pc:08x}: 0x{caller_pc:08x}");
109 if instruction_seems_valid(caller_pc as u64, args.modules, args.symbol_provider).await {
110 // `ra` is usually saved directly at the bottom of the frame,
111 // so sp is just address_of_pc + ptr
112 let caller_sp = address_of_pc.checked_add(POINTER_WIDTH)?;
113
114 // Don't do any more validation, and don't try to restore fp
115 // (that's what breakpad does!)
116
117 trace!(
118 "scan seems valid -- caller_pc: 0x{caller_pc:016x}, caller_sp: 0x{caller_sp:016x}"
119 );
120
121 let mut caller_ctx = MipsContext::default();
122 caller_ctx.set_register(PROGRAM_COUNTER, caller_pc as u64);
123 caller_ctx.set_register(STACK_POINTER, caller_sp as u64);
124
125 let mut valid = HashSet::new();
126 valid.insert(PROGRAM_COUNTER);
127 valid.insert(STACK_POINTER);
128
129 let context = MinidumpContext {
130 raw: MinidumpRawContext::Mips(caller_ctx),
131 valid: MinidumpContextValidity::Some(valid),
132 };
133 return Some(StackFrame::from_context(context, FrameTrust::Scan));
134 }
135 }
136
137 None
138 }
139
140 async fn get_caller_by_scan64<P>(
141 ctx: &MipsContext,
142 args: &GetCallerFrameArgs<'_, P>,
143 ) -> Option<StackFrame>
144 where
145 P: SymbolProvider + Sync,
146 {
147 const MAX_STACK_SIZE: u64 = 1024;
148 const POINTER_WIDTH: u64 = 8;
149 trace!("trying scan");
150 // Stack scanning is just walking from the end of the frame until we encounter
151 // a value on the stack that looks like a pointer into some code (it's an address
152 // in a range covered by one of our modules). If we find such an instruction,
153 // we assume it's a `ra` value that was saved on the stack by the callee in
154 // its function prologue, following a `jal` (call) instruction of the caller.
155 // The next frame is then assumed to end just before that `ra` value.
156 let last_sp = ctx.get_register(STACK_POINTER, args.valid())?;
157
158 let count = MAX_STACK_SIZE / POINTER_WIDTH;
159
160 for i in 0..count {
161 let address_of_pc = last_sp.checked_add(i * POINTER_WIDTH)?;
162 let caller_pc = args.stack_memory.get_memory_at_address(address_of_pc)?;
163 if instruction_seems_valid(caller_pc, args.modules, args.symbol_provider).await {
164 // `ra` is usually saved directly at the bottom of the frame,
165 // so sp is just address_of_pc + ptr
166 let caller_sp = address_of_pc.checked_add(POINTER_WIDTH)?;
167
168 // Don't do any more validation, and don't try to restore fp
169 // (that's what breakpad does!)
170
171 trace!(
172 "scan seems valid -- caller_pc: 0x{caller_pc:016x}, caller_sp: 0x{caller_sp:016x}"
173 );
174
175 let mut caller_ctx = MipsContext::default();
176 caller_ctx.set_register(PROGRAM_COUNTER, caller_pc);
177 caller_ctx.set_register(STACK_POINTER, caller_sp);
178
179 let mut valid = HashSet::new();
180 valid.insert(PROGRAM_COUNTER);
181 valid.insert(STACK_POINTER);
182
183 let context = MinidumpContext {
184 raw: MinidumpRawContext::Mips(caller_ctx),
185 valid: MinidumpContextValidity::Some(valid),
186 };
187 return Some(StackFrame::from_context(context, FrameTrust::Scan));
188 }
189 }
190
191 None
192 }
193
194 async fn instruction_seems_valid<P>(
195 instruction: Pointer,
196 modules: &MinidumpModuleList,
197 symbol_provider: &P,
198 ) -> bool
199 where
200 P: SymbolProvider + Sync,
201 {
202 if instruction < 0x1000 {
203 return false;
204 }
205
206 super::instruction_seems_valid_by_symbols(instruction, modules, symbol_provider).await
207 }
208
209 pub async fn get_caller_frame<P>(
210 ctx: &MipsContext,
211 args: &GetCallerFrameArgs<'_, P>,
212 ) -> Option<StackFrame>
213 where
214 P: SymbolProvider + Sync,
215 {
216 let ctx32 = Mips32Context::try_from(ctx.clone());
217
218 // .await doesn't like closures, so don't use Option chaining
219 let mut frame = None;
220 if frame.is_none() {
221 match &ctx32 {
222 Ok(mips32) => frame = get_caller_by_cfi(mips32, args).await,
223 Err(mips64) => frame = get_caller_by_cfi(mips64, args).await,
224 }
225 }
226 if frame.is_none() {
227 match &ctx32 {
228 Ok(mips32) => frame = get_caller_by_scan32(mips32, args).await,
229 Err(mips64) => frame = get_caller_by_scan64(mips64, args).await,
230 }
231 }
232 let mut frame = frame?;
233
234 // We now check the frame to see if it looks like unwinding is complete,
235 // based on the frame we computed having a nonsense value. Returning
236 // None signals to the unwinder to stop unwinding.
237
238 // if the instruction is within the first ~page of memory, it's basically
239 // null, and we can assume unwinding is complete.
240 if frame.context.get_instruction_pointer() < 4096 {
241 trace!("instruction pointer was nullish, assuming unwind complete");
242 return None;
243 }
244
245 // If the new stack pointer is at a lower address than the old,
246 // then that's clearly incorrect. Treat this as end-of-stack to
247 // enforce progress and avoid infinite loops.
248
249 let sp = frame.context.get_stack_pointer();
250 let last_sp = ctx.get_register_always(STACK_POINTER);
251 if sp <= last_sp {
252 // Mips leaf functions may not actually touch the stack (thanks
253 // to the return address register allowing you to "push" the return address
254 // to a register), so we need to permit the stack pointer to not
255 // change for the first frame of the unwind. After that we need
256 // more strict validation to avoid infinite loops.
257 let is_leaf = args.callee_frame.trust == FrameTrust::Context && sp == last_sp;
258 if !is_leaf {
259 trace!("stack pointer went backwards, assuming unwind complete");
260 return None;
261 }
262 }
263
264 // Ok, the frame now seems well and truly valid, do final cleanup.
265
266 // The Mips `jal` instruction always sets $ra to PC + 8
267 let ip = frame.context.get_instruction_pointer();
268 frame.instruction = ip - 8;
269
270 Some(frame)
271 }
272
273 /// This is a hack to have a different [`CpuContext`] type/impl depending on the
274 /// context flags of the inner [`MipsContext`]
275 #[derive(Clone)]
276 struct Mips32Context(MipsContext);
277
278 impl CpuContext for Mips32Context {
279 type Register = u32;
280
281 const REGISTERS: &'static [&'static str] = <MipsContext as CpuContext>::REGISTERS;
282
283 fn get_register_always(&self, reg: &str) -> Self::Register {
284 self.0.get_register_always(reg) as u32
285 }
286
287 fn set_register(&mut self, reg: &str, val: Self::Register) -> Option<()> {
288 self.0.set_register(reg, val.into())
289 }
290
291 fn stack_pointer_register_name(&self) -> &'static str {
292 self.0.stack_pointer_register_name()
293 }
294
295 fn instruction_pointer_register_name(&self) -> &'static str {
296 self.0.instruction_pointer_register_name()
297 }
298 }
299
300 impl IntoRawContext for Mips32Context {
301 fn into_ctx(self) -> MinidumpRawContext {
302 MinidumpRawContext::Mips(self.0)
303 }
304 }
305
306 trait IntoRawContext {
307 fn into_ctx(self) -> MinidumpRawContext;
308 }
309
310 impl IntoRawContext for MipsContext {
311 fn into_ctx(self) -> MinidumpRawContext {
312 MinidumpRawContext::Mips(self)
313 }
314 }
315
316 impl TryFrom<MipsContext> for Mips32Context {
317 type Error = MipsContext;
318
319 fn try_from(ctx: MipsContext) -> Result<Self, Self::Error> {
320 if ContextFlagsCpu::from_flags(ctx.context_flags).contains(ContextFlagsCpu::CONTEXT_MIPS64)
321 {
322 Err(ctx)
323 } else {
324 Ok(Self(ctx))
325 }
326 }
327 }