diff --git a/Cargo.lock b/Cargo.lock index 31917c4085..a9cf2d2ef3 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1587,6 +1587,14 @@ dependencies = [ "serde_json", ] +[[package]] +name = "craft-android-res" +version = "0.1.0" +dependencies = [ + "serde", + "thiserror 2.0.21", +] + [[package]] name = "craft-anicraft-format" version = "0.1.0" diff --git a/Cargo.toml b/Cargo.toml index ec7a834661..15e1a7c12d 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -11,6 +11,7 @@ rust-version = "1.95" repository = "https://github.com/storytold/craft-libs" [workspace.dependencies] +craft-android-res = { path = "crates/android-res" } craft-audio-dsp = { path = "crates/audio-dsp" } craft-xfa = { path = "crates/xfa" } craft-evm = { path = "crates/evm" } diff --git a/crates/android-res/Cargo.toml b/crates/android-res/Cargo.toml new file mode 100644 index 0000000000..cc54d2513c --- /dev/null +++ b/crates/android-res/Cargo.toml @@ -0,0 +1,15 @@ +[package] +name = "craft-android-res" +description = "Bounded readers for compiled Android binary XML and resource tables" +version.workspace = true +edition.workspace = true +license.workspace = true +rust-version.workspace = true +repository.workspace = true + +[lints] +workspace = true + +[dependencies] +serde = { workspace = true } +thiserror = { workspace = true } diff --git a/crates/android-res/README.md b/crates/android-res/README.md new file mode 100644 index 0000000000..cc3a643e11 --- /dev/null +++ b/crates/android-res/README.md @@ -0,0 +1,16 @@ +# craft-android-res + +Read-only wire decoding for Android compiled XML (AXML) and Android resource +tables (ARSC). XML and resource tables share the bounded chunk, string-pool, +and typed-value readers. APK container selection, manifest inventory policy, +device/security interpretation, and presentation remain consumer-owned. + +## Provenance + +The decoders, checked-reader subset, and synthetic test fixture subset were +moved from [Craft Anything at 8cec25d](https://github.com/storytold/craft-anything/tree/8cec25d02007db604b57ce6735ad4eb44a1a9948/crates/formats). +The original implementation is Brandon Thomas (echelon), [f64ae3bf](https://github.com/storytold/craft-anything/commit/f64ae3bf3c8863a982af1304e06de20653803968). +Later parser bounds and resource identity/qualifier work came from Afloat +and BFlat; typed-attribute handling also includes RRFZ's work. The original +[fixture generator](https://github.com/storytold/craft-anything/blob/8cec25d02007db604b57ce6735ad4eb44a1a9948/crates/testkit/src/android.rs) +remains the source of the test data. No external assets or added dependencies. diff --git a/crates/android-res/src/arsc.rs b/crates/android-res/src/arsc.rs new file mode 100644 index 0000000000..a9f0e47d7d --- /dev/null +++ b/crates/android-res/src/arsc.rs @@ -0,0 +1,637 @@ +//! Android compiled resource tables (`resources.arsc`): the global string pool, packages, type +//! and key string pools, type specs, and typed entries per configuration (locale, density, +//! orientation, SDK level…). Simple and complex (bag) entries, sparse and 16-bit offset tables. + +use crate::Error; +use crate::axml::{ResValue, StringPool, chunk}; +use crate::bytes::Reader; +use serde::Serialize; + +const RES_TABLE: u16 = 0x0002; +const RES_PACKAGE: u16 = 0x0200; +const RES_TYPE: u16 = 0x0201; +const RES_TYPE_SPEC: u16 = 0x0202; +const RES_LIBRARY: u16 = 0x0203; +const NO_ENTRY: u32 = 0xffff_ffff; +const MAX_PACKAGES: usize = 64; +const MAX_BAG: usize = 4096; + +/// Limits for one table. +#[derive(Debug, Clone, Copy)] +pub struct Limits { + /// Most entries decoded across all types and configurations. + pub max_entries: usize, +} + +impl Default for Limits { + fn default() -> Self { + Limits { max_entries: 2_000_000 } + } +} + +#[derive(Debug, Clone, PartialEq, Serialize)] +pub struct TypeInfo { + pub id: u8, + pub name: String, + pub entry_count: u32, + /// Configuration qualifiers that have values for this type ("default" for none). + pub configs: Vec, +} + +#[derive(Debug, Clone, PartialEq, Serialize)] +pub struct Package { + pub id: u32, + pub name: String, + pub types: Vec, + pub keys: usize, + /// Shared-library package references (id → name). + pub libraries: Vec<(u32, String)>, +} + +#[derive(Debug, Clone, PartialEq, Serialize)] +pub struct BagItem { + pub name: String, + pub value: String, + pub value_type: &'static str, +} + +/// One value of one resource in one configuration. +#[derive(Debug, Clone, PartialEq, Serialize)] +pub struct Entry { + /// `0xPPTTEEEE` + pub id: String, + pub package: String, + #[serde(rename = "type")] + pub type_name: String, + pub key: String, + /// Qualifier string, e.g. `fr`, `es-rMX`, `night-xhdpi`, or `default`. + pub config: String, + /// Android locale qualifier, empty for the default locale. + pub locale: String, + #[serde(skip_serializing_if = "Option::is_none")] + pub value: Option, + #[serde(skip_serializing_if = "Option::is_none")] + pub value_type: Option<&'static str>, + #[serde(skip_serializing_if = "Option::is_none")] + pub parent: Option, + #[serde(skip_serializing_if = "Vec::is_empty")] + pub bag: Vec, + #[serde(skip)] + pub raw: Option, +} + +#[derive(Debug, Clone, Default, PartialEq, Serialize)] +pub struct Table { + pub packages: Vec, + pub global_strings: usize, + pub entries: Vec, + pub truncated: bool, + pub warnings: Vec, +} + +fn utf16_fixed(r: &Reader<'_>, off: usize, chars: usize) -> String { + let units: Vec = (0..chars).map_while(|i| r.u16_le(off + i * 2)).take_while(|&u| u != 0).collect(); + String::from_utf16_lossy(&units) +} + +fn ascii2(b: &[u8]) -> String { + b.iter().take_while(|&&c| c != 0).map(|&c| if c.is_ascii_graphic() { c as char } else { '?' }).collect() +} + +/// A packed 2-byte language or region code (3-letter codes are packed into 15 bits). +fn unpack_code(b: &[u8], base: u8) -> String { + let (b0, b1) = (b.first().copied().unwrap_or(0), b.get(1).copied().unwrap_or(0)); + if b0 & 0x80 != 0 { + let first = b1 & 0x1f; + let second = ((b1 & 0xe0) >> 5) | ((b0 & 0x03) << 3); + let third = (b0 & 0x7c) >> 2; + [first, second, third].iter().map(|c| (c.wrapping_add(base)) as char).collect() + } else { + ascii2(&[b0, b1]) + } +} + +/// Qualifier string and locale for a `ResTable_config` at `off`. +fn config_qualifiers(r: &Reader<'_>, off: usize) -> (String, String) { + let size = r.u32_le(off).unwrap_or(0) as usize; + let get8 = |o: usize| if o < size { r.u8(off + o) } else { None }; + let get16 = |o: usize| if o + 1 < size { r.u16_le(off + o) } else { None }; + let mut q: Vec = Vec::new(); + if let Some(mcc) = get16(4).filter(|&v| v != 0) { + q.push(format!("mcc{mcc}")); + } + if let Some(mnc) = get16(6).filter(|&v| v != 0) { + q.push(format!("mnc{}", if mnc == u16::MAX { 0 } else { mnc })); + } + let lang = if size >= 12 { r.slice(off + 8, 2).map(|b| unpack_code(b, b'a')).unwrap_or_default() } else { String::new() }; + let region = if size >= 12 { r.slice(off + 10, 2).map(|b| unpack_code(b, b'0')).unwrap_or_default() } else { String::new() }; + // Extended locale fields were appended to ResTable_config. Older + // configurations end before one or more of these fields. + let subtag = |start: usize, len: usize| { + if start + len <= size { r.slice(off + start, len).map(ascii2).unwrap_or_default() } else { String::new() } + }; + let script = if get8(52).unwrap_or(0) == 0 { subtag(36, 4) } else { String::new() }; + let variant = subtag(40, 8); + let numbering = subtag(53, 8); + let mut locale = lang; + if !locale.is_empty() && (!script.is_empty() || !variant.is_empty() || !numbering.is_empty()) { + locale.insert_str(0, "b+"); + for part in [&script, ®ion, &variant].into_iter().filter(|p| !p.is_empty()) { + locale.push('+'); + locale.push_str(part); + } + if !numbering.is_empty() { + locale.push_str("+u+nu+"); + locale.push_str(&numbering); + } + } else if !locale.is_empty() && !region.is_empty() { + locale.push_str(&format!("-r{region}")); + } + if !locale.is_empty() { + q.push(locale.clone()); + } + let axis = |q: &mut Vec, v: Option, mask, names: &[(u8, &str)]| { + if let Some(key) = v.map(|n| n & mask) + && let Some((_, name)) = names.iter().find(|(value, _)| *value == key) + { + q.push((*name).to_owned()); + } + }; + axis(&mut q, get8(19), 0x03, &[(1, "neuter"), (2, "feminine"), (3, "masculine")]); + if let Some(sl) = get8(28) { + match sl & 0xc0 { + 0x40 => q.push("ldltr".into()), + 0x80 => q.push("ldrtl".into()), + _ => {} + } + } + if let Some(sw) = get16(30).filter(|&v| v != 0) { + q.push(format!("sw{sw}dp")); + } + if let Some(w) = get16(32).filter(|&v| v != 0) { + q.push(format!("w{w}dp")); + } + if let Some(h) = get16(34).filter(|&v| v != 0) { + q.push(format!("h{h}dp")); + } + if let Some(sl) = get8(28) { + match sl & 0x0f { + 1 => q.push("small".into()), + 2 => q.push("normal".into()), + 3 => q.push("large".into()), + 4 => q.push("xlarge".into()), + _ => {} + } + match sl & 0x30 { + 0x10 => q.push("notlong".into()), + 0x20 => q.push("long".into()), + _ => {} + } + } + axis(&mut q, get8(48), 0x03, &[(1, "notround"), (2, "round")]); + axis(&mut q, get8(49), 0x03, &[(1, "nowidecg"), (2, "widecg")]); + axis(&mut q, get8(49), 0x0c, &[(4, "lowdr"), (8, "highdr")]); + match get8(12) { + Some(1) => q.push("port".into()), + Some(2) => q.push("land".into()), + Some(3) => q.push("square".into()), + _ => {} + } + if let Some(ui) = get8(29) { + match ui & 0x0f { + 2 => q.push("desk".into()), + 3 => q.push("car".into()), + 4 => q.push("television".into()), + 5 => q.push("appliance".into()), + 6 => q.push("watch".into()), + 7 => q.push("vrheadset".into()), + _ => {} + } + match ui & 0x30 { + 0x10 => q.push("notnight".into()), + 0x20 => q.push("night".into()), + _ => {} + } + } + if let Some(d) = get16(14).filter(|&v| v != 0) { + q.push(match d { + 120 => "ldpi".into(), + 160 => "mdpi".into(), + 213 => "tvdpi".into(), + 240 => "hdpi".into(), + 320 => "xhdpi".into(), + 480 => "xxhdpi".into(), + 640 => "xxxhdpi".into(), + 0xfffe => "anydpi".into(), + 0xffff => "nodpi".into(), + d => format!("{d}dpi"), + }); + } + match get8(13) { + Some(1) => q.push("notouch".into()), + Some(3) => q.push("finger".into()), + _ => {} + } + axis(&mut q, get8(18), 0x03, &[(1, "keysexposed"), (2, "keyshidden"), (3, "keyssoft")]); + match get8(16) { + Some(1) => q.push("nokeys".into()), + Some(2) => q.push("qwerty".into()), + Some(3) => q.push("12key".into()), + _ => {} + } + axis(&mut q, get8(18), 0x0c, &[(4, "navexposed"), (8, "navhidden")]); + match get8(17) { + Some(1) => q.push("nonav".into()), + Some(2) => q.push("dpad".into()), + Some(3) => q.push("trackball".into()), + Some(4) => q.push("wheel".into()), + _ => {} + } + if let (Some(w), Some(h)) = (get16(20), get16(22)) + && w != 0 + && h != 0 + { + q.push(format!("{w}x{h}")); + } + if let Some(v) = get16(24).filter(|&v| v != 0) { + q.push(format!("v{v}")); + } + let s = if q.is_empty() { "default".to_string() } else { q.join("-") }; + (s, locale) +} + +struct Pkg<'a> { + name: &'a str, + id: u32, + types: &'a StringPool, + keys: &'a StringPool, +} + +fn type_name(p: &Pkg<'_>, id: u8) -> String { + p.types.get(u32::from(id).wrapping_sub(1)).map(str::to_string).unwrap_or_else(|| format!("type{id}")) +} + +/// Parse a resource table. +pub fn parse(data: &[u8], limits: Limits) -> Result { + let r = Reader::new(data); + let (t, h, size) = chunk(&r, 0).ok_or_else(|| Error::Truncated("resource table header".into()))?; + if t != RES_TABLE { + return Err(Error::Malformed(format!("not a resource table (chunk type {t:#x})"))); + } + let data = data.get(..size).ok_or_else(|| Error::Truncated("resource table payload".into()))?; + let r = Reader::new(data); + let mut table = Table::default(); + let mut global = StringPool::default(); + let mut pos = h; + while pos < size { + let Some((ct, _ch, cs)) = chunk(&r, pos) else { + table.warnings.push(format!("unreadable chunk at offset {pos}")); + break; + }; + match ct { + crate::axml::RES_STRING_POOL => match StringPool::parse(data, pos) { + Ok(p) => { + if p.strings.len() < p.declared { + table.truncated = true; + table.warnings.push(format!("global string pool was capped at {} of {} strings", p.strings.len(), p.declared)); + } + table.global_strings = p.declared; + global = p; + } + Err(e) => table.warnings.push(format!("global string pool: {e}")), + }, + RES_PACKAGE => { + if table.packages.len() >= MAX_PACKAGES { + table.warnings.push("too many packages; the rest were skipped".into()); + } else { + parse_package(data, pos, cs, &global, &mut table, limits); + } + } + _ => {} + } + pos = match pos.checked_add(cs) { + Some(p) => p, + None => break, + }; + } + Ok(table) +} + +fn parse_package(data: &[u8], pos: usize, cs: usize, global: &StringPool, table: &mut Table, limits: Limits) { + let Some(data) = pos.checked_add(cs).and_then(|end| data.get(..end)) else { + table.warnings.push("package runs past its resource table".into()); + return; + }; + let r = Reader::new(data); + let hsize = usize::from(r.u16_le(pos + 2).unwrap_or(0)); + if hsize < 284 { + table.warnings.push(format!("package at offset {pos}: incomplete header")); + return; + } + let id = r.u32_le(pos + 8).unwrap_or(0); + let name = utf16_fixed(&r, pos + 12, 128); + // Older 284-byte packages predate this field. Type names still use the + // unshifted chunk ID, while public resource identities include the offset. + let type_id_offset = if hsize >= 288 { r.u32_le(pos + 284).unwrap_or(0) } else { 0 }; + let Ok(type_id_offset) = u8::try_from(type_id_offset) else { + table.truncated = true; + table.warnings.push(format!("package {name}: type ID offset is outside the one-byte type field")); + return; + }; + let type_strings = r.u32_le(pos + 268).unwrap_or(0) as usize; + let key_strings = r.u32_le(pos + 276).unwrap_or(0) as usize; + let end = data.len(); + let mut read_pool = |offset: usize, label: &str| { + if offset == 0 { + return StringPool::default(); + } + let Some(start) = pos.checked_add(offset).filter(|&start| offset >= hsize && start < end) else { + table.warnings.push(format!("package {name}: {label} string pool is outside its payload")); + return StringPool::default(); + }; + match StringPool::parse(data, start) { + Ok(pool) => { + if pool.strings.len() < pool.declared { + table.truncated = true; + table.warnings.push(format!( + "package {name}: {label} string pool was capped at {} of {} strings", + pool.strings.len(), + pool.declared + )); + } + pool + } + Err(error) => { + table.warnings.push(format!("package {name}: {label} string pool: {error}")); + StringPool::default() + } + } + }; + let types = read_pool(type_strings, "type"); + let keys = read_pool(key_strings, "key"); + let mut package = Package { id, name: name.clone(), types: Vec::new(), keys: keys.declared, libraries: Vec::new() }; + let p = Pkg { name: &name, id, types: &types, keys: &keys }; + let mut c = pos.saturating_add(hsize.max(8)); + while c < end { + let Some((ct, ch, sz)) = chunk(&r, c) else { + table.warnings.push(format!("package {name}: unreadable chunk at offset {c}")); + break; + }; + // Each child was checked against its package; reads within it must also stop before + // the next sibling, including fixed-width library records and bag headers. + let Some(child) = data.get(..c.saturating_add(sz)) else { + table.warnings.push(format!("package {name}: child chunk runs past its package")); + break; + }; + let r = Reader::new(child); + let local_tid = r.u8(c + 8).unwrap_or(0); + let type_id = local_tid.checked_add(type_id_offset).filter(|_| local_tid != 0); + match (ct, type_id) { + (RES_TYPE_SPEC, Some(tid)) if ch >= 16 => { + let count = r.u32_le(c + 12).unwrap_or(0); + if !package.types.iter().any(|t| t.id == tid) && package.types.len() < 256 { + package.types.push(TypeInfo { id: tid, name: type_name(&p, local_tid), entry_count: count, configs: Vec::new() }); + } + } + (RES_TYPE, Some(tid)) if ch >= 24 => { + let (cfg, _) = config_qualifiers(&r, c + 20); + match package.types.iter_mut().find(|t| t.id == tid) { + Some(t) => { + if !t.configs.contains(&cfg) && t.configs.len() < 4096 { + t.configs.push(cfg); + } + } + None => { + if package.types.len() < 256 { + package.types.push(TypeInfo { + id: tid, + name: type_name(&p, local_tid), + entry_count: r.u32_le(c + 12).unwrap_or(0), + configs: vec![cfg], + }) + } + } + } + parse_type(&r, c, ch, sz, &p, tid, global, table, limits); + } + (RES_TYPE_SPEC | RES_TYPE, None) if ch >= 16 => { + table.truncated = true; + table.warnings.push(format!("package {name}: type ID {local_tid} with offset {type_id_offset} is outside the one-byte type field")); + } + (RES_LIBRARY, _) if ch >= 12 => { + let n = r.u32_le(c + 8).unwrap_or(0) as usize; + let available = (sz - ch) / 260; + if n > available { + table.warnings.push(format!("package {name}: library records run past their chunk")); + } + for i in 0..n.min(256).min(available) { + let e = c + ch + i * 260; + if let Some(lid) = r.u32_le(e) { + package.libraries.push((lid, utf16_fixed(&r, e + 4, 128))); + } + } + } + (RES_TYPE_SPEC | RES_TYPE | RES_LIBRARY, _) => { + table.warnings.push(format!("package {name}: incomplete chunk header at offset {c}")); + } + _ => {} + } + c = match c.checked_add(sz) { + Some(x) => x, + None => break, + }; + } + table.packages.push(package); +} + +#[allow(clippy::too_many_arguments)] +fn parse_type(r: &Reader<'_>, c: usize, ch: usize, sz: usize, p: &Pkg<'_>, type_id: u8, global: &StringPool, table: &mut Table, limits: Limits) { + let tid = r.u8(c + 8).unwrap_or(0); + let flags = r.u8(c + 9).unwrap_or(0); + let count = r.u32_le(c + 12).unwrap_or(0) as usize; + let entries_start = r.u32_le(c + 16).unwrap_or(0) as usize; + let (cfg, locale) = config_qualifiers(r, c + 20); + let end = c + sz; + let tname = type_name(p, tid); + let sparse = flags & 0x01 != 0; + let off16 = flags & 0x02 != 0; + // (entry index, offset from entries_start) + let mut slots: Vec<(u32, usize)> = Vec::new(); + let table_bytes = if sparse || off16 { count.saturating_mul(if sparse { 4 } else { 2 }) } else { count.saturating_mul(4) }; + if c.saturating_add(ch).saturating_add(table_bytes) > end { + table.warnings.push(format!("{tname} ({cfg}): entry table runs past its chunk")); + return; + } + if count != 0 && (entries_start < ch.saturating_add(table_bytes) || entries_start > sz) { + table.warnings.push(format!("{tname} ({cfg}): invalid entry data start")); + return; + } + for i in 0..count { + let at = c + ch; + if sparse { + let (Some(idx), Some(o)) = (r.u16_le(at + i * 4), r.u16_le(at + i * 4 + 2)) else { break }; + slots.push((u32::from(idx), usize::from(o) * 4)); + } else if off16 { + let Some(o) = r.u16_le(at + i * 2) else { break }; + if o != 0xffff { + slots.push((i as u32, usize::from(o) * 4)); + } + } else { + let Some(o) = r.u32_le(at + i * 4) else { break }; + if o != NO_ENTRY { + slots.push((i as u32, o as usize)); + } + } + } + for (idx, o) in slots { + if table.entries.len() >= limits.max_entries { + table.truncated = true; + return; + } + let Some(e) = c.checked_add(entries_start).and_then(|x| x.checked_add(o)) else { continue }; + if e.saturating_add(8) > end { + continue; + } + let esize = usize::from(r.u16_le(e).unwrap_or(0)); + let eflags = r.u16_le(e + 2).unwrap_or(0); + let id = (p.id << 24) | (u32::from(type_id) << 16) | (idx & 0xffff); + let mut entry = Entry { + id: format!("{id:#010x}"), + package: p.name.to_string(), + type_name: tname.clone(), + key: String::new(), + config: cfg.clone(), + locale: locale.clone(), + value: None, + value_type: None, + parent: None, + bag: Vec::new(), + raw: None, + }; + if eflags & 0x08 != 0 { + // Compact entry: key index in the size field, type in the high byte of flags. + entry.key = p.keys.get(u32::from(r.u16_le(e).unwrap_or(0))).unwrap_or("").to_string(); + let v = ResValue { data_type: (eflags >> 8) as u8, data: r.u32_le(e + 4).unwrap_or(0) }; + entry.value = Some(v.format(global)); + entry.value_type = Some(v.type_name()); + entry.raw = Some(v); + } else { + entry.key = r.u32_le(e + 4).and_then(|k| p.keys.get(k)).unwrap_or("").to_string(); + if eflags & 0x01 != 0 { + if esize < 16 || e.saturating_add(esize) > end { + table.truncated = true; + table.warnings.push(format!("{tname} ({cfg}): incomplete bag header")); + table.entries.push(entry); + continue; + } + let n = r.u32_le(e + 12).unwrap_or(0) as usize; + let mut m = e + esize; + if n > (end - m) / 12 { + table.truncated = true; + table.warnings.push(format!("{tname} ({cfg}): incomplete bag data")); + table.entries.push(entry); + continue; + } + let parent = r.u32_le(e + 8).unwrap_or(0); + if parent != 0 { + entry.parent = Some(format!("@{parent:#010x}")); + } + if n > MAX_BAG { + table.truncated = true; + } + for _ in 0..n.min(MAX_BAG) { + if m.saturating_add(12) > end { + break; + } + let name = r.u32_le(m).unwrap_or(0); + let v = ResValue { data_type: r.u8(m + 7).unwrap_or(0), data: r.u32_le(m + 8).unwrap_or(0) }; + entry.bag.push(BagItem { name: format!("@{name:#010x}"), value: v.format(global), value_type: v.type_name() }); + m += 12; + } + } else { + let v_at = e.saturating_add(esize.max(8)); + if v_at.saturating_add(8) <= end { + let v = ResValue { data_type: r.u8(v_at + 3).unwrap_or(0), data: r.u32_le(v_at + 4).unwrap_or(0) }; + entry.value = Some(v.format(global)); + entry.value_type = Some(v.type_name()); + entry.raw = Some(v); + } + } + } + table.entries.push(entry); + } +} + +impl Table { + /// String resources grouped by locale (`""` = default): (locale, key, value). + pub fn strings_by_locale(&self) -> std::collections::BTreeMap> { + let mut out: std::collections::BTreeMap> = Default::default(); + for e in self.entries.iter().filter(|e| e.type_name == "string") { + if let Some(v) = &e.value { + out.entry(e.locale.clone()).or_default().push((e.key.clone(), v.clone())); + } + } + out + } +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::fixtures as fx; + + #[test] + fn decodes_table() { + let t = parse(&fx::resources_arsc(), Limits::default()).unwrap(); + assert!(t.warnings.is_empty(), "{:?}", t.warnings); + assert_eq!(t.packages.len(), 1); + let p = &t.packages[0]; + assert_eq!(p.id, 0x7f); + assert_eq!(p.name, fx::PACKAGE); + assert_eq!(p.types[0].name, "string"); + assert_eq!(p.types[0].configs, vec!["default", "fr"]); + let by = t.strings_by_locale(); + assert_eq!(by[""], vec![("app_name".to_string(), "Notes".to_string()), ("greeting".to_string(), "Hello".to_string())]); + assert_eq!(by["fr"], vec![("app_name".to_string(), "Notes FR".to_string()), ("greeting".to_string(), "Bonjour".to_string())]); + let app = t.entries.iter().find(|e| e.key == "app_name" && e.locale.is_empty()).unwrap(); + assert_eq!(app.id, "0x7f010000"); + let style = t.entries.iter().find(|e| e.type_name == "style").unwrap(); + assert_eq!(style.key, "AppTheme"); + assert_eq!(style.parent.as_deref(), Some("@0x01030005")); + assert_eq!(style.bag[0].value, "#ff336699"); + assert_eq!(style.config, "night-xhdpi-v21"); + } + + #[test] + fn distinct_locale_scripts_and_variants_keep_separate_keys() { + let mut cfg = [0u8; 64]; + cfg[0] = 64; + cfg[8..12].copy_from_slice(b"zhTW"); + cfg[36..40].copy_from_slice(b"Hant"); + assert_eq!(config_qualifiers(&Reader::new(&cfg), 0).1, "b+zh+Hant+TW"); + cfg[36..40].copy_from_slice(b"Hans"); + assert_eq!(config_qualifiers(&Reader::new(&cfg), 0).1, "b+zh+Hans+TW"); + cfg[52] = 1; // The inferred script is not part of the requested locale. + assert_eq!(config_qualifiers(&Reader::new(&cfg), 0).1, "zh-rTW"); + cfg[40..45].copy_from_slice(b"POSIX"); + assert_eq!(config_qualifiers(&Reader::new(&cfg), 0).1, "b+zh+TW+POSIX"); + cfg[53..57].copy_from_slice(b"latn"); + assert_eq!(config_qualifiers(&Reader::new(&cfg), 0).1, "b+zh+TW+POSIX+u+nu+latn"); + cfg[0] = 36; // Bytes beyond the declared configuration are unrelated. + assert_eq!(config_qualifiers(&Reader::new(&cfg), 0).1, "zh-rTW"); + } + + #[test] + fn qualifiers() { + let mut cfg = vec![0u8; 64]; + cfg[0] = 64; + cfg[8] = b'e'; + cfg[9] = b's'; + cfg[10] = b'M'; + cfg[11] = b'X'; + cfg[12] = 2; + let (q, l) = config_qualifiers(&Reader::new(&cfg), 0); + assert_eq!(q, "es-rMX-land"); + assert_eq!(l, "es-rMX"); + } +} diff --git a/crates/android-res/src/axml.rs b/crates/android-res/src/axml.rs new file mode 100644 index 0000000000..e76617940c --- /dev/null +++ b/crates/android-res/src/axml.rs @@ -0,0 +1,763 @@ +//! Android binary XML (AXML): the compiled form of `AndroidManifest.xml` and `res/*.xml`. +//! Chunks, the string pool (UTF-8 and UTF-16), the resource-id map, namespaces, elements and +//! typed attribute values. Also the string pool and typed-value formatting that resource tables +//! share. Manifest inventory and policy are left to callers. + +use crate::Error; +use crate::bytes::Reader; +use serde::Serialize; + +pub const RES_STRING_POOL: u16 = 0x0001; +pub const RES_XML: u16 = 0x0003; +const XML_START_NS: u16 = 0x0100; +const XML_END_NS: u16 = 0x0101; +const XML_START_ELEMENT: u16 = 0x0102; +const XML_END_ELEMENT: u16 = 0x0103; +const XML_CDATA: u16 = 0x0104; +const XML_RESOURCE_MAP: u16 = 0x0180; + +/// Most strings decoded from one pool. +const MAX_STRINGS: usize = 1_000_000; +/// Longest string kept (characters). +const MAX_STRING: usize = 64 * 1024; +/// Base budget for decoded string bytes; larger chunks allow at most three times their size. +const BASE_POOL_BYTES: usize = 64 << 20; +/// Most extra UTF-8 length candidates examined across one string pool. +const MAX_RECOVERY_PROBES: usize = 65_536; +/// Most XML nodes decoded. +const MAX_NODES: usize = 200_000; +/// Deepest element nesting tracked. +const MAX_DEPTH: usize = 512; + +pub const ANDROID_NS: &str = "http://schemas.android.com/apk/res/android"; + +/// A chunk header: type, header size, total size, at `off`. +pub(crate) fn chunk(r: &Reader<'_>, off: usize) -> Option<(u16, usize, usize)> { + let t = r.u16_le(off)?; + let h = usize::from(r.u16_le(off.checked_add(2)?)?); + let s = r.u32_le(off.checked_add(4)?)? as usize; + if h < 8 || s < h || off.checked_add(s)? > r.len() { + return None; + } + Some((t, h, s)) +} + +/// Reads the bounded Android chunk header at the given byte offset. +pub fn chunk_header(data: &[u8], off: usize) -> Option<(u16, usize, usize)> { + chunk(&Reader::new(data), off) +} + +/// A decoded string pool. +#[derive(Debug, Clone, Default, PartialEq, Eq)] +pub struct StringPool { + pub strings: Vec, + pub utf8: bool, + /// Strings the pool declared (may exceed `strings.len()` when capped). + pub declared: usize, +} + +impl StringPool { + pub fn get(&self, i: u32) -> Option<&str> { + if i == u32::MAX { + return None; + } + self.strings.get(i as usize).map(String::as_str) + } + + /// Parse the pool whose chunk starts at `off`, retaining a prefix within the string and byte budgets. + pub fn parse(data: &[u8], off: usize) -> Result { + let mut recovery_left = MAX_RECOVERY_PROBES; + Self::parse_with_recovery_budget(data, off, &mut recovery_left) + } + + fn parse_with_recovery_budget(data: &[u8], off: usize, recovery_left: &mut usize) -> Result { + let r = Reader::new(data); + let (t, hdr, size) = chunk(&r, off).ok_or_else(|| Error::Truncated("string pool header".into()))?; + if t != RES_STRING_POOL { + return Err(Error::Malformed(format!("expected a string pool, found chunk type {t:#x}"))); + } + if hdr < 28 { + return Err(Error::Malformed("string pool header is smaller than 28 bytes".into())); + } + let r = Reader::new(r.slice(off, size).ok_or_else(|| Error::Truncated("string pool".into()))?); + let count = r.u32_le(8).ok_or_else(|| Error::Truncated("string pool".into()))? as usize; + let styles = r.u32_le(12).ok_or_else(|| Error::Truncated("string pool".into()))? as usize; + let flags = r.u32_le(16).ok_or_else(|| Error::Truncated("string pool".into()))?; + let strings_start = r.u32_le(20).ok_or_else(|| Error::Truncated("string pool".into()))? as usize; + let styles_start = r.u32_le(24).ok_or_else(|| Error::Truncated("string pool".into()))? as usize; + let utf8 = flags & (1 << 8) != 0; + let offsets_end = count + .checked_add(styles) + .and_then(|n| n.checked_mul(4)) + .and_then(|n| hdr.checked_add(n)) + .ok_or_else(|| Error::Malformed("string pool offset tables are too large".into()))?; + if offsets_end > size || strings_start > size || (count != 0 && strings_start < offsets_end) { + return Err(Error::Malformed("string pool offset tables or string data lie outside their area".into())); + } + if (styles != 0 && styles_start == 0) + || (styles_start != 0 && (styles_start < offsets_end || styles_start < strings_start || styles_start > size)) + { + return Err(Error::Malformed("string pool style data lie outside their area".into())); + } + let end = if styles_start == 0 { size } else { styles_start }; + let string_bytes = r.slice(strings_start, end - strings_start).ok_or_else(|| Error::Truncated("string data".into()))?; + let strings_reader = Reader::new(string_bytes); + let mut strings = Vec::with_capacity(count.min(MAX_STRINGS).min(65_536)); + let mut bytes_left = BASE_POOL_BYTES.max(size.saturating_mul(3)); + for i in 0..count.min(MAX_STRINGS) { + let at = r.u32_le(hdr + i * 4).ok_or_else(|| Error::Truncated("string offsets".into()))? as usize; + let s = if at >= string_bytes.len() { + None + } else if utf8 { + utf8_string(&strings_reader, at, string_bytes.len(), recovery_left) + } else { + utf16_string(&strings_reader, at, string_bytes.len()) + }; + let s = s.unwrap_or_default(); + if s.len() > bytes_left { + break; + } + bytes_left -= s.len(); + strings.push(s); + } + Ok(StringPool { strings, utf8, declared: count }) + } +} + +fn utf8_len(r: &Reader<'_>, at: usize) -> Option<(usize, usize)> { + let b0 = usize::from(r.u8(at)?); + if b0 & 0x80 != 0 { + let b1 = usize::from(r.u8(at + 1)?); + Some((((b0 & 0x7f) << 8) | b1, 2)) + } else { + Some((b0, 1)) + } +} + +fn utf8_string(r: &Reader<'_>, at: usize, end: usize, recovery_left: &mut usize) -> Option { + let (_chars, n1) = utf8_len(r, at)?; + let (mut bytes, n2) = utf8_len(r, at.checked_add(n1)?)?; + let start = at.checked_add(n1 + n2)?; + // Older AAPT keeps only the low 15 length bits; probe matching lengths inside this pool. + loop { + let terminator = start.checked_add(bytes)?; + if terminator >= end { + return None; + } + // The declared candidate costs one read per entry, already bounded by MAX_STRINGS. + if bytes >= 0x8000 { + *recovery_left = recovery_left.checked_sub(1)?; + } + if r.u8(terminator)? == 0 { + break; + } + bytes = bytes.checked_add(0x8000)?; + } + let b = r.slice(start, bytes.min(MAX_STRING * 4))?; + Some(String::from_utf8_lossy(b).into_owned()) +} + +fn utf16_string(r: &Reader<'_>, at: usize, end: usize) -> Option { + let u0 = usize::from(r.u16_le(at)?); + let (len, hdr) = if u0 & 0x8000 != 0 { (((u0 & 0x7fff) << 16) | usize::from(r.u16_le(at + 2)?), 4) } else { (u0, 2) }; + let start = at.checked_add(hdr)?; + let terminator = start.checked_add(len.checked_mul(2)?)?; + if terminator.checked_add(2)? > end || r.u16_le(terminator)? != 0 { + return None; + } + let n = len.min(MAX_STRING); + let mut units = Vec::with_capacity(n); + for i in 0..n { + units.push(r.u16_le(start + i * 2)?); + } + Some(String::from_utf16_lossy(&units)) +} + +/// A typed value (`Res_value`): data type and 32-bit data. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)] +pub struct ResValue { + pub data_type: u8, + pub data: u32, +} + +impl ResValue { + pub fn type_name(&self) -> &'static str { + match self.data_type { + 0x00 => "null", + 0x01 => "reference", + 0x02 => "attribute", + 0x03 => "string", + 0x04 => "float", + 0x05 => "dimension", + 0x06 => "fraction", + 0x07 => "dynamic-reference", + 0x08 => "dynamic-attribute", + 0x10 => "int-dec", + 0x11 => "int-hex", + 0x12 => "boolean", + 0x1c => "color-argb8", + 0x1d => "color-rgb8", + 0x1e => "color-argb4", + 0x1f => "color-rgb4", + _ => "unknown", + } + } + + /// Human form; strings come from `pool`. + pub fn format(&self, pool: &StringPool) -> String { + let d = self.data; + match self.data_type { + 0x00 => { + if d == 1 { + "@empty".into() + } else { + "@null".into() + } + } + 0x01 | 0x07 => { + if d == 0 { + "@null".into() + } else { + format!("@{d:#010x}") + } + } + 0x02 | 0x08 => format!("?{d:#010x}"), + 0x03 => pool.get(d).unwrap_or("").to_string(), + 0x04 => format!("{}", f32::from_bits(d)), + 0x05 => complex(d, &["px", "dp", "sp", "pt", "in", "mm"]), + 0x06 => complex(d, &["%", "%p"]), + 0x10 => (d as i32).to_string(), + 0x11 => format!("{d:#x}"), + 0x12 => (if d != 0 { "true" } else { "false" }).into(), + 0x1c..=0x1f => format!("#{d:08x}"), + _ => format!("{d:#x} (type {:#x})", self.data_type), + } + } +} + +fn complex(d: u32, units: &[&str]) -> String { + const RADIX: [f64; 4] = [1.0, 1.0 / 128.0, 1.0 / 32768.0, 1.0 / 8_388_608.0]; + let mantissa = f64::from((d & 0xffff_ff00) as i32 >> 8); + let radix = RADIX.get(((d >> 4) & 3) as usize).copied().unwrap_or(1.0); + let mut v = mantissa * radix; + let unit = units.get((d & 0xf) as usize).copied().unwrap_or("?"); + if units.len() == 2 { + v *= 100.0; + } + let v = (v * 10_000.0).round() / 10_000.0; + format!("{v}{unit}") +} + +/// One attribute of an element. +#[derive(Debug, Clone, PartialEq, Serialize)] +pub struct Attribute { + #[serde(skip_serializing_if = "Option::is_none")] + pub namespace: Option, + pub name: String, + /// The framework/app resource id of the attribute name, when the resource map gives one. + #[serde(skip_serializing_if = "Option::is_none")] + pub resource_id: Option, + /// Formatted value. + pub value: String, + pub value_type: &'static str, + #[serde(skip)] + pub raw: ResValue, +} + +/// One XML node event. +#[derive(Debug, Clone, PartialEq, Serialize)] +#[serde(tag = "kind", rename_all = "snake_case")] +pub enum Node { + Start { depth: usize, name: String, namespace: Option, line: u32, attributes: Vec }, + End { depth: usize, name: String }, + Text { depth: usize, text: String }, + Namespace { prefix: String, uri: String }, +} + +/// A decoded binary XML document. +#[derive(Debug, Clone, Default, PartialEq, Serialize)] +pub struct Document { + pub nodes: Vec, + #[serde(skip)] + pub pool: StringPool, + pub resource_ids: usize, + pub namespaces: Vec<(String, String)>, + pub truncated: bool, + pub warnings: Vec, +} + +/// Names of common framework attributes by resource id, used when a name string was stripped. +pub fn framework_attr(id: u32) -> Option<&'static str> { + Some(match id { + 0x0101_0000 => "theme", + 0x0101_0001 => "label", + 0x0101_0002 => "icon", + 0x0101_0003 => "name", + 0x0101_0006 => "permission", + 0x0101_0007 => "readPermission", + 0x0101_0008 => "writePermission", + 0x0101_0009 => "protectionLevel", + 0x0101_000e => "enabled", + 0x0101_000f => "debuggable", + 0x0101_0010 => "exported", + 0x0101_0018 => "authorities", + 0x0101_020c => "minSdkVersion", + 0x0101_021b => "versionCode", + 0x0101_021c => "versionName", + 0x0101_0270 => "targetSdkVersion", + 0x0101_0271 => "maxSdkVersion", + 0x0101_0280 => "allowBackup", + _ => return None, + }) +} + +/// Decode a binary XML file. +pub fn parse(data: &[u8]) -> Result { + let r = Reader::new(data); + let (t, h, size) = chunk(&r, 0).ok_or_else(|| Error::Truncated("binary XML header".into()))?; + if t != RES_XML { + return Err(Error::Malformed(format!("not binary XML (chunk type {t:#x})"))); + } + let data = r.slice(0, size).ok_or_else(|| Error::Truncated("binary XML document".into()))?; + let r = Reader::new(data); + let mut doc = Document::default(); + let mut res_map: Vec = Vec::new(); + let mut pos = h; + let mut depth = 0usize; + let mut ns_stack: Vec<(String, String)> = Vec::new(); + while pos < size { + let Some((ct, ch, cs)) = chunk(&r, pos) else { + doc.truncated = true; + doc.warnings.push(format!("unreadable chunk at offset {pos}")); + break; + }; + let extension = match ct { + XML_START_NS | XML_END_NS | XML_END_ELEMENT => 8, + XML_START_ELEMENT => 20, + XML_CDATA => 12, + _ => 0, + }; + if extension != 0 && (ch < 16 || cs - ch < extension) { + doc.truncated = true; + doc.warnings.push(format!("incomplete XML node at offset {pos}")); + break; + } + match ct { + RES_STRING_POOL => match StringPool::parse(data, pos) { + Ok(p) => { + if p.strings.len() < p.declared { + doc.truncated = true; + doc.warnings.push(format!("string pool was capped at {} of {} strings", p.strings.len(), p.declared)); + } + doc.pool = p; + } + Err(e) => doc.warnings.push(format!("string pool: {e}")), + }, + XML_RESOURCE_MAP => { + let n = (cs - ch) / 4; + res_map = (0..n.min(MAX_STRINGS)).filter_map(|i| r.u32_le(pos + ch + i * 4)).collect(); + doc.resource_ids = res_map.len(); + } + XML_START_NS | XML_END_NS => { + let prefix = r.u32_le(pos + ch).and_then(|i| doc.pool.get(i)).unwrap_or("").to_string(); + let uri = r.u32_le(pos + ch + 4).and_then(|i| doc.pool.get(i)).unwrap_or("").to_string(); + if ct == XML_START_NS { + if doc.namespaces.len() < 256 { + doc.namespaces.push((prefix.clone(), uri.clone())); + } + if ns_stack.len() < MAX_DEPTH { + ns_stack.push((prefix.clone(), uri.clone())); + } + if doc.nodes.len() < MAX_NODES { + doc.nodes.push(Node::Namespace { prefix, uri }); + } + } else { + ns_stack.pop(); + } + } + XML_START_ELEMENT => { + if doc.nodes.len() >= MAX_NODES { + doc.truncated = true; + break; + } + let line = r.u32_le(pos + 8).unwrap_or(0); + let ext = pos + ch; + let ns = r.u32_le(ext).and_then(|i| doc.pool.get(i)).map(str::to_string); + let name = r.u32_le(ext + 4).and_then(|i| doc.pool.get(i)).unwrap_or("?").to_string(); + let a_start = usize::from(r.u16_le(ext + 8).unwrap_or(20)); + let a_size = usize::from(r.u16_le(ext + 10).unwrap_or(20)); + let a_count = usize::from(r.u16_le(ext + 12).unwrap_or(0)); + if a_count != 0 && (a_start < 20 || a_size < 20) { + doc.truncated = true; + doc.warnings.push(format!("element {name}: invalid attribute table layout")); + break; + } + let mut attributes = Vec::new(); + for i in 0..a_count { + let relative = a_start + i * a_size; + if relative.checked_add(a_size).is_none_or(|end| end > cs - ch) { + doc.truncated = true; + doc.warnings.push(format!("element {name}: attribute {i} runs past its chunk")); + break; + } + let a = ext + relative; + let value_size = usize::from(r.u16_le(a + 12).unwrap_or(0)); + if value_size < 8 || value_size > a_size - 12 { + doc.truncated = true; + doc.warnings.push(format!("element {name}: invalid typed value size in attribute {i}")); + break; + } + let ans = r.u32_le(a).and_then(|i| doc.pool.get(i)).map(str::to_string); + let name_idx = r.u32_le(a + 4).unwrap_or(u32::MAX); + let raw_str = r.u32_le(a + 8).unwrap_or(u32::MAX); + let vt = r.u8(a + 15).unwrap_or(0); + let vd = r.u32_le(a + 16).unwrap_or(0); + let rid = res_map.get(name_idx as usize).copied(); + let mut aname = doc.pool.get(name_idx).unwrap_or("").to_string(); + if aname.is_empty() { + aname = rid.and_then(framework_attr).map(str::to_string).unwrap_or_else(|| format!("attr_{name_idx}")); + } + let raw = ResValue { data_type: vt, data: vd }; + let value = if vt == 0x03 || (raw_str != u32::MAX && vt == 0) { + doc.pool.get(if vt == 0x03 { vd } else { raw_str }).unwrap_or("").to_string() + } else { + raw.format(&doc.pool) + }; + attributes.push(Attribute { + namespace: ans, + name: aname, + resource_id: rid.map(|x| format!("{x:#010x}")), + value, + value_type: raw.type_name(), + raw, + }); + } + doc.nodes.push(Node::Start { depth, name, namespace: ns, line, attributes }); + depth = (depth + 1).min(MAX_DEPTH); + } + XML_END_ELEMENT => { + depth = depth.saturating_sub(1); + let name = r.u32_le(pos + ch + 4).and_then(|i| doc.pool.get(i)).unwrap_or("?").to_string(); + if doc.nodes.len() < MAX_NODES { + doc.nodes.push(Node::End { depth, name }); + } + } + XML_CDATA => { + let text = r.u32_le(pos + ch).and_then(|i| doc.pool.get(i)).unwrap_or("").to_string(); + if doc.nodes.len() < MAX_NODES { + doc.nodes.push(Node::Text { depth, text }); + } + } + _ => {} + } + pos = match pos.checked_add(cs) { + Some(p) => p, + None => break, + }; + } + Ok(doc) +} + +fn esc(s: &str) -> String { + s.replace('&', "&").replace('<', "<").replace('>', ">").replace('"', """) +} + +impl Document { + fn prefix_for(&self, uri: &str) -> Option<&str> { + self.namespaces.iter().find(|(_, u)| u == uri).map(|(p, _)| p.as_str()) + } + + /// An XML text rendition (for reading, not byte-exact source). + pub fn to_xml(&self, max_bytes: usize) -> String { + let mut out = String::from("\n"); + let mut first = true; + for n in &self.nodes { + if out.len() > max_bytes { + out.push_str("\n"); + break; + } + match n { + Node::Start { depth, name, attributes, .. } => { + out.push_str(&" ".repeat((*depth).min(64))); + out.push('<'); + out.push_str(name); + if first { + for (p, u) in &self.namespaces { + out.push_str(&format!(" xmlns:{p}=\"{}\"", esc(u))); + } + first = false; + } + for a in attributes { + let p = a.namespace.as_deref().and_then(|u| self.prefix_for(u)).map(|p| format!("{p}:")).unwrap_or_default(); + out.push_str(&format!(" {p}{}=\"{}\"", a.name, esc(&a.value))); + } + out.push_str(">\n"); + } + Node::End { depth, name } => { + out.push_str(&" ".repeat((*depth).min(64))); + out.push_str(&format!("\n")); + } + Node::Text { depth, text } => { + out.push_str(&" ".repeat((*depth).min(64))); + out.push_str(&esc(text)); + out.push('\n'); + } + Node::Namespace { .. } => {} + } + } + out + } +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::fixtures as fx; + + fn pool_with_offsets(offsets: &[u32], string_data: &[u8]) -> Vec { + let start = 28 + offsets.len() * 4; + let mut data = vec![0; start]; + data[..2].copy_from_slice(&RES_STRING_POOL.to_le_bytes()); + data[2..4].copy_from_slice(&28u16.to_le_bytes()); + data[8..12].copy_from_slice(&(offsets.len() as u32).to_le_bytes()); + data[16..20].copy_from_slice(&0x100u32.to_le_bytes()); + data[20..24].copy_from_slice(&(start as u32).to_le_bytes()); + for (i, offset) in offsets.iter().enumerate() { + let at = 28 + i * 4; + data[at..at + 4].copy_from_slice(&offset.to_le_bytes()); + } + data.extend_from_slice(string_data); + data.resize(data.len().next_multiple_of(4), b'x'); + let size = data.len() as u32; + data[4..8].copy_from_slice(&size.to_le_bytes()); + data + } + + fn append_legacy_ascii(data: &mut Vec, len: usize) -> u32 { + let offset = data.len() as u32; + let encoded = [0x80 | ((len >> 8) & 0x7f) as u8, (len & 0xff) as u8]; + data.extend_from_slice(&encoded); + data.extend_from_slice(&encoded); + data.resize(data.len() + len, b'x'); + data.push(0); + offset + } + + fn shared_ascii_pool(utf8: bool, count: usize) -> Vec { + let len = 16_384usize; + let mut strings = Vec::new(); + if utf8 { + append_legacy_ascii(&mut strings, len); + } else { + strings.extend_from_slice(&(len as u16).to_le_bytes()); + for _ in 0..len { + strings.extend_from_slice(b"x\0"); + } + strings.extend_from_slice(&[0, 0]); + } + let mut data = pool_with_offsets(&vec![0; count], &strings); + if !utf8 { + data[16..20].fill(0); + } + data + } + + #[test] + fn shared_offsets_spend_a_pool_byte_budget() { + for utf8 in [true, false] { + let mut data = shared_ascii_pool(utf8, 8192); + for appended in [false, true] { + if appended { + // Unrelated bytes after the chunk cannot buy more retained copies. + data.resize(24 << 20, 0); + } + let pool = StringPool::parse(&data, 0).unwrap(); + assert_eq!(pool.declared, 8192); + assert_eq!(pool.strings.len(), 4096); + assert_eq!(pool.strings.iter().map(String::len).sum::(), 64 << 20); + assert_eq!(pool.get(4095).map(str::len), Some(16_384)); + assert_eq!(pool.get(4096), None); + } + let data = shared_ascii_pool(utf8, 2); + let pool = StringPool::parse(&data, 0).unwrap(); + assert_eq!(pool.strings.len(), 2); + assert_eq!(pool.get(0), pool.get(1)); + } + } + + fn pool_container(kind: u16, header: usize, children: &[u8]) -> Vec { + let mut data = vec![0; header]; + data[0..2].copy_from_slice(&kind.to_le_bytes()); + data[2..4].copy_from_slice(&(header as u16).to_le_bytes()); + data.extend_from_slice(children); + let len = data.len() as u32; + data[4..8].copy_from_slice(&len.to_le_bytes()); + data + } + + #[test] + fn xml_and_resource_tables_disclose_partial_string_pools() { + let pool = shared_ascii_pool(true, 8192); + { + let doc = parse(&pool_container(RES_XML, 8, &pool)).unwrap(); + assert!(doc.truncated); + assert!(doc.warnings.iter().any(|w| w.contains("string pool") && w.contains("4096 of 8192"))); + assert_eq!(doc.pool.strings.len(), 4096); + } + let table = crate::arsc::parse(&pool_container(2, 12, &pool), crate::arsc::Limits::default()).unwrap(); + assert!(table.truncated); + assert_eq!(table.global_strings, 8192); + assert!(table.warnings.iter().any(|w| w.contains("global string pool") && w.contains("4096 of 8192"))); + for (field, label) in [(268, "type"), (276, "key")] { + let mut package = pool_container(0x0200, 288, &pool); + package[8..12].copy_from_slice(&0x7fu32.to_le_bytes()); + package[field..field + 4].copy_from_slice(&288u32.to_le_bytes()); + let table = crate::arsc::parse(&pool_container(2, 12, &package), crate::arsc::Limits::default()).unwrap(); + assert!(table.truncated, "{label}"); + assert!(table.warnings.iter().any(|w| w.contains(&format!("{label} string pool")) && w.contains("4096 of 8192"))); + assert_eq!(table.packages.len(), 1); + } + } + + #[test] + fn repeated_offsets_share_the_utf8_recovery_budget() { + let mut strings = Vec::new(); + let long = append_legacy_ascii(&mut strings, 0x8000); + let short = strings.len() as u32; + strings.extend_from_slice(b"\x02\x02ok\0"); + let data = pool_with_offsets(&[long, long, long, short], &strings); + let mut left = 2; + let parsed = StringPool::parse_with_recovery_budget(&data, 0, &mut left).unwrap(); + assert_eq!(left, 0); + assert_eq!(parsed.declared, 4); + assert_eq!(parsed.strings.len(), 4); + assert_eq!(parsed.get(0).map(str::len), Some(0x8000)); + assert_eq!(parsed.get(1), parsed.get(0)); + assert_eq!(parsed.get(2), Some("")); + assert_eq!(parsed.get(3), Some("ok")); + } + + #[test] + fn distinct_offsets_share_the_utf8_recovery_budget() { + let mut strings = Vec::new(); + let mut offsets: Vec = (0..3).map(|_| append_legacy_ascii(&mut strings, 0x8000)).collect(); + offsets.push(strings.len() as u32); + strings.extend_from_slice(b"\x02\x02ok\0"); + let data = pool_with_offsets(&offsets, &strings); + let mut left = 2; + let parsed = StringPool::parse_with_recovery_budget(&data, 0, &mut left).unwrap(); + assert_eq!(left, 0); + assert_eq!(parsed.get(0).map(str::len), Some(0x8000)); + assert_eq!(parsed.get(1).map(str::len), Some(0x8000)); + assert_eq!(parsed.get(2), Some("")); + assert_eq!(parsed.get(3), Some("ok")); + } + + #[test] + fn utf8_recovery_stops_before_a_probe_without_credit() { + let mut strings = Vec::new(); + let long = append_legacy_ascii(&mut strings, 0x10000); + let short = strings.len() as u32; + strings.extend_from_slice(b"\x02\x02ok\0"); + let data = pool_with_offsets(&[long, short], &strings); + for (allowance, length, remaining) in [(0, 0, 0), (1, 0, 0), (2, 0x10000, 0), (3, 0x10000, 1)] { + let mut left = allowance; + let parsed = StringPool::parse_with_recovery_budget(&data, 0, &mut left).unwrap(); + assert_eq!(left, remaining); + assert_eq!(parsed.get(0).map(str::len), Some(length)); + assert_eq!(parsed.get(1), Some("ok")); + } + } + + #[test] + fn short_strings_and_out_of_bounds_candidates_spend_no_recovery_probes() { + let data = pool_with_offsets(&[0, 5], b"\x80\0\x80\0x\x02\x02ok\0"); + let mut left = 7; + let parsed = StringPool::parse_with_recovery_budget(&data, 0, &mut left).unwrap(); + assert_eq!(left, 7); + assert_eq!(parsed.get(0), Some("")); + assert_eq!(parsed.get(1), Some("ok")); + } + + #[test] + fn default_pool_budget_stops_repeated_recovery_before_later_long_strings() { + let mut strings = vec![b'x'; 2 * 0x8000 + 16]; + strings[..4].copy_from_slice(&[0x80, 0, 0x80, 0]); + let long = append_legacy_ascii(&mut strings, 0x8000); + let short = strings.len() as u32; + strings.extend_from_slice(b"\x02\x02ok\0"); + // Offset zero has three in-bounds extra candidates, all nonzero. + let repeated = MAX_RECOVERY_PROBES / 3 + 1; + let mut offsets = vec![0; repeated]; + offsets.extend([long, short]); + let data = pool_with_offsets(&offsets, &strings); + let parsed = StringPool::parse(&data, 0).unwrap(); + assert_eq!(parsed.declared, repeated + 2); + assert_eq!(parsed.strings.len(), repeated + 2); + assert!(parsed.strings[..repeated].iter().all(String::is_empty)); + assert_eq!(parsed.get(repeated as u32), Some("")); + assert_eq!(parsed.get((repeated + 1) as u32), Some("ok")); + } + + fn chunk_at(data: &[u8], kind: u16) -> usize { + let r = Reader::new(data); + let mut pos = 8; + loop { + let (t, _, n) = chunk(&r, pos).unwrap(); + if t == kind { + return pos; + } + pos += n; + } + } + + #[test] + fn namespace_extensions_follow_the_declared_header() { + let mut data = fx::manifest_axml(); + let pos = chunk_at(&data, XML_START_NS); + data.splice(pos + 16..pos + 16, [0xff; 4]); + data[pos + 2..pos + 4].copy_from_slice(&20u16.to_le_bytes()); + data[pos + 4..pos + 8].copy_from_slice(&28u32.to_le_bytes()); + let len = data.len() as u32; + data[4..8].copy_from_slice(&len.to_le_bytes()); + let doc = parse(&data).unwrap(); + assert!(doc.warnings.is_empty()); + assert_eq!(doc.namespaces[0], ("android".into(), ANDROID_NS.into())); + } + + #[test] + fn extended_attribute_strides_keep_each_manifest_value() { + let mut data = fx::manifest_axml(); + let pos = chunk_at(&data, XML_START_ELEMENT); + let ext = pos + 16; + // The fixture writes three 20-byte attributes with 8-byte typed values. + for index in (1..=3).rev() { + let end = ext + 20 + index * 20; + data.splice(end..end, [0xff; 4]); + } + data[ext + 10..ext + 12].copy_from_slice(&24u16.to_le_bytes()); + data[pos + 4..pos + 8].copy_from_slice(&(36 + 3 * 24u32).to_le_bytes()); + let len = data.len() as u32; + data[4..8].copy_from_slice(&len.to_le_bytes()); + + let doc = parse(&data).unwrap(); + assert!(!doc.truncated); + assert!(doc.warnings.is_empty(), "{:?}", doc.warnings); + let Node::Start { attributes, .. } = &doc.nodes[1] else { + panic!("expected the manifest start after the namespace"); + }; + let pairs: Vec<_> = attributes.iter().map(|a| (a.name.as_str(), a.value.as_str())).collect(); + assert_eq!(pairs, [("package", fx::PACKAGE), ("versionCode", "42"), ("versionName", "1.2.3")]); + } + + #[test] + fn values_format() { + let p = StringPool { strings: vec!["x".into()], utf8: false, declared: 1 }; + assert_eq!(ResValue { data_type: 0x05, data: (16 << 8) | 1 }.format(&p), "16dp"); + assert_eq!(ResValue { data_type: 0x12, data: 0xffff_ffff }.format(&p), "true"); + assert_eq!(ResValue { data_type: 0x1c, data: 0xff00_ff00 }.format(&p), "#ff00ff00"); + assert_eq!(ResValue { data_type: 0x10, data: (-5i32) as u32 }.format(&p), "-5"); + assert_eq!(ResValue { data_type: 0x03, data: 0 }.format(&p), "x"); + assert_eq!(ResValue { data_type: 0x04, data: 1.5f32.to_bits() }.format(&p), "1.5"); + } +} diff --git a/crates/android-res/src/bytes.rs b/crates/android-res/src/bytes.rs new file mode 100644 index 0000000000..bf2e751d66 --- /dev/null +++ b/crates/android-res/src/bytes.rs @@ -0,0 +1,37 @@ +//! 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 slice(&self, off: usize, len: usize) -> Option<&'a [u8]> { + let end = off.checked_add(len)?; + self.data.get(off..end) + } + + pub fn u8(&self, off: usize) -> Option { + self.data.get(off).copied() + } + + fn arr(&self, off: usize) -> Option<[u8; N]> { + self.slice(off, N)?.try_into().ok() + } + + pub fn u16_le(&self, off: usize) -> Option { + self.arr(off).map(u16::from_le_bytes) + } + + pub fn u32_le(&self, off: usize) -> Option { + self.arr(off).map(u32::from_le_bytes) + } +} diff --git a/crates/android-res/src/fixtures.rs b/crates/android-res/src/fixtures.rs new file mode 100644 index 0000000000..54235d3b0c --- /dev/null +++ b/crates/android-res/src/fixtures.rs @@ -0,0 +1,376 @@ +//! Test-only XML and resource table fixtures ported from Craft Anything. + +pub const PACKAGE: &str = "com.example.notes"; + +fn u16le(v: &mut Vec, x: u16) { + v.extend_from_slice(&x.to_le_bytes()); +} + +fn u32le(v: &mut Vec, x: u32) { + v.extend_from_slice(&x.to_le_bytes()); +} + +fn align4(v: &mut Vec) { + while !v.len().is_multiple_of(4) { + v.push(0); + } +} + +/// A string pool chunk (UTF-16, or UTF-8 when `utf8`). +pub fn string_pool(strings: &[&str], utf8: bool) -> Vec { + let mut data = Vec::new(); + let mut offs = Vec::new(); + for s in strings { + offs.push(data.len() as u32); + if utf8 { + let n16 = s.encode_utf16().count(); + data.push(n16 as u8); + data.push(s.len() as u8); + data.extend_from_slice(s.as_bytes()); + data.push(0); + } else { + let units: Vec = s.encode_utf16().collect(); + u16le(&mut data, units.len() as u16); + for u in units { + u16le(&mut data, u); + } + u16le(&mut data, 0); + } + } + align4(&mut data); + let strings_start = 28 + 4 * strings.len(); + let mut v = Vec::new(); + u16le(&mut v, 0x0001); + u16le(&mut v, 28); + u32le(&mut v, (strings_start + data.len()) as u32); + u32le(&mut v, strings.len() as u32); + u32le(&mut v, 0); + u32le(&mut v, if utf8 { 1 << 8 } else { 0 }); + u32le(&mut v, strings_start as u32); + u32le(&mut v, 0); + for o in offs { + u32le(&mut v, o); + } + v.extend_from_slice(&data); + v +} + +/// An attribute value in a binary XML element. +#[derive(Debug, Clone, Copy)] +pub enum AxVal<'a> { + Str(&'a str), + Bool(bool), + Int(i32), + Hex(u32), + Ref(u32), +} + +#[derive(Debug, Clone)] +pub struct AxAttr<'a> { + pub name: &'a str, + /// Android framework attribute (namespaced, with its resource id). + pub res_id: Option, + pub val: AxVal<'a>, +} + +#[derive(Debug, Clone)] +pub enum AxNode<'a> { + Start(&'a str, Vec>), + End(&'a str), +} + +const NS: &str = "http://schemas.android.com/apk/res/android"; + +/// Shorthand for an `android:` attribute. +pub fn a<'a>(name: &'a str, res_id: u32, val: AxVal<'a>) -> AxAttr<'a> { + AxAttr { name, res_id: Some(res_id), val } +} + +/// Write a binary XML document with the android namespace declared on the root. +pub fn axml(nodes: &[AxNode<'_>]) -> Vec { + let mut strings: Vec = Vec::new(); + let mut ids: Vec = Vec::new(); + for n in nodes { + if let AxNode::Start(_, attrs) = n { + for at in attrs { + if let Some(id) = at.res_id + && !strings.iter().any(|s| s == at.name) + { + strings.push(at.name.to_string()); + ids.push(id); + } + } + } + } + let intern = |s: &str, strings: &mut Vec| -> u32 { + if let Some(i) = strings.iter().position(|x| x == s) { + return i as u32; + } + strings.push(s.to_string()); + (strings.len() - 1) as u32 + }; + let prefix = intern("android", &mut strings); + let uri = intern(NS, &mut strings); + let mut body = Vec::new(); + let ns_chunk = |t: u16| { + let mut c = Vec::new(); + u16le(&mut c, t); + u16le(&mut c, 16); + u32le(&mut c, 24); + u32le(&mut c, 1); + u32le(&mut c, u32::MAX); + u32le(&mut c, prefix); + u32le(&mut c, uri); + c + }; + body.extend(ns_chunk(0x0100)); + for (line, n) in nodes.iter().enumerate() { + match n { + AxNode::Start(name, attrs) => { + let nidx = intern(name, &mut strings); + let mut c = Vec::new(); + u16le(&mut c, 0x0102); + u16le(&mut c, 16); + u32le(&mut c, (36 + 20 * attrs.len()) as u32); + u32le(&mut c, line as u32 + 2); + u32le(&mut c, u32::MAX); + u32le(&mut c, u32::MAX); + u32le(&mut c, nidx); + u16le(&mut c, 20); + u16le(&mut c, 20); + u16le(&mut c, attrs.len() as u16); + u16le(&mut c, 0); + u16le(&mut c, 0); + u16le(&mut c, 0); + for at in attrs { + let an = intern(at.name, &mut strings); + let (raw, ty, data) = match at.val { + AxVal::Str(s) => { + let i = intern(s, &mut strings); + (i, 0x03u8, i) + } + AxVal::Bool(b) => (u32::MAX, 0x12, if b { u32::MAX } else { 0 }), + AxVal::Int(i) => (u32::MAX, 0x10, i as u32), + AxVal::Hex(h) => (u32::MAX, 0x11, h), + AxVal::Ref(r) => (u32::MAX, 0x01, r), + }; + u32le(&mut c, if at.res_id.is_some() { uri } else { u32::MAX }); + u32le(&mut c, an); + u32le(&mut c, raw); + u16le(&mut c, 8); + c.push(0); + c.push(ty); + u32le(&mut c, data); + } + body.extend(c); + } + AxNode::End(name) => { + let nidx = intern(name, &mut strings); + let mut c = Vec::new(); + u16le(&mut c, 0x0103); + u16le(&mut c, 16); + u32le(&mut c, 24); + u32le(&mut c, line as u32 + 2); + u32le(&mut c, u32::MAX); + u32le(&mut c, u32::MAX); + u32le(&mut c, nidx); + body.extend(c); + } + } + } + body.extend(ns_chunk(0x0101)); + let refs: Vec<&str> = strings.iter().map(String::as_str).collect(); + let pool = string_pool(&refs, false); + let mut map = Vec::new(); + u16le(&mut map, 0x0180); + u16le(&mut map, 8); + u32le(&mut map, (8 + 4 * ids.len()) as u32); + for id in &ids { + u32le(&mut map, *id); + } + let mut out = Vec::new(); + u16le(&mut out, 0x0003); + u16le(&mut out, 8); + u32le(&mut out, (8 + pool.len() + map.len() + body.len()) as u32); + out.extend(pool); + out.extend(map); + out.extend(body); + out +} + +/// The Notes app's `AndroidManifest.xml`. +pub fn manifest_axml() -> Vec { + use AxNode::{End, Start}; + use AxVal::*; + let name = |v| a("name", 0x0101_0003, Str(v)); + axml(&[ + Start( + "manifest", + vec![ + AxAttr { name: "package", res_id: None, val: Str(PACKAGE) }, + a("versionCode", 0x0101_021b, Int(42)), + a("versionName", 0x0101_021c, Str("1.2.3")), + ], + ), + Start("uses-sdk", vec![a("minSdkVersion", 0x0101_020c, Int(24)), a("targetSdkVersion", 0x0101_0270, Int(34))]), + End("uses-sdk"), + Start("uses-permission", vec![name("android.permission.INTERNET")]), + End("uses-permission"), + Start("uses-permission", vec![name("android.permission.CAMERA")]), + End("uses-permission"), + Start("permission", vec![name("com.example.notes.permission.SYNC"), a("protectionLevel", 0x0101_0009, Hex(2))]), + End("permission"), + Start( + "application", + vec![ + name(".NotesApp"), + a("label", 0x0101_0001, Ref(0x7f01_0000)), + a("debuggable", 0x0101_000f, Bool(true)), + a("allowBackup", 0x0101_0280, Bool(false)), + ], + ), + Start("activity", vec![name(".MainActivity"), a("exported", 0x0101_0010, Bool(true))]), + Start("intent-filter", vec![]), + Start("action", vec![name("android.intent.action.MAIN")]), + End("action"), + Start("category", vec![name("android.intent.category.LAUNCHER")]), + End("category"), + Start("data", vec![a("scheme", 0x0101_0027, Str("notes")), a("host", 0x0101_0028, Str("open"))]), + End("data"), + End("intent-filter"), + End("activity"), + Start("service", vec![name(".SyncService"), a("exported", 0x0101_0010, Bool(false))]), + End("service"), + Start( + "provider", + vec![ + name("androidx.core.content.FileProvider"), + a("authorities", 0x0101_0018, Str("com.example.notes.files")), + a("exported", 0x0101_0010, Bool(false)), + ], + ), + End("provider"), + End("application"), + End("manifest"), + ]) +} + +fn config(lang: &[u8; 2], density: u16, ui_mode: u8, sdk: u16) -> Vec { + let mut c = vec![0u8; 64]; + c[0] = 64; + if lang != b"\0\0" { + c[8..10].copy_from_slice(lang); + } + c[14..16].copy_from_slice(&density.to_le_bytes()); + c[24..26].copy_from_slice(&sdk.to_le_bytes()); + c[29] = ui_mode; + c +} + +fn type_spec(id: u8, entries: u32) -> Vec { + let mut c = Vec::new(); + u16le(&mut c, 0x0202); + u16le(&mut c, 16); + u32le(&mut c, 16 + 4 * entries); + c.push(id); + c.push(0); + u16le(&mut c, 0); + u32le(&mut c, entries); + for _ in 0..entries { + u32le(&mut c, 0); + } + c +} + +/// A type chunk from already-encoded entries. +fn type_chunk(id: u8, cfg: &[u8], entries: &[Vec]) -> Vec { + let header = 20 + cfg.len(); + let start = header + 4 * entries.len(); + let mut offs = Vec::new(); + let mut body = Vec::new(); + for e in entries { + offs.push(body.len() as u32); + body.extend_from_slice(e); + } + let mut c = Vec::new(); + u16le(&mut c, 0x0201); + u16le(&mut c, header as u16); + u32le(&mut c, (start + body.len()) as u32); + c.push(id); + c.push(0); + u16le(&mut c, 0); + u32le(&mut c, entries.len() as u32); + u32le(&mut c, start as u32); + c.extend_from_slice(cfg); + for o in offs { + u32le(&mut c, o); + } + c.extend(body); + c +} + +fn simple_entry(key: u32, ty: u8, data: u32) -> Vec { + let mut e = Vec::new(); + u16le(&mut e, 8); + u16le(&mut e, 0); + u32le(&mut e, key); + u16le(&mut e, 8); + e.push(0); + e.push(ty); + u32le(&mut e, data); + e +} + +/// `resources.arsc`: `string/app_name` and `string/greeting` in the default locale and French, +/// and one `style/AppTheme` bag (night, xhdpi, v21) with a parent and a colour item. +pub fn resources_arsc() -> Vec { + let global = string_pool(&["Notes", "Hello", "Notes FR", "Bonjour"], true); + let types = string_pool(&["string", "style"], false); + let keys = string_pool(&["app_name", "greeting", "AppTheme"], false); + let mut bag = Vec::new(); + u16le(&mut bag, 16); + u16le(&mut bag, 1); + u32le(&mut bag, 2); + u32le(&mut bag, 0x0103_0005); + u32le(&mut bag, 1); + u32le(&mut bag, 0x7f03_0000); + u16le(&mut bag, 8); + bag.push(0); + bag.push(0x1c); + u32le(&mut bag, 0xff33_6699); + let mut chunks = Vec::new(); + chunks.extend(type_spec(1, 2)); + chunks.extend(type_chunk(1, &config(b"\0\0", 0, 0, 0), &[simple_entry(0, 3, 0), simple_entry(1, 3, 1)])); + chunks.extend(type_chunk(1, &config(b"fr", 0, 0, 0), &[simple_entry(0, 3, 2), simple_entry(1, 3, 3)])); + chunks.extend(type_spec(2, 1)); + chunks.extend(type_chunk(2, &config(b"\0\0", 320, 0x20, 21), &[bag])); + let header = 288usize; + let mut pkg = Vec::new(); + u16le(&mut pkg, 0x0200); + u16le(&mut pkg, header as u16); + u32le(&mut pkg, (header + types.len() + keys.len() + chunks.len()) as u32); + u32le(&mut pkg, 0x7f); + let mut name = [0u16; 128]; + for (i, u) in PACKAGE.encode_utf16().enumerate() { + name[i] = u; + } + for u in name { + u16le(&mut pkg, u); + } + u32le(&mut pkg, header as u32); + u32le(&mut pkg, 2); + u32le(&mut pkg, (header + types.len()) as u32); + u32le(&mut pkg, 3); + u32le(&mut pkg, 0); + pkg.extend(types); + pkg.extend(keys); + pkg.extend(chunks); + let mut out = Vec::new(); + u16le(&mut out, 0x0002); + u16le(&mut out, 12); + u32le(&mut out, (12 + global.len() + pkg.len()) as u32); + u32le(&mut out, 1); + out.extend(global); + out.extend(pkg); + out +} diff --git a/crates/android-res/src/lib.rs b/crates/android-res/src/lib.rs new file mode 100644 index 0000000000..656f6dbf13 --- /dev/null +++ b/crates/android-res/src/lib.rs @@ -0,0 +1,17 @@ +//! Bounded readers for compiled Android XML and resource tables. +pub mod arsc; +pub mod axml; +mod bytes; +#[cfg(test)] +mod fixtures; + +/// Failure to decode the Android wire format. +#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)] +pub enum Error { + /// A required record did not fit within the available bytes. + #[error("truncated: {0}")] + Truncated(String), + /// The available bytes do not form the required structure. + #[error("malformed: {0}")] + Malformed(String), +}