1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
use super::register_ordering;
use super::unwindregs::{Reg, UnwindRegsX86_64};
use crate::error::Error;
use crate::unwind_rule::UnwindRule;
use arrayvec::ArrayVec;
/// For all of these: return address is *(new_sp - 8)
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum UnwindRuleX86_64 {
EndOfStack,
/// (sp, bp) = (sp + 8, bp)
JustReturn,
/// (sp, bp) = if is_first_frame (sp + 8, bp) else (bp + 16, *bp)
JustReturnIfFirstFrameOtherwiseFp,
/// (sp, bp) = (sp + 8x, bp)
OffsetSp {
sp_offset_by_8: u16,
},
/// (sp, bp) = (sp + 8x, *(sp + 8y))
OffsetSpAndRestoreBp {
sp_offset_by_8: u16,
bp_storage_offset_from_sp_by_8: i16,
},
/// (sp, bp) = (bp + 16, *bp)
UseFramePointer,
/// (sp, ...) = (sp + 8 * (offset + register count), ... popped according to encoded ordering)
/// This supports the common case of pushed callee-saved registers followed by a stack
/// allocation. Up to 8 registers can be stored, which covers all callee-saved registers (aside
/// from RSP which is implicit).
///
/// The registers are stored in a separate compressed ordering to facilitate restoring register
/// values if desired. If not for this we could simply store the total offset.
OffsetSpAndPopRegisters {
/// The additional stack pointer offset to undo before popping the registers, divided by 8 bytes.
sp_offset_by_8: u16,
/// The number of registers to pop from the stack.
register_count: u8,
/// An encoded ordering of the callee-save registers to pop from the stack, see register_ordering.
encoded_registers_to_pop: u16,
},
}
pub enum OffsetOrPop {
None,
OffsetBy8(u16),
Pop(Reg),
}
impl UnwindRuleX86_64 {
/// Get the rule which represents the given operations, if possible.
pub fn for_sequence_of_offset_or_pop<I, T>(iter: I) -> Option<Self>
where
I: Iterator<Item = T>,
T: Into<OffsetOrPop>,
{
let mut iter = iter.map(Into::into).peekable();
let sp_offset_by_8 = if let Some(&OffsetOrPop::OffsetBy8(offset)) = iter.peek() {
iter.next();
offset
} else {
0
};
let mut regs = ArrayVec::<Reg, 8>::new();
for i in iter {
if let OffsetOrPop::Pop(reg) = i {
// If try_push errors we've exceeded the number of supported registers: there's no
// way to encode these operations as an unwind rule.
regs.try_push(reg).ok()?;
} else {
return None;
}
}
if regs.is_empty() && sp_offset_by_8 == 0 {
Some(Self::JustReturn)
} else {
let (register_count, encoded_registers_to_pop) = register_ordering::encode(®s)?;
Some(Self::OffsetSpAndPopRegisters {
sp_offset_by_8,
register_count,
encoded_registers_to_pop,
})
}
}
}
impl UnwindRuleX86_64 {
/// Executes the rule. With `from_dwarf_row`, the rule was translated from a DWARF CFI
/// row and follows the full DWARF evaluation in `x86_64::dwarf`: the caller's RBP stays
/// unchanged when its slot cannot be read, and a CFA of RBP + 16 only has to advance the
/// unwind rather than move the stack pointer up.
fn exec_impl<F>(
self,
is_first_frame: bool,
from_dwarf_row: bool,
regs: &mut UnwindRegsX86_64,
read_stack: &mut F,
) -> Result<Option<u64>, Error>
where
F: FnMut(u64) -> Result<u64, ()>,
{
let sp = regs.sp();
let mut restored_regs = ArrayVec::<(Reg, u64), 8>::new();
let (new_sp, new_bp) = match self {
UnwindRuleX86_64::EndOfStack => return Ok(None),
UnwindRuleX86_64::JustReturn => {
let new_sp = sp.checked_add(8).ok_or(Error::IntegerOverflow)?;
(new_sp, regs.bp())
}
UnwindRuleX86_64::JustReturnIfFirstFrameOtherwiseFp => {
if is_first_frame {
let new_sp = sp.checked_add(8).ok_or(Error::IntegerOverflow)?;
(new_sp, regs.bp())
} else {
let sp = regs.sp();
let bp = regs.bp();
if bp == 0 {
return Ok(None);
}
let new_sp = bp.checked_add(16).ok_or(Error::IntegerOverflow)?;
if new_sp <= sp {
return Err(Error::FramepointerUnwindingMovedBackwards);
}
let new_bp = read_stack(bp).map_err(|_| Error::CouldNotReadStack(bp))?;
(new_sp, new_bp)
}
}
UnwindRuleX86_64::OffsetSp { sp_offset_by_8 } => {
let sp_offset = u64::from(sp_offset_by_8) * 8;
let new_sp = sp.checked_add(sp_offset).ok_or(Error::IntegerOverflow)?;
(new_sp, regs.bp())
}
UnwindRuleX86_64::OffsetSpAndRestoreBp {
sp_offset_by_8,
bp_storage_offset_from_sp_by_8,
} => {
let sp_offset = u64::from(sp_offset_by_8) * 8;
let new_sp = sp.checked_add(sp_offset).ok_or(Error::IntegerOverflow)?;
let bp_storage_offset_from_sp = i64::from(bp_storage_offset_from_sp_by_8) * 8;
let bp_location = sp
.checked_add_signed(bp_storage_offset_from_sp)
.ok_or(Error::IntegerOverflow)?;
let new_bp = match read_stack(bp_location) {
Ok(new_bp) => new_bp,
Err(()) if from_dwarf_row || (is_first_frame && bp_location < sp) => {
// DWARF rows keep the current RBP on any read error, like the full
// evaluation does. Other rules ignore errors when reading beyond the
// stack pointer in the first frame. These negative offsets are sometimes seen in x86_64 epilogues, where
// a bunch of registers are popped one after the other, and the compiler
// doesn't always set the already-popped register to "unchanged" (because
// doing so would take up extra space in the dwarf information).
// read_stack may legitimately refuse to read beyond the stack pointer,
// for example when the stack bytes are coming from a linux perf event
// sample record, where the ustack bytes are copied starting from sp.
regs.bp()
}
Err(()) => return Err(Error::CouldNotReadStack(bp_location)),
};
(new_sp, new_bp)
}
UnwindRuleX86_64::UseFramePointer => {
// Do a frame pointer stack walk. Code that is compiled with frame pointers
// has the following function prologues and epilogues:
//
// Function prologue:
// pushq %rbp
// movq %rsp, %rbp
//
// Function epilogue:
// popq %rbp
// ret
//
// Functions are called with callq; callq pushes the return address onto the stack.
// When a function reaches its end, ret pops the return address from the stack and jumps to it.
// So when a function is called, we have the following stack layout:
//
// [... rest of the stack]
// ^ rsp ^ rbp
// callq some_function
// [return address] [... rest of the stack]
// ^ rsp ^ rbp
// pushq %rbp
// [caller's frame pointer] [return address] [... rest of the stack]
// ^ rsp ^ rbp
// movq %rsp, %rbp
// [caller's frame pointer] [return address] [... rest of the stack]
// ^ rsp, rbp
// <other instructions>
// [... more stack] [caller's frame pointer] [return address] [... rest of the stack]
// ^ rsp ^ rbp
//
// So: *rbp is the caller's frame pointer, and *(rbp + 8) is the return address.
//
// Or, in other words, the following linked list is built up on the stack:
// #[repr(C)]
// struct CallFrameInfo {
// previous: *const CallFrameInfo,
// return_address: *const c_void,
// }
// and rbp is a *const CallFrameInfo.
let sp = regs.sp();
let bp = regs.bp();
if bp == 0 {
return Ok(None);
}
let new_sp = bp.checked_add(16).ok_or(Error::IntegerOverflow)?;
let moved_backwards = if from_dwarf_row {
!is_first_frame && new_sp < sp
} else {
new_sp <= sp
};
if moved_backwards {
return Err(Error::FramepointerUnwindingMovedBackwards);
}
let new_bp = match read_stack(bp) {
Ok(new_bp) => new_bp,
Err(()) if from_dwarf_row => bp,
Err(()) => return Err(Error::CouldNotReadStack(bp)),
};
// new_bp is the caller's bp. If the caller uses frame pointers, then bp should be
// a valid frame pointer and we could do a coherency check on new_bp to make sure
// it's moving in the right direction. But if the caller is using bp as a general
// purpose register, then any value (including zero) would be a valid value.
// At this point we don't know how the caller uses bp, so we leave new_bp unchecked.
(new_sp, new_bp)
}
UnwindRuleX86_64::OffsetSpAndPopRegisters {
sp_offset_by_8,
register_count,
encoded_registers_to_pop,
} => {
let sp = regs.sp();
let mut sp = sp
.checked_add(sp_offset_by_8 as u64 * 8)
.ok_or(Error::IntegerOverflow)?;
for reg in register_ordering::decode(register_count, encoded_registers_to_pop) {
let value = read_stack(sp).map_err(|_| Error::CouldNotReadStack(sp))?;
sp = sp.checked_add(8).ok_or(Error::IntegerOverflow)?;
restored_regs.push((reg, value));
}
let new_bp = restored_regs
.iter()
.find_map(|(reg, value)| (*reg == Reg::RBP).then_some(*value))
.unwrap_or_else(|| regs.bp());
(sp.checked_add(8).ok_or(Error::IntegerOverflow)?, new_bp)
}
};
let return_address_location = new_sp.checked_sub(8).ok_or(Error::IntegerOverflow)?;
let return_address = read_stack(return_address_location)
.map_err(|_| Error::CouldNotReadStack(return_address_location))?;
if return_address == 0 {
return Ok(None);
}
if new_sp == sp && return_address == regs.ip() {
return Err(Error::DidNotAdvance);
}
regs.clear_non_frame_registers();
for (reg, value) in restored_regs {
regs.set(reg, value);
}
regs.set_ip(return_address);
regs.set_sp(new_sp);
regs.set_bp(new_bp);
Ok(Some(return_address))
}
}
impl UnwindRule for UnwindRuleX86_64 {
type UnwindRegs = UnwindRegsX86_64;
fn rule_for_stub_functions() -> Self {
UnwindRuleX86_64::JustReturn
}
fn rule_for_function_start() -> Self {
UnwindRuleX86_64::JustReturn
}
fn fallback_rule() -> Self {
UnwindRuleX86_64::UseFramePointer
}
fn exec<F>(
self,
is_first_frame: bool,
regs: &mut UnwindRegsX86_64,
read_stack: &mut F,
) -> Result<Option<u64>, Error>
where
F: FnMut(u64) -> Result<u64, ()>,
{
self.exec_impl(is_first_frame, false, regs, read_stack)
}
fn exec_with_dwarf_register_rules<F>(
self,
register_rules: u64,
is_first_frame: bool,
regs: &mut UnwindRegsX86_64,
read_stack: &mut F,
) -> Result<Option<u64>, Error>
where
F: FnMut(u64) -> Result<u64, ()>,
{
let preserved = DWARF_CALLEE_SAVED_REGISTERS.map(|register| regs.get_if_set(register));
let return_address = self.exec_impl(is_first_frame, true, regs, read_stack)?;
if return_address.is_some() {
let cfa = regs.sp();
for (index, (register, value)) in DWARF_CALLEE_SAVED_REGISTERS
.into_iter()
.zip(preserved)
.enumerate()
{
let value = match DwarfRegisterRule::unpack(register_rules, index) {
DwarfRegisterRule::SameValue => value,
DwarfRegisterRule::Undefined => None,
DwarfRegisterRule::Offset { cfa_offset_by_8 } => cfa
.checked_add_signed(i64::from(cfa_offset_by_8) * 8)
.and_then(|address| read_stack(address).ok()),
};
if let Some(value) = value {
regs.set(register, value);
}
}
}
Ok(return_address)
}
}
/// The callee-saved registers that DWARF CFI rows can recover through a cached rule, in the
/// order in which their rules are packed.
pub(crate) const DWARF_CALLEE_SAVED_REGISTERS: [Reg; 5] =
[Reg::RBX, Reg::R12, Reg::R13, Reg::R14, Reg::R15];
/// How a DWARF CFI row recovers one of the `DWARF_CALLEE_SAVED_REGISTERS`. The rules of a
/// row are packed into ten bits per register, so that zero is the DWARF default of keeping
/// every callee-saved register.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(crate) enum DwarfRegisterRule {
/// The caller has the same value as the callee.
SameValue,
/// The value in the caller is unknown.
Undefined,
/// The caller's value is stored at CFA + 8 * `cfa_offset_by_8`.
Offset { cfa_offset_by_8: i8 },
}
impl DwarfRegisterRule {
const PACKED_BITS: usize = 10;
pub(crate) fn pack(rules: [Self; DWARF_CALLEE_SAVED_REGISTERS.len()]) -> u64 {
rules
.into_iter()
.enumerate()
.fold(0, |packed, (index, rule)| {
let bits = match rule {
Self::SameValue => 0,
Self::Undefined => 1 << 8,
Self::Offset { cfa_offset_by_8 } => 2 << 8 | u64::from(cfa_offset_by_8 as u8),
};
packed | bits << (index * Self::PACKED_BITS)
})
}
fn unpack(packed: u64, index: usize) -> Self {
let bits = packed >> (index * Self::PACKED_BITS);
match (bits >> 8) & 0b11 {
1 => Self::Undefined,
2 => Self::Offset {
cfa_offset_by_8: bits as u8 as i8,
},
_ => Self::SameValue,
}
}
}
#[cfg(test)]
mod test {
use super::*;
#[test]
fn test_basic() {
let stack = [
1, 2, 0x100300, 4, 0x40, 0x100200, 5, 6, 0x70, 0x100100, 7, 8, 9, 10, 0x0, 0x0,
];
let mut read_stack = |addr| Ok(stack[(addr / 8) as usize]);
let mut regs = UnwindRegsX86_64::new(0x100400, 0x10, 0x20);
let res =
UnwindRuleX86_64::OffsetSp { sp_offset_by_8: 1 }.exec(true, &mut regs, &mut read_stack);
assert_eq!(res, Ok(Some(0x100300)));
assert_eq!(regs.ip(), 0x100300);
assert_eq!(regs.sp(), 0x18);
assert_eq!(regs.bp(), 0x20);
let res = UnwindRuleX86_64::UseFramePointer.exec(true, &mut regs, &mut read_stack);
assert_eq!(res, Ok(Some(0x100200)));
assert_eq!(regs.ip(), 0x100200);
assert_eq!(regs.sp(), 0x30);
assert_eq!(regs.bp(), 0x40);
let res = UnwindRuleX86_64::UseFramePointer.exec(false, &mut regs, &mut read_stack);
assert_eq!(res, Ok(Some(0x100100)));
assert_eq!(regs.ip(), 0x100100);
assert_eq!(regs.sp(), 0x50);
assert_eq!(regs.bp(), 0x70);
let res = UnwindRuleX86_64::UseFramePointer.exec(false, &mut regs, &mut read_stack);
assert_eq!(res, Ok(None));
}
#[test]
fn test_overflow() {
// This test makes sure that debug builds don't panic when trying to use frame pointer
// unwinding on code that was using the bp register as a general-purpose register and
// storing -1 in it. -1 is u64::MAX, so an unchecked add panics in debug builds.
let stack = [
1, 2, 0x100300, 4, 0x40, 0x100200, 5, 6, 0x70, 0x100100, 7, 8, 9, 10, 0x0, 0x0,
];
let mut read_stack = |addr| Ok(stack[(addr / 8) as usize]);
let mut regs = UnwindRegsX86_64::new(0x100400, u64::MAX / 8 * 8, u64::MAX);
let res = UnwindRuleX86_64::JustReturn.exec(true, &mut regs, &mut read_stack);
assert_eq!(res, Err(Error::IntegerOverflow));
let res =
UnwindRuleX86_64::OffsetSp { sp_offset_by_8: 1 }.exec(true, &mut regs, &mut read_stack);
assert_eq!(res, Err(Error::IntegerOverflow));
let res = UnwindRuleX86_64::OffsetSpAndRestoreBp {
sp_offset_by_8: 1,
bp_storage_offset_from_sp_by_8: 2,
}
.exec(true, &mut regs, &mut read_stack);
assert_eq!(res, Err(Error::IntegerOverflow));
let res = UnwindRuleX86_64::UseFramePointer.exec(true, &mut regs, &mut read_stack);
assert_eq!(res, Err(Error::IntegerOverflow));
}
#[test]
fn uncovered_older_frame_with_zero_bp_ends_stack() {
let mut regs = UnwindRegsX86_64::new(0x100400, 0x1000, 0);
let original_regs = regs;
let mut read_stack =
|_| -> Result<u64, ()> { panic!("a zero frame pointer should not read the stack") };
let result = UnwindRuleX86_64::JustReturnIfFirstFrameOtherwiseFp.exec(
false,
&mut regs,
&mut read_stack,
);
assert_eq!(result, Ok(None));
assert_eq!(regs, original_regs);
}
#[test]
fn test_unwind_clears_unrestored_general_purpose_registers() {
let stack = [0x100200, 0x100100];
let mut read_stack = |addr| Ok(stack[(addr / 8) as usize]);
let mut regs = UnwindRegsX86_64::new(0x100300, 0, 0x20);
regs.set(Reg::RAX, 0xaa);
regs.set(Reg::RBX, 0xbb);
let res =
UnwindRuleX86_64::OffsetSp { sp_offset_by_8: 1 }.exec(true, &mut regs, &mut read_stack);
assert_eq!(res, Ok(Some(0x100200)));
assert_eq!(regs.get_if_set(Reg::RAX), None);
assert_eq!(regs.get_if_set(Reg::RBX), None);
assert_eq!(regs.get_if_set(Reg::RSP), Some(8));
assert_eq!(regs.get_if_set(Reg::RBP), Some(0x20));
}
#[test]
fn test_unwind_keeps_restored_general_purpose_registers() {
let stack = [0xbeef, 0x100200];
let mut read_stack = |addr| Ok(stack[(addr / 8) as usize]);
let mut regs = UnwindRegsX86_64::new(0x100300, 0, 0x20);
regs.set(Reg::RAX, 0xaa);
regs.set(Reg::RBX, 0xbb);
let res = UnwindRuleX86_64::OffsetSpAndPopRegisters {
sp_offset_by_8: 0,
register_count: 1,
encoded_registers_to_pop: 0,
}
.exec(true, &mut regs, &mut read_stack);
assert_eq!(res, Ok(Some(0x100200)));
assert_eq!(regs.get_if_set(Reg::RAX), None);
assert_eq!(regs.get_if_set(Reg::RBX), Some(0xbeef));
assert_eq!(regs.get_if_set(Reg::RSP), Some(16));
assert_eq!(regs.get_if_set(Reg::RBP), Some(0x20));
}
#[test]
fn dwarf_register_defaults_preserve_only_callee_saved_registers() {
let stack = [0x100200];
let mut read_stack = |addr| Ok(stack[(addr / 8) as usize]);
let mut regs = UnwindRegsX86_64::new(0x100300, 0, 0x20);
regs.set(Reg::RAX, 0xaa);
regs.set(Reg::RBX, 0xbb);
regs.set(Reg::R12, 0xcc);
let res = UnwindRuleX86_64::OffsetSp { sp_offset_by_8: 1 }.exec_with_dwarf_register_rules(
0,
true,
&mut regs,
&mut read_stack,
);
assert_eq!(res, Ok(Some(0x100200)));
assert_eq!(regs.get_if_set(Reg::RAX), None);
assert_eq!(regs.get_if_set(Reg::RBX), Some(0xbb));
assert_eq!(regs.get_if_set(Reg::R12), Some(0xcc));
assert_eq!(regs.get_if_set(Reg::RSP), Some(8));
assert_eq!(regs.get_if_set(Reg::RBP), Some(0x20));
}
}