diff --git a/ATTRIBUTION.md b/ATTRIBUTION.md index 4c86afd61..cbf153813 100644 --- a/ATTRIBUTION.md +++ b/ATTRIBUTION.md @@ -132,3 +132,7 @@ Sanitization, animation fitting and numeric output policy remain caller-owned. ## JSONC span-preserving editing `crates/jsonc` is extracted from Craft Anything `crates/formats/src/jsonc.rs` at `e5c9c94106747ed44b9a3fb0decce867c2285f93` (MIT OR Apache-2.0). The original implementation and hardening by BFlat, newline preservation by NetterSilver, and subsequent RRFZ/Afloat correctness fixes retain separate primary-author port commits with immutable source revisions. Shared API wiring and optional input-byte admission are subsequent changes. Compatibility parsing and all existing formatting/editing tests are retained; application file I/O and policy are not imported. + +## Dalvik DEX inspection + +`crates/dex` extracts Craft Anything `crates/formats/src/dex.rs` and `dex_ops.rs` at `5979f9b13f16dcf1df3c7ae7f8e7735f452866f2` (MIT OR Apache-2.0). Five source-history ports preserve Brandon Thomas, BFlat and Afloat as primary authors. Five regression imports retain BFlat/Afloat authors and exact source revisions. The checked byte-reader/MUTF-8 subset and synthetic DEX fixture come from that app's `bytes.rs` and `testkit/src/android.rs`; deterministic noise/mutations come from its testkit. No application file I/O, APK logic or execution is imported. Shared neutral errors and workspace wiring are subsequent changes; existing per-file strings, member/handler and bytecode payload budgets are retained. diff --git a/Cargo.lock b/Cargo.lock index 9fa1f4401..720433ee7 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1722,6 +1722,14 @@ dependencies = [ "thiserror 2.0.21", ] +[[package]] +name = "craft-dex" +version = "0.1.0" +dependencies = [ + "serde", + "thiserror 2.0.21", +] + [[package]] name = "craft-dialogs" version = "0.1.0" diff --git a/Cargo.toml b/Cargo.toml index 50ec3c917..803e433de 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -11,6 +11,7 @@ rust-version = "1.95" repository = "https://github.com/storytold/craft-libs" [workspace.dependencies] +craft-dex = { path = "crates/dex" } craft-jsonc = { path = "crates/jsonc" } craft-palette = { path = "crates/palette" } craft-score = { path = "crates/score" } diff --git a/crates/dex/Cargo.toml b/crates/dex/Cargo.toml new file mode 100644 index 000000000..e4eb285f5 --- /dev/null +++ b/crates/dex/Cargo.toml @@ -0,0 +1,13 @@ +[package] +name="craft-dex" +description="Dalvik DEX reader and bytecode decoder with retained input bounds and partial-report semantics" +version.workspace=true +edition.workspace=true +license.workspace=true +rust-version.workspace=true +repository.workspace=true +[lints] +workspace=true +[dependencies] +serde={workspace=true} +thiserror={workspace=true} diff --git a/crates/dex/src/bytes.rs b/crates/dex/src/bytes.rs new file mode 100644 index 000000000..555505a2d --- /dev/null +++ b/crates/dex/src/bytes.rs @@ -0,0 +1,81 @@ +//! Checked little/big-endian reads over untrusted bytes. Every read returns `None` when out of range. + +#[derive(Debug, Clone, Copy)] +pub struct Reader<'a> { + data: &'a [u8], +} + +impl<'a> Reader<'a> { + pub fn new(data: &'a [u8]) -> Self { + Reader { data } + } + + pub fn len(&self) -> usize { + self.data.len() + } + + pub fn data(&self) -> &'a [u8] { + self.data + } + + pub fn slice(&self, off: usize, len: usize) -> Option<&'a [u8]> { + let end = off.checked_add(len)?; + self.data.get(off..end) + } + + pub fn u8(&self, off: usize) -> Option { + self.data.get(off).copied() + } + + fn arr(&self, off: usize) -> Option<[u8; N]> { + self.slice(off, N)?.try_into().ok() + } + + pub fn u16_le(&self, off: usize) -> Option { + self.arr(off).map(u16::from_le_bytes) + } + + pub fn u32_le(&self, off: usize) -> Option { + self.arr(off).map(u32::from_le_bytes) + } + + /// A NUL-terminated string starting at `off`, at most `max` bytes, lossily decoded. + pub fn cstr(&self, off: usize, max: usize) -> Option { + let rest = self.data.get(off..)?; + let rest = rest.get(..max.min(rest.len()))?; + let end = rest.iter().position(|&b| b == 0).unwrap_or(rest.len()); + Some(String::from_utf8_lossy(rest.get(..end)?).into_owned()) + } + + /// Unsigned LEB128 at `off`: (value, bytes consumed). At most 10 bytes. + pub fn uleb128(&self, off: usize) -> Option<(u64, usize)> { + let mut result = 0u64; + for i in 0..10usize { + let b = self.u8(off.checked_add(i)?)?; + let payload = u64::from(b & 0x7f); + let shift = 7 * i as u32; + if shift > 0 && payload.checked_shl(shift)? >> shift != payload { + return None; + } + result |= payload << shift; + if b & 0x80 == 0 { + return Some((result, i + 1)); + } + } + None + } +} + +/// Decode one modified UTF-8 code unit. Invalid bytes consume only themselves, +/// so a damaged sequence cannot hide valid text or borrow missing bytes. +pub(crate) fn mutf8_unit(bytes: &[u8]) -> (u16, usize) { + match bytes { + [a @ 0x00..=0x7f, ..] => (u16::from(*a), 1), + [0xc0, 0x80, ..] => (0, 2), + [a @ 0xc2..=0xdf, b @ 0x80..=0xbf, ..] => ((u16::from(*a & 0x1f) << 6) | u16::from(*b & 0x3f), 2), + [a @ 0xe0..=0xef, b @ 0x80..=0xbf, c @ 0x80..=0xbf, ..] if *a != 0xe0 || *b >= 0xa0 => { + ((u16::from(*a & 0x0f) << 12) | (u16::from(*b & 0x3f) << 6) | u16::from(*c & 0x3f), 3) + } + _ => (0xfffd, 1), + } +} diff --git a/crates/dex/src/dex.rs b/crates/dex/src/dex.rs index c4076dfc8..e578dc397 100644 --- a/crates/dex/src/dex.rs +++ b/crates/dex/src/dex.rs @@ -348,8 +348,11 @@ pub fn parse(data: &[u8]) -> Result, FormatError> { ProtoId { shorty: r.u32_le(o).unwrap_or(0), ret: r.u32_le(o + 4).unwrap_or(NO_INDEX), params_off: r.u32_le(o + 8).unwrap_or(0) } }) .collect(); - let member = - |o: usize| MemberId { class_idx: r.u16_le(o).unwrap_or(0), type_or_proto: r.u16_le(o + 2).unwrap_or(0), name_idx: r.u32_le(o + 4).unwrap_or(NO_INDEX) }; + let member = |o: usize| MemberId { + class_idx: r.u16_le(o).unwrap_or(0), + type_or_proto: r.u16_le(o + 2).unwrap_or(0), + name_idx: r.u32_le(o + 4).unwrap_or(NO_INDEX), + }; let fields = (0..nf).map(|i| member(fo + i * 8)).collect(); let methods = (0..nm).map(|i| member(mo + i * 8)).collect(); let classes = (0..nc) @@ -423,7 +426,9 @@ impl<'a> Dex<'a> { /// `Lcls;->name:Ltype;` pub fn field_ref(&self, i: u32) -> String { match self.fields.get(i as usize) { - Some(f) => format!("{}->{}:{}", self.type_desc(u32::from(f.class_idx)), self.string(f.name_idx), self.type_desc(u32::from(f.type_or_proto))), + Some(f) => { + format!("{}->{}:{}", self.type_desc(u32::from(f.class_idx)), self.string(f.name_idx), self.type_desc(u32::from(f.type_or_proto))) + } None => format!(""), } } @@ -431,7 +436,9 @@ impl<'a> Dex<'a> { /// `Lcls;->name(…)R` pub fn method_ref(&self, i: u32) -> String { match self.methods.get(i as usize) { - Some(m) => format!("{}->{}{}", self.type_desc(u32::from(m.class_idx)), self.string(m.name_idx), self.proto_desc(u32::from(m.type_or_proto))), + Some(m) => { + format!("{}->{}{}", self.type_desc(u32::from(m.class_idx)), self.string(m.name_idx), self.proto_desc(u32::from(m.type_or_proto))) + } None => format!(""), } } @@ -683,9 +690,10 @@ pub fn references(dex: &Dex<'_>, desc: &str, method: Option<&str>, max: usize) - let cls = dex.type_desc(u32::from(id.class_idx)); (cls == desc && method.is_none_or(|n| dex.string(id.name_idx) == n)).then(|| ("method", dex.method_ref(idx))) }), - IndexKind::Field if method.is_none() => { - dex.fields.get(idx as usize).and_then(|id| (dex.type_desc(u32::from(id.class_idx)) == desc).then(|| ("field", dex.field_ref(idx)))) - } + IndexKind::Field if method.is_none() => dex + .fields + .get(idx as usize) + .and_then(|id| (dex.type_desc(u32::from(id.class_idx)) == desc).then(|| ("field", dex.field_ref(idx)))), IndexKind::Type if method.is_none() => { let t = dex.type_desc(idx); (t.trim_start_matches('[') == desc).then_some(("type", t)) @@ -707,7 +715,7 @@ pub fn references(dex: &Dex<'_>, desc: &str, method: Option<&str>, max: usize) - #[cfg(test)] mod tests { use super::*; - use craft_anything_testkit::android as fx; + use crate::test_support::android as fx; #[test] fn parses_fixture() { @@ -785,7 +793,7 @@ mod tests { } let _ = references(d, "Lcom/example/notes/Util;", None, 100); }; - for m in craft_anything_testkit::mutations(&data) { + for m in crate::test_support::mutations(&data) { if let Ok(d) = parse(&m) { walk(&d); } @@ -796,7 +804,7 @@ mod tests { } } for seed in 0..64 { - let mut n = craft_anything_testkit::noise(seed, 2048); + let mut n = crate::test_support::noise(seed, 2048); n[..8].copy_from_slice(b"dex\n035\0"); n[40..44].copy_from_slice(&0x1234_5678u32.to_le_bytes()); if let Ok(d) = parse(&n) { diff --git a/crates/dex/src/dex_ops.rs b/crates/dex/src/dex_ops.rs index 71095fc75..3c27d4c5c 100644 --- a/crates/dex/src/dex_ops.rs +++ b/crates/dex/src/dex_ops.rs @@ -170,7 +170,8 @@ const BINOPS_2ADDR: [&str; 32] = [ "rem-double/2addr", ]; -const LIT16: [&str; 8] = ["add-int/lit16", "rsub-int", "mul-int/lit16", "div-int/lit16", "rem-int/lit16", "and-int/lit16", "or-int/lit16", "xor-int/lit16"]; +const LIT16: [&str; 8] = + ["add-int/lit16", "rsub-int", "mul-int/lit16", "div-int/lit16", "rem-int/lit16", "and-int/lit16", "or-int/lit16", "xor-int/lit16"]; const LIT8: [&str; 11] = [ "add-int/lit8", "rsub-int/lit8", @@ -236,7 +237,8 @@ const SFIELD: [&str; 14] = [ "sput-short", ]; const INVOKE: [&str; 5] = ["invoke-virtual", "invoke-super", "invoke-direct", "invoke-static", "invoke-interface"]; -const INVOKE_RANGE: [&str; 5] = ["invoke-virtual/range", "invoke-super/range", "invoke-direct/range", "invoke-static/range", "invoke-interface/range"]; +const INVOKE_RANGE: [&str; 5] = + ["invoke-virtual/range", "invoke-super/range", "invoke-direct/range", "invoke-static/range", "invoke-interface/range"]; fn pick(list: &[&'static str], i: u8, base: u8) -> &'static str { list.get(usize::from(i.wrapping_sub(base))).copied().unwrap_or("unused") @@ -683,7 +685,7 @@ mod tests { #[test] fn hostile() { for seed in 0..200 { - let n = craft_anything_testkit::noise(seed, 256); + let n = crate::test_support::noise(seed, 256); let code: Vec = n.as_chunks::<2>().0.iter().map(|c| u16::from_le_bytes(*c)).collect(); let _ = decode(&code, 1000); } diff --git a/crates/dex/src/lib.rs b/crates/dex/src/lib.rs new file mode 100644 index 000000000..97d28b7f4 --- /dev/null +++ b/crates/dex/src/lib.rs @@ -0,0 +1,42 @@ +#![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)] +#![forbid(unsafe_code)] +//! Dalvik DEX inspection and bytecode decoding. Never executes bytecode. +mod bytes; +/// Checked byte reader accepted by the signed-LEB compatibility helper. +pub use bytes::Reader; +pub mod dex; +pub mod dex_ops; +pub use dex::*; +#[cfg(test)] +mod test_support; +/// Parser admission failures; damaged substructures retain the original partial-report behavior. +#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)] +pub enum DexError { + #[error("the file ends early ({0})")] + Truncated(String), + #[error("the file is malformed ({0})")] + Malformed(String), + #[error("not supported: {0}")] + Unsupported(String), +} +use DexError as FormatError; + +#[cfg(test)] +#[path = "regressions/array_widths.rs"] +mod array_widths; + +#[cfg(test)] +#[path = "regressions/capped_table_boundaries.rs"] +mod capped_table_boundaries; + +#[cfg(test)] +#[path = "regressions/invoke_registers.rs"] +mod invoke_registers; + +#[cfg(test)] +#[path = "regressions/payload_budgets.rs"] +mod payload_budgets; + +#[cfg(test)] +#[path = "regressions/signed_leb128.rs"] +mod signed_leb128; diff --git a/crates/dex/src/test_support.rs b/crates/dex/src/test_support.rs new file mode 100644 index 000000000..a3a179145 --- /dev/null +++ b/crates/dex/src/test_support.rs @@ -0,0 +1,471 @@ +// Synthetic DEX fixture and deterministic mutations retained from Craft Anything. +/// Deterministic pseudo-random bytes (xorshift) for fuzz-like loops. +pub fn noise(seed: u64, len: usize) -> Vec { + let mut x = seed.wrapping_mul(0x9e37_79b9_7f4a_7c15) | 1; + (0..len) + .map(|_| { + x ^= x << 13; + x ^= x >> 7; + x ^= x << 17; + x as u8 + }) + .collect() +} + +/// Every way to damage a sample used by robustness tests: truncations at many lengths and +/// single-byte corruptions spread across the file. +pub fn mutations(sample: &[u8]) -> Vec> { + let mut out = Vec::new(); + let n = sample.len(); + let step = (n / 64).max(1); + let mut len = 0; + while len < n { + out.push(sample[..len].to_vec()); + len += step; + } + for (i, seed) in (0..n).step_by(step).zip(1u64..) { + let mut m = sample.to_vec(); + let noise = noise(seed, 8); + for (j, v) in noise.iter().enumerate() { + if let Some(b) = m.get_mut(i + j) { + *b = *v; + } + } + out.push(m); + let mut m = sample.to_vec(); + if let Some(b) = m.get_mut(i) { + *b = 0xff; + } + out.push(m); + } + out +} + +pub mod android { + pub const HELLO: &str = "Hello, Craft!"; + fn u16le(v: &mut Vec, x: u16) { + v.extend_from_slice(&x.to_le_bytes()); + } + fn u32le(v: &mut Vec, x: u32) { + v.extend_from_slice(&x.to_le_bytes()); + } + fn uleb(v: &mut Vec, mut x: u32) { + loop { + let b = (x & 0x7f) as u8; + x >>= 7; + if x == 0 { + v.push(b); + break; + } + v.push(b | 0x80); + } + } + fn sleb(v: &mut Vec, mut x: i32) { + loop { + let b = (x & 0x7f) as u8; + x >>= 7; + let done = (x == 0 && b & 0x40 == 0) || (x == -1 && b & 0x40 != 0); + v.push(if done { b } else { b | 0x80 }); + if done { + break; + } + } + } + fn align4(v: &mut Vec) { + while !v.len().is_multiple_of(4) { + v.push(0); + } + } + + #[derive(Debug, Clone, Default)] + pub struct TrySpec { + pub start: u32, + pub count: u16, + /// (type idx, handler address) + pub handlers: Vec<(u32, u32)>, + pub catch_all: Option, + } + + #[derive(Debug, Clone, Default)] + pub struct CodeSpec { + pub registers: u16, + pub ins: u16, + pub outs: u16, + pub insns: Vec, + pub tries: Vec, + } + + #[derive(Debug, Clone)] + pub struct MethodSpec { + pub method: u32, + pub access: u32, + pub code: Option, + } + + #[derive(Debug, Clone, Default)] + pub struct ClassSpec { + pub class: u32, + pub access: u32, + pub superclass: u32, + pub interfaces: Vec, + pub source_file: u32, + pub annotations: Vec, + pub static_fields: Vec<(u32, u32)>, + pub instance_fields: Vec<(u32, u32)>, + pub direct: Vec, + pub virtuals: Vec, + } + + #[derive(Debug, Clone, Default)] + pub struct DexBuilder { + strings: Vec, + types: Vec, + protos: Vec<(u32, u32, Vec)>, + fields: Vec<(u32, u32, u32)>, + methods: Vec<(u32, u32, u32)>, + pub classes: Vec, + } + + impl DexBuilder { + pub fn string(&mut self, s: &str) -> u32 { + if let Some(i) = self.strings.iter().position(|x| x == s) { + return i as u32; + } + self.strings.push(s.to_string()); + (self.strings.len() - 1) as u32 + } + + pub fn ty(&mut self, desc: &str) -> u32 { + let s = self.string(desc); + if let Some(i) = self.types.iter().position(|&x| x == s) { + return i as u32; + } + self.types.push(s); + (self.types.len() - 1) as u32 + } + + pub fn proto(&mut self, ret: &str, params: &[&str]) -> u32 { + let short = |d: &str| if d.starts_with('L') || d.starts_with('[') { 'L' } else { d.chars().next().unwrap() }; + let shorty: String = std::iter::once(short(ret)).chain(params.iter().map(|p| short(p))).collect(); + let s = self.string(&shorty); + let r = self.ty(ret); + let ps: Vec = params.iter().map(|p| self.ty(p)).collect(); + if let Some(i) = self.protos.iter().position(|p| p.1 == r && p.2 == ps) { + return i as u32; + } + self.protos.push((s, r, ps)); + (self.protos.len() - 1) as u32 + } + + pub fn field(&mut self, cls: &str, ty: &str, name: &str) -> u32 { + let c = self.ty(cls); + let t = self.ty(ty); + let n = self.string(name); + if let Some(i) = self.fields.iter().position(|&f| f == (c, t, n)) { + return i as u32; + } + self.fields.push((c, t, n)); + (self.fields.len() - 1) as u32 + } + + pub fn method(&mut self, cls: &str, name: &str, ret: &str, params: &[&str]) -> u32 { + let c = self.ty(cls); + let p = self.proto(ret, params); + let n = self.string(name); + if let Some(i) = self.methods.iter().position(|&m| m == (c, p, n)) { + return i as u32; + } + self.methods.push((c, p, n)); + (self.methods.len() - 1) as u32 + } + + pub fn build(self) -> Vec { + let ns = self.strings.len(); + let nt = self.types.len(); + let np = self.protos.len(); + let nf = self.fields.len(); + let nm = self.methods.len(); + let nc = self.classes.len(); + let string_ids = 0x70; + let type_ids = string_ids + ns * 4; + let proto_ids = type_ids + nt * 4; + let field_ids = proto_ids + np * 12; + let method_ids = field_ids + nf * 8; + let class_defs = method_ids + nm * 8; + let mut data_start = class_defs + nc * 32; + data_start = (data_start + 3) & !3; + let mut d: Vec = Vec::new(); + let at = |d: &Vec| (data_start + d.len()) as u32; + // type lists + let tl = |d: &mut Vec, list: &[u32]| -> u32 { + if list.is_empty() { + return 0; + } + align4(d); + let o = at(d); + u32le(d, list.len() as u32); + for &t in list { + u16le(d, t as u16); + } + o + }; + let proto_params: Vec = self.protos.iter().map(|p| tl(&mut d, &p.2)).collect(); + let class_ifaces: Vec = self.classes.iter().map(|c| tl(&mut d, &c.interfaces)).collect(); + // string data + let mut string_offs = Vec::new(); + for s in &self.strings { + string_offs.push(at(&d)); + uleb(&mut d, s.encode_utf16().count() as u32); + for ch in s.chars() { + let c = ch as u32; + if c == 0 { + d.extend_from_slice(&[0xc0, 0x80]); + } else if c < 0x80 { + d.push(c as u8); + } else if c < 0x800 { + d.extend_from_slice(&[0xc0 | (c >> 6) as u8, 0x80 | (c & 0x3f) as u8]); + } else { + d.extend_from_slice(&[0xe0 | (c >> 12) as u8, 0x80 | ((c >> 6) & 0x3f) as u8, 0x80 | (c & 0x3f) as u8]); + } + } + d.push(0); + } + // code items, class data, annotations + let mut class_data_offs = Vec::new(); + let mut annot_offs = Vec::new(); + for c in &self.classes { + let code_off = |d: &mut Vec, m: &MethodSpec| -> u32 { + let Some(code) = &m.code else { return 0 }; + align4(d); + let o = at(d); + u16le(d, code.registers); + u16le(d, code.ins); + u16le(d, code.outs); + u16le(d, code.tries.len() as u16); + u32le(d, 0); + u32le(d, code.insns.len() as u32); + for &i in &code.insns { + u16le(d, i); + } + if !code.tries.is_empty() { + if code.insns.len() % 2 == 1 { + u16le(d, 0); + } + let mut list = Vec::new(); + uleb(&mut list, code.tries.len() as u32); + let mut offs = Vec::new(); + for t in &code.tries { + offs.push(list.len() as u16); + let n = t.handlers.len() as i32; + sleb(&mut list, if t.catch_all.is_some() { -n } else { n }); + for &(ty, addr) in &t.handlers { + uleb(&mut list, ty); + uleb(&mut list, addr); + } + if let Some(a) = t.catch_all { + uleb(&mut list, a); + } + } + for (t, off) in code.tries.iter().zip(offs) { + u32le(d, t.start); + u16le(d, t.count); + u16le(d, off); + } + d.extend_from_slice(&list); + } + o + }; + let mut direct = c.direct.clone(); + direct.sort_by_key(|m| m.method); + let mut virtuals = c.virtuals.clone(); + virtuals.sort_by_key(|m| m.method); + let direct_offs: Vec = direct.iter().map(|m| code_off(&mut d, m)).collect(); + let virtual_offs: Vec = virtuals.iter().map(|m| code_off(&mut d, m)).collect(); + let cd = at(&d); + let mut sf = c.static_fields.clone(); + sf.sort(); + let mut inf = c.instance_fields.clone(); + inf.sort(); + uleb(&mut d, sf.len() as u32); + uleb(&mut d, inf.len() as u32); + uleb(&mut d, direct.len() as u32); + uleb(&mut d, virtuals.len() as u32); + for list in [&sf, &inf] { + let mut prev = 0; + for &(f, a) in list.iter() { + uleb(&mut d, f - prev); + uleb(&mut d, a); + prev = f; + } + } + for (list, offs) in [(&direct, &direct_offs), (&virtuals, &virtual_offs)] { + let mut prev = 0; + for (m, &o) in list.iter().zip(offs.iter()) { + uleb(&mut d, m.method - prev); + uleb(&mut d, m.access); + uleb(&mut d, o); + prev = m.method; + } + } + class_data_offs.push(cd); + if c.annotations.is_empty() { + annot_offs.push(0); + } else { + let mut items = Vec::new(); + for &t in &c.annotations { + items.push(at(&d)); + d.push(1); // runtime visibility + uleb(&mut d, t); + uleb(&mut d, 0); + } + align4(&mut d); + let set_off = at(&d); + u32le(&mut d, items.len() as u32); + for i in items { + u32le(&mut d, i); + } + let dir = at(&d); + u32le(&mut d, set_off); + u32le(&mut d, 0); + u32le(&mut d, 0); + u32le(&mut d, 0); + annot_offs.push(dir); + } + } + align4(&mut d); + let file_size = data_start + d.len(); + let mut out = vec![0u8; data_start]; + out[..8].copy_from_slice(b"dex\n035\0"); + let put = |out: &mut Vec, off: usize, v: u32| out[off..off + 4].copy_from_slice(&v.to_le_bytes()); + put(&mut out, 32, file_size as u32); + put(&mut out, 36, 0x70); + put(&mut out, 40, 0x1234_5678); + for (i, (n, o)) in + [(ns, string_ids), (nt, type_ids), (np, proto_ids), (nf, field_ids), (nm, method_ids), (nc, class_defs)].iter().enumerate() + { + put(&mut out, 56 + i * 8, *n as u32); + put(&mut out, 60 + i * 8, if *n == 0 { 0 } else { *o as u32 }); + } + put(&mut out, 104, d.len() as u32); + put(&mut out, 108, data_start as u32); + for (i, o) in string_offs.iter().enumerate() { + put(&mut out, string_ids + i * 4, *o); + } + for (i, t) in self.types.iter().enumerate() { + put(&mut out, type_ids + i * 4, *t); + } + for (i, p) in self.protos.iter().enumerate() { + put(&mut out, proto_ids + i * 12, p.0); + put(&mut out, proto_ids + i * 12 + 4, p.1); + put(&mut out, proto_ids + i * 12 + 8, proto_params[i]); + } + for (i, (c, t, n)) in self.fields.iter().enumerate() { + out[field_ids + i * 8..field_ids + i * 8 + 2].copy_from_slice(&(*c as u16).to_le_bytes()); + out[field_ids + i * 8 + 2..field_ids + i * 8 + 4].copy_from_slice(&(*t as u16).to_le_bytes()); + put(&mut out, field_ids + i * 8 + 4, *n); + } + for (i, (c, p, n)) in self.methods.iter().enumerate() { + out[method_ids + i * 8..method_ids + i * 8 + 2].copy_from_slice(&(*c as u16).to_le_bytes()); + out[method_ids + i * 8 + 2..method_ids + i * 8 + 4].copy_from_slice(&(*p as u16).to_le_bytes()); + put(&mut out, method_ids + i * 8 + 4, *n); + } + for (i, c) in self.classes.iter().enumerate() { + let o = class_defs + i * 32; + for (k, v) in + [c.class, c.access, c.superclass, class_ifaces[i], c.source_file, annot_offs[i], class_data_offs[i], 0].iter().enumerate() + { + put(&mut out, o + k * 4, *v); + } + } + out.extend_from_slice(&d); + let sum = adler32(&out[12..]); + put(&mut out, 8, sum); + out + } + } + + fn adler32(data: &[u8]) -> u32 { + let (mut a, mut b) = (1u32, 0u32); + for &x in data { + a = (a + u32::from(x)) % 65521; + b = (b + a) % 65521; + } + (b << 16) | a + } + + const MAIN: &str = "Lcom/example/notes/MainActivity;"; + const UTIL: &str = "Lcom/example/notes/Util;"; + const STRING: &str = "Ljava/lang/String;"; + + /// `classes.dex` of the Notes app: `MainActivity` (constructor, `onCreate`, `run`, `pick` with a + /// packed switch inside a try/catch) and `Util` (two `log` overloads printing through + /// `System.out`). + pub fn notes_dex() -> Vec { + let mut b = DexBuilder::default(); + let activity = b.ty("Landroid/app/Activity;"); + let main = b.ty(MAIN); + let runnable = b.ty("Ljava/lang/Runnable;"); + let deprecated = b.ty("Ljava/lang/Deprecated;"); + let rte = b.ty("Ljava/lang/RuntimeException;"); + let object = b.ty("Ljava/lang/Object;"); + let util = b.ty(UTIL); + let tag = b.field(MAIN, STRING, "TAG"); + let count = b.field(MAIN, "I", "count"); + let out = b.field("Ljava/lang/System;", "Ljava/io/PrintStream;", "out"); + let super_init = b.method("Landroid/app/Activity;", "", "V", &[]); + let super_create = b.method("Landroid/app/Activity;", "onCreate", "V", &["Landroid/os/Bundle;"]); + let init = b.method(MAIN, "", "V", &[]); + let on_create = b.method(MAIN, "onCreate", "V", &["Landroid/os/Bundle;"]); + let run = b.method(MAIN, "run", "V", &[]); + let pick = b.method(MAIN, "pick", "I", &["I"]); + let log_s = b.method(UTIL, "log", "V", &[STRING]); + let log_i = b.method(UTIL, "log", "V", &["I"]); + let println = b.method("Ljava/io/PrintStream;", "println", "V", &[STRING]); + let hello = b.string(HELLO); + let main_src = b.string("MainActivity.java"); + let util_src = b.string("Util.java"); + let code = |registers, ins, outs, insns: Vec| Some(CodeSpec { registers, ins, outs, insns, tries: vec![] }); + b.classes.push(ClassSpec { + class: main, + access: 0x1, + superclass: activity, + interfaces: vec![runnable], + source_file: main_src, + annotations: vec![deprecated], + static_fields: vec![(tag, 0x1a)], + instance_fields: vec![(count, 0x2)], + direct: vec![MethodSpec { method: init, access: 0x10001, code: code(1, 1, 1, vec![0x1070, super_init as u16, 0x0000, 0x000e]) }], + virtuals: vec![ + MethodSpec { + method: on_create, + access: 0x1, + code: code(3, 2, 2, vec![0x001a, hello as u16, 0x1071, log_s as u16, 0x0000, 0x206f, super_create as u16, 0x0021, 0x000e]), + }, + MethodSpec { method: run, access: 0x1, code: code(1, 1, 1, vec![0x7012, 0x1071, log_i as u16, 0x0000, 0x000e]) }, + MethodSpec { + method: pick, + access: 0x1, + code: Some(CodeSpec { + registers: 3, + ins: 2, + outs: 0, + insns: vec![0x022b, 10, 0, 0x0012, 0x000f, 0x1012, 0x000f, 0x2012, 0x000f, 0x0000, 0x0100, 2, 1, 0, 5, 0, 7, 0], + tries: vec![TrySpec { start: 0, count: 3, handlers: vec![(rte, 3)], catch_all: Some(3) }], + }), + }, + ], + }); + b.classes.push(ClassSpec { + class: util, + access: 0x11, + superclass: object, + source_file: util_src, + direct: vec![ + MethodSpec { method: log_s, access: 0x9, code: code(2, 1, 2, vec![0x0062, out as u16, 0x206e, println as u16, 0x0010, 0x000e]) }, + MethodSpec { method: log_i, access: 0x9, code: code(1, 1, 0, vec![0x000e]) }, + ], + ..ClassSpec::default() + }); + b.build() + } +}