diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 31b9abd1..f6c734ba 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -7,6 +7,10 @@ on: - github-actions pull_request: +concurrency: + group: ${{ github.workflow }}-${{ github.head_ref || github.run_id }} + cancel-in-progress: true + jobs: unit_tests: name: Build sources @@ -25,8 +29,8 @@ jobs: - { os: ubuntu-latest, target: arm-unknown-linux-musleabi, use-cross: true } - { os: ubuntu-latest, target: arm-linux-androideabi, use-cross: true } - { os: ubuntu-latest, target: arm-unknown-linux-gnueabihf, use-cross: true } + - { os: windows-2022, target: x86_64-pc-windows-msvc, use-cross: false } #- { os: macos-latest, target: x86_64-apple-darwin, use-cross: false } - #- { os: windows-latest, target: x86_64-pc-windows-msvc, use-cross: false } steps: - name: Checkout repository uses: actions/checkout@v2 diff --git a/Cargo.toml b/Cargo.toml index 6beb65e0..f402185c 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -8,7 +8,7 @@ license = "MIT" [dependencies] byteorder = "1.3.2" cfg-if = "1.0" -crash-context = "0.0.2" +crash-context = "0.1" memoffset = "0.6" minidump-common = "0.10" scroll = "0.11" @@ -23,9 +23,20 @@ memmap2 = "0.5" [target.'cfg(any(target_os = "linux", target_os = "android"))'.dependencies] nix = "0.23" +[target.'cfg(target_os = "windows")'.dependencies.windows-sys] +version = "0.34" # Latest is 0.35 (for now), but a vast majority of the ecosystem uses 0.34 +features = [ + # MiniDumpWriteDump requires...a lot of features + "Win32_Foundation", + "Win32_Storage_FileSystem", + "Win32_System_Diagnostics_Debug", + "Win32_System_Kernel", + "Win32_System_Memory", + # VerifierEnumerateResource and friends + "Win32_System_ApplicationVerifier", + # GetCurrentThreadId & OpenProcess + "Win32_System_Threading", +] + [dev-dependencies] minidump = "0.10" - -[patch.crates-io] -minidump = { git = "https://github.com/rust-minidump/rust-minidump" } -minidump-common = { git = "https://github.com/rust-minidump/rust-minidump" } diff --git a/src/bin/test.rs b/src/bin/test.rs index 0146db7a..8a8f4095 100644 --- a/src/bin/test.rs +++ b/src/bin/test.rs @@ -1,292 +1,356 @@ -#![cfg(any(target_os = "linux", target_os = "android"))] - // This binary shouldn't be under /src, but under /tests, but that is // currently not possible (https://github.com/rust-lang/cargo/issues/4356) -use minidump_writer::{ - ptrace_dumper::{PtraceDumper, AT_SYSINFO_EHDR}, - LINUX_GATE_LIBRARY_NAME, -}; -use nix::{ - sys::mman::{mmap, MapFlags, ProtFlags}, - unistd::getppid, -}; -use std::{env, error, result}; - -type Error = Box; -pub type Result = result::Result; - -macro_rules! test { - ($x:expr, $errmsg:expr) => { - if $x { - Ok(()) - } else { - Err($errmsg) - } + +type Error = Box; +pub type Result = std::result::Result; + +#[cfg(any(target_os = "linux", target_os = "android"))] +mod linux { + use super::*; + use minidump_writer::{ + ptrace_dumper::{PtraceDumper, AT_SYSINFO_EHDR}, + LINUX_GATE_LIBRARY_NAME, + }; + use nix::{ + sys::mman::{mmap, MapFlags, ProtFlags}, + unistd::getppid, }; -} -fn test_setup() -> Result<()> { - let ppid = getppid(); - PtraceDumper::new(ppid.as_raw())?; - Ok(()) -} + macro_rules! test { + ($x:expr, $errmsg:expr) => { + if $x { + Ok(()) + } else { + Err($errmsg) + } + }; + } -fn test_thread_list() -> Result<()> { - let ppid = getppid(); - let dumper = PtraceDumper::new(ppid.as_raw())?; - test!(!dumper.threads.is_empty(), "No threads")?; - test!( - dumper - .threads - .iter() - .filter(|x| x.tid == ppid.as_raw()) - .count() - == 1, - "Thread found multiple times" - )?; - Ok(()) -} + fn test_setup() -> Result<()> { + let ppid = getppid(); + PtraceDumper::new(ppid.as_raw())?; + Ok(()) + } -fn test_copy_from_process(stack_var: usize, heap_var: usize) -> Result<()> { - let ppid = getppid().as_raw(); - let mut dumper = PtraceDumper::new(ppid)?; - dumper.suspend_threads()?; - let stack_res = PtraceDumper::copy_from_process(ppid, stack_var as *mut libc::c_void, 1)?; - - let expected_stack: libc::c_long = 0x11223344; - test!( - stack_res == expected_stack.to_ne_bytes(), - "stack var not correct" - )?; - - let heap_res = PtraceDumper::copy_from_process(ppid, heap_var as *mut libc::c_void, 1)?; - let expected_heap: libc::c_long = 0x55667788; - test!( - heap_res == expected_heap.to_ne_bytes(), - "heap var not correct" - )?; - dumper.resume_threads()?; - Ok(()) -} + fn test_thread_list() -> Result<()> { + let ppid = getppid(); + let dumper = PtraceDumper::new(ppid.as_raw())?; + test!(!dumper.threads.is_empty(), "No threads")?; + test!( + dumper + .threads + .iter() + .filter(|x| x.tid == ppid.as_raw()) + .count() + == 1, + "Thread found multiple times" + )?; + Ok(()) + } -fn test_find_mappings(addr1: usize, addr2: usize) -> Result<()> { - let ppid = getppid(); - let dumper = PtraceDumper::new(ppid.as_raw())?; - dumper - .find_mapping(addr1) - .ok_or("No mapping for addr1 found")?; + fn test_copy_from_process(stack_var: usize, heap_var: usize) -> Result<()> { + let ppid = getppid().as_raw(); + let mut dumper = PtraceDumper::new(ppid)?; + dumper.suspend_threads()?; + let stack_res = PtraceDumper::copy_from_process(ppid, stack_var as *mut libc::c_void, 1)?; - dumper - .find_mapping(addr2) - .ok_or("No mapping for addr2 found")?; + let expected_stack: libc::c_long = 0x11223344; + test!( + stack_res == expected_stack.to_ne_bytes(), + "stack var not correct" + )?; - test!(dumper.find_mapping(0).is_none(), "NULL found")?; - Ok(()) -} + let heap_res = PtraceDumper::copy_from_process(ppid, heap_var as *mut libc::c_void, 1)?; + let expected_heap: libc::c_long = 0x55667788; + test!( + heap_res == expected_heap.to_ne_bytes(), + "heap var not correct" + )?; + dumper.resume_threads()?; + Ok(()) + } -fn test_file_id() -> Result<()> { - let ppid = getppid().as_raw(); - let exe_link = format!("/proc/{}/exe", ppid); - let exe_name = std::fs::read_link(&exe_link)?.into_os_string(); - let mut dumper = PtraceDumper::new(getppid().as_raw())?; - let mut found_exe = None; - for (idx, mapping) in dumper.mappings.iter().enumerate() { - if mapping.name.as_ref().map(|x| x.into()).as_ref() == Some(&exe_name) { - found_exe = Some(idx); - break; - } + fn test_find_mappings(addr1: usize, addr2: usize) -> Result<()> { + let ppid = getppid(); + let dumper = PtraceDumper::new(ppid.as_raw())?; + dumper + .find_mapping(addr1) + .ok_or("No mapping for addr1 found")?; + + dumper + .find_mapping(addr2) + .ok_or("No mapping for addr2 found")?; + + test!(dumper.find_mapping(0).is_none(), "NULL found")?; + Ok(()) } - let idx = found_exe.unwrap(); - let id = dumper.elf_identifier_for_mapping_index(idx)?; - assert!(!id.is_empty()); - assert!(id.iter().any(|&x| x > 0)); - Ok(()) -} -fn test_merged_mappings(path: String, mapped_mem: usize, mem_size: usize) -> Result<()> { - // Now check that PtraceDumper interpreted the mappings properly. - let dumper = PtraceDumper::new(getppid().as_raw())?; - let mut mapping_count = 0; - for map in &dumper.mappings { - if map.name == Some(path.clone()) { - mapping_count += 1; - // This mapping should encompass the entire original mapped - // range. - assert_eq!(map.start_address, mapped_mem); - assert_eq!(map.size, mem_size); - assert_eq!(0, map.offset); + fn test_file_id() -> Result<()> { + let ppid = getppid().as_raw(); + let exe_link = format!("/proc/{}/exe", ppid); + let exe_name = std::fs::read_link(&exe_link)?.into_os_string(); + let mut dumper = PtraceDumper::new(getppid().as_raw())?; + let mut found_exe = None; + for (idx, mapping) in dumper.mappings.iter().enumerate() { + if mapping.name.as_ref().map(|x| x.into()).as_ref() == Some(&exe_name) { + found_exe = Some(idx); + break; + } } + let idx = found_exe.unwrap(); + let id = dumper.elf_identifier_for_mapping_index(idx)?; + assert!(!id.is_empty()); + assert!(id.iter().any(|&x| x > 0)); + Ok(()) } - assert_eq!(1, mapping_count); - Ok(()) -} -fn test_linux_gate_mapping_id() -> Result<()> { - let ppid = getppid().as_raw(); - let mut dumper = PtraceDumper::new(ppid)?; - let mut found_linux_gate = false; - for mut mapping in dumper.mappings.clone() { - if mapping.name.as_deref() == Some(LINUX_GATE_LIBRARY_NAME) { - found_linux_gate = true; - dumper.suspend_threads()?; - let id = PtraceDumper::elf_identifier_for_mapping(&mut mapping, ppid)?; - test!(!id.is_empty(), "id-vec is empty")?; - test!(id.iter().any(|&x| x > 0), "all id elements are 0")?; - dumper.resume_threads()?; - break; + fn test_merged_mappings(path: String, mapped_mem: usize, mem_size: usize) -> Result<()> { + // Now check that PtraceDumper interpreted the mappings properly. + let dumper = PtraceDumper::new(getppid().as_raw())?; + let mut mapping_count = 0; + for map in &dumper.mappings { + if map.name == Some(path.clone()) { + mapping_count += 1; + // This mapping should encompass the entire original mapped + // range. + assert_eq!(map.start_address, mapped_mem); + assert_eq!(map.size, mem_size); + assert_eq!(0, map.offset); + } } + assert_eq!(1, mapping_count); + Ok(()) } - test!(found_linux_gate, "found no linux_gate")?; - Ok(()) -} -fn test_mappings_include_linux_gate() -> Result<()> { - let ppid = getppid().as_raw(); - let dumper = PtraceDumper::new(ppid)?; - let linux_gate_loc = dumper.auxv[&AT_SYSINFO_EHDR]; - test!(linux_gate_loc != 0, "linux_gate_loc == 0")?; - let mut found_linux_gate = false; - for mapping in &dumper.mappings { - if mapping.name.as_deref() == Some(LINUX_GATE_LIBRARY_NAME) { - found_linux_gate = true; - test!( - linux_gate_loc == mapping.start_address.try_into()?, - "linux_gate_loc != start_address" - )?; - - // This doesn't work here, as we do not test via "fork()", so the addresses are different - // let ll = mapping.start_address as *const u8; - // for idx in 0..header::SELFMAG { - // let mag = unsafe { std::ptr::read(ll.offset(idx as isize)) == header::ELFMAG[idx] }; - // test!( - // mag, - // format!("ll: {} != ELFMAG: {} at {}", mag, header::ELFMAG[idx], idx) - // )?; - // } - break; + fn test_linux_gate_mapping_id() -> Result<()> { + let ppid = getppid().as_raw(); + let mut dumper = PtraceDumper::new(ppid)?; + let mut found_linux_gate = false; + for mut mapping in dumper.mappings.clone() { + if mapping.name.as_deref() == Some(LINUX_GATE_LIBRARY_NAME) { + found_linux_gate = true; + dumper.suspend_threads()?; + let id = PtraceDumper::elf_identifier_for_mapping(&mut mapping, ppid)?; + test!(!id.is_empty(), "id-vec is empty")?; + test!(id.iter().any(|&x| x > 0), "all id elements are 0")?; + dumper.resume_threads()?; + break; + } } + test!(found_linux_gate, "found no linux_gate")?; + Ok(()) } - test!(found_linux_gate, "found no linux_gate")?; - Ok(()) -} -fn spawn_and_wait(num: usize) -> Result<()> { - // One less than the requested amount, as the main thread counts as well - for _ in 1..num { - std::thread::spawn(|| { - println!("1"); - loop { - std::thread::park(); + fn test_mappings_include_linux_gate() -> Result<()> { + let ppid = getppid().as_raw(); + let dumper = PtraceDumper::new(ppid)?; + let linux_gate_loc = dumper.auxv[&AT_SYSINFO_EHDR]; + test!(linux_gate_loc != 0, "linux_gate_loc == 0")?; + let mut found_linux_gate = false; + for mapping in &dumper.mappings { + if mapping.name.as_deref() == Some(LINUX_GATE_LIBRARY_NAME) { + found_linux_gate = true; + test!( + linux_gate_loc == mapping.start_address.try_into()?, + "linux_gate_loc != start_address" + )?; + + // This doesn't work here, as we do not test via "fork()", so the addresses are different + // let ll = mapping.start_address as *const u8; + // for idx in 0..header::SELFMAG { + // let mag = unsafe { std::ptr::read(ll.offset(idx as isize)) == header::ELFMAG[idx] }; + // test!( + // mag, + // format!("ll: {} != ELFMAG: {} at {}", mag, header::ELFMAG[idx], idx) + // )?; + // } + break; } - }); - } - println!("1"); - loop { - std::thread::park(); + } + test!(found_linux_gate, "found no linux_gate")?; + Ok(()) } -} -fn spawn_name_wait(num: usize) -> Result<()> { - // One less than the requested amount, as the main thread counts as well - for id in 1..num { - std::thread::Builder::new() - .name(format!("thread_{}", id)) - .spawn(|| { + fn spawn_and_wait(num: usize) -> Result<()> { + // One less than the requested amount, as the main thread counts as well + for _ in 1..num { + std::thread::spawn(|| { println!("1"); loop { std::thread::park(); } - })?; - } - println!("1"); - loop { - std::thread::park(); + }); + } + println!("1"); + loop { + std::thread::park(); + } } -} -fn spawn_mmap_wait() -> Result<()> { - let page_size = nix::unistd::sysconf(nix::unistd::SysconfVar::PAGE_SIZE).unwrap(); - let memory_size = page_size.unwrap() as usize; - // Get some memory to be mapped by the child-process - let mapped_mem = unsafe { - mmap( - std::ptr::null_mut(), - memory_size, - ProtFlags::PROT_READ | ProtFlags::PROT_WRITE, - MapFlags::MAP_PRIVATE | MapFlags::MAP_ANON, - -1, - 0, - ) - .unwrap() - }; - println!("{} {}", mapped_mem as usize, memory_size); - loop { - std::thread::park(); + fn spawn_name_wait(num: usize) -> Result<()> { + // One less than the requested amount, as the main thread counts as well + for id in 1..num { + std::thread::Builder::new() + .name(format!("thread_{}", id)) + .spawn(|| { + println!("1"); + loop { + std::thread::park(); + } + })?; + } + println!("1"); + loop { + std::thread::park(); + } } -} -fn spawn_alloc_wait() -> Result<()> { - let page_size = nix::unistd::sysconf(nix::unistd::SysconfVar::PAGE_SIZE).unwrap(); - let memory_size = page_size.unwrap() as usize; + fn spawn_mmap_wait() -> Result<()> { + let page_size = nix::unistd::sysconf(nix::unistd::SysconfVar::PAGE_SIZE).unwrap(); + let memory_size = page_size.unwrap() as usize; + // Get some memory to be mapped by the child-process + let mapped_mem = unsafe { + mmap( + std::ptr::null_mut(), + memory_size, + ProtFlags::PROT_READ | ProtFlags::PROT_WRITE, + MapFlags::MAP_PRIVATE | MapFlags::MAP_ANON, + -1, + 0, + ) + .unwrap() + }; - let mut values = Vec::::with_capacity(memory_size); - for idx in 0..memory_size { - values.push((idx % 255) as u8); + println!("{} {}", mapped_mem as usize, memory_size); + loop { + std::thread::park(); + } } - println!("{:p} {}", values.as_ptr(), memory_size); - loop { - std::thread::park(); + fn spawn_alloc_wait() -> Result<()> { + let page_size = nix::unistd::sysconf(nix::unistd::SysconfVar::PAGE_SIZE).unwrap(); + let memory_size = page_size.unwrap() as usize; + + let mut values = Vec::::with_capacity(memory_size); + for idx in 0..memory_size { + values.push((idx % 255) as u8); + } + + println!("{:p} {}", values.as_ptr(), memory_size); + loop { + std::thread::park(); + } } -} -fn main() -> Result<()> { - let args: Vec<_> = env::args().skip(1).collect(); - match args.len() { - 1 => match args[0].as_ref() { - "file_id" => test_file_id(), - "setup" => test_setup(), - "thread_list" => test_thread_list(), - "mappings_include_linux_gate" => test_mappings_include_linux_gate(), - "linux_gate_mapping_id" => test_linux_gate_mapping_id(), - "spawn_mmap_wait" => spawn_mmap_wait(), - "spawn_alloc_wait" => spawn_alloc_wait(), - _ => Err("Len 1: Unknown test option".into()), - }, - 2 => match args[0].as_ref() { - "spawn_and_wait" => { - let num_of_threads: usize = args[1].parse().unwrap(); - spawn_and_wait(num_of_threads) + pub(super) fn real_main(args: Vec) -> Result<()> { + match args.len() { + 1 => match args[0].as_ref() { + "file_id" => test_file_id(), + "setup" => test_setup(), + "thread_list" => test_thread_list(), + "mappings_include_linux_gate" => test_mappings_include_linux_gate(), + "linux_gate_mapping_id" => test_linux_gate_mapping_id(), + "spawn_mmap_wait" => spawn_mmap_wait(), + "spawn_alloc_wait" => spawn_alloc_wait(), + _ => Err("Len 1: Unknown test option".into()), + }, + 2 => match args[0].as_ref() { + "spawn_and_wait" => { + let num_of_threads: usize = args[1].parse().unwrap(); + spawn_and_wait(num_of_threads) + } + "spawn_name_wait" => { + let num_of_threads: usize = args[1].parse().unwrap(); + spawn_name_wait(num_of_threads) + } + _ => Err(format!("Len 2: Unknown test option: {}", args[0]).into()), + }, + 3 => { + if args[0] == "find_mappings" { + let addr1: usize = args[1].parse().unwrap(); + let addr2: usize = args[2].parse().unwrap(); + test_find_mappings(addr1, addr2) + } else if args[0] == "copy_from_process" { + let stack_var: usize = args[1].parse().unwrap(); + let heap_var: usize = args[2].parse().unwrap(); + test_copy_from_process(stack_var, heap_var) + } else { + Err(format!("Len 3: Unknown test option: {}", args[0]).into()) + } } - "spawn_name_wait" => { - let num_of_threads: usize = args[1].parse().unwrap(); - spawn_name_wait(num_of_threads) + 4 => { + if args[0] == "merged_mappings" { + let path = &args[1]; + let mapped_mem: usize = args[2].parse().unwrap(); + let mem_size: usize = args[3].parse().unwrap(); + test_merged_mappings(path.to_string(), mapped_mem, mem_size) + } else { + Err(format!("Len 4: Unknown test option: {}", args[0]).into()) + } } - _ => Err(format!("Len 2: Unknown test option: {}", args[0]).into()), + _ => Err("Unknown test option".into()), + } + } +} + +#[cfg(target_os = "windows")] +mod windows { + use super::*; + use std::mem; + use windows_sys::Win32::{ + Foundation::CloseHandle, + System::{ + Diagnostics::Debug::{GetThreadContext, CONTEXT, EXCEPTION_POINTERS, EXCEPTION_RECORD}, + Threading::{GetCurrentProcessId, GetCurrentThread, GetCurrentThreadId}, }, - 3 => { - if args[0] == "find_mappings" { - let addr1: usize = args[1].parse().unwrap(); - let addr2: usize = args[2].parse().unwrap(); - test_find_mappings(addr1, addr2) - } else if args[0] == "copy_from_process" { - let stack_var: usize = args[1].parse().unwrap(); - let heap_var: usize = args[2].parse().unwrap(); - test_copy_from_process(stack_var, heap_var) - } else { - Err(format!("Len 3: Unknown test option: {}", args[0]).into()) + }; + + #[inline(never)] + pub(super) fn real_main(args: Vec) -> Result<()> { + let exception_code = u32::from_str_radix(&args[0], 16).unwrap() as i32; + + // Generate the exception and communicate back where the exception pointers + // are + unsafe { + let mut exception_record: EXCEPTION_RECORD = mem::zeroed(); + let mut exception_context: CONTEXT = mem::zeroed(); + exception_context.ContextFlags = + minidump_common::format::ContextFlagsAmd64::CONTEXT_AMD64_ALL.bits(); + + let pid = GetCurrentProcessId(); + let tid = GetCurrentThreadId(); + + GetThreadContext(GetCurrentThread(), &mut exception_context); + + let exception_ptrs = EXCEPTION_POINTERS { + ExceptionRecord: &mut exception_record, + ContextRecord: &mut exception_context, + }; + + exception_record.ExceptionCode = exception_code; + + let exc_ptr_addr = &exception_ptrs as *const _ as usize; + + println!("{pid} {exc_ptr_addr} {tid} {exception_code:x}"); + + // Wait until we're killed + loop { + std::thread::park(); } } - 4 => { - if args[0] == "merged_mappings" { - let path = &args[1]; - let mapped_mem: usize = args[2].parse().unwrap(); - let mem_size: usize = args[3].parse().unwrap(); - test_merged_mappings(path.to_string(), mapped_mem, mem_size) - } else { - Err(format!("Len 4: Unknown test option: {}", args[0]).into()) - } + } +} + +fn main() -> Result<()> { + let args: Vec<_> = std::env::args().skip(1).collect(); + + cfg_if::cfg_if! { + if #[cfg(any(target_os = "linux", target_os = "android"))] { + linux::real_main(args) + } else if #[cfg(target_os = "windows")] { + windows::real_main(args) + } else { + unimplemented!(); } - _ => Err("Unknown test option".into()), } } diff --git a/src/lib.rs b/src/lib.rs index 8a5ea122..ab803757 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -3,6 +3,10 @@ cfg_if::cfg_if! { mod linux; pub use linux::*; + } else if #[cfg(target_os = "windows")] { + mod windows; + + pub use windows::*; } } diff --git a/src/windows.rs b/src/windows.rs new file mode 100644 index 00000000..1ae7a276 --- /dev/null +++ b/src/windows.rs @@ -0,0 +1,2 @@ +pub mod errors; +pub mod minidump_writer; diff --git a/src/windows/errors.rs b/src/windows/errors.rs new file mode 100644 index 00000000..f85e9752 --- /dev/null +++ b/src/windows/errors.rs @@ -0,0 +1,7 @@ +#[derive(Debug, thiserror::Error)] +pub enum Error { + #[error(transparent)] + Io(#[from] std::io::Error), + #[error(transparent)] + Scroll(#[from] scroll::Error), +} diff --git a/src/windows/minidump_writer.rs b/src/windows/minidump_writer.rs new file mode 100644 index 00000000..ce6bc2f8 --- /dev/null +++ b/src/windows/minidump_writer.rs @@ -0,0 +1,284 @@ +use crate::windows::errors::Error; +use minidump_common::format::{BreakpadInfoValid, MINIDUMP_BREAKPAD_INFO, MINIDUMP_STREAM_TYPE}; +use scroll::Pwrite; +use std::{ffi::c_void, os::windows::io::AsRawHandle}; +pub use windows_sys::Win32::Foundation::HANDLE; +use windows_sys::Win32::{ + Foundation::{CloseHandle, ERROR_SUCCESS, STATUS_INVALID_HANDLE}, + System::{ApplicationVerifier as av, Diagnostics::Debug as md, Threading as threading}, +}; + +pub struct MinidumpWriter { + /// The crash context as captured by an exception handler + crash_context: crash_context::CrashContext, + /// Handle to the crashing process, which could be ourselves + crashing_process: HANDLE, + /// The pid of the crashing process. + crashing_pid: u32, + /// The `EXCEPTION_POINTERS` contained in crash context is a pointer into the + /// memory of the process that crashed, as it contains an `EXCEPTION_RECORD` + /// record which is an internally linked list, so in the case that we are + /// dumping a process other than the current one, we need to tell + /// MiniDumpWriteDump that the pointers come from an external process so that + /// it can use eg ReadProcessMemory to get the contextual information from + /// the crash, rather than from the current process + is_external_process: bool, +} + +impl MinidumpWriter { + /// Creates a minidump writer for a crash that occurred in an external process. + /// + /// # Errors + /// + /// Fails if we are unable to open the external process for some reason + pub fn external_process( + crash_context: crash_context::CrashContext, + pid: u32, + ) -> Result { + // SAFETY: syscall + let crashing_process = unsafe { + threading::OpenProcess( + threading::PROCESS_ALL_ACCESS, // desired access + 0, // inherit handles + pid, // pid + ) + }; + + if crashing_process == 0 { + Err(std::io::Error::last_os_error().into()) + } else { + Ok(Self { + crash_context, + crashing_process, + crashing_pid: pid, + is_external_process: true, + }) + } + } + + /// Creates a minidump writer for a crash that occurred in the current process. + /// + /// Note that in-process dumping is inherently unreliable, it is recommended + /// to use the [`Self::external_process`] in a different process than the + /// one that crashed when possible. + pub fn current_process(crash_context: crash_context::CrashContext) -> Self { + let crashing_pid = std::process::id(); + + // SAFETY: syscall + let crashing_process = unsafe { threading::GetCurrentProcess() }; + + Self { + crash_context, + crashing_process, + crashing_pid, + is_external_process: false, + } + } + + /// Writes a minidump to the specified file + pub fn dump(&self, destination: &mut std::fs::File) -> Result<(), Error> { + let exc_info = if !self.crash_context.exception_pointers.is_null() { + // https://docs.microsoft.com/en-us/windows/win32/api/minidumpapiset/ns-minidumpapiset-minidump_exception_information + Some(md::MINIDUMP_EXCEPTION_INFORMATION { + ThreadId: self.crash_context.thread_id, + // This is a mut pointer for some reason...I don't _think_ it is + // actually mut in practice...? + ExceptionPointers: self.crash_context.exception_pointers as *mut _, + ClientPointers: if self.is_external_process { 1 } else { 0 }, + }) + } else { + None + }; + + // This is a bit dangerous if doing in-process dumping, but that's not + // (currently) a real target of this crate, so this allocation is fine + let mut user_streams = Vec::with_capacity(2); + + let mut breakpad_info = self.fill_breakpad_stream(); + + if let Some(bp_info) = &mut breakpad_info { + user_streams.push(md::MINIDUMP_USER_STREAM { + Type: MINIDUMP_STREAM_TYPE::BreakpadInfoStream as u32, + BufferSize: bp_info.len() as u32, + // Again with the mut pointer + Buffer: bp_info.as_mut_ptr().cast(), + }); + } + + let mut handle_stream_buffer = self.fill_handle_stream(); + + // Note that we do this by ref, as the buffer inside the option needs + // to stay alive for as long as we're writing the minidump since + // the user stream has a pointer to it + if let Some(buf) = &mut handle_stream_buffer { + let handle_stream = md::MINIDUMP_USER_STREAM { + Type: MINIDUMP_STREAM_TYPE::HandleOperationListStream as u32, + BufferSize: buf.len() as u32, + // Still not getting over the mut pointers here + Buffer: buf.as_mut_ptr().cast(), + }; + + user_streams.push(handle_stream); + } + + let user_stream_infos = md::MINIDUMP_USER_STREAM_INFORMATION { + UserStreamCount: user_streams.len() as u32, + UserStreamArray: user_streams.as_mut_ptr(), + }; + + // Write the actual minidump + // https://docs.microsoft.com/en-us/windows/win32/api/minidumpapiset/nf-minidumpapiset-minidumpwritedump + // SAFETY: syscall + let ret = unsafe { + md::MiniDumpWriteDump( + self.crashing_process, // HANDLE to the process with the crash we want to capture + self.crashing_pid, // process id + destination.as_raw_handle() as HANDLE, // file to write the minidump to + md::MiniDumpNormal, // MINIDUMP_TYPE - we _might_ want to make this configurable + exc_info + .as_ref() + .map_or(std::ptr::null(), |ei| ei as *const _), // exceptionparam - the actual exception information + &user_stream_infos, // user streams + std::ptr::null(), // callback, unused + ) + }; + + if ret == 0 { + Err(std::io::Error::last_os_error().into()) + } else { + Ok(()) + } + } + + /// Create an MDRawBreakpadInfo stream to the minidump, to provide additional + /// information about the exception handler to the Breakpad processor. + /// The information will help the processor determine which threads are + /// relevant. The Breakpad processor does not require this information but + /// can function better with Breakpad-generated dumps when it is present. + /// The native debugger is not harmed by the presence of this information. + /// + /// This info is only relevant for in-process dumping + fn fill_breakpad_stream(&self) -> Option<[u8; 12]> { + if self.is_external_process { + return None; + } + + let mut breakpad_info = [0u8; 12]; + + let bp_info = MINIDUMP_BREAKPAD_INFO { + validity: BreakpadInfoValid::DumpThreadId.bits() + | BreakpadInfoValid::RequestingThreadId.bits(), + dump_thread_id: self.crash_context.thread_id, + // Safety: syscall + requesting_thread_id: unsafe { threading::GetCurrentThreadId() }, + }; + + // TODO: derive Pwrite for MINIDUMP_BREAKPAD_INFO + // https://github.com/rust-minidump/rust-minidump/pull/534 + let mut offset = 0; + breakpad_info.gwrite(bp_info.validity, &mut offset).ok()?; + breakpad_info + .gwrite(bp_info.dump_thread_id, &mut offset) + .ok()?; + breakpad_info + .gwrite(bp_info.requesting_thread_id, &mut offset) + .ok()?; + + Some(breakpad_info) + } + + /// In the case of a `STATUS_INVALID_HANDLE` exception, this function + /// enumerates all of the handle operations that occurred within the crashing + /// process and fills out a minidump user stream with the ops pertaining to + /// the last invalid handle that is enumerated, which is, presumably + /// (hopefully?), the one that led to the exception + fn fill_handle_stream(&self) -> Option> { + if self.crash_context.exception_code != STATUS_INVALID_HANDLE { + return None; + } + + // State object we pass to the enumeration + struct HandleState { + ops: Vec, + last_invalid: u64, + } + + unsafe extern "system" fn enum_callback( + resource_description: *mut c_void, + enumeration_context: *mut c_void, + enumeration_level: *mut u32, + ) -> u32 { + let description = &*resource_description.cast::(); + let mut hs = &mut *enumeration_context.cast::(); + + // Remember the last invalid handle operation. + if description.OperationType == av::OperationDbBADREF as u32 { + hs.last_invalid = description.Handle; + } + + // Record all handle operations. + hs.ops.push(*description); + *enumeration_level = av::HeapEnumerationEverything as u32; + ERROR_SUCCESS + } + + let mut hs = HandleState { + ops: Vec::new(), + last_invalid: 0, + }; + + // https://docs.microsoft.com/en-us/windows/win32/api/avrfsdk/nf-avrfsdk-verifierenumerateresource + // SAFETY: syscall + if unsafe { + av::VerifierEnumerateResource( + self.crashing_process, // process to enumerate the handles for + 0, // flags + av::AvrfResourceHandleTrace, // resource typea, we want to trace handles + Some(enum_callback), // enumeration callback + (&mut hs as *mut HandleState).cast(), // enumeration context + ) + } == ERROR_SUCCESS + { + let mut stream_buf = Vec::new(); + + // https://docs.microsoft.com/en-us/windows/win32/api/minidumpapiset/ns-minidumpapiset-minidump_handle_operation_list + let mut md_list = md::MINIDUMP_HANDLE_OPERATION_LIST { + SizeOfHeader: std::mem::size_of::() as u32, + SizeOfEntry: std::mem::size_of::() as u32, + NumberOfEntries: 0, + Reserved: 0, + }; + + stream_buf.resize(md_list.SizeOfHeader as usize, 0); + + #[inline] + fn to_bytes(v: &T) -> &[u8] { + // SAFETY: both AVRF_HANDLE_OPERATION and MINIDUMP_HANDLE_OPERATION_LIST + // are POD types + unsafe { + std::slice::from_raw_parts((v as *const T).cast(), std::mem::size_of::()) + } + } + + for op in hs.ops.into_iter().filter(|op| op.Handle == hs.last_invalid) { + stream_buf.extend_from_slice(to_bytes(&op)); + md_list.NumberOfEntries += 1; + } + + stream_buf[..md_list.SizeOfHeader as usize].copy_from_slice(to_bytes(&md_list)); + + Some(stream_buf) + } else { + // We don't _particularly_ care if this fails, it's better if we had + // the info, but not critical + None + } + } +} + +impl Drop for MinidumpWriter { + fn drop(&mut self) { + // SAFETY: syscall + unsafe { CloseHandle(self.crashing_process) }; + } +} diff --git a/tests/minidump_writer.rs b/tests/linux_minidump_writer.rs similarity index 98% rename from tests/minidump_writer.rs rename to tests/linux_minidump_writer.rs index 27c56f9e..3901f08e 100644 --- a/tests/minidump_writer.rs +++ b/tests/linux_minidump_writer.rs @@ -180,28 +180,27 @@ fn test_write_and_read_dump_from_parent_helper(context: Context) { let _: MinidumpException = dump.get_stream().expect("Couldn't find MinidumpException"); let _: MinidumpThreadList = dump.get_stream().expect("Couldn't find MinidumpThreadList"); let _: MinidumpMemoryList = dump.get_stream().expect("Couldn't find MinidumpMemoryList"); - let _: MinidumpException = dump.get_stream().expect("Couldn't find MinidumpException"); let _: MinidumpSystemInfo = dump.get_stream().expect("Couldn't find MinidumpSystemInfo"); let _ = dump - .get_raw_stream(LinuxCpuInfo) + .get_raw_stream(LinuxCpuInfo as u32) .expect("Couldn't find LinuxCpuInfo"); let _ = dump - .get_raw_stream(LinuxProcStatus) + .get_raw_stream(LinuxProcStatus as u32) .expect("Couldn't find LinuxProcStatus"); let _ = dump - .get_raw_stream(LinuxCmdLine) + .get_raw_stream(LinuxCmdLine as u32) .expect("Couldn't find LinuxCmdLine"); let _ = dump - .get_raw_stream(LinuxEnviron) + .get_raw_stream(LinuxEnviron as u32) .expect("Couldn't find LinuxEnviron"); let _ = dump - .get_raw_stream(LinuxAuxv) + .get_raw_stream(LinuxAuxv as u32) .expect("Couldn't find LinuxAuxv"); let _ = dump - .get_raw_stream(LinuxMaps) + .get_raw_stream(LinuxMaps as u32) .expect("Couldn't find LinuxMaps"); let _ = dump - .get_raw_stream(LinuxDsoDebug) + .get_raw_stream(LinuxDsoDebug as u32) .expect("Couldn't find LinuxDsoDebug"); } #[test] diff --git a/tests/ptrace_dumper.rs b/tests/ptrace_dumper.rs index ffe2fb79..520a3eaa 100644 --- a/tests/ptrace_dumper.rs +++ b/tests/ptrace_dumper.rs @@ -1,3 +1,6 @@ +//! All of these tests are specific to ptrace +#![cfg(any(target_os = "linux", target_os = "android"))] + use minidump_writer::ptrace_dumper::PtraceDumper; use nix::sys::mman::{mmap, MapFlags, ProtFlags}; use nix::sys::signal::Signal; diff --git a/tests/windows_minidump_writer.rs b/tests/windows_minidump_writer.rs new file mode 100644 index 00000000..7415e370 --- /dev/null +++ b/tests/windows_minidump_writer.rs @@ -0,0 +1,140 @@ +#![cfg(all(target_os = "windows", target_arch = "x86_64"))] + +use minidump::{CrashReason, Minidump, MinidumpMemoryList, MinidumpSystemInfo, MinidumpThreadList}; +use minidump_writer::minidump_writer::MinidumpWriter; +use std::mem; +use windows_sys::Win32::{ + Foundation::{EXCEPTION_ILLEGAL_INSTRUCTION, STATUS_INVALID_PARAMETER}, + System::{ + Diagnostics::Debug::{RtlCaptureContext, EXCEPTION_POINTERS, EXCEPTION_RECORD}, + Threading::GetCurrentThreadId, + }, +}; +mod common; +use common::start_child_and_return; + +fn get_crash_reason<'a, T: std::ops::Deref + 'a>( + md: &Minidump<'a, T>, +) -> CrashReason { + let exc: minidump::MinidumpException<'_> = + md.get_stream().expect("unable to find exception stream"); + + exc.get_crash_reason( + minidump::system_info::Os::Windows, + minidump::system_info::Cpu::X86_64, + ) +} + +/// Ensures that we can write minidumps for the current process, even if this is +/// not necessarily the primary intended use case of out-of-process dumping +#[test] +fn dump_current_process() { + let mut tmpfile = tempfile::Builder::new() + .prefix("windows_current_process") + .tempfile() + .unwrap(); + + unsafe { + let mut exception_record: EXCEPTION_RECORD = mem::zeroed(); + let mut exception_context = mem::MaybeUninit::uninit(); + + RtlCaptureContext(exception_context.as_mut_ptr()); + + let mut exception_context = exception_context.assume_init(); + + let exception_ptrs = EXCEPTION_POINTERS { + ExceptionRecord: &mut exception_record, + ContextRecord: &mut exception_context, + }; + + exception_record.ExceptionCode = STATUS_INVALID_PARAMETER; + + let crash_context = crash_context::CrashContext { + exception_pointers: (&exception_ptrs as *const EXCEPTION_POINTERS).cast(), + thread_id: GetCurrentThreadId(), + exception_code: STATUS_INVALID_PARAMETER, + }; + + let dumper = MinidumpWriter::current_process(crash_context); + + dumper + .dump(tmpfile.as_file_mut()) + .expect("failed to write minidump"); + } + + let md = Minidump::read_path(tmpfile.path()).expect("failed to read minidump"); + + let _: MinidumpThreadList = md.get_stream().expect("Couldn't find MinidumpThreadList"); + let _: MinidumpMemoryList = md.get_stream().expect("Couldn't find MinidumpMemoryList"); + let _: MinidumpSystemInfo = md.get_stream().expect("Couldn't find MinidumpSystemInfo"); + + let crash_reason = get_crash_reason(&md); + + assert_eq!( + crash_reason, + CrashReason::from_windows_error(STATUS_INVALID_PARAMETER as u32) + ); +} + +/// Ensures that we can write minidumps for an external process. Unfortunately +/// this requires us to know the actual pointer in the client process for the +/// exception, as the `MiniDumpWriteDump` syscall directly reads points from +/// the process memory, so we communicate that back from the client process +/// via stdout +#[test] +fn dump_external_process() { + use std::io::BufRead; + + let mut child = start_child_and_return(&format!("{:x}", EXCEPTION_ILLEGAL_INSTRUCTION)); + + let (process_id, exception_pointers, thread_id, exception_code) = { + let mut f = std::io::BufReader::new(child.stdout.as_mut().expect("Can't open stdout")); + let mut buf = String::new(); + f.read_line(&mut buf).expect("failed to read stdout"); + assert!(!buf.is_empty()); + + let mut biter = buf.trim().split(' '); + + let process_id: u32 = biter.next().unwrap().parse().unwrap(); + let exception_pointers: usize = biter.next().unwrap().parse().unwrap(); + let thread_id: u32 = biter.next().unwrap().parse().unwrap(); + let exception_code = u32::from_str_radix(biter.next().unwrap(), 16).unwrap() as i32; + + (process_id, exception_pointers, thread_id, exception_code) + }; + + assert_eq!(exception_code, EXCEPTION_ILLEGAL_INSTRUCTION); + + let crash_context = crash_context::CrashContext { + exception_pointers: exception_pointers as _, + thread_id, + exception_code, + }; + + let mut tmpfile = tempfile::Builder::new() + .prefix("windows_external_process") + .tempfile() + .unwrap(); + + let dumper = MinidumpWriter::external_process(crash_context, process_id) + .expect("failed to create MinidumpWriter"); + + dumper + .dump(tmpfile.as_file_mut()) + .expect("failed to write minidump"); + + child.kill().expect("failed to kill child"); + + let md = Minidump::read_path(tmpfile.path()).expect("failed to read minidump"); + + let _: MinidumpThreadList = md.get_stream().expect("Couldn't find MinidumpThreadList"); + let _: MinidumpMemoryList = md.get_stream().expect("Couldn't find MinidumpMemoryList"); + let _: MinidumpSystemInfo = md.get_stream().expect("Couldn't find MinidumpSystemInfo"); + + let crash_reason = get_crash_reason(&md); + + assert_eq!( + crash_reason, + CrashReason::from_windows_code(EXCEPTION_ILLEGAL_INSTRUCTION as u32) + ); +}