mirror of
https://github.com/storytold/craft-libs.git
synced 2026-11-26 16:17:55 +00:00
Merge remote-tracking branch 'origin/main' into HEAD
# Conflicts: # Cargo.toml
This commit is contained in:
@@ -143,6 +143,10 @@ Sanitization, animation fitting and numeric output policy remain caller-owned.
|
||||
|
||||
`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. 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
|
||||
|
||||
`crates/java-class` extracts Craft Anything `java_class.rs` and `java_ops.rs` at `5979f9b13f16dcf1df3c7ae7f8e7735f452866f2` (MIT OR Apache-2.0), preserving separate primary-author source-history ports by Brandon Thomas, BFlat, Afloat and RRFZ. The checked byte-reader, modified UTF-8 unit decoder, descriptor display helper and synthetic class fixtures come from the same source snapshot. Seven regression files retain their source authors. Neutral error wiring and shared crate integration are subsequent changes. No JAR archive, application I/O or bytecode execution is imported.
|
||||
@@ -158,6 +162,10 @@ Sanitization, animation fitting and numeric output policy remain caller-owned.
|
||||
|
||||
`crates/har` preserves Craft Anything `crates/formats/src/har.rs` from `5979f9b13f16dcf1df3c7ae7f8e7735f452866f2` (MIT OR Apache-2.0). Brandon Thomas introduced the typed reader in `f64ae3bf3c8863a982af1304e06de20653803968`; BFlat added UTF-8 BOM compatibility in `cb0bb9d8fa4536ba44ef2c86f5ed759b879cc2d3`. Both source snapshots retain primary author attribution. Shared wiring, explicit byte admission and its tests are subsequent Dylan M. Taylor changes. Redaction and analysis remain app-owned.
|
||||
|
||||
## 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.
|
||||
|
||||
## EVM bytecode inspection
|
||||
|
||||
`crates/evm` extracts Craft Anything `crates/formats/src/evm.rs` at `a31e995858f4312e0f1d59a007112da191ef2d26` (MIT OR Apache-2.0). Eight separate source-history ports preserve Brandon Thomas, Afloat, RRFZ and NetterSilver as primary authors with immutable source references. Synthetic EVM fixtures and deterministic mutation helpers come from the same app source; regression files retain their source provenance. Neutral errors and workspace integration are subsequent changes. No code execution or transaction behavior is imported.
|
||||
|
||||
Generated
+16
@@ -1779,6 +1779,15 @@ dependencies = [
|
||||
"thiserror 2.0.21",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "craft-dex"
|
||||
version = "0.1.0"
|
||||
dependencies = [
|
||||
"craft-testkit",
|
||||
"serde",
|
||||
"thiserror 2.0.21",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "craft-dialogs"
|
||||
version = "0.1.0"
|
||||
@@ -3527,6 +3536,13 @@ dependencies = [
|
||||
"thiserror 2.0.21",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "craft-xfa"
|
||||
version = "0.1.0"
|
||||
dependencies = [
|
||||
"craft-xml",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "craft-xfdf"
|
||||
version = "0.1.0"
|
||||
|
||||
@@ -11,6 +11,7 @@ rust-version = "1.95"
|
||||
repository = "https://github.com/storytold/craft-libs"
|
||||
|
||||
[workspace.dependencies]
|
||||
craft-xfa = { path = "crates/xfa" }
|
||||
craft-evm = { path = "crates/evm" }
|
||||
craft-java-class = { path = "crates/java-class" }
|
||||
craft-sourcemap = { path = "crates/sourcemap" }
|
||||
@@ -61,6 +62,7 @@ craft-aaf = { path = "crates/aaf" }
|
||||
craft-atomic = { path = "crates/atomic" }
|
||||
# The ArtCraft Launcher's app list for AI agents (storytold/craft-ai-integrations, crates/app/ai-agents).
|
||||
craft-ai-agents = { git = "https://github.com/storytold/craft-ai-integrations", rev = "d94a3593adcff504eaaad9e5aee4c84fd2f07a72" }
|
||||
craft-dex = { path = "crates/dex" }
|
||||
craft-xtask = { path = "crates/xtask" }
|
||||
craft-captions = { path = "crates/captions" }
|
||||
craft-cfb = { path = "crates/cfb" }
|
||||
|
||||
@@ -0,0 +1,16 @@
|
||||
[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}
|
||||
|
||||
[dev-dependencies]
|
||||
craft-testkit = { workspace = true }
|
||||
@@ -0,0 +1,85 @@
|
||||
//! 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 is_empty(&self) -> bool {
|
||||
self.data.is_empty()
|
||||
}
|
||||
|
||||
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<u8> {
|
||||
self.data.get(off).copied()
|
||||
}
|
||||
|
||||
fn arr<const N: usize>(&self, off: usize) -> Option<[u8; N]> {
|
||||
self.slice(off, N)?.try_into().ok()
|
||||
}
|
||||
|
||||
pub fn u16_le(&self, off: usize) -> Option<u16> {
|
||||
self.arr(off).map(u16::from_le_bytes)
|
||||
}
|
||||
|
||||
pub fn u32_le(&self, off: usize) -> Option<u32> {
|
||||
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<String> {
|
||||
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),
|
||||
}
|
||||
}
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,696 @@
|
||||
//! 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<i32> },
|
||||
SparseSwitch { keys: Vec<i32>, targets: Vec<i32> },
|
||||
FillArrayData { element_width: u16, count: u32, data: Vec<u8> },
|
||||
}
|
||||
|
||||
/// 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<u32>,
|
||||
/// True for `/range` forms.
|
||||
pub range: bool,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub literal: Option<i64>,
|
||||
/// Absolute branch or payload target, in code units.
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub target: Option<i64>,
|
||||
pub index_kind: IndexKind,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub index: Option<u32>,
|
||||
/// Second index (the proto of `invoke-polymorphic`).
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub index2: Option<u32>,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub payload: Option<Payload>,
|
||||
}
|
||||
|
||||
/// 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<u32> {
|
||||
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)?;
|
||||
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;
|
||||
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<Insn> {
|
||||
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 => {
|
||||
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];
|
||||
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));
|
||||
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 {
|
||||
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 and caps all retained payload copies together.
|
||||
pub fn decode(code: &[u16], max: usize) -> (Vec<Insn>, 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<Insn>, 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(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 => {
|
||||
complete = false;
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
// Attach payloads to their users (31t formats).
|
||||
// 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)
|
||||
}
|
||||
|
||||
#[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<u16> = 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 = crate::test_support::noise(seed, 256);
|
||||
let code: Vec<u16> = 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);
|
||||
}
|
||||
}
|
||||
@@ -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;
|
||||
@@ -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());
|
||||
}
|
||||
}
|
||||
@@ -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<u8>) {
|
||||
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<u8>) {
|
||||
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<u8> {
|
||||
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 }));
|
||||
}
|
||||
}
|
||||
@@ -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));
|
||||
}
|
||||
@@ -0,0 +1,88 @@
|
||||
use crate::dex_ops::{self, Payload};
|
||||
|
||||
fn arrays(references: usize, bytes: usize) -> Vec<u16> {
|
||||
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::<Vec<_>>(), [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);
|
||||
}
|
||||
@@ -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 }]);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,430 @@
|
||||
// Synthetic DEX fixture and deterministic mutations retained from Craft Anything.
|
||||
pub use craft_testkit::sample_damage::{mutations, noise};
|
||||
|
||||
pub mod android {
|
||||
pub const HELLO: &str = "Hello, Craft!";
|
||||
fn u16le(v: &mut Vec<u8>, x: u16) {
|
||||
v.extend_from_slice(&x.to_le_bytes());
|
||||
}
|
||||
fn u32le(v: &mut Vec<u8>, x: u32) {
|
||||
v.extend_from_slice(&x.to_le_bytes());
|
||||
}
|
||||
fn uleb(v: &mut Vec<u8>, 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<u8>, 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<u8>) {
|
||||
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<u32>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Default)]
|
||||
pub struct CodeSpec {
|
||||
pub registers: u16,
|
||||
pub ins: u16,
|
||||
pub outs: u16,
|
||||
pub insns: Vec<u16>,
|
||||
pub tries: Vec<TrySpec>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct MethodSpec {
|
||||
pub method: u32,
|
||||
pub access: u32,
|
||||
pub code: Option<CodeSpec>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Default)]
|
||||
pub struct ClassSpec {
|
||||
pub class: u32,
|
||||
pub access: u32,
|
||||
pub superclass: u32,
|
||||
pub interfaces: Vec<u32>,
|
||||
pub source_file: u32,
|
||||
pub annotations: Vec<u32>,
|
||||
pub static_fields: Vec<(u32, u32)>,
|
||||
pub instance_fields: Vec<(u32, u32)>,
|
||||
pub direct: Vec<MethodSpec>,
|
||||
pub virtuals: Vec<MethodSpec>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Default)]
|
||||
pub struct DexBuilder {
|
||||
strings: Vec<String>,
|
||||
types: Vec<u32>,
|
||||
protos: Vec<(u32, u32, Vec<u32>)>,
|
||||
fields: Vec<(u32, u32, u32)>,
|
||||
methods: Vec<(u32, u32, u32)>,
|
||||
pub classes: Vec<ClassSpec>,
|
||||
}
|
||||
|
||||
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<u32> = 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<u8> {
|
||||
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<u8> = Vec::new();
|
||||
let at = |d: &Vec<u8>| (data_start + d.len()) as u32;
|
||||
// type lists
|
||||
let tl = |d: &mut Vec<u8>, 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<u32> = self.protos.iter().map(|p| tl(&mut d, &p.2)).collect();
|
||||
let class_ifaces: Vec<u32> = 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 c in s.encode_utf16() {
|
||||
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<u8>, 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<u32> = direct.iter().map(|m| code_off(&mut d, m)).collect();
|
||||
let virtual_offs: Vec<u32> = 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<u8>, 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<u8> {
|
||||
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;", "<init>", "V", &[]);
|
||||
let super_create = b.method("Landroid/app/Activity;", "onCreate", "V", &["Landroid/os/Bundle;"]);
|
||||
let init = b.method(MAIN, "<init>", "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<u16>| 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()
|
||||
}
|
||||
}
|
||||
@@ -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 {
|
||||
|
||||
@@ -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!("<table>{columns}<tr>{cells}</tr></table>"));
|
||||
let FBlock::Table(table) = &flow.blocks[0] else { panic!("expected table") };
|
||||
table.widths.clone()
|
||||
};
|
||||
let partial = "<td width='400'>x</td><td>y</td>";
|
||||
let widthless = "<colgroup><col><col></colgroup>";
|
||||
assert!(widths("", partial).is_empty());
|
||||
assert_eq!(widths(widthless, partial), widths("", partial));
|
||||
let complete = "<td width='40'>x</td><td width='80'>y</td>";
|
||||
assert_eq!(widths(widthless, complete), vec![30.0, 60.0]);
|
||||
// An explicitly declared column still enables the existing average-fill rule.
|
||||
assert_eq!(widths("<colgroup><col style='width:100pt'><col></colgroup>", "<td>x</td><td>y</td>"), vec![100.0, 100.0]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn numeric_entity_rejects_sign() {
|
||||
assert_eq!(unescape("a&#+65;b"), "a&#+65;b");
|
||||
|
||||
+7
-14
@@ -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.
|
||||
|
||||
+200
-157
@@ -1,133 +1,150 @@
|
||||
#![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::Deserializer;
|
||||
use serde::de::{IgnoredAny, MapAccess, Visitor};
|
||||
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<MapEntry>,
|
||||
#[serde(default)]
|
||||
pub parameters: Vec<Value>,
|
||||
#[serde(default)]
|
||||
pub inputs: Vec<Value>,
|
||||
#[serde(default)]
|
||||
pub presets: Vec<Value>,
|
||||
pub source: String,
|
||||
#[serde(flatten)]
|
||||
pub extra: BTreeMap<String, Value>,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct MapEntry {
|
||||
pub usage: String,
|
||||
pub file: String,
|
||||
#[serde(flatten)]
|
||||
pub extra: BTreeMap<String, Value>,
|
||||
}
|
||||
|
||||
/// 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<Self, Error> {
|
||||
#[derive(Debug)]
|
||||
pub struct Material {
|
||||
pub source: Vec<u8>,
|
||||
/// Keys are paths relative to source.sbs, including the resources/ prefix.
|
||||
pub resources: BTreeMap<String, Vec<u8>>,
|
||||
}
|
||||
|
||||
impl Material {
|
||||
pub fn open(bytes: &[u8], limits: Limits) -> Result<Self, Error> {
|
||||
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()))?;
|
||||
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<A: MapAccess<'de>>(self, mut map: A) -> Result<Self::Value, A::Error> {
|
||||
let mut version = None;
|
||||
let mut extra = false;
|
||||
while let Some(key) = map.next_key::<String>()? {
|
||||
if key == "version" {
|
||||
if version.is_some() {
|
||||
return Err(serde::de::Error::duplicate_field("version"));
|
||||
}
|
||||
version = Some(map.next_value::<u32>()?);
|
||||
} else {
|
||||
map.next_value::<IgnoredAny>()?;
|
||||
extra = true;
|
||||
}
|
||||
}
|
||||
Ok((version.ok_or_else(|| serde::de::Error::missing_field("version"))?, extra))
|
||||
}
|
||||
}
|
||||
if !(limits.min_version..=limits.max_version).contains(&manifest.version) {
|
||||
return Err(Error::Version(manifest.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));
|
||||
}
|
||||
if manifest.maps.len() > limits.max_maps {
|
||||
return Err(Error::Limit(format!("{} maps exceeds {}", manifest.maps.len(), limits.max_maps)));
|
||||
if extra {
|
||||
return Err(Error::Invalid("material.json must contain only the version".into()));
|
||||
}
|
||||
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<Vec<u8>, 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<Vec<u8>, Error> {
|
||||
self.read(&self.manifest.source.clone())
|
||||
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)) {
|
||||
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_index(index, 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<u8>)], source: &[u8]) -> Result<Vec<u8>, 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<Item = (&'a str, &'a [u8])>) -> Result<Vec<u8>, 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 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)?;
|
||||
}
|
||||
writer.add(&manifest.source, source, Compression::Stored)?;
|
||||
Ok(writer.finish()?)
|
||||
}
|
||||
|
||||
@@ -135,82 +152,108 @@ pub fn write(manifest: &Manifest, maps: &[(String, Vec<u8>)], 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"<package/>", [("resources/oak.png", b"image".as_slice())]).unwrap();
|
||||
let pkg = Material::open(&bytes, Limits::default()).unwrap();
|
||||
assert_eq!(pkg.source, b"<package/>");
|
||||
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 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 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 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 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 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"<package/>", [("resources/shape.svg", b"<svg/>".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] {
|
||||
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 v3_requires_source_and_a_version_only_marker() {
|
||||
for (marker, source) in [(MARKER, None), (br#"{"version":3,"graph":"Other"}"#.as_slice(), Some(b"<package/>".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 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());
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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()));
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -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.
|
||||
|
||||
@@ -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<f64> {
|
||||
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<f64> {
|
||||
}
|
||||
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::<Vec<_>>());
|
||||
// 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
|
||||
|
||||
+36
-1
@@ -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
|
||||
|| !matches!(info.sample_format, 1 | 2)
|
||||
|| !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 || 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);
|
||||
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
|
||||
|
||||
@@ -118,3 +118,74 @@ 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<u8> {
|
||||
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<u8> {
|
||||
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])),
|
||||
(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::<Vec<u16>>());
|
||||
}
|
||||
|
||||
/// Any other short strip is still a corrupt file.
|
||||
#[test]
|
||||
fn other_short_strips_are_still_refused() {
|
||||
let refused = |bytes: Vec<u8>| 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]))));
|
||||
// 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
|
||||
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));
|
||||
}
|
||||
|
||||
@@ -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<usize> = (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);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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 }
|
||||
@@ -0,0 +1,11 @@
|
||||
# craft-xfa
|
||||
|
||||
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, 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.
|
||||
|
||||
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.
|
||||
@@ -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;
|
||||
@@ -0,0 +1,566 @@
|
||||
//! Lightweight namespace-aware XML DOM with source byte ranges, backed by `craft_xml`.
|
||||
|
||||
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/";
|
||||
|
||||
#[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<String>,
|
||||
name: String,
|
||||
value: String,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug)]
|
||||
enum NodeKind {
|
||||
Element {
|
||||
ns: Option<String>,
|
||||
name: String,
|
||||
attrs: Vec<AttrData>,
|
||||
/// In-scope `(prefix, uri)` bindings at this element (`""` for default namespace).
|
||||
namespaces: Vec<(String, String)>,
|
||||
range: Range<usize>,
|
||||
},
|
||||
Text(String),
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug)]
|
||||
struct NodeData {
|
||||
kind: NodeKind,
|
||||
children: Vec<usize>,
|
||||
}
|
||||
|
||||
pub struct Document {
|
||||
nodes: Vec<NodeData>,
|
||||
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),
|
||||
}
|
||||
}
|
||||
|
||||
// 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<Option<String>, 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<Option<String>, String> {
|
||||
if prefix == "xml" {
|
||||
return copy_namespace(XML_NS, bytes);
|
||||
}
|
||||
if prefix == "xmlns" {
|
||||
return copy_namespace(XMLNS_NS, bytes);
|
||||
}
|
||||
if prefix.is_empty() {
|
||||
if is_attr {
|
||||
return Ok(None);
|
||||
}
|
||||
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() => copy_namespace(u, bytes),
|
||||
_ => Err(format!("undeclared namespace prefix: {prefix}")),
|
||||
}
|
||||
}
|
||||
impl Document {
|
||||
pub fn parse(text: &str) -> Result<Self, String> {
|
||||
Self::parse_with_options(text, ParsingOptions::default())
|
||||
}
|
||||
|
||||
pub fn parse_with_options(text: &str, options: ParsingOptions) -> Result<Self, String> {
|
||||
Self::parse_with_namespace_budget(text, options, MAX_NAMESPACE_BYTES)
|
||||
}
|
||||
|
||||
fn parse_with_namespace_budget(text: &str, options: ParsingOptions, mut namespace_bytes: usize) -> Result<Self, String> {
|
||||
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;
|
||||
|
||||
// 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<NodeData> = 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<usize> = None;
|
||||
|
||||
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 {
|
||||
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, &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, &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()));
|
||||
}
|
||||
}
|
||||
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<Node<'_>> {
|
||||
(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<usize>,
|
||||
}
|
||||
|
||||
impl<'a> Iterator for Descendants<'a> {
|
||||
type Item = Node<'a>;
|
||||
|
||||
fn next(&mut self) -> Option<Self::Item> {
|
||||
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<K: AttributeKey>(&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<Item = Attribute<'a>> + 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<Item = Namespace<'a>> + 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<Item = Node<'a>> + 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<usize> {
|
||||
match &self.doc.nodes[self.id].kind {
|
||||
NodeKind::Element { range, .. } => range.clone(),
|
||||
NodeKind::Text(_) => 0..0,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn element_ranges_slice_original_input_with_utf8_bom() {
|
||||
for prefix in ["", "\u{feff}", "\u{feff}<?xml version='1.0'?>"] {
|
||||
for child_xml in ["<é/>", "<é>text</é>"] {
|
||||
let root_xml = format!("<r>{child_xml}</r>");
|
||||
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 repeated_leading_bom_is_rejected_before_event_parsing() {
|
||||
for prefix in ["\u{feff}\u{feff}", "\u{feff}\u{feff}\u{feff}"] {
|
||||
for body in ["<r><é/></r>", "<?xml version='1.0'?><r><é>text</é></r>"] {
|
||||
assert!(Document::parse(&format!("{prefix}{body}")).is_err());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[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 [("<n/>", 0), ("<p:n/>", 1), ("<n p:a='v'/>", 1), ("<p:n p:a='v'/>", 2)] {
|
||||
let input = format!("<r xmlns:p='{uri}'>{}</r>", 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 = "<root xmlns='urn:outer' xmlns:p='urn:p' a='v'><p:child xmlns='urn:inner' p:a='x'>one<![CDATA[two]]>three</p:child><leaf xmlns=''/></root>";
|
||||
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("<p:child"));
|
||||
assert!(text[child.range()].ends_with("</p:child>"));
|
||||
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 traversal_identity_and_accessors_preserve_element_and_text_semantics() {
|
||||
let source = "<?before value?><r xmlns='urn:r' xmlns:p='urn:p' a='plain' p:a='qualified' xml:lang='en'>first<!--gap--><?inside value?>second<empty/><p:child>last</p:child></r>";
|
||||
let doc = Document::parse(source).unwrap();
|
||||
let other = Document::parse(source).unwrap();
|
||||
let root = doc.root_element();
|
||||
assert!(root != other.root_element());
|
||||
assert!(std::ptr::eq(root.document(), &doc));
|
||||
assert!(root.is_element());
|
||||
assert!(!root.is_text());
|
||||
assert_eq!(root.tag_name().name(), "r");
|
||||
assert_eq!(root.lookup_prefix("urn:p"), Some("p"));
|
||||
assert_eq!(root.lookup_prefix(XML_NS), Some("xml"));
|
||||
assert_eq!(root.lookup_prefix("absent"), None);
|
||||
assert_eq!(root.lookup_namespace_uri(Some("xml")), Some(XML_NS));
|
||||
assert_eq!(root.lookup_namespace_uri(Some("xmlns")), Some(XMLNS_NS));
|
||||
assert_eq!(root.lookup_namespace_uri(Some("absent")), None);
|
||||
let attrs: Vec<_> = root.attributes().map(|a| (a.namespace(), a.name(), a.value())).collect();
|
||||
assert_eq!(attrs, vec![(None, "a", "plain"), (Some("urn:p"), "a", "qualified"), (Some(XML_NS), "lang", "en")]);
|
||||
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("<r xmlns='urn:r' xmlns:p='urn:p'>first<!--gap--><?inside value?>second<empty/><p:child>last</p:child></r>").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));
|
||||
assert_eq!(all.iter().filter(|n| n.is_element()).map(|n| n.tag_name().name()).collect::<Vec<_>>(), vec!["r", "empty", "child"]);
|
||||
let text = root.children().next().unwrap();
|
||||
assert!(text.is_text());
|
||||
assert!(!text.is_element());
|
||||
assert_eq!(text.text(), Some("firstsecond"));
|
||||
assert_eq!(text.tag_name().name(), "");
|
||||
assert_eq!(text.tag_name().namespace(), None);
|
||||
assert_eq!(text.attribute("a"), None);
|
||||
assert_eq!(text.attributes().len(), 0);
|
||||
assert_eq!(text.namespaces().len(), 0);
|
||||
assert_eq!(text.lookup_prefix("urn:p"), None);
|
||||
assert_eq!(text.lookup_namespace_uri(Some("p")), None);
|
||||
assert_eq!(text.range(), 0..0);
|
||||
assert_eq!(text.children().count(), 0);
|
||||
assert_eq!(text.descendants().count(), 1);
|
||||
assert!(doc.get_node(NodeId(usize::MAX)).is_none());
|
||||
assert_eq!(root.children().nth(1).unwrap().text(), None);
|
||||
assert_eq!(Document::parse("<r><child/>tail</r>").unwrap().root_element().text(), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn inherited_namespace_declarations_have_an_aggregate_budget() {
|
||||
use std::fmt::Write;
|
||||
let mut xml = String::from("<r");
|
||||
for i in 0..512 {
|
||||
write!(xml, " xmlns:p{i}='u{i}'").unwrap();
|
||||
}
|
||||
xml.push_str("><child");
|
||||
for i in 512..1024 {
|
||||
write!(xml, " xmlns:p{i}='u{i}'").unwrap();
|
||||
}
|
||||
let accepted = format!("{xml}/></r>");
|
||||
assert!(Document::parse(&accepted).is_ok());
|
||||
let rejected = format!("{xml} xmlns:extra='extra'/></r>");
|
||||
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.
|
||||
assert!(Document::parse("<r a='1' a='2'/>").is_err());
|
||||
assert!(Document::parse("<r xmlns:a='u' xmlns:b='u' a:x='1' b:x='2'/>").is_err());
|
||||
assert!(Document::parse("<p:root/>").is_err());
|
||||
assert!(Document::parse("<!DOCTYPE root><root/>").is_err());
|
||||
assert!(Document::parse_with_options("<!DOCTYPE root><root/>", ParsingOptions { allow_dtd: true, nodes_limit: 8 }).is_ok());
|
||||
assert!(Document::parse_with_options("<root>text</root>", ParsingOptions { allow_dtd: false, nodes_limit: 1 }).is_err());
|
||||
assert!(Document::parse_with_options("<root/>", ParsingOptions { allow_dtd: false, nodes_limit: 0 }).is_err());
|
||||
let text = format!("{}{}", "<n>".repeat(1025), "</n>".repeat(1025));
|
||||
assert!(Document::parse(&text).is_err());
|
||||
assert!(Document::parse("").is_err());
|
||||
}
|
||||
}
|
||||
@@ -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<Option<(u64, u64)>, 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,20 @@ 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<Option<Vec<u8>>, Error> {
|
||||
let Some(index) = self.zip.index_for_name(name) else { return Ok(None) };
|
||||
self.read_index_named(index, name, 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<Option<Vec<u8>>, Error> {
|
||||
if index >= self.zip.len() {
|
||||
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<Option<Vec<u8>>, 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();
|
||||
@@ -213,6 +236,32 @@ 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();
|
||||
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();
|
||||
|
||||
@@ -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, encoding="utf-8",
|
||||
)
|
||||
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()
|
||||
@@ -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.
|
||||
|
||||
@@ -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,82 @@ 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"],
|
||||
])
|
||||
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"])
|
||||
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()
|
||||
|
||||
Reference in New Issue
Block a user