From 65848bfe290d2234e9195e411996596798832e58 Mon Sep 17 00:00:00 2001 From: FredApps <153173854+FredApps@users.noreply.github.com> Date: Mon, 16 Nov 2026 11:47:05 +0100 Subject: [PATCH] Add craft-macho: Mach-O slice tables and header names from Craft Anything Moves the header pieces of Craft Anything's crates/formats/src/macho.rs into a pure-Rust crate: fat_slices (fat and fat64), FatSlice, cpu_name, load_command_name, load_command_min_size, nibble_version and unixthread_pc. The load command walker, symbols, stubs and Objective-C metadata stay in the app. Part of #778. Co-authored-by: Afloat Co-authored-by: BFlat Co-authored-by: Brandon Thomas Co-authored-by: Cr <60964294+Chr0mium24@users.noreply.github.com> Co-authored-by: GGWA <65288322+rech4210@users.noreply.github.com> --- Cargo.lock | 9 ++ Cargo.toml | 1 + README.md | 1 + crates/macho/Cargo.toml | 22 ++++ crates/macho/src/bytes.rs | 39 +++++++ crates/macho/src/lib.rs | 192 ++++++++++++++++++++++++++++++++++ crates/macho/src/tests.rs | 213 ++++++++++++++++++++++++++++++++++++++ 7 files changed, 477 insertions(+) create mode 100644 crates/macho/Cargo.toml create mode 100644 crates/macho/src/bytes.rs create mode 100644 crates/macho/src/lib.rs create mode 100644 crates/macho/src/tests.rs diff --git a/Cargo.lock b/Cargo.lock index 480e000e5..8d0c9f2c9 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -2100,6 +2100,15 @@ dependencies = [ "thiserror 2.0.21", ] +[[package]] +name = "craft-macho" +version = "0.1.0" +dependencies = [ + "serde", + "serde_json", + "thiserror 2.0.21", +] + [[package]] name = "craft-markdown" version = "0.1.0" diff --git a/Cargo.toml b/Cargo.toml index bd08fa725..0176a86e0 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -174,6 +174,7 @@ craft-xcf = { path = "crates/xcf" } craft-xml = { path = "crates/xml" } craft-zip = { path = "crates/zip" } craft-y4m = { path = "crates/y4m" } +craft-macho = { path = "crates/macho" } craft-epub = { path = "crates/epub" } craft-ews = { path = "crates/ews" } craft-video = { path = "crates/video" } diff --git a/README.md b/README.md index 8150dfea9..48b989df3 100644 --- a/README.md +++ b/README.md @@ -386,6 +386,7 @@ See the [release notes](CHANGELOG.md) for included functionality and known limit text-format crates read into and write from. WordCraft's model without its editing code. - [`craft-xlsx`](crates/xlsx/README.md): Excel workbooks (`.xlsx`, `.xlsm`, SpreadsheetML, transitional and strict) and binary workbooks (`.xlsb`) on `craft-opc`: the workbook part, shared strings, the styles tables and worksheet rows streamed one at a time, with limits on the package, the XML and the binary records. - [`craft-ora`](crates/ora/README.md): OpenRaster documents (`.ora`): the ZIP archive and the `stack.xml` layer tree as written, read with bounded sizes and written. From PhotoCraft. +- [`craft-macho`](crates/macho/src/lib.rs): Mach-O header pieces from untrusted bytes, from Craft Anything: universal (fat and fat64) slice tables checked against the file, CPU and load command names, the fixed size each load command needs before its fields are read, and the thread-state program counter. - [`craft-y4m`](crates/y4m/src/lib.rs): YUV4MPEG2 (`.y4m`) reader, from FilmCraft: the stream header, colour space layouts at 8 to 16 bits, a frame index built from the `FRAME` lines without loading the file, and plane access. Bounded on hostile input. diff --git a/crates/macho/Cargo.toml b/crates/macho/Cargo.toml new file mode 100644 index 000000000..8fed852ce --- /dev/null +++ b/crates/macho/Cargo.toml @@ -0,0 +1,22 @@ +[package] +name = "craft-macho" +description = "Mach-O header pieces from hostile bytes, from Craft Anything: universal (fat and fat64) slice tables, CPU and load command names, load command minimum sizes and the thread-state program counter. Pure Rust, no I/O." +version.workspace = true +edition.workspace = true +license.workspace = true +rust-version.workspace = true +repository.workspace = true + +[lints] +workspace = true + +[dependencies] +thiserror = { workspace = true } +# `serde`: `Serialize` on `FatSlice`, for apps that report slice tables as JSON. +serde = { workspace = true, optional = true } + +[features] +serde = ["dep:serde"] + +[dev-dependencies] +serde_json = { workspace = true } diff --git a/crates/macho/src/bytes.rs b/crates/macho/src/bytes.rs new file mode 100644 index 000000000..bfe0d9f81 --- /dev/null +++ b/crates/macho/src/bytes.rs @@ -0,0 +1,39 @@ +//! Bounds-checked fixed-width reads in either byte order: out of range is `None`. + +#[derive(Debug, Clone, Copy)] +pub(crate) struct Reader<'a> { + bytes: &'a [u8], +} + +impl<'a> Reader<'a> { + pub(crate) fn new(bytes: &'a [u8]) -> Self { + Self { bytes } + } + + /// `len` bytes starting at `at`. + pub(crate) fn slice(&self, at: usize, len: usize) -> Option<&'a [u8]> { + let end = at.checked_add(len)?; + self.bytes.get(at..end) + } + + fn word(&self, at: usize) -> Option<[u8; N]> { + let (word, _) = self.bytes.get(at..)?.split_first_chunk::()?; + Some(*word) + } + + pub(crate) fn u32_le(&self, at: usize) -> Option { + self.word(at).map(u32::from_le_bytes) + } + + pub(crate) fn u64_le(&self, at: usize) -> Option { + self.word(at).map(u64::from_le_bytes) + } + + pub(crate) fn u32_be(&self, at: usize) -> Option { + self.word(at).map(u32::from_be_bytes) + } + + pub(crate) fn u64_be(&self, at: usize) -> Option { + self.word(at).map(u64::from_be_bytes) + } +} diff --git a/crates/macho/src/lib.rs b/crates/macho/src/lib.rs new file mode 100644 index 000000000..ed146d5e7 --- /dev/null +++ b/crates/macho/src/lib.rs @@ -0,0 +1,192 @@ +#![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)] +#![forbid(unsafe_code)] + +//! Mach-O header pieces from untrusted bytes: universal (fat and fat64) slice tables +//! ([`fat_slices`]), CPU and load command names, the fixed size each known load command needs +//! before its fields can be read, and the program counter in a thread command. +//! +//! From Craft Anything (`crates/formats/src/macho.rs`), where the load command walker, symbol, +//! stub and Objective-C code built on these stays. With the `serde` feature, [`FatSlice`] is +//! `Serialize`. + +mod bytes; + +use crate::bytes::Reader; + +/// Slices allowed in a universal binary's table. +pub const MAX_FAT_SLICES: usize = 64; + +/// Thread-state records walked in one thread command. +pub const MAX_THREAD_STATES: usize = 4096; + +/// Why [`fat_slices`] gave up. +#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)] +pub enum MachoError { + /// The header or a slice ends before the file does. + #[error("the file ends early ({0})")] + Truncated(String), + /// Not a universal binary, or an implausible slice count. + #[error("the file is malformed ({0})")] + Malformed(String), +} + +/// One architecture in a universal binary's slice table. +#[derive(Debug, Clone, PartialEq, Eq)] +#[cfg_attr(feature = "serde", derive(serde::Serialize))] +pub struct FatSlice { + /// [`cpu_name`] of the slice's CPU type and subtype. + pub arch: String, + pub cputype: u32, + pub cpusubtype: u32, + /// File offset of the thin image. + pub offset: u64, + pub size: u64, + /// Alignment as a power of two. + pub align: u32, +} + +/// A CPU type and subtype as the name `lipo` and `-arch` use (`x86_64h`, `arm64e`…), or +/// `cpu0x…` for others. +pub fn cpu_name(cputype: u32, sub: u32) -> String { + match cputype { + 7 => "i386".into(), + 0x0100_0007 if sub & 0x00ff_ffff == 8 => "x86_64h".into(), + 0x0100_0007 => "x86_64".into(), + 12 => "arm".into(), + 0x0100_000c => { + if sub & 0xff == 2 { + "arm64e".into() + } else { + "arm64".into() + } + } + 0x0200_000c => "arm64_32".into(), + 18 => "ppc".into(), + 0x0100_0012 => "ppc64".into(), + other => format!("cpu{other:#x}"), + } +} + +/// The slices of a universal (fat, or fat64 with magic `0xcafebabf`) binary. Every slice must +/// lie inside `data`. More than [`MAX_FAT_SLICES`] slices is refused: Java class files share the +/// magic and carry their version there. +pub fn fat_slices(data: &[u8]) -> Result, MachoError> { + let r = Reader::new(data); + let magic = r.u32_be(0).ok_or_else(|| MachoError::Truncated("fat header".into()))?; + let wide = match magic { + 0xcafe_babe => false, + 0xcafe_babf => true, + _ => return Err(MachoError::Malformed("not a universal binary".into())), + }; + let n = r.u32_be(4).ok_or_else(|| MachoError::Truncated("fat header".into()))? as usize; + if n == 0 || n > MAX_FAT_SLICES { + return Err(MachoError::Malformed(format!("{n} slices (Java class files share this magic)"))); + } + let mut out = Vec::new(); + for i in 0..n { + let s = if wide { + let o = 8 + i * 32; + (r.u32_be(o), r.u32_be(o + 4), r.u64_be(o + 8), r.u64_be(o + 16), r.u32_be(o + 24)) + } else { + let o = 8 + i * 20; + (r.u32_be(o), r.u32_be(o + 4), r.u32_be(o + 8).map(u64::from), r.u32_be(o + 12).map(u64::from), r.u32_be(o + 16)) + }; + let (Some(cpu), Some(sub), Some(offset), Some(size), Some(align)) = s else { + return Err(MachoError::Truncated("fat arch table".into())); + }; + if offset.checked_add(size).is_none_or(|end| end > data.len() as u64) { + return Err(MachoError::Truncated(format!("slice {i} runs past the end of the file"))); + } + out.push(FatSlice { arch: cpu_name(cpu, sub), cputype: cpu, cpusubtype: sub, offset, size, align }); + } + Ok(out) +} + +/// A load command's `LC_` name, or its number in hex for ones not listed. +pub fn load_command_name(cmd: u32) -> String { + match cmd { + 0x1 => "LC_SEGMENT", + 0x2 => "LC_SYMTAB", + 0x5 => "LC_UNIXTHREAD", + 0xb => "LC_DYSYMTAB", + 0xc => "LC_LOAD_DYLIB", + 0xd => "LC_ID_DYLIB", + 0xe => "LC_LOAD_DYLINKER", + 0x19 => "LC_SEGMENT_64", + 0x1b => "LC_UUID", + 0x1d => "LC_CODE_SIGNATURE", + 0x1e => "LC_SEGMENT_SPLIT_INFO", + 0x20 => "LC_LAZY_LOAD_DYLIB", + 0x21 => "LC_ENCRYPTION_INFO", + 0x22 => "LC_DYLD_INFO", + 0x8000_0022 => "LC_DYLD_INFO_ONLY", + 0x24 => "LC_VERSION_MIN_MACOSX", + 0x25 => "LC_VERSION_MIN_IPHONEOS", + 0x26 => "LC_FUNCTION_STARTS", + 0x29 => "LC_DATA_IN_CODE", + 0x2a => "LC_SOURCE_VERSION", + 0x2c => "LC_ENCRYPTION_INFO_64", + 0x32 => "LC_BUILD_VERSION", + 0x8000_0018 => "LC_LOAD_WEAK_DYLIB", + 0x8000_001c => "LC_RPATH", + 0x8000_001f => "LC_REEXPORT_DYLIB", + 0x8000_0028 => "LC_MAIN", + 0x8000_0033 => "LC_DYLD_EXPORTS_TRIE", + 0x8000_0034 => "LC_DYLD_CHAINED_FIXUPS", + other => return format!("{other:#x}"), + } + .into() +} + +/// Fixed bytes required before decoding a known load command's fields (8, the command header, +/// for unknown ones). +pub fn load_command_min_size(cmd: u32) -> usize { + match cmd { + 0x1 => 56, + 0x2 | 0x1b | 0x2c | 0x32 | 0x8000_0028 => 24, + 0x5 => 16, + 0xb => 80, + 0xc | 0xd | 0x20 | 0x8000_0018 | 0x8000_001f | 0x8000_0023 => 24, + 0xe | 0xf | 0x12 | 0x13 | 0x14 | 0x15 | 0x27 | 0x8000_001c => 12, + 0x19 => 72, + 0x1d | 0x1e | 0x24 | 0x25 | 0x26 | 0x29 | 0x2a | 0x2b | 0x2e | 0x2f | 0x30 | 0x8000_0033 | 0x8000_0034 => 16, + 0x21 => 20, + 0x22 | 0x8000_0022 => 48, + _ => 8, + } +} + +/// An `X.Y.Z` version packed as `xxxx.yy.zz` nibbles (`LC_VERSION_MIN_*`, `LC_BUILD_VERSION`). +pub fn nibble_version(v: u32) -> String { + format!("{}.{}.{}", v >> 16, (v >> 8) & 0xff, v & 0xff) +} + +/// The program counter in an `LC_UNIXTHREAD` / `LC_THREAD` body (the bytes after its 8-byte +/// command header): the first complete x86_64 (flavor 4), arm64 (flavor 6) or i386 (flavor 1) +/// thread state for `cpu`. A command can carry several flavor/count/state records; counts are +/// 32-bit words. At most [`MAX_THREAD_STATES`] records are walked. +pub fn unixthread_pc(data: &[u8], cpu: u32, is64: bool) -> Option { + let r = Reader::new(data); + let mut pos = 0usize; + for _ in 0..MAX_THREAD_STATES { + let flavor = r.u32_le(pos)?; + let count = r.u32_le(pos.checked_add(4)?)?; + let state = pos.checked_add(8)?; + let size = usize::try_from(count).ok()?.checked_mul(4)?; + let record = Reader::new(r.slice(state, size)?); + let pc = match (cpu, is64, flavor) { + (0x0100_0007, true, 4) if count >= 42 => record.u64_le(16 * 8), + (0x0100_000c, true, 6) if count >= 68 => record.u64_le(32 * 8), + (7, false, 1) if count >= 16 => record.u32_le(10 * 4).map(u64::from), + _ => None, + }; + if pc.is_some() { + return pc; + } + pos = state.checked_add(size)?; + } + None +} + +#[cfg(test)] +mod tests; diff --git a/crates/macho/src/tests.rs b/crates/macho/src/tests.rs new file mode 100644 index 000000000..4f3b403dd --- /dev/null +++ b/crates/macho/src/tests.rs @@ -0,0 +1,213 @@ +//! Slice table, name and thread-state tests. The thread-state cases are Craft Anything's +//! `macho_thread_state` integration test, called on the command body directly instead of +//! through the app's program model. + +use super::*; + +const X86_64: u32 = 0x0100_0007; +const ARM64: u32 = 0x0100_000c; + +/// A universal binary with `slices` of (cputype, cpusubtype, body), each at a 0x100 boundary. +fn fat(wide: bool, slices: &[(u32, u32, &[u8])]) -> Vec { + let entry = if wide { 32 } else { 20 }; + let mut d = vec![0u8; 0x100]; + d[0..4].copy_from_slice(&(if wide { 0xcafe_babfu32 } else { 0xcafe_babe }).to_be_bytes()); + d[4..8].copy_from_slice(&(slices.len() as u32).to_be_bytes()); + for (i, &(cpu, sub, body)) in slices.iter().enumerate() { + let offset = d.len(); + let o = 8 + i * entry; + d[o..o + 4].copy_from_slice(&cpu.to_be_bytes()); + d[o + 4..o + 8].copy_from_slice(&sub.to_be_bytes()); + if wide { + d[o + 8..o + 16].copy_from_slice(&(offset as u64).to_be_bytes()); + d[o + 16..o + 24].copy_from_slice(&(body.len() as u64).to_be_bytes()); + d[o + 24..o + 28].copy_from_slice(&8u32.to_be_bytes()); + } else { + d[o + 8..o + 12].copy_from_slice(&(offset as u32).to_be_bytes()); + d[o + 12..o + 16].copy_from_slice(&(body.len() as u32).to_be_bytes()); + d[o + 16..o + 20].copy_from_slice(&8u32.to_be_bytes()); + } + d.extend_from_slice(body); + d.resize(d.len().next_multiple_of(0x100), 0); + } + d +} + +#[test] +fn fat_and_fat64_tables_list_their_slices() { + for wide in [false, true] { + let d = fat(wide, &[(X86_64, 3, &[1; 16]), (ARM64, 2, &[2; 32])]); + let s = fat_slices(&d).unwrap(); + assert_eq!(s.len(), 2, "wide={wide}"); + assert_eq!(s[0], FatSlice { arch: "x86_64".into(), cputype: X86_64, cpusubtype: 3, offset: 0x100, size: 16, align: 8 }); + assert_eq!((s[1].arch.as_str(), s[1].offset, s[1].size), ("arm64e", 0x200, 32)); + } +} + +#[test] +fn damaged_tables_are_errors() { + assert_eq!(fat_slices(b"\xca\xfe"), Err(MachoError::Truncated("fat header".into()))); + assert_eq!(fat_slices(&[0xfe, 0xed, 0xfa, 0xcf, 0, 0, 0, 1]), Err(MachoError::Malformed("not a universal binary".into()))); + assert_eq!(fat_slices(&[0xca, 0xfe, 0xba, 0xbe]), Err(MachoError::Truncated("fat header".into()))); + // A Java 21 class file: minor 0, major 65. + let java = [0xca, 0xfe, 0xba, 0xbe, 0, 0, 0, 65]; + assert_eq!(fat_slices(&java).unwrap_err().to_string(), "the file is malformed (65 slices (Java class files share this magic))"); + assert!(matches!(fat_slices(&[0xca, 0xfe, 0xba, 0xbe, 0, 0, 0, 0]), Err(MachoError::Malformed(_)))); + let d = fat(false, &[(X86_64, 3, &[1; 16])]); + assert_eq!(fat_slices(&d[..20]), Err(MachoError::Truncated("fat arch table".into()))); + assert_eq!(fat_slices(&d[..0x108]), Err(MachoError::Truncated("slice 0 runs past the end of the file".into()))); + let mut wrap = fat(true, &[(X86_64, 3, &[1; 16])]); + wrap[16..24].copy_from_slice(&u64::MAX.to_be_bytes()); + assert!(matches!(fat_slices(&wrap), Err(MachoError::Truncated(_))), "offset + size must not wrap"); +} + +#[test] +fn cpu_names() { + let names: Vec = [ + (7, 3), + (X86_64, 3), + (X86_64, 8), + (X86_64, 0x8000_0008), + (X86_64, 0x108), + (12, 9), + (ARM64, 0), + (ARM64, 0x8000_0002), + (0x0200_000c, 1), + (18, 0), + (0x0100_0012, 0), + (0x99, 0), + ] + .into_iter() + .map(|(cpu, sub)| cpu_name(cpu, sub)) + .collect(); + assert_eq!(names, ["i386", "x86_64", "x86_64h", "x86_64h", "x86_64", "arm", "arm64", "arm64e", "arm64_32", "ppc", "ppc64", "cpu0x99"]); +} + +#[test] +fn load_command_names_and_sizes() { + let known = [ + (0x1, "LC_SEGMENT", 56), + (0x2, "LC_SYMTAB", 24), + (0x5, "LC_UNIXTHREAD", 16), + (0xb, "LC_DYSYMTAB", 80), + (0xc, "LC_LOAD_DYLIB", 24), + (0xd, "LC_ID_DYLIB", 24), + (0xe, "LC_LOAD_DYLINKER", 12), + (0x19, "LC_SEGMENT_64", 72), + (0x1b, "LC_UUID", 24), + (0x1d, "LC_CODE_SIGNATURE", 16), + (0x1e, "LC_SEGMENT_SPLIT_INFO", 16), + (0x20, "LC_LAZY_LOAD_DYLIB", 24), + (0x21, "LC_ENCRYPTION_INFO", 20), + (0x22, "LC_DYLD_INFO", 48), + (0x8000_0022, "LC_DYLD_INFO_ONLY", 48), + (0x24, "LC_VERSION_MIN_MACOSX", 16), + (0x25, "LC_VERSION_MIN_IPHONEOS", 16), + (0x26, "LC_FUNCTION_STARTS", 16), + (0x29, "LC_DATA_IN_CODE", 16), + (0x2a, "LC_SOURCE_VERSION", 16), + (0x2c, "LC_ENCRYPTION_INFO_64", 24), + (0x32, "LC_BUILD_VERSION", 24), + (0x8000_0018, "LC_LOAD_WEAK_DYLIB", 24), + (0x8000_001c, "LC_RPATH", 12), + (0x8000_001f, "LC_REEXPORT_DYLIB", 24), + (0x8000_0028, "LC_MAIN", 24), + (0x8000_0033, "LC_DYLD_EXPORTS_TRIE", 16), + (0x8000_0034, "LC_DYLD_CHAINED_FIXUPS", 16), + ]; + for (cmd, name, size) in known { + assert_eq!(load_command_name(cmd), name); + assert_eq!(load_command_min_size(cmd), size, "{name}"); + } + assert_eq!(load_command_name(0x8000_0023), "0x80000023"); + assert_eq!(load_command_min_size(0x8000_0023), 24); + assert_eq!(load_command_min_size(0x27), 12); + assert_eq!(load_command_min_size(0x2e), 16); + assert_eq!(load_command_min_size(0x77), 8); +} + +#[test] +fn nibble_versions() { + assert_eq!(nibble_version(0x000e_0500), "14.5.0"); + assert_eq!(nibble_version(0x000a_0f01), "10.15.1"); +} + +fn state(flavor: u32, count: u32, bytes: usize, pc_offset: usize, pc: u64, wide: bool) -> Vec { + let mut b = vec![0u8; 8 + bytes]; + b[0..4].copy_from_slice(&flavor.to_le_bytes()); + b[4..8].copy_from_slice(&count.to_le_bytes()); + if wide { + b[8 + pc_offset..16 + pc_offset].copy_from_slice(&pc.to_le_bytes()); + } else { + b[8 + pc_offset..12 + pc_offset].copy_from_slice(&(pc as u32).to_le_bytes()); + } + b +} + +fn decode(cpu: u32, wide: bool, states: &[Vec]) -> Option { + unixthread_pc(&states.concat(), cpu, wide) +} + +#[test] +fn a_program_counter_requires_a_complete_declared_state() { + for count in [0, 1, 34, 41] { + assert_eq!(decode(X86_64, true, &[state(4, count, 168, 128, 0x1234, true)]), None, "count {count}"); + } + assert_eq!(decode(X86_64, true, &[state(4, 42, 136, 128, 0x1234, true)]), None); + assert_eq!(decode(ARM64, true, &[state(6, 68, 264, 256, 0x1234, true)]), None); +} + +#[test] +fn flavor_numbers_are_interpreted_for_the_image_cpu() { + assert_eq!(decode(ARM64, true, &[state(4, 42, 168, 128, 0x1234, true)]), None); + assert_eq!(decode(X86_64, true, &[state(6, 68, 272, 256, 0x1234, true)]), None); + assert_eq!(decode(12, false, &[state(1, 17, 68, 40, 0x1234, false)]), None); +} + +#[test] +fn a_later_matching_state_is_reached_using_word_counts() { + let unknown = state(99, 2, 8, 0, 0, true); + let matching = state(4, 42, 168, 128, 0x1234, true); + assert_eq!(decode(X86_64, true, &[unknown, matching]), Some(0x1234)); +} + +#[test] +fn complete_supported_states_keep_their_program_counters() { + assert_eq!(decode(X86_64, true, &[state(4, 42, 168, 128, 0x1234, true)]), Some(0x1234)); + assert_eq!(decode(ARM64, true, &[state(6, 68, 272, 256, 0x1234, true)]), Some(0x1234)); + assert_eq!(decode(7, false, &[state(1, 16, 64, 40, 0x1234, false)]), Some(0x1234)); +} + +#[test] +fn endless_empty_states_stop() { + assert_eq!(unixthread_pc(&vec![0; 8 * (MAX_THREAD_STATES + 4)], X86_64, true), None); + assert_eq!(unixthread_pc(&[4, 0, 0, 0, 0xff, 0xff, 0xff, 0xff], X86_64, true), None); +} + +#[cfg(feature = "serde")] +#[test] +fn slices_serialize() { + let s = fat_slices(&fat(false, &[(ARM64, 0, &[0; 4])])).unwrap(); + let value = serde_json::to_value(&s[0]).unwrap(); + assert_eq!(value["arch"], "arm64"); + assert_eq!(value["offset"], 0x100); +} + +#[test] +fn damaged_input_never_panics() { + let sample = fat(true, &[(X86_64, 3, &[1; 16]), (ARM64, 2, &[2; 32])]); + let thread = state(4, 42, 168, 128, 0x1234, true); + for source in [&sample, &thread] { + for i in 0..source.len() { + let _ = fat_slices(&source[..i]); + let _ = unixthread_pc(&source[..i], X86_64, true); + for v in [0x00, 0x7f, 0xff] { + let mut m = source.clone(); + m[i] = v; + let _ = fat_slices(&m); + let _ = unixthread_pc(&m, ARM64, true); + let _ = unixthread_pc(&m, 7, false); + } + } + } +}