mirror of
https://github.com/ivall/xcl.git
synced 2026-11-24 05:14:57 +01:00
Merge pull request #127 from gbuyssens/pr/eh-pe-cpu-check
This commit is contained in:
+94
-29
@@ -216,17 +216,43 @@ unsafe extern "system" fn gs_failure(cookie: usize, ret: usize) {
|
||||
/// First-chance C++ exceptions (0xE06D7363), the first 16: type, what() and where they were
|
||||
/// thrown. One nobody catches ends the process through std::terminate → abort → __fastfail
|
||||
/// (0xC0000409), which leaves no other trace (a static initializer in a title DLL's DllMain).
|
||||
/// The C string at `p`, at most `max` bytes, read only as far as the memory is readable (a
|
||||
/// vectored handler faulting on an unmapped byte after a title's string would turn the
|
||||
/// exception it looks at into a fatal one).
|
||||
unsafe fn bounded_cstr(p: usize, max: usize) -> String {
|
||||
let mut bytes = Vec::new();
|
||||
let mut a = p;
|
||||
while bytes.len() < max {
|
||||
// readability is checked page by page: at the start and at every page crossed
|
||||
if (a == p || a & 0xFFF == 0) && !crate::gpu::shader::readable(a, 1) {
|
||||
break;
|
||||
}
|
||||
let b = *(a as *const u8);
|
||||
if b == 0 {
|
||||
break;
|
||||
}
|
||||
bytes.push(b);
|
||||
a += 1;
|
||||
}
|
||||
String::from_utf8_lossy(&bytes).into_owned()
|
||||
}
|
||||
|
||||
unsafe extern "system" fn cpp_exception_logger(info: *mut EXCEPTION_POINTERS) -> i32 {
|
||||
const CPP: i32 = 0xE06D_7363_u32 as i32;
|
||||
const THREAD_NAME: i32 = 0x406D_1388;
|
||||
if info.is_null() || (*info).ExceptionRecord.is_null() || (*info).ContextRecord.is_null() {
|
||||
return 0;
|
||||
}
|
||||
let rec = &*(*info).ExceptionRecord;
|
||||
// the debugger's thread-name exception (THREADNAME_INFO: 0x1000, name, thread id, flags):
|
||||
// the name goes to SetThreadDescription, where tools – and XCL's thread dump – see it
|
||||
if rec.ExceptionCode == THREAD_NAME && rec.NumberParameters >= 3 && rec.ExceptionInformation[0] == 0x1000 {
|
||||
let (name, tid) = (rec.ExceptionInformation[1], rec.ExceptionInformation[2] as u32);
|
||||
if name != 0 && crate::gpu::shader::readable(name, 1) {
|
||||
let n: Vec<u16> = std::ffi::CStr::from_ptr(name as *const std::ffi::c_char).to_string_lossy().encode_utf16().chain([0]).collect();
|
||||
name_thread(tid, &n);
|
||||
if name != 0 {
|
||||
let n: Vec<u16> = bounded_cstr(name, 256).encode_utf16().chain([0]).collect();
|
||||
if n.len() > 1 {
|
||||
name_thread(tid, &n);
|
||||
}
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
@@ -253,19 +279,20 @@ unsafe extern "system" fn cpp_exception_logger(info: *mut EXCEPTION_POINTERS) ->
|
||||
let td = rd32(base + first as usize + 4);
|
||||
if td > 0 {
|
||||
let p = base + td as usize + 16;
|
||||
if crate::gpu::shader::readable(p, 64) {
|
||||
name = std::ffi::CStr::from_ptr(p as *const std::ffi::c_char).to_string_lossy().into_owned();
|
||||
if crate::gpu::shader::readable(p, 1) {
|
||||
name = bounded_cstr(p, 256);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
// std::exception { vfptr, const char* what, … }
|
||||
// std::exception { vfptr, const char* what, … } – for other thrown types the second word is
|
||||
// whatever the object holds: read as a string only where it points at readable memory
|
||||
let mut what = String::new();
|
||||
if object != 0 && crate::gpu::shader::readable(object + 8, 8) {
|
||||
let s = (object as *const usize).add(1).read_unaligned();
|
||||
if s != 0 && crate::gpu::shader::readable(s, 1) {
|
||||
what = std::ffi::CStr::from_ptr(s as *const std::ffi::c_char).to_string_lossy().chars().take(200).collect();
|
||||
if s != 0 {
|
||||
what = bounded_cstr(s, 200);
|
||||
}
|
||||
}
|
||||
let ctx = &*(*info).ContextRecord;
|
||||
@@ -413,16 +440,22 @@ pub fn dump_threads() {
|
||||
if te.th32OwnerProcessID == pid && te.th32ThreadID != me {
|
||||
let h = OpenThread(THREAD_SUSPEND_RESUME | THREAD_GET_CONTEXT | THREAD_QUERY_INFORMATION, 0, te.th32ThreadID);
|
||||
if !h.is_null() {
|
||||
if SuspendThread(h) != u32::MAX {
|
||||
// CONTEXT must be 16-byte aligned
|
||||
let mut buf = vec![0u8; std::mem::size_of::<CONTEXT>() + 16];
|
||||
let ctx = ((buf.as_mut_ptr() as usize + 15) & !15) as *mut CONTEXT;
|
||||
(*ctx).ContextFlags = CONTEXT_CONTROL_AMD64 | CONTEXT_INTEGER_AMD64;
|
||||
if GetThreadContext(h, ctx) != 0 {
|
||||
let frames: Vec<String> = unwind(&mut *ctx, 14).into_iter().map(modules::describe_address).collect();
|
||||
lines.push(format!("thread {} '{}': {}", te.th32ThreadID, thread_name(h), frames.join(" < ")));
|
||||
}
|
||||
// CONTEXT must be 16-byte aligned
|
||||
#[repr(align(16))]
|
||||
struct Aligned(CONTEXT);
|
||||
let mut c: Aligned = std::mem::zeroed();
|
||||
c.0.ContextFlags = CONTEXT_CONTROL_AMD64 | CONTEXT_INTEGER_AMD64;
|
||||
// only the context is taken while the thread is suspended: the unwinding
|
||||
// (RtlLookupFunctionEntry), the module lookup (loader lock), the name and the
|
||||
// formatting (heap) take locks the suspended thread may hold (#106)
|
||||
let got = SuspendThread(h) != u32::MAX && {
|
||||
let ok = GetThreadContext(h, &mut c.0) != 0;
|
||||
ResumeThread(h);
|
||||
ok
|
||||
};
|
||||
if got {
|
||||
let frames: Vec<String> = unwind(&mut c.0, 14).into_iter().map(modules::describe_address).collect();
|
||||
lines.push(format!("thread {} '{}': {}", te.th32ThreadID, thread_name(h), frames.join(" < ")));
|
||||
}
|
||||
CloseHandle(h);
|
||||
}
|
||||
@@ -500,6 +533,10 @@ pub fn watch_writes(addr: usize) {
|
||||
while start.elapsed().as_secs() < 60 {
|
||||
unsafe {
|
||||
let snap = CreateToolhelp32Snapshot(TH32CS_SNAPTHREAD, 0);
|
||||
if snap == windows_sys::Win32::Foundation::INVALID_HANDLE_VALUE {
|
||||
std::thread::sleep(std::time::Duration::from_millis(50));
|
||||
continue;
|
||||
}
|
||||
let mut e: THREADENTRY32 = std::mem::zeroed();
|
||||
e.dwSize = std::mem::size_of::<THREADENTRY32>() as u32;
|
||||
let mut ok = Thread32First(snap, &mut e) != 0;
|
||||
@@ -512,14 +549,17 @@ pub fn watch_writes(addr: usize) {
|
||||
struct Aligned(CONTEXT);
|
||||
let mut c: Aligned = std::mem::zeroed();
|
||||
c.0.ContextFlags = CONTEXT_DEBUG_REGISTERS_AMD64;
|
||||
SuspendThread(h);
|
||||
if GetThreadContext(h, &mut c.0) != 0 {
|
||||
c.0.Dr0 = addr as u64;
|
||||
// L0, RW0 = 01 (writes), LEN0 = 10 (8 bytes)
|
||||
c.0.Dr7 = (c.0.Dr7 & !0xF_0003) | 1 | (0b01 << 16) | (0b10 << 18);
|
||||
SetThreadContext(h, &c.0);
|
||||
if SuspendThread(h) != u32::MAX {
|
||||
if GetThreadContext(h, &mut c.0) != 0 {
|
||||
c.0.Dr0 = addr as u64;
|
||||
// L0, RW0 = 01 (writes), LEN0 = 10 (8 bytes)
|
||||
c.0.Dr7 = (c.0.Dr7 & !0xF_0003) | 1 | (0b01 << 16) | (0b10 << 18);
|
||||
SetThreadContext(h, &c.0);
|
||||
}
|
||||
ResumeThread(h);
|
||||
} else {
|
||||
armed.remove(&e.th32ThreadID);
|
||||
}
|
||||
ResumeThread(h);
|
||||
windows_sys::Win32::Foundation::CloseHandle(h);
|
||||
}
|
||||
}
|
||||
@@ -666,6 +706,10 @@ pub fn start_probes() {
|
||||
loop {
|
||||
unsafe {
|
||||
let snap = CreateToolhelp32Snapshot(TH32CS_SNAPTHREAD, 0);
|
||||
if snap == windows_sys::Win32::Foundation::INVALID_HANDLE_VALUE {
|
||||
std::thread::sleep(std::time::Duration::from_millis(50));
|
||||
continue;
|
||||
}
|
||||
let mut e: THREADENTRY32 = std::mem::zeroed();
|
||||
e.dwSize = std::mem::size_of::<THREADENTRY32>() as u32;
|
||||
let mut ok = Thread32First(snap, &mut e) != 0;
|
||||
@@ -677,12 +721,15 @@ pub fn start_probes() {
|
||||
struct Aligned(CONTEXT);
|
||||
let mut c: Aligned = std::mem::zeroed();
|
||||
c.0.ContextFlags = CONTEXT_DEBUG_REGISTERS_AMD64;
|
||||
SuspendThread(h);
|
||||
if GetThreadContext(h, &mut c.0) != 0 {
|
||||
arm_context(&mut c.0);
|
||||
SetThreadContext(h, &c.0);
|
||||
if SuspendThread(h) != u32::MAX {
|
||||
if GetThreadContext(h, &mut c.0) != 0 {
|
||||
arm_context(&mut c.0);
|
||||
SetThreadContext(h, &c.0);
|
||||
}
|
||||
ResumeThread(h);
|
||||
} else {
|
||||
armed.remove(&e.th32ThreadID);
|
||||
}
|
||||
ResumeThread(h);
|
||||
windows_sys::Win32::Foundation::CloseHandle(h);
|
||||
}
|
||||
}
|
||||
@@ -699,6 +746,24 @@ pub fn start_probes() {
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn bounded_cstr_stops_at_nul_limit_and_unreadable_memory() {
|
||||
unsafe {
|
||||
let s = b"hello\0tail";
|
||||
assert_eq!(bounded_cstr(s.as_ptr() as usize, 64), "hello");
|
||||
assert_eq!(bounded_cstr(s.as_ptr() as usize, 3), "hel");
|
||||
assert_eq!(bounded_cstr(0, 64), "");
|
||||
// a string running to the end of a page followed by an unmapped one
|
||||
use windows_sys::Win32::System::Memory::{VirtualAlloc, VirtualFree, MEM_COMMIT, MEM_RELEASE, MEM_RESERVE, PAGE_READWRITE};
|
||||
let p = VirtualAlloc(std::ptr::null(), 0x2000, MEM_RESERVE, PAGE_READWRITE) as usize;
|
||||
assert_ne!(p, 0);
|
||||
assert_ne!(VirtualAlloc(p as *const _, 0x1000, MEM_COMMIT, PAGE_READWRITE) as usize, 0);
|
||||
std::ptr::write_bytes(p as *mut u8, b'x', 0x1000);
|
||||
assert_eq!(bounded_cstr(p + 0x1000 - 4, 64), "xxxx");
|
||||
VirtualFree(p as *mut _, 0, MEM_RELEASE);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn finds_both_cookie_checks() {
|
||||
let pc = [0x48, 0x3B, 0x0D, 1, 2, 3, 4, 0x75, 0x10, 0x48, 0xC1, 0xC1, 0x10, 0x66, 0xF7, 0xC1, 0xFF, 0xFF, 0x75, 0x01, 0xC3, 0x48, 0xC1, 0xC9, 0x10, 0xE9, 0, 0, 0, 0, 0xCC];
|
||||
|
||||
@@ -353,6 +353,21 @@ pub fn run(target: &Path, args: &[String]) -> i32 {
|
||||
let environment = crate::preflight::run(&boot.config.d3d12_adapter);
|
||||
crate::preflight::print(&environment);
|
||||
|
||||
// the console's CPU is a Zen 2: its titles are compiled for it and fault with an illegal
|
||||
// instruction (0xC000001D) on a PC without its extensions – said here instead
|
||||
let missing = missing_console_cpu_features();
|
||||
if !missing.is_empty() {
|
||||
if std::env::var_os("XCL_SKIP_CPU_CHECK").is_some() {
|
||||
println!(" WARNING: this CPU lacks {} (XCL_SKIP_CPU_CHECK set, continuing)", missing.join(", "));
|
||||
} else {
|
||||
eprintln!(
|
||||
"xcl: this CPU lacks {}: Xbox Series X|S games are compiled for the console's Zen 2 CPU\n and need them (they would stop with an illegal instruction). XCL_SKIP_CPU_CHECK=1 runs anyway.",
|
||||
missing.join(", ")
|
||||
);
|
||||
return 2;
|
||||
}
|
||||
}
|
||||
|
||||
let mut cmdline = quote(&exe.to_string_lossy());
|
||||
for a in args {
|
||||
cmdline.push(' ');
|
||||
@@ -369,6 +384,30 @@ pub fn run(target: &Path, args: &[String]) -> i32 {
|
||||
code as i32
|
||||
}
|
||||
|
||||
/// Instruction set extensions of the console's Zen 2 that this CPU does not have (titles are
|
||||
/// compiled for them: AVX2, FMA, F16C, BMI1 / BMI2, LZCNT, POPCNT, MOVBE, SSE4.2).
|
||||
pub fn missing_console_cpu_features() -> Vec<&'static str> {
|
||||
let mut missing = Vec::new();
|
||||
macro_rules! need {
|
||||
($($feature:tt => $name:literal),* $(,)?) => {
|
||||
$(if !std::arch::is_x86_feature_detected!($feature) { missing.push($name); })*
|
||||
};
|
||||
}
|
||||
need!(
|
||||
"sse4.2" => "SSE4.2",
|
||||
"popcnt" => "POPCNT",
|
||||
"avx" => "AVX",
|
||||
"avx2" => "AVX2",
|
||||
"fma" => "FMA",
|
||||
"f16c" => "F16C",
|
||||
"bmi1" => "BMI1",
|
||||
"bmi2" => "BMI2",
|
||||
"lzcnt" => "LZCNT",
|
||||
"movbe" => "MOVBE",
|
||||
);
|
||||
missing
|
||||
}
|
||||
|
||||
fn spawn_host(cmdline: &str, cwd: &Path, boot_path: &Path) -> Result<u32, String> {
|
||||
use windows_sys::Win32::Foundation::{CloseHandle, GetLastError};
|
||||
use windows_sys::Win32::System::Threading::{
|
||||
|
||||
+49
-12
@@ -409,7 +409,7 @@ impl<'a> Pe<'a> {
|
||||
let mut out = Vec::new();
|
||||
let names_rva = if int_rva != 0 { int_rva } else { iat_rva };
|
||||
for i in 0..65536u32 {
|
||||
let slot = names_rva + i * 8;
|
||||
let slot = names_rva.checked_add(i * 8).ok_or(PeError::BadRva(names_rva))?;
|
||||
let v = self.u64_at(slot).ok_or(PeError::BadRva(slot))?;
|
||||
if v == 0 {
|
||||
break;
|
||||
@@ -419,10 +419,10 @@ impl<'a> Pe<'a> {
|
||||
} else {
|
||||
let hn = (v & 0x7FFF_FFFF) as u32;
|
||||
let hint = self.u16_at(hn).ok_or(PeError::BadRva(hn))?;
|
||||
let name = self.cstr_at(hn + 2).ok_or(PeError::BadRva(hn + 2))?;
|
||||
let name = self.cstr_at(hn.wrapping_add(2)).ok_or(PeError::BadRva(hn))?;
|
||||
ImportName::Name { hint, name }
|
||||
};
|
||||
out.push(ImportEntry { iat_rva: iat_rva + i * 8, what });
|
||||
out.push(ImportEntry { iat_rva: iat_rva.checked_add(i * 8).ok_or(PeError::BadRva(iat_rva))?, what });
|
||||
}
|
||||
Ok(out)
|
||||
}
|
||||
@@ -434,7 +434,7 @@ impl<'a> Pe<'a> {
|
||||
return Ok(out);
|
||||
}
|
||||
for i in 0..4096u32 {
|
||||
let o = d.rva + i * 20;
|
||||
let o = d.rva.checked_add(i * 20).ok_or(PeError::BadRva(d.rva))?;
|
||||
let int_rva = self.u32_at(o).ok_or(PeError::BadRva(o))?;
|
||||
let name_rva = self.u32_at(o + 12).ok_or(PeError::BadRva(o))?;
|
||||
let iat_rva = self.u32_at(o + 16).ok_or(PeError::BadRva(o))?;
|
||||
@@ -455,7 +455,7 @@ impl<'a> Pe<'a> {
|
||||
return Ok(out);
|
||||
}
|
||||
for i in 0..4096u32 {
|
||||
let o = d.rva + i * 32;
|
||||
let o = d.rva.checked_add(i * 32).ok_or(PeError::BadRva(d.rva))?;
|
||||
let attrs = self.u32_at(o).ok_or(PeError::BadRva(o))?;
|
||||
let mut name_rva = self.u32_at(o + 4).ok_or(PeError::BadRva(o))?;
|
||||
let mut hmod_rva = self.u32_at(o + 8).ok_or(PeError::BadRva(o))?;
|
||||
@@ -485,23 +485,27 @@ impl<'a> Pe<'a> {
|
||||
if d.rva == 0 || d.size == 0 {
|
||||
return Ok(out);
|
||||
}
|
||||
// the block sizes come from the file: a block past the directory's end (or one whose
|
||||
// offsets overflow) is a malformed image, not a panic or a 2^31-entry loop
|
||||
let mut pos = 0u32;
|
||||
while pos + 8 <= d.size {
|
||||
let page = self.u32_at(d.rva + pos).ok_or(PeError::BadRva(d.rva + pos))?;
|
||||
let block = self.u32_at(d.rva + pos + 4).ok_or(PeError::BadRva(d.rva + pos))?;
|
||||
while pos.saturating_add(8) <= d.size {
|
||||
let at = d.rva.checked_add(pos).ok_or(PeError::BadRva(d.rva))?;
|
||||
let page = self.u32_at(at).ok_or(PeError::BadRva(at))?;
|
||||
let block = self.u32_at(at + 4).ok_or(PeError::BadRva(at))?;
|
||||
if block < 8 {
|
||||
break;
|
||||
}
|
||||
if block > d.size - pos {
|
||||
return Err(PeError::BadRva(at));
|
||||
}
|
||||
let n = (block - 8) / 2;
|
||||
for i in 0..n {
|
||||
let e = self
|
||||
.u16_at(d.rva + pos + 8 + i * 2)
|
||||
.ok_or(PeError::BadRva(d.rva + pos))?;
|
||||
let e = self.u16_at(at + 8 + i * 2).ok_or(PeError::BadRva(at))?;
|
||||
let kind = e >> 12;
|
||||
if kind == IMAGE_REL_BASED_ABSOLUTE {
|
||||
continue;
|
||||
}
|
||||
out.push(Reloc { rva: page + (e & 0x0FFF) as u32, kind });
|
||||
out.push(Reloc { rva: page.checked_add((e & 0x0FFF) as u32).ok_or(PeError::BadRva(at))?, kind });
|
||||
}
|
||||
pos += block;
|
||||
}
|
||||
@@ -640,6 +644,39 @@ mod tests {
|
||||
assert!(pe.relocations().unwrap().iter().all(|r| r.kind == IMAGE_REL_BASED_DIR64));
|
||||
}
|
||||
|
||||
/// Malformed directories are errors, not panics or runaway loops (#106): a relocation block
|
||||
/// claiming more than the directory holds, import descriptors at the end of the address space.
|
||||
#[test]
|
||||
fn malformed_relocations_and_imports_are_errors() {
|
||||
let mut data = system_file("kernel32.dll");
|
||||
let (reloc, import) = {
|
||||
let pe = Pe::parse(&data, Layout::File).unwrap();
|
||||
(pe.dir(DIR_BASERELOC), pe.dir(DIR_IMPORT))
|
||||
};
|
||||
let pe = Pe::parse(&data, Layout::File).unwrap();
|
||||
let first_block = pe.rva_to_offset(reloc.rva).unwrap();
|
||||
drop(pe);
|
||||
// the first block's size: larger than the whole directory
|
||||
data[first_block + 4..first_block + 8].copy_from_slice(&0xFFFF_FFF0u32.to_le_bytes());
|
||||
let pe = Pe::parse(&data, Layout::File).unwrap();
|
||||
assert!(matches!(pe.relocations(), Err(PeError::BadRva(_))));
|
||||
drop(pe);
|
||||
data[first_block + 4..first_block + 8].copy_from_slice(&(reloc.size + 8).to_le_bytes());
|
||||
let pe = Pe::parse(&data, Layout::File).unwrap();
|
||||
assert!(matches!(pe.relocations(), Err(PeError::BadRva(_))));
|
||||
drop(pe);
|
||||
// the import directory at the top of the address space: its descriptors' offsets overflow
|
||||
let dirs_off = {
|
||||
let pe = Pe::parse(&data, Layout::File).unwrap();
|
||||
// the data directories follow the optional header: find the import entry by value
|
||||
let needle = [import.rva.to_le_bytes(), import.size.to_le_bytes()].concat();
|
||||
data[..pe.size_of_headers as usize].windows(8).position(|w| w == needle.as_slice()).unwrap()
|
||||
};
|
||||
data[dirs_off..dirs_off + 4].copy_from_slice(&0xFFFF_FFF0u32.to_le_bytes());
|
||||
let pe = Pe::parse(&data, Layout::File).unwrap();
|
||||
assert!(pe.imports().is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn parses_own_test_binary_tls() {
|
||||
// The test harness itself is an x64 Rust binary with static TLS.
|
||||
|
||||
Reference in New Issue
Block a user