use std::collections::HashMap;
use std::mem::zeroed;
use std::ptr::null_mut;
use windows_sys::Win32::Foundation::{FreeLibrary, HANDLE, HMODULE};
use windows_sys::Win32::System::Diagnostics::Debug::{
CONTEXT, CONTEXT_CONTROL_AMD64, CONTEXT_INTEGER_AMD64, GetThreadContext,
};
use windows_sys::Win32::System::LibraryLoader::{
GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS, GetModuleHandleExW,
};
use windows_sys::Win32::System::Threading::{ResumeThread, SuspendThread};
use windows_sys::Win32::System::WindowsProgramming::QueryThreadCycleTime;
use super::sys;
use crate::MAX_FRAMES;
use crate::unwind_info::{
Frame, Image, PeImage, RSP, Registers, RuntimeFunction, StackCopy, Stepped, UnwindPlan,
load_plan, lookup, parse_pdata, read_pe, step,
};
pub(super) const STACK_COPY_BYTES: usize = 256 * 1024;
const MAX_PDATA_BYTES: u32 = 64 << 20;
const MAX_CACHED_MODULES: usize = 512;
const MAX_CACHED_PLANS: usize = 1 << 16;
#[repr(C, align(16))]
pub(super) struct AlignedContext(pub(super) CONTEXT);
pub(super) struct Capture {
context: Box<AlignedContext>,
stack: Vec<u8>,
len: usize,
rsp: u64,
pub(super) cycles: Option<u64>,
pub(super) truncated: bool,
}
pub(super) struct StackInfo {
pub(super) teb: Option<u64>,
pub(super) bounds: Option<(u64, u64)>,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(super) enum Outcome {
Gone,
NoContext,
Captured,
}
struct Paused(HANDLE);
impl Drop for Paused {
fn drop(&mut self) {
unsafe { ResumeThread(self.0) };
}
}
impl Capture {
pub(super) fn new() -> Self {
let context: AlignedContext = unsafe { zeroed() };
Self {
context: Box::new(context),
stack: vec![0; STACK_COPY_BYTES],
len: 0,
rsp: 0,
cycles: None,
truncated: false,
}
}
pub(super) fn take(&mut self, handle: HANDLE, stack: &mut StackInfo) -> Outcome {
self.len = 0;
self.rsp = 0;
self.cycles = None;
self.truncated = false;
if unsafe { SuspendThread(handle) } == u32::MAX {
return Outcome::Gone;
}
let _paused = Paused(handle);
let mut cycles = 0_u64;
if unsafe { QueryThreadCycleTime(handle, &raw mut cycles) } != 0 {
self.cycles = Some(cycles);
}
self.context.0.ContextFlags = CONTEXT_CONTROL_AMD64 | CONTEXT_INTEGER_AMD64;
if unsafe { GetThreadContext(handle, &raw mut self.context.0) } == 0 {
return Outcome::NoContext;
}
let rsp = self.context.0.Rsp;
self.rsp = rsp;
if rsp & 7 != 0 {
return Outcome::Captured;
}
let inside =
|bounds: Option<(u64, u64)>| bounds.is_some_and(|(low, high)| rsp >= low && rsp < high);
if !inside(stack.bounds)
&& let Some(teb) = stack.teb
{
stack.bounds = sys::stack_bounds(teb);
}
let Some((_, high)) = stack.bounds.filter(|_| inside(stack.bounds)) else {
return Outcome::Captured;
};
let wanted = high - rsp;
let len = usize::try_from(wanted).map_or(STACK_COPY_BYTES, |w| w.min(STACK_COPY_BYTES));
self.truncated = wanted > STACK_COPY_BYTES as u64;
let len = len.min(self.stack.len());
let read = unsafe { sys::read_into(rsp, self.stack.as_mut_ptr(), len) };
self.len = read & !7;
Outcome::Captured
}
fn registers(&self) -> Registers {
let c = &self.context.0;
Registers {
rip: c.Rip,
gpr: [
c.Rax, c.Rcx, c.Rdx, c.Rbx, c.Rsp, c.Rbp, c.Rsi, c.Rdi, c.R8, c.R9, c.R10, c.R11,
c.R12, c.R13, c.R14, c.R15,
],
}
}
pub(super) fn unwind(
&self,
unwinder: &mut Unwinder,
frames: &mut [u64; MAX_FRAMES],
) -> (u64, usize) {
let mut regs = self.registers();
let leaf = regs.rip;
let stack = StackCopy {
base: self.rsp,
bytes: self.stack.get(..self.len).unwrap_or_default(),
};
let depth = unwinder.walk(&mut regs, &stack, frames);
unwinder.pins.clear();
(leaf, depth)
}
}
struct ModuleRef(HMODULE);
impl Drop for ModuleRef {
fn drop(&mut self) {
unsafe { FreeLibrary(self.0) };
}
}
struct Pinned {
_reference: ModuleRef,
base: u64,
pe: PeImage,
}
impl Pinned {
fn new(address: u64) -> Option<Self> {
let mut module: HMODULE = null_mut();
let name = std::ptr::without_provenance::<u16>(usize::try_from(address).ok()?);
let found = unsafe {
GetModuleHandleExW(
GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS,
name,
&raw mut module,
)
} != 0;
if !found || module.is_null() {
return None;
}
let reference = ModuleRef(module);
let base = module.addr() as u64;
let pe = read_pe(|out| {
unsafe { sys::read_into(base, out.as_mut_ptr(), out.len()) }
})?;
if address.checked_sub(base)? >= u64::from(pe.size) {
return None;
}
Some(Self {
_reference: reference,
base,
pe,
})
}
fn contains(&self, address: u64) -> bool {
address
.checked_sub(self.base)
.is_some_and(|rva| rva < u64::from(self.pe.size))
}
fn key(&self) -> ModuleKey {
ModuleKey {
base: self.base,
size: self.pe.size,
stamp: self.pe.stamp,
checksum: self.pe.checksum,
exception: self.pe.exception,
}
}
}
struct PinnedImage<'a>(&'a Pinned);
impl Image for PinnedImage<'_> {
fn read(&mut self, rva: u32, out: &mut [u8]) -> bool {
if !self.0.pe.is_readable(rva, out.len()) {
return false;
}
let read =
unsafe { sys::read_into(self.0.base + u64::from(rva), out.as_mut_ptr(), out.len()) };
read == out.len()
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
struct ModuleKey {
base: u64,
size: u32,
stamp: u32,
checksum: u32,
exception: (u32, u32),
}
#[derive(Default)]
struct ModuleData {
table: Vec<RuntimeFunction>,
plans: HashMap<u32, Option<UnwindPlan>>,
}
impl ModuleData {
fn load(pinned: &Pinned) -> Self {
let (rva, size) = pinned.pe.exception;
let mut table = Vec::new();
if size > 0 && size <= MAX_PDATA_BYTES {
let mut bytes = vec![0_u8; size as usize];
if PinnedImage(pinned).read(rva, &mut bytes) {
table = parse_pdata(&bytes);
}
}
Self {
table,
plans: HashMap::new(),
}
}
}
#[derive(Default)]
pub(super) struct Unwinder {
modules: HashMap<ModuleKey, ModuleData>,
pins: Vec<Pinned>,
}
impl Unwinder {
fn pin(&mut self, address: u64) -> Option<usize> {
if let Some(at) = self.pins.iter().position(|pin| pin.contains(address)) {
return Some(at);
}
let pinned = Pinned::new(address)?;
self.pins.push(pinned);
Some(self.pins.len() - 1)
}
fn walk(
&mut self,
regs: &mut Registers,
stack: &StackCopy,
frames: &mut [u64; MAX_FRAMES],
) -> usize {
let mut depth = 0;
let mut exact = true;
while depth < MAX_FRAMES && regs.rip != 0 {
let pc = regs.rip;
let probe = if exact { pc } else { pc.wrapping_sub(1) };
let Some(slot) = frames.get_mut(depth) else {
break;
};
let found = self.pin(probe).and_then(|at| {
let pinned = self.pins.get(at)?;
let key = pinned.key();
if !self.modules.contains_key(&key) && self.modules.len() >= MAX_CACHED_MODULES {
self.modules.clear();
}
let data = self
.modules
.entry(key)
.or_insert_with(|| ModuleData::load(pinned));
let mut image = PinnedImage(pinned);
let rva = u32::try_from(probe.checked_sub(pinned.base)?).ok()?;
let entry = lookup(&data.table, rva, &mut image)?;
let unwind = entry.function.unwind;
if !data.plans.contains_key(&unwind) {
if data.plans.len() >= MAX_CACHED_PLANS {
data.plans.clear();
}
data.plans.insert(unwind, load_plan(unwind, &mut image));
}
Some((at, entry))
});
let Some((at, entry)) = found else {
*slot = pc;
depth += 1;
let Some(return_address) = (depth == 1).then(|| stack.word(regs.rsp())).flatten()
else {
break;
};
regs.rip = return_address;
regs.gpr[RSP] = regs.rsp().wrapping_add(8);
exact = false;
continue;
};
let Some(pinned) = self.pins.get(at) else {
break;
};
*slot = pinned.base + u64::from(entry.function.begin);
depth += 1;
if stack.bytes.is_empty() || !stack.holds(regs.rsp()) {
break;
}
let Some(data) = self.modules.get(&pinned.key()) else {
break;
};
let Some(Some(plan)) = data.plans.get(&entry.function.unwind) else {
break;
};
let Some(pc_rva) = pc
.checked_sub(pinned.base)
.and_then(|rva| u32::try_from(rva).ok())
else {
break;
};
let before = regs.rsp();
let frame = Frame {
entry,
plan,
pc: pc_rva,
exact,
};
match step(&frame, regs, stack, &data.table, &mut PinnedImage(pinned)) {
Some(stepped) => exact = stepped == Stepped::MachineFrame,
None => break,
}
if regs.rsp() <= before {
break;
}
}
depth
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn context_alignment() {
assert_eq!(std::mem::align_of::<AlignedContext>(), 16);
let capture = Capture::new();
assert_eq!((&raw const capture.context.0).addr() % 16, 0);
assert_eq!(capture.stack.len(), STACK_COPY_BYTES);
}
#[test]
fn pinning_finds_this_module_and_refuses_other_memory() {
let here = pinning_finds_this_module_and_refuses_other_memory as fn() as usize as u64;
let pinned = Pinned::new(here).unwrap();
assert!(pinned.contains(here));
assert!(pinned.pe.size > 0);
assert_ne!(pinned.pe.exception, (0, 0), "an x64 image has .pdata");
assert!(Pinned::new(0x10).is_none());
let heap = Box::new(0_u64);
assert!(Pinned::new((&raw const *heap).addr() as u64).is_none());
}
#[test]
fn pinned_reads_stay_in_readable_ranges() {
let here = pinned_reads_stay_in_readable_ranges as fn() as usize as u64;
let pinned = Pinned::new(here).unwrap();
let mut image = PinnedImage(&pinned);
let mut mz = [0_u8; 2];
assert!(image.read(0, &mut mz));
assert_eq!(&mz, b"MZ");
let mut past = [0_u8; 8];
let after_headers = pinned.pe.readable[0].1;
assert!(after_headers < 0x1000, "{:x?}", pinned.pe.readable);
assert!(!pinned.pe.is_readable(after_headers, past.len()));
assert!(!image.read(after_headers, &mut past));
assert!(!image.read(pinned.pe.size - 4, &mut past));
assert!(!image.read(u32::MAX - 2, &mut past));
}
#[inline(never)]
fn deeper(depth: u32, out: &mut Vec<u64>) {
if depth == 0 {
let mut capture = Capture::new();
let mut context: AlignedContext =
unsafe { zeroed() };
context.0.ContextFlags = CONTEXT_CONTROL_AMD64 | CONTEXT_INTEGER_AMD64;
unsafe {
windows_sys::Win32::System::Diagnostics::Debug::RtlCaptureContext(
&raw mut context.0,
);
}
let rsp = context.0.Rsp;
let len = 64 * 1024;
let read = unsafe { sys::read_into(rsp, capture.stack.as_mut_ptr(), len) };
capture.len = read & !7;
capture.rsp = rsp;
*capture.context = context;
let mut frames = [0_u64; MAX_FRAMES];
let mut unwinder = Unwinder::default();
let (_, depth) = capture.unwind(&mut unwinder, &mut frames);
assert!(unwinder.pins.is_empty(), "pins are released after the walk");
out.extend_from_slice(&frames[..depth]);
return;
}
deeper(std::hint::black_box(depth - 1), out);
std::hint::black_box(&out);
}
#[test]
fn a_live_stack_unwinds_through_its_callers() {
let mut frames = Vec::new();
deeper(4, &mut frames);
let start = deeper as fn(u32, &mut Vec<u64>) as usize as u64;
let recursive = frames.iter().filter(|&&frame| frame == start).count();
assert!(recursive >= 5, "{recursive} deeper frames in {frames:x?}");
let test = a_live_stack_unwinds_through_its_callers as fn() as usize as u64;
assert!(frames.contains(&test), "{frames:x?}");
}
#[test]
fn a_capture_without_a_stack_records_only_the_leaf() {
let mut capture = Capture::new();
let here = a_capture_without_a_stack_records_only_the_leaf as fn() as usize as u64;
capture.context.0.Rip = here + 1;
capture.context.0.Rsp = 0x1000;
capture.len = 0;
let mut frames = [0_u64; MAX_FRAMES];
let mut unwinder = Unwinder::default();
let (leaf, depth) = capture.unwind(&mut unwinder, &mut frames);
assert_eq!((leaf, depth), (here + 1, 1));
assert_eq!(frames[0], here, "the leaf's function start");
capture.context.0.Rip = 0x10;
let (_, depth) = capture.unwind(&mut unwinder, &mut frames);
assert_eq!((depth, frames[0]), (1, 0x10));
}
}