const MAX_CHAIN: usize = 32;
const MAX_INDIRECT: usize = 4;
const EPILOG_WINDOW: usize = 64;
const MAX_POPS: usize = 16;
const UNW_FLAG_CHAININFO: u8 = 0x4;
const IMAGE_FILE_MACHINE_AMD64: u16 = 0x8664;
const IMAGE_NT_OPTIONAL_HDR64_MAGIC: u16 = 0x20b;
const IMAGE_SCN_MEM_READ: u32 = 0x4000_0000;
const IMAGE_DIRECTORY_ENTRY_EXCEPTION: usize = 3;
const FIRST_HEADER_BYTES: usize = 4096;
const MAX_HEADER_BYTES: usize = 1 << 20;
pub(crate) const RSP: usize = 4;
pub(crate) trait Image {
fn read(&mut self, rva: u32, out: &mut [u8]) -> bool;
}
impl<F: FnMut(u32, &mut [u8]) -> bool> Image for F {
fn read(&mut self, rva: u32, out: &mut [u8]) -> bool {
self(rva, out)
}
}
fn u16_at(bytes: &[u8], at: usize) -> Option<u16> {
bytes
.get(at..at.checked_add(2)?)
.and_then(|b| b.try_into().ok())
.map(u16::from_le_bytes)
}
fn u32_at(bytes: &[u8], at: usize) -> Option<u32> {
bytes
.get(at..at.checked_add(4)?)
.and_then(|b| b.try_into().ok())
.map(u32::from_le_bytes)
}
fn i32_at(bytes: &[u8], at: usize) -> Option<i32> {
u32_at(bytes, at).map(|value| i32::from_le_bytes(value.to_le_bytes()))
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub(crate) struct PeImage {
pub size: u32,
pub stamp: u32,
pub checksum: u32,
pub exception: (u32, u32),
pub readable: Vec<(u32, u32)>,
}
impl PeImage {
pub fn is_readable(&self, rva: u32, len: usize) -> bool {
let Some(end) = u32::try_from(len).ok().and_then(|len| rva.checked_add(len)) else {
return false;
};
self.readable
.iter()
.any(|&(start, stop)| rva >= start && end <= stop)
}
}
pub(crate) fn parse_pe(bytes: &[u8]) -> Option<PeImage> {
if bytes.get(..2)? != b"MZ" {
return None;
}
let nt = usize::try_from(u32_at(bytes, 0x3c)?).ok()?;
if bytes.get(nt..nt.checked_add(4)?)? != b"PE\0\0" {
return None;
}
let file = nt + 4;
if u16_at(bytes, file)? != IMAGE_FILE_MACHINE_AMD64 {
return None;
}
let sections = usize::from(u16_at(bytes, file + 2)?);
let stamp = u32_at(bytes, file + 4)?;
let optional_size = usize::from(u16_at(bytes, file + 16)?);
let optional = file + 20;
if u16_at(bytes, optional)? != IMAGE_NT_OPTIONAL_HDR64_MAGIC {
return None;
}
let size = u32_at(bytes, optional + 56)?;
let headers = u32_at(bytes, optional + 60)?.min(size);
let checksum = u32_at(bytes, optional + 64)?;
let directories = usize::try_from(u32_at(bytes, optional + 108)?).ok()?;
let exception = if directories > IMAGE_DIRECTORY_ENTRY_EXCEPTION
&& optional_size >= 112 + 8 * (IMAGE_DIRECTORY_ENTRY_EXCEPTION + 1)
{
let at = optional + 112 + 8 * IMAGE_DIRECTORY_ENTRY_EXCEPTION;
(u32_at(bytes, at)?, u32_at(bytes, at + 4)?)
} else {
(0, 0)
};
let mut readable = vec![(0, headers)];
let table = optional.checked_add(optional_size)?;
for index in 0..sections {
let at = table.checked_add(index.checked_mul(40)?)?;
let header = bytes.get(at..at.checked_add(40)?)?;
let virtual_size = u32_at(header, 8)?;
let address = u32_at(header, 12)?;
let raw_size = u32_at(header, 16)?;
let characteristics = u32_at(header, 36)?;
let extent = if virtual_size == 0 {
raw_size
} else {
virtual_size
};
if characteristics & IMAGE_SCN_MEM_READ != 0 && address < size {
let end = address.saturating_add(extent).min(size);
readable.push((address, end));
}
}
Some(PeImage {
size,
stamp,
checksum,
exception,
readable,
})
}
fn header_len(bytes: &[u8]) -> Result<Option<usize>, usize> {
if bytes.get(..2) != Some(b"MZ") {
return Ok(None);
}
let Some(nt) = u32_at(bytes, 0x3c).and_then(|at| usize::try_from(at).ok()) else {
return Ok(None);
};
let Some(coff_end) = nt.checked_add(24) else {
return Ok(None);
};
if bytes.len() < coff_end {
return Err(coff_end);
}
if bytes.get(nt..nt + 4) != Some(b"PE\0\0") {
return Ok(None);
}
let len = u16_at(bytes, nt + 6)
.zip(u16_at(bytes, nt + 20))
.and_then(|(sections, optional)| {
usize::from(sections)
.checked_mul(40)?
.checked_add(usize::from(optional))?
.checked_add(coff_end)
});
Ok(len)
}
pub(crate) fn read_pe(mut read: impl FnMut(&mut [u8]) -> usize) -> Option<PeImage> {
let mut bytes = vec![0_u8; FIRST_HEADER_BYTES];
for _ in 0..3 {
let asked = bytes.len();
let got = read(&mut bytes).min(asked);
bytes.truncate(got);
let wanted = match header_len(&bytes) {
Ok(Some(len)) if len <= got => return parse_pe(bytes.get(..len)?),
Ok(Some(len)) | Err(len) => len,
Ok(None) => return None,
};
if got < asked || wanted > MAX_HEADER_BYTES {
return None;
}
bytes.resize(wanted, 0);
}
None
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(crate) struct RuntimeFunction {
pub begin: u32,
pub end: u32,
pub unwind: u32,
}
impl RuntimeFunction {
fn from_bytes(bytes: &[u8]) -> Option<Self> {
Some(Self {
begin: u32_at(bytes, 0)?,
end: u32_at(bytes, 4)?,
unwind: u32_at(bytes, 8)?,
})
}
}
pub(crate) fn parse_pdata(bytes: &[u8]) -> Vec<RuntimeFunction> {
bytes
.as_chunks::<12>()
.0
.iter()
.filter_map(|entry| RuntimeFunction::from_bytes(entry))
.collect()
}
fn resolve(mut function: RuntimeFunction, image: &mut impl Image) -> Option<RuntimeFunction> {
for _ in 0..=MAX_INDIRECT {
if function.unwind & 1 == 0 {
return Some(function);
}
let mut bytes = [0_u8; 12];
if !image.read(function.unwind & !1, &mut bytes) {
return None;
}
function = RuntimeFunction::from_bytes(&bytes)?;
}
None
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(crate) struct Entry {
pub sampled: RuntimeFunction,
pub function: RuntimeFunction,
}
pub(crate) fn lookup(table: &[RuntimeFunction], rva: u32, image: &mut impl Image) -> Option<Entry> {
let after = table.partition_point(|function| function.begin <= rva);
let sampled = *table.get(after.checked_sub(1)?)?;
if rva >= sampled.end {
return None;
}
Some(Entry {
sampled,
function: resolve(sampled, image)?,
})
}
fn primary_entry(mut function: RuntimeFunction, image: &mut impl Image) -> Option<RuntimeFunction> {
for _ in 0..=MAX_CHAIN {
let mut header = [0_u8; 4];
if !image.read(function.unwind, &mut header) {
return None;
}
if (header[0] >> 3) & UNW_FLAG_CHAININFO == 0 {
return Some(function);
}
let count = u32::from(header[2]);
let at = function.unwind.checked_add(4 + (count + (count & 1)) * 2)?;
let mut bytes = [0_u8; 12];
if !image.read(at, &mut bytes) {
return None;
}
function = resolve(RuntimeFunction::from_bytes(&bytes)?, image)?;
}
None
}
fn same_function(
function: RuntimeFunction,
target: u32,
table: &[RuntimeFunction],
image: &mut impl Image,
) -> Option<RuntimeFunction> {
let primary = primary_entry(function, image)?;
let other = primary_entry(lookup(table, target, image)?.function, image)?;
(other.begin == primary.begin).then_some(primary)
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
enum Op {
Push(u8),
Alloc(u64),
SetFrame,
Save(u8, u64),
Skip,
MachineFrame(bool),
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
struct Code {
offset: u8,
op: Op,
}
#[derive(Clone, Debug, Default, PartialEq, Eq)]
struct Epilogs {
size: u8,
at_end: bool,
back: Vec<u16>,
}
impl Epilogs {
fn holding(&self, function: RuntimeFunction, pc: u32) -> Option<u32> {
let size = u32::from(self.size);
let at_end = self.at_end.then_some(size);
at_end
.into_iter()
.chain(self.back.iter().map(|&back| u32::from(back)))
.map(|back| pc.wrapping_sub(function.end.wrapping_sub(back)))
.find(|&into| into < size)
}
}
#[derive(Clone, Debug, PartialEq, Eq)]
struct Block {
version: u8,
epilogs: Option<Epilogs>,
prolog: u8,
frame_register: u8,
frame_offset: u64,
chained: bool,
codes: Vec<Code>,
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub(crate) struct UnwindPlan {
blocks: Vec<Block>,
}
fn decode_block(
rva: u32,
image: &mut impl Image,
depth: usize,
primary_frame: u8,
) -> Option<(Block, Option<u32>)> {
let mut header = [0_u8; 4];
if !image.read(rva, &mut header) {
return None;
}
let [version_flags, prolog, count, frame] = header;
let version = version_flags & 7;
let chained = (version_flags >> 3) & UNW_FLAG_CHAININFO != 0;
if version != 1 && version != 2 {
return None;
}
let frame_register = frame & 0xf;
if depth > 0 && frame_register != 0 && frame_register != primary_frame {
return None;
}
let count = usize::from(count);
let padded = count + (count & 1);
let mut raw = [0_u8; 512 + 12];
let wanted = raw.get_mut(..padded * 2 + if chained { 12 } else { 0 })?;
if !image.read(rva.checked_add(4)?, wanted) {
return None;
}
let slot = |index: usize| u16_at(wanted, index * 2);
let far = |index: usize| -> Option<u64> {
Some(u64::from(slot(index + 1)?) | (u64::from(slot(index + 2)?) << 16))
};
let op_of = |index: usize| {
wanted
.get(index * 2 + 1)
.map(|&byte| (byte & 0xf, byte >> 4))
};
let epilogs = match (version, op_of(0)) {
(2, Some((6, info))) if count > 0 => {
let back = (1..count)
.map_while(|index| match op_of(index)? {
(6, high) => {
let low = *wanted.get(index * 2)?;
let back = u16::from(low) | (u16::from(high) << 8);
(back != 0).then_some(back)
}
_ => None,
})
.collect();
Some(Epilogs {
size: *wanted.first()?,
at_end: info & 1 != 0,
back,
})
}
_ => None,
};
let mut codes = Vec::with_capacity(count);
let mut i = 0;
while i < count {
let offset = *wanted.get(i * 2)?;
let op_byte = *wanted.get(i * 2 + 1)?;
let (op, info) = (op_byte & 0xf, op_byte >> 4);
let (decoded, used) = match op {
0 => (Op::Push(info), 1),
1 => match info {
0 => (Op::Alloc(u64::from(slot(i + 1)?) * 8), 2),
1 => (Op::Alloc(far(i)?), 3),
_ => return None,
},
2 => (Op::Alloc(u64::from(info) * 8 + 8), 1),
3 => {
if frame_register == 0 {
return None;
}
(Op::SetFrame, 1)
}
4 => (Op::Save(info, u64::from(slot(i + 1)?) * 8), 2),
5 => (Op::Save(info, far(i)?), 3),
6 if version == 2 => (Op::Skip, 2),
8 => {
slot(i + 1)?;
(Op::Skip, 2)
}
9 => {
far(i)?;
(Op::Skip, 3)
}
10 => {
if info > 1 || i + 1 != count || chained {
return None;
}
(Op::MachineFrame(info == 1), 1)
}
_ => return None,
};
codes.push(Code {
offset,
op: decoded,
});
i += used;
}
if i != count {
return None;
}
let next = if chained {
let function = RuntimeFunction::from_bytes(wanted.get(padded * 2..)?)?;
Some(resolve(function, image)?.unwind)
} else {
None
};
let block = Block {
version,
epilogs,
prolog,
frame_register,
frame_offset: u64::from(frame >> 4) * 16,
chained,
codes,
};
Some((block, next))
}
pub(crate) fn load_plan(rva: u32, image: &mut impl Image) -> Option<UnwindPlan> {
let mut blocks: Vec<Block> = Vec::new();
let mut next = Some(rva);
while let Some(rva) = next {
if blocks.len() >= MAX_CHAIN {
return None;
}
let primary = blocks.first().map_or(0, |block| block.frame_register);
let (block, chained) = decode_block(rva, image, blocks.len(), primary)?;
blocks.push(block);
next = chained;
}
Some(UnwindPlan { blocks })
}
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub(crate) struct Registers {
pub rip: u64,
pub gpr: [u64; 16],
}
impl Registers {
pub fn rsp(&self) -> u64 {
self.gpr[RSP]
}
fn get(&self, number: u8) -> Option<u64> {
self.gpr.get(usize::from(number)).copied()
}
fn set(&mut self, number: u8, value: u64) -> Option<()> {
*self.gpr.get_mut(usize::from(number))? = value;
Some(())
}
}
#[derive(Clone, Copy, Debug)]
pub(crate) struct StackCopy<'a> {
pub base: u64,
pub bytes: &'a [u8],
}
impl StackCopy<'_> {
pub fn word(&self, address: u64) -> Option<u64> {
let at = usize::try_from(address.checked_sub(self.base)?).ok()?;
let bytes = self.bytes.get(at..at.checked_add(8)?)?;
Some(u64::from_le_bytes(bytes.try_into().ok()?))
}
pub fn holds(&self, address: u64) -> bool {
self.word(address).is_some()
}
}
#[derive(Clone, Copy, Debug)]
pub(crate) struct Frame<'a> {
pub entry: Entry,
pub plan: &'a UnwindPlan,
pub pc: u32,
pub exact: bool,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(crate) enum Stepped {
Return,
MachineFrame,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
struct Epilog {
adjust: Option<(bool, i64)>,
pops: [u8; MAX_POPS],
pop_count: usize,
release: u64,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
enum InEpilog {
Decoded(Epilog),
Described(u32),
}
fn read_window(image: &mut impl Image, rva: u32, out: &mut [u8; EPILOG_WINDOW]) -> usize {
if image.read(rva, out) {
return EPILOG_WINDOW;
}
let (mut good, mut bad) = (0, EPILOG_WINDOW);
while bad - good > 1 {
let mid = good + (bad - good) / 2;
if out.get_mut(..mid).is_some_and(|part| image.read(rva, part)) {
good = mid;
} else {
bad = mid;
}
}
if out
.get_mut(..good)
.is_some_and(|part| image.read(rva, part))
{
good
} else {
0
}
}
fn decode_epilog(
code: &[u8],
rva: u32,
function: RuntimeFunction,
block: &Block,
table: &[RuntimeFunction],
image: &mut impl Image,
) -> Option<Epilog> {
let frame_register = block.frame_register;
let byte = |at: usize| code.get(at).copied();
let mut at = 0;
let mut adjust = None;
let (b0, b1, b2) = (byte(0)?, byte(1), byte(2));
if b0 & 0xf8 == 0x48 {
match (b1, b2) {
(Some(0x83), Some(0xc4)) if b0 == 0x48 => {
adjust = Some((false, i64::from(i8::from_le_bytes([byte(3)?]))));
at = 4;
}
(Some(0x81), Some(0xc4)) if b0 == 0x48 => {
adjust = Some((false, i64::from(i32_at(code, 3)?)));
at = 7;
}
(Some(0x8d), Some(modrm)) if b0 & 0xfe == 0x48 => {
let base = ((b0 & 1) << 3) | (modrm & 7);
if base != 0 && base == frame_register && modrm & 7 != 4 {
match modrm & 0xf8 {
0x60 => {
adjust = Some((true, i64::from(i8::from_le_bytes([byte(3)?]))));
at = 4;
}
0xa0 => {
adjust = Some((true, i64::from(i32_at(code, 3)?)));
at = 7;
}
_ => return None,
}
} else {
return None;
}
}
_ => {}
}
}
let mut pops = [0_u8; MAX_POPS];
let mut pop_count = 0;
loop {
let (rex, op) = match byte(at)? {
prefix @ 0x40..=0x4f => (prefix, byte(at + 1)?),
op => (0, op),
};
if op & 0xf8 != 0x58 {
break;
}
*pops.get_mut(pop_count)? = ((rex & 1) << 3) | (op & 7);
pop_count += 1;
at += if rex == 0 { 1 } else { 2 };
}
if byte(at)? == 0xf2 {
at += 1;
}
let release = match (byte(at)?, byte(at + 1)) {
(0xc3, _) | (0xf3, Some(0xc3)) | (0xff, Some(0x25)) => 0,
(0xc2, _) => u64::from(u16_at(code, at + 1)?),
(op @ (0xeb | 0xe9), _) => {
let (length, displacement) = if op == 0xeb {
(2, i64::from(i8::from_le_bytes([byte(at + 1)?])))
} else {
(5, i64::from(i32_at(code, at + 1)?))
};
let next = i64::from(rva) + i64::try_from(at).ok()? + length;
let tail_call = match u32::try_from(next + displacement) {
Err(_) => true,
Ok(target) if target < function.begin || target >= function.end => {
same_function(function, target, table, image)
.is_none_or(|primary| target == primary.begin)
}
Ok(target) => target == function.begin && !block.chained,
};
if !tail_call {
return None;
}
0
}
(rex, Some(0xff)) if rex & 0xf8 == 0x48 && byte(at + 2)? & 0x38 == 0x20 => 0,
_ => return None,
};
Some(Epilog {
adjust,
pops,
pop_count,
release,
})
}
fn find_epilog(
frame: &Frame,
block: &Block,
table: &[RuntimeFunction],
image: &mut impl Image,
) -> Option<InEpilog> {
if block.version >= 2 {
let epilogs = block.epilogs.as_ref()?;
return epilogs
.holding(frame.entry.function, frame.pc)
.map(InEpilog::Described);
}
let mut window = [0_u8; EPILOG_WINDOW];
let len = read_window(image, frame.pc, &mut window);
let code = window.get(..len)?;
decode_epilog(code, frame.pc, frame.entry.function, block, table, image).map(InEpilog::Decoded)
}
fn emulate_epilog(
epilog: &Epilog,
frame_register: u8,
regs: &mut Registers,
stack: &StackCopy,
) -> Option<()> {
match epilog.adjust {
Some((false, add)) => regs.gpr[RSP] = regs.rsp().checked_add_signed(add)?,
Some((true, disp)) => regs.gpr[RSP] = regs.get(frame_register)?.checked_add_signed(disp)?,
None => {}
}
for ®ister in epilog.pops.get(..epilog.pop_count)? {
let value = stack.word(regs.rsp())?;
regs.set(register, value)?;
regs.gpr[RSP] = regs.rsp().checked_add(8)?;
}
regs.rip = stack.word(regs.rsp())?;
regs.gpr[RSP] = regs.rsp().checked_add(8)?.checked_add(epilog.release)?;
Some(())
}
fn finish_described_epilog(
plan: &UnwindPlan,
into: u32,
regs: &mut Registers,
stack: &StackCopy,
) -> Option<Stepped> {
let pushes = |code: &Code| matches!(code.op, Op::Push(_) | Op::MachineFrame(_));
let codes = plan
.blocks
.iter()
.find_map(|block| block.codes.get(block.codes.iter().position(pushes)?..))
.unwrap_or_default();
let mut codes = codes.iter().peekable();
let mut done = 0_u32;
while let Some(&&Code {
op: Op::Push(register),
..
}) = codes.peek()
{
if done >= into {
let value = stack.word(regs.rsp())?;
regs.set(register, value)?;
regs.gpr[RSP] = regs.rsp().checked_add(8)?;
}
done += if register >= 8 { 2 } else { 1 };
codes.next();
}
if codes.next_if(|code| code.op == Op::Alloc(8)).is_some() && done >= into {
regs.gpr[RSP] = regs.rsp().checked_add(8)?;
}
match codes.next() {
None => {}
Some(&Code {
op: Op::MachineFrame(_),
..
}) => {
regs.rip = stack.word(regs.rsp())?;
regs.gpr[RSP] = stack.word(regs.rsp().checked_add(24)?)?;
return Some(Stepped::MachineFrame);
}
Some(_) => return None,
}
regs.rip = stack.word(regs.rsp())?;
regs.gpr[RSP] = regs.rsp().checked_add(8)?;
Some(Stepped::Return)
}
pub(crate) fn step(
frame: &Frame,
regs: &mut Registers,
stack: &StackCopy,
table: &[RuntimeFunction],
image: &mut impl Image,
) -> Option<Stepped> {
let primary = frame.plan.blocks.first()?;
let Entry { sampled, function } = frame.entry;
let pc = frame.pc;
if pc < sampled.begin || pc > sampled.end || (frame.exact && pc == sampled.end) {
return None;
}
let offset = if pc >= function.begin && pc <= function.end {
pc - function.begin
} else {
u32::MAX
};
let in_prolog = offset < u32::from(primary.prolog);
let mut next = *regs;
let frame_register = primary.frame_register;
if frame.exact
&& !in_prolog
&& let Some(epilog) = find_epilog(frame, primary, table, image)
{
let stepped = match epilog {
InEpilog::Decoded(epilog) => {
emulate_epilog(&epilog, frame_register, &mut next, stack)?;
Stepped::Return
}
InEpilog::Described(into) => {
finish_described_epilog(frame.plan, into, &mut next, stack)?
}
};
*regs = next;
return Some(stepped);
}
let from_frame = |regs: &Registers| regs.get(frame_register)?.checked_sub(primary.frame_offset);
let frame_base = if frame_register == 0 {
Some(regs.rsp())
} else if !in_prolog || primary.chained {
from_frame(regs)
} else {
primary
.codes
.iter()
.find(|code| code.op == Op::SetFrame)
.and_then(|code| {
if offset >= u32::from(code.offset) {
from_frame(regs)
} else {
Some(regs.rsp())
}
})
};
let mut machine_frame = false;
for (index, block) in frame.plan.blocks.iter().enumerate() {
for code in &block.codes {
if index == 0 && offset < u32::from(code.offset) {
continue;
}
match code.op {
Op::Push(register) => {
let value = stack.word(next.rsp())?;
next.set(register, value)?;
next.gpr[RSP] = next.rsp().checked_add(8)?;
}
Op::Alloc(bytes) => next.gpr[RSP] = next.rsp().checked_add(bytes)?,
Op::SetFrame => {
next.gpr[RSP] = next
.get(block.frame_register)?
.checked_sub(block.frame_offset)?;
}
Op::Save(register, at) => {
let value = stack.word(frame_base?.checked_add(at)?)?;
next.set(register, value)?;
}
Op::Skip => {}
Op::MachineFrame(error_code) => {
let base = next.rsp().checked_add(if error_code { 8 } else { 0 })?;
next.rip = stack.word(base)?;
next.gpr[RSP] = stack.word(base.checked_add(24)?)?;
machine_frame = true;
}
}
}
}
if machine_frame {
*regs = next;
return Some(Stepped::MachineFrame);
}
next.rip = stack.word(next.rsp())?;
next.gpr[RSP] = next.rsp().checked_add(8)?;
*regs = next;
Some(Stepped::Return)
}
#[cfg(test)]
mod tests {
use super::*;
struct Fake(Vec<u8>);
impl Fake {
fn new() -> Self {
Self(vec![0; 0x2000])
}
fn put(&mut self, rva: usize, bytes: &[u8]) {
self.0[rva..rva + bytes.len()].copy_from_slice(bytes);
}
fn info_v(
&mut self,
rva: usize,
version: u8,
flags: u8,
prolog: u8,
frame: u8,
slots: &[u16],
) {
let mut bytes = vec![
version | (flags << 3),
prolog,
u8::try_from(slots.len()).unwrap(),
frame,
];
for slot in slots {
bytes.extend(slot.to_le_bytes());
}
self.put(rva, &bytes);
}
fn info(&mut self, rva: usize, flags: u8, prolog: u8, frame: u8, slots: &[u16]) {
self.info_v(rva, 1, flags, prolog, frame, slots);
}
fn function(&mut self, rva: usize, begin: u32, end: u32, unwind: u32) {
let mut bytes = Vec::new();
bytes.extend(begin.to_le_bytes());
bytes.extend(end.to_le_bytes());
bytes.extend(unwind.to_le_bytes());
self.put(rva, &bytes);
}
fn reader(&self) -> impl FnMut(u32, &mut [u8]) -> bool + '_ {
|rva, out| {
let start = rva as usize;
match self.0.get(start..start + out.len()) {
Some(src) => {
out.copy_from_slice(src);
true
}
None => false,
}
}
}
fn plan(&self, rva: u32) -> Option<UnwindPlan> {
load_plan(rva, &mut self.reader())
}
}
fn code(offset: u8, op: u8, info: u8) -> u16 {
u16::from(offset) | (u16::from(op | (info << 4)) << 8)
}
fn stack_of(words: &[u64]) -> Vec<u8> {
words.iter().flat_map(|word| word.to_le_bytes()).collect()
}
const BASE: u64 = 0x10_0000;
const FUNCTION: RuntimeFunction = RuntimeFunction {
begin: 0x1000,
end: 0x1100,
unwind: 0x100,
};
const ENTRY: Entry = Entry {
sampled: FUNCTION,
function: FUNCTION,
};
const fn function(begin: u32, end: u32, unwind: u32) -> RuntimeFunction {
RuntimeFunction { begin, end, unwind }
}
fn step_over(
image: &Fake,
frame: &Frame,
table: &[RuntimeFunction],
regs: &mut Registers,
bytes: &[u8],
) -> Option<Stepped> {
let stack = StackCopy { base: BASE, bytes };
step(frame, regs, &stack, table, &mut image.reader())
}
fn regs(rsp: u64) -> Registers {
let mut regs = Registers::default();
regs.gpr[RSP] = rsp;
regs
}
fn run(
image: &Fake,
plan: &UnwindPlan,
pc: u32,
exact: bool,
regs: &mut Registers,
bytes: &[u8],
) -> Option<Stepped> {
let frame = Frame {
entry: ENTRY,
plan,
pc,
exact,
};
let stack = StackCopy { base: BASE, bytes };
step(&frame, regs, &stack, &[FUNCTION], &mut image.reader())
}
#[test]
fn stack_words_stay_inside_the_copy() {
let bytes = stack_of(&[1, 2]);
let stack = StackCopy {
base: BASE,
bytes: &bytes,
};
assert_eq!(stack.word(BASE), Some(1));
assert_eq!(stack.word(BASE + 8), Some(2));
assert_eq!(stack.word(BASE + 9), None, "runs past the end");
assert_eq!(stack.word(BASE + 16), None);
assert_eq!(stack.word(BASE - 8), None);
assert_eq!(stack.word(u64::MAX - 3), None);
assert!(
!StackCopy {
base: 0,
bytes: &[]
}
.holds(0)
);
}
#[test]
fn a_leaf_info_pops_only_the_return_address() {
let mut image = Fake::new();
image.info(0x100, 0, 0, 0, &[]);
let plan = image.plan(0x100).unwrap();
let bytes = stack_of(&[0xdead]);
let mut r = regs(BASE);
assert_eq!(
run(&image, &plan, 0x1010, false, &mut r, &bytes),
Some(Stepped::Return)
);
assert_eq!((r.rip, r.rsp()), (0xdead, BASE + 8));
}
#[test]
fn prolog_codes_apply_only_once_executed() {
let mut image = Fake::new();
image.info(
0x100,
0,
6,
0,
&[code(6, 2, 1), code(2, 0, 5), code(1, 0, 3)],
);
let plan = image.plan(0x100).unwrap();
let bytes = stack_of(&[0, 0, 0xb9, 0xb3, 0xaaa]);
let mut r = regs(BASE);
run(&image, &plan, 0x1020, false, &mut r, &bytes).unwrap();
assert_eq!(
(r.rip, r.rsp(), r.gpr[5], r.gpr[3]),
(0xaaa, BASE + 40, 0xb9, 0xb3)
);
let bytes = stack_of(&[0xb3, 0xbbb]);
let mut r = regs(BASE);
run(&image, &plan, 0x1001, true, &mut r, &bytes).unwrap();
assert_eq!((r.rip, r.rsp(), r.gpr[3]), (0xbbb, BASE + 16, 0xb3));
let bytes = stack_of(&[0xccc]);
let mut r = regs(BASE);
run(&image, &plan, 0x1000, true, &mut r, &bytes).unwrap();
assert_eq!((r.rip, r.rsp()), (0xccc, BASE + 8));
}
#[test]
fn large_allocations_and_far_saves() {
let mut image = Fake::new();
image.info(
0x100,
0,
12,
0,
&[code(12, 5, 6), 0x0008, 0x0000, code(7, 1, 0), 3],
);
let plan = image.plan(0x100).unwrap();
let bytes = stack_of(&[0, 0x51, 0, 0x777]);
let mut r = regs(BASE);
run(&image, &plan, 0x1040, false, &mut r, &bytes).unwrap();
assert_eq!((r.rip, r.rsp(), r.gpr[6]), (0x777, BASE + 32, 0x51));
image.info(0x200, 0, 9, 0, &[code(9, 1, 1), 0x0010, 0x0000]);
let plan = image.plan(0x200).unwrap();
let mut words = vec![0_u64; 2];
words.push(0x888);
let mut r = regs(BASE);
run(&image, &plan, 0x1040, false, &mut r, &stack_of(&words)).unwrap();
assert_eq!((r.rip, r.rsp()), (0x888, BASE + 24));
}
#[test]
fn frame_register_establishes_the_frame() {
let mut image = Fake::new();
image.info(
0x100,
0,
14,
5 | (1 << 4),
&[
code(14, 4, 3),
1,
code(10, 3, 0),
code(5, 2, 3),
code(1, 0, 5),
],
);
let plan = image.plan(0x100).unwrap();
let frame = BASE + 0x40;
let mut words = vec![0_u64; 8];
words.extend([0, 0xb3, 0, 0, 0xb9, 0x999]);
let bytes = stack_of(&words);
let mut r = regs(BASE);
r.gpr[5] = frame + 0x10;
run(&image, &plan, 0x1050, false, &mut r, &bytes).unwrap();
assert_eq!(r.gpr[3], 0xb3, "rbx from [frame base + 8]");
assert_eq!((r.rip, r.gpr[5], r.rsp()), (0x999, 0xb9, frame + 0x30));
let mut r = regs(BASE);
r.gpr[5] = 0x8;
assert_eq!(run(&image, &plan, 0x1050, false, &mut r, &bytes), None);
assert_eq!(r.gpr[5], 0x8, "registers untouched on a stop");
}
#[test]
fn in_the_prolog_the_frame_register_counts_once_set() {
let mut image = Fake::new();
image.info(
0x100,
0,
8,
5,
&[code(8, 2, 1), code(4, 3, 0), code(1, 0, 5)],
);
let plan = image.plan(0x100).unwrap();
let bytes = stack_of(&[0xb9, 0x123]);
let mut r = regs(BASE);
r.gpr[5] = BASE;
run(&image, &plan, 0x1004, true, &mut r, &bytes).unwrap();
assert_eq!((r.rip, r.gpr[5], r.rsp()), (0x123, 0xb9, BASE + 16));
let mut r = regs(BASE);
r.gpr[5] = 0x5555;
run(&image, &plan, 0x1001, true, &mut r, &bytes).unwrap();
assert_eq!((r.rip, r.gpr[5], r.rsp()), (0x123, 0xb9, BASE + 16));
}
#[test]
fn machine_frames_give_an_exact_pc() {
let mut image = Fake::new();
image.info(0x100, 0, 0, 0, &[code(0, 10, 0)]);
let plan = image.plan(0x100).unwrap();
let bytes = stack_of(&[0x4242, 0x33, 0x246, BASE + 0x1000, 0x2b]);
let mut r = regs(BASE);
assert_eq!(
run(&image, &plan, 0x1000, false, &mut r, &bytes),
Some(Stepped::MachineFrame)
);
assert_eq!((r.rip, r.rsp()), (0x4242, BASE + 0x1000));
image.info(0x180, 0, 0, 0, &[code(0, 10, 1)]);
let plan = image.plan(0x180).unwrap();
let bytes = stack_of(&[7, 0x4343, 0x33, 0x246, BASE + 0x2000, 0x2b]);
let mut r = regs(BASE);
run(&image, &plan, 0x1000, false, &mut r, &bytes).unwrap();
assert_eq!((r.rip, r.rsp()), (0x4343, BASE + 0x2000));
let mut r = regs(BASE);
assert_eq!(
run(&image, &plan, 0x1000, false, &mut r, &bytes[..32]),
None
);
}
#[test]
fn chained_infos_apply_in_full() {
let mut image = Fake::new();
image.info(0x100, UNW_FLAG_CHAININFO, 1, 0, &[code(1, 0, 3)]);
image.function(0x100 + 4 + 4, 0x800, 0x900, 0x200);
image.info(0x200, 0, 5, 0, &[code(5, 2, 2), code(1, 0, 5)]);
let plan = image.plan(0x100).unwrap();
let bytes = stack_of(&[0xb3, 0, 0, 0, 0xb9, 0xabc]);
let mut r = regs(BASE);
run(&image, &plan, 0x1010, false, &mut r, &bytes).unwrap();
assert_eq!(
(r.rip, r.rsp(), r.gpr[3], r.gpr[5]),
(0xabc, BASE + 48, 0xb3, 0xb9)
);
}
#[test]
fn chained_frame_registers_must_agree() {
let mut image = Fake::new();
image.info(0x100, UNW_FLAG_CHAININFO, 0, 5, &[]);
image.function(0x104, 0x800, 0x900, 0x200);
image.info(0x200, 0, 4, 5, &[code(4, 3, 0), code(1, 0, 5)]);
let plan = image.plan(0x100).unwrap();
let bytes = stack_of(&[0, 0, 0xb9, 0xfed]);
let mut r = regs(BASE);
r.gpr[5] = BASE + 16;
run(&image, &plan, 0x1010, false, &mut r, &bytes).unwrap();
assert_eq!((r.rip, r.gpr[5], r.rsp()), (0xfed, 0xb9, BASE + 32));
image.info(0x300, UNW_FLAG_CHAININFO, 0, 5, &[]);
image.function(0x304, 0x800, 0x900, 0x400);
image.info(0x400, 0, 4, 3, &[code(4, 3, 0)]);
assert!(image.plan(0x300).is_none());
image.info(0x500, UNW_FLAG_CHAININFO, 0, 0, &[]);
image.function(0x504, 0x800, 0x900, 0x200);
assert!(image.plan(0x500).is_none());
}
#[test]
fn malformed_infos_are_refused() {
let mut image = Fake::new();
image.put(0x100, &[3, 0, 0, 0]);
assert!(image.plan(0x100).is_none(), "version 3");
image.put(0x110, &[0, 0, 0, 0]);
assert!(image.plan(0x110).is_none(), "version 0");
image.info(0x200, 0, 4, 0, &[code(4, 1, 0)]);
assert!(image.plan(0x200).is_none(), "ALLOC_LARGE without its slot");
image.info(0x280, 0, 4, 0, &[code(4, 1, 2), 0, 0]);
assert!(image.plan(0x280).is_none(), "ALLOC_LARGE info 2");
for op in [6, 7, 11, 12, 15] {
image.info(0x300, 0, 4, 0, &[code(4, op, 0), 0, 0]);
assert!(image.plan(0x300).is_none(), "op {op} in version 1");
}
image.info(0x380, 0, 4, 0, &[code(4, 3, 0)]);
assert!(
image.plan(0x380).is_none(),
"SET_FPREG without a frame register"
);
image.info(0x400, 0, 0, 0, &[code(0, 10, 0), code(0, 0, 3)]);
assert!(image.plan(0x400).is_none());
image.info(0x440, 0, 0, 0, &[code(0, 10, 2)]);
assert!(image.plan(0x440).is_none());
image.info(0x480, UNW_FLAG_CHAININFO, 0, 0, &[code(0, 10, 0)]);
assert!(image.plan(0x480).is_none());
let mut tail = Fake(vec![0; 8]);
tail.put(4, &[1, 0, 200, 0]);
assert!(tail.plan(4).is_none());
assert!(image.plan(0xffff_fff0).is_none());
image.info(0x500, UNW_FLAG_CHAININFO, 0, 0, &[]);
image.function(0x504, 0, 0, 0x500);
assert!(image.plan(0x500).is_none());
}
#[test]
fn version_two_epilog_codes_are_skipped() {
let mut image = Fake::new();
image.info_v(0x100, 2, 0, 4, 0, &[code(1, 6, 1), 0x0000, code(1, 0, 3)]);
let plan = image.plan(0x100).unwrap();
let bytes = stack_of(&[0xb3, 0x321]);
let mut r = regs(BASE);
run(&image, &plan, 0x1040, false, &mut r, &bytes).unwrap();
assert_eq!((r.rip, r.rsp(), r.gpr[3]), (0x321, BASE + 16, 0xb3));
}
#[test]
fn huge_allocations_stop_instead_of_reading_past_the_copy() {
let mut image = Fake::new();
image.info(
0x100,
0,
4,
0,
&[code(4, 1, 1), 0xffff, 0xffff, code(4, 1, 1), 0xffff, 0xffff],
);
let plan = image.plan(0x100).unwrap();
let bytes = stack_of(&[1, 2, 3]);
let mut r = regs(BASE);
assert_eq!(run(&image, &plan, 0x1040, false, &mut r, &bytes), None);
image.info(0x200, 0, 4, 0, &[code(4, 5, 3), 0xfff8, 0x7fff]);
let plan = image.plan(0x200).unwrap();
let mut r = regs(BASE);
assert_eq!(run(&image, &plan, 0x1040, false, &mut r, &bytes), None);
let mut r = regs(u64::MAX - 7);
let stack = StackCopy {
base: u64::MAX - 7,
bytes: &bytes[..8],
};
let frame = Frame {
entry: ENTRY,
plan: &plan,
pc: 0x1040,
exact: false,
};
assert_eq!(step(&frame, &mut r, &stack, &[], &mut image.reader()), None);
}
fn epilog_image(tail: &[u8]) -> (Fake, UnwindPlan) {
let mut image = Fake::new();
image.info(0x100, 0, 5, 0, &[code(5, 2, 1), code(1, 0, 3)]);
image.put(0x1080, tail);
let plan = image.plan(0x100).unwrap();
(image, plan)
}
#[test]
fn an_exact_pc_in_an_epilog_finishes_the_epilog() {
let (image, plan) = epilog_image(&[0x48, 0x83, 0xc4, 0x10, 0x5b, 0xc3]);
let bytes = stack_of(&[0, 0, 0xb3, 0x1111]);
let mut r = regs(BASE);
run(&image, &plan, 0x1080, true, &mut r, &bytes).unwrap();
assert_eq!((r.rip, r.rsp(), r.gpr[3]), (0x1111, BASE + 32, 0xb3));
let bytes = stack_of(&[0xb3, 0x2222]);
let mut r = regs(BASE);
run(&image, &plan, 0x1084, true, &mut r, &bytes).unwrap();
assert_eq!((r.rip, r.rsp(), r.gpr[3]), (0x2222, BASE + 16, 0xb3));
let bytes = stack_of(&[0x3333]);
let mut r = regs(BASE);
run(&image, &plan, 0x1085, true, &mut r, &bytes).unwrap();
assert_eq!((r.rip, r.rsp()), (0x3333, BASE + 8));
let bytes = stack_of(&[0, 0, 0xb3, 0x4444]);
let mut r = regs(BASE);
run(&image, &plan, 0x1080, false, &mut r, &bytes).unwrap();
assert_eq!((r.rip, r.rsp()), (0x4444, BASE + 32));
}
#[test]
fn epilog_forms() {
let (image, plan) =
epilog_image(&[0x48, 0x81, 0xc4, 0x10, 0, 0, 0, 0x41, 0x5c, 0xf3, 0xc3]);
let bytes = stack_of(&[0, 0, 0xc12, 0x5555]);
let mut r = regs(BASE);
run(&image, &plan, 0x1080, true, &mut r, &bytes).unwrap();
assert_eq!((r.rip, r.gpr[12], r.rsp()), (0x5555, 0xc12, BASE + 32));
let (image, plan) = epilog_image(&[0xc2, 0x08, 0x00]);
let bytes = stack_of(&[0x6666, 0]);
let mut r = regs(BASE);
run(&image, &plan, 0x1080, true, &mut r, &bytes).unwrap();
assert_eq!((r.rip, r.rsp()), (0x6666, BASE + 16));
let (image, plan) = epilog_image(&[0x5b, 0xe9, 0x00, 0x01, 0x00, 0x00]);
let bytes = stack_of(&[0xb3, 0x7777]);
let mut r = regs(BASE);
run(&image, &plan, 0x1080, true, &mut r, &bytes).unwrap();
assert_eq!((r.rip, r.gpr[3], r.rsp()), (0x7777, 0xb3, BASE + 16));
let (image, plan) = epilog_image(&[0xff, 0x25, 0, 0, 0, 0]);
let mut r = regs(BASE);
run(&image, &plan, 0x1080, true, &mut r, &stack_of(&[0x8888])).unwrap();
assert_eq!(r.rip, 0x8888);
}
#[test]
fn jumps_inside_the_function_are_not_epilogs() {
let (image, plan) = epilog_image(&[0x5b, 0xeb, 0xf0]);
let bytes = stack_of(&[0, 0, 0xb3, 0x9999]);
let mut r = regs(BASE);
run(&image, &plan, 0x1080, true, &mut r, &bytes).unwrap();
assert_eq!((r.rip, r.rsp()), (0x9999, BASE + 32));
let (image, plan) = epilog_image(&[0x90, 0xc3]);
let mut r = regs(BASE);
run(&image, &plan, 0x1080, true, &mut r, &bytes).unwrap();
assert_eq!(r.rsp(), BASE + 32);
}
#[test]
fn lea_epilogs_need_the_frame_register() {
let mut image = Fake::new();
image.info(
0x100,
0,
8,
5,
&[code(8, 2, 3), code(4, 3, 0), code(1, 0, 5)],
);
image.put(0x1080, &[0x48, 0x8d, 0x65, 0x00, 0x5d, 0xc3]);
image.put(0x1090, &[0x48, 0x8d, 0x63, 0x00, 0x5d, 0xc3]);
let plan = image.plan(0x100).unwrap();
let mut words = vec![0_u64; 4];
words.extend([0xb9, 0xaaaa]);
let bytes = stack_of(&words);
let mut r = regs(BASE);
r.gpr[5] = BASE + 32;
run(&image, &plan, 0x1080, true, &mut r, &bytes).unwrap();
assert_eq!((r.rip, r.gpr[5], r.rsp()), (0xaaaa, 0xb9, BASE + 48));
let mut r = regs(BASE);
r.gpr[5] = BASE + 32;
r.gpr[3] = 0x1;
run(&image, &plan, 0x1090, true, &mut r, &bytes).unwrap();
assert_eq!(r.rsp(), BASE + 48, "unwound from the codes instead");
}
#[test]
fn epilogs_reading_past_the_copy_stop() {
let (image, plan) = epilog_image(&[0x48, 0x81, 0xc4, 0x00, 0x00, 0x10, 0x00, 0xc3]);
let bytes = stack_of(&[1, 2, 3]);
let mut r = regs(BASE);
assert_eq!(run(&image, &plan, 0x1080, true, &mut r, &bytes), None);
let mut image = Fake(vec![0; 0x1082]);
image.info(0x100, 0, 0, 0, &[]);
image.put(0x1080, &[0x5b, 0xc3]);
let plan = image.plan(0x100).unwrap();
let mut r = regs(BASE);
run(
&image,
&plan,
0x1080,
true,
&mut r,
&stack_of(&[0xb3, 0xbbbb]),
)
.unwrap();
assert_eq!((r.rip, r.gpr[3]), (0xbbbb, 0xb3));
}
#[test]
fn jumps_into_chained_fragments_of_the_function_are_not_tail_calls() {
let mut image = Fake::new();
image.info(0x200, 0, 1, 0, &[code(1, 0, 3)]);
image.info(0x100, UNW_FLAG_CHAININFO, 0, 0, &[]);
image.function(0x104, 0x1400, 0x1500, 0x200);
image.info(0x300, UNW_FLAG_CHAININFO, 0, 0, &[]);
image.function(0x304, 0x1400, 0x1500, 0x200);
image.info(0x400, 0, 0, 0, &[]);
let a = function(0x1000, 0x1100, 0x100);
let table = [
a,
function(0x1200, 0x1300, 0x300),
function(0x1400, 0x1500, 0x200),
function(0x1600, 0x1700, 0x400),
];
let plan = image.plan(0x100).unwrap();
let frame = Frame {
entry: Entry {
sampled: a,
function: a,
},
plan: &plan,
pc: 0x1080,
exact: true,
};
let bytes = stack_of(&[0xb3, 0x1234]);
let check = |image: &mut Fake, target: u32, tail_call: bool| {
image.put(0x1080, &[0xe9]);
image.put(0x1081, &target.wrapping_sub(0x1085).to_le_bytes());
let mut r = regs(BASE);
assert_eq!(
step_over(image, &frame, &table, &mut r, &bytes),
Some(Stepped::Return)
);
let expected = if tail_call {
(0xb3, 0, BASE + 8)
} else {
(0x1234, 0xb3, BASE + 16)
};
assert_eq!((r.rip, r.gpr[3], r.rsp()), expected, "jmp {target:x}");
};
check(&mut image, 0x1210, false);
check(&mut image, 0x1410, false);
check(&mut image, 0x1000, false);
check(&mut image, 0x1400, true);
check(&mut image, 0x1610, true);
image.function(0x304, 0x1600, 0x1700, 0x400);
check(&mut image, 0x1210, true);
}
fn v2_image() -> (Fake, UnwindPlan) {
let mut image = Fake::new();
image.info_v(
0x100,
2,
0,
7,
0,
&[
code(4, 6, 1),
code(0x40, 6, 0),
code(7, 2, 3),
code(3, 0, 3),
code(2, 0, 12),
],
);
image.put(0x1050, &[0x5b, 0xc3]);
let plan = image.plan(0x100).unwrap();
(image, plan)
}
#[test]
fn version_two_epilogs_follow_their_descriptors() {
let (image, plan) = v2_image();
let epilogs = plan.blocks[0].epilogs.clone().unwrap();
assert_eq!(
epilogs,
Epilogs {
size: 4,
at_end: true,
back: vec![0x40]
}
);
let full = stack_of(&[0, 0, 0, 0, 0xb3, 0xc12, 0x1111]);
let unwound = |r: &Registers| (r.rip, r.rsp(), r.gpr[3], r.gpr[12]);
let mut r = regs(BASE);
let bytes = stack_of(&[0xb3, 0xc12, 0x1111]);
assert_eq!(
run(&image, &plan, 0x10fc, true, &mut r, &bytes),
Some(Stepped::Return)
);
assert_eq!(unwound(&r), (0x1111, BASE + 24, 0xb3, 0xc12));
let mut r = regs(BASE);
r.gpr[3] = 0x77;
run(
&image,
&plan,
0x10fd,
true,
&mut r,
&stack_of(&[0xc12, 0x2222]),
)
.unwrap();
assert_eq!(unwound(&r), (0x2222, BASE + 16, 0x77, 0xc12));
let mut r = regs(BASE);
run(&image, &plan, 0x10ff, true, &mut r, &stack_of(&[0x3333])).unwrap();
assert_eq!(unwound(&r), (0x3333, BASE + 8, 0, 0));
let mut r = regs(BASE);
run(
&image,
&plan,
0x10c1,
true,
&mut r,
&stack_of(&[0xc12, 0x4444]),
)
.unwrap();
assert_eq!(unwound(&r), (0x4444, BASE + 16, 0, 0xc12));
for (pc, exact) in [(0x10f8, true), (0x10fc, false), (0x10c1, false)] {
let mut r = regs(BASE);
run(&image, &plan, pc, exact, &mut r, &full).unwrap();
assert_eq!(unwound(&r), (0x1111, BASE + 56, 0xb3, 0xc12), "{pc:x}");
}
let mut r = regs(BASE);
run(&image, &plan, 0x1050, true, &mut r, &full).unwrap();
assert_eq!(unwound(&r), (0x1111, BASE + 56, 0xb3, 0xc12));
let mut r = regs(BASE);
assert_eq!(run(&image, &plan, 0x10fc, true, &mut r, &bytes[..16]), None);
}
#[test]
fn version_two_machine_frame_epilogs_end_in_iretq() {
let mut image = Fake::new();
image.info_v(
0x100,
2,
0,
1,
0,
&[code(3, 6, 1), code(0, 6, 0), code(1, 0, 3), code(0, 10, 0)],
);
image.put(0x10fd, &[0x5b, 0x48, 0xcf]);
let plan = image.plan(0x100).unwrap();
let frame = [0x4242, 0x33, 0x246, BASE + 0x1000, 0x2b];
let mut words = vec![0xb3];
words.extend(frame);
let mut r = regs(BASE);
assert_eq!(
run(&image, &plan, 0x10fd, true, &mut r, &stack_of(&words)),
Some(Stepped::MachineFrame)
);
assert_eq!((r.rip, r.rsp(), r.gpr[3]), (0x4242, BASE + 0x1000, 0xb3));
let mut r = regs(BASE);
assert_eq!(
run(&image, &plan, 0x10fe, true, &mut r, &stack_of(&frame)),
Some(Stepped::MachineFrame)
);
assert_eq!((r.rip, r.rsp(), r.gpr[3]), (0x4242, BASE + 0x1000, 0));
}
#[test]
fn epilogs_at_a_section_end_and_repne_transfers() {
let mut image = Fake(vec![0; 0x1083]);
image.info(0x100, 0, 0, 0, &[]);
image.put(0x1080, &[0x41, 0x5c, 0xc3]);
let plan = image.plan(0x100).unwrap();
let mut window = [0_u8; EPILOG_WINDOW];
assert_eq!(read_window(&mut image.reader(), 0x1080, &mut window), 3);
assert_eq!(window[..3], [0x41, 0x5c, 0xc3]);
let mut r = regs(BASE);
run(
&image,
&plan,
0x1080,
true,
&mut r,
&stack_of(&[0xc12, 0xbbbb]),
)
.unwrap();
assert_eq!((r.rip, r.gpr[12], r.rsp()), (0xbbbb, 0xc12, BASE + 16));
let (image, plan) = epilog_image(&[0x48, 0x83, 0xc4, 0x10, 0x5b, 0xf2, 0xc3]);
let mut r = regs(BASE);
run(
&image,
&plan,
0x1084,
true,
&mut r,
&stack_of(&[0xb3, 0x2222]),
)
.unwrap();
assert_eq!((r.rip, r.gpr[3], r.rsp()), (0x2222, 0xb3, BASE + 16));
let (image, plan) = epilog_image(&[0x5b, 0xf2, 0xe9, 0x00, 0x01, 0x00, 0x00]);
let mut r = regs(BASE);
run(
&image,
&plan,
0x1080,
true,
&mut r,
&stack_of(&[0xb3, 0x7777]),
)
.unwrap();
assert_eq!((r.rip, r.gpr[3], r.rsp()), (0x7777, 0xb3, BASE + 16));
let (image, plan) = epilog_image(&[0x5b, 0xf2, 0xeb, 0xf0]);
let mut r = regs(BASE);
run(
&image,
&plan,
0x1080,
true,
&mut r,
&stack_of(&[0, 0, 0xb3, 0x9999]),
)
.unwrap();
assert_eq!((r.rip, r.rsp()), (0x9999, BASE + 32));
let (image, plan) = epilog_image(&[0xf2, 0xe9, 0x5a, 0xef, 0xff, 0xff]);
let mut r = regs(BASE);
run(
&image,
&plan,
0x1080,
true,
&mut r,
&stack_of(&[0x5555, 0, 0xdead]),
)
.unwrap();
assert_eq!((r.rip, r.rsp()), (0x5555, BASE + 8));
}
#[test]
fn an_epilog_unwinds_once_the_frame_register_is_restored() {
let mut image = Fake::new();
image.info(0x100, 0, 5, 5 | (1 << 4), &[code(5, 3, 0), code(1, 0, 5)]);
image.put(0x1080, &[0x5d, 0xc3]);
let plan = image.plan(0x100).unwrap();
let mut r = regs(BASE);
assert_eq!(
run(&image, &plan, 0x1081, true, &mut r, &stack_of(&[0x5678])),
Some(Stepped::Return)
);
assert_eq!((r.rip, r.rsp(), r.gpr[5]), (0x5678, BASE + 8, 0));
}
#[test]
fn lookups_follow_the_table_and_indirect_entries() {
let mut image = Fake::new();
image.function(0x600, 0x3000, 0x3100, 0x700);
let table = [
RuntimeFunction {
begin: 0x1000,
end: 0x1100,
unwind: 0x100,
},
RuntimeFunction {
begin: 0x2000,
end: 0x2010,
unwind: 0x601,
},
];
let mut reader = image.reader();
let own = |function| {
Some(Entry {
sampled: function,
function,
})
};
assert_eq!(lookup(&table, 0x1000, &mut reader), own(table[0]));
assert_eq!(lookup(&table, 0x10ff, &mut reader), own(table[0]));
assert_eq!(
lookup(&table, 0x1100, &mut reader),
None,
"end is exclusive"
);
assert_eq!(lookup(&table, 0xfff, &mut reader), None);
let fragment = lookup(&table, 0x2008, &mut reader).unwrap();
assert_eq!(
fragment.sampled, table[1],
"the entry holding the pc is kept"
);
assert_eq!(fragment.function, function(0x3000, 0x3100, 0x700));
assert_eq!(lookup(&[], 5, &mut reader), None);
drop(reader);
image.info(0x700, 0, 5, 0, &[code(5, 2, 1), code(1, 0, 3)]);
let plan = image.plan(0x700).unwrap();
let bytes = stack_of(&[0, 0, 0xb3, 0xfeed]);
for exact in [false, true] {
let frame = Frame {
entry: fragment,
plan: &plan,
pc: 0x2008,
exact,
};
let mut r = regs(BASE);
assert_eq!(
step_over(&image, &frame, &table, &mut r, &bytes),
Some(Stepped::Return)
);
assert_eq!((r.rip, r.rsp(), r.gpr[3]), (0xfeed, BASE + 32, 0xb3));
}
let at = |pc, exact| Frame {
entry: fragment,
plan: &plan,
pc,
exact,
};
let mut r = regs(BASE);
assert!(step_over(&image, &at(0x2010, false), &table, &mut r, &bytes).is_some());
for (pc, exact) in [
(0x2010, true),
(0x1fff, false),
(0x2011, false),
(0x3008, true),
] {
let mut r = regs(BASE);
assert_eq!(
step_over(&image, &at(pc, exact), &table, &mut r, &bytes),
None,
"{pc:x}"
);
}
image.function(0x800, 0, 0, 0x801);
let looping = [RuntimeFunction {
begin: 0,
end: 0x10,
unwind: 0x801,
}];
assert_eq!(lookup(&looping, 4, &mut image.reader()), None);
}
#[test]
fn pdata_parses_whole_entries() {
let mut bytes = Vec::new();
for value in [0x1000_u32, 0x1010, 0x100, 0x2000, 0x2020, 0x200, 7] {
bytes.extend(value.to_le_bytes());
}
let table = parse_pdata(&bytes);
assert_eq!(table.len(), 2);
assert_eq!(table[1].unwind, 0x200);
}
fn pe_header() -> Vec<u8> {
let mut bytes = vec![0_u8; 0x400];
bytes[0..2].copy_from_slice(b"MZ");
bytes[0x3c..0x40].copy_from_slice(&0x80_u32.to_le_bytes());
bytes[0x80..0x84].copy_from_slice(b"PE\0\0");
let file = 0x84;
bytes[file..file + 2].copy_from_slice(&IMAGE_FILE_MACHINE_AMD64.to_le_bytes());
bytes[file + 2..file + 4].copy_from_slice(&2_u16.to_le_bytes());
bytes[file + 4..file + 8].copy_from_slice(&0x1234_5678_u32.to_le_bytes());
bytes[file + 16..file + 18].copy_from_slice(&240_u16.to_le_bytes());
let opt = file + 20;
bytes[opt..opt + 2].copy_from_slice(&IMAGE_NT_OPTIONAL_HDR64_MAGIC.to_le_bytes());
bytes[opt + 56..opt + 60].copy_from_slice(&0x5000_u32.to_le_bytes());
bytes[opt + 60..opt + 64].copy_from_slice(&0x400_u32.to_le_bytes());
bytes[opt + 64..opt + 68].copy_from_slice(&0xabcd_u32.to_le_bytes());
bytes[opt + 108..opt + 112].copy_from_slice(&16_u32.to_le_bytes());
bytes[opt + 136..opt + 140].copy_from_slice(&0x3000_u32.to_le_bytes());
bytes[opt + 140..opt + 144].copy_from_slice(&0x24_u32.to_le_bytes());
let section = |bytes: &mut Vec<u8>, at: usize, size: u32, address: u32, flags: u32| {
bytes[at + 8..at + 12].copy_from_slice(&size.to_le_bytes());
bytes[at + 12..at + 16].copy_from_slice(&address.to_le_bytes());
bytes[at + 36..at + 40].copy_from_slice(&flags.to_le_bytes());
};
let table = opt + 240;
section(&mut bytes, table, 0x1800, 0x1000, 0x6000_0020);
section(&mut bytes, table + 40, 0x800, 0x3000, 0x0000_0040);
bytes
}
#[test]
fn pe_headers_parse() {
let pe = parse_pe(&pe_header()).unwrap();
assert_eq!(pe.size, 0x5000);
assert_eq!((pe.stamp, pe.checksum), (0x1234_5678, 0xabcd));
assert_eq!(pe.exception, (0x3000, 0x24));
assert_eq!(pe.readable, vec![(0, 0x400), (0x1000, 0x2800)]);
assert!(pe.is_readable(0x1000, 0x1800));
assert!(!pe.is_readable(0x1000, 0x1801));
assert!(!pe.is_readable(0x3000, 4), "not a readable section");
assert!(!pe.is_readable(u32::MAX, 2));
assert!(pe.is_readable(0x3c, 4), "headers");
}
#[test]
fn foreign_or_truncated_headers_are_refused() {
let good = pe_header();
assert!(parse_pe(&good[..0x100]).is_none(), "section table cut off");
let mut bad = good.clone();
bad[0] = b'X';
assert!(parse_pe(&bad).is_none());
let mut arm = good.clone();
arm[0x84..0x86].copy_from_slice(&0xaa64_u16.to_le_bytes());
assert!(parse_pe(&arm).is_none(), "not x64");
let mut pe32 = good.clone();
pe32[0x98..0x9a].copy_from_slice(&0x10b_u16.to_le_bytes());
assert!(parse_pe(&pe32).is_none(), "PE32");
let mut far = good;
far[0x3c..0x40].copy_from_slice(&u32::MAX.to_le_bytes());
assert!(parse_pe(&far).is_none());
assert!(parse_pe(&[]).is_none());
}
fn wide_pe(nt: usize, sections: u16) -> Vec<u8> {
let table = nt + 24 + 240;
let mut bytes = vec![0_u8; table + usize::from(sections) * 40];
let len = u32::try_from(bytes.len()).unwrap();
bytes[0..2].copy_from_slice(b"MZ");
bytes[0x3c..0x40].copy_from_slice(&u32::try_from(nt).unwrap().to_le_bytes());
bytes[nt..nt + 4].copy_from_slice(b"PE\0\0");
let file = nt + 4;
bytes[file..file + 2].copy_from_slice(&IMAGE_FILE_MACHINE_AMD64.to_le_bytes());
bytes[file + 2..file + 4].copy_from_slice(§ions.to_le_bytes());
bytes[file + 16..file + 18].copy_from_slice(&240_u16.to_le_bytes());
let opt = file + 20;
bytes[opt..opt + 2].copy_from_slice(&IMAGE_NT_OPTIONAL_HDR64_MAGIC.to_le_bytes());
bytes[opt + 56..opt + 60].copy_from_slice(&0x0100_0000_u32.to_le_bytes());
bytes[opt + 60..opt + 64].copy_from_slice(&len.to_le_bytes());
bytes[opt + 108..opt + 112].copy_from_slice(&16_u32.to_le_bytes());
for index in 0..usize::from(sections) {
let at = table + index * 40;
let address = u32::try_from(index + 1).unwrap() * 0x1000;
bytes[at + 8..at + 12].copy_from_slice(&0x1000_u32.to_le_bytes());
bytes[at + 12..at + 16].copy_from_slice(&address.to_le_bytes());
bytes[at + 36..at + 40].copy_from_slice(&0x4000_0040_u32.to_le_bytes());
}
bytes
}
fn read_headers(bytes: &[u8], readable: usize) -> (Option<PeImage>, usize) {
let mut reads = 0;
let pe = read_pe(|out| {
reads += 1;
let len = out.len().min(bytes.len()).min(readable);
out[..len].copy_from_slice(&bytes[..len]);
len
});
(pe, reads)
}
#[test]
fn section_tables_past_the_first_page_are_read_whole() {
let bytes = wide_pe(0x80, 96);
assert_eq!(bytes.len(), 0x1088);
assert!(
parse_pe(&bytes[..FIRST_HEADER_BYTES]).is_none(),
"one page is not enough"
);
let (pe, reads) = read_headers(&bytes, usize::MAX);
let pe = pe.unwrap();
assert_eq!(reads, 2, "the first page, then the whole table");
assert_eq!(pe.readable.len(), 97);
assert_eq!(pe.readable[96], (0x60000, 0x61000));
assert_eq!(pe.readable[0], (0, 0x1088));
let (pe, reads) = read_headers(&wide_pe(0x80, 2), usize::MAX);
assert_eq!((pe.unwrap().readable.len(), reads), (3, 1));
let (pe, reads) = read_headers(&wide_pe(0x1100, 2), usize::MAX);
assert_eq!((pe.unwrap().readable.len(), reads), (3, 3));
assert!(read_headers(&bytes, 0x1000).0.is_none());
assert!(read_headers(&bytes, 0x1087).0.is_none());
let (pe, reads) = read_headers(&wide_pe(0x80, u16::MAX), usize::MAX);
assert!(pe.is_none());
assert_eq!(reads, 1);
assert!(read_headers(&[0; 64], usize::MAX).0.is_none());
let mut far = wide_pe(0x80, 2);
far[0x3c..0x40].copy_from_slice(&u32::MAX.to_le_bytes());
assert!(read_headers(&far, usize::MAX).0.is_none());
}
}