diff --git a/crates/java-class/src/java_class.rs b/crates/java-class/src/java_class.rs index 4b751ec3ee..47fd0ef67a 100644 --- a/crates/java-class/src/java_class.rs +++ b/crates/java-class/src/java_class.rs @@ -11,6 +11,7 @@ use crate::bytes::Reader; use crate::java_ops::{self, Insn}; use crate::{FormatError, descriptor as dex}; use serde::Serialize; +use std::collections::HashMap; /// Most constant-pool entries, fields, methods, attributes or interfaces we read from one file. const MAX_ITEMS: usize = 1 << 20; @@ -18,6 +19,9 @@ const MAX_ITEMS: usize = 1 << 20; const MAX_ATTRS: usize = 64 * 1024; /// Deepest annotation/element-value nesting we walk. const MAX_ANNO_DEPTH: usize = 32; +/// Most bytes of constant-pool text copied into one parsed class. Many entries can name the same +/// long `Utf8`; once the limit is reached, further names are kept as pool-index placeholders. +pub(crate) const MAX_COPIED_TEXT: usize = 64 << 20; /// One constant-pool entry. Index 0 and the slot after a `Long`/`Double` are `Unusable`. #[derive(Debug, Clone, PartialEq)] @@ -347,6 +351,76 @@ fn utf8_of(pool: &[Const], idx: u16) -> &str { } } +/// Copies constant-pool text into the parse result within `MAX_COPIED_TEXT` bytes in total. +pub(crate) struct Names<'p> { + pool: &'p [Const], + left: usize, + exhausted: bool, + /// The length of each text `keep` has built, by kind and pool index. + built: HashMap<(&'static str, u16), usize>, +} + +impl<'p> Names<'p> { + pub(crate) fn new(pool: &'p [Const]) -> Self { + Names { pool, left: MAX_COPIED_TEXT, exhausted: false, built: HashMap::new() } + } + + /// Charge `len` bytes; false once the budget cannot cover them. + fn admit(&mut self, len: usize) -> bool { + match self.left.checked_sub(len) { + Some(left) => { + self.left = left; + true + } + None => { + self.exhausted = true; + false + } + } + } + + /// `render(pool, idx)` when the budget covers it, otherwise the placeholder ``. + /// The length of each rendered text is kept by kind and index, so a text over the budget is + /// built at most once however many entries name it. + pub(crate) fn keep(&mut self, kind: &'static str, idx: u16, render: fn(&[Const], u16) -> String) -> String { + self.keep_as((kind, idx), kind, idx, render) + } + + /// Like `keep` for a loadable constant. Constants that copy the same Utf8 the same way share + /// one kept length, so many `String` entries over one long Utf8 build its text at most once + /// past the budget. + pub(crate) fn constant(&mut self, idx: u16, render: fn(&[Const], u16) -> String) -> String { + let key = const_text_key(self.pool, idx); + self.keep_as(key, "const", idx, render) + } + + fn keep_as(&mut self, key: (&'static str, u16), kind: &'static str, idx: u16, render: fn(&[Const], u16) -> String) -> String { + if let Some(&len) = self.built.get(&key) { + return if self.admit(len) { render(self.pool, idx) } else { format!("<{kind}#{idx}>") }; + } + let text = render(self.pool, idx); + self.built.insert(key, text.len()); + if self.admit(text.len()) { text } else { format!("<{kind}#{idx}>") } + } + + /// The Utf8 at `idx` (empty when it is not a Utf8), or `` once the budget is spent. + fn utf8(&mut self, idx: u16) -> String { + let text = utf8_of(self.pool, idx); + if self.admit(text.len()) { text.to_string() } else { format!("") } + } + + /// Like `class_name_at`, or `` once the budget is spent. + fn class(&mut self, idx: u16) -> String { + match self.pool.get(idx as usize) { + Some(Const::Class(name_idx)) => { + let text = utf8_of(self.pool, *name_idx); + if self.admit(text.len()) { text.to_string() } else { format!("") } + } + _ => format!(""), + } + } +} + /// Parse a class file. pub fn parse(data: &[u8]) -> Result { if !data.starts_with(&[0xca, 0xfe, 0xba, 0xbe]) { @@ -369,8 +443,9 @@ pub fn parse(data: &[u8]) -> Result { let access = c.u16().ok_or_else(|| FormatError::Truncated("access flags".into()))?; let this_idx = c.u16().ok_or_else(|| FormatError::Truncated("this_class".into()))?; let super_idx = c.u16().ok_or_else(|| FormatError::Truncated("super_class".into()))?; - let this_class = class_name_at(&pool, this_idx); - let super_class = if super_idx == 0 { None } else { Some(class_name_at(&pool, super_idx)) }; + let mut names = Names::new(&pool); + let this_class = names.class(this_idx); + let super_class = if super_idx == 0 { None } else { Some(names.class(super_idx)) }; // Interfaces let n_iface = c.u16().ok_or_else(|| FormatError::Truncated("interfaces count".into()))? as usize; let mut interfaces = Vec::new(); @@ -379,12 +454,12 @@ pub fn parse(data: &[u8]) -> Result { warnings.push("interface list ended early".into()); break; }; - interfaces.push(class_name_at(&pool, i)); + interfaces.push(names.class(i)); } // Fields - let fields = parse_members(&mut c, &pool, &mut warnings, "field")?; + let fields = parse_members(&mut c, &mut names, &mut warnings, "field")?; // Methods - let methods = parse_members(&mut c, &pool, &mut warnings, "method")?; + let methods = parse_members(&mut c, &mut names, &mut warnings, "method")?; // Class attributes let (attrs, complete) = read_attrs(&mut c, &pool); if !complete { @@ -399,24 +474,27 @@ pub fn parse(data: &[u8]) -> Result { match a.name { "SourceFile" => { if let Some(i) = Reader::new(a.info).u16_be(0) { - source_file = Some(utf8_of(&pool, i).to_string()); + source_file = Some(names.utf8(i)); } } "Signature" => { if let Some(i) = Reader::new(a.info).u16_be(0) { - signature = Some(utf8_of(&pool, i).to_string()); + signature = Some(names.utf8(i)); } } "BootstrapMethods" => match bootstrap_table(a.info) { Some(table) => bootstrap_methods = table, None => warnings.push("invalid BootstrapMethods table".into()), }, - "InnerClasses" => inner_classes = parse_inner_classes(a.info, &pool), - "RuntimeVisibleAnnotations" => annotations.extend(parse_annotation_types(a.info, &pool, "runtime")), - "RuntimeInvisibleAnnotations" => annotations.extend(parse_annotation_types(a.info, &pool, "class")), + "InnerClasses" => inner_classes = parse_inner_classes(a.info, &mut names), + "RuntimeVisibleAnnotations" => annotations.extend(parse_annotation_types(a.info, &mut names, "runtime")), + "RuntimeInvisibleAnnotations" => annotations.extend(parse_annotation_types(a.info, &mut names, "class")), _ => {} } } + if names.exhausted { + warnings.push(format!("names exceed {} MiB of copied text; later ones are shown as pool indices", MAX_COPIED_TEXT >> 20)); + } Ok(ClassFile { version, access, @@ -518,7 +596,8 @@ fn bootstrap_table(data: &[u8]) -> Option)>> { (cursor.pos == data.len()).then_some(table) } -fn parse_members(c: &mut Cursor<'_>, pool: &[Const], warnings: &mut Vec, what: &str) -> Result, FormatError> { +fn parse_members(c: &mut Cursor<'_>, names: &mut Names<'_>, warnings: &mut Vec, what: &str) -> Result, FormatError> { + let pool = names.pool; let n = c.u16().ok_or_else(|| FormatError::Truncated(format!("{what} count")))? as usize; let mut out = Vec::new(); for _ in 0..n.min(MAX_ITEMS) { @@ -526,21 +605,20 @@ fn parse_members(c: &mut Cursor<'_>, pool: &[Const], warnings: &mut Vec, warnings.push(format!("{what} table ended early")); break; }; - let mut m = - Member { access, name: utf8_of(pool, name_idx).to_string(), descriptor: utf8_of(pool, desc_idx).to_string(), ..Default::default() }; + let mut m = Member { access, name: names.utf8(name_idx), descriptor: names.utf8(desc_idx), ..Default::default() }; let (attrs, _) = read_attrs(c, pool); for a in attrs { match a.name { - "Code" => m.code = parse_code(a.info, pool), + "Code" => m.code = parse_code(a.info, names), "ConstantValue" => { if let Some(i) = Reader::new(a.info).u16_be(0) { - m.constant_value = Some(const_display(pool, i)); + m.constant_value = Some(names.constant(i, const_display)); } } - "Exceptions" => m.exceptions = parse_exceptions_attr(a.info, pool), + "Exceptions" => m.exceptions = parse_exceptions_attr(a.info, names), "Signature" => { if let Some(i) = Reader::new(a.info).u16_be(0) { - m.signature = Some(utf8_of(pool, i).to_string()); + m.signature = Some(names.utf8(i)); } } "Deprecated" => m.deprecated = true, @@ -553,7 +631,8 @@ fn parse_members(c: &mut Cursor<'_>, pool: &[Const], warnings: &mut Vec, Ok(out) } -fn parse_code(info: &[u8], pool: &[Const]) -> Option { +fn parse_code(info: &[u8], names: &mut Names<'_>) -> Option { + let pool = names.pool; let mut c = Cursor::new(info); let max_stack = c.u16()?; let max_locals = c.u16()?; @@ -563,7 +642,7 @@ fn parse_code(info: &[u8], pool: &[Const]) -> Option { let mut exceptions = Vec::new(); for _ in 0..n_exc.min(MAX_ITEMS) { let (Some(start_pc), Some(end_pc), Some(handler_pc), Some(catch)) = (c.u16(), c.u16(), c.u16(), c.u16()) else { break }; - exceptions.push(ExceptionEntry { start_pc, end_pc, handler_pc, catch_type: (catch != 0).then(|| class_name_at(pool, catch)) }); + exceptions.push(ExceptionEntry { start_pc, end_pc, handler_pc, catch_type: (catch != 0).then(|| names.class(catch)) }); } let mut line_numbers = Vec::new(); let (attrs, _) = read_attrs(&mut c, pool); @@ -580,27 +659,27 @@ fn parse_code(info: &[u8], pool: &[Const]) -> Option { Some(Code { max_stack, max_locals, bytecode, exceptions, line_numbers }) } -fn parse_exceptions_attr(info: &[u8], pool: &[Const]) -> Vec { +fn parse_exceptions_attr(info: &[u8], names: &mut Names<'_>) -> Vec { let mut c = Cursor::new(info); let n = c.u16().unwrap_or(0) as usize; let mut out = Vec::new(); for _ in 0..n.min(MAX_ITEMS) { let Some(i) = c.u16() else { break }; - out.push(class_name_at(pool, i)); + out.push(names.class(i)); } out } -fn parse_inner_classes(info: &[u8], pool: &[Const]) -> Vec { +fn parse_inner_classes(info: &[u8], names: &mut Names<'_>) -> Vec { let mut c = Cursor::new(info); let n = c.u16().unwrap_or(0) as usize; let mut out = Vec::new(); for _ in 0..n.min(MAX_ITEMS) { let (Some(inner), Some(outer), Some(name), Some(access)) = (c.u16(), c.u16(), c.u16(), c.u16()) else { break }; out.push(InnerClass { - inner: (inner != 0).then(|| class_name_at(pool, inner)), - outer: (outer != 0).then(|| class_name_at(pool, outer)), - name: (name != 0).then(|| utf8_of(pool, name).to_string()), + inner: (inner != 0).then(|| names.class(inner)), + outer: (outer != 0).then(|| names.class(outer)), + name: (name != 0).then(|| names.utf8(name)), access, }); } @@ -608,32 +687,35 @@ fn parse_inner_classes(info: &[u8], pool: &[Const]) -> Vec { } /// Extract annotation type names (dotted) from a `Runtime*Annotations` attribute, best-effort. -fn parse_annotation_types(info: &[u8], pool: &[Const], visibility: &str) -> Vec { +fn parse_annotation_types(info: &[u8], names: &mut Names<'_>, visibility: &str) -> Vec { let mut c = Cursor::new(info); let n = c.u16().unwrap_or(0) as usize; let mut out = Vec::new(); for _ in 0..n.min(MAX_ITEMS) { - match read_annotation(&mut c, pool, 0) { - Some(t) => out.push(format!("{t} ({visibility})")), + match read_annotation(&mut c, names.pool, 0) { + Some(idx) => { + let t = names.keep("utf8", idx, |pool, idx| field_type(utf8_of(pool, idx))); + out.push(format!("{t} ({visibility})")); + } None => break, } } out } -/// Read one `annotation` structure, returning its (dotted) type name; advances past its values. -fn read_annotation(c: &mut Cursor<'_>, pool: &[Const], depth: usize) -> Option { +/// Read one `annotation` structure, returning the pool index of its type descriptor; advances past +/// its values. +fn read_annotation(c: &mut Cursor<'_>, pool: &[Const], depth: usize) -> Option { if depth > MAX_ANNO_DEPTH { return None; } let type_idx = c.u16()?; let n_pairs = c.u16()? as usize; - let type_name = field_type(utf8_of(pool, type_idx)); for _ in 0..n_pairs.min(MAX_ITEMS) { let _name_idx = c.u16()?; skip_element_value(c, pool, depth + 1)?; } - Some(type_name) + Some(type_idx) } fn skip_element_value(c: &mut Cursor<'_>, pool: &[Const], depth: usize) -> Option<()> { @@ -686,6 +768,17 @@ fn const_display(pool: &[Const], idx: u16) -> String { } } +/// The key under which `Names` keeps the length of `const_display(pool, idx)`: the Utf8 a +/// `String`, `Class` or `MethodType` constant copies, otherwise the constant itself. +fn const_text_key(pool: &[Const], idx: u16) -> (&'static str, u16) { + match pool.get(idx as usize) { + Some(Const::String(s)) => ("const-string", *s), + Some(Const::Class(n)) => ("const-class", *n), + Some(Const::MethodType(d)) => ("const-method-type", *d), + _ => ("const", idx), + } +} + // --------------------------------------------------------------------------------------------- // Resolution and formatting on a parsed class diff --git a/crates/java-class/src/lib.rs b/crates/java-class/src/lib.rs index 4d135e16b2..7e54dd258f 100644 --- a/crates/java-class/src/lib.rs +++ b/crates/java-class/src/lib.rs @@ -33,6 +33,10 @@ mod java_attribute_names; #[path = "regressions/java_constant_pool_slots.rs"] mod java_constant_pool_slots; +#[cfg(test)] +#[path = "regressions/java_copied_names.rs"] +mod java_copied_names; + #[cfg(test)] #[path = "regressions/java_invoke_operands.rs"] mod java_invoke_operands; diff --git a/crates/java-class/src/regressions/java_copied_names.rs b/crates/java-class/src/regressions/java_copied_names.rs new file mode 100644 index 0000000000..2279807c17 --- /dev/null +++ b/crates/java-class/src/regressions/java_copied_names.rs @@ -0,0 +1,248 @@ +use crate::java_class::{self, ClassFile, Const, MAX_COPIED_TEXT, Names}; +use std::cell::Cell; + +const BIG: usize = u16::MAX as usize; +// Each repeat names the 65,535-byte Utf8 at least once, so 1,100 repeats exceed the limit. +const REPEATS: u16 = 1100; + +#[derive(Clone, Copy, Debug)] +enum Scope { + Interfaces, + Fields, + Methods, + Throws, + Catches, + InnerClasses, + Constants, +} + +fn u16b(out: &mut Vec, n: u16) { + out.extend_from_slice(&n.to_be_bytes()); +} + +fn utf8(out: &mut Vec, text: &str) { + out.push(1); + u16b(out, text.len() as u16); + out.extend_from_slice(text.as_bytes()); +} + +fn attr(out: &mut Vec, name: u16, info: &[u8]) { + u16b(out, name); + out.extend_from_slice(&(info.len() as u32).to_be_bytes()); + out.extend_from_slice(info); +} + +// Every repeated entry names pool entry 1 (a 65,535-byte Utf8) directly or through the +// `Class` at entry 2 or the `String` at entry 11. The file stays well under 100 KiB. +fn fixture(scope: Scope) -> Vec { + let mut out = vec![0xca, 0xfe, 0xba, 0xbe, 0, 0, 0, 52]; + u16b(&mut out, 12); + utf8(&mut out, &"A".repeat(BIG)); // 1 + out.extend_from_slice(&[7, 0, 1]); // 2 + utf8(&mut out, "java/lang/Object"); // 3 + out.extend_from_slice(&[7, 0, 3]); // 4 + utf8(&mut out, "Sample"); // 5 + out.extend_from_slice(&[7, 0, 5]); // 6 + for text in ["Exceptions", "InnerClasses", "Code", "ConstantValue"] { + utf8(&mut out, text); // 7..10 + } + out.extend_from_slice(&[8, 0, 1]); // 11 + for word in [0x0021, 6, 4] { + u16b(&mut out, word); + } + // Interfaces + if matches!(scope, Scope::Interfaces) { + u16b(&mut out, REPEATS); + for _ in 0..REPEATS { + u16b(&mut out, 2); + } + } else { + u16b(&mut out, 0); + } + // Fields and methods named and described by entry 1. + for table in [Scope::Fields, Scope::Methods] { + if std::mem::discriminant(&scope) == std::mem::discriminant(&table) { + u16b(&mut out, REPEATS); + for _ in 0..REPEATS { + for word in [0, 1, 1, 0] { + u16b(&mut out, word); + } + } + } else if matches!((scope, table), (Scope::Constants, Scope::Fields)) { + // Fields named `Sample` whose `ConstantValue` is the string at entry 11. + u16b(&mut out, REPEATS); + for _ in 0..REPEATS { + for word in [0x0018, 5, 5, 1] { + u16b(&mut out, word); + } + attr(&mut out, 10, &[0, 11]); + } + } else if matches!((scope, table), (Scope::Throws | Scope::Catches, Scope::Methods)) { + u16b(&mut out, 1); + for word in [0x0009, 5, 5, 1] { + u16b(&mut out, word); + } + let mut info = Vec::new(); + if matches!(scope, Scope::Throws) { + u16b(&mut info, REPEATS); + for _ in 0..REPEATS { + u16b(&mut info, 2); + } + attr(&mut out, 7, &info); + } else { + info.extend_from_slice(&[0, 0, 0, 0, 0, 0, 0, 1, 0xb1]); + u16b(&mut info, REPEATS); + for _ in 0..REPEATS { + for word in [0, 1, 0, 2] { + u16b(&mut info, word); + } + } + u16b(&mut info, 0); + attr(&mut out, 9, &info); + } + } else { + u16b(&mut out, 0); + } + } + // Class attributes + if matches!(scope, Scope::InnerClasses) { + u16b(&mut out, 1); + let mut info = Vec::new(); + u16b(&mut info, REPEATS); + for _ in 0..REPEATS { + for word in [2, 0, 1, 0] { + u16b(&mut info, word); + } + } + attr(&mut out, 8, &info); + } else { + u16b(&mut out, 0); + } + out +} + +/// The copied names of one scope's repeated entries. +fn names(parsed: &ClassFile, scope: Scope) -> Vec<&str> { + let mut out = Vec::new(); + match scope { + Scope::Interfaces => out.extend(parsed.interfaces.iter().map(String::as_str)), + Scope::Fields | Scope::Methods => { + let members = if matches!(scope, Scope::Fields) { &parsed.fields } else { &parsed.methods }; + for m in members { + out.extend([m.name.as_str(), m.descriptor.as_str()]); + } + } + Scope::Throws => out.extend(parsed.methods.iter().flat_map(|m| m.exceptions.iter().map(String::as_str))), + Scope::Catches => { + let codes = parsed.methods.iter().filter_map(|m| m.code.as_ref()); + out.extend(codes.flat_map(|c| c.exceptions.iter().filter_map(|e| e.catch_type.as_deref()))); + } + Scope::InnerClasses => { + for row in &parsed.inner_classes { + out.extend(row.inner.as_deref()); + out.extend(row.name.as_deref()); + } + } + Scope::Constants => out.extend(parsed.fields.iter().filter_map(|m| m.constant_value.as_deref())), + } + out +} + +fn check(scope: Scope) { + let bytes = fixture(scope); + assert!(bytes.len() < 100_000, "{scope:?}: {}", bytes.len()); + let parsed = java_class::parse(&bytes).unwrap(); + let names = names(&parsed, scope); + let per_entry = if matches!(scope, Scope::Fields | Scope::Methods | Scope::InnerClasses) { 2 } else { 1 }; + // Every entry is still listed; the budget replaces names, not rows. + assert_eq!(names.len(), usize::from(REPEATS) * per_entry, "{scope:?}"); + // A string constant is shown quoted, two bytes longer than its Utf8. + let full: Vec = names.iter().map(|n| n.len()).filter(|&n| n >= BIG).collect(); + assert!(!full.is_empty(), "{scope:?}: the first names are copied in full"); + let copied: usize = full.iter().sum(); + assert!(copied <= MAX_COPIED_TEXT, "{scope:?}: {copied} bytes of names copied"); + assert!(names.iter().any(|n| n.starts_with('<') && n.ends_with('>')), "{scope:?}: names past the budget are placeholders"); + assert!(parsed.warnings.iter().any(|w| w.contains("pool indices")), "{scope:?}: {:?}", parsed.warnings); + assert_eq!(parsed.this_class, "Sample"); + assert_eq!(parsed.super_class.as_deref(), Some("java/lang/Object")); +} + +#[test] +fn repeated_interface_names_stay_within_the_copy_budget() { + check(Scope::Interfaces); +} + +#[test] +fn repeated_field_names_stay_within_the_copy_budget() { + check(Scope::Fields); +} + +#[test] +fn repeated_method_names_stay_within_the_copy_budget() { + check(Scope::Methods); +} + +#[test] +fn repeated_thrown_type_names_stay_within_the_copy_budget() { + check(Scope::Throws); +} + +#[test] +fn repeated_caught_type_names_stay_within_the_copy_budget() { + check(Scope::Catches); +} + +#[test] +fn repeated_inner_class_names_stay_within_the_copy_budget() { + check(Scope::InnerClasses); +} + +#[test] +fn repeated_constant_values_stay_within_the_copy_budget() { + check(Scope::Constants); +} + +thread_local! { + static RENDERS: Cell = const { Cell::new(0) }; +} + +fn counted_render(pool: &[Const], idx: u16) -> String { + RENDERS.with(|n| n.set(n.get() + 1)); + match pool.get(usize::from(idx)) { + Some(Const::Utf8(s)) => format!("{s:?}"), + Some(Const::String(s)) => match pool.get(usize::from(*s)) { + Some(Const::Utf8(text)) => format!("{text:?}"), + _ => String::new(), + }, + _ => String::new(), + } +} + +#[test] +fn text_over_the_budget_is_rendered_once() { + let pool = vec![Const::Unusable, Const::Utf8("A".repeat(BIG))]; + let mut names = Names::new(&pool); + RENDERS.with(|n| n.set(0)); + let kept: Vec = (0..2 * MAX_COPIED_TEXT / BIG).map(|_| names.keep("const", 1, counted_render)).collect(); + let copied = kept.iter().filter(|t| t.len() == BIG + 2).count(); + assert!(copied >= 1 && copied < kept.len(), "{copied} of {} copied", kept.len()); + assert_eq!(kept.last().map(String::as_str), Some("")); + // Only the copied texts are rendered; the refusals reuse the length kept from the first one. + assert_eq!(RENDERS.with(Cell::get), copied); +} + +#[test] +fn string_constants_over_one_utf8_are_rendered_once_past_the_budget() { + let entries = 2 * MAX_COPIED_TEXT / BIG; + let mut pool = vec![Const::Unusable, Const::Utf8("A".repeat(BIG))]; + pool.extend((0..entries).map(|_| Const::String(1))); + let mut names = Names::new(&pool); + RENDERS.with(|n| n.set(0)); + let kept: Vec = (2..pool.len()).map(|i| names.constant(i as u16, counted_render)).collect(); + let copied = kept.iter().filter(|t| t.len() == BIG + 2).count(); + assert!(copied >= 1 && copied < kept.len(), "{copied} of {} copied", kept.len()); + assert_eq!(kept.last().map(String::as_str), Some(format!("", pool.len() - 1).as_str())); + // Each `String` entry is its own pool index, but all of them quote entry 1, so the refusals + // reuse the length kept for entry 1 instead of building the text again. + assert_eq!(RENDERS.with(Cell::get), copied); +}