From ff8c279854733aea4a5806838f19a5e81a76cfa7 Mon Sep 17 00:00:00 2001 From: Davi Augusto Date: Tue, 17 Nov 2026 10:02:44 -0300 Subject: [PATCH 01/37] craft-raw: Sony ZV-E10 in-file distortion The ZV-E10 joins APSC_BODIES with the ILCE-6700's rule (11 knots over its own default crop's half diagonal / 10 = 360.56 px, the corrected- radius index, the frame-filling zoom, the 0.5 px APS-C fit gate) and its own distortion unit, 16384: the ILCE-6700's 15000 over-corrects its 16 mm photos by about 9 %. APS-C bodies now carry their unit. Measured on 4 photos with the E PZ 16-50 mm at 16-32 mm against the camera JPEG: p95 0.26-0.64 px at 1440 px as rendered (uncorrected up to 18.7 px; unit 15000 up to 2.18 px). Ported from storytold/lightcraft#3743, overtaken by the craft-raw cutover. --- .../docs/sony-ilce7rm6-lens-corrections.md | 35 ++++++++++-- crates/raw/src/arw_lens_rm6.rs | 54 +++++++++++++++---- 2 files changed, 76 insertions(+), 13 deletions(-) diff --git a/crates/raw/docs/sony-ilce7rm6-lens-corrections.md b/crates/raw/docs/sony-ilce7rm6-lens-corrections.md index 216fc4b63..8a87bdc3b 100644 --- a/crates/raw/docs/sony-ilce7rm6-lens-corrections.md +++ b/crates/raw/docs/sony-ilce7rm6-lens-corrections.md @@ -7,7 +7,7 @@ chromatic aberration (CA). LightCraft reads them and turns distortion into a DNG reaches the same **Optics ▸ Enable Lens Corrections** (`optics.lens_profile`) as a DNG's embedded warp and Panasonic's RW2 distortion data. Lateral CA is parsed and converts to the warp's red and blue planes, but it is **off by default**: applied after demosaic it made the render's CA worse (Verification). Vignetting is read but not applied (below). The -conversion is verified on the **ILCE-7RM6** and, for distortion, the **ILCE-6700** ([ILCE-6700](#ilce-6700)); the +conversion is verified on the **ILCE-7RM6** and, for distortion, the **ILCE-6700** ([ILCE-6700](#ilce-6700)) and the **ZV-E10** ([ZV-E10](#zv-e10)); the ILCE-7RM4A has its own conversion, with other conventions ([Two conventions](#two-conventions)), and other Sony bodies' tables give no correction until they are verified. @@ -105,7 +105,7 @@ the photo (portrait files are covered) and is carried by DNG export, as RW2's is ## Which bodies get it Only bodies on one of two allowlists in `arw_lens_rm6.rs` get an opcode: `FULL_FRAME_CROP` (today `ILCE-7RM6`, -9984 × 6656) and `APSC_BODIES` (today `ILCE-6700`, below). The unit and the knot spacing are verified per body; a body +9984 × 6656) and `APSC_BODIES` (today `ILCE-6700` and `ZV-E10`, below, each with its distortion unit). The unit and the knot spacing are verified per body; a body with another sensor size or another unit would be warped wrongly. Other bodies get no correction from this conversion; the ILCE-7RM4A gets its own, with other conventions (below). To add a body: collect photos of it shot with distortion correction on (several lenses and focal lengths), repeat the camera-JPEG registration below against the uncorrected @@ -113,7 +113,7 @@ render, confirm the unit, the knot spacing and the zoom rule (or measure the bod default crop to `FULL_FRAME_CROP`, or an APS-C body whose knots span its own crop (as measured for the ILCE-6700) to `APSC_BODIES`, with a test; an APS-C body also needs its fit gate checked against the camera JPEG (see *ILCE-6700*). -For bodies in `APSC_BODIES` (today `ILCE-6700`), the knots span the file's own default crop: spacing = its half +For bodies in `APSC_BODIES` (today `ILCE-6700` and `ZV-E10`), the knots span the file's own default crop: spacing = its half diagonal / (knot count − 1). This crop-based rule applies only to that list. The ILCE-7RM6 keeps its sensor-fixed 400 px in both modes; in full frame (16 knots) the crop-based rule gives the same 400 px, and in its APS-C mode (11 knots) it would give 392 px, which was only an alternative measurement there (it fits as well, above). @@ -166,6 +166,29 @@ As rendered (`lightcraft-cli render`, Enable Lens Corrections on): At 11.7 mm and longer an exception of this kind fits worse than the body's rule (412 px / 14500 on the grid: 0.73–1.19 px against 0.48–0.69 px), so it stops at 10.5 mm, the longest measured focal length where it helps; 10.6–11.6 mm is unmeasured and takes the body's rule. +## ZV-E10 + +The ZV-E10 (APS-C, 6000 × 4000 default crop at (12, 12) in 6048 × 4024 storage) writes 11-knot tables like the +ILCE-6700, zero-padded to the same 17 values. Measured as above on 4 photos shot with distortion correction Auto (the +E PZ 16-50 mm F3.5-5.6 OSS, which forces it; its owner's photos, only the summary numbers here): 2 at 16 mm, 1 at 29 mm +(portrait) and 1 at 32 mm. Feature matches between the uncorrected render and the camera JPEG +(LightCraft's `tools/sony_distortion_check.py`, SIFT agreement after the best similarity), the camera's map applied to the render's +points in a scan of knot spacing 340–380 px and unit 15000–17800: + +| | p95 residual at 1440 px | +|---|---| +| Uncorrected | 2.7–18.7 px (16 mm: 18.6–18.7 px) | +| The ILCE-6700's rule (half diagonal / 10 = 360.56 px, unit 15000), as rendered | 0.45–2.18 px: the 16 mm photos over-corrected by about 9 % | +| Sensor-fixed 400 px, unit 16384 | 0.43–3.21 px | +| **Half diagonal / 10 = 360.56 px, unit 16384** (exact table) | **0.27–0.61 px** | +| The same as LightCraft renders it (`lightcraft-cli render`, Enable Lens Corrections on, fitted polynomial) | **0.26–0.64 px** (median residual 0.07–0.36 px) | + +At 360.56 px every unit from 16300 to 17000 lands within 0.60–0.64 px worst (the measurement's floor on these scenes); +spacing and unit trade off along a ridge as on the ILCE-6700 (375 px / 15700 and 380 px / 15400 reach 0.59 px), so the +body keeps the ILCE-6700's crop-based spacing and takes its own unit, 16384, in `APSC_BODIES`. The fitted polynomial +passes the 0.5 px APS-C fit gate on all four tables, the strongest (16 mm, −1905 at the last knot) included. An HDR +merge of a ZV-E10 bracket keeps the warp in the merged DNG's `OpcodeList3`, as for any raw with embedded corrections. + ## Two conventions A second Sony decoder, `src/arw_lens.rs` @@ -344,7 +367,7 @@ the resampled source by the source, framing and output size, so tone, colour and ## Limits -- **ILCE-7RM6 and ILCE-6700 only.** Other Sony bodies record the same tags; their knot spacing (defined here by the +- **ILCE-7RM6, ILCE-6700 and ZV-E10 only.** Other Sony bodies record the same tags; their knot spacing (defined here by the full-frame crop, or an APS-C body's own crop), unit and zoom rule are unverified, so they get no correction from this conversion (the ILCE-7RM4A's distortion has its own: [Two conventions](#two-conventions)). - **ILCE-6700 at strong barrel distortion:** the body's rule leaves 1.36–1.38 px at the Sigma 10–18 mm's 10 mm end; @@ -355,6 +378,10 @@ the resampled source by the source, framing and output size, so tone, colour and 6656 × 4608 frame, misses the 0.5 px fit gate, so that photo stays uncorrected (5.3 px). Other wide lenses with similarly strong tables are unmeasured. Its vignetting and lateral CA tables are read, not applied: measured in #2801 (the camera JPEG doesn't compensate vignetting, as on the ILCE-7RM6). +- **ZV-E10: one lens, four photos.** Only the E PZ 16-50 mm (16–32 mm) is measured. Its unit, 16384, differs from + the ILCE-6700's 15000; the ILCE-6700's own E 16–55 mm at 16 mm also fits a higher unit (16000, above), so the unit + may belong to the lens rather than the body. Other lenses on the ZV-E10 are unmeasured and take 16384. The + ZV-E10M2 (another sensor) is not covered. - **APS-C distortion is unverified in camera on the ILCE-7RM6:** no APS-C photo with distortion correction on was available; the APS-C knot spacing is verified on CA only, and the APS-C zoom follows the full-frame rule. - **Aspect-ratio crops** (in-camera 4:3, 16:9, 1:1) were not measured; the correction uses the crop the file records. diff --git a/crates/raw/src/arw_lens_rm6.rs b/crates/raw/src/arw_lens_rm6.rs index d3e3b7275..29b71d6b0 100644 --- a/crates/raw/src/arw_lens_rm6.rs +++ b/crates/raw/src/arw_lens_rm6.rs @@ -40,9 +40,10 @@ //! The correction is produced whatever the in-camera flag says. Only bodies listed in [`FULL_FRAME_CROP`] or //! [`APSC_BODIES`] get it: the unit and the knot spacing are verified on the ILCE-7RM6 and, for distortion, on the //! ILCE-6700 (APS-C, 11 knots spanning its own crop, the same unit 15000: 0.73 px worst over 27 photos with three -//! lenses as rendered, 1.38 px at the 10–18 mm's 10 mm end). Another body is added by repeating the measurement on its photos shot -//! with distortion correction on and listing its full-frame default crop (or, for an APS-C body, its model). The method -//! and the numbers: docs/sony-ilce7rm6-lens-corrections.md. +//! lenses as rendered, 1.38 px at the 10–18 mm's 10 mm end) and the ZV-E10 (the same APS-C rule with unit 16384: +//! 0.64 px worst over 4 photos with the E PZ 16–50 mm at 16–32 mm as rendered). Another body is added by repeating the +//! measurement on its photos shot with distortion correction on and listing its full-frame default crop (or, for an +//! APS-C body, its model). The method and the numbers: docs/sony-ilce7rm6-lens-corrections.md. use crate::opcodes::max_radius; use crate::shared::fit_radial_warp; @@ -59,9 +60,15 @@ pub(crate) const CA_FLAG: u16 = 0x7034; /// The bodies whose tables are verified (Exif `Model`), with their full-frame default crop (width, height) in px. const FULL_FRAME_CROP: &[(&str, (f64, f64))] = &[("ILCE-7RM6", (9984.0, 6656.0))]; -/// The verified APS-C bodies (Exif `Model`): their knots span the file's own default crop, the last knot at its corner. -/// Measured on the ILCE-6700 (docs/sony-ilce7rm6-lens-corrections.md → ILCE-6700). -const APSC_BODIES: &[&str] = &["ILCE-6700"]; +/// The verified APS-C bodies (Exif `Model`) with their distortion unit: their knots span the file's own default crop, +/// the last knot at its corner. Measured against the camera JPEG (docs/sony-ilce7rm6-lens-corrections.md → ILCE-6700, +/// ZV-E10): the ILCE-6700 at the ILCE-7RM6's 15000; the ZV-E10 at 16384, where 15000 over-corrects by about 9 %. +const APSC_BODIES: &[(&str, f64)] = &[("ILCE-6700", DISTORTION_UNIT), ("ZV-E10", 16384.0)]; + +/// The distortion unit of an [`APSC_BODIES`] body. +fn apsc_unit(model: &str) -> Option { + APSC_BODIES.iter().find(|(m, _)| *m == model.trim()).map(|&(_, unit)| unit) +} /// A lens whose tables follow its body's convention with another knot spacing and unit, at the focal lengths up to /// `max_focal_mm`; measured like the body, against the camera JPEG. @@ -153,7 +160,7 @@ fn knot_spacing(model: &str, knots: usize, crop: Rect) -> Option { } let gaps = knots.checked_sub(1).filter(|&n| n > 0)?; let half_diagonal = (crop.width as f64).hypot(crop.height as f64) / 2.0; - (APSC_BODIES.contains(&model) && crate::arw_lens::is_3_2(crop)).then(|| half_diagonal / gaps as f64) + (apsc_unit(model).is_some() && crate::arw_lens::is_3_2(crop)).then(|| half_diagonal / gaps as f64) } /// The knot table at radius `r` px: knot `i` at `i · spacing`, linear in between, the last segment extended beyond @@ -261,8 +268,8 @@ pub(crate) fn lens_opcodes(raw: &Ifd, model: &str, lens: Option<&str>, focal_mm: let Some(spacing) = knot_spacing(model, knots, crop) else { return Vec::new() }; let op = if let Some(e) = lens_exception(model, lens, focal_mm) { gated_warp_opcode(&tables, e.knot_spacing, e.unit, active, crop, false, APSC_FIT_ERROR_PX_AT_1440) - } else if APSC_BODIES.contains(&model.trim()) { - gated_warp_opcode(&tables, spacing, DISTORTION_UNIT, active, crop, false, APSC_FIT_ERROR_PX_AT_1440) + } else if let Some(unit) = apsc_unit(model) { + gated_warp_opcode(&tables, spacing, unit, active, crop, false, APSC_FIT_ERROR_PX_AT_1440) } else { warp_opcode(&tables, spacing, active, crop, false) }; @@ -310,6 +317,8 @@ mod tests { const FF_HQ_R: [f64; 4] = [0.9715153129, 0.02236266369, 0.0007060224765, 0.005666341563]; const FF_HQ_B: [f64; 4] = [0.97137946, 0.02277016389, 0.0003830082563, 0.005727820598]; const APSC_G: [f64; 4] = [1.01627551, -0.0618606692, 0.02768349621, -0.005595798468]; + /// The ZV-E10 16 mm example's G plane (unit 16384, knots over its crop's half diagonal / 10), from the same recipe. + const ZV_E10_G: [f64; 4] = [1.051925248, -0.1972416727, 0.09393523723, -0.0282770833]; const APSC_R: [f64; 4] = [1.016503991, -0.06206460153, 0.0278447625, -0.005644118171]; const APSC_B: [f64; 4] = [1.016155702, -0.06162477627, 0.02753315326, -0.005554915901]; @@ -629,6 +638,33 @@ mod tests { assert!(matches!(ops.as_slice(), [Opcode::WarpRectilinear { planes, .. }] if planes.len() == 1), "{ops:?}"); } + /// A ZV-E10 file (E PZ 16-50 mm at 16 mm): 11 knots, zero-padded as this body stores them. + const ZV_E10_16MM_DISTORTION: [i16; 17] = [11, 72, -7, -129, -266, -446, -640, -877, -1114, -1380, -1639, -1905, 0, 0, 0, 0, 0]; + /// The ZV-E10's decoded geometry: 6048 × 4024 storage, a 6000 × 4000 default crop at (12, 12). + const ZV_E10_ACTIVE: Rect = Rect { x: 0, y: 0, width: 6048, height: 4024 }; + const ZV_E10_CROP: Rect = Rect { x: 12, y: 12, width: 6000, height: 4000 }; + + /// The ZV-E10 follows the ILCE-6700's APS-C rule (knots over its own crop's half diagonal / 10, the APS-C fit + /// gate) with its own unit, 16384; its zero padding is not read as knots, and its successor (ZV-E10M2) stays + /// unverified. + #[test] + fn zv_e10_uses_the_apsc_rule_with_its_own_unit() { + let s = knot_spacing("ZV-E10", 11, ZV_E10_CROP).unwrap(); + assert!((s - 360.5551).abs() < 1e-3, "{s}"); + let ifd = sony_lens_ifd(&ZV_E10_16MM_DISTORTION, &APSC_VIGNETTING, &APSC_CA, [17, 2, 1]); + let t = read_tables(&ifd); + assert_eq!(t.distortion.as_ref().map(Vec::len), Some(11)); + let gated = gated_warp_opcode(&t, s, 16384.0, ZV_E10_ACTIVE, ZV_E10_CROP, false, APSC_FIT_ERROR_PX_AT_1440); + let ops = lens_opcodes(&ifd, " ZV-E10 ", Some("E PZ 16-50mm F3.5-5.6 OSS"), Some(16.0), ZV_E10_ACTIVE, ZV_E10_CROP); + assert_warp(ops.first().cloned(), [3011.5 / 6047.0, 0.5], &[ZV_E10_G]); + assert_eq!(ops, gated.into_iter().collect::>()); + // the ILCE-6700's unit would warp it differently + let at_15000 = gated_warp_opcode(&t, s, DISTORTION_UNIT, ZV_E10_ACTIVE, ZV_E10_CROP, false, APSC_FIT_ERROR_PX_AT_1440); + assert_ne!(ops.first(), at_15000.as_ref()); + assert_eq!(apsc_unit("ILCE-6700"), Some(DISTORTION_UNIT)); + assert!(lens_opcodes(&ifd, "ZV-E10M2", None, None, ZV_E10_ACTIVE, ZV_E10_CROP).is_empty()); + } + const SIGMA_10_18: &str = "10-18mm F2.8 DC DN | Contemporary 023"; /// The Sigma 10-18 mm exception: its spacing and unit at 10-10.5 mm, the body's rule from 11.7 mm (and without a From e97e73f5792e180d3b9227c3c1a10a9e21f56b14 Mon Sep 17 00:00:00 2001 From: Brandon Thomas Date: Tue, 17 Nov 2026 08:38:13 -0500 Subject: [PATCH 02/37] dex: Craft Anything Port Craft Anything f64ae3bf3c8863a982af1304e06de20653803968 reader and opcode decoder. --- crates/dex/src/dex.rs | 810 ++++++++++++++++++++++++++++++++++++++ crates/dex/src/dex_ops.rs | 640 ++++++++++++++++++++++++++++++ 2 files changed, 1450 insertions(+) create mode 100644 crates/dex/src/dex.rs create mode 100644 crates/dex/src/dex_ops.rs diff --git a/crates/dex/src/dex.rs b/crates/dex/src/dex.rs new file mode 100644 index 000000000..e46d97b5b --- /dev/null +++ b/crates/dex/src/dex.rs @@ -0,0 +1,810 @@ +//! Dalvik executables (DEX): header, string/type/proto/field/method ids, class definitions, +//! class data, code items with try/catch handlers, class annotations, a smali-like listing of +//! method bodies and a reference finder. Counts are checked against the file size, strings are +//! decoded from MUTF-8 under a total budget, and every read is bounds-checked. + +use crate::FormatError; +use crate::bytes::Reader; +use crate::dex_ops::{IndexKind, Insn, Payload}; +use serde::Serialize; + +pub const NO_INDEX: u32 = 0xffff_ffff; +/// Longest string decoded (UTF-16 units). +const MAX_STRING_UNITS: usize = 16 * 1024; +/// Total UTF-16 units decoded across all strings of one file. +const STRING_BUDGET: usize = 64 * 1024 * 1024; +/// Most members per class list. +const MAX_MEMBERS: usize = 65_536; +/// Most try blocks / handlers per method. +const MAX_TRIES: usize = 4096; +const MAX_HANDLERS: usize = 256; + +#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize)] +pub struct Header { + pub version: String, + pub checksum: String, + /// Adler-32 recomputed over the file. + pub checksum_ok: bool, + /// SHA-1 field as stored (not recomputed). + pub signature: String, + pub file_size: u32, + pub header_size: u32, + pub endian_tag: String, + pub string_ids: u32, + pub type_ids: u32, + pub proto_ids: u32, + pub field_ids: u32, + pub method_ids: u32, + pub class_defs: u32, + pub data_size: u32, +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +struct ProtoId { + shorty: u32, + ret: u32, + params_off: u32, +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub struct MemberId { + pub class_idx: u16, + /// Type (fields) or proto (methods). + pub type_or_proto: u16, + pub name_idx: u32, +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub struct ClassDef { + pub class_idx: u32, + pub access: u32, + pub superclass_idx: u32, + pub interfaces_off: u32, + pub source_file_idx: u32, + pub annotations_off: u32, + pub class_data_off: u32, + pub static_values_off: u32, +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)] +pub struct EncodedField { + pub field_idx: u32, + pub access: u32, +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)] +pub struct EncodedMethod { + pub method_idx: u32, + pub access: u32, + pub code_off: u32, +} + +#[derive(Debug, Clone, Default, PartialEq, Eq)] +pub struct ClassData { + pub static_fields: Vec, + pub instance_fields: Vec, + pub direct_methods: Vec, + pub virtual_methods: Vec, + pub complete: bool, +} + +#[derive(Debug, Clone, PartialEq, Eq, Serialize)] +pub struct Handler { + /// Exception type descriptor; `None` for catch-all. + pub exception: Option, + pub address: u32, +} + +#[derive(Debug, Clone, PartialEq, Eq, Serialize)] +pub struct Try { + pub start: u32, + pub end: u32, + pub handlers: Vec, +} + +#[derive(Debug, Clone, Default, PartialEq, Eq)] +pub struct Code { + pub registers: u16, + pub ins: u16, + pub outs: u16, + pub insns: Vec, + pub tries: Vec, + pub debug_info_off: u32, +} + +/// A parsed DEX file. +#[derive(Debug, Clone)] +pub struct Dex<'a> { + data: &'a [u8], + pub header: Header, + pub strings: Vec, + types: Vec, + protos: Vec, + pub fields: Vec, + pub methods: Vec, + pub classes: Vec, + pub warnings: Vec, +} + +fn adler32(data: &[u8]) -> u32 { + let (mut a, mut b) = (1u32, 0u32); + for chunk in data.chunks(5552) { + for &x in chunk { + a += u32::from(x); + b += a; + } + a %= 65521; + b %= 65521; + } + (b << 16) | a +} + +/// Decode modified UTF-8 (as used by DEX and class files) to a String. +pub fn mutf8(r: &Reader<'_>, mut at: usize, max_units: usize) -> (String, usize) { + let mut units: Vec = Vec::new(); + let mut consumed = 0usize; + while units.len() < max_units { + let Some(b0) = r.u8(at) else { break }; + if b0 == 0 { + break; + } + let (u, n) = if b0 < 0x80 { + (u16::from(b0), 1) + } else if b0 & 0xe0 == 0xc0 { + let b1 = r.u8(at + 1).unwrap_or(0); + ((u16::from(b0 & 0x1f) << 6) | u16::from(b1 & 0x3f), 2) + } else if b0 & 0xf0 == 0xe0 { + let b1 = r.u8(at + 1).unwrap_or(0); + let b2 = r.u8(at + 2).unwrap_or(0); + ((u16::from(b0 & 0x0f) << 12) | (u16::from(b1 & 0x3f) << 6) | u16::from(b2 & 0x3f), 3) + } else { + (0xfffd, 1) + }; + units.push(u); + at = at.saturating_add(n); + consumed += n; + } + (String::from_utf16_lossy(&units), consumed) +} + +/// Signed LEB128 at `off`: (value, bytes). +pub fn sleb128(r: &Reader<'_>, off: usize) -> Option<(i64, usize)> { + let mut result = 0i64; + let mut shift = 0u32; + for i in 0..10usize { + let b = r.u8(off.checked_add(i)?)?; + result |= i64::from(b & 0x7f).checked_shl(shift)?; + shift += 7; + if b & 0x80 == 0 { + if shift < 64 && b & 0x40 != 0 { + result |= -1i64 << shift; + } + return Some((result, i + 1)); + } + } + None +} + +/// `Lcom/x/Y;` → `com.x.Y`; `[I` → `int[]`. +pub fn java_name(desc: &str) -> String { + let dims = desc.chars().take_while(|&c| c == '[').count(); + let base = desc.get(dims..).unwrap_or(""); + let name = match base { + "V" => "void".to_string(), + "Z" => "boolean".to_string(), + "B" => "byte".to_string(), + "S" => "short".to_string(), + "C" => "char".to_string(), + "I" => "int".to_string(), + "J" => "long".to_string(), + "F" => "float".to_string(), + "D" => "double".to_string(), + b if b.starts_with('L') && b.ends_with(';') => b.get(1..b.len() - 1).unwrap_or("").replace('/', "."), + b => b.to_string(), + }; + format!("{name}{}", "[]".repeat(dims.min(255))) +} + +/// `com.x.Y` or `com/x/Y` or `Lcom/x/Y;` → `Lcom/x/Y;`. +pub fn to_descriptor(name: &str) -> String { + let n = name.trim(); + if n.starts_with('L') && n.ends_with(';') { n.to_string() } else { format!("L{};", n.replace('.', "/")) } +} + +/// Access flag names for a class, field or method. +pub fn access_flags(flags: u32, kind: &str) -> Vec<&'static str> { + let mut v = Vec::new(); + let table: &[(u32, &str)] = &[ + (0x1, "public"), + (0x2, "private"), + (0x4, "protected"), + (0x8, "static"), + (0x10, "final"), + (0x100, "native"), + (0x200, "interface"), + (0x400, "abstract"), + (0x800, "strictfp"), + (0x1000, "synthetic"), + (0x2000, "annotation"), + (0x4000, "enum"), + (0x10000, "constructor"), + (0x20000, "declared-synchronized"), + ]; + for (bit, name) in table { + if flags & bit != 0 { + v.push(*name); + } + } + match kind { + "method" => { + if flags & 0x20 != 0 { + v.push("synchronized"); + } + if flags & 0x40 != 0 { + v.push("bridge"); + } + if flags & 0x80 != 0 { + v.push("varargs"); + } + } + "field" => { + if flags & 0x40 != 0 { + v.push("volatile"); + } + if flags & 0x80 != 0 { + v.push("transient"); + } + } + _ => {} + } + v +} + +fn table(r: &Reader<'_>, count_off: usize, what: &str, entry: usize) -> Result<(usize, usize), FormatError> { + let n = r.u32_le(count_off).ok_or_else(|| FormatError::Truncated("header".into()))? as usize; + let off = r.u32_le(count_off + 4).ok_or_else(|| FormatError::Truncated("header".into()))? as usize; + if n == 0 { + return Ok((0, 0)); + } + let bytes = n.checked_mul(entry).ok_or_else(|| FormatError::Malformed(format!("{what} count overflows")))?; + if off.checked_add(bytes).is_none_or(|e| e > r.len()) { + return Err(FormatError::Malformed(format!("{n} {what} at offset {off} run past the end of the file"))); + } + Ok((n, off)) +} + +/// True when bytes start with a DEX magic. +pub fn is_dex(data: &[u8]) -> bool { + data.starts_with(b"dex\n") && data.len() >= 0x70 +} + +/// Parse a DEX file. +pub fn parse(data: &[u8]) -> Result, FormatError> { + let r = Reader::new(data); + if !data.starts_with(b"dex\n") { + return Err(FormatError::Malformed("not a DEX file (no dex magic)".into())); + } + if data.len() < 0x70 { + return Err(FormatError::Truncated("DEX header".into())); + } + let mut warnings = Vec::new(); + let version = r.cstr(4, 4).unwrap_or_default(); + let checksum = r.u32_le(8).unwrap_or(0); + let file_size = r.u32_le(32).unwrap_or(0); + let endian = r.u32_le(40).unwrap_or(0); + if endian != 0x1234_5678 { + return Err(FormatError::Unsupported(format!("byte-swapped DEX (endian tag {endian:#x})"))); + } + if file_size as usize != data.len() { + warnings.push(format!("header says {file_size} bytes, the file has {}", data.len())); + } + let sum_end = (file_size as usize).min(data.len()); + let checksum_ok = data.get(12..sum_end).is_some_and(|d| adler32(d) == checksum); + if !checksum_ok { + warnings.push("Adler-32 checksum does not match the content".into()); + } + let (ns, so) = table(&r, 56, "strings", 4)?; + let (nt, to) = table(&r, 64, "types", 4)?; + let (np, po) = table(&r, 72, "protos", 12)?; + let (nf, fo) = table(&r, 80, "fields", 8)?; + let (nm, mo) = table(&r, 88, "methods", 8)?; + let (nc, co) = table(&r, 96, "classes", 32)?; + let header = Header { + version, + checksum: format!("{checksum:08x}"), + checksum_ok, + signature: r.slice(12, 20).map(|b| b.iter().map(|x| format!("{x:02x}")).collect()).unwrap_or_default(), + file_size, + header_size: r.u32_le(36).unwrap_or(0), + endian_tag: format!("{endian:#x}"), + string_ids: ns as u32, + type_ids: nt as u32, + proto_ids: np as u32, + field_ids: nf as u32, + method_ids: nm as u32, + class_defs: nc as u32, + data_size: r.u32_le(104).unwrap_or(0), + }; + let mut strings = Vec::with_capacity(ns); + let mut budget = STRING_BUDGET; + let mut over_budget = false; + for i in 0..ns { + let off = r.u32_le(so + i * 4).unwrap_or(0) as usize; + let s = match r.uleb128(off) { + Some((len, n)) if budget > 0 => { + let want = (len as usize).min(MAX_STRING_UNITS).min(budget); + let (s, _) = mutf8(&r, off.saturating_add(n), want); + budget = budget.saturating_sub(want.max(1)); + s + } + Some(_) => { + over_budget = true; + format!("") + } + None => format!(""), + }; + strings.push(s); + } + if over_budget { + warnings.push("string decoding budget reached; later strings are shown as ".into()); + } + let types = (0..nt).map(|i| r.u32_le(to + i * 4).unwrap_or(NO_INDEX)).collect(); + let protos = (0..np) + .map(|i| { + let o = po + i * 12; + ProtoId { shorty: r.u32_le(o).unwrap_or(0), ret: r.u32_le(o + 4).unwrap_or(NO_INDEX), params_off: r.u32_le(o + 8).unwrap_or(0) } + }) + .collect(); + let member = + |o: usize| MemberId { class_idx: r.u16_le(o).unwrap_or(0), type_or_proto: r.u16_le(o + 2).unwrap_or(0), name_idx: r.u32_le(o + 4).unwrap_or(NO_INDEX) }; + let fields = (0..nf).map(|i| member(fo + i * 8)).collect(); + let methods = (0..nm).map(|i| member(mo + i * 8)).collect(); + let classes = (0..nc) + .map(|i| { + let o = co + i * 32; + let g = |k: usize| r.u32_le(o + k * 4).unwrap_or(0); + ClassDef { + class_idx: g(0), + access: g(1), + superclass_idx: g(2), + interfaces_off: g(3), + source_file_idx: g(4), + annotations_off: g(5), + class_data_off: g(6), + static_values_off: g(7), + } + }) + .collect(); + Ok(Dex { data, header, strings, types, protos, fields, methods, classes, warnings }) +} + +impl<'a> Dex<'a> { + fn r(&self) -> Reader<'a> { + Reader::new(self.data) + } + + pub fn string(&self, i: u32) -> &str { + self.strings.get(i as usize).map(String::as_str).unwrap_or("") + } + + /// The descriptor of type `i` (`Lcom/x/Y;`). + pub fn type_desc(&self, i: u32) -> String { + match self.types.get(i as usize) { + Some(&s) => self.string(s).to_string(), + None => format!(""), + } + } + + fn type_list(&self, off: u32) -> Vec { + if off == 0 { + return Vec::new(); + } + let r = self.r(); + let n = r.u32_le(off as usize).unwrap_or(0) as usize; + (0..n.min(256)).filter_map(|i| r.u16_le(off as usize + 4 + i * 2).map(u32::from)).collect() + } + + /// `(Ljava/lang/String;I)V` + pub fn proto_desc(&self, i: u32) -> String { + match self.protos.get(i as usize) { + Some(p) => { + let params: String = self.type_list(p.params_off).into_iter().map(|t| self.type_desc(t)).collect(); + format!("({params}){}", self.type_desc(p.ret)) + } + None => format!(""), + } + } + + /// Parameter type descriptors and return type of proto `i`. + pub fn proto_parts(&self, i: u32) -> (Vec, String) { + match self.protos.get(i as usize) { + Some(p) => (self.type_list(p.params_off).into_iter().map(|t| self.type_desc(t)).collect(), self.type_desc(p.ret)), + None => (Vec::new(), "?".into()), + } + } + + pub fn shorty(&self, i: u32) -> &str { + self.protos.get(i as usize).map(|p| self.string(p.shorty)).unwrap_or("") + } + + /// `Lcls;->name:Ltype;` + pub fn field_ref(&self, i: u32) -> String { + match self.fields.get(i as usize) { + Some(f) => format!("{}->{}:{}", self.type_desc(u32::from(f.class_idx)), self.string(f.name_idx), self.type_desc(u32::from(f.type_or_proto))), + None => format!(""), + } + } + + /// `Lcls;->name(…)R` + pub fn method_ref(&self, i: u32) -> String { + match self.methods.get(i as usize) { + Some(m) => format!("{}->{}{}", self.type_desc(u32::from(m.class_idx)), self.string(m.name_idx), self.proto_desc(u32::from(m.type_or_proto))), + None => format!(""), + } + } + + pub fn class_name(&self, c: &ClassDef) -> String { + self.type_desc(c.class_idx) + } + + pub fn find_class(&self, name: &str) -> Option<&ClassDef> { + let want = to_descriptor(name); + self.classes.iter().find(|c| self.class_name(c) == want) + } + + pub fn interfaces(&self, c: &ClassDef) -> Vec { + self.type_list(c.interfaces_off).into_iter().map(|t| self.type_desc(t)).collect() + } + + /// Type descriptors of the class-level annotations. + pub fn annotations(&self, c: &ClassDef) -> Vec { + let r = self.r(); + let mut out = Vec::new(); + if c.annotations_off == 0 { + return out; + } + let Some(set_off) = r.u32_le(c.annotations_off as usize) else { return out }; + if set_off == 0 { + return out; + } + let n = r.u32_le(set_off as usize).unwrap_or(0) as usize; + for i in 0..n.min(256) { + let Some(item) = r.u32_le(set_off as usize + 4 + i * 4) else { break }; + // visibility u8, then encoded_annotation: uleb type_idx … + let vis = r.u8(item as usize).unwrap_or(0); + if let Some((t, _)) = r.uleb128(item as usize + 1) { + let v = match vis { + 0 => "build", + 1 => "runtime", + 2 => "system", + _ => "?", + }; + out.push(format!("{} ({v})", self.type_desc(t as u32))); + } + } + out + } + + pub fn class_data(&self, c: &ClassDef) -> ClassData { + let mut cd = ClassData::default(); + if c.class_data_off == 0 { + cd.complete = true; + return cd; + } + let r = self.r(); + let mut pos = c.class_data_off as usize; + let next = |pos: &mut usize| -> Option { + let (v, n) = r.uleb128(*pos)?; + *pos += n; + u32::try_from(v).ok() + }; + let (Some(sf), Some(inf), Some(dm), Some(vm)) = (next(&mut pos), next(&mut pos), next(&mut pos), next(&mut pos)) else { return cd }; + let remaining = self.data.len().saturating_sub(pos); + let total = [sf, inf, dm, vm].iter().map(|&x| x as usize).sum::(); + if total > remaining || total > MAX_MEMBERS * 4 { + return cd; + } + for (count, is_method, slot) in [(sf, false, 0), (inf, false, 1), (dm, true, 2), (vm, true, 3)] { + let mut idx: u32 = 0; + for _ in 0..count.min(MAX_MEMBERS as u32) { + let Some(diff) = next(&mut pos) else { return cd }; + let Some(access) = next(&mut pos) else { return cd }; + idx = match idx.checked_add(diff) { + Some(v) => v, + None => return cd, + }; + if is_method { + let Some(code_off) = next(&mut pos) else { return cd }; + let m = EncodedMethod { method_idx: idx, access, code_off }; + if slot == 2 { + cd.direct_methods.push(m); + } else { + cd.virtual_methods.push(m); + } + } else { + let f = EncodedField { field_idx: idx, access }; + if slot == 0 { + cd.static_fields.push(f); + } else { + cd.instance_fields.push(f); + } + } + } + } + cd.complete = true; + cd + } + + /// The code item at `off`. + pub fn code(&self, off: u32) -> Option { + if off == 0 { + return None; + } + let r = self.r(); + let o = off as usize; + let registers = r.u16_le(o)?; + let ins = r.u16_le(o + 2)?; + let outs = r.u16_le(o + 4)?; + let tries_size = usize::from(r.u16_le(o + 6)?); + let debug_info_off = r.u32_le(o + 8)?; + let n = r.u32_le(o + 12)? as usize; + let bytes = r.slice(o + 16, n.checked_mul(2)?)?; + let insns: Vec = bytes.as_chunks::<2>().0.iter().map(|c| u16::from_le_bytes(*c)).collect(); + let mut tries = Vec::new(); + let mut t_off = o + 16 + n * 2; + if tries_size > 0 && n % 2 == 1 { + t_off += 2; + } + let handlers_base = t_off + tries_size * 8; + for i in 0..tries_size.min(MAX_TRIES) { + let at = t_off + i * 8; + let (Some(start), Some(count), Some(h_off)) = (r.u32_le(at), r.u16_le(at + 4), r.u16_le(at + 6)) else { break }; + let mut handlers = Vec::new(); + let mut p = handlers_base + usize::from(h_off); + if let Some((size, k)) = sleb128(&r, p) { + p += k; + for _ in 0..size.unsigned_abs().min(MAX_HANDLERS as u64) { + let Some((t, k1)) = r.uleb128(p) else { break }; + let Some((addr, k2)) = r.uleb128(p + k1) else { break }; + p += k1 + k2; + handlers.push(Handler { exception: Some(self.type_desc(t as u32)), address: addr as u32 }); + } + if size <= 0 + && let Some((addr, _)) = r.uleb128(p) + { + handlers.push(Handler { exception: None, address: addr as u32 }); + } + } + tries.push(Try { start, end: start.saturating_add(u32::from(count)), handlers }); + } + Some(Code { registers, ins, outs, insns, tries, debug_info_off }) + } + + /// Name of method `i`. + pub fn method_name(&self, i: u32) -> &str { + self.methods.get(i as usize).map(|m| self.string(m.name_idx)).unwrap_or("") + } + + /// Java-like signature: `public static void log(java.lang.String)`. + pub fn method_signature(&self, m: &EncodedMethod) -> String { + let Some(id) = self.methods.get(m.method_idx as usize) else { return format!("", m.method_idx) }; + let (params, ret) = self.proto_parts(u32::from(id.type_or_proto)); + let flags = access_flags(m.access, "method").into_iter().filter(|f| *f != "constructor").collect::>().join(" "); + let params = params.iter().map(|p| java_name(p)).collect::>().join(", "); + format!("{}{}{} {}({params})", flags, if flags.is_empty() { "" } else { " " }, java_name(&ret), self.string(id.name_idx)).trim().to_string() + } + + /// Render one instruction smali-style. + pub fn format_insn(&self, i: &Insn) -> String { + let mut parts: Vec = Vec::new(); + if !i.regs.is_empty() { + let is_list = i.name.starts_with("invoke") || i.name.starts_with("filled-new-array"); + if i.range { + match (i.regs.first(), i.regs.last()) { + (Some(a), Some(b)) => parts.push(format!("{{v{a} .. v{b}}}")), + _ => parts.push("{}".into()), + } + } else if is_list { + parts.push(format!("{{{}}}", i.regs.iter().map(|r| format!("v{r}")).collect::>().join(", "))); + } else { + parts.extend(i.regs.iter().map(|r| format!("v{r}"))); + } + } else if i.range || i.name.starts_with("invoke") { + parts.push("{}".into()); + } + if let Some(l) = i.literal { + parts.push(if (-9..=9).contains(&l) { format!("{l}") } else { format!("{l:#x}") }); + } + if let Some(idx) = i.index { + parts.push(match i.index_kind { + IndexKind::String => format!("{:?}", self.string(idx)), + IndexKind::Type => self.type_desc(idx), + IndexKind::Field => self.field_ref(idx), + IndexKind::Method => self.method_ref(idx), + IndexKind::CallSite => format!("call_site@{idx}"), + IndexKind::MethodHandle => format!("method_handle@{idx}"), + IndexKind::Proto => self.proto_desc(idx), + IndexKind::None => format!("@{idx}"), + }); + } + if let Some(p) = i.index2 { + parts.push(self.proto_desc(p)); + } + if let Some(t) = i.target { + parts.push(format!(":{t:04x}")); + } + let mut s = if parts.is_empty() { i.name.to_string() } else { format!("{} {}", i.name, parts.join(", ")) }; + match (&i.payload, i.opcode) { + (Some(Payload::PackedSwitch { first_key, targets }), 0x2b) => { + let cases: Vec = targets + .iter() + .enumerate() + .take(32) + .map(|(k, t)| format!("{} -> :{:04x}", i64::from(*first_key) + k as i64, i64::from(i.offset) + i64::from(*t))) + .collect(); + s.push_str(&format!(" # {}", cases.join(", "))); + } + (Some(Payload::SparseSwitch { keys, targets }), 0x2c) => { + let cases: Vec = + keys.iter().zip(targets).take(32).map(|(k, t)| format!("{k} -> :{:04x}", i64::from(i.offset) + i64::from(*t))).collect(); + s.push_str(&format!(" # {}", cases.join(", "))); + } + (Some(Payload::FillArrayData { element_width, count, .. }), _) => s.push_str(&format!(" # {count} x {element_width}-byte elements")), + (Some(Payload::PackedSwitch { targets, .. }), 0) => s.push_str(&format!(" ({} cases)", targets.len())), + (Some(Payload::SparseSwitch { targets, .. }), 0) => s.push_str(&format!(" ({} cases)", targets.len())), + _ => {} + } + s + } +} + +/// One place code refers to a class, method or field. +#[derive(Debug, Clone, PartialEq, Eq, Serialize)] +pub struct Reference { + /// Caller method, `Lcls;->name(…)R`. + pub caller: String, + /// Code unit offset in the caller. + pub offset: u32, + pub instruction: &'static str, + /// method, field or type + pub kind: &'static str, + pub target: String, +} + +/// Every instruction that refers to class `desc` (optionally only its methods named `method`). +pub fn references(dex: &Dex<'_>, desc: &str, method: Option<&str>, max: usize) -> (Vec, bool) { + let mut out = Vec::new(); + for c in &dex.classes { + let cd = dex.class_data(c); + for m in cd.direct_methods.iter().chain(&cd.virtual_methods) { + let Some(code) = dex.code(m.code_off) else { continue }; + let (insns, _) = crate::dex_ops::decode(&code.insns, 200_000); + for i in &insns { + let Some(idx) = i.index else { continue }; + let hit = match i.index_kind { + IndexKind::Method => dex.methods.get(idx as usize).and_then(|id| { + let cls = dex.type_desc(u32::from(id.class_idx)); + (cls == desc && method.is_none_or(|n| dex.string(id.name_idx) == n)).then(|| ("method", dex.method_ref(idx))) + }), + IndexKind::Field if method.is_none() => { + dex.fields.get(idx as usize).and_then(|id| (dex.type_desc(u32::from(id.class_idx)) == desc).then(|| ("field", dex.field_ref(idx)))) + } + IndexKind::Type if method.is_none() => { + let t = dex.type_desc(idx); + (t.trim_start_matches('[') == desc).then_some(("type", t)) + } + _ => None, + }; + if let Some((kind, target)) = hit { + if out.len() >= max { + return (out, true); + } + out.push(Reference { caller: dex.method_ref(m.method_idx), offset: i.offset, instruction: i.name, kind, target }); + } + } + } + } + (out, false) +} + +#[cfg(test)] +mod tests { + use super::*; + use craft_anything_testkit::android as fx; + + #[test] + fn parses_fixture() { + let data = fx::notes_dex(); + let d = parse(&data).unwrap(); + assert!(d.warnings.is_empty(), "{:?}", d.warnings); + assert!(d.header.checksum_ok); + assert_eq!(d.header.version, "035"); + assert_eq!(d.classes.len(), 2); + let main = d.find_class("com.example.notes.MainActivity").unwrap(); + assert_eq!(d.type_desc(main.superclass_idx), "Landroid/app/Activity;"); + assert_eq!(d.interfaces(main), vec!["Ljava/lang/Runnable;"]); + assert_eq!(d.string(main.source_file_idx), "MainActivity.java"); + assert_eq!(d.annotations(main), vec!["Ljava/lang/Deprecated; (runtime)"]); + let cd = d.class_data(main); + assert!(cd.complete); + assert_eq!(cd.static_fields.len(), 1); + assert_eq!(cd.instance_fields.len(), 1); + assert_eq!(cd.direct_methods.len(), 1); + assert_eq!(cd.virtual_methods.len(), 3); + let on_create = cd.virtual_methods.iter().find(|m| d.method_name(m.method_idx) == "onCreate").unwrap(); + assert_eq!(d.method_signature(on_create), "public void onCreate(android.os.Bundle)"); + let code = d.code(on_create.code_off).unwrap(); + let (ins, complete) = crate::dex_ops::decode(&code.insns, 1000); + assert!(complete); + let text: Vec = ins.iter().map(|i| d.format_insn(i)).collect(); + assert_eq!(text[0], "const-string v0, \"Hello, Craft!\""); + assert_eq!(text[1], "invoke-static {v0}, Lcom/example/notes/Util;->log(Ljava/lang/String;)V"); + let pick = cd.virtual_methods.iter().find(|m| d.method_name(m.method_idx) == "pick").unwrap(); + let pc = d.code(pick.code_off).unwrap(); + assert_eq!(pc.tries.len(), 1); + assert_eq!(pc.tries[0].handlers[0].exception.as_deref(), Some("Ljava/lang/RuntimeException;")); + assert_eq!(pc.tries[0].handlers[1].exception, None); + let (pins, _) = crate::dex_ops::decode(&pc.insns, 1000); + let sw = pins.iter().find(|i| i.name == "packed-switch").unwrap(); + assert!(d.format_insn(sw).contains("# 1 -> :"), "{}", d.format_insn(sw)); + let (refs, more) = references(&d, "Lcom/example/notes/Util;", Some("log"), 100); + assert!(!more); + assert_eq!(refs.len(), 2, "{refs:?}"); + assert_eq!(refs[0].caller, "Lcom/example/notes/MainActivity;->onCreate(Landroid/os/Bundle;)V"); + let (all, _) = references(&d, "Ljava/lang/System;", None, 100); + assert_eq!(all[0].kind, "field"); + } + + #[test] + fn helpers() { + assert_eq!(java_name("[[Ljava/lang/String;"), "java.lang.String[][]"); + assert_eq!(java_name("J"), "long"); + assert_eq!(to_descriptor("a.b.C"), "La/b/C;"); + assert_eq!(to_descriptor("La/b/C;"), "La/b/C;"); + assert_eq!(access_flags(0x10009, "method"), vec!["public", "static", "constructor"]); + let r = Reader::new(&[0x7f]); + assert_eq!(sleb128(&r, 0), Some((-1, 1))); + let s = [0xc0, 0x80, 0xe2, 0x82, 0xac, 0x41, 0]; + assert_eq!(mutf8(&Reader::new(&s), 0, 100).0, "\0\u{20ac}A"); + } + + #[test] + fn hostile() { + let data = fx::notes_dex(); + let walk = |d: &Dex<'_>| { + for c in &d.classes { + let cd = d.class_data(c); + let _ = d.annotations(c); + let _ = d.interfaces(c); + for m in cd.direct_methods.iter().chain(&cd.virtual_methods) { + let _ = d.method_signature(m); + if let Some(code) = d.code(m.code_off) { + let (ins, _) = crate::dex_ops::decode(&code.insns, 10_000); + for i in &ins { + let _ = d.format_insn(i); + } + } + } + } + let _ = references(d, "Lcom/example/notes/Util;", None, 100); + }; + for m in craft_anything_testkit::mutations(&data) { + if let Ok(d) = parse(&m) { + walk(&d); + } + } + for len in 0..data.len() { + if let Ok(d) = parse(&data[..len]) { + walk(&d); + } + } + for seed in 0..64 { + let mut n = craft_anything_testkit::noise(seed, 2048); + n[..8].copy_from_slice(b"dex\n035\0"); + n[40..44].copy_from_slice(&0x1234_5678u32.to_le_bytes()); + if let Ok(d) = parse(&n) { + walk(&d); + } + } + } +} diff --git a/crates/dex/src/dex_ops.rs b/crates/dex/src/dex_ops.rs new file mode 100644 index 000000000..139ad77ac --- /dev/null +++ b/crates/dex/src/dex_ops.rs @@ -0,0 +1,640 @@ +//! Dalvik bytecode: the opcode table (all 256 slots and three payload pseudo-instructions) and a +//! decoder for every instruction format. Pure decoding; index operands are resolved by the caller. + +use serde::Serialize; + +/// What an index operand refers to. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)] +#[serde(rename_all = "snake_case")] +pub enum IndexKind { + None, + String, + Type, + Field, + Method, + CallSite, + MethodHandle, + Proto, +} + +/// Instruction formats from the Dalvik specification (`10x`, `35c`, …). +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)] +pub enum Fmt { + F10x, + F12x, + F11n, + F11x, + F10t, + F20t, + F22x, + F21t, + F21s, + F21h, + F21c, + F23x, + F22b, + F22t, + F22s, + F22c, + F30t, + F32x, + F31i, + F31t, + F31c, + F35c, + F3rc, + F45cc, + F4rcc, + F51l, +} + +impl Fmt { + /// Length in 16-bit code units. + pub fn units(self) -> usize { + use Fmt::*; + match self { + F10x | F12x | F11n | F11x | F10t => 1, + F20t | F22x | F21t | F21s | F21h | F21c | F23x | F22b | F22t | F22s | F22c => 2, + F30t | F32x | F31i | F31t | F31c | F35c | F3rc => 3, + F45cc | F4rcc => 4, + F51l => 5, + } + } +} + +/// One opcode slot. +#[derive(Debug, Clone, Copy)] +pub struct Op { + pub name: &'static str, + pub fmt: Fmt, + pub index: IndexKind, +} + +const fn op(name: &'static str, fmt: Fmt, index: IndexKind) -> Op { + Op { name, fmt, index } +} + +const UNUSED: Op = op("unused", Fmt::F10x, IndexKind::None); + +const UNOPS: [&str; 21] = [ + "neg-int", + "not-int", + "neg-long", + "not-long", + "neg-float", + "neg-double", + "int-to-long", + "int-to-float", + "int-to-double", + "long-to-int", + "long-to-float", + "long-to-double", + "float-to-int", + "float-to-long", + "float-to-double", + "double-to-int", + "double-to-long", + "double-to-float", + "int-to-byte", + "int-to-char", + "int-to-short", +]; + +const BINOPS: [&str; 32] = [ + "add-int", + "sub-int", + "mul-int", + "div-int", + "rem-int", + "and-int", + "or-int", + "xor-int", + "shl-int", + "shr-int", + "ushr-int", + "add-long", + "sub-long", + "mul-long", + "div-long", + "rem-long", + "and-long", + "or-long", + "xor-long", + "shl-long", + "shr-long", + "ushr-long", + "add-float", + "sub-float", + "mul-float", + "div-float", + "rem-float", + "add-double", + "sub-double", + "mul-double", + "div-double", + "rem-double", +]; + +const BINOPS_2ADDR: [&str; 32] = [ + "add-int/2addr", + "sub-int/2addr", + "mul-int/2addr", + "div-int/2addr", + "rem-int/2addr", + "and-int/2addr", + "or-int/2addr", + "xor-int/2addr", + "shl-int/2addr", + "shr-int/2addr", + "ushr-int/2addr", + "add-long/2addr", + "sub-long/2addr", + "mul-long/2addr", + "div-long/2addr", + "rem-long/2addr", + "and-long/2addr", + "or-long/2addr", + "xor-long/2addr", + "shl-long/2addr", + "shr-long/2addr", + "ushr-long/2addr", + "add-float/2addr", + "sub-float/2addr", + "mul-float/2addr", + "div-float/2addr", + "rem-float/2addr", + "add-double/2addr", + "sub-double/2addr", + "mul-double/2addr", + "div-double/2addr", + "rem-double/2addr", +]; + +const LIT16: [&str; 8] = ["add-int/lit16", "rsub-int", "mul-int/lit16", "div-int/lit16", "rem-int/lit16", "and-int/lit16", "or-int/lit16", "xor-int/lit16"]; +const LIT8: [&str; 11] = [ + "add-int/lit8", + "rsub-int/lit8", + "mul-int/lit8", + "div-int/lit8", + "rem-int/lit8", + "and-int/lit8", + "or-int/lit8", + "xor-int/lit8", + "shl-int/lit8", + "shr-int/lit8", + "ushr-int/lit8", +]; +const CMP: [&str; 5] = ["cmpl-float", "cmpg-float", "cmpl-double", "cmpg-double", "cmp-long"]; +const IF2: [&str; 6] = ["if-eq", "if-ne", "if-lt", "if-ge", "if-gt", "if-le"]; +const IFZ: [&str; 6] = ["if-eqz", "if-nez", "if-ltz", "if-gez", "if-gtz", "if-lez"]; +const ARR: [&str; 14] = [ + "aget", + "aget-wide", + "aget-object", + "aget-boolean", + "aget-byte", + "aget-char", + "aget-short", + "aput", + "aput-wide", + "aput-object", + "aput-boolean", + "aput-byte", + "aput-char", + "aput-short", +]; +const IFIELD: [&str; 14] = [ + "iget", + "iget-wide", + "iget-object", + "iget-boolean", + "iget-byte", + "iget-char", + "iget-short", + "iput", + "iput-wide", + "iput-object", + "iput-boolean", + "iput-byte", + "iput-char", + "iput-short", +]; +const SFIELD: [&str; 14] = [ + "sget", + "sget-wide", + "sget-object", + "sget-boolean", + "sget-byte", + "sget-char", + "sget-short", + "sput", + "sput-wide", + "sput-object", + "sput-boolean", + "sput-byte", + "sput-char", + "sput-short", +]; +const INVOKE: [&str; 5] = ["invoke-virtual", "invoke-super", "invoke-direct", "invoke-static", "invoke-interface"]; +const INVOKE_RANGE: [&str; 5] = ["invoke-virtual/range", "invoke-super/range", "invoke-direct/range", "invoke-static/range", "invoke-interface/range"]; + +fn pick(list: &[&'static str], i: u8, base: u8) -> &'static str { + list.get(usize::from(i.wrapping_sub(base))).copied().unwrap_or("unused") +} + +/// The opcode table entry for `b`. +pub fn opcode(b: u8) -> Op { + use Fmt::*; + use IndexKind as K; + match b { + 0x00 => op("nop", F10x, K::None), + 0x01 => op("move", F12x, K::None), + 0x02 => op("move/from16", F22x, K::None), + 0x03 => op("move/16", F32x, K::None), + 0x04 => op("move-wide", F12x, K::None), + 0x05 => op("move-wide/from16", F22x, K::None), + 0x06 => op("move-wide/16", F32x, K::None), + 0x07 => op("move-object", F12x, K::None), + 0x08 => op("move-object/from16", F22x, K::None), + 0x09 => op("move-object/16", F32x, K::None), + 0x0a => op("move-result", F11x, K::None), + 0x0b => op("move-result-wide", F11x, K::None), + 0x0c => op("move-result-object", F11x, K::None), + 0x0d => op("move-exception", F11x, K::None), + 0x0e => op("return-void", F10x, K::None), + 0x0f => op("return", F11x, K::None), + 0x10 => op("return-wide", F11x, K::None), + 0x11 => op("return-object", F11x, K::None), + 0x12 => op("const/4", F11n, K::None), + 0x13 => op("const/16", F21s, K::None), + 0x14 => op("const", F31i, K::None), + 0x15 => op("const/high16", F21h, K::None), + 0x16 => op("const-wide/16", F21s, K::None), + 0x17 => op("const-wide/32", F31i, K::None), + 0x18 => op("const-wide", F51l, K::None), + 0x19 => op("const-wide/high16", F21h, K::None), + 0x1a => op("const-string", F21c, K::String), + 0x1b => op("const-string/jumbo", F31c, K::String), + 0x1c => op("const-class", F21c, K::Type), + 0x1d => op("monitor-enter", F11x, K::None), + 0x1e => op("monitor-exit", F11x, K::None), + 0x1f => op("check-cast", F21c, K::Type), + 0x20 => op("instance-of", F22c, K::Type), + 0x21 => op("array-length", F12x, K::None), + 0x22 => op("new-instance", F21c, K::Type), + 0x23 => op("new-array", F22c, K::Type), + 0x24 => op("filled-new-array", F35c, K::Type), + 0x25 => op("filled-new-array/range", F3rc, K::Type), + 0x26 => op("fill-array-data", F31t, K::None), + 0x27 => op("throw", F11x, K::None), + 0x28 => op("goto", F10t, K::None), + 0x29 => op("goto/16", F20t, K::None), + 0x2a => op("goto/32", F30t, K::None), + 0x2b => op("packed-switch", F31t, K::None), + 0x2c => op("sparse-switch", F31t, K::None), + 0x2d..=0x31 => op(pick(&CMP, b, 0x2d), F23x, K::None), + 0x32..=0x37 => op(pick(&IF2, b, 0x32), F22t, K::None), + 0x38..=0x3d => op(pick(&IFZ, b, 0x38), F21t, K::None), + 0x44..=0x51 => op(pick(&ARR, b, 0x44), F23x, K::None), + 0x52..=0x5f => op(pick(&IFIELD, b, 0x52), F22c, K::Field), + 0x60..=0x6d => op(pick(&SFIELD, b, 0x60), F21c, K::Field), + 0x6e..=0x72 => op(pick(&INVOKE, b, 0x6e), F35c, K::Method), + 0x74..=0x78 => op(pick(&INVOKE_RANGE, b, 0x74), F3rc, K::Method), + 0x7b..=0x8f => op(pick(&UNOPS, b, 0x7b), F12x, K::None), + 0x90..=0xaf => op(pick(&BINOPS, b, 0x90), F23x, K::None), + 0xb0..=0xcf => op(pick(&BINOPS_2ADDR, b, 0xb0), F12x, K::None), + 0xd0..=0xd7 => op(pick(&LIT16, b, 0xd0), F22s, K::None), + 0xd8..=0xe2 => op(pick(&LIT8, b, 0xd8), F22b, K::None), + 0xfa => op("invoke-polymorphic", F45cc, K::Method), + 0xfb => op("invoke-polymorphic/range", F4rcc, K::Method), + 0xfc => op("invoke-custom", F35c, K::CallSite), + 0xfd => op("invoke-custom/range", F3rc, K::CallSite), + 0xfe => op("const-method-handle", F21c, K::MethodHandle), + 0xff => op("const-method-type", F21c, K::Proto), + _ => UNUSED, + } +} + +/// Switch and array payloads. +#[derive(Debug, Clone, PartialEq, Eq, Serialize)] +#[serde(tag = "kind", rename_all = "kebab-case")] +pub enum Payload { + PackedSwitch { first_key: i32, targets: Vec }, + SparseSwitch { keys: Vec, targets: Vec }, + FillArrayData { element_width: u16, count: u32, data: Vec }, +} + +/// One decoded instruction. +#[derive(Debug, Clone, PartialEq, Eq, Serialize)] +pub struct Insn { + /// Offset in 16-bit code units from the start of the method's code. + pub offset: u32, + pub opcode: u8, + pub name: &'static str, + /// Length in code units. + pub units: u32, + /// Registers in operand order (for ranges: every register in the range). + pub regs: Vec, + /// True for `/range` forms. + pub range: bool, + #[serde(skip_serializing_if = "Option::is_none")] + pub literal: Option, + /// Absolute branch or payload target, in code units. + #[serde(skip_serializing_if = "Option::is_none")] + pub target: Option, + pub index_kind: IndexKind, + #[serde(skip_serializing_if = "Option::is_none")] + pub index: Option, + /// Second index (the proto of `invoke-polymorphic`). + #[serde(skip_serializing_if = "Option::is_none")] + pub index2: Option, + #[serde(skip_serializing_if = "Option::is_none")] + pub payload: Option, +} + +/// Most entries decoded from one payload. +const MAX_PAYLOAD: usize = 65_536; + +fn u32_at(code: &[u16], i: usize) -> Option { + Some(u32::from(*code.get(i)?) | (u32::from(*code.get(i + 1)?) << 16)) +} + +/// Decode a payload pseudo-instruction at `pc`; returns it and its length in units. +fn payload(code: &[u16], pc: usize) -> Option<(Payload, usize)> { + let ident = *code.get(pc)?; + match ident { + 0x0100 => { + let size = usize::from(*code.get(pc + 1)?); + let first_key = u32_at(code, pc + 2)? as i32; + let mut targets = Vec::with_capacity(size.min(MAX_PAYLOAD)); + for i in 0..size.min(MAX_PAYLOAD) { + targets.push(u32_at(code, pc + 4 + i * 2)? as i32); + } + Some((Payload::PackedSwitch { first_key, targets }, size * 2 + 4)) + } + 0x0200 => { + let size = usize::from(*code.get(pc + 1)?); + let mut keys = Vec::with_capacity(size.min(MAX_PAYLOAD)); + let mut targets = Vec::with_capacity(size.min(MAX_PAYLOAD)); + for i in 0..size.min(MAX_PAYLOAD) { + keys.push(u32_at(code, pc + 2 + i * 2)? as i32); + targets.push(u32_at(code, pc + 2 + size * 2 + i * 2)? as i32); + } + Some((Payload::SparseSwitch { keys, targets }, size * 4 + 2)) + } + 0x0300 => { + let width = *code.get(pc + 1)?; + let count = u32_at(code, pc + 2)?; + let bytes = usize::from(width).checked_mul(count as usize)?; + let units = bytes.checked_add(1)? / 2 + 4; + if pc.checked_add(units)? > code.len() { + return None; + } + let mut data = Vec::with_capacity(bytes.min(MAX_PAYLOAD)); + for i in 0..bytes.min(MAX_PAYLOAD) { + let u = *code.get(pc + 4 + i / 2)?; + data.push(if i % 2 == 0 { u as u8 } else { (u >> 8) as u8 }); + } + Some((Payload::FillArrayData { element_width: width, count, data }, units)) + } + _ => None, + } +} + +/// Decode one instruction at `pc`, or `None` when it runs past the end. +pub fn decode_one(code: &[u16], pc: usize) -> Option { + use Fmt::*; + let u0 = *code.get(pc)?; + let b = (u0 & 0xff) as u8; + let hi = (u0 >> 8) as u8; + if b == 0 && hi != 0 { + let (p, units) = payload(code, pc)?; + let name = match p { + Payload::PackedSwitch { .. } => "packed-switch-payload", + Payload::SparseSwitch { .. } => "sparse-switch-payload", + Payload::FillArrayData { .. } => "array-data-payload", + }; + return Some(Insn { + offset: pc as u32, + opcode: 0, + name, + units: units as u32, + regs: vec![], + range: false, + literal: None, + target: None, + index_kind: IndexKind::None, + index: None, + index2: None, + payload: Some(p), + }); + } + let o = opcode(b); + let n = o.fmt.units(); + if pc.checked_add(n)? > code.len() { + return None; + } + let u = |i: usize| code.get(pc + i).copied().unwrap_or(0); + let a4 = u32::from(hi & 0x0f); + let b4 = u32::from(hi >> 4); + let aa = u32::from(hi); + let rel = |d: i64| pc as i64 + d; + let mut insn = Insn { + offset: pc as u32, + opcode: b, + name: o.name, + units: n as u32, + regs: vec![], + range: false, + literal: None, + target: None, + index_kind: o.index, + index: None, + index2: None, + payload: None, + }; + match o.fmt { + F10x => {} + F12x => insn.regs = vec![a4, b4], + F11n => { + insn.regs = vec![a4]; + insn.literal = Some(i64::from((hi as i8) >> 4)); + } + F11x => insn.regs = vec![aa], + F10t => insn.target = Some(rel(i64::from(hi as i8))), + F20t => insn.target = Some(rel(i64::from(u(1) as i16))), + F22x => insn.regs = vec![aa, u32::from(u(1))], + F21t => { + insn.regs = vec![aa]; + insn.target = Some(rel(i64::from(u(1) as i16))); + } + F21s => { + insn.regs = vec![aa]; + insn.literal = Some(i64::from(u(1) as i16)); + } + F21h => { + insn.regs = vec![aa]; + let v = i64::from(u(1) as i16); + insn.literal = Some(if b == 0x19 { v << 48 } else { v << 16 }); + } + F21c => { + insn.regs = vec![aa]; + insn.index = Some(u32::from(u(1))); + } + F23x => insn.regs = vec![aa, u32::from(u(1) & 0xff), u32::from(u(1) >> 8)], + F22b => { + insn.regs = vec![aa, u32::from(u(1) & 0xff)]; + insn.literal = Some(i64::from((u(1) >> 8) as u8 as i8)); + } + F22t => { + insn.regs = vec![a4, b4]; + insn.target = Some(rel(i64::from(u(1) as i16))); + } + F22s => { + insn.regs = vec![a4, b4]; + insn.literal = Some(i64::from(u(1) as i16)); + } + F22c => { + insn.regs = vec![a4, b4]; + insn.index = Some(u32::from(u(1))); + } + F30t => insn.target = Some(rel(i64::from((u32::from(u(1)) | (u32::from(u(2)) << 16)) as i32))), + F32x => insn.regs = vec![u32::from(u(1)), u32::from(u(2))], + F31i => { + insn.regs = vec![aa]; + insn.literal = Some(i64::from((u32::from(u(1)) | (u32::from(u(2)) << 16)) as i32)); + } + F31t => { + insn.regs = vec![aa]; + insn.target = Some(rel(i64::from((u32::from(u(1)) | (u32::from(u(2)) << 16)) as i32))); + } + F31c => { + insn.regs = vec![aa]; + insn.index = Some(u32::from(u(1)) | (u32::from(u(2)) << 16)); + } + F35c | F45cc => { + let count = b4.min(5) as usize; + let g = a4; + let w = u(2); + let all = [u32::from(w & 0xf), u32::from((w >> 4) & 0xf), u32::from((w >> 8) & 0xf), u32::from(w >> 12), g]; + insn.regs = all.iter().take(count).copied().collect(); + insn.index = Some(u32::from(u(1))); + if o.fmt == F45cc { + insn.index2 = Some(u32::from(u(3))); + } + } + F3rc | F4rcc => { + let first = u32::from(u(2)); + insn.regs = (0..aa).map(|i| first.saturating_add(i)).collect(); + insn.range = true; + insn.index = Some(u32::from(u(1))); + if o.fmt == F4rcc { + insn.index2 = Some(u32::from(u(3))); + } + } + F51l => { + insn.regs = vec![aa]; + let v = u64::from(u(1)) | (u64::from(u(2)) << 16) | (u64::from(u(3)) << 32) | (u64::from(u(4)) << 48); + insn.literal = Some(v as i64); + } + } + Some(insn) +} + +/// Decode a whole method body, attaching each switch/array payload to the instruction that +/// references it. Stops at `max` instructions. +pub fn decode(code: &[u16], max: usize) -> (Vec, bool) { + let mut out = Vec::new(); + let mut pc = 0usize; + let mut complete = true; + while pc < code.len() { + if out.len() >= max { + complete = false; + break; + } + match decode_one(code, pc) { + Some(i) => { + pc += (i.units as usize).max(1); + out.push(i); + } + None => { + complete = false; + break; + } + } + } + // Attach payloads to their users (31t formats). + let payloads: Vec<(i64, Payload)> = out.iter().filter_map(|i| i.payload.clone().map(|p| (i64::from(i.offset), p))).collect(); + for i in out.iter_mut().filter(|i| matches!(i.opcode, 0x26 | 0x2b | 0x2c)) { + if let Some(t) = i.target + && let Some((_, p)) = payloads.iter().find(|(o, _)| *o == t) + { + i.payload = Some(p.clone()); + } + } + (out, complete) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn table_is_complete() { + let mut named = 0; + for b in 0..=255u8 { + let o = opcode(b); + if o.name != "unused" { + named += 1; + } + } + // 256 slots minus the 0x3e-0x43, 0x73, 0x79-0x7a and 0xe3-0xf9 holes. + assert_eq!(named, 256 - 6 - 1 - 2 - 23); + assert_eq!(opcode(0x6e).name, "invoke-virtual"); + assert_eq!(opcode(0x8f).name, "int-to-short"); + assert_eq!(opcode(0xaf).name, "rem-double"); + assert_eq!(opcode(0xcf).name, "rem-double/2addr"); + assert_eq!(opcode(0xe2).name, "ushr-int/lit8"); + } + + #[test] + fn decodes_formats() { + // const/4 v1, #-1 ; invoke-static {v0, v1}, meth@5 ; packed-switch v0, +4 ; return-void + // payload: packed, size 2, first 10, targets 1, 2 + let code: Vec = vec![0xf112, 0x2071, 5, 0x0010, 0x002b, 4, 0, 0x000e, 0x0100, 2, 10, 0, 1, 0, 2, 0]; + let (ins, complete) = decode(&code, 100); + assert!(complete); + assert_eq!(ins[0].name, "const/4"); + assert_eq!(ins[0].literal, Some(-1)); + assert_eq!(ins[0].regs, vec![1]); + assert_eq!(ins[1].name, "invoke-static"); + assert_eq!(ins[1].regs, vec![0, 1]); + assert_eq!(ins[1].index, Some(5)); + assert_eq!(ins[2].name, "packed-switch"); + assert_eq!(ins[2].target, Some(8)); + assert_eq!(ins[2].payload, Some(Payload::PackedSwitch { first_key: 10, targets: vec![1, 2] })); + assert_eq!(ins[4].name, "packed-switch-payload"); + // const-wide v0, 0x1122334455667788 + let (w, _) = decode(&[0x0018, 0x7788, 0x5566, 0x3344, 0x1122], 10); + assert_eq!(w[0].literal, Some(0x1122_3344_5566_7788)); + // fill-array-data payload width 1 count 3 + let (f, _) = decode(&[0x0300, 1, 3, 0, 0x0201, 0x0003], 10); + assert_eq!(f[0].payload, Some(Payload::FillArrayData { element_width: 1, count: 3, data: vec![1, 2, 3] })); + // invoke-virtual/range {v4..v6} + let (r, _) = decode(&[0x0374, 9, 4], 10); + assert_eq!(r[0].regs, vec![4, 5, 6]); + assert!(r[0].range); + } + + #[test] + fn hostile() { + for seed in 0..200 { + let n = craft_anything_testkit::noise(seed, 256); + let code: Vec = n.as_chunks::<2>().0.iter().map(|c| u16::from_le_bytes(*c)).collect(); + let _ = decode(&code, 1000); + } + let _ = decode(&[0x0300, 0xffff, 0xffff, 0xffff], 10); + let _ = decode(&[0x0200, 0xffff], 10); + let _ = decode(&[0x0018], 10); + } +} From b4e455d01758837e2e9f5a3bf9b29ea6f34be1ad Mon Sep 17 00:00:00 2001 From: BFlat Date: Tue, 17 Nov 2026 08:38:14 -0500 Subject: [PATCH 03/37] dex: More format parsers keep to their declared lengths and refuse impossible values (#722) Port Craft Anything b9ca099903aeef5d4b33a7e83e8e7062ab94c65a reader and opcode decoder. --- crates/dex/src/dex.rs | 17 +++++------------ crates/dex/src/dex_ops.rs | 14 ++++++++++++-- 2 files changed, 17 insertions(+), 14 deletions(-) diff --git a/crates/dex/src/dex.rs b/crates/dex/src/dex.rs index e46d97b5b..b01a1b247 100644 --- a/crates/dex/src/dex.rs +++ b/crates/dex/src/dex.rs @@ -148,18 +148,7 @@ pub fn mutf8(r: &Reader<'_>, mut at: usize, max_units: usize) -> (String, usize) if b0 == 0 { break; } - let (u, n) = if b0 < 0x80 { - (u16::from(b0), 1) - } else if b0 & 0xe0 == 0xc0 { - let b1 = r.u8(at + 1).unwrap_or(0); - ((u16::from(b0 & 0x1f) << 6) | u16::from(b1 & 0x3f), 2) - } else if b0 & 0xf0 == 0xe0 { - let b1 = r.u8(at + 1).unwrap_or(0); - let b2 = r.u8(at + 2).unwrap_or(0); - ((u16::from(b0 & 0x0f) << 12) | (u16::from(b1 & 0x3f) << 6) | u16::from(b2 & 0x3f), 3) - } else { - (0xfffd, 1) - }; + let (u, n) = crate::bytes::mutf8_unit(r.data().get(at..).unwrap_or_default()); units.push(u); at = at.saturating_add(n); consumed += n; @@ -173,6 +162,10 @@ pub fn sleb128(r: &Reader<'_>, off: usize) -> Option<(i64, usize)> { let mut shift = 0u32; for i in 0..10usize { let b = r.u8(off.checked_add(i)?)?; + // Only one value bit remains in the tenth byte; the rest must extend its sign. + if i == 9 && !matches!(b, 0x00 | 0x7f) { + return None; + } result |= i64::from(b & 0x7f).checked_shl(shift)?; shift += 7; if b & 0x80 == 0 { diff --git a/crates/dex/src/dex_ops.rs b/crates/dex/src/dex_ops.rs index 139ad77ac..53fbf1d05 100644 --- a/crates/dex/src/dex_ops.rs +++ b/crates/dex/src/dex_ops.rs @@ -384,6 +384,9 @@ fn payload(code: &[u16], pc: usize) -> Option<(Payload, usize)> { } 0x0300 => { let width = *code.get(pc + 1)?; + if !matches!(width, 1 | 2 | 4 | 8) { + return None; + } let count = u32_at(code, pc + 2)?; let bytes = usize::from(width).checked_mul(count as usize)?; let units = bytes.checked_add(1)? / 2 + 4; @@ -513,7 +516,10 @@ pub fn decode_one(code: &[u16], pc: usize) -> Option { insn.index = Some(u32::from(u(1)) | (u32::from(u(2)) << 16)); } F35c | F45cc => { - let count = b4.min(5) as usize; + if b4 > 5 { + return None; + } + let count = b4 as usize; let g = a4; let w = u(2); let all = [u32::from(w & 0xf), u32::from((w >> 4) & 0xf), u32::from((w >> 8) & 0xf), u32::from(w >> 12), g]; @@ -525,7 +531,11 @@ pub fn decode_one(code: &[u16], pc: usize) -> Option { } F3rc | F4rcc => { let first = u32::from(u(2)); - insn.regs = (0..aa).map(|i| first.saturating_add(i)).collect(); + let end = first.checked_add(aa)?; + if end > u32::from(u16::MAX) + 1 { + return None; + } + insn.regs = (first..end).collect(); insn.range = true; insn.index = Some(u32::from(u(1))); if o.fmt == F4rcc { From 77e7878f7bbc38fffd1ec024182f56098ca4d92d Mon Sep 17 00:00:00 2001 From: Afloat <132809511+Afloat16@users.noreply.github.com> Date: Tue, 17 Nov 2026 08:38:14 -0500 Subject: [PATCH 04/37] dex: Address the parser review findings from #722 (#766) Port Craft Anything eab6a0f01bf9fc3a36798d322e4442e169394dfc reader and opcode decoder. --- crates/dex/src/dex.rs | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/crates/dex/src/dex.rs b/crates/dex/src/dex.rs index b01a1b247..6b23d2e78 100644 --- a/crates/dex/src/dex.rs +++ b/crates/dex/src/dex.rs @@ -156,14 +156,14 @@ pub fn mutf8(r: &Reader<'_>, mut at: usize, max_units: usize) -> (String, usize) (String::from_utf16_lossy(&units), consumed) } -/// Signed LEB128 at `off`: (value, bytes). +/// Signed 32-bit DEX LEB128 at `off`: (value, bytes), using at most five bytes. pub fn sleb128(r: &Reader<'_>, off: usize) -> Option<(i64, usize)> { let mut result = 0i64; let mut shift = 0u32; - for i in 0..10usize { + for i in 0..5usize { let b = r.u8(off.checked_add(i)?)?; - // Only one value bit remains in the tenth byte; the rest must extend its sign. - if i == 9 && !matches!(b, 0x00 | 0x7f) { + // Four value bits remain in byte five; the other bits must extend the sign. + if i == 4 && !matches!(b, 0x00..=0x07 | 0x78..=0x7f) { return None; } result |= i64::from(b & 0x7f).checked_shl(shift)?; From 0373b7f8e347bd4f284a0522365b19520547495c Mon Sep 17 00:00:00 2001 From: Afloat Date: Tue, 17 Nov 2026 08:38:14 -0500 Subject: [PATCH 05/37] dex: Preserve DEX boundaries when member or handler lists are capped (R3.12) (#1388) Port Craft Anything 34d9450b75f402217a7243c04d6c5ed3d2d3f8d4 reader and opcode decoder. --- crates/dex/src/dex.rs | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/crates/dex/src/dex.rs b/crates/dex/src/dex.rs index 6b23d2e78..c4076dfc8 100644 --- a/crates/dex/src/dex.rs +++ b/crates/dex/src/dex.rs @@ -523,6 +523,9 @@ impl<'a> Dex<'a> { } } } + if count > MAX_MEMBERS as u32 { + return cd; + } } cd.complete = true; cd @@ -563,6 +566,7 @@ impl<'a> Dex<'a> { handlers.push(Handler { exception: Some(self.type_desc(t as u32)), address: addr as u32 }); } if size <= 0 + && handlers.len() as u64 == size.unsigned_abs() && let Some((addr, _)) = r.uleb128(p) { handlers.push(Handler { exception: None, address: addr as u32 }); From 794b884096e75083a6ab22b936185cb0ece3cd46 Mon Sep 17 00:00:00 2001 From: Afloat Date: Tue, 17 Nov 2026 08:38:14 -0500 Subject: [PATCH 06/37] dex: Bound retained DEX payload attachments (R3.12) (#1548) Port Craft Anything 1ebdb78760d6bfd31f1a70e6389e0d441adb3d2e reader and opcode decoder. --- crates/dex/src/dex_ops.rs | 60 +++++++++++++++++++++++++++++++++------ 1 file changed, 52 insertions(+), 8 deletions(-) diff --git a/crates/dex/src/dex_ops.rs b/crates/dex/src/dex_ops.rs index 53fbf1d05..71095fc75 100644 --- a/crates/dex/src/dex_ops.rs +++ b/crates/dex/src/dex_ops.rs @@ -354,6 +354,25 @@ pub struct Insn { /// Most entries decoded from one payload. const MAX_PAYLOAD: usize = 65_536; +/// Maximum payload bytes retained by one decoded method, including copies attached to users. +pub const DEFAULT_MAX_PAYLOAD_BYTES: usize = 64 << 20; + +impl Payload { + fn retained_bytes(&self) -> usize { + match self { + Self::PackedSwitch { targets, .. } => targets.len().saturating_mul(4), + Self::SparseSwitch { keys, targets } => keys.len().saturating_add(targets.len()).saturating_mul(4), + Self::FillArrayData { data, .. } => data.len(), + } + } + + fn complete(&self) -> bool { + match self { + Self::FillArrayData { element_width, count, data } => u64::from(*element_width) * u64::from(*count) == data.len() as u64, + _ => true, + } + } +} fn u32_at(code: &[u16], i: usize) -> Option { Some(u32::from(*code.get(i)?) | (u32::from(*code.get(i + 1)?) << 16)) @@ -552,19 +571,36 @@ pub fn decode_one(code: &[u16], pc: usize) -> Option { } /// Decode a whole method body, attaching each switch/array payload to the instruction that -/// references it. Stops at `max` instructions. +/// references it. Stops at `max` instructions and caps all retained payload copies together. pub fn decode(code: &[u16], max: usize) -> (Vec, bool) { + decode_with_payload_limit(code, max, DEFAULT_MAX_PAYLOAD_BYTES) +} + +/// Decode with an explicit aggregate payload byte budget. Payloads that do not fit are omitted; +/// their instruction metadata remains and the returned completeness flag is false. A source +/// payload and every attached copy consume the same budget, before the copy is allocated. +pub fn decode_with_payload_limit(code: &[u16], max: usize, max_payload_bytes: usize) -> (Vec, bool) { let mut out = Vec::new(); let mut pc = 0usize; let mut complete = true; + let mut bytes_left = max_payload_bytes; while pc < code.len() { if out.len() >= max { complete = false; break; } match decode_one(code, pc) { - Some(i) => { + Some(mut i) => { pc += (i.units as usize).max(1); + if let Some(p) = &i.payload { + complete &= p.complete(); + if let Some(left) = bytes_left.checked_sub(p.retained_bytes()) { + bytes_left = left; + } else { + i.payload = None; + complete = false; + } + } out.push(i); } None => { @@ -574,12 +610,20 @@ pub fn decode(code: &[u16], max: usize) -> (Vec, bool) { } } // Attach payloads to their users (31t formats). - let payloads: Vec<(i64, Payload)> = out.iter().filter_map(|i| i.payload.clone().map(|p| (i64::from(i.offset), p))).collect(); - for i in out.iter_mut().filter(|i| matches!(i.opcode, 0x26 | 0x2b | 0x2c)) { - if let Some(t) = i.target - && let Some((_, p)) = payloads.iter().find(|(o, _)| *o == t) - { - i.payload = Some(p.clone()); + // The decoder visits offsets in order. Index their positions without copying any payload. + let payloads: Vec<(i64, usize)> = out.iter().enumerate().filter(|(_, i)| i.payload.is_some()).map(|(n, i)| (i64::from(i.offset), n)).collect(); + for n in 0..out.len() { + let Some(target) = out.get(n).filter(|i| matches!(i.opcode, 0x26 | 0x2b | 0x2c)).and_then(|i| i.target) else { continue }; + let Ok(position) = payloads.binary_search_by_key(&target, |(offset, _)| *offset) else { continue }; + let Some(payload) = payloads.get(position).and_then(|(_, index)| out.get(*index)).and_then(|i| i.payload.as_ref()) else { continue }; + let Some(left) = bytes_left.checked_sub(payload.retained_bytes()) else { + complete = false; + continue; + }; + bytes_left = left; + let copy = payload.clone(); + if let Some(instruction) = out.get_mut(n) { + instruction.payload = Some(copy); } } (out, complete) From e1eae62fe29d52e6f5e79d0742fd587f54b02e8b Mon Sep 17 00:00:00 2001 From: BFlat Date: Tue, 17 Nov 2026 08:39:25 -0500 Subject: [PATCH 07/37] dex: retain array_widths regressions Source crates/formats/tests/dex_array_widths.rs at b9ca099903aeef5d4b33a7e83e8e7062ab94c65a. Imports adapted only. --- crates/dex/src/regressions/array_widths.rs | 39 ++++++++++++++++++++++ 1 file changed, 39 insertions(+) create mode 100644 crates/dex/src/regressions/array_widths.rs diff --git a/crates/dex/src/regressions/array_widths.rs b/crates/dex/src/regressions/array_widths.rs new file mode 100644 index 000000000..37524b002 --- /dev/null +++ b/crates/dex/src/regressions/array_widths.rs @@ -0,0 +1,39 @@ +use crate::dex_ops::{Payload, decode, decode_one}; + +#[test] +fn zero_width_does_not_describe_a_huge_complete_array() { + let code = [0x0300, 0, 0xffff, 0xffff]; + assert!(decode_one(&code, 0).is_none()); + assert!(!decode(&code, 16).1); +} + +#[test] +fn unsupported_element_widths_are_refused_even_for_empty_arrays() { + for width in [0, 3, 5, 6, 7, 9, 16, u16::MAX] { + assert!(decode_one(&[0x0300, width, 0, 0], 0).is_none(), "width {width}"); + } +} + +#[test] +fn all_primitive_widths_and_odd_byte_padding_still_decode() { + for width in [1u16, 2, 4, 8] { + let count = 3u32; + let bytes = usize::from(width) * count as usize; + let mut code = vec![0x0300, width, count as u16, 0]; + code.resize(4 + bytes.div_ceil(2), 0x2211); + let instruction = decode_one(&code, 0).unwrap(); + assert_eq!(instruction.units as usize, code.len()); + match instruction.payload.unwrap() { + Payload::FillArrayData { element_width, count: decoded, data } => { + assert_eq!(element_width, width); + assert_eq!(decoded, count); + assert_eq!(data.len(), bytes); + assert_eq!(data[0], 0x11); + } + other => panic!("unexpected payload {other:?}"), + } + assert!(decode_one(&[0x0300, width, 0, 0], 0).is_some()); + code.pop(); + assert!(decode_one(&code, 0).is_none()); + } +} From 570e8bc8735cf6250adb1098dbe2244b1cb6200c Mon Sep 17 00:00:00 2001 From: Afloat Date: Tue, 17 Nov 2026 08:39:25 -0500 Subject: [PATCH 08/37] dex: retain capped_table_boundaries regressions Source crates/formats/tests/dex_capped_table_boundaries.rs at 34d9450b75f402217a7243c04d6c5ed3d2d3f8d4. Imports adapted only. --- .../regressions/capped_table_boundaries.rs | 114 ++++++++++++++++++ 1 file changed, 114 insertions(+) create mode 100644 crates/dex/src/regressions/capped_table_boundaries.rs diff --git a/crates/dex/src/regressions/capped_table_boundaries.rs b/crates/dex/src/regressions/capped_table_boundaries.rs new file mode 100644 index 000000000..7fbb419f5 --- /dev/null +++ b/crates/dex/src/regressions/capped_table_boundaries.rs @@ -0,0 +1,114 @@ +use crate::dex::{self, ClassDef, Code}; + +const MEMBER_CAP: usize = 65_536; +const HANDLER_CAP: usize = 256; + +fn uleb(mut value: u32, bytes: &mut Vec) { + loop { + let byte = (value & 0x7f) as u8; + value >>= 7; + bytes.push(byte | if value == 0 { 0 } else { 0x80 }); + if value == 0 { + break; + } + } +} + +fn sleb(mut value: i32, bytes: &mut Vec) { + loop { + let byte = value as u8 & 0x7f; + value >>= 7; + let done = (value == 0 && byte & 0x40 == 0) || (value == -1 && byte & 0x40 != 0); + bytes.push(byte | if done { 0 } else { 0x80 }); + if done { + break; + } + } +} + +fn header() -> Vec { + let mut bytes = vec![0; 0x70]; + bytes[..8].copy_from_slice(b"dex\n035\0"); + bytes[36..40].copy_from_slice(&0x70u32.to_le_bytes()); + bytes[40..44].copy_from_slice(&0x1234_5678u32.to_le_bytes()); + bytes +} + +fn class_data(count: usize) -> dex::ClassData { + let mut bytes = header(); + for n in [count as u32, 0, 1, 0] { + uleb(n, &mut bytes); + } + bytes.extend_from_slice(&[0, 1].repeat(count)); + bytes.extend_from_slice(&[3, 9, 7]); + let len = bytes.len() as u32; + bytes[32..36].copy_from_slice(&len.to_le_bytes()); + let class = ClassDef { + class_idx: 0, + access: 0, + superclass_idx: 0, + interfaces_off: 0, + source_file_idx: 0, + annotations_off: 0, + class_data_off: 0x70, + static_values_off: 0, + }; + dex::parse(&bytes).unwrap().class_data(&class) +} + +fn code(size: i32, payload: &[u8]) -> Code { + let mut bytes = header(); + bytes.extend_from_slice(&[1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 8, 0, 0, 0]); + bytes.extend_from_slice(&[0; 16]); + bytes.extend_from_slice(&[0, 0, 0, 0, 1, 0, 1, 0]); + bytes.push(1); + sleb(size, &mut bytes); + bytes.extend_from_slice(payload); + let len = bytes.len() as u32; + bytes[32..36].copy_from_slice(&len.to_le_bytes()); + dex::parse(&bytes).unwrap().code(0x70).unwrap() +} + +#[test] +fn capped_class_members_do_not_become_the_next_group() { + let data = class_data(MEMBER_CAP + 1); + assert_eq!(data.static_fields.len(), MEMBER_CAP); + assert!(data.direct_methods.is_empty()); + assert!(!data.complete); +} + +#[test] +fn an_exact_member_limit_keeps_the_following_group() { + let data = class_data(MEMBER_CAP); + assert_eq!(data.static_fields.len(), MEMBER_CAP); + assert!(data.complete); + assert_eq!(data.direct_methods, [dex::EncodedMethod { method_idx: 3, access: 9, code_off: 7 }]); +} + +#[test] +fn an_unread_typed_handler_is_not_a_catch_all() { + let mut payload = [0, 1].repeat(HANDLER_CAP + 1); + payload.push(7); + let parsed = code(-((HANDLER_CAP + 1) as i32), &payload); + assert_eq!(parsed.tries[0].handlers.len(), HANDLER_CAP); + assert!(parsed.tries[0].handlers.iter().all(|handler| handler.exception.is_some() && handler.address == 1)); +} + +#[test] +fn an_incomplete_typed_handler_cannot_supply_a_catch_all_address() { + let parsed = code(-2, &[0, 1, 0]); + assert_eq!(parsed.tries[0].handlers.len(), 1); + assert!(parsed.tries[0].handlers[0].exception.is_some()); + assert_eq!(parsed.tries[0].handlers[0].address, 1); +} + +#[test] +fn complete_typed_lists_keep_their_real_catch_all() { + for count in [0, 1, HANDLER_CAP] { + let mut payload = [0, 1].repeat(count); + payload.push(7); + let parsed = code(-(count as i32), &payload); + assert_eq!(parsed.tries[0].handlers.len(), count + 1); + assert_eq!(parsed.tries[0].handlers.last(), Some(&dex::Handler { exception: None, address: 7 })); + } +} From 79ad1aff6fa1758c91e53a9001baf4f38e5c028e Mon Sep 17 00:00:00 2001 From: BFlat Date: Tue, 17 Nov 2026 08:39:25 -0500 Subject: [PATCH 09/37] dex: retain invoke_registers regressions Source crates/formats/tests/dex_invoke_registers.rs at b9ca099903aeef5d4b33a7e83e8e7062ab94c65a. Imports adapted only. --- .../dex/src/regressions/invoke_registers.rs | 33 +++++++++++++++++++ 1 file changed, 33 insertions(+) create mode 100644 crates/dex/src/regressions/invoke_registers.rs diff --git a/crates/dex/src/regressions/invoke_registers.rs b/crates/dex/src/regressions/invoke_registers.rs new file mode 100644 index 000000000..c2c6faab6 --- /dev/null +++ b/crates/dex/src/regressions/invoke_registers.rs @@ -0,0 +1,33 @@ +use crate::dex_ops::{decode, decode_one}; + +#[test] +fn fixed_register_lists_cannot_claim_more_than_five_arguments() { + for op in [0x24u16, 0x6e, 0x6f, 0x70, 0x71, 0x72, 0xfa, 0xfc] { + for count in 6..=15 { + let code = [(count << 12) | op, 1, 0x4321, 2]; + assert!(decode_one(&code, 0).is_none(), "opcode {op:#x}, count {count}"); + assert!(!decode(&code, 16).1); + } + } +} + +#[test] +fn range_arguments_cannot_leave_the_encoded_register_space() { + for op in [0x25u16, 0x74, 0x75, 0x76, 0x77, 0x78, 0xfb, 0xfd] { + assert!(decode_one(&[0x0200 | op, 1, u16::MAX, 2], 0).is_none(), "{op:#x}"); + assert!(decode_one(&[0xff00 | op, 1, u16::MAX - 1, 2], 0).is_none(), "{op:#x}"); + } +} + +#[test] +fn zero_and_boundary_register_lists_remain_valid() { + let fixed = decode_one(&[0x5571, 1, 0x4321], 0).unwrap(); + assert_eq!(fixed.regs, vec![1, 2, 3, 4, 5]); + assert!(decode_one(&[0x0071, 1, 0], 0).unwrap().regs.is_empty()); + let range = decode_one(&[0x0277, 1, u16::MAX - 1], 0).unwrap(); + assert_eq!(range.regs, vec![65534, 65535]); + assert!(decode_one(&[0x0077, 1, u16::MAX], 0).unwrap().regs.is_empty()); + let polymorphic = decode_one(&[0x01fb, 1, u16::MAX, 2], 0).unwrap(); + assert_eq!(polymorphic.regs, vec![65535]); + assert_eq!(polymorphic.index2, Some(2)); +} From 7cd3dcfdece717c73edc7463ac09fbeaf6ddb9fd Mon Sep 17 00:00:00 2001 From: Afloat Date: Tue, 17 Nov 2026 08:39:25 -0500 Subject: [PATCH 10/37] dex: retain payload_budgets regressions Source crates/formats/tests/dex_payload_budgets.rs at 1ebdb78760d6bfd31f1a70e6389e0d441adb3d2e. Imports adapted only. --- crates/dex/src/regressions/payload_budgets.rs | 88 +++++++++++++++++++ 1 file changed, 88 insertions(+) create mode 100644 crates/dex/src/regressions/payload_budgets.rs diff --git a/crates/dex/src/regressions/payload_budgets.rs b/crates/dex/src/regressions/payload_budgets.rs new file mode 100644 index 000000000..8680373a4 --- /dev/null +++ b/crates/dex/src/regressions/payload_budgets.rs @@ -0,0 +1,88 @@ +use crate::dex_ops::{self, Payload}; + +fn arrays(references: usize, bytes: usize) -> Vec { + let mut code = Vec::new(); + let offset = (references * 3).next_multiple_of(2); + for n in 0..references { + let relative = u32::try_from(offset - n * 3).unwrap(); + code.extend([0x0026, relative as u16, (relative >> 16) as u16]); + } + code.resize(offset, 0); + let count = u32::try_from(bytes).unwrap(); + code.extend([0x0300, 1, count as u16, (count >> 16) as u16]); + code.resize(code.len() + bytes.div_ceil(2), 0x5a5a); + code +} + +fn bytes(rows: &[dex_ops::Insn]) -> usize { + rows.iter() + .map(|i| match i.payload.as_ref() { + Some(Payload::FillArrayData { data, .. }) => data.len(), + Some(Payload::PackedSwitch { targets, .. }) => targets.len() * 4, + Some(Payload::SparseSwitch { keys, targets }) => (keys.len() + targets.len()) * 4, + None => 0, + }) + .sum() +} + +#[test] +fn shared_arrays_charge_the_source_and_each_attached_copy() { + let code = arrays(4, 8); + let (rows, complete) = dex_ops::decode_with_payload_limit(&code, 100, 24); + assert!(!complete); + assert_eq!(bytes(&rows), 24); + assert!(rows[0].payload.is_some() && rows[1].payload.is_some()); + assert!(rows[2].payload.is_none() && rows[3].payload.is_none()); + assert!(rows.last().unwrap().payload.is_some()); + let (full, complete) = dex_ops::decode_with_payload_limit(&code, 100, 40); + assert!(complete); + assert_eq!(bytes(&full), 40); +} + +#[test] +fn zero_budget_keeps_offsets_and_payload_instruction_metadata() { + let code = arrays(2, 8); + let (rows, complete) = dex_ops::decode_with_payload_limit(&code, 100, 0); + assert!(!complete); + assert_eq!(rows.iter().map(|i| i.offset).collect::>(), [0, 3, 6]); + assert_eq!(rows[2].name, "array-data-payload"); + assert_eq!(rows[2].units, 8); + assert!(rows.iter().all(|i| i.payload.is_none())); + assert!(dex_ops::decode_with_payload_limit(&[0x000e], 100, 0).1); +} + +#[test] +fn both_switch_tables_are_accounted_and_backward_references_work() { + // packed table: one target; sparse table: one key and one target; users follow the tables. + let code = [0x0100, 1, 7, 0, 1, 0, 0x0200, 1, 9, 0, 2, 0, 0x002b, 0xfff4, 0xffff, 0x002c, 0xfff7, 0xffff]; + let (rows, complete) = dex_ops::decode_with_payload_limit(&code, 100, 24); + assert!(complete); + assert_eq!(rows[2].payload, Some(Payload::PackedSwitch { first_key: 7, targets: vec![1] })); + assert_eq!(rows[3].payload, Some(Payload::SparseSwitch { keys: vec![9], targets: vec![2] })); + let (rows, complete) = dex_ops::decode_with_payload_limit(&code, 100, 16); + assert!(!complete); + assert!(rows[2].payload.is_some()); + assert!(rows[3].payload.is_none()); + assert_eq!(bytes(&rows), 16); +} + +#[test] +fn the_existing_per_array_cap_is_reported_as_partial() { + let (rows, complete) = dex_ops::decode(&arrays(1, 65_537), 100); + assert!(!complete); + assert_eq!(bytes(&rows), 2 * 65_536); + let (rows, complete) = dex_ops::decode(&arrays(1, 8), 1); + assert!(!complete); + assert_eq!(rows.len(), 1); + assert!(rows[0].payload.is_none()); +} + +#[test] +#[ignore = "memory regression: run separately with a 128 MiB address-space limit"] +fn repeated_array_references_stay_under_the_default_byte_budget() { + let code = arrays(2048, 65_536); + let (rows, complete) = dex_ops::decode(&code, 200_000); + assert!(!complete); + assert_eq!(rows.len(), 2049); + assert_eq!(bytes(&rows), dex_ops::DEFAULT_MAX_PAYLOAD_BYTES); +} From 4039bc76955a61b44ce0838ea8d92315cfd955e0 Mon Sep 17 00:00:00 2001 From: Afloat <132809511+Afloat16@users.noreply.github.com> Date: Tue, 17 Nov 2026 08:39:25 -0500 Subject: [PATCH 11/37] dex: retain signed_leb128 regressions Source crates/formats/tests/dex_signed_leb128.rs at eab6a0f01bf9fc3a36798d322e4442e169394dfc. Imports adapted only. --- crates/dex/src/regressions/signed_leb128.rs | 94 +++++++++++++++++++++ 1 file changed, 94 insertions(+) create mode 100644 crates/dex/src/regressions/signed_leb128.rs diff --git a/crates/dex/src/regressions/signed_leb128.rs b/crates/dex/src/regressions/signed_leb128.rs new file mode 100644 index 000000000..f38fd8db6 --- /dev/null +++ b/crates/dex/src/regressions/signed_leb128.rs @@ -0,0 +1,94 @@ +use crate::bytes::Reader; +use crate::dex::{self, Code, Handler, sleb128}; + +#[test] +fn rejects_invalid_fifth_byte_sign_extensions() { + for prefix in [0x80, 0xff] { + for last in 0x08..=0x77 { + let mut encoded = vec![prefix; 4]; + encoded.push(last); + assert_eq!(sleb128(&Reader::new(&encoded), 0), None, "last byte {last:#x}"); + } + } +} + +#[test] +fn retains_signed_32_bit_limits_and_ordinary_values() { + assert_eq!(sleb128(&Reader::new(&[0xff, 0xff, 0xff, 0xff, 0x07]), 0), Some((i64::from(i32::MAX), 5))); + assert_eq!(sleb128(&Reader::new(&[0x80, 0x80, 0x80, 0x80, 0x78]), 0), Some((i64::from(i32::MIN), 5))); + assert_eq!(sleb128(&Reader::new(&[0x9b, 0xf1, 0x59]), 0), Some((-624485, 3))); + assert_eq!(sleb128(&Reader::new(&[0xe5, 0x8e, 0x26]), 0), Some((624485, 3))); + assert_eq!(sleb128(&Reader::new(&[0xff, 0x7f]), 0), Some((-1, 2))); + assert_eq!(sleb128(&Reader::new(&[0x80, 0]), 0), Some((0, 2))); + assert_eq!(sleb128(&Reader::new(&[0x55, 0x7f, 0x55]), 1), Some((-1, 1))); +} + +#[test] +fn retains_valid_five_byte_sign_extensions() { + assert_eq!(sleb128(&Reader::new(&[0x80, 0x80, 0x80, 0x80, 0]), 0), Some((0, 5))); + assert_eq!(sleb128(&Reader::new(&[0x81, 0x80, 0x80, 0x80, 0]), 0), Some((1, 5))); + assert_eq!(sleb128(&Reader::new(&[0xff, 0xff, 0xff, 0xff, 0x7f]), 0), Some((-1, 5))); +} + +#[test] +fn rejects_values_longer_than_five_bytes() { + for (prefix, last) in [(0x80, 0), (0xff, 0x7f)] { + for length in [6, 10] { + let mut encoded = vec![prefix; length - 1]; + encoded.push(last); + assert_eq!(sleb128(&Reader::new(&encoded), 0), None, "{encoded:x?}"); + } + } +} + +#[test] +fn rejects_truncated_values_and_out_of_range_offsets() { + assert_eq!(sleb128(&Reader::new(&[0x80; 5]), 0), None); + assert_eq!(sleb128(&Reader::new(&[0x80]), 0), None); + assert_eq!(sleb128(&Reader::new(&[]), 0), None); + assert_eq!(sleb128(&Reader::new(&[0]), usize::MAX), None); +} + +fn code_with_handler(size: &[u8], payload: &[u8]) -> Code { + let mut bytes = vec![0; 0x70]; + bytes[..8].copy_from_slice(b"dex\n035\0"); + bytes[36..40].copy_from_slice(&0x70u32.to_le_bytes()); + bytes[40..44].copy_from_slice(&0x1234_5678u32.to_le_bytes()); + // Eight nop instructions and one try entry pointing to the first encoded handler. + bytes.extend_from_slice(&[1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 8, 0, 0, 0]); + bytes.extend_from_slice(&[0; 16]); + bytes.extend_from_slice(&[0, 0, 0, 0, 1, 0, 1, 0]); + bytes.push(1); + bytes.extend_from_slice(size); + bytes.extend_from_slice(payload); + let len = bytes.len() as u32; + bytes[32..36].copy_from_slice(&len.to_le_bytes()); + dex::parse(&bytes).unwrap().code(0x70).unwrap() +} + +#[test] +fn invalid_sizes_do_not_create_handlers() { + let sizes: &[&[u8]] = &[ + &[0x80, 0x80, 0x80, 0x80, 0x08], + &[0x80, 0x80, 0x80, 0x80, 0x77], + &[0x80, 0x80, 0x80, 0x80, 0x80, 0], + &[0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0], + ]; + for size in sizes { + // These bytes could be a type/address pair or a catch-all address if size is accepted. + let code = code_with_handler(size, &[0, 7]); + assert_eq!(code.tries.len(), 1); + assert!(code.tries[0].handlers.is_empty(), "invalid size {size:x?}"); + } +} + +#[test] +fn valid_catch_all_handlers_are_retained() { + for size in [&[0][..], &[0x80, 0x80, 0x80, 0x80, 0][..]] { + let code = code_with_handler(size, &[7]); + assert_eq!(code.tries.len(), 1); + assert_eq!(code.tries[0].start, 0); + assert_eq!(code.tries[0].end, 1); + assert_eq!(code.tries[0].handlers, vec![Handler { exception: None, address: 7 }]); + } +} From 66f8c510489bdb2729b30538bfec44f457cc3e64 Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Tue, 17 Nov 2026 08:40:02 -0500 Subject: [PATCH 12/37] Expose shared DEX inspection and bytecode decoding --- ATTRIBUTION.md | 4 + Cargo.lock | 8 + Cargo.toml | 1 + crates/dex/Cargo.toml | 13 + crates/dex/src/bytes.rs | 81 ++++++ crates/dex/src/dex.rs | 28 +- crates/dex/src/dex_ops.rs | 8 +- crates/dex/src/lib.rs | 42 +++ crates/dex/src/test_support.rs | 471 +++++++++++++++++++++++++++++++++ 9 files changed, 643 insertions(+), 13 deletions(-) create mode 100644 crates/dex/Cargo.toml create mode 100644 crates/dex/src/bytes.rs create mode 100644 crates/dex/src/lib.rs create mode 100644 crates/dex/src/test_support.rs diff --git a/ATTRIBUTION.md b/ATTRIBUTION.md index 4c86afd61..cbf153813 100644 --- a/ATTRIBUTION.md +++ b/ATTRIBUTION.md @@ -132,3 +132,7 @@ Sanitization, animation fitting and numeric output policy remain caller-owned. ## JSONC span-preserving editing `crates/jsonc` is extracted from Craft Anything `crates/formats/src/jsonc.rs` at `e5c9c94106747ed44b9a3fb0decce867c2285f93` (MIT OR Apache-2.0). The original implementation and hardening by BFlat, newline preservation by NetterSilver, and subsequent RRFZ/Afloat correctness fixes retain separate primary-author port commits with immutable source revisions. Shared API wiring and optional input-byte admission are subsequent changes. Compatibility parsing and all existing formatting/editing tests are retained; application file I/O and policy are not imported. + +## Dalvik DEX inspection + +`crates/dex` extracts Craft Anything `crates/formats/src/dex.rs` and `dex_ops.rs` at `5979f9b13f16dcf1df3c7ae7f8e7735f452866f2` (MIT OR Apache-2.0). Five source-history ports preserve Brandon Thomas, BFlat and Afloat as primary authors. Five regression imports retain BFlat/Afloat authors and exact source revisions. The checked byte-reader/MUTF-8 subset and synthetic DEX fixture come from that app's `bytes.rs` and `testkit/src/android.rs`; deterministic noise/mutations come from its testkit. No application file I/O, APK logic or execution is imported. Shared neutral errors and workspace wiring are subsequent changes; existing per-file strings, member/handler and bytecode payload budgets are retained. diff --git a/Cargo.lock b/Cargo.lock index 9fa1f4401..720433ee7 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1722,6 +1722,14 @@ dependencies = [ "thiserror 2.0.21", ] +[[package]] +name = "craft-dex" +version = "0.1.0" +dependencies = [ + "serde", + "thiserror 2.0.21", +] + [[package]] name = "craft-dialogs" version = "0.1.0" diff --git a/Cargo.toml b/Cargo.toml index 50ec3c917..803e433de 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -11,6 +11,7 @@ rust-version = "1.95" repository = "https://github.com/storytold/craft-libs" [workspace.dependencies] +craft-dex = { path = "crates/dex" } craft-jsonc = { path = "crates/jsonc" } craft-palette = { path = "crates/palette" } craft-score = { path = "crates/score" } diff --git a/crates/dex/Cargo.toml b/crates/dex/Cargo.toml new file mode 100644 index 000000000..e4eb285f5 --- /dev/null +++ b/crates/dex/Cargo.toml @@ -0,0 +1,13 @@ +[package] +name="craft-dex" +description="Dalvik DEX reader and bytecode decoder with retained input bounds and partial-report semantics" +version.workspace=true +edition.workspace=true +license.workspace=true +rust-version.workspace=true +repository.workspace=true +[lints] +workspace=true +[dependencies] +serde={workspace=true} +thiserror={workspace=true} diff --git a/crates/dex/src/bytes.rs b/crates/dex/src/bytes.rs new file mode 100644 index 000000000..555505a2d --- /dev/null +++ b/crates/dex/src/bytes.rs @@ -0,0 +1,81 @@ +//! Checked little/big-endian reads over untrusted bytes. Every read returns `None` when out of range. + +#[derive(Debug, Clone, Copy)] +pub struct Reader<'a> { + data: &'a [u8], +} + +impl<'a> Reader<'a> { + pub fn new(data: &'a [u8]) -> Self { + Reader { data } + } + + pub fn len(&self) -> usize { + self.data.len() + } + + pub fn data(&self) -> &'a [u8] { + self.data + } + + pub fn slice(&self, off: usize, len: usize) -> Option<&'a [u8]> { + let end = off.checked_add(len)?; + self.data.get(off..end) + } + + pub fn u8(&self, off: usize) -> Option { + self.data.get(off).copied() + } + + fn arr(&self, off: usize) -> Option<[u8; N]> { + self.slice(off, N)?.try_into().ok() + } + + pub fn u16_le(&self, off: usize) -> Option { + self.arr(off).map(u16::from_le_bytes) + } + + pub fn u32_le(&self, off: usize) -> Option { + self.arr(off).map(u32::from_le_bytes) + } + + /// A NUL-terminated string starting at `off`, at most `max` bytes, lossily decoded. + pub fn cstr(&self, off: usize, max: usize) -> Option { + let rest = self.data.get(off..)?; + let rest = rest.get(..max.min(rest.len()))?; + let end = rest.iter().position(|&b| b == 0).unwrap_or(rest.len()); + Some(String::from_utf8_lossy(rest.get(..end)?).into_owned()) + } + + /// Unsigned LEB128 at `off`: (value, bytes consumed). At most 10 bytes. + pub fn uleb128(&self, off: usize) -> Option<(u64, usize)> { + let mut result = 0u64; + for i in 0..10usize { + let b = self.u8(off.checked_add(i)?)?; + let payload = u64::from(b & 0x7f); + let shift = 7 * i as u32; + if shift > 0 && payload.checked_shl(shift)? >> shift != payload { + return None; + } + result |= payload << shift; + if b & 0x80 == 0 { + return Some((result, i + 1)); + } + } + None + } +} + +/// Decode one modified UTF-8 code unit. Invalid bytes consume only themselves, +/// so a damaged sequence cannot hide valid text or borrow missing bytes. +pub(crate) fn mutf8_unit(bytes: &[u8]) -> (u16, usize) { + match bytes { + [a @ 0x00..=0x7f, ..] => (u16::from(*a), 1), + [0xc0, 0x80, ..] => (0, 2), + [a @ 0xc2..=0xdf, b @ 0x80..=0xbf, ..] => ((u16::from(*a & 0x1f) << 6) | u16::from(*b & 0x3f), 2), + [a @ 0xe0..=0xef, b @ 0x80..=0xbf, c @ 0x80..=0xbf, ..] if *a != 0xe0 || *b >= 0xa0 => { + ((u16::from(*a & 0x0f) << 12) | (u16::from(*b & 0x3f) << 6) | u16::from(*c & 0x3f), 3) + } + _ => (0xfffd, 1), + } +} diff --git a/crates/dex/src/dex.rs b/crates/dex/src/dex.rs index c4076dfc8..e578dc397 100644 --- a/crates/dex/src/dex.rs +++ b/crates/dex/src/dex.rs @@ -348,8 +348,11 @@ pub fn parse(data: &[u8]) -> Result, FormatError> { ProtoId { shorty: r.u32_le(o).unwrap_or(0), ret: r.u32_le(o + 4).unwrap_or(NO_INDEX), params_off: r.u32_le(o + 8).unwrap_or(0) } }) .collect(); - let member = - |o: usize| MemberId { class_idx: r.u16_le(o).unwrap_or(0), type_or_proto: r.u16_le(o + 2).unwrap_or(0), name_idx: r.u32_le(o + 4).unwrap_or(NO_INDEX) }; + let member = |o: usize| MemberId { + class_idx: r.u16_le(o).unwrap_or(0), + type_or_proto: r.u16_le(o + 2).unwrap_or(0), + name_idx: r.u32_le(o + 4).unwrap_or(NO_INDEX), + }; let fields = (0..nf).map(|i| member(fo + i * 8)).collect(); let methods = (0..nm).map(|i| member(mo + i * 8)).collect(); let classes = (0..nc) @@ -423,7 +426,9 @@ impl<'a> Dex<'a> { /// `Lcls;->name:Ltype;` pub fn field_ref(&self, i: u32) -> String { match self.fields.get(i as usize) { - Some(f) => format!("{}->{}:{}", self.type_desc(u32::from(f.class_idx)), self.string(f.name_idx), self.type_desc(u32::from(f.type_or_proto))), + Some(f) => { + format!("{}->{}:{}", self.type_desc(u32::from(f.class_idx)), self.string(f.name_idx), self.type_desc(u32::from(f.type_or_proto))) + } None => format!(""), } } @@ -431,7 +436,9 @@ impl<'a> Dex<'a> { /// `Lcls;->name(…)R` pub fn method_ref(&self, i: u32) -> String { match self.methods.get(i as usize) { - Some(m) => format!("{}->{}{}", self.type_desc(u32::from(m.class_idx)), self.string(m.name_idx), self.proto_desc(u32::from(m.type_or_proto))), + Some(m) => { + format!("{}->{}{}", self.type_desc(u32::from(m.class_idx)), self.string(m.name_idx), self.proto_desc(u32::from(m.type_or_proto))) + } None => format!(""), } } @@ -683,9 +690,10 @@ pub fn references(dex: &Dex<'_>, desc: &str, method: Option<&str>, max: usize) - let cls = dex.type_desc(u32::from(id.class_idx)); (cls == desc && method.is_none_or(|n| dex.string(id.name_idx) == n)).then(|| ("method", dex.method_ref(idx))) }), - IndexKind::Field if method.is_none() => { - dex.fields.get(idx as usize).and_then(|id| (dex.type_desc(u32::from(id.class_idx)) == desc).then(|| ("field", dex.field_ref(idx)))) - } + IndexKind::Field if method.is_none() => dex + .fields + .get(idx as usize) + .and_then(|id| (dex.type_desc(u32::from(id.class_idx)) == desc).then(|| ("field", dex.field_ref(idx)))), IndexKind::Type if method.is_none() => { let t = dex.type_desc(idx); (t.trim_start_matches('[') == desc).then_some(("type", t)) @@ -707,7 +715,7 @@ pub fn references(dex: &Dex<'_>, desc: &str, method: Option<&str>, max: usize) - #[cfg(test)] mod tests { use super::*; - use craft_anything_testkit::android as fx; + use crate::test_support::android as fx; #[test] fn parses_fixture() { @@ -785,7 +793,7 @@ mod tests { } let _ = references(d, "Lcom/example/notes/Util;", None, 100); }; - for m in craft_anything_testkit::mutations(&data) { + for m in crate::test_support::mutations(&data) { if let Ok(d) = parse(&m) { walk(&d); } @@ -796,7 +804,7 @@ mod tests { } } for seed in 0..64 { - let mut n = craft_anything_testkit::noise(seed, 2048); + let mut n = crate::test_support::noise(seed, 2048); n[..8].copy_from_slice(b"dex\n035\0"); n[40..44].copy_from_slice(&0x1234_5678u32.to_le_bytes()); if let Ok(d) = parse(&n) { diff --git a/crates/dex/src/dex_ops.rs b/crates/dex/src/dex_ops.rs index 71095fc75..3c27d4c5c 100644 --- a/crates/dex/src/dex_ops.rs +++ b/crates/dex/src/dex_ops.rs @@ -170,7 +170,8 @@ const BINOPS_2ADDR: [&str; 32] = [ "rem-double/2addr", ]; -const LIT16: [&str; 8] = ["add-int/lit16", "rsub-int", "mul-int/lit16", "div-int/lit16", "rem-int/lit16", "and-int/lit16", "or-int/lit16", "xor-int/lit16"]; +const LIT16: [&str; 8] = + ["add-int/lit16", "rsub-int", "mul-int/lit16", "div-int/lit16", "rem-int/lit16", "and-int/lit16", "or-int/lit16", "xor-int/lit16"]; const LIT8: [&str; 11] = [ "add-int/lit8", "rsub-int/lit8", @@ -236,7 +237,8 @@ const SFIELD: [&str; 14] = [ "sput-short", ]; const INVOKE: [&str; 5] = ["invoke-virtual", "invoke-super", "invoke-direct", "invoke-static", "invoke-interface"]; -const INVOKE_RANGE: [&str; 5] = ["invoke-virtual/range", "invoke-super/range", "invoke-direct/range", "invoke-static/range", "invoke-interface/range"]; +const INVOKE_RANGE: [&str; 5] = + ["invoke-virtual/range", "invoke-super/range", "invoke-direct/range", "invoke-static/range", "invoke-interface/range"]; fn pick(list: &[&'static str], i: u8, base: u8) -> &'static str { list.get(usize::from(i.wrapping_sub(base))).copied().unwrap_or("unused") @@ -683,7 +685,7 @@ mod tests { #[test] fn hostile() { for seed in 0..200 { - let n = craft_anything_testkit::noise(seed, 256); + let n = crate::test_support::noise(seed, 256); let code: Vec = n.as_chunks::<2>().0.iter().map(|c| u16::from_le_bytes(*c)).collect(); let _ = decode(&code, 1000); } diff --git a/crates/dex/src/lib.rs b/crates/dex/src/lib.rs new file mode 100644 index 000000000..97d28b7f4 --- /dev/null +++ b/crates/dex/src/lib.rs @@ -0,0 +1,42 @@ +#![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)] +#![forbid(unsafe_code)] +//! Dalvik DEX inspection and bytecode decoding. Never executes bytecode. +mod bytes; +/// Checked byte reader accepted by the signed-LEB compatibility helper. +pub use bytes::Reader; +pub mod dex; +pub mod dex_ops; +pub use dex::*; +#[cfg(test)] +mod test_support; +/// Parser admission failures; damaged substructures retain the original partial-report behavior. +#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)] +pub enum DexError { + #[error("the file ends early ({0})")] + Truncated(String), + #[error("the file is malformed ({0})")] + Malformed(String), + #[error("not supported: {0}")] + Unsupported(String), +} +use DexError as FormatError; + +#[cfg(test)] +#[path = "regressions/array_widths.rs"] +mod array_widths; + +#[cfg(test)] +#[path = "regressions/capped_table_boundaries.rs"] +mod capped_table_boundaries; + +#[cfg(test)] +#[path = "regressions/invoke_registers.rs"] +mod invoke_registers; + +#[cfg(test)] +#[path = "regressions/payload_budgets.rs"] +mod payload_budgets; + +#[cfg(test)] +#[path = "regressions/signed_leb128.rs"] +mod signed_leb128; diff --git a/crates/dex/src/test_support.rs b/crates/dex/src/test_support.rs new file mode 100644 index 000000000..a3a179145 --- /dev/null +++ b/crates/dex/src/test_support.rs @@ -0,0 +1,471 @@ +// Synthetic DEX fixture and deterministic mutations retained from Craft Anything. +/// Deterministic pseudo-random bytes (xorshift) for fuzz-like loops. +pub fn noise(seed: u64, len: usize) -> Vec { + let mut x = seed.wrapping_mul(0x9e37_79b9_7f4a_7c15) | 1; + (0..len) + .map(|_| { + x ^= x << 13; + x ^= x >> 7; + x ^= x << 17; + x as u8 + }) + .collect() +} + +/// Every way to damage a sample used by robustness tests: truncations at many lengths and +/// single-byte corruptions spread across the file. +pub fn mutations(sample: &[u8]) -> Vec> { + let mut out = Vec::new(); + let n = sample.len(); + let step = (n / 64).max(1); + let mut len = 0; + while len < n { + out.push(sample[..len].to_vec()); + len += step; + } + for (i, seed) in (0..n).step_by(step).zip(1u64..) { + let mut m = sample.to_vec(); + let noise = noise(seed, 8); + for (j, v) in noise.iter().enumerate() { + if let Some(b) = m.get_mut(i + j) { + *b = *v; + } + } + out.push(m); + let mut m = sample.to_vec(); + if let Some(b) = m.get_mut(i) { + *b = 0xff; + } + out.push(m); + } + out +} + +pub mod android { + pub const HELLO: &str = "Hello, Craft!"; + fn u16le(v: &mut Vec, x: u16) { + v.extend_from_slice(&x.to_le_bytes()); + } + fn u32le(v: &mut Vec, x: u32) { + v.extend_from_slice(&x.to_le_bytes()); + } + fn uleb(v: &mut Vec, mut x: u32) { + loop { + let b = (x & 0x7f) as u8; + x >>= 7; + if x == 0 { + v.push(b); + break; + } + v.push(b | 0x80); + } + } + fn sleb(v: &mut Vec, mut x: i32) { + loop { + let b = (x & 0x7f) as u8; + x >>= 7; + let done = (x == 0 && b & 0x40 == 0) || (x == -1 && b & 0x40 != 0); + v.push(if done { b } else { b | 0x80 }); + if done { + break; + } + } + } + fn align4(v: &mut Vec) { + while !v.len().is_multiple_of(4) { + v.push(0); + } + } + + #[derive(Debug, Clone, Default)] + pub struct TrySpec { + pub start: u32, + pub count: u16, + /// (type idx, handler address) + pub handlers: Vec<(u32, u32)>, + pub catch_all: Option, + } + + #[derive(Debug, Clone, Default)] + pub struct CodeSpec { + pub registers: u16, + pub ins: u16, + pub outs: u16, + pub insns: Vec, + pub tries: Vec, + } + + #[derive(Debug, Clone)] + pub struct MethodSpec { + pub method: u32, + pub access: u32, + pub code: Option, + } + + #[derive(Debug, Clone, Default)] + pub struct ClassSpec { + pub class: u32, + pub access: u32, + pub superclass: u32, + pub interfaces: Vec, + pub source_file: u32, + pub annotations: Vec, + pub static_fields: Vec<(u32, u32)>, + pub instance_fields: Vec<(u32, u32)>, + pub direct: Vec, + pub virtuals: Vec, + } + + #[derive(Debug, Clone, Default)] + pub struct DexBuilder { + strings: Vec, + types: Vec, + protos: Vec<(u32, u32, Vec)>, + fields: Vec<(u32, u32, u32)>, + methods: Vec<(u32, u32, u32)>, + pub classes: Vec, + } + + impl DexBuilder { + pub fn string(&mut self, s: &str) -> u32 { + if let Some(i) = self.strings.iter().position(|x| x == s) { + return i as u32; + } + self.strings.push(s.to_string()); + (self.strings.len() - 1) as u32 + } + + pub fn ty(&mut self, desc: &str) -> u32 { + let s = self.string(desc); + if let Some(i) = self.types.iter().position(|&x| x == s) { + return i as u32; + } + self.types.push(s); + (self.types.len() - 1) as u32 + } + + pub fn proto(&mut self, ret: &str, params: &[&str]) -> u32 { + let short = |d: &str| if d.starts_with('L') || d.starts_with('[') { 'L' } else { d.chars().next().unwrap() }; + let shorty: String = std::iter::once(short(ret)).chain(params.iter().map(|p| short(p))).collect(); + let s = self.string(&shorty); + let r = self.ty(ret); + let ps: Vec = params.iter().map(|p| self.ty(p)).collect(); + if let Some(i) = self.protos.iter().position(|p| p.1 == r && p.2 == ps) { + return i as u32; + } + self.protos.push((s, r, ps)); + (self.protos.len() - 1) as u32 + } + + pub fn field(&mut self, cls: &str, ty: &str, name: &str) -> u32 { + let c = self.ty(cls); + let t = self.ty(ty); + let n = self.string(name); + if let Some(i) = self.fields.iter().position(|&f| f == (c, t, n)) { + return i as u32; + } + self.fields.push((c, t, n)); + (self.fields.len() - 1) as u32 + } + + pub fn method(&mut self, cls: &str, name: &str, ret: &str, params: &[&str]) -> u32 { + let c = self.ty(cls); + let p = self.proto(ret, params); + let n = self.string(name); + if let Some(i) = self.methods.iter().position(|&m| m == (c, p, n)) { + return i as u32; + } + self.methods.push((c, p, n)); + (self.methods.len() - 1) as u32 + } + + pub fn build(self) -> Vec { + let ns = self.strings.len(); + let nt = self.types.len(); + let np = self.protos.len(); + let nf = self.fields.len(); + let nm = self.methods.len(); + let nc = self.classes.len(); + let string_ids = 0x70; + let type_ids = string_ids + ns * 4; + let proto_ids = type_ids + nt * 4; + let field_ids = proto_ids + np * 12; + let method_ids = field_ids + nf * 8; + let class_defs = method_ids + nm * 8; + let mut data_start = class_defs + nc * 32; + data_start = (data_start + 3) & !3; + let mut d: Vec = Vec::new(); + let at = |d: &Vec| (data_start + d.len()) as u32; + // type lists + let tl = |d: &mut Vec, list: &[u32]| -> u32 { + if list.is_empty() { + return 0; + } + align4(d); + let o = at(d); + u32le(d, list.len() as u32); + for &t in list { + u16le(d, t as u16); + } + o + }; + let proto_params: Vec = self.protos.iter().map(|p| tl(&mut d, &p.2)).collect(); + let class_ifaces: Vec = self.classes.iter().map(|c| tl(&mut d, &c.interfaces)).collect(); + // string data + let mut string_offs = Vec::new(); + for s in &self.strings { + string_offs.push(at(&d)); + uleb(&mut d, s.encode_utf16().count() as u32); + for ch in s.chars() { + let c = ch as u32; + if c == 0 { + d.extend_from_slice(&[0xc0, 0x80]); + } else if c < 0x80 { + d.push(c as u8); + } else if c < 0x800 { + d.extend_from_slice(&[0xc0 | (c >> 6) as u8, 0x80 | (c & 0x3f) as u8]); + } else { + d.extend_from_slice(&[0xe0 | (c >> 12) as u8, 0x80 | ((c >> 6) & 0x3f) as u8, 0x80 | (c & 0x3f) as u8]); + } + } + d.push(0); + } + // code items, class data, annotations + let mut class_data_offs = Vec::new(); + let mut annot_offs = Vec::new(); + for c in &self.classes { + let code_off = |d: &mut Vec, m: &MethodSpec| -> u32 { + let Some(code) = &m.code else { return 0 }; + align4(d); + let o = at(d); + u16le(d, code.registers); + u16le(d, code.ins); + u16le(d, code.outs); + u16le(d, code.tries.len() as u16); + u32le(d, 0); + u32le(d, code.insns.len() as u32); + for &i in &code.insns { + u16le(d, i); + } + if !code.tries.is_empty() { + if code.insns.len() % 2 == 1 { + u16le(d, 0); + } + let mut list = Vec::new(); + uleb(&mut list, code.tries.len() as u32); + let mut offs = Vec::new(); + for t in &code.tries { + offs.push(list.len() as u16); + let n = t.handlers.len() as i32; + sleb(&mut list, if t.catch_all.is_some() { -n } else { n }); + for &(ty, addr) in &t.handlers { + uleb(&mut list, ty); + uleb(&mut list, addr); + } + if let Some(a) = t.catch_all { + uleb(&mut list, a); + } + } + for (t, off) in code.tries.iter().zip(offs) { + u32le(d, t.start); + u16le(d, t.count); + u16le(d, off); + } + d.extend_from_slice(&list); + } + o + }; + let mut direct = c.direct.clone(); + direct.sort_by_key(|m| m.method); + let mut virtuals = c.virtuals.clone(); + virtuals.sort_by_key(|m| m.method); + let direct_offs: Vec = direct.iter().map(|m| code_off(&mut d, m)).collect(); + let virtual_offs: Vec = virtuals.iter().map(|m| code_off(&mut d, m)).collect(); + let cd = at(&d); + let mut sf = c.static_fields.clone(); + sf.sort(); + let mut inf = c.instance_fields.clone(); + inf.sort(); + uleb(&mut d, sf.len() as u32); + uleb(&mut d, inf.len() as u32); + uleb(&mut d, direct.len() as u32); + uleb(&mut d, virtuals.len() as u32); + for list in [&sf, &inf] { + let mut prev = 0; + for &(f, a) in list.iter() { + uleb(&mut d, f - prev); + uleb(&mut d, a); + prev = f; + } + } + for (list, offs) in [(&direct, &direct_offs), (&virtuals, &virtual_offs)] { + let mut prev = 0; + for (m, &o) in list.iter().zip(offs.iter()) { + uleb(&mut d, m.method - prev); + uleb(&mut d, m.access); + uleb(&mut d, o); + prev = m.method; + } + } + class_data_offs.push(cd); + if c.annotations.is_empty() { + annot_offs.push(0); + } else { + let mut items = Vec::new(); + for &t in &c.annotations { + items.push(at(&d)); + d.push(1); // runtime visibility + uleb(&mut d, t); + uleb(&mut d, 0); + } + align4(&mut d); + let set_off = at(&d); + u32le(&mut d, items.len() as u32); + for i in items { + u32le(&mut d, i); + } + let dir = at(&d); + u32le(&mut d, set_off); + u32le(&mut d, 0); + u32le(&mut d, 0); + u32le(&mut d, 0); + annot_offs.push(dir); + } + } + align4(&mut d); + let file_size = data_start + d.len(); + let mut out = vec![0u8; data_start]; + out[..8].copy_from_slice(b"dex\n035\0"); + let put = |out: &mut Vec, off: usize, v: u32| out[off..off + 4].copy_from_slice(&v.to_le_bytes()); + put(&mut out, 32, file_size as u32); + put(&mut out, 36, 0x70); + put(&mut out, 40, 0x1234_5678); + for (i, (n, o)) in + [(ns, string_ids), (nt, type_ids), (np, proto_ids), (nf, field_ids), (nm, method_ids), (nc, class_defs)].iter().enumerate() + { + put(&mut out, 56 + i * 8, *n as u32); + put(&mut out, 60 + i * 8, if *n == 0 { 0 } else { *o as u32 }); + } + put(&mut out, 104, d.len() as u32); + put(&mut out, 108, data_start as u32); + for (i, o) in string_offs.iter().enumerate() { + put(&mut out, string_ids + i * 4, *o); + } + for (i, t) in self.types.iter().enumerate() { + put(&mut out, type_ids + i * 4, *t); + } + for (i, p) in self.protos.iter().enumerate() { + put(&mut out, proto_ids + i * 12, p.0); + put(&mut out, proto_ids + i * 12 + 4, p.1); + put(&mut out, proto_ids + i * 12 + 8, proto_params[i]); + } + for (i, (c, t, n)) in self.fields.iter().enumerate() { + out[field_ids + i * 8..field_ids + i * 8 + 2].copy_from_slice(&(*c as u16).to_le_bytes()); + out[field_ids + i * 8 + 2..field_ids + i * 8 + 4].copy_from_slice(&(*t as u16).to_le_bytes()); + put(&mut out, field_ids + i * 8 + 4, *n); + } + for (i, (c, p, n)) in self.methods.iter().enumerate() { + out[method_ids + i * 8..method_ids + i * 8 + 2].copy_from_slice(&(*c as u16).to_le_bytes()); + out[method_ids + i * 8 + 2..method_ids + i * 8 + 4].copy_from_slice(&(*p as u16).to_le_bytes()); + put(&mut out, method_ids + i * 8 + 4, *n); + } + for (i, c) in self.classes.iter().enumerate() { + let o = class_defs + i * 32; + for (k, v) in + [c.class, c.access, c.superclass, class_ifaces[i], c.source_file, annot_offs[i], class_data_offs[i], 0].iter().enumerate() + { + put(&mut out, o + k * 4, *v); + } + } + out.extend_from_slice(&d); + let sum = adler32(&out[12..]); + put(&mut out, 8, sum); + out + } + } + + fn adler32(data: &[u8]) -> u32 { + let (mut a, mut b) = (1u32, 0u32); + for &x in data { + a = (a + u32::from(x)) % 65521; + b = (b + a) % 65521; + } + (b << 16) | a + } + + const MAIN: &str = "Lcom/example/notes/MainActivity;"; + const UTIL: &str = "Lcom/example/notes/Util;"; + const STRING: &str = "Ljava/lang/String;"; + + /// `classes.dex` of the Notes app: `MainActivity` (constructor, `onCreate`, `run`, `pick` with a + /// packed switch inside a try/catch) and `Util` (two `log` overloads printing through + /// `System.out`). + pub fn notes_dex() -> Vec { + let mut b = DexBuilder::default(); + let activity = b.ty("Landroid/app/Activity;"); + let main = b.ty(MAIN); + let runnable = b.ty("Ljava/lang/Runnable;"); + let deprecated = b.ty("Ljava/lang/Deprecated;"); + let rte = b.ty("Ljava/lang/RuntimeException;"); + let object = b.ty("Ljava/lang/Object;"); + let util = b.ty(UTIL); + let tag = b.field(MAIN, STRING, "TAG"); + let count = b.field(MAIN, "I", "count"); + let out = b.field("Ljava/lang/System;", "Ljava/io/PrintStream;", "out"); + let super_init = b.method("Landroid/app/Activity;", "", "V", &[]); + let super_create = b.method("Landroid/app/Activity;", "onCreate", "V", &["Landroid/os/Bundle;"]); + let init = b.method(MAIN, "", "V", &[]); + let on_create = b.method(MAIN, "onCreate", "V", &["Landroid/os/Bundle;"]); + let run = b.method(MAIN, "run", "V", &[]); + let pick = b.method(MAIN, "pick", "I", &["I"]); + let log_s = b.method(UTIL, "log", "V", &[STRING]); + let log_i = b.method(UTIL, "log", "V", &["I"]); + let println = b.method("Ljava/io/PrintStream;", "println", "V", &[STRING]); + let hello = b.string(HELLO); + let main_src = b.string("MainActivity.java"); + let util_src = b.string("Util.java"); + let code = |registers, ins, outs, insns: Vec| Some(CodeSpec { registers, ins, outs, insns, tries: vec![] }); + b.classes.push(ClassSpec { + class: main, + access: 0x1, + superclass: activity, + interfaces: vec![runnable], + source_file: main_src, + annotations: vec![deprecated], + static_fields: vec![(tag, 0x1a)], + instance_fields: vec![(count, 0x2)], + direct: vec![MethodSpec { method: init, access: 0x10001, code: code(1, 1, 1, vec![0x1070, super_init as u16, 0x0000, 0x000e]) }], + virtuals: vec![ + MethodSpec { + method: on_create, + access: 0x1, + code: code(3, 2, 2, vec![0x001a, hello as u16, 0x1071, log_s as u16, 0x0000, 0x206f, super_create as u16, 0x0021, 0x000e]), + }, + MethodSpec { method: run, access: 0x1, code: code(1, 1, 1, vec![0x7012, 0x1071, log_i as u16, 0x0000, 0x000e]) }, + MethodSpec { + method: pick, + access: 0x1, + code: Some(CodeSpec { + registers: 3, + ins: 2, + outs: 0, + insns: vec![0x022b, 10, 0, 0x0012, 0x000f, 0x1012, 0x000f, 0x2012, 0x000f, 0x0000, 0x0100, 2, 1, 0, 5, 0, 7, 0], + tries: vec![TrySpec { start: 0, count: 3, handlers: vec![(rte, 3)], catch_all: Some(3) }], + }), + }, + ], + }); + b.classes.push(ClassSpec { + class: util, + access: 0x11, + superclass: object, + source_file: util_src, + direct: vec![ + MethodSpec { method: log_s, access: 0x9, code: code(2, 1, 2, vec![0x0062, out as u16, 0x206e, println as u16, 0x0010, 0x000e]) }, + MethodSpec { method: log_i, access: 0x9, code: code(1, 1, 0, vec![0x000e]) }, + ], + ..ClassSpec::default() + }); + b.build() + } +} From 60f7c5d74f6e5dfda2fa5779cff0b57d8fd45263 Mon Sep 17 00:00:00 2001 From: techneissa <55485515+techneissa@users.noreply.github.com> Date: Tue, 17 Nov 2026 16:53:35 +0300 Subject: [PATCH 13/37] raw: read a DNG strip whose byte count is only ActiveArea wide in full (#2040) An uncompressed single-sample integer DNG strip whose StripByteCounts is exactly ActiveArea columns (from column 0) by ImageLength rows, while the file holds the whole ImageWidth by ImageLength raster from the strip's offset, is read at its declared size instead of refused. Every other shortfall stays Corrupt. --- crates/raw/src/dng.rs | 37 +++++++++++++- crates/raw/src/dng/compat_review_tests.rs | 59 +++++++++++++++++++++++ 2 files changed, 95 insertions(+), 1 deletion(-) diff --git a/crates/raw/src/dng.rs b/crates/raw/src/dng.rs index efa1ec4f5..a7be5d67b 100644 --- a/crates/raw/src/dng.rs +++ b/crates/raw/src/dng.rs @@ -8,6 +8,7 @@ use crate::{ BlackLevel, Camera, Cfa, CinemaTags, ColorData, LevelSource, LevelSources, Limits, Matrix3, Mode, Orientation, RawData, RawError, RawFormat, RawImage, RawNotices, Rect, Result, Timecode, opcodes, }; +use craft_tiff::image::{ImageInfo, Layout}; use craft_tiff::tags::{self as t, photometric}; use craft_tiff::{ByteOrder, Ifd, Tiff, Value}; @@ -273,7 +274,10 @@ fn decode_ifd(bytes: &[u8], tiff: &Tiff, pixels: &Ifd, main: &Ifd, mode: Mode, f { return Err(RawError::Unsupported(format!("DNG compression {c} (GoPro VC-5) is not decoded yet"))); } - let info = pixels.image()?; + let mut info = pixels.image()?; + if std::ptr::eq(pixels, raw) { + extend_understated_strip(bytes, &mut info, raw); + } let (w, h, cpp) = (info.width as usize, info.height as usize, info.samples_per_pixel as usize); // one sample (CFA or monochrome), RGB or four colours; two are neither and can't be developed (storytold/lightcraft#1511) if !matches!(cpp, 1 | 3 | 4) { @@ -522,6 +526,37 @@ fn cinema_tags(ifd0: &Ifd, raw: &Ifd) -> CinemaTags { } } +/// Trust the file over `StripByteCounts` for an uncompressed single-strip image whose byte count is exactly +/// `ActiveArea` columns by `ImageLength` rows while the file holds the whole `ImageWidth` by `ImageLength` raster from +/// the strip's offset on. DJI Mavic 3 DNGs write the count of the active columns (5280) for a strip of full 5376-wide +/// rows that ends at the end of the file, so reading only the counted bytes refuses a complete image +/// (storytold/craft-libs#2040). The strip is lengthened only then, so every other short strip is still refused, and +/// it never reaches past the end of the file. The active area has to start at column 0, so it is the stored rows' +/// leading columns. +fn extend_understated_strip(bytes: &[u8], info: &mut ImageInfo, raw: &Ifd) { + let bits = u64::from(info.bits()); + if !matches!(info.layout, Layout::Strips { .. }) + || info.compression != t::compression::NONE + || info.samples_per_pixel != 1 + || info.planar == 2 + || info.sample_format == 3 + || !matches!(bits, 8 | 16) + { + return; + } + let ([offset], [count]) = (&info.offsets[..], &info.byte_counts[..]) else { return }; + let Some([top, left, bottom, right]) = raw.u64s(t::ACTIVE_AREA).and_then(|a| <[u64; 4]>::try_from(a).ok()) else { return }; + if left != 0 || bottom <= top || right == 0 || right >= u64::from(info.width) { + return; + } + let row_bytes = |width: u64| width.checked_mul(u64::from(info.height))?.checked_mul(bits / 8); + let (Some(counted), Some(needed)) = (row_bytes(right), row_bytes(u64::from(info.width))) else { return }; + let fits = offset.checked_add(needed).is_some_and(|end| end <= bytes.len() as u64); + if *count == counted && fits { + info.byte_counts = vec![needed]; + } +} + /// The default crop is relative to ActiveArea. DNG 1.7.1 defines independent /// defaults: origin (0, 0), size ImageWidth/ImageLength. An unusable optional crop /// preserves the entire active image. Valid partly overlapping rectangles retain the diff --git a/crates/raw/src/dng/compat_review_tests.rs b/crates/raw/src/dng/compat_review_tests.rs index 48300cbf7..309d1e5b7 100644 --- a/crates/raw/src/dng/compat_review_tests.rs +++ b/crates/raw/src/dng/compat_review_tests.rs @@ -118,3 +118,62 @@ fn decoded_notices_record_actual_crop_gain_table_and_cfa_decisions() { let limits = Limits { max_samples: 47, ..Default::default() }; assert!(matches!(decode_as(&linear(&[]), Mode::Full, RawFormat::Dng, &limits), Err(RawError::Limit(_)))); } + +/// A 16-bit CFA DNG of `width` x `height` whose strip holds every row in full but whose `StripByteCounts` says +/// `counted` bytes. +fn understated_strip_dng(width: u32, height: u32, counted: u32, active_area: Option<[u32; 4]>) -> Vec { + let mut raw = IfdBuilder::new(); + for (tag, value) in [ + (t::IMAGE_WIDTH, Value::Long(vec![width])), + (t::IMAGE_LENGTH, Value::Long(vec![height])), + (t::BITS_PER_SAMPLE, Value::Short(vec![16])), + (t::SAMPLES_PER_PIXEL, Value::Short(vec![1])), + (t::PHOTOMETRIC, Value::Short(vec![photometric::CFA])), + (t::COMPRESSION, Value::Short(vec![1])), + (t::CFA_REPEAT_PATTERN_DIM, Value::Short(vec![2, 2])), + (t::CFA_PATTERN_EP, Value::Byte(vec![0, 1, 1, 2])), + ] { + raw.set(tag, value); + } + if let Some(area) = active_area { + raw.set(t::ACTIVE_AREA, Value::Long(area.to_vec())); + } + let samples = (width * height) as u16; + raw.set_image(ImageData::Strips { rows_per_strip: height, strips: vec![(0..samples).flat_map(u16::to_le_bytes).collect()] }); + let mut bytes = TiffWriter::new(ByteOrder::Little, false).write(&[raw]).unwrap(); + // the writer counts the real bytes: understate that one count, a LONG in the IFD + let count = (width * height * 2).to_le_bytes(); + let at = bytes.windows(4).position(|w| w == count).unwrap(); + bytes[at..at + 4].copy_from_slice(&counted.to_le_bytes()); + bytes +} + +/// storytold/craft-libs#2040: the DJI Mavic 3 counts 5280 x 3956 x 2 bytes for a strip that holds 5376-wide rows +/// to the end of the file. +#[test] +fn a_strip_counted_only_active_area_wide_is_read_in_full() { + let bytes = understated_strip_dng(8, 4, 6 * 4 * 2, Some([0, 0, 4, 6])); + for mode in [Mode::Full, Mode::Header] { + let img = decode_as(&bytes, mode, RawFormat::Dng, &Limits::default()).unwrap(); + assert_eq!((img.width, img.height), (8, 4)); + } + let img = decode_as(&bytes, Mode::Full, RawFormat::Dng, &Limits::default()).unwrap(); + let RawData::U16(v) = &img.data else { panic!("integer samples") }; + assert_eq!(v, &(0..32).collect::>()); +} + +/// Any other short strip is still a corrupt file. +#[test] +fn other_short_strips_are_still_refused() { + let refused = |bytes: Vec| matches!(decode_as(&bytes, Mode::Full, RawFormat::Dng, &Limits::default()), Err(RawError::Corrupt(_))); + // no ActiveArea to explain the count + assert!(refused(understated_strip_dng(8, 4, 6 * 4 * 2, None))); + // the count is not exactly the area's bytes + assert!(refused(understated_strip_dng(8, 4, 5 * 4 * 2, Some([0, 0, 4, 6])))); + // the area does not start at column 0 + assert!(refused(understated_strip_dng(8, 4, 6 * 4 * 2, Some([0, 2, 4, 8])))); + // the file does not hold the whole raster + let mut cut = understated_strip_dng(8, 4, 6 * 4 * 2, Some([0, 0, 4, 6])); + cut.truncate(cut.len() - 8); + assert!(refused(cut)); +} From c93a6057fe722107d6b465b3a0daead58ef3a439 Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Tue, 17 Nov 2026 08:54:38 -0500 Subject: [PATCH 14/37] Retain is_empty on the public checked byte reader --- crates/dex/src/bytes.rs | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/crates/dex/src/bytes.rs b/crates/dex/src/bytes.rs index 555505a2d..3e69ae4fd 100644 --- a/crates/dex/src/bytes.rs +++ b/crates/dex/src/bytes.rs @@ -14,6 +14,10 @@ impl<'a> Reader<'a> { self.data.len() } + pub fn is_empty(&self) -> bool { + self.data.is_empty() + } + pub fn data(&self) -> &'a [u8] { self.data } From 1a0d5d607859a2e529851482de09b8e53aaeec3e Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Tue, 17 Nov 2026 09:58:00 -0500 Subject: [PATCH 15/37] Extract XFA namespace-aware XML DOM without layout policy --- ATTRIBUTION.md | 4 + Cargo.lock | 7 + Cargo.toml | 1 + crates/xfa/Cargo.toml | 14 ++ crates/xfa/README.md | 9 + crates/xfa/src/lib.rs | 6 + crates/xfa/src/xml.rs | 428 ++++++++++++++++++++++++++++++++++++++++++ 7 files changed, 469 insertions(+) create mode 100644 crates/xfa/Cargo.toml create mode 100644 crates/xfa/README.md create mode 100644 crates/xfa/src/lib.rs create mode 100644 crates/xfa/src/xml.rs diff --git a/ATTRIBUTION.md b/ATTRIBUTION.md index 4c86afd61..6caa0fd33 100644 --- a/ATTRIBUTION.md +++ b/ATTRIBUTION.md @@ -132,3 +132,7 @@ Sanitization, animation fitting and numeric output policy remain caller-owned. ## JSONC span-preserving editing `crates/jsonc` is extracted from Craft Anything `crates/formats/src/jsonc.rs` at `e5c9c94106747ed44b9a3fb0decce867c2285f93` (MIT OR Apache-2.0). The original implementation and hardening by BFlat, newline preservation by NetterSilver, and subsequent RRFZ/Afloat correctness fixes retain separate primary-author port commits with immutable source revisions. Shared API wiring and optional input-byte admission are subsequent changes. Compatibility parsing and all existing formatting/editing tests are retained; application file I/O and policy are not imported. + +## XFA XML DOM + +`crates/xfa/src/xml.rs` is extracted from PDFCraft at `271e479c53723b1b294c866d5cb2f27604601b29`, originally by Dylan M. Taylor (`eead4541`, `7d44e654`), MIT OR Apache-2.0. Only visibility and module boundaries change; PDF/layout/form policy remains in the app. diff --git a/Cargo.lock b/Cargo.lock index 9fa1f4401..7bf961c6b 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -3380,6 +3380,13 @@ dependencies = [ "thiserror 2.0.21", ] +[[package]] +name = "craft-xfa" +version = "0.1.0" +dependencies = [ + "craft-xml", +] + [[package]] name = "craft-xfl" version = "0.1.0" diff --git a/Cargo.toml b/Cargo.toml index 50ec3c917..d9094ba20 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -11,6 +11,7 @@ rust-version = "1.95" repository = "https://github.com/storytold/craft-libs" [workspace.dependencies] +craft-xfa = { path = "crates/xfa" } craft-jsonc = { path = "crates/jsonc" } craft-palette = { path = "crates/palette" } craft-score = { path = "crates/score" } diff --git a/crates/xfa/Cargo.toml b/crates/xfa/Cargo.toml new file mode 100644 index 000000000..7dca38e84 --- /dev/null +++ b/crates/xfa/Cargo.toml @@ -0,0 +1,14 @@ +[package] +name = "craft-xfa" +description = "Namespace-aware source-span XML DOM for XFA adapters; no PDF or layout policy" +version.workspace = true +edition.workspace = true +license.workspace = true +rust-version.workspace = true +repository.workspace = true + +[lints] +workspace = true + +[dependencies] +craft-xml = { workspace = true } diff --git a/crates/xfa/README.md b/crates/xfa/README.md new file mode 100644 index 000000000..e4ed85e08 --- /dev/null +++ b/crates/xfa/README.md @@ -0,0 +1,9 @@ +# craft-xfa + +Scoped namespace-aware XML DOM extracted unchanged from PDFCraft xfa/xml.rs at 271e479c. This is not a complete XFA implementation: template interpretation, packets, data binding, scripts, layout, fonts and PDF generation remain app-owned. + +Preserves source byte ranges, coalesced text, namespace shadowing and document-local node identities. Uses craft-xml strict events with DTD rejection by default, depth 1024 and caller node count. Other event-reader defaults remain in force. Namespace snapshots are copied per element as before; this is not a new total-memory bound or a full XML namespaces conformance claim. + +Original source by Dylan M. Taylor (eead4541, 7d44e654), MIT OR Apache-2.0. + +Compatibility delta versus the original app XML pin e2dc681a3: current strict craft-xml rejects duplicate raw or expanded attribute names. This deliberately preserves shared security hardening; valid-document DOM behavior is unchanged, but malformed acceptance and errors are not promised byte-identical. Regression tests cover both duplicate forms. diff --git a/crates/xfa/src/lib.rs b/crates/xfa/src/lib.rs new file mode 100644 index 000000000..61640dbf6 --- /dev/null +++ b/crates/xfa/src/lib.rs @@ -0,0 +1,6 @@ +//! XFA XML infrastructure, extracted from PDFCraft. Layout and application policy stay local. +#![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)] +#![forbid(unsafe_code)] +/// Compatibility depth limit for XFA XML documents. +pub const MAX_XML_DEPTH: usize = 1024; +pub mod xml; diff --git a/crates/xfa/src/xml.rs b/crates/xfa/src/xml.rs new file mode 100644 index 000000000..0840170e6 --- /dev/null +++ b/crates/xfa/src/xml.rs @@ -0,0 +1,428 @@ +//! Lightweight namespace-aware XML DOM with source byte ranges, backed by `craft_xml`. + +use std::ops::Range; + +const XML_NS: &str = "http://www.w3.org/XML/1998/namespace"; +const XMLNS_NS: &str = "http://www.w3.org/2000/xmlns/"; + +#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] +pub struct NodeId(pub usize); + +#[derive(Clone, Debug)] +pub struct ParsingOptions { + pub allow_dtd: bool, + pub nodes_limit: u32, +} + +impl Default for ParsingOptions { + fn default() -> Self { + Self { allow_dtd: false, nodes_limit: u32::MAX } + } +} + +#[derive(Clone, Debug)] +struct AttrData { + ns: Option, + name: String, + value: String, +} + +#[derive(Clone, Debug)] +enum NodeKind { + Element { + ns: Option, + name: String, + attrs: Vec, + /// In-scope `(prefix, uri)` bindings at this element (`""` for default namespace). + namespaces: Vec<(String, String)>, + range: Range, + }, + Text(String), +} + +#[derive(Clone, Debug)] +struct NodeData { + kind: NodeKind, + children: Vec, +} + +pub struct Document { + nodes: Vec, + root: usize, +} + +#[derive(Clone, Copy)] +pub struct Node<'a> { + doc: &'a Document, + id: usize, +} + +impl PartialEq for Node<'_> { + fn eq(&self, other: &Self) -> bool { + self.id == other.id && std::ptr::eq(self.doc, other.doc) + } +} + +impl Eq for Node<'_> {} + +#[derive(Clone, Copy)] +pub struct ExpandedName<'a> { + ns: Option<&'a str>, + name: &'a str, +} + +impl<'a> ExpandedName<'a> { + pub fn name(&self) -> &'a str { + self.name + } + + pub fn namespace(&self) -> Option<&'a str> { + self.ns + } +} + +pub trait AttributeKey { + fn matches(&self, ns: Option<&str>, name: &str) -> bool; +} + +impl AttributeKey for &str { + fn matches(&self, ns: Option<&str>, name: &str) -> bool { + ns.is_none() && name == *self + } +} + +impl AttributeKey for (&str, &str) { + fn matches(&self, ns: Option<&str>, name: &str) -> bool { + ns == Some(self.0) && name == self.1 + } +} + +#[derive(Clone, Copy)] +pub struct Attribute<'a> { + attr: &'a AttrData, +} + +impl<'a> Attribute<'a> { + pub fn name(&self) -> &'a str { + &self.attr.name + } + + pub fn namespace(&self) -> Option<&'a str> { + self.attr.ns.as_deref() + } + + pub fn value(&self) -> &'a str { + &self.attr.value + } +} + +#[derive(Clone, Copy)] +pub struct Namespace<'a> { + prefix: &'a str, + uri: &'a str, +} + +impl<'a> Namespace<'a> { + pub fn name(&self) -> Option<&'a str> { + (!self.prefix.is_empty()).then_some(self.prefix) + } + + pub fn uri(&self) -> &'a str { + self.uri + } +} + +fn split_qname(qname: &str) -> (&str, &str) { + match qname.split_once(':') { + Some((p, l)) => (p, l), + None => ("", qname), + } +} + +fn resolve_ns(scope: &[(String, String)], prefix: &str, is_attr: bool) -> Result, String> { + if prefix == "xml" { + return Ok(Some(XML_NS.to_string())); + } + if prefix == "xmlns" { + return Ok(Some(XMLNS_NS.to_string())); + } + if prefix.is_empty() { + if is_attr { + return Ok(None); + } + return Ok(scope.iter().rev().find(|(p, _)| p.is_empty()).and_then(|(_, u)| (!u.is_empty()).then(|| u.clone()))); + } + match scope.iter().rev().find(|(p, _)| p == prefix) { + Some((_, u)) if !u.is_empty() => Ok(Some(u.clone())), + _ => Err(format!("undeclared namespace prefix: {prefix}")), + } +} + +impl Document { + pub fn parse(text: &str) -> Result { + Self::parse_with_options(text, ParsingOptions::default()) + } + + pub fn parse_with_options(text: &str, options: ParsingOptions) -> Result { + let mut opts = craft_xml::Options { + strict: true, + doctype: if options.allow_dtd { craft_xml::Doctype::Ignore } else { craft_xml::Doctype::Reject }, + ..Default::default() + }; + opts.limits.max_nodes = options.nodes_limit as usize; + opts.limits.max_depth = crate::MAX_XML_DEPTH; + + let mut events = opts.events(text.as_bytes()); + let mut nodes: Vec = Vec::new(); + let mut open: Vec<(usize, usize)> = Vec::new(); // (node_id, scope_len_before) + let mut scope: Vec<(String, String)> = Vec::new(); + let mut root: Option = None; + + while let Some(ev) = events.next().map_err(|e| e.to_string())? { + let span = events.span(); + match ev { + craft_xml::Event::Start { name, attrs } => { + if nodes.len() >= options.nodes_limit as usize { + return Err("nodes limit reached".to_string()); + } + let scope_mark = scope.len(); + for (k, v) in &attrs { + if k == "xmlns" { + scope.push((String::new(), v.clone())); + } else if let Some(prefix) = k.strip_prefix("xmlns:") { + scope.push((prefix.to_string(), v.clone())); + } + } + let (el_prefix, el_local) = split_qname(&name); + let el_ns = resolve_ns(&scope, el_prefix, false)?; + let mut el_attrs = Vec::new(); + for (k, v) in attrs { + if k == "xmlns" || k.starts_with("xmlns:") { + continue; + } + let (ap, al) = split_qname(&k); + let ans = resolve_ns(&scope, ap, true)?; + el_attrs.push(AttrData { ns: ans, name: al.to_string(), value: v }); + } + // Deduplicate in-scope namespace bindings, keeping the innermost binding per prefix. + let mut namespaces: Vec<(String, String)> = Vec::new(); + for (p, u) in scope.iter().rev() { + if !namespaces.iter().any(|(ep, _)| ep == p) { + namespaces.push((p.clone(), u.clone())); + } + } + namespaces.retain(|(_, u)| !u.is_empty()); + let id = nodes.len(); + nodes.push(NodeData { + kind: NodeKind::Element { ns: el_ns, name: el_local.to_string(), attrs: el_attrs, namespaces, range: span.start..span.end }, + children: Vec::new(), + }); + if let Some(&(parent, _)) = open.last() { + nodes[parent].children.push(id); + } else if root.is_none() { + root = Some(id); + } + open.push((id, scope_mark)); + } + craft_xml::Event::End { .. } => { + if let Some((id, scope_mark)) = open.pop() { + if let NodeKind::Element { range, .. } = &mut nodes[id].kind { + range.end = span.end; + } + scope.truncate(scope_mark); + } + } + craft_xml::Event::Text(t) | craft_xml::Event::CData(t) => { + if let Some(&(parent, _)) = open.last() { + if let Some(&last_child) = nodes[parent].children.last() + && let NodeKind::Text(existing) = &mut nodes[last_child].kind + { + existing.push_str(&t); + continue; + } + if nodes.len() >= options.nodes_limit as usize { + return Err("nodes limit reached".to_string()); + } + let id = nodes.len(); + nodes.push(NodeData { kind: NodeKind::Text(t), children: Vec::new() }); + nodes[parent].children.push(id); + } + } + craft_xml::Event::Pi { .. } | craft_xml::Event::Comment(_) => {} + } + } + + let Some(root) = root else { + return Err("empty XML document".to_string()); + }; + Ok(Self { nodes, root }) + } + + pub fn root_element(&self) -> Node<'_> { + Node { doc: self, id: self.root } + } + + pub fn get_node(&self, id: NodeId) -> Option> { + (id.0 < self.nodes.len()).then_some(Node { doc: self, id: id.0 }) + } + + pub fn descendants(&self) -> Descendants<'_> { + Descendants { doc: self, stack: vec![self.root] } + } +} + +pub struct Descendants<'a> { + doc: &'a Document, + stack: Vec, +} + +impl<'a> Iterator for Descendants<'a> { + type Item = Node<'a>; + + fn next(&mut self) -> Option { + let id = self.stack.pop()?; + let children = &self.doc.nodes[id].children; + for &c in children.iter().rev() { + self.stack.push(c); + } + Some(Node { doc: self.doc, id }) + } +} + +impl<'a> Node<'a> { + pub fn id(&self) -> NodeId { + NodeId(self.id) + } + + pub fn document(&self) -> &'a Document { + self.doc + } + + pub fn is_element(&self) -> bool { + matches!(self.doc.nodes[self.id].kind, NodeKind::Element { .. }) + } + + pub fn is_text(&self) -> bool { + matches!(self.doc.nodes[self.id].kind, NodeKind::Text(_)) + } + + pub fn tag_name(&self) -> ExpandedName<'a> { + match &self.doc.nodes[self.id].kind { + NodeKind::Element { ns, name, .. } => ExpandedName { ns: ns.as_deref(), name }, + NodeKind::Text(_) => ExpandedName { ns: None, name: "" }, + } + } + + pub fn attribute(&self, key: K) -> Option<&'a str> { + match &self.doc.nodes[self.id].kind { + NodeKind::Element { attrs, .. } => attrs.iter().find(|a| key.matches(a.ns.as_deref(), &a.name)).map(|a| a.value.as_str()), + NodeKind::Text(_) => None, + } + } + + pub fn attributes(&self) -> impl ExactSizeIterator> + use<'a> { + let attrs = match &self.doc.nodes[self.id].kind { + NodeKind::Element { attrs, .. } => attrs.as_slice(), + NodeKind::Text(_) => &[], + }; + attrs.iter().map(|attr| Attribute { attr }) + } + + pub fn namespaces(&self) -> impl ExactSizeIterator> + use<'a> { + let ns = match &self.doc.nodes[self.id].kind { + NodeKind::Element { namespaces, .. } => namespaces.as_slice(), + NodeKind::Text(_) => &[], + }; + ns.iter().map(|(p, u)| Namespace { prefix: p, uri: u }) + } + + pub fn lookup_prefix(&self, uri: &str) -> Option<&'a str> { + if uri == XML_NS { + return Some("xml"); + } + match &self.doc.nodes[self.id].kind { + NodeKind::Element { namespaces, .. } => namespaces.iter().find(|(_, u)| u == uri).map(|(p, _)| p.as_str()), + NodeKind::Text(_) => None, + } + } + + pub fn lookup_namespace_uri(&self, prefix: Option<&str>) -> Option<&'a str> { + if prefix == Some("xml") { + return Some(XML_NS); + } + if prefix == Some("xmlns") { + return Some(XMLNS_NS); + } + let target = prefix.unwrap_or(""); + match &self.doc.nodes[self.id].kind { + NodeKind::Element { namespaces, .. } => namespaces.iter().find(|(p, _)| p == target).map(|(_, u)| u.as_str()), + NodeKind::Text(_) => None, + } + } + + pub fn children(&self) -> impl Iterator> + use<'a> { + let doc = self.doc; + doc.nodes[self.id].children.iter().map(move |&id| Node { doc, id }) + } + + pub fn descendants(&self) -> Descendants<'a> { + Descendants { doc: self.doc, stack: vec![self.id] } + } + + pub fn text(&self) -> Option<&'a str> { + match &self.doc.nodes[self.id].kind { + NodeKind::Text(t) => Some(t.as_str()), + NodeKind::Element { .. } => self.doc.nodes[self.id].children.first().and_then(|&cid| match &self.doc.nodes[cid].kind { + NodeKind::Text(t) => Some(t.as_str()), + _ => None, + }), + } + } + + pub fn range(&self) -> Range { + match &self.doc.nodes[self.id].kind { + NodeKind::Element { range, .. } => range.clone(), + NodeKind::Text(_) => 0..0, + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn namespace_shadowing_attributes_text_and_source_ranges() { + let text = "onethree"; + let doc = Document::parse(text).unwrap(); + let root = doc.root_element(); + assert_eq!(root.tag_name().namespace(), Some("urn:outer")); + assert_eq!(root.attribute("a"), Some("v")); + let child = root.children().next().unwrap(); + assert_eq!(child.tag_name().namespace(), Some("urn:p")); + assert_eq!(child.attribute(("urn:p", "a")), Some("x")); + assert_eq!(child.lookup_namespace_uri(None), Some("urn:inner")); + assert_eq!(child.text(), Some("onetwothree")); + assert_eq!(child.children().count(), 1); + assert!(text[child.range()].starts_with("")); + assert!(doc.get_node(child.id()).unwrap() == child); + assert_eq!(root.children().nth(1).unwrap().tag_name().namespace(), None); + assert_eq!(root.range(), 0..text.len()); + } + + #[test] + fn malformed_dtd_and_resource_limits_are_preserved() { + // Current shared XML rejects duplicate attributes, unlike the older app pin. + assert!(Document::parse("").is_err()); + assert!(Document::parse("").is_err()); + assert!(Document::parse("").is_err()); + assert!(Document::parse("").is_err()); + assert!(Document::parse_with_options("", ParsingOptions { allow_dtd: true, nodes_limit: 8 }).is_ok()); + assert!(Document::parse_with_options("text", ParsingOptions { allow_dtd: false, nodes_limit: 1 }).is_err()); + assert!(Document::parse_with_options("", ParsingOptions { allow_dtd: false, nodes_limit: 0 }).is_err()); + let text = format!("{}{}", "".repeat(1025), "".repeat(1025)); + assert!(Document::parse(&text).is_err()); + assert!(Document::parse("").is_err()); + } +} From c50eb61065846fc6d4feca3438ffa691dc855313 Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Tue, 17 Nov 2026 10:11:04 -0500 Subject: [PATCH 16/37] Document and test inherited namespace declaration budget --- crates/xfa/README.md | 2 ++ crates/xfa/src/xml.rs | 17 +++++++++++++++++ 2 files changed, 19 insertions(+) diff --git a/crates/xfa/README.md b/crates/xfa/README.md index e4ed85e08..a3548c2d1 100644 --- a/crates/xfa/README.md +++ b/crates/xfa/README.md @@ -7,3 +7,5 @@ Preserves source byte ranges, coalesced text, namespace shadowing and document-l Original source by Dylan M. Taylor (eead4541, 7d44e654), MIT OR Apache-2.0. Compatibility delta versus the original app XML pin e2dc681a3: current strict craft-xml rejects duplicate raw or expanded attribute names. This deliberately preserves shared security hardening; valid-document DOM behavior is unchanged, but malformed acceptance and errors are not promised byte-identical. Regression tests cover both duplicate forms. + +The updated strict reader also bounds aggregate active namespace declarations to 1024 across ancestor elements, not just attributes per tag. The old app path could accept more inherited declarations. The exact boundary and one-over case are tested; this intentional tighter resource admission is retained. diff --git a/crates/xfa/src/xml.rs b/crates/xfa/src/xml.rs index 0840170e6..2f4a49db8 100644 --- a/crates/xfa/src/xml.rs +++ b/crates/xfa/src/xml.rs @@ -411,6 +411,23 @@ mod tests { assert_eq!(root.range(), 0..text.len()); } + #[test] + fn inherited_namespace_declarations_have_an_aggregate_budget() { + use std::fmt::Write; + let mut xml = String::from(""); + assert!(Document::parse(&accepted).is_ok()); + let rejected = format!("{xml} xmlns:extra='extra'/>"); + assert!(Document::parse(&rejected).is_err()); + } + #[test] fn malformed_dtd_and_resource_limits_are_preserved() { // Current shared XML rejects duplicate attributes, unlike the older app pin. From 786c5571f05595276857e7faa36c8be2fe895a7d Mon Sep 17 00:00:00 2001 From: techneissa <55485515+techneissa@users.noreply.github.com> Date: Tue, 17 Nov 2026 18:39:50 +0300 Subject: [PATCH 17/37] raw: refuse an understated DNG strip whose ActiveArea reaches below the image (#2040) decode drops such an ActiveArea for the whole image, so nothing would explain the short byte count. --- crates/raw/src/dng.rs | 2 +- crates/raw/src/dng/compat_review_tests.rs | 2 ++ 2 files changed, 3 insertions(+), 1 deletion(-) diff --git a/crates/raw/src/dng.rs b/crates/raw/src/dng.rs index a7be5d67b..f62aeef47 100644 --- a/crates/raw/src/dng.rs +++ b/crates/raw/src/dng.rs @@ -546,7 +546,7 @@ fn extend_understated_strip(bytes: &[u8], info: &mut ImageInfo, raw: &Ifd) { } let ([offset], [count]) = (&info.offsets[..], &info.byte_counts[..]) else { return }; let Some([top, left, bottom, right]) = raw.u64s(t::ACTIVE_AREA).and_then(|a| <[u64; 4]>::try_from(a).ok()) else { return }; - if left != 0 || bottom <= top || right == 0 || right >= u64::from(info.width) { + if left != 0 || bottom <= top || bottom > u64::from(info.height) || right == 0 || right >= u64::from(info.width) { return; } let row_bytes = |width: u64| width.checked_mul(u64::from(info.height))?.checked_mul(bits / 8); diff --git a/crates/raw/src/dng/compat_review_tests.rs b/crates/raw/src/dng/compat_review_tests.rs index 309d1e5b7..149ee492d 100644 --- a/crates/raw/src/dng/compat_review_tests.rs +++ b/crates/raw/src/dng/compat_review_tests.rs @@ -170,6 +170,8 @@ fn other_short_strips_are_still_refused() { assert!(refused(understated_strip_dng(8, 4, 6 * 4 * 2, None))); // the count is not exactly the area's bytes assert!(refused(understated_strip_dng(8, 4, 5 * 4 * 2, Some([0, 0, 4, 6])))); + // the area reaches below the image, so decode would discard it + assert!(refused(understated_strip_dng(8, 4, 6 * 4 * 2, Some([4, 0, 5, 6])))); // the area does not start at column 0 assert!(refused(understated_strip_dng(8, 4, 6 * 4 * 2, Some([0, 2, 4, 8])))); // the file does not hold the whole raster From 71e271483380e211f38e7d49c0765c59cff6e785 Mon Sep 17 00:00:00 2001 From: techneissa <55485515+techneissa@users.noreply.github.com> Date: Tue, 17 Nov 2026 18:47:47 +0300 Subject: [PATCH 18/37] raw: lengthen an understated DNG strip only for integer samples (#2040) SampleFormat 4 and other undefined values no longer reach the extension; an absent tag still reads as 1 (unsigned), so a file without it is unchanged. --- crates/raw/src/dng.rs | 2 +- crates/raw/src/dng/compat_review_tests.rs | 10 ++++++++++ 2 files changed, 11 insertions(+), 1 deletion(-) diff --git a/crates/raw/src/dng.rs b/crates/raw/src/dng.rs index f62aeef47..9589f5d4d 100644 --- a/crates/raw/src/dng.rs +++ b/crates/raw/src/dng.rs @@ -539,7 +539,7 @@ fn extend_understated_strip(bytes: &[u8], info: &mut ImageInfo, raw: &Ifd) { || info.compression != t::compression::NONE || info.samples_per_pixel != 1 || info.planar == 2 - || info.sample_format == 3 + || !matches!(info.sample_format, 1 | 2) || !matches!(bits, 8 | 16) { return; diff --git a/crates/raw/src/dng/compat_review_tests.rs b/crates/raw/src/dng/compat_review_tests.rs index 149ee492d..7fcc1b4f4 100644 --- a/crates/raw/src/dng/compat_review_tests.rs +++ b/crates/raw/src/dng/compat_review_tests.rs @@ -122,7 +122,15 @@ fn decoded_notices_record_actual_crop_gain_table_and_cfa_decisions() { /// A 16-bit CFA DNG of `width` x `height` whose strip holds every row in full but whose `StripByteCounts` says /// `counted` bytes. fn understated_strip_dng(width: u32, height: u32, counted: u32, active_area: Option<[u32; 4]>) -> Vec { + understated_strip_dng_with(width, height, counted, active_area, &[]) +} + +/// [`understated_strip_dng`] with `extra` tags set on the raw IFD. +fn understated_strip_dng_with(width: u32, height: u32, counted: u32, active_area: Option<[u32; 4]>, extra: &[(u16, Value)]) -> Vec { let mut raw = IfdBuilder::new(); + for (tag, value) in extra { + raw.set(*tag, value.clone()); + } for (tag, value) in [ (t::IMAGE_WIDTH, Value::Long(vec![width])), (t::IMAGE_LENGTH, Value::Long(vec![height])), @@ -170,6 +178,8 @@ fn other_short_strips_are_still_refused() { assert!(refused(understated_strip_dng(8, 4, 6 * 4 * 2, None))); // the count is not exactly the area's bytes assert!(refused(understated_strip_dng(8, 4, 5 * 4 * 2, Some([0, 0, 4, 6])))); + // samples that are neither integer nor absent-format (SampleFormat 4 is undefined) + assert!(refused(understated_strip_dng_with(8, 4, 6 * 4 * 2, Some([0, 0, 4, 6]), &[(t::SAMPLE_FORMAT, Value::Short(vec![4]))]))); // the area reaches below the image, so decode would discard it assert!(refused(understated_strip_dng(8, 4, 6 * 4 * 2, Some([4, 0, 5, 6])))); // the area does not start at column 0 From 9799e3be701c0b135ee4283facdf0ad978effcd3 Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Tue, 17 Nov 2026 12:10:30 -0500 Subject: [PATCH 19/37] Split XFA accessor regressions without weakening assertions --- crates/xfa/src/xml.rs | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/crates/xfa/src/xml.rs b/crates/xfa/src/xml.rs index 2bed07bbf..b76f4d755 100644 --- a/crates/xfa/src/xml.rs +++ b/crates/xfa/src/xml.rs @@ -433,6 +433,13 @@ mod tests { let namespaces: Vec<_> = root.namespaces().map(|n| (n.name(), n.uri())).collect(); assert!(namespaces.contains(&(None, "urn:r"))); assert!(namespaces.contains(&(Some("p"), "urn:p"))); + } + + #[test] + fn descendants_and_text_nodes_preserve_identity_and_empty_accessors() { + let doc = + Document::parse("firstsecondlast").unwrap(); + let root = doc.root_element(); let all: Vec<_> = doc.descendants().collect(); assert_eq!(all.len(), 5); assert!(all.iter().zip(root.descendants()).all(|(a, b)| *a == b)); From 7983b10f94b0c77f2568172154daad183b0daac3 Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Tue, 17 Nov 2026 14:17:25 -0500 Subject: [PATCH 20/37] dex: bound retained handler descriptors and reject overflowing offsets --- crates/dex/src/dex.rs | 129 +++++++++++++++++++++++++++++++++++++++--- 1 file changed, 122 insertions(+), 7 deletions(-) diff --git a/crates/dex/src/dex.rs b/crates/dex/src/dex.rs index e578dc397..e25acb859 100644 --- a/crates/dex/src/dex.rs +++ b/crates/dex/src/dex.rs @@ -18,6 +18,9 @@ const MAX_MEMBERS: usize = 65_536; /// Most try blocks / handlers per method. const MAX_TRIES: usize = 4096; const MAX_HANDLERS: usize = 256; +/// Most handler descriptor bytes retained while reading one code item, however many try blocks +/// share a handler list. +const MAX_HANDLER_DESCRIPTOR_BYTES: usize = 1 << 20; #[derive(Debug, Clone, Default, PartialEq, Eq, Serialize)] pub struct Header { @@ -469,10 +472,11 @@ impl<'a> Dex<'a> { } let n = r.u32_le(set_off as usize).unwrap_or(0) as usize; for i in 0..n.min(256) { - let Some(item) = r.u32_le(set_off as usize + 4 + i * 4) else { break }; + let Some(item_at) = (set_off as usize).checked_add(4).and_then(|base| base.checked_add(i * 4)) else { break }; + let Some(item) = r.u32_le(item_at) else { break }; // visibility u8, then encoded_annotation: uleb type_idx … - let vis = r.u8(item as usize).unwrap_or(0); - if let Some((t, _)) = r.uleb128(item as usize + 1) { + let (Some(vis), Some(annotation_at)) = (r.u8(item as usize), (item as usize).checked_add(1)) else { continue }; + if let Some((t, _)) = r.uleb128(annotation_at) { let v = match vis { 0 => "build", 1 => "runtime", @@ -500,8 +504,8 @@ impl<'a> Dex<'a> { }; let (Some(sf), Some(inf), Some(dm), Some(vm)) = (next(&mut pos), next(&mut pos), next(&mut pos), next(&mut pos)) else { return cd }; let remaining = self.data.len().saturating_sub(pos); - let total = [sf, inf, dm, vm].iter().map(|&x| x as usize).sum::(); - if total > remaining || total > MAX_MEMBERS * 4 { + let total: u64 = [sf, inf, dm, vm].iter().map(|&x| u64::from(x)).sum(); + if total > remaining as u64 || total > MAX_MEMBERS as u64 * 4 { return cd; } for (count, is_method, slot) in [(sf, false, 0), (inf, false, 1), (dm, true, 2), (vm, true, 3)] { @@ -559,7 +563,8 @@ impl<'a> Dex<'a> { t_off += 2; } let handlers_base = t_off + tries_size * 8; - for i in 0..tries_size.min(MAX_TRIES) { + let mut retained = 0usize; + 'tries: for i in 0..tries_size.min(MAX_TRIES) { let at = t_off + i * 8; let (Some(start), Some(count), Some(h_off)) = (r.u32_le(at), r.u16_le(at + 4), r.u16_le(at + 6)) else { break }; let mut handlers = Vec::new(); @@ -570,7 +575,13 @@ impl<'a> Dex<'a> { let Some((t, k1)) = r.uleb128(p) else { break }; let Some((addr, k2)) = r.uleb128(p + k1) else { break }; p += k1 + k2; - handlers.push(Handler { exception: Some(self.type_desc(t as u32)), address: addr as u32 }); + let desc = self.type_desc(t as u32); + let Some(next) = retained.checked_add(desc.len()) else { break 'tries }; + if next > MAX_HANDLER_DESCRIPTOR_BYTES { + break 'tries; + } + retained = next; + handlers.push(Handler { exception: Some(desc), address: addr as u32 }); } if size <= 0 && handlers.len() as u64 == size.unsigned_abs() @@ -812,4 +823,108 @@ mod tests { } } } + + fn bare_dex<'a>(data: &'a [u8], strings: Vec, types: Vec) -> Dex<'a> { + Dex { + data, + header: Header { + version: "035".into(), + checksum: String::new(), + checksum_ok: false, + signature: String::new(), + file_size: data.len() as u32, + header_size: 0x70, + endian_tag: String::new(), + string_ids: 0, + type_ids: 0, + proto_ids: 0, + field_ids: 0, + method_ids: 0, + class_defs: 0, + data_size: 0, + }, + strings, + types, + protos: Vec::new(), + fields: Vec::new(), + methods: Vec::new(), + classes: Vec::new(), + warnings: Vec::new(), + } + } + + #[test] + fn repeated_handler_lists_stop_at_the_descriptor_budget() { + let desc = format!("L{};", "a".repeat(16 * 1024)); + let mut data = vec![0u8; 4]; + data.extend_from_slice(&0u16.to_le_bytes()); + data.extend_from_slice(&0u16.to_le_bytes()); + data.extend_from_slice(&0u16.to_le_bytes()); + data.extend_from_slice(&(MAX_TRIES as u16).to_le_bytes()); + data.extend_from_slice(&0u32.to_le_bytes()); + data.extend_from_slice(&0u32.to_le_bytes()); + for _ in 0..MAX_TRIES { + data.extend_from_slice(&0u32.to_le_bytes()); + data.extend_from_slice(&1u16.to_le_bytes()); + data.extend_from_slice(&0u16.to_le_bytes()); + } + data.push(0x01); // sleb128: one typed handler + data.push(0x00); // type index 0 + data.push(0x00); // handler address + let d = bare_dex(&data, vec![desc.clone()], vec![0]); + let code = d.code(4).expect("code item"); + assert!(!code.tries.is_empty()); + assert!(code.tries.len() < MAX_TRIES, "read {} tries", code.tries.len()); + assert_eq!(code.tries[0].handlers[0].exception.as_deref(), Some(desc.as_str())); + let retained: usize = code.tries.iter().flat_map(|t| &t.handlers).filter_map(|h| h.exception.as_ref()).map(String::len).sum(); + assert!(retained <= MAX_HANDLER_DESCRIPTOR_BYTES, "{retained}"); + } + + #[test] + fn annotations_reject_an_unrepresentable_item_offset() { + let mut data = vec![0u8; 4]; + data.extend_from_slice(&8u32.to_le_bytes()); + data.extend_from_slice(&1u32.to_le_bytes()); + data.extend_from_slice(&u32::MAX.to_le_bytes()); + let d = bare_dex(&data, Vec::new(), Vec::new()); + let c = ClassDef { + class_idx: 0, + access: 0, + superclass_idx: 0, + interfaces_off: 0, + source_file_idx: 0, + annotations_off: 4, + class_data_off: 0, + static_values_off: 0, + }; + assert!(d.annotations(&c).is_empty()); + } + + #[test] + fn class_data_counts_do_not_overflow() { + let mut data = vec![0u8; 4]; + for mut x in [u32::MAX, 1, 0, 0] { + loop { + let b = (x & 0x7f) as u8; + x >>= 7; + if x == 0 { + data.push(b); + break; + } + data.push(b | 0x80); + } + } + let d = bare_dex(&data, Vec::new(), Vec::new()); + let c = ClassDef { + class_idx: 0, + access: 0, + superclass_idx: 0, + interfaces_off: 0, + source_file_idx: 0, + annotations_off: 0, + class_data_off: 4, + static_values_off: 0, + }; + assert!(!d.class_data(&c).complete); + } } From 5b1ad7511ce68a56f79d53a66b0dbddb5d2ed943 Mon Sep 17 00:00:00 2001 From: FredApps <153173854+FredApps@users.noreply.github.com> Date: Wed, 18 Nov 2026 09:17:21 +0700 Subject: [PATCH 21/37] dex: bound retained reference caller and target strings (#2115) Co-authored-by: FredApps --- crates/dex/src/dex.rs | 65 ++++++++++++++++++++++++++++++++++++++++++- 1 file changed, 64 insertions(+), 1 deletion(-) diff --git a/crates/dex/src/dex.rs b/crates/dex/src/dex.rs index e25acb859..3ecc8224c 100644 --- a/crates/dex/src/dex.rs +++ b/crates/dex/src/dex.rs @@ -686,8 +686,18 @@ pub struct Reference { pub target: String, } +/// Maximum caller and target string bytes retained across a reference query. +/// A count limit alone cannot bound repeated, amplified method signatures. +const MAX_REFERENCE_BYTES: usize = 64 << 20; + /// Every instruction that refers to class `desc` (optionally only its methods named `method`). +/// Returns a truncated prefix when the count or aggregate caller/target byte budget is exhausted. pub fn references(dex: &Dex<'_>, desc: &str, method: Option<&str>, max: usize) -> (Vec, bool) { + references_with_byte_limit(dex, desc, method, max, MAX_REFERENCE_BYTES) +} + +fn references_with_byte_limit(dex: &Dex<'_>, desc: &str, method: Option<&str>, max: usize, max_bytes: usize) -> (Vec, bool) { + let mut bytes_left = max_bytes; let mut out = Vec::new(); for c in &dex.classes { let cd = dex.class_data(c); @@ -715,7 +725,12 @@ pub fn references(dex: &Dex<'_>, desc: &str, method: Option<&str>, max: usize) - if out.len() >= max { return (out, true); } - out.push(Reference { caller: dex.method_ref(m.method_idx), offset: i.offset, instruction: i.name, kind, target }); + let caller = dex.method_ref(m.method_idx); + let Some(left) = bytes_left.checked_sub(caller.len()).and_then(|left| left.checked_sub(target.len())) else { + return (out, true); + }; + bytes_left = left; + out.push(Reference { caller, offset: i.offset, instruction: i.name, kind, target }); } } } @@ -927,4 +942,52 @@ mod tests { }; assert!(!d.class_data(&c).complete); } + + #[test] + fn references_bound_repeated_long_signatures_before_retaining_results() { + let mut data = vec![0u8; 578]; + data[4..8].copy_from_slice(&256u32.to_le_bytes()); + // 256 parameter entries all refer to the same long descriptor. + // One direct method at offset 520, with code at 544 (ULEB128 A0 04). + data[520..528].copy_from_slice(&[0, 0, 1, 0, 0, 0, 0xa0, 4]); + data[556..560].copy_from_slice(&9u32.to_le_bytes()); + for offset in [560, 566, 572] { + data[offset..offset + 2].copy_from_slice(&0x0071u16.to_le_bytes()); + } + let desc = format!("L{};", "x".repeat(256)); + let mut dex = bare_dex(&data, vec![desc.clone(), "run".into()], vec![0]); + dex.protos.push(ProtoId { shorty: 0, ret: 0, params_off: 4 }); + dex.methods.push(MemberId { class_idx: 0, type_or_proto: 0, name_idx: 1 }); + dex.classes.push(ClassDef { + class_idx: 0, + access: 0, + superclass_idx: NO_INDEX, + interfaces_off: 0, + source_file_idx: NO_INDEX, + annotations_off: 0, + class_data_off: 520, + static_values_off: 0, + }); + let signature = dex.method_ref(0); + assert!(signature.len() > 256 * 256); + let pair_bytes = signature.len() * 2; + let (all, truncated) = references_with_byte_limit(&dex, &desc, Some("run"), 100, pair_bytes * 3); + assert!(!truncated); + assert_eq!(all.len(), 3); + assert!(all.iter().all(|r| r.caller == signature && r.target == signature)); + let (bounded, truncated) = references_with_byte_limit(&dex, &desc, Some("run"), 100, pair_bytes * 2); + assert!(truncated); + assert_eq!(bounded, all[..2]); + assert_eq!(bounded.iter().map(|r| r.caller.len() + r.target.len()).sum::(), pair_bytes * 2); + let (below_one, truncated) = references_with_byte_limit(&dex, &desc, Some("run"), 100, pair_bytes - 1); + assert!(truncated); + assert!(below_one.is_empty()); + let (count_limited, truncated) = references_with_byte_limit(&dex, &desc, Some("run"), 1, usize::MAX); + assert!(truncated); + assert_eq!(count_limited, all[..1]); + let (zero, truncated) = references_with_byte_limit(&dex, &desc, Some("run"), 0, usize::MAX); + assert!(truncated); + assert!(zero.is_empty()); + assert_eq!(references(&dex, &desc, Some("run"), 100), (all, false)); + } } From 72d8ac7c6cfe846cb848a3938d08a1474d4260c9 Mon Sep 17 00:00:00 2001 From: FredApps <153173854+FredApps@users.noreply.github.com> Date: Wed, 18 Nov 2026 09:17:29 +0700 Subject: [PATCH 22/37] fix(xfa): bound retained namespace copies before allocation (#2122) Co-authored-by: FredApps --- crates/xfa/README.md | 4 ++-- crates/xfa/src/xml.rs | 50 ++++++++++++++++++++++++++++++++++++------- 2 files changed, 44 insertions(+), 10 deletions(-) diff --git a/crates/xfa/README.md b/crates/xfa/README.md index a3548c2d1..21620cbb9 100644 --- a/crates/xfa/README.md +++ b/crates/xfa/README.md @@ -1,8 +1,8 @@ # craft-xfa -Scoped namespace-aware XML DOM extracted unchanged from PDFCraft xfa/xml.rs at 271e479c. This is not a complete XFA implementation: template interpretation, packets, data binding, scripts, layout, fonts and PDF generation remain app-owned. +Scoped namespace-aware XML DOM extracted from PDFCraft xfa/xml.rs at 271e479c. This is not a complete XFA implementation: template interpretation, packets, data binding, scripts, layout, fonts and PDF generation remain app-owned. -Preserves source byte ranges, coalesced text, namespace shadowing and document-local node identities. Uses craft-xml strict events with DTD rejection by default, depth 1024 and caller node count. Other event-reader defaults remain in force. Namespace snapshots are copied per element as before; this is not a new total-memory bound or a full XML namespaces conformance claim. +Preserves source byte ranges, coalesced text, namespace shadowing and document-local node identities. Uses craft-xml strict events with DTD rejection by default, depth 1024 and caller node count. Other event-reader defaults remain in force. Namespace snapshots are copied per element as before, with a 64 MiB cumulative pre-allocation budget for snapshot entry headers, prefix/URI bytes and resolved element/attribute namespace URI copies. Excess returns an error. This intentionally tightens resource admission; it is not a total DOM memory bound or a full XML namespaces conformance claim. Original source by Dylan M. Taylor (eead4541, 7d44e654), MIT OR Apache-2.0. diff --git a/crates/xfa/src/xml.rs b/crates/xfa/src/xml.rs index b76f4d755..70fe5d580 100644 --- a/crates/xfa/src/xml.rs +++ b/crates/xfa/src/xml.rs @@ -2,6 +2,7 @@ use std::ops::Range; +const MAX_NAMESPACE_BYTES: usize = 64 << 20; const XML_NS: &str = "http://www.w3.org/XML/1998/namespace"; const XMLNS_NS: &str = "http://www.w3.org/2000/xmlns/"; @@ -139,31 +140,49 @@ fn split_qname(qname: &str) -> (&str, &str) { } } -fn resolve_ns(scope: &[(String, String)], prefix: &str, is_attr: bool) -> Result, String> { +// One long inherited URI otherwise gets copied into every descendant. Charge retained +// namespace strings and snapshot entry headers before copying, across the whole document. +fn charge_namespace(bytes: &mut usize, amount: usize) -> Result<(), String> { + *bytes = bytes.checked_sub(amount).ok_or_else(|| "namespace retention budget exceeded".to_string())?; + Ok(()) +} + +fn copy_namespace(uri: &str, bytes: &mut usize) -> Result, String> { + charge_namespace(bytes, uri.len())?; + Ok(Some(uri.to_string())) +} + +fn resolve_ns(scope: &[(String, String)], prefix: &str, is_attr: bool, bytes: &mut usize) -> Result, String> { if prefix == "xml" { - return Ok(Some(XML_NS.to_string())); + return copy_namespace(XML_NS, bytes); } if prefix == "xmlns" { - return Ok(Some(XMLNS_NS.to_string())); + return copy_namespace(XMLNS_NS, bytes); } if prefix.is_empty() { if is_attr { return Ok(None); } - return Ok(scope.iter().rev().find(|(p, _)| p.is_empty()).and_then(|(_, u)| (!u.is_empty()).then(|| u.clone()))); + return match scope.iter().rev().find(|(p, _)| p.is_empty()) { + Some((_, u)) if !u.is_empty() => copy_namespace(u, bytes), + _ => Ok(None), + }; } match scope.iter().rev().find(|(p, _)| p == prefix) { - Some((_, u)) if !u.is_empty() => Ok(Some(u.clone())), + Some((_, u)) if !u.is_empty() => copy_namespace(u, bytes), _ => Err(format!("undeclared namespace prefix: {prefix}")), } } - impl Document { pub fn parse(text: &str) -> Result { Self::parse_with_options(text, ParsingOptions::default()) } pub fn parse_with_options(text: &str, options: ParsingOptions) -> Result { + Self::parse_with_namespace_budget(text, options, MAX_NAMESPACE_BYTES) + } + + fn parse_with_namespace_budget(text: &str, options: ParsingOptions, mut namespace_bytes: usize) -> Result { let mut opts = craft_xml::Options { strict: true, doctype: if options.allow_dtd { craft_xml::Doctype::Ignore } else { craft_xml::Doctype::Reject }, @@ -194,20 +213,23 @@ impl Document { } } let (el_prefix, el_local) = split_qname(&name); - let el_ns = resolve_ns(&scope, el_prefix, false)?; + let el_ns = resolve_ns(&scope, el_prefix, false, &mut namespace_bytes)?; let mut el_attrs = Vec::new(); for (k, v) in attrs { if k == "xmlns" || k.starts_with("xmlns:") { continue; } let (ap, al) = split_qname(&k); - let ans = resolve_ns(&scope, ap, true)?; + let ans = resolve_ns(&scope, ap, true, &mut namespace_bytes)?; el_attrs.push(AttrData { ns: ans, name: al.to_string(), value: v }); } // Deduplicate in-scope namespace bindings, keeping the innermost binding per prefix. let mut namespaces: Vec<(String, String)> = Vec::new(); for (p, u) in scope.iter().rev() { if !namespaces.iter().any(|(ep, _)| ep == p) { + charge_namespace(&mut namespace_bytes, std::mem::size_of::<(String, String)>())?; + charge_namespace(&mut namespace_bytes, p.len())?; + charge_namespace(&mut namespace_bytes, u.len())?; namespaces.push((p.clone(), u.clone())); } } @@ -391,6 +413,18 @@ impl<'a> Node<'a> { mod tests { use super::*; + #[test] + fn inherited_namespace_copies_obey_aggregate_byte_admission() { + let uri = format!("urn:{}", "x".repeat(124)); + let snapshot = std::mem::size_of::<(String, String)>() + 1 + uri.len(); + for (child, expanded_copies) in [("", 0), ("", 1), ("", 1), ("", 2)] { + let input = format!("{}", child.repeat(8)); + let needed = 9 * snapshot + 8 * expanded_copies * uri.len(); + assert!(Document::parse_with_namespace_budget(&input, ParsingOptions::default(), needed).is_ok()); + assert!(Document::parse_with_namespace_budget(&input, ParsingOptions::default(), needed - 1).is_err()); + assert!(Document::parse_with_namespace_budget(&input, ParsingOptions::default(), 0).is_err()); + } + } #[test] fn namespace_shadowing_attributes_text_and_source_ranges() { let text = "onethree"; From aa423ded8095ce5a92e1590aee31a6625f54febe Mon Sep 17 00:00:00 2001 From: FredApps <153173854+FredApps@users.noreply.github.com> Date: Wed, 18 Nov 2026 03:36:07 +0100 Subject: [PATCH 23/37] docs(xfa): distinguish extracted baseline from later hardening --- ATTRIBUTION.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/ATTRIBUTION.md b/ATTRIBUTION.md index 63061b638..eb9a55eeb 100644 --- a/ATTRIBUTION.md +++ b/ATTRIBUTION.md @@ -145,7 +145,7 @@ Sanitization, animation fitting and numeric output policy remain caller-owned. ## XFA XML DOM -`crates/xfa/src/xml.rs` is extracted from PDFCraft at `271e479c53723b1b294c866d5cb2f27604601b29`, originally by Dylan M. Taylor (`eead4541`, `7d44e654`), MIT OR Apache-2.0. Only visibility and module boundaries change; PDF/layout/form policy remains in the app. +`crates/xfa/src/xml.rs` is extracted from PDFCraft at `271e479c53723b1b294c866d5cb2f27604601b29`, originally by Dylan M. Taylor (`eead4541`, `7d44e654`), MIT OR Apache-2.0. The initial extraction changes visibility and module boundaries; subsequent namespace-retention budget hardening intentionally tightens resource admission. PDF/layout/form policy remains in the app. ## Java class inspection From c255ab0e517b489fdefb69500456c755d6ecd763 Mon Sep 17 00:00:00 2001 From: skylar taylor-barrick Date: Wed, 18 Nov 2026 04:43:01 +0100 Subject: [PATCH 24/37] fix(html): keep widthless colgroups on cell-width fallback --- crates/html/src/doc/builder.rs | 2 +- crates/html/src/doc/tests.rs | 17 +++++++++++++++++ 2 files changed, 18 insertions(+), 1 deletion(-) diff --git a/crates/html/src/doc/builder.rs b/crates/html/src/doc/builder.rs index b6859523f..022a51015 100644 --- a/crates/html/src/doc/builder.rs +++ b/crates/html/src/doc/builder.rs @@ -935,7 +935,7 @@ impl<'r> Builder<'r> { ft.rows.retain(|r| !r.is_empty()); } if !ft.rows.is_empty() { - if !col_widths.is_empty() && ft.cols() <= MAX_TABLE_COLS { + if col_widths.iter().any(Option::is_some) && ft.cols() <= MAX_TABLE_COLS { let mut widths = vec![None; ft.cols()]; for (i, &cw) in col_widths.iter().take(ft.cols()).enumerate() { if let Some(w) = cw { diff --git a/crates/html/src/doc/tests.rs b/crates/html/src/doc/tests.rs index 6c4e5fe8e..c81687d48 100644 --- a/crates/html/src/doc/tests.rs +++ b/crates/html/src/doc/tests.rs @@ -1,5 +1,22 @@ use super::*; +#[test] +fn widthless_columns_do_not_change_cell_width_resolution() { + let widths = |columns: &str, cells: &str| { + let flow = parse(&format!("{columns}{cells}
")); + let FBlock::Table(table) = &flow.blocks[0] else { panic!("expected table") }; + table.widths.clone() + }; + let partial = "xy"; + let widthless = ""; + assert!(widths("", partial).is_empty()); + assert_eq!(widths(widthless, partial), widths("", partial)); + let complete = "xy"; + assert_eq!(widths(widthless, complete), vec![30.0, 60.0]); + // An explicitly declared column still enables the existing average-fill rule. + assert_eq!(widths("", "xy"), vec![100.0, 100.0]); +} + #[test] fn numeric_entity_rejects_sign() { assert_eq!(unescape("a&#+65;b"), "a&#+65;b"); From 50fbf2bd0c05a88f95c95019f6752a1fccd94479 Mon Sep 17 00:00:00 2001 From: FredApps <153173854+FredApps@users.noreply.github.com> Date: Wed, 18 Nov 2026 11:07:00 +0700 Subject: [PATCH 25/37] testkit: share exact format mutation corpus across DEX WASM and TAR (#2106) Co-authored-by: FredApps --- Cargo.lock | 1 + crates/dex/Cargo.toml | 3 +++ crates/dex/src/test_support.rs | 42 +---------------------------- crates/testkit/src/sample_damage.rs | 39 +++++++++++++++++++++++++++ 4 files changed, 44 insertions(+), 41 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 62f2866e4..5147fa867 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1757,6 +1757,7 @@ dependencies = [ name = "craft-dex" version = "0.1.0" dependencies = [ + "craft-testkit", "serde", "thiserror 2.0.21", ] diff --git a/crates/dex/Cargo.toml b/crates/dex/Cargo.toml index e4eb285f5..fc7e35d1d 100644 --- a/crates/dex/Cargo.toml +++ b/crates/dex/Cargo.toml @@ -11,3 +11,6 @@ workspace=true [dependencies] serde={workspace=true} thiserror={workspace=true} + +[dev-dependencies] +craft-testkit = { workspace = true } diff --git a/crates/dex/src/test_support.rs b/crates/dex/src/test_support.rs index a3a179145..5d50cd671 100644 --- a/crates/dex/src/test_support.rs +++ b/crates/dex/src/test_support.rs @@ -1,45 +1,5 @@ // Synthetic DEX fixture and deterministic mutations retained from Craft Anything. -/// Deterministic pseudo-random bytes (xorshift) for fuzz-like loops. -pub fn noise(seed: u64, len: usize) -> Vec { - let mut x = seed.wrapping_mul(0x9e37_79b9_7f4a_7c15) | 1; - (0..len) - .map(|_| { - x ^= x << 13; - x ^= x >> 7; - x ^= x << 17; - x as u8 - }) - .collect() -} - -/// Every way to damage a sample used by robustness tests: truncations at many lengths and -/// single-byte corruptions spread across the file. -pub fn mutations(sample: &[u8]) -> Vec> { - let mut out = Vec::new(); - let n = sample.len(); - let step = (n / 64).max(1); - let mut len = 0; - while len < n { - out.push(sample[..len].to_vec()); - len += step; - } - for (i, seed) in (0..n).step_by(step).zip(1u64..) { - let mut m = sample.to_vec(); - let noise = noise(seed, 8); - for (j, v) in noise.iter().enumerate() { - if let Some(b) = m.get_mut(i + j) { - *b = *v; - } - } - out.push(m); - let mut m = sample.to_vec(); - if let Some(b) = m.get_mut(i) { - *b = 0xff; - } - out.push(m); - } - out -} +pub use craft_testkit::sample_damage::{mutations, noise}; pub mod android { pub const HELLO: &str = "Hello, Craft!"; diff --git a/crates/testkit/src/sample_damage.rs b/crates/testkit/src/sample_damage.rs index f0bdec729..b2fbeb757 100644 --- a/crates/testkit/src/sample_damage.rs +++ b/crates/testkit/src/sample_damage.rs @@ -72,3 +72,42 @@ mod tests { } } } + +#[cfg(test)] +mod dex_corpus_compatibility_tests { + use super::*; + + #[test] + fn noise_keeps_zero_wrapping_seed_and_draw_order() { + assert_eq!(noise(0, 8), [65, 65, 41, 37, 101, 1, 113, 13]); + assert_eq!(noise(1, 8), [173, 118, 54, 116, 236, 121, 207, 234]); + assert_eq!(noise(u64::MAX, 8), [44, 200, 255, 170, 173, 156, 79, 209]); + assert!(noise(1, 0).is_empty()); + } + + #[test] + fn mutation_order_and_empty_sample_are_stable() { + assert!(mutations(&[]).is_empty()); + assert_eq!(mutations(&[1, 2]), vec![vec![], vec![1], vec![173, 118], vec![255, 2], vec![1, 27], vec![1, 255]]); + } + + #[test] + fn stride_transition_preserves_every_original_case() { + for len in [1, 63, 64, 65, 127, 128, 129, 1024] { + let seed = vec![7; len]; + let step = (len / 64).max(1); + let cases = mutations(&seed); + let positions: Vec = (0..len).step_by(step).collect(); + assert_eq!(cases.len(), positions.len() * 3); + for (case, &end) in cases.iter().zip(&positions) { + assert_eq!(case.as_slice(), &seed[..end]); + } + for (pair, &offset) in cases[positions.len()..].as_chunks::<2>().0.iter().zip(&positions) { + assert_eq!(pair[0].len(), len); + let mut expected = seed.clone(); + expected[offset] = 255; + assert_eq!(pair[1], expected); + } + } + } +} From 80f1cedd4bc66b927a6fd8fbc979ca9995523bd9 Mon Sep 17 00:00:00 2001 From: FredApps <153173854+FredApps@users.noreply.github.com> Date: Wed, 18 Nov 2026 12:39:50 +0700 Subject: [PATCH 26/37] fix(xfa): retain original source ranges after UTF-8 BOM (#2160) * test(xfa): reproduce BOM-relative source ranges * fix(xfa): translate BOM-stripped spans to original input --- crates/xfa/src/xml.rs | 24 +++++++++++++++++++++++- 1 file changed, 23 insertions(+), 1 deletion(-) diff --git a/crates/xfa/src/xml.rs b/crates/xfa/src/xml.rs index 70fe5d580..7afab7600 100644 --- a/crates/xfa/src/xml.rs +++ b/crates/xfa/src/xml.rs @@ -191,7 +191,11 @@ impl Document { opts.limits.max_nodes = options.nodes_limit as usize; opts.limits.max_depth = crate::MAX_XML_DEPTH; - let mut events = opts.events(text.as_bytes()); + // quick-xml excludes a leading UTF-8 BOM from its buffer positions. + // Parse it explicitly so every stored range still addresses the original input. + let input = text.strip_prefix('\u{feff}').unwrap_or(text); + let source_offset = text.len() - input.len(); + let mut events = opts.events(input.as_bytes()); let mut nodes: Vec = Vec::new(); let mut open: Vec<(usize, usize)> = Vec::new(); // (node_id, scope_len_before) let mut scope: Vec<(String, String)> = Vec::new(); @@ -199,6 +203,7 @@ impl Document { while let Some(ev) = events.next().map_err(|e| e.to_string())? { let span = events.span(); + let span = span.start + source_offset..span.end + source_offset; match ev { craft_xml::Event::Start { name, attrs } => { if nodes.len() >= options.nodes_limit as usize { @@ -413,6 +418,23 @@ impl<'a> Node<'a> { mod tests { use super::*; + #[test] + fn element_ranges_slice_original_input_with_utf8_bom() { + for prefix in ["", "\u{feff}", "\u{feff}"] { + for child_xml in ["<é/>", "<é>text"] { + let root_xml = format!("{child_xml}"); + let input = format!("{prefix}{root_xml}"); + let doc = Document::parse(&input).unwrap(); + let root = doc.root_element(); + let child = root.children().next().unwrap(); + assert_eq!(input.get(root.range()), Some(root_xml.as_str())); + assert_eq!(input.get(child.range()), Some(child_xml)); + assert_eq!(root.range(), prefix.len()..input.len()); + assert_eq!(child.range(), prefix.len() + 3..prefix.len() + 3 + child_xml.len()); + } + } + } + #[test] fn inherited_namespace_copies_obey_aggregate_byte_admission() { let uri = format!("urn:{}", "x".repeat(124)); From 6a18b99d6f719467780da4333e6b2b49a5c937fa Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Wed, 18 Nov 2026 01:01:37 -0500 Subject: [PATCH 27/37] fix(dex): report partial instruction decoding and encode fixture UTF-16 --- crates/dex/src/dex.rs | 55 ++++++++++++++++++++++++++++++++-- crates/dex/src/test_support.rs | 3 +- 2 files changed, 53 insertions(+), 5 deletions(-) diff --git a/crates/dex/src/dex.rs b/crates/dex/src/dex.rs index 3ecc8224c..253af049c 100644 --- a/crates/dex/src/dex.rs +++ b/crates/dex/src/dex.rs @@ -691,7 +691,7 @@ pub struct Reference { const MAX_REFERENCE_BYTES: usize = 64 << 20; /// Every instruction that refers to class `desc` (optionally only its methods named `method`). -/// Returns a truncated prefix when the count or aggregate caller/target byte budget is exhausted. +/// Reports truncation when instruction decoding is incomplete or the count or byte budget is exhausted. pub fn references(dex: &Dex<'_>, desc: &str, method: Option<&str>, max: usize) -> (Vec, bool) { references_with_byte_limit(dex, desc, method, max, MAX_REFERENCE_BYTES) } @@ -699,11 +699,13 @@ pub fn references(dex: &Dex<'_>, desc: &str, method: Option<&str>, max: usize) - fn references_with_byte_limit(dex: &Dex<'_>, desc: &str, method: Option<&str>, max: usize, max_bytes: usize) -> (Vec, bool) { let mut bytes_left = max_bytes; let mut out = Vec::new(); + let mut complete = true; for c in &dex.classes { let cd = dex.class_data(c); for m in cd.direct_methods.iter().chain(&cd.virtual_methods) { let Some(code) = dex.code(m.code_off) else { continue }; - let (insns, _) = crate::dex_ops::decode(&code.insns, 200_000); + let (insns, decoded) = crate::dex_ops::decode(&code.insns, 200_000); + complete &= decoded; for i in &insns { let Some(idx) = i.index else { continue }; let hit = match i.index_kind { @@ -735,7 +737,7 @@ fn references_with_byte_limit(dex: &Dex<'_>, desc: &str, method: Option<&str>, m } } } - (out, false) + (out, !complete) } #[cfg(test)] @@ -990,4 +992,51 @@ mod tests { assert!(zero.is_empty()); assert_eq!(references(&dex, &desc, Some("run"), 100), (all, false)); } + #[test] + fn references_report_incomplete_instruction_decoding() { + for (insns, incomplete) in [(vec![0x000e], false), (vec![0x0071], true), (vec![0; 200_001], true)] { + let mut b = fx::DexBuilder::default(); + let class = b.ty("Ltest;"); + let method = b.method("Ltest;", "run", "V", &[]); + b.classes.push(fx::ClassSpec { + class, + direct: vec![fx::MethodSpec { method, access: 0, code: Some(fx::CodeSpec { insns, ..Default::default() }) }], + ..Default::default() + }); + let bytes = b.build(); + let dex = parse(&bytes).unwrap(); + let (hits, truncated) = references(&dex, "Lmissing;", None, 100); + assert!(hits.is_empty()); + assert_eq!(truncated, incomplete); + } + } + + #[test] + fn references_keep_incompleteness_across_later_complete_methods() { + let mut b = fx::DexBuilder::default(); + let class = b.ty("Ltest;"); + let broken = b.method("Ltest;", "broken", "V", &[]); + let complete = b.method("Ltest;", "complete", "V", &[]); + b.classes.push(fx::ClassSpec { + class, + direct: vec![ + fx::MethodSpec { method: broken, access: 0, code: Some(fx::CodeSpec { insns: vec![0x0071], ..Default::default() }) }, + fx::MethodSpec { method: complete, access: 0, code: Some(fx::CodeSpec { insns: vec![0x000e], ..Default::default() }) }, + ], + ..Default::default() + }); + let bytes = b.build(); + let dex = parse(&bytes).unwrap(); + assert_eq!(references(&dex, "Lmissing;", None, 100), (Vec::new(), true)); + } + + #[test] + fn fixture_strings_round_trip_supplementary_and_null_characters() { + let mut b = fx::DexBuilder::default(); + let text = "a\0é😀z"; + let id = b.string(text); + let bytes = b.build(); + let dex = parse(&bytes).unwrap(); + assert_eq!(dex.string(id), text); + } } diff --git a/crates/dex/src/test_support.rs b/crates/dex/src/test_support.rs index 5d50cd671..772a9f0e4 100644 --- a/crates/dex/src/test_support.rs +++ b/crates/dex/src/test_support.rs @@ -176,8 +176,7 @@ pub mod android { for s in &self.strings { string_offs.push(at(&d)); uleb(&mut d, s.encode_utf16().count() as u32); - for ch in s.chars() { - let c = ch as u32; + for c in s.encode_utf16() { if c == 0 { d.extend_from_slice(&[0xc0, 0x80]); } else if c < 0x80 { From 5ae0786c5bb1206d70c5d26cd3778253deed06b6 Mon Sep 17 00:00:00 2001 From: chasse20 Date: Wed, 18 Nov 2026 01:54:53 -0500 Subject: [PATCH 28/37] Publish MCMAT v3 as a bounded procedural source archive --- crates/mcmat/README.md | 21 +-- crates/mcmat/src/lib.rs | 283 ++++++++++++++++++---------------------- 2 files changed, 133 insertions(+), 171 deletions(-) diff --git a/crates/mcmat/README.md b/crates/mcmat/README.md index 074a0ac44..2f69e68c9 100644 --- a/crates/mcmat/README.md +++ b/crates/mcmat/README.md @@ -1,17 +1,10 @@ # craft-mcmat -A bounded reader and writer for portable MaterialCraft `.mcmat` ZIP packages. A package -contains `material.json`, named texture maps and a source package. Applications interpret -parameter values and cook or render maps themselves; this crate does not depend on an app's -model. It supports callers that read either version 1 or version 2 of the manifest, or both. +The MCMAT v3 portable material is a ZIP containing a version-only `material.json`, one +`source.sbs`, and the required source assets under `resources/`. The sole root-level +material graph in the SBS is the entry. Applications inspect its exposed controls and +cook its outputs through MaterialCraft. Texture maps and MaterialX documents are generated +by exporters. Earlier archives must be republished from their original projects. -`is_material` checks for a manifest with a bounded ZIP index; `Material::open` takes caller-provided version, entry-count, map-count, per-entry and total -expanded-byte limits. Each subsequent `read` and `read_source` shares that budget, including -repeated references to the same ZIP member. Duplicate member names are refused. The manifest -preserves unknown fields at the top level and on maps; parameter, input and preset objects are -kept as JSON values so their unknown fields survive too. `write` preserves the caller's source -entry name and map names, and rejects duplicate archive member names through `craft-zip`. - -The source package is opaque. Version 1 commonly names `source.mcraft`; MaterialCraft's version 2 -writer names `source.sbs`. Callers that invoke another application must preserve the source's -format and extension rather than infer it from `.mcmat` alone. +`Material::open` checks archive entries and expansion budgets before returning source +files. `write` compresses the XML and version marker and preserves source asset bytes. diff --git a/crates/mcmat/src/lib.rs b/crates/mcmat/src/lib.rs index 75b8709ef..076fe636a 100644 --- a/crates/mcmat/src/lib.rs +++ b/crates/mcmat/src/lib.rs @@ -1,133 +1,126 @@ #![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)] #![forbid(unsafe_code)] -//! Bounded interchange for MaterialCraft portable materials (`.mcmat`). -//! -//! The manifest and its version belong to the format, while interpreting parameter values, -//! cooking maps and opening the source package belong to the caller. Unknown fields survive -//! deserialization and serialization, including fields added by later versions. - -use std::collections::BTreeMap; +//! The clean-room MCMAT v3 source archive. Applications interpret the SBS entry graph. use craft_zip::{Archive, Compression, Writer}; -use serde::{Deserialize, Serialize}; -use serde_json::Value; +use serde::Deserialize; +use std::collections::{BTreeMap, BTreeSet}; -pub const FORMAT: &str = "craft-material"; +pub const VERSION: u32 = 3; pub const MANIFEST_ENTRY: &str = "material.json"; +pub const SOURCE_ENTRY: &str = "source.sbs"; +const MARKER: &[u8] = br#"{"version":3}"#; -/// A portable manifest; typed parameter values remain JSON so applications can adapt their own model. -#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] -#[serde(rename_all = "camelCase")] -pub struct Manifest { - pub format: String, - pub version: u32, - pub name: String, - pub graph: String, - pub size: [u32; 2], - pub maps: Vec, - #[serde(default)] - pub parameters: Vec, - #[serde(default)] - pub inputs: Vec, - #[serde(default)] - pub presets: Vec, - pub source: String, - #[serde(flatten)] - pub extra: BTreeMap, -} - -#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] -#[serde(rename_all = "camelCase")] -pub struct MapEntry { - pub usage: String, - pub file: String, - #[serde(flatten)] - pub extra: BTreeMap, -} - -/// All limits are supplied by the consumer, including the versions it understands. #[derive(Clone, Copy, Debug)] pub struct Limits { - pub min_version: u32, - pub max_version: u32, pub max_entries: u64, - pub max_maps: usize, pub max_manifest_bytes: u64, pub max_entry_bytes: u64, pub max_total_bytes: u64, } +impl Default for Limits { + fn default() -> Self { + Self { max_entries: 100_000, max_manifest_bytes: 64 << 20, max_entry_bytes: 256 << 20, max_total_bytes: 1 << 30 } + } +} + #[derive(Debug, thiserror::Error)] pub enum Error { #[error("invalid portable material: {0}")] Invalid(String), - #[error("unsupported portable material version {0}")] + #[error("unsupported .mcmat version {0} (expected 3). Republish from the original authoring project")] Version(u32), - #[error("portable material limit: {0}")] - Limit(String), #[error("portable material archive: {0}")] Archive(#[from] craft_zip::Error), } -/// Whether a bounded ZIP index contains a material manifest. This does not validate the manifest. +/// File sniffing also recognizes old manifests so the reader can give republishing guidance. pub fn is_material(bytes: &[u8], max_entries: u64) -> bool { - Archive::open(bytes, craft_zip::Limits { max_entries, max_total_bytes: 0 }) - .is_ok_and(|archive| !archive.has_duplicate_names() && archive.contains(MANIFEST_ENTRY)) + Archive::open(bytes, craft_zip::Limits { max_entries, max_total_bytes: 0 }).is_ok_and(|archive| archive.contains(MANIFEST_ENTRY)) } -/// Manifest and original archive, retaining one shared expanded-byte budget across reads. -pub struct Material<'a> { - pub manifest: Manifest, - archive: Archive<'a>, - max_entry_bytes: u64, +fn valid_resource(name: &str) -> bool { + name.len() <= 4096 + && name.starts_with("resources/") + && !name.contains(['\\', ':']) + && !name.chars().any(char::is_control) + && name.split('/').all(|part| !matches!(part, "" | "." | "..")) } -impl<'a> Material<'a> { - pub fn open(bytes: &'a [u8], limits: Limits) -> Result { +#[derive(Debug)] +pub struct Material { + pub source: Vec, + /// Keys are paths relative to source.sbs, including the resources/ prefix. + pub resources: BTreeMap>, +} + +impl Material { + pub fn open(bytes: &[u8], limits: Limits) -> Result { let mut archive = Archive::open(bytes, craft_zip::Limits { max_entries: limits.max_entries, max_total_bytes: limits.max_total_bytes })?; - if archive.has_duplicate_names() { - return Err(Error::Invalid("duplicate archive entries".into())); + if archive.has_duplicate_names() || archive.has_overlapping_files()? { + return Err(Error::Invalid("duplicate or overlapping archive entries".into())); } - let json = archive.read(MANIFEST_ENTRY, limits.max_manifest_bytes)?.ok_or_else(|| Error::Invalid("material.json is missing".into()))?; - let manifest: Manifest = serde_json::from_slice(&json).map_err(|e| Error::Invalid(format!("material.json: {e}")))?; - if manifest.format != FORMAT { - return Err(Error::Invalid(format!("format `{}`", manifest.format))); + let json = archive.read(MANIFEST_ENTRY, limits.max_manifest_bytes)?.ok_or_else(|| Error::Invalid("missing material.json".into()))?; + #[derive(Deserialize)] + struct Version { + version: u32, } - if !(limits.min_version..=limits.max_version).contains(&manifest.version) { - return Err(Error::Version(manifest.version)); + let marker: Version = serde_json::from_slice(&json).map_err(|err| Error::Invalid(format!("material.json: {err}")))?; + if marker.version != VERSION { + return Err(Error::Version(marker.version)); } - if manifest.maps.len() > limits.max_maps { - return Err(Error::Limit(format!("{} maps exceeds {}", manifest.maps.len(), limits.max_maps))); + #[derive(Deserialize)] + #[serde(deny_unknown_fields)] + struct Marker { + version: u32, } - Ok(Self { manifest, archive, max_entry_bytes: limits.max_entry_bytes }) - } - - /// Read one named member, charging it to the same budget as previous reads. - pub fn read(&mut self, name: &str) -> Result, Error> { - self.archive.read(name, self.max_entry_bytes)?.ok_or_else(|| Error::Invalid(format!("{name} is missing"))) - } - - pub fn read_source(&mut self) -> Result, Error> { - self.read(&self.manifest.source.clone()) + if !serde_json::from_slice::(&json).is_ok_and(|m| m.version == VERSION) { + return Err(Error::Invalid("material.json must contain only the version".into())); + } + let source = archive.read(SOURCE_ENTRY, limits.max_entry_bytes)?.ok_or_else(|| Error::Invalid("missing source.sbs".into()))?; + let mut resources = BTreeMap::new(); + let mut seen = BTreeSet::new(); + for index in 0..archive.len() { + let name = archive.entry_name(index)?.ok_or_else(|| Error::Invalid("invalid entry name".into()))?; + if name == SOURCE_ENTRY || name == MANIFEST_ENTRY { + continue; + } + if name.strip_suffix('/').is_some_and(|dir| dir == "resources" || valid_resource(dir)) { + continue; + } + if !valid_resource(&name) || !seen.insert(name.to_ascii_lowercase()) { + return Err(Error::Invalid(format!("invalid or ambiguous resource path `{name}`"))); + } + let data = archive.read(&name, limits.max_entry_bytes)?.ok_or_else(|| Error::Invalid(format!("missing `{name}`")))?; + resources.insert(name, data); + } + Ok(Self { source, resources }) } } -/// Write a manifest, its named maps, and the source. Duplicate member names are rejected. -pub fn write(manifest: &Manifest, maps: &[(String, Vec)], source: &[u8]) -> Result, Error> { - // Flattened fields must not serialize a second copy of a known key. - const KNOWN: &[&str] = &["format", "version", "name", "graph", "size", "maps", "parameters", "inputs", "presets", "source"]; - if manifest.extra.keys().any(|key| KNOWN.contains(&key.as_str())) - || manifest.maps.iter().any(|map| map.extra.contains_key("usage") || map.extra.contains_key("file")) - { - return Err(Error::Invalid("an extra field duplicates a known field".into())); - } - let json = serde_json::to_vec_pretty(manifest).map_err(|e| Error::Invalid(format!("material.json: {e}")))?; +/// Write one SBS document with its referenced source assets. +pub fn write<'a>(source: &[u8], resources: impl IntoIterator) -> Result, Error> { + let limits = Limits::default(); let mut writer = Writer::new(); - writer.add(MANIFEST_ENTRY, &json, Compression::Deflated)?; - for (name, bytes) in maps { - writer.add(name, bytes, Compression::Stored)?; + let mut seen = BTreeSet::new(); + let mut total = (source.len() as u64).saturating_add(MARKER.len() as u64); + if source.len() as u64 > limits.max_entry_bytes { + return Err(Error::Invalid("source.sbs exceeds the entry limit".into())); + } + writer.add(MANIFEST_ENTRY, MARKER, Compression::Deflated)?; + writer.add(SOURCE_ENTRY, source, Compression::Deflated)?; + for (name, bytes) in resources { + if !valid_resource(name) || !seen.insert(name.to_ascii_lowercase()) { + return Err(Error::Invalid(format!("invalid or ambiguous resource path `{name}`"))); + } + total = total.saturating_add(bytes.len() as u64); + if bytes.len() as u64 > limits.max_entry_bytes || total > limits.max_total_bytes || seen.len() as u64 + 2 > limits.max_entries { + return Err(Error::Invalid(format!("archive limits exceeded at `{name}`"))); + } + let compression = if name.ends_with(".svg") { Compression::Deflated } else { Compression::Stored }; + writer.add(name, bytes, compression)?; } - writer.add(&manifest.source, source, Compression::Stored)?; Ok(writer.finish()?) } @@ -135,82 +128,58 @@ pub fn write(manifest: &Manifest, maps: &[(String, Vec)], source: &[u8]) -> mod tests { use super::*; - fn limits() -> Limits { - Limits { - min_version: 1, - max_version: 2, - max_entries: 100, - max_maps: 4, - max_manifest_bytes: 4096, - max_entry_bytes: 100, - max_total_bytes: 8192, - } - } - - fn sample(version: u32) -> Manifest { - serde_json::from_value(serde_json::json!({ - "format": "craft-material", "version": version, "name": "Stone", "graph": "Stone", "size": [64, 64], - "maps": [{"usage": "baseColor", "file": "maps/base.png", "colorSpace": "srgb", "futureMap": true}], - "parameters": [{"id": "rough", "value": {"t": "float", "v": 0.25}, "futureParam": 42}], - "inputs": [{"identifier": "curvature", "kind": "gray"}], "presets": [], - "source": if version == 1 { "source.mcraft" } else { "source.sbs" }, "futureField": {"keep": true} - })) - .unwrap() - } - #[test] - fn both_protocol_versions_keep_unknown_fields_and_payloads() { - for version in [1, 2] { - let manifest = sample(version); - let bytes = write(&manifest, &[("maps/base.png".into(), vec![1, 2, 3])], b"source").unwrap(); - assert!(is_material(&bytes, 100)); - assert!(!is_material(&bytes, 1)); - let mut material = Material::open(&bytes, limits()).unwrap(); - assert_eq!(material.manifest, manifest); - assert_eq!(material.read("maps/base.png").unwrap(), [1, 2, 3]); - assert_eq!(material.read_source().unwrap(), b"source"); - let json = serde_json::to_value(&material.manifest).unwrap(); - assert_eq!(json["futureField"]["keep"], true); - assert_eq!(json["maps"][0]["futureMap"], true); - assert_eq!(json["parameters"][0]["futureParam"], 42); + fn procedural_source_and_assets_round_trip_under_one_budget() { + let bytes = write(b"", [("resources/oak.png", b"image".as_slice())]).unwrap(); + let pkg = Material::open(&bytes, Limits::default()).unwrap(); + assert_eq!(pkg.source, b""); + assert_eq!(pkg.resources["resources/oak.png"], b"image"); + let mut archive = Archive::open(&bytes, craft_zip::Limits { max_entries: 3, max_total_bytes: 128 }).unwrap(); + assert_eq!(archive.read(MANIFEST_ENTRY, 32).unwrap().unwrap(), MARKER); + assert_eq!(archive.is_stored(SOURCE_ENTRY), Some(false)); + assert_eq!(archive.is_stored("resources/oak.png"), Some(true)); + for limits in [ + Limits { max_entries: 2, ..Default::default() }, + Limits { max_entry_bytes: 2, ..Default::default() }, + Limits { max_total_bytes: 24, ..Default::default() }, + ] { + assert!(Material::open(&bytes, limits).is_err()); } } #[test] - fn limits_apply_to_the_manifest_maps_and_aggregate_reads() { - let manifest = sample(2); - let bytes = write(&manifest, &[("maps/base.png".into(), vec![1; 8])], &[2; 8]).unwrap(); - let mut unsupported = limits(); - unsupported.max_version = 1; - assert!(matches!(Material::open(&bytes, unsupported), Err(Error::Version(2)))); - let mut no_maps = limits(); - no_maps.max_maps = 0; - assert!(matches!(Material::open(&bytes, no_maps), Err(Error::Limit(_)))); - let mut tiny_entry = limits(); - tiny_entry.max_entry_bytes = 7; - assert!(Material::open(&bytes, tiny_entry).unwrap().read("maps/base.png").is_err()); - let json_len = serde_json::to_vec_pretty(&manifest).unwrap().len() as u64; - let mut aggregate = limits(); - aggregate.max_total_bytes = json_len + 15; - let mut material = Material::open(&bytes, aggregate).unwrap(); - assert_eq!(material.read("maps/base.png").unwrap().len(), 8); - assert!(material.read_source().is_err()); + fn rejects_previous_versions_before_requiring_the_v3_layout() { + for version in [0, 1, 2, 4] { + let mut zip = Writer::new(); + zip.add(MANIFEST_ENTRY, format!(r#"{{"format":"craft-material","version":{version}}}"#).as_bytes(), Compression::Deflated).unwrap(); + let bytes = zip.finish().unwrap(); + assert!(is_material(&bytes, 2)); + assert!(matches!(Material::open(&bytes, Limits::default()), Err(Error::Version(v)) if v == version)); + } } #[test] - fn refuses_extra_fields_that_duplicate_known_keys() { - let mut manifest = sample(2); - manifest.extra.insert("version".into(), 3.into()); - assert!(write(&manifest, &[], b"source").is_err()); - manifest.extra.remove("version"); - manifest.maps[0].extra.insert("file".into(), "other".into()); - assert!(write(&manifest, &[], b"source").is_err()); + fn v3_requires_source_and_a_version_only_marker() { + for (marker, source) in [(MARKER, None), (br#"{"version":3,"graph":"Other"}"#.as_slice(), Some(b"".as_slice()))] { + let mut zip = Writer::new(); + zip.add(MANIFEST_ENTRY, marker, Compression::Deflated).unwrap(); + if let Some(source) = source { + zip.add(SOURCE_ENTRY, source, Compression::Deflated).unwrap(); + } + assert!(Material::open(&zip.finish().unwrap(), Limits::default()).is_err()); + } } #[test] - fn refuses_duplicate_names_on_write() { - let manifest = sample(2); - let duplicate = [("maps/base.png".to_string(), vec![1]), ("maps/base.png".to_string(), vec![2])]; - assert!(write(&manifest, &duplicate, b"source").is_err()); + fn rejects_ambiguous_or_nonlocal_resource_members() { + for name in ["resources/../../x", "resources/a\\x", "/x", "maps/color.png", "resources/C:/x", "preview.png"] { + assert!(write(b"x", [(name, &b"x"[..])]).is_err()); + let mut zip = Writer::new(); + zip.add(MANIFEST_ENTRY, MARKER, Compression::Stored).unwrap(); + zip.add(SOURCE_ENTRY, b"x", Compression::Deflated).unwrap(); + zip.add(name, b"x", Compression::Stored).unwrap(); + assert!(Material::open(&zip.finish().unwrap(), Limits::default()).is_err()); + } + assert!(write(b"x", [("resources/A", &b"a"[..]), ("resources/a", &b"b"[..])]).is_err()); } } From 14176282fd02834652a34e81a34c19a393e8c9f4 Mon Sep 17 00:00:00 2001 From: FredApps <153173854+FredApps@users.noreply.github.com> Date: Wed, 18 Nov 2026 14:06:25 +0700 Subject: [PATCH 29/37] fix(dex): preserve decode completeness and fixture UTF-16 encoding (#2164) --- crates/dex/src/dex.rs | 45 +++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 45 insertions(+) diff --git a/crates/dex/src/dex.rs b/crates/dex/src/dex.rs index 253af049c..528ec334e 100644 --- a/crates/dex/src/dex.rs +++ b/crates/dex/src/dex.rs @@ -745,6 +745,51 @@ mod tests { use super::*; use crate::test_support::android as fx; + #[test] + fn reference_queries_preserve_incomplete_decode_across_methods() { + for incomplete in [false, true] { + let mut builder = fx::DexBuilder::default(); + let class = builder.ty("LTest;"); + let first = builder.method("LTest;", "first", "V", &[]); + let second = builder.method("LTest;", "second", "V", &[]); + let mut first_code = vec![0x0071, second as u16, 0]; + if incomplete { + first_code.push(0x0071); // truncated invoke-static + } + let code = |insns| Some(fx::CodeSpec { insns, ..Default::default() }); + builder.classes.push(fx::ClassSpec { + class, + direct: vec![ + fx::MethodSpec { method: first, access: 0, code: code(first_code) }, + fx::MethodSpec { method: second, access: 0, code: code(vec![0x000e]) }, + ], + ..Default::default() + }); + let data = builder.build(); + let dex = parse(&data).unwrap(); + let (found, truncated) = references(&dex, "LTest;", Some("second"), 10); + assert_eq!(found.len(), 1); + assert_eq!(found[0].caller, "LTest;->first()V"); + assert_eq!(found[0].target, "LTest;->second()V"); + assert_eq!(truncated, incomplete); + let (absent, truncated) = references(&dex, "LAbsent;", None, 10); + assert!(absent.is_empty()); + assert_eq!(truncated, incomplete); + } + } + + #[test] + fn fixture_strings_round_trip_utf16_surrogate_pairs() { + let mut builder = fx::DexBuilder::default(); + let text = "A\0é😀"; + let index = builder.string(text); + let data = builder.build(); + let dex = parse(&data).unwrap(); + assert_eq!(dex.string(index), text); + let offset = Reader::new(&data).u32_le(0x70).unwrap() as usize; + assert_eq!(&data[offset..offset + 13], &[5, 0x41, 0xc0, 0x80, 0xc3, 0xa9, 0xed, 0xa0, 0xbd, 0xed, 0xb8, 0x80, 0]); + } + #[test] fn parses_fixture() { let data = fx::notes_dex(); From b0f25d641840bea1dda99c1e5e0c8db9221bcf28 Mon Sep 17 00:00:00 2001 From: chasse20 Date: Wed, 18 Nov 2026 02:15:10 -0500 Subject: [PATCH 30/37] Compress raw MCMAT source assets --- crates/mcmat/src/lib.rs | 14 +++++++++++++- 1 file changed, 13 insertions(+), 1 deletion(-) diff --git a/crates/mcmat/src/lib.rs b/crates/mcmat/src/lib.rs index 076fe636a..fe328cceb 100644 --- a/crates/mcmat/src/lib.rs +++ b/crates/mcmat/src/lib.rs @@ -118,7 +118,11 @@ pub fn write<'a>(source: &[u8], resources: impl IntoIterator limits.max_entry_bytes || total > limits.max_total_bytes || seen.len() as u64 + 2 > limits.max_entries { return Err(Error::Invalid(format!("archive limits exceeded at `{name}`"))); } - let compression = if name.ends_with(".svg") { Compression::Deflated } else { Compression::Stored }; + let extension = name.rsplit_once('.').map(|(_, ext)| ext.to_ascii_lowercase()); + let compression = match extension.as_deref() { + Some("png" | "jpg" | "jpeg" | "webp" | "gif" | "exr" | "woff" | "woff2") => Compression::Stored, + _ => Compression::Deflated, + }; writer.add(name, bytes, compression)?; } Ok(writer.finish()?) @@ -147,6 +151,14 @@ mod tests { } } + #[test] + fn compresses_unencoded_source_assets() { + let bytes = write(b"", [("resources/shape.svg", b"".as_slice()), ("resources/font.ttf", b"font".as_slice())]).unwrap(); + let mut archive = Archive::open(&bytes, craft_zip::Limits { max_entries: 4, max_total_bytes: 128 }).unwrap(); + assert_eq!(archive.is_stored("resources/shape.svg"), Some(false)); + assert_eq!(archive.is_stored("resources/font.ttf"), Some(false)); + } + #[test] fn rejects_previous_versions_before_requiring_the_v3_layout() { for version in [0, 1, 2, 4] { From c03ba68ab363bcf337a5f2c9548ead0b941b427f Mon Sep 17 00:00:00 2001 From: FredApps <153173854+FredApps@users.noreply.github.com> Date: Wed, 18 Nov 2026 14:36:07 +0700 Subject: [PATCH 31/37] fix(xfa): reject repeated leading BOM before parsing spans (#2176) --- crates/xfa/src/xml.rs | 13 +++++++++++++ 1 file changed, 13 insertions(+) diff --git a/crates/xfa/src/xml.rs b/crates/xfa/src/xml.rs index 7afab7600..7d6dd8193 100644 --- a/crates/xfa/src/xml.rs +++ b/crates/xfa/src/xml.rs @@ -194,6 +194,10 @@ impl Document { // quick-xml excludes a leading UTF-8 BOM from its buffer positions. // Parse it explicitly so every stored range still addresses the original input. let input = text.strip_prefix('\u{feff}').unwrap_or(text); + // A second U+FEFF is content outside the root, not another encoding marker. + if input.starts_with('\u{feff}') { + return Err("multiple leading XML byte-order marks".to_string()); + } let source_offset = text.len() - input.len(); let mut events = opts.events(input.as_bytes()); let mut nodes: Vec = Vec::new(); @@ -435,6 +439,15 @@ mod tests { } } + #[test] + fn repeated_leading_bom_is_rejected_before_event_parsing() { + for prefix in ["\u{feff}\u{feff}", "\u{feff}\u{feff}\u{feff}"] { + for body in ["<é/>", "<é>text"] { + assert!(Document::parse(&format!("{prefix}{body}")).is_err()); + } + } + } + #[test] fn inherited_namespace_copies_obey_aggregate_byte_admission() { let uri = format!("urn:{}", "x".repeat(124)); From 486319f5ff8bf2a7fa80aa9df3196d20750ec257 Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Wed, 18 Nov 2026 05:18:38 -0500 Subject: [PATCH 32/37] fix(dex): retain reference-query parse incompleteness --- crates/dex/src/dex.rs | 71 +++++++++++++++++++++++++++++++++++++++++-- 1 file changed, 69 insertions(+), 2 deletions(-) diff --git a/crates/dex/src/dex.rs b/crates/dex/src/dex.rs index 528ec334e..8c0b25573 100644 --- a/crates/dex/src/dex.rs +++ b/crates/dex/src/dex.rs @@ -691,7 +691,8 @@ pub struct Reference { const MAX_REFERENCE_BYTES: usize = 64 << 20; /// Every instruction that refers to class `desc` (optionally only its methods named `method`). -/// Reports truncation when instruction decoding is incomplete or the count or byte budget is exhausted. +/// Reports truncation for incomplete class data, unreadable nonzero code offsets, incomplete +/// instruction decoding, or an exhausted count or byte budget. pub fn references(dex: &Dex<'_>, desc: &str, method: Option<&str>, max: usize) -> (Vec, bool) { references_with_byte_limit(dex, desc, method, max, MAX_REFERENCE_BYTES) } @@ -702,8 +703,14 @@ fn references_with_byte_limit(dex: &Dex<'_>, desc: &str, method: Option<&str>, m let mut complete = true; for c in &dex.classes { let cd = dex.class_data(c); + complete &= cd.complete; for m in cd.direct_methods.iter().chain(&cd.virtual_methods) { - let Some(code) = dex.code(m.code_off) else { continue }; + let Some(code) = dex.code(m.code_off) else { + // Zero means no implementation (native/abstract), not damaged code. + // A nonzero unreadable body may hide references from this query. + complete &= m.code_off == 0; + continue; + }; let (insns, decoded) = crate::dex_ops::decode(&code.insns, 200_000); complete &= decoded; for i in &insns { @@ -778,6 +785,66 @@ mod tests { } } + #[test] + fn reference_queries_keep_class_data_and_code_parse_failures() { + let mut builder = fx::DexBuilder::default(); + let class = builder.ty("LTest;"); + let target = builder.method("LTest;", "target", "V", &[]); + let caller = builder.method("LTest;", "caller", "V", &[]); + builder.classes.push(fx::ClassSpec { + class, + direct: vec![ + fx::MethodSpec { method: target, access: 0, code: Some(fx::CodeSpec { insns: vec![0x000e], ..Default::default() }) }, + fx::MethodSpec { + method: caller, + access: 0, + code: Some(fx::CodeSpec { insns: vec![0x0071, target as u16, 0], ..Default::default() }), + }, + ], + ..Default::default() + }); + let bytes = builder.build(); + let mut dex = parse(&bytes).unwrap(); + let expected = references(&dex, "LTest;", Some("target"), 10); + assert_eq!(expected.0.len(), 1); + assert!(!expected.1); + + // A damaged class before a valid one must not hide the valid result or reset truncation. + let mut bad = dex.classes[0]; + bad.class_data_off = bytes.len() as u32; + dex.classes.insert(0, bad); + assert!(!dex.class_data(&dex.classes[0]).complete); + assert_eq!(references(&dex, "LTest;", Some("target"), 10), (expected.0.clone(), true)); + assert_eq!(references(&dex, "LAbsent;", None, 10), (Vec::new(), true)); + + // Locate the first method's code offset, after four counts and its index/access. + let original = parse(&bytes).unwrap(); + let reader = Reader::new(&bytes); + let mut at = original.classes[0].class_data_off as usize; + for _ in 0..6 { + at += reader.uleb128(at).unwrap().1; + } + let width = reader.uleb128(at).unwrap().1; + for missing in [false, true] { + let mut changed = bytes.clone(); + // Preserve the encoded width so the later valid method stays aligned. + changed[at..at + width].fill(if missing { 0xff } else { 0x80 }); + changed[at + width - 1] = if missing { 0x7f } else { 0 }; + let dex = parse(&changed).unwrap(); + let methods = dex.class_data(&dex.classes[0]); + assert!(methods.complete); + let offset = methods.direct_methods[0].code_off; + if missing { + assert!(offset as usize >= changed.len()); + } else { + assert_eq!(offset, 0); + } + assert!(dex.code(offset).is_none()); + assert_eq!(references(&dex, "LTest;", Some("target"), 10), (expected.0.clone(), missing)); + assert_eq!(references(&dex, "LAbsent;", None, 10), (Vec::new(), missing)); + } + } + #[test] fn fixture_strings_round_trip_utf16_surrogate_pairs() { let mut builder = fx::DexBuilder::default(); From abde74fa7dcb6e35beffa6cb98e90ba5595d33ba Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Wed, 18 Nov 2026 06:33:33 -0500 Subject: [PATCH 33/37] fix(mcmat): validate manifests and read resources by index --- crates/mcmat/src/lib.rs | 90 +++++++++++++++++++++++++++++++++------ crates/zip/src/archive.rs | 34 +++++++++++++++ 2 files changed, 110 insertions(+), 14 deletions(-) diff --git a/crates/mcmat/src/lib.rs b/crates/mcmat/src/lib.rs index fe328cceb..ca3fa7641 100644 --- a/crates/mcmat/src/lib.rs +++ b/crates/mcmat/src/lib.rs @@ -3,7 +3,8 @@ //! The clean-room MCMAT v3 source archive. Applications interpret the SBS entry graph. use craft_zip::{Archive, Compression, Writer}; -use serde::Deserialize; +use serde::Deserializer; +use serde::de::{IgnoredAny, MapAccess, Visitor}; use std::collections::{BTreeMap, BTreeSet}; pub const VERSION: u32 = 3; @@ -62,20 +63,36 @@ impl Material { return Err(Error::Invalid("duplicate or overlapping archive entries".into())); } let json = archive.read(MANIFEST_ENTRY, limits.max_manifest_bytes)?.ok_or_else(|| Error::Invalid("missing material.json".into()))?; - #[derive(Deserialize)] - struct Version { - version: u32, + struct Marker; + impl<'de> Visitor<'de> for Marker { + type Value = (u32, bool); + fn expecting(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.write_str("a version object") + } + fn visit_map>(self, mut map: A) -> Result { + let mut version = None; + let mut extra = false; + while let Some(key) = map.next_key::()? { + if key == "version" { + if version.is_some() { + return Err(serde::de::Error::duplicate_field("version")); + } + version = Some(map.next_value::()?); + } else { + map.next_value::()?; + extra = true; + } + } + Ok((version.ok_or_else(|| serde::de::Error::missing_field("version"))?, extra)) + } } - let marker: Version = serde_json::from_slice(&json).map_err(|err| Error::Invalid(format!("material.json: {err}")))?; - if marker.version != VERSION { - return Err(Error::Version(marker.version)); + let mut deserializer = serde_json::Deserializer::from_slice(&json); + let (version, extra) = deserializer.deserialize_map(Marker).map_err(|err| Error::Invalid(format!("material.json: {err}")))?; + deserializer.end().map_err(|err| Error::Invalid(format!("material.json: {err}")))?; + if version != VERSION { + return Err(Error::Version(version)); } - #[derive(Deserialize)] - #[serde(deny_unknown_fields)] - struct Marker { - version: u32, - } - if !serde_json::from_slice::(&json).is_ok_and(|m| m.version == VERSION) { + if extra { return Err(Error::Invalid("material.json must contain only the version".into())); } let source = archive.read(SOURCE_ENTRY, limits.max_entry_bytes)?.ok_or_else(|| Error::Invalid("missing source.sbs".into()))?; @@ -87,12 +104,15 @@ impl Material { continue; } if name.strip_suffix('/').is_some_and(|dir| dir == "resources" || valid_resource(dir)) { + if archive.entry_sizes(index)? != Some((0, 0)) { + return Err(Error::Invalid("directory entries must have no payload".into())); + } continue; } if !valid_resource(&name) || !seen.insert(name.to_ascii_lowercase()) { return Err(Error::Invalid(format!("invalid or ambiguous resource path `{name}`"))); } - let data = archive.read(&name, limits.max_entry_bytes)?.ok_or_else(|| Error::Invalid(format!("missing `{name}`")))?; + let data = archive.read_index(index, limits.max_entry_bytes)?.ok_or_else(|| Error::Invalid(format!("missing `{name}`")))?; resources.insert(name, data); } Ok(Self { source, resources }) @@ -151,6 +171,48 @@ mod tests { } } + #[test] + fn marker_requires_an_object_and_complete_input() { + for marker in [b"[3]".as_slice(), b"[2]", b"null", b"3", br#"{"version":3} {}"#, br#"{"version":3,"version":3}"#] { + let mut zip = Writer::new(); + zip.add(MANIFEST_ENTRY, marker, Compression::Stored).unwrap(); + zip.add(SOURCE_ENTRY, b"source", Compression::Stored).unwrap(); + assert!(matches!(Material::open(&zip.finish().unwrap(), Limits::default()), Err(Error::Invalid(_)))); + } + } + + #[test] + fn directory_members_must_be_empty() { + for payload in [b"".as_slice(), b"hidden"] { + let mut zip = Writer::new(); + zip.add(MANIFEST_ENTRY, MARKER, Compression::Stored).unwrap(); + zip.add(SOURCE_ENTRY, b"source", Compression::Stored).unwrap(); + zip.add("resources/", payload, Compression::Stored).unwrap(); + assert_eq!(Material::open(&zip.finish().unwrap(), Limits::default()).is_ok(), payload.is_empty()); + } + } + + #[test] + fn legacy_encoded_resource_names_read_by_index_under_one_budget() { + let mut zip = Writer::new(); + zip.add(MANIFEST_ENTRY, MARKER, Compression::Stored).unwrap(); + zip.add(SOURCE_ENTRY, b"s", Compression::Stored).unwrap(); + zip.add("resources/a.bin", b"data", Compression::Stored).unwrap(); + let mut bytes = zip.finish().unwrap(); + // Same-length CP437 name in both headers: no UTF-8 flag, 0x82 decodes to é. + let offsets: Vec<_> = + bytes.windows(b"resources/a.bin".len()).enumerate().filter_map(|(i, n)| (n == b"resources/a.bin").then_some(i + 10)).collect(); + assert_eq!(offsets.len(), 2); + for offset in offsets { + bytes[offset] = 0x82; + } + let total = MARKER.len() as u64 + 1 + 4; + let limits = Limits { max_total_bytes: total, ..Default::default() }; + let material = Material::open(&bytes, limits).unwrap(); + assert_eq!(material.resources["resources/é.bin"], b"data"); + assert!(Material::open(&bytes, Limits { max_total_bytes: total - 1, ..limits }).is_err()); + } + #[test] fn compresses_unencoded_source_assets() { let bytes = write(b"", [("resources/shape.svg", b"".as_slice()), ("resources/font.ttf", b"font".as_slice())]).unwrap(); diff --git a/crates/zip/src/archive.rs b/crates/zip/src/archive.rs index 49da63585..d00be89d0 100644 --- a/crates/zip/src/archive.rs +++ b/crates/zip/src/archive.rs @@ -108,6 +108,15 @@ impl<'a> Archive<'a> { Ok(Some(file.is_dir())) } + /// Declared decoded and compressed sizes at `index`, without name lookup. + pub fn entry_sizes(&mut self, index: usize) -> Result, Error> { + if index >= self.zip.len() { + return Ok(None); + } + let file = self.zip.by_index_raw(index).map_err(|e| Error::NotZip(e.to_string()))?; + Ok(Some((file.size(), file.compressed_size()))) + } + /// Do two entries share a name? `zip` then keeps one of them, and which one a writer meant /// is not known: a format that must not guess refuses the archive. pub fn has_duplicate_names(&self) -> bool { @@ -178,6 +187,16 @@ impl<'a> Archive<'a> { /// Only the bytes of a read that succeeds are charged to the total. pub fn read(&mut self, name: &str, max: u64) -> Result>, Error> { let Some(index) = self.zip.index_for_name(name) else { return Ok(None) }; + self.read_index(index, max) + } + + /// Read the entry at `index` under the same size, checksum and aggregate budget + /// rules as [`Self::read`], without repeating a decoded-name lookup. + pub fn read_index(&mut self, index: usize, max: u64) -> Result>, Error> { + if index >= self.zip.len() { + return Ok(None); + } + let name = self.entry_name(index)?.unwrap_or_default(); let entry = |msg: String| Error::Entry { name: name.to_string(), msg }; let f = self.zip.by_index(index).map_err(|e| entry(e.to_string()))?; let declared = f.size(); @@ -213,6 +232,21 @@ impl Archive<'static> { mod ownership_tests { use super::*; + #[test] + fn indexed_reads_charge_the_same_budget_and_enforce_entry_limits() { + let mut writer = crate::Writer::new(); + writer.add("a", b"abc", crate::Compression::Stored).unwrap(); + writer.add("b", b"def", crate::Compression::Deflated).unwrap(); + let bytes = writer.finish().unwrap(); + let mut archive = Archive::open(&bytes, Limits { max_entries: 2, max_total_bytes: 5 }).unwrap(); + assert!(archive.read_index(0, 2).is_err()); + assert_eq!(archive.read_index(0, 3).unwrap().unwrap(), b"abc"); + assert!(archive.read_index(1, 3).is_err()); + assert_eq!(archive.read_index(2, 3).unwrap(), None); + assert_eq!(archive.entry_sizes(0).unwrap(), Some((3, 3))); + assert_eq!(archive.entry_sizes(2).unwrap(), None); + } + #[test] fn owned_storage_lives_until_last_archive_clone_is_dropped() { let bytes = crate::Writer::new().finish().unwrap(); From ce732d2b8b29f689fd43bef545fbc513306b18b1 Mon Sep 17 00:00:00 2001 From: FredApps Date: Wed, 18 Nov 2026 13:25:09 +0100 Subject: [PATCH 34/37] ci: preserve full Windows formatting with package-sized invocations --- scripts/ci-format-workspace.py | 46 ++++++++++++++++ scripts/ci-full-validation.sh | 7 ++- scripts/test-full-validation.py | 95 ++++++++++++++++++++++++++++++--- 3 files changed, 141 insertions(+), 7 deletions(-) create mode 100644 scripts/ci-format-workspace.py diff --git a/scripts/ci-format-workspace.py b/scripts/ci-format-workspace.py new file mode 100644 index 000000000..a9b1569a2 --- /dev/null +++ b/scripts/ci-format-workspace.py @@ -0,0 +1,46 @@ +#!/usr/bin/env python3 +"""Check every workspace package separately to bound rustfmt's Windows argv.""" +import json +from pathlib import Path +import re +import subprocess + +ROOT = Path(__file__).resolve().parents[1] + + +def workspace_names(metadata): + members = metadata["workspace_members"] + packages = metadata["packages"] + if not members or len(members) != len(set(members)): + raise ValueError("workspace member inventory is empty or duplicated") + by_id = {package["id"]: package for package in packages} + if len(by_id) != len(packages): + raise ValueError("metadata contains duplicate package IDs") + names = [] + for member in members: + name = by_id[member]["name"] + # Package names are data, never command text or option fragments. + if not isinstance(name, str) or not re.fullmatch(r"[A-Za-z0-9_][A-Za-z0-9_-]*", name): + raise ValueError("invalid workspace package name") + names.append(name) + if len(names) != len(set(names)): + raise ValueError("workspace package names are ambiguous") + return sorted(names) + + +def check_workspace(): + result = subprocess.run( + ["cargo", "metadata", "--no-deps", "--offline", "--locked", "--format-version", "1"], + cwd=ROOT, check=True, stdout=subprocess.PIPE, text=True, + ) + names = workspace_names(json.loads(result.stdout)) + # From this virtual workspace root, cargo fmt normally checks all workspace packages. + # Keep Cargo responsible for target kinds, editions and rustfmt configuration. + # One package per call retains all its targets without the workspace-sized argv. + print(f"Checking formatting for {len(names)} workspace packages", flush=True) + for name in names: + subprocess.run(["cargo", "fmt", "--check", "--package", name], cwd=ROOT, check=True) + + +if __name__ == "__main__": + check_workspace() diff --git a/scripts/ci-full-validation.sh b/scripts/ci-full-validation.sh index 6e9509b5e..3b413ec88 100644 --- a/scripts/ci-full-validation.sh +++ b/scripts/ci-full-validation.sh @@ -5,7 +5,12 @@ unset CRAFT_HOSTILE_DIVISOR PROPTEST_CASES if [ "${RUNNER_OS:-}" = Windows ]; then powershell.exe -NoProfile -Command '$ErrorActionPreference = "Stop"; Start-Service Spooler; Add-PrinterDriver -Name "Generic / Text Only"' fi -cargo fmt --check +# Windows cannot spawn one rustfmt command with every workspace target (#2200). +if [ "${RUNNER_OS:-}" = Windows ]; then + python scripts/ci-format-workspace.py +else + cargo fmt --check +fi cargo clippy --workspace --all-targets --locked -- -D warnings cargo clippy --workspace --all-targets --all-features --locked -- -D warnings # cargo test includes docs and ordinary example linking, as required by AGENTS.md. diff --git a/scripts/test-full-validation.py b/scripts/test-full-validation.py index 658f49f54..4181ef7cc 100644 --- a/scripts/test-full-validation.py +++ b/scripts/test-full-validation.py @@ -29,7 +29,11 @@ unset CRAFT_HOSTILE_DIVISOR PROPTEST_CASES if [ "${RUNNER_OS:-}" = Windows ]; then powershell.exe -NoProfile -Command '$ErrorActionPreference = "Stop"; Start-Service Spooler; Add-PrinterDriver -Name "Generic / Text Only"' fi -cargo fmt --check +if [ "${RUNNER_OS:-}" = Windows ]; then + python scripts/ci-format-workspace.py +else + cargo fmt --check +fi cargo clippy --workspace --all-targets --locked -- -D warnings cargo clippy --workspace --all-targets --all-features --locked -- -D warnings cargo test --workspace --locked @@ -54,6 +58,7 @@ cargo() { if [ "$*" = "$FAIL" ]; then return 17; fi } powershell.exe() { printf 'print-queue\n'; } +python() { test "$*" = "scripts/ci-format-workspace.py" || return 31; cargo fmt --check; } """ return subprocess.run([BASH, "-c", mock + SOURCE], env=env, capture_output=True, text=True, check=False) @@ -89,11 +94,13 @@ class FullValidation(unittest.TestCase): (["print-queue"] if name == "Windows" else []) + COMMANDS) def test_every_failure_stops_the_gate(self): - for i, command in enumerate(COMMANDS): - with self.subTest(command=command): - p = run("Linux", command) - self.assertEqual(p.returncode, 17, p.stdout + p.stderr) - self.assertEqual(p.stdout.splitlines(), COMMANDS[:i + 1]) + for name in ["Linux", "macOS", "Windows"]: + for i, command in enumerate(COMMANDS): + with self.subTest(os=name, command=command): + p = run(name, command) + self.assertEqual(p.returncode, 17, p.stdout + p.stderr) + self.assertEqual(p.stdout.splitlines(), + (["print-queue"] if name == "Windows" else []) + COMMANDS[:i + 1]) def test_workflow_preserves_fork_and_platform_boundaries(self): text = (ROOT / ".github/workflows/full-validation.yml").read_text() @@ -120,5 +127,81 @@ class FullValidation(unittest.TestCase): self.assertIn("macos-latest", pdf) + +class PackageFormatting(unittest.TestCase): + @staticmethod + def helper(): + import importlib.util + spec = importlib.util.spec_from_file_location("ci_format_workspace", ROOT / "scripts/ci-format-workspace.py") + module = importlib.util.module_from_spec(spec) + spec.loader.exec_module(module) + return module + + @staticmethod + def metadata(): + return {"workspace_members": ["id-b", "id-a"], "workspace_default_members": ["id-a"], + "packages": [{"id": "id-a", "name": "craft-a"}, + {"id": "id-b", "name": "craft-b"}, + {"id": "external", "name": "not-a-member"}]} + + def test_all_workspace_members_not_only_defaults_and_no_external_dependencies(self): + helper = self.helper() + self.assertEqual(helper.workspace_names(self.metadata()), ["craft-a", "craft-b"]) + + def test_new_package_automatically_included(self): + helper = self.helper() + data = self.metadata() + data["workspace_members"].append("id-new") + data["packages"].append({"id": "id-new", "name": "craft-new"}) + self.assertEqual(helper.workspace_names(data), ["craft-a", "craft-b", "craft-new"]) + + def test_bad_inventory_fails_closed(self): + helper = self.helper() + for members in ([], ["id-a", "id-a"], ["missing"]): + data = self.metadata() + data["workspace_members"] = members + with self.subTest(members=members), self.assertRaises((ValueError, KeyError)): + helper.workspace_names(data) + for name in ("--all", "craft-a;echo injected", "craft-a", ""): + data = self.metadata() + data["packages"][1]["name"] = name + with self.subTest(name=name), self.assertRaises(ValueError): + helper.workspace_names(data) + + def test_calls_cargo_with_one_package_and_no_shell(self): + import json + helper = self.helper() + result = subprocess.CompletedProcess([], 0, stdout=json.dumps(self.metadata())) + with patch.object(helper.subprocess, "run", return_value=result) as execute: + helper.check_workspace() + self.assertEqual([call.args[0] for call in execute.call_args_list], [ + ["cargo", "metadata", "--no-deps", "--offline", "--locked", "--format-version", "1"], + ["cargo", "fmt", "--check", "--package", "craft-a"], + ["cargo", "fmt", "--check", "--package", "craft-b"], + ]) + for call in execute.call_args_list: + self.assertEqual(call.kwargs["cwd"], ROOT) + self.assertTrue(call.kwargs["check"]) + self.assertNotIn("shell", call.kwargs) + + def test_metadata_failure_prevents_formatting(self): + helper = self.helper() + failure = subprocess.CalledProcessError(17, ["cargo", "metadata"]) + with patch.object(helper.subprocess, "run", side_effect=failure) as execute: + with self.assertRaises(subprocess.CalledProcessError): + helper.check_workspace() + self.assertEqual(execute.call_count, 1) + + def test_first_format_failure_stops_later_packages(self): + import json + helper = self.helper() + result = subprocess.CompletedProcess([], 0, stdout=json.dumps(self.metadata())) + failure = subprocess.CalledProcessError(17, ["cargo", "fmt"]) + with patch.object(helper.subprocess, "run", side_effect=[result, failure]) as execute: + with self.assertRaises(subprocess.CalledProcessError): + helper.check_workspace() + self.assertEqual(execute.call_count, 2) + + if __name__ == "__main__": unittest.main() From 83131112ab21848f577f87ccabfb31360913edb4 Mon Sep 17 00:00:00 2001 From: FredApps Date: Wed, 18 Nov 2026 13:26:52 +0100 Subject: [PATCH 35/37] Decode Cargo metadata as UTF-8 on Windows --- scripts/ci-format-workspace.py | 2 +- scripts/test-full-validation.py | 1 + 2 files changed, 2 insertions(+), 1 deletion(-) diff --git a/scripts/ci-format-workspace.py b/scripts/ci-format-workspace.py index a9b1569a2..32605af70 100644 --- a/scripts/ci-format-workspace.py +++ b/scripts/ci-format-workspace.py @@ -31,7 +31,7 @@ def workspace_names(metadata): def check_workspace(): result = subprocess.run( ["cargo", "metadata", "--no-deps", "--offline", "--locked", "--format-version", "1"], - cwd=ROOT, check=True, stdout=subprocess.PIPE, text=True, + cwd=ROOT, check=True, stdout=subprocess.PIPE, text=True, encoding="utf-8", ) names = workspace_names(json.loads(result.stdout)) # From this virtual workspace root, cargo fmt normally checks all workspace packages. diff --git a/scripts/test-full-validation.py b/scripts/test-full-validation.py index 4181ef7cc..b37e979c8 100644 --- a/scripts/test-full-validation.py +++ b/scripts/test-full-validation.py @@ -179,6 +179,7 @@ class PackageFormatting(unittest.TestCase): ["cargo", "fmt", "--check", "--package", "craft-a"], ["cargo", "fmt", "--check", "--package", "craft-b"], ]) + self.assertEqual(execute.call_args_list[0].kwargs["encoding"], "utf-8") for call in execute.call_args_list: self.assertEqual(call.kwargs["cwd"], ROOT) self.assertTrue(call.kwargs["check"]) From 74b198524b3909ec376b6a3882f8d1d1b8acd468 Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Wed, 18 Nov 2026 07:47:03 -0500 Subject: [PATCH 36/37] fix(zip): preserve named read error contracts --- crates/zip/src/archive.rs | 17 ++++++++++++++++- 1 file changed, 16 insertions(+), 1 deletion(-) diff --git a/crates/zip/src/archive.rs b/crates/zip/src/archive.rs index d00be89d0..b9b3b3d80 100644 --- a/crates/zip/src/archive.rs +++ b/crates/zip/src/archive.rs @@ -187,7 +187,7 @@ impl<'a> Archive<'a> { /// Only the bytes of a read that succeeds are charged to the total. pub fn read(&mut self, name: &str, max: u64) -> Result>, Error> { let Some(index) = self.zip.index_for_name(name) else { return Ok(None) }; - self.read_index(index, max) + self.read_index_named(index, name, max) } /// Read the entry at `index` under the same size, checksum and aggregate budget @@ -197,6 +197,10 @@ impl<'a> Archive<'a> { return Ok(None); } let name = self.entry_name(index)?.unwrap_or_default(); + self.read_index_named(index, &name, max) + } + + fn read_index_named(&mut self, index: usize, name: &str, max: u64) -> Result>, Error> { let entry = |msg: String| Error::Entry { name: name.to_string(), msg }; let f = self.zip.by_index(index).map_err(|e| entry(e.to_string()))?; let declared = f.size(); @@ -232,6 +236,17 @@ impl Archive<'static> { mod ownership_tests { use super::*; + #[test] + fn named_read_preserves_entry_error_for_a_corrupt_local_header() { + let mut writer = crate::Writer::new(); + writer.add("a", b"abc", crate::Compression::Stored).unwrap(); + let mut bytes = writer.finish().unwrap(); + bytes[0] = 0; // The central directory remains valid; the local signature does not. + let mut archive = Archive::open(&bytes, Limits { max_entries: 1, max_total_bytes: 3 }).unwrap(); + assert!(matches!(archive.read("a", 3), Err(Error::Entry { name, .. }) if name == "a")); + assert_eq!(archive.budget().remaining(), 3); + } + #[test] fn indexed_reads_charge_the_same_budget_and_enforce_entry_limits() { let mut writer = crate::Writer::new(); From bc4aae37bb219049596327fca971046dab0b78be Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Wed, 18 Nov 2026 12:12:13 -0500 Subject: [PATCH 37/37] Merge pull request #2245 from storytold/fix/ocsp-certificate-wrapper-20261118 fix(pkcs7): read standard OCSP certificate sequence wrappers --- crates/pkcs7/src/revocation.rs | 17 ++++++++++++++--- crates/pkcs7/tests/it/crypto.rs | 10 +++++++++- 2 files changed, 23 insertions(+), 4 deletions(-) diff --git a/crates/pkcs7/src/revocation.rs b/crates/pkcs7/src/revocation.rs index dfb398cae..91d69730a 100644 --- a/crates/pkcs7/src/revocation.rs +++ b/crates/pkcs7/src/revocation.rs @@ -249,10 +249,21 @@ impl OcspResponse { for t in it { if t.tag == tag::ctx(0) { for c in t.children()? { - if c.tag == tag::SEQUENCE - && let Ok(cert) = Certificate::parse(c.raw) - { + if c.tag != tag::SEQUENCE { + continue; + } + // Preserve the historical direct-certificate form. RFC 6960 instead wraps + // certificates in one SEQUENCE OF inside [0]; unwrap only that one level. + if let Ok(cert) = Certificate::parse(c.raw) { responder_cert.get_or_insert(cert); + } else if let Ok(certs) = c.children() { + for cert in certs { + if cert.tag == tag::SEQUENCE + && let Ok(cert) = Certificate::parse(cert.raw) + { + responder_cert.get_or_insert(cert); + } + } } } } diff --git a/crates/pkcs7/tests/it/crypto.rs b/crates/pkcs7/tests/it/crypto.rs index 75ab5415d..d92612a5e 100644 --- a/crates/pkcs7/tests/it/crypto.rs +++ b/crates/pkcs7/tests/it/crypto.rs @@ -498,9 +498,17 @@ fn a_responder_that_copies_the_issuers_name_does_not_answer_for_it() { let single = der::seq(&[&cert_id, &revoked, &this.encode(), &der::tlv(tag::ctx(0), &next.encode())]); let by_key = der::tlv(tag::ctx(2), &der::octets(&DigestAlg::Sha1.digest(&[&impostor.public_key.key_bits()]))); // RFC 6960's `[0] EXPLICIT SEQUENCE OF Certificate`, and the certificate directly in `[0]`. - for certs in [der::explicit(0, &der::seq(&[&impostor.raw])), der::explicit(0, &impostor.raw)] { + for certs in [ + der::explicit(0, &der::seq(&[&impostor.raw])), + der::explicit(0, &impostor.raw), + // An unreadable entry must not hide the first readable certificate; later entries + // must not replace it. Parsing it still does not authorize the impostor. + der::explicit(0, &der::seq(&[&der::seq(&[]), &impostor.raw, &issuer.raw])), + ] { let forged = OcspResponse::parse(&signed_ocsp(&key, &by_key, Some(&certs), &single, this)).unwrap(); assert_eq!(forged.check(issuer, issuer, mid_june()), RevocationStatus::Unknown); + // Rejection must follow verification policy, not failure to read the embedded certificate. + assert_eq!(forged.into_parts().responder_cert.map(|cert| cert.raw), Some(impostor.raw.clone())); } }