Merge pull request #198 from Dufftwt/fix/crash-report-instruction-bytes

Crash reports: show the bytes of an instruction the CPU refused
This commit is contained in:
Marvis authored and GitHub committed 2026-11-24 08:53:55 +01:00
commit ca4477b6f2
1 file changed
+53
+53
View File
@@ -379,6 +379,22 @@ pub unsafe fn report_unhandled(info: *const EXCEPTION_POINTERS) {
unsafe { report("unhandled exception", info, true) };
}
/// The bytes at `at` as hex, as many as the longest x86 instruction (15),
/// but none past the end of `at`'s page: the next page may not be mapped.
/// For an instruction the CPU refused, they name it (`0f 01 fd` is
/// `rdpru`), which the address alone does not.
///
/// # Safety
/// `at`'s page is readable.
unsafe fn instruction_bytes(at: usize) -> String {
let n = (0x1000 - (at & 0xfff)).min(15);
// SAFETY: `n` bytes from `at` stay inside its page, which the caller
// says is readable.
let bytes = unsafe { std::slice::from_raw_parts(at as *const u8, n) };
let hex: Vec<_> = bytes.iter().map(|b| format!("{b:02x}")).collect();
hex.join(" ")
}
/// MSVC's code for a C++ `throw`, and its magic first parameter.
const CPP_EXCEPTION: i32 = 0xE06D_7363_u32 as i32;
const CPP_MAGIC: usize = 0x1993_0520;
@@ -440,6 +456,9 @@ unsafe fn report(what: &str, info: *const EXCEPTION_POINTERS, to_file: bool) {
} else if code == CPP_EXCEPTION && record.NumberParameters >= 4 && p[0] == CPP_MAGIC {
// SAFETY: a live MSVC throw.
format!(" (C++ {} thrown)", unsafe { thrown(&p) })
} else if code == EXCEPTION_ILLEGAL_INSTRUCTION || code == EXCEPTION_PRIV_INSTRUCTION {
// SAFETY: the CPU refused the instruction at `at`, so it fetched it.
format!(" (code {})", unsafe { instruction_bytes(at) })
} else {
String::new()
};
@@ -848,4 +867,38 @@ mod tests {
None
);
}
#[test]
fn instruction_bytes_stop_at_the_end_of_their_page() {
use windows_sys::Win32::System::Memory::{
MEM_COMMIT, MEM_RELEASE, MEM_RESERVE, PAGE_NOACCESS, PAGE_READWRITE, VirtualAlloc,
VirtualFree, VirtualProtect,
};
// rdpru, then the next instruction (mov rcx, rax) and padding.
let mut code = [0x90_u8; 16];
code[..6].copy_from_slice(&[0x0f, 0x01, 0xfd, 0x48, 0x89, 0xc1]);
// SAFETY: two fresh pages of ours, the second made unreadable, so a
// read past the end of the first faults.
unsafe {
let page = VirtualAlloc(
std::ptr::null(),
0x2000,
MEM_RESERVE | MEM_COMMIT,
PAGE_READWRITE,
)
.cast::<u8>();
assert!(!page.is_null());
let mut old = 0;
let guard = page.add(0x1000).cast();
assert_ne!(VirtualProtect(guard, 0x1000, PAGE_NOACCESS, &mut old), 0);
page.copy_from_nonoverlapping(code.as_ptr(), code.len());
let whole = "0f 01 fd 48 89 c1 90 90 90 90 90 90 90 90 90";
assert_eq!(instruction_bytes(page as usize), whole);
// The page's last three bytes: rdpru, and nothing read after it.
let end = page.add(0x1000 - 3);
end.copy_from_nonoverlapping(code.as_ptr(), 3);
assert_eq!(instruction_bytes(end as usize), "0f 01 fd");
VirtualFree(page.cast(), 0, MEM_RELEASE);
}
}
}