diff --git a/Cargo.toml b/Cargo.toml index e92da703..9f8a692b 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -8,6 +8,7 @@ license = "MIT" [dependencies] byteorder = "1.3.2" cfg-if = "1.0" +crash-context = "0.0.1" memoffset = "0.6" minidump-common = "0.10" scroll = "0.11" diff --git a/src/linux/crash_context.rs b/src/linux/crash_context.rs index 4802ad87..f7a554d1 100644 --- a/src/linux/crash_context.rs +++ b/src/linux/crash_context.rs @@ -2,55 +2,18 @@ //! structures which we get from the kernel. These are platform specific //! functions to juggle the `ucontext_t` and user structures into minidump format. -#![allow(non_camel_case_types)] +pub struct CrashContext { + pub inner: crash_context::CrashContext, +} cfg_if::cfg_if! { if #[cfg(target_arch = "x86_64")] { - pub(crate) mod x86_64; - - pub type fpstate_t = libc::user_fpregs_struct; + mod x86_64; } else if #[cfg(target_arch = "x86")] { - pub(crate) mod x86; - - pub type fpstate_t = libc::_libc_fpstate; - } else if #[cfg(target_arch = "arm")] { - pub(crate) mod arm; + mod x86; } else if #[cfg(target_arch = "aarch64")] { - pub(crate) mod aarch64; - - /// Magic value written by the kernel and our custom getcontext - pub const FPSIMD_MAGIC: u32 = 0x46508001; - - #[repr(C)] - #[derive(Clone)] - pub struct _aarch64_ctx { - pub magic: u32, - pub size: u32, - } - - #[repr(C)] - #[derive(Clone)] - pub struct fpsimd_context { - pub head: _aarch64_ctx, - pub fpsr: u32, - pub fpcr: u32, - pub vregs: [u128; 32], - } - - pub type fpstate_t = fpsimd_context; + mod aarch64; + } else if #[cfg(target_arch = "arm")] { + mod arm; } } - -#[repr(C)] -#[derive(Clone)] -pub struct CrashContext { - pub siginfo: libc::siginfo_t, - pub tid: libc::pid_t, // the crashing thread. - #[cfg(not(target_arch = "arm"))] - pub context: libc::ucontext_t, - // #ifdef this out because FP state is not part of user ABI for Linux ARM. - // In case of MIPS Linux FP state is already part of ucontext_t so - // 'float_state' is not required. - #[cfg(not(target_arch = "arm"))] - pub float_state: fpstate_t, -} diff --git a/src/linux/crash_context/aarch64.rs b/src/linux/crash_context/aarch64.rs index 216d9441..37c5eff7 100644 --- a/src/linux/crash_context/aarch64.rs +++ b/src/linux/crash_context/aarch64.rs @@ -6,23 +6,29 @@ use crate::{ impl CrashContext { pub fn get_instruction_pointer(&self) -> usize { - self.context.uc_mcontext.pc as usize + self.inner.context.uc_mcontext.pc as usize } pub fn get_stack_pointer(&self) -> usize { - self.context.uc_mcontext.sp as usize + self.inner.context.uc_mcontext.sp as usize } pub fn fill_cpu_context(&self, out: &mut RawContextCPU) { out.context_flags = format::ContextFlagsArm64Old::CONTEXT_ARM64_OLD_FULL.bits() as u64; - out.cpsr = self.context.uc_mcontext.pstate as u32; - out.iregs[..GP_REG_COUNT].copy_from_slice(&self.context.uc_mcontext.regs[..GP_REG_COUNT]); - out.sp = self.context.uc_mcontext.sp; - out.pc = self.context.uc_mcontext.pc; + { + let gregs = &self.inner.context.uc_mcontext; + out.cpsr = gregs.pstate as u32; + out.iregs[..GP_REG_COUNT].copy_from_slice(&gregs.regs[..GP_REG_COUNT]); + out.sp = gregs.sp; + out.pc = gregs.pc; + } - out.fpsr = self.float_state.fpsr; - out.fpcr = self.float_state.fpcr; - out.float_regs[..FP_REG_COUNT].copy_from_slice(&self.float_state.vregs[..FP_REG_COUNT]); + { + let fs = &self.inner.float_state; + out.float_save.fpsr = fs.fpsr; + out.float_save.fpcr = fs.fpcr; + out.float_save.regs[..FP_REG_COUNT].copy_from_slice(&fs.vregs[..FP_REG_COUNT]); + } } } diff --git a/src/linux/crash_context/x86.rs b/src/linux/crash_context/x86.rs index 874a31f9..7f092716 100644 --- a/src/linux/crash_context/x86.rs +++ b/src/linux/crash_context/x86.rs @@ -6,11 +6,11 @@ use libc::{ }; impl CrashContext { pub fn get_instruction_pointer(&self) -> usize { - self.context.uc_mcontext.gregs[REG_EIP as usize] as usize + self.inner.context.uc_mcontext.gregs[REG_EIP as usize] as usize } pub fn get_stack_pointer(&self) -> usize { - self.context.uc_mcontext.gregs[REG_ESP as usize] as usize + self.inner.context.uc_mcontext.gregs[REG_ESP as usize] as usize } pub fn fill_cpu_context(&self, out: &mut RawContextCPU) { @@ -18,7 +18,7 @@ impl CrashContext { | ContextFlagsX86::CONTEXT_X86_FLOATING_POINT.bits(); { - let gregs = &self.context.uc_mcontext.gregs; + let gregs = &self.inner.context.uc_mcontext.gregs; out.gs = gregs[REG_GS as usize] as u32; out.fs = gregs[REG_FS as usize] as u32; out.es = gregs[REG_ES as usize] as u32; @@ -40,7 +40,7 @@ impl CrashContext { } { - let fs = &self.float_state; + let fs = &self.inner.float_state; let mut out = &mut out.float_save; out.control_word = fs.cw; out.status_word = fs.sw; diff --git a/src/linux/crash_context/x86_64.rs b/src/linux/crash_context/x86_64.rs index ffc5f8ad..e5596926 100644 --- a/src/linux/crash_context/x86_64.rs +++ b/src/linux/crash_context/x86_64.rs @@ -10,18 +10,18 @@ use scroll::Pwrite; impl CrashContext { pub fn get_instruction_pointer(&self) -> usize { - self.context.uc_mcontext.gregs[REG_RIP as usize] as usize + self.inner.context.uc_mcontext.gregs[REG_RIP as usize] as usize } pub fn get_stack_pointer(&self) -> usize { - self.context.uc_mcontext.gregs[REG_RSP as usize] as usize + self.inner.context.uc_mcontext.gregs[REG_RSP as usize] as usize } pub fn fill_cpu_context(&self, out: &mut RawContextCPU) { out.context_flags = format::ContextFlagsAmd64::CONTEXT_AMD64_FULL.bits(); { - let gregs = &self.context.uc_mcontext.gregs; + let gregs = &self.inner.context.uc_mcontext.gregs; out.cs = (gregs[REG_CSGSFS as usize] & 0xffff) as u16; out.fs = ((gregs[REG_CSGSFS as usize] >> 32) & 0xffff) as u16; @@ -51,7 +51,7 @@ impl CrashContext { } { - let fs = &self.float_state; + let fs = &self.inner.float_state; let mut float_save = format::XMM_SAVE_AREA32 { control_word: fs.cwd, diff --git a/src/linux/dumper_cpu_info/arm.rs b/src/linux/dumper_cpu_info/arm.rs index b5f33b01..3f014484 100644 --- a/src/linux/dumper_cpu_info/arm.rs +++ b/src/linux/dumper_cpu_info/arm.rs @@ -1,4 +1,5 @@ use crate::{errors::CpuInfoError, minidump_format::*}; +use scroll::Pwrite; use std::{ collections::HashSet, fs::File, @@ -26,7 +27,7 @@ pub fn parse_cpus_from_sysfile(file: &mut File) -> Result> { continue; } let cores: std::result::Result, _> = - items.split("-").map(|x| x.parse::()).collect(); + items.split('-').map(|x| x.parse::()).collect(); let cores = cores?; match cores.as_slice() { [x] => { @@ -63,30 +64,22 @@ impl CpuInfoEntry { } } -struct CpuFeaturesEntry { - tag: &'static str, - hwcaps: u32, -} - -impl CpuFeaturesEntry { - fn new(tag: &'static str, hwcaps: u32) -> Self { - CpuFeaturesEntry { tag, hwcaps } +/// Retrieves the hardware capabilities from the 'Features' field. +#[cfg(target_arch = "arm")] +fn parse_features(val: &str) -> u32 { + struct CpuFeaturesEntry { + tag: &'static str, + hwcaps: u32, } -} -pub fn write_cpu_information(sys_info: &mut MDRawSystemInfo) -> Result<()> { - // The CPUID value is broken up in several entries in /proc/cpuinfo. - // This table is used to rebuild it from the entries. - let cpu_id_entries = [ - CpuInfoEntry::new("CPU implementer", 'x', 24, 8), - CpuInfoEntry::new("CPU variant", 'x', 20, 4), - CpuInfoEntry::new("CPU part", 'x', 4, 12), - CpuInfoEntry::new("CPU revision", 'd', 0, 4), - ]; + impl CpuFeaturesEntry { + fn new(tag: &'static str, hwcaps: u32) -> Self { + CpuFeaturesEntry { tag, hwcaps } + } + } // The ELF hwcaps are listed in the "Features" entry as textual tags. // This table is used to rebuild them. - #[cfg(target_arch = "arm")] let cpu_features_entries = [ CpuFeaturesEntry::new("swp", MDCPUInformationARMElfHwCaps::HWCAP_SWP), CpuFeaturesEntry::new("half", MDCPUInformationARMElfHwCaps::HWCAP_HALF), @@ -110,6 +103,36 @@ pub fn write_cpu_information(sys_info: &mut MDRawSystemInfo) -> Result<()> { CpuFeaturesEntry::new("idiv", HWCAP_IDIV), ]; + let mut ehwc = 0; + // Parse each space-separated tag. + for tag in val.split_whitespace() { + for entry in &cpu_features_entries { + if entry.tag == tag { + ehwc |= entry.hwcaps; + break; + } + } + } + + ehwc +} + +/// Stub for aarch64, always 0 +#[cfg(target_arch = "aarch64")] +fn parse_features(_val: &str) -> u32 { + 0 +} + +pub fn write_cpu_information(sys_info: &mut MDRawSystemInfo) -> Result<()> { + // The CPUID value is broken up in several entries in /proc/cpuinfo. + // This table is used to rebuild it from the entries. + let cpu_id_entries = [ + CpuInfoEntry::new("CPU implementer", 'x', 24, 8), + CpuInfoEntry::new("CPU variant", 'x', 20, 4), + CpuInfoEntry::new("CPU part", 'x', 4, 12), + CpuInfoEntry::new("CPU revision", 'd', 0, 4), + ]; + // processor_architecture should always be set, do this first if cfg!(target_arch = "aarch64") { sys_info.processor_architecture = @@ -162,6 +185,7 @@ pub fn write_cpu_information(sys_info: &mut MDRawSystemInfo) -> Result<()> { }; let mut cpuid = 0; + let mut elf_hwcaps = 0; for line in BufReader::new(cpuinfo_file).lines() { let line = line?; @@ -174,33 +198,30 @@ pub fn write_cpu_information(sys_info: &mut MDRawSystemInfo) -> Result<()> { continue; } - let split: Vec<_> = line.split(":").map(|x| x.trim()).collect(); - let field = split[0]; - let value = split.get(1); // Option, might be missing - for entry in &cpu_id_entries { - if value.is_none() { - break; - } - if field != entry.field { - continue; - } - let mut result; - let val = value.unwrap(); - - let rr = if val.starts_with("0x") || entry.format == 'x' { - usize::from_str_radix(val.trim_start_matches("0x"), 16) - } else { - usize::from_str_radix(val, 10) - }; - result = match rr { - Ok(x) => x, - Err(_) => { + let (field, value) = if let Some(ind) = line.find(':') { + (&line[..ind], Some(&line[ind + 1..])) + } else { + (line.as_str(), None) + }; + + if let Some(val) = value { + for entry in &cpu_id_entries { + if field != entry.field { continue; } - }; - result &= (1 << entry.bit_length) - 1; - result <<= entry.bit_lshift; - cpuid |= result as u32; + + let rr = if val.starts_with("0x") || entry.format == 'x' { + usize::from_str_radix(val.trim_start_matches("0x"), 16) + } else { + val.parse() + }; + + if let Ok(mut result) = rr { + result &= (1 << entry.bit_length) - 1; + result <<= entry.bit_lshift; + cpuid |= result as u32; + } + } } if cfg!(target_arch = "arm") { @@ -235,51 +256,35 @@ pub fn write_cpu_information(sys_info: &mut MDRawSystemInfo) -> Result<()> { } } - let elf_hwcaps = { - let mut elf_hwcaps = 0; - #[cfg(target_arch = "arm")] - { - // Rebuild the ELF hwcaps from the 'Features' field. - if field == "Features" { - if let Some(val) = value { - // Parse each space-separated tag. - for tag in val.split_whitespace() { - for entry in &cpu_features_entries { - if entry.tag == tag { - elf_hwcaps |= entry.hwcaps; - break; - } - } - } - } - } + // Rebuild the ELF hwcaps from the 'Features' field. + if field == "Features" { + if let Some(val) = value { + elf_hwcaps = parse_features(val); } + } + } - elf_hwcaps - }; + // The sys_info.cpu field is just a byte array, but in arm's case it is + // actually + // minidump_common::format::ARMCpuInfo { + // pub cpuid: u32, + // pub elf_hwcaps: u32, + // } + sys_info + .cpu + .data + .pwrite_with(cpuid, 0, scroll::Endian::Little) + .expect("impossible"); + sys_info + .cpu + .data + .pwrite_with( + elf_hwcaps, + std::mem::size_of::(), + scroll::Endian::Little, + ) + .expect("impossible"); - // The sys_info.cpu field is just a byte array, but in arm's case it is - // actually - // minidump_common::format::ARMCpuInfo { - // pub cpuid: u32, - // pub elf_hwcaps: u32, - // } - use scroll::Pwrite; - sys_info - .cpu - .data - .pwrite_with(cpuid, 0, scroll::Endian::Little) - .expect("impossible"); - sys_info - .cpu - .data - .pwrite_with( - elf_hwcaps, - std::mem::size_of::(), - scroll::Endian::Little, - ) - .expect("impossible"); - } Ok(()) } @@ -310,28 +315,28 @@ mod tests { fn test_one_cpu() { let mut file = new_file("10"); let set = parse_cpus_from_sysfile(&mut file).expect("Failed to file"); - assert_eq!(set, [10,].iter().map(|x| *x).collect()); + assert_eq!(set, [10,].iter().copied().collect()); } #[test] fn test_one_cpu_newline() { let mut file = new_file("10\n"); let set = parse_cpus_from_sysfile(&mut file).expect("Failed to file"); - assert_eq!(set, [10,].iter().map(|x| *x).collect()); + assert_eq!(set, [10,].iter().copied().collect()); } #[test] fn test_two_cpus() { let mut file = new_file("1,10\n"); let set = parse_cpus_from_sysfile(&mut file).expect("Failed to file"); - assert_eq!(set, [1, 10].iter().map(|x| *x).collect()); + assert_eq!(set, [1, 10].iter().copied().collect()); } #[test] fn test_two_cpus_with_range() { let mut file = new_file("1-2\n"); let set = parse_cpus_from_sysfile(&mut file).expect("Failed to file"); - assert_eq!(set, [1, 2].iter().map(|x| *x).collect()); + assert_eq!(set, [1, 2].iter().copied().collect()); } #[test] @@ -345,7 +350,7 @@ mod tests { fn test_multiple_items() { let mut file = new_file("0, 2-4, 128\n"); let set = parse_cpus_from_sysfile(&mut file).expect("Failed to file"); - assert_eq!(set, [0, 2, 3, 4, 128].iter().map(|x| *x).collect()); + assert_eq!(set, [0, 2, 3, 4, 128].iter().copied().collect()); } #[test] @@ -358,7 +363,7 @@ mod tests { let set2 = parse_cpus_from_sysfile(&mut file2).expect("Failed to file"); assert_eq!(set2, (16..=24).collect()); - set1 = set1.intersection(&set2).map(|x| *x).collect(); + set1 = set1.intersection(&set2).copied().collect(); assert_eq!(set1, (16..=19).collect()); } @@ -366,14 +371,14 @@ mod tests { fn test_intersects_with_discontinuous() { let mut file1 = new_file("0, 2-4, 7, 10\n"); let mut set1 = parse_cpus_from_sysfile(&mut file1).expect("Failed to file"); - assert_eq!(set1, [0, 2, 3, 4, 7, 10].iter().map(|x| *x).collect()); + assert_eq!(set1, [0, 2, 3, 4, 7, 10].iter().copied().collect()); let mut file2 = new_file("0-2, 5, 8-10\n"); let set2 = parse_cpus_from_sysfile(&mut file2).expect("Failed to file"); - assert_eq!(set2, [0, 1, 2, 5, 8, 9, 10].iter().map(|x| *x).collect()); + assert_eq!(set2, [0, 1, 2, 5, 8, 9, 10].iter().copied().collect()); - set1 = set1.intersection(&set2).map(|x| *x).collect(); - assert_eq!(set1, [0, 2, 10].iter().map(|x| *x).collect()); + set1 = set1.intersection(&set2).copied().collect(); + assert_eq!(set1, [0, 2, 10].iter().copied().collect()); } #[test] diff --git a/src/linux/sections/exception_stream.rs b/src/linux/sections/exception_stream.rs index 8d2a7fd3..45da0284 100644 --- a/src/linux/sections/exception_stream.rs +++ b/src/linux/sections/exception_stream.rs @@ -66,11 +66,11 @@ pub fn write( } #[cfg(not(target_arch = "arm"))] { - sig_addr = unsafe { context.siginfo.si_addr() } as u64; + sig_addr = context.inner.siginfo.ssi_addr as u64; } MDException { - exception_code: context.siginfo.si_signo as u32, - exception_flags: context.siginfo.si_code as u32, + exception_code: context.inner.siginfo.ssi_signo as u32, + exception_flags: context.inner.siginfo.ssi_code as u32, exception_record: 0, exception_address: sig_addr, number_parameters: 0, diff --git a/src/linux/thread_info/x86.rs b/src/linux/thread_info/x86.rs index 82652700..9ede4f44 100644 --- a/src/linux/thread_info/x86.rs +++ b/src/linux/thread_info/x86.rs @@ -248,7 +248,6 @@ impl ThreadInfoX86 { out.float_save.data_offset = self.fpregs.foo as u32; out.float_save.data_selector = self.fpregs.fos as u32; - use scroll::Pwrite; { let ra = &mut out.float_save.register_area; // 8 registers * 10 bytes per register. diff --git a/tests/minidump_writer.rs b/tests/minidump_writer.rs index 2daf998b..27c56f9e 100644 --- a/tests/minidump_writer.rs +++ b/tests/minidump_writer.rs @@ -2,8 +2,6 @@ use minidump::*; use minidump_common::format::{GUID, MINIDUMP_STREAM_TYPE::*}; -#[cfg(not(target_arch = "arm"))] -use minidump_writer::crash_context::fpstate_t; use minidump_writer::{ app_memory::AppMemory, crash_context::CrashContext, @@ -16,10 +14,11 @@ use minidump_writer::{ use nix::{errno::Errno, sys::signal::Signal}; use std::collections::HashSet; -use std::io::{BufRead, BufReader}; -use std::os::unix::process::ExitStatusExt; -use std::process::{Command, Stdio}; -use std::str::FromStr; +use std::{ + io::{BufRead, BufReader}, + os::unix::process::ExitStatusExt, + process::{Command, Stdio}, +}; mod common; use common::*; @@ -31,23 +30,28 @@ enum Context { } #[cfg(not(any(target_arch = "mips", target_arch = "arm")))] -fn get_ucontext() -> Result { - let mut context = std::mem::MaybeUninit::::uninit(); - let res = unsafe { libc::getcontext(context.as_mut_ptr()) }; - Errno::result(res)?; - unsafe { Ok(context.assume_init()) } +fn get_ucontext() -> Result { + let mut context = std::mem::MaybeUninit::uninit(); + unsafe { + let res = crash_context::crash_context_getcontext(context.as_mut_ptr()); + Errno::result(res)?; + + Ok(context.assume_init()) + } } #[cfg(not(any(target_arch = "mips", target_arch = "arm")))] fn get_crash_context(tid: Pid) -> CrashContext { - let siginfo: libc::siginfo_t = unsafe { std::mem::zeroed() }; + let siginfo: libc::signalfd_siginfo = unsafe { std::mem::zeroed() }; let context = get_ucontext().expect("Failed to get ucontext"); - let float_state: fpstate_t = unsafe { std::mem::zeroed() }; + let float_state = unsafe { std::mem::zeroed() }; CrashContext { - siginfo, - tid, - context, - float_state, + inner: crash_context::CrashContext { + siginfo, + tid, + context, + float_state, + }, } } @@ -108,8 +112,16 @@ fn test_write_and_read_dump_from_parent_helper(context: Context) { .read_line(&mut buf) .expect("Couldn't read address provided by child"); let mut output = buf.split_whitespace(); - let mmap_addr = usize::from_str(output.next().unwrap()).expect("unable to parse mmap_addr"); - let memory_size = usize::from_str(output.next().unwrap()).expect("unable to parse memory_size"); + let mmap_addr = output + .next() + .unwrap() + .parse() + .expect("unable to parse mmap_addr"); + let memory_size = output + .next() + .unwrap() + .parse() + .expect("unable to parse memory_size"); // Add information about the mapped memory. let mapping = MappingInfo { start_address: mmap_addr, @@ -219,7 +231,11 @@ fn test_write_with_additional_memory_helper(context: Context) { let mut output = buf.split_whitespace(); let memory_addr = usize::from_str_radix(output.next().unwrap().trim_start_matches("0x"), 16) .expect("unable to parse mmap_addr"); - let memory_size = usize::from_str(output.next().unwrap()).expect("unable to parse memory_size"); + let memory_size = output + .next() + .unwrap() + .parse() + .expect("unable to parse memory_size"); let app_memory = AppMemory { ptr: memory_addr, @@ -627,7 +643,11 @@ fn test_write_early_abort_helper(context: Context) { let _ = usize::from_str_radix(output.next().unwrap().trim_start_matches("0x"), 16) .expect("unable to parse mmap_addr"); let memory_addr = 0; - let memory_size = usize::from_str(output.next().unwrap()).expect("unable to parse memory_size"); + let memory_size = output + .next() + .unwrap() + .parse() + .expect("unable to parse memory_size"); let app_memory = AppMemory { ptr: memory_addr,