From acfb5fc329636087859bca4f58ae09c557e5aab8 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Tue, 17 Nov 2026 14:38:14 -0800 Subject: [PATCH] java-class: bound the constant-pool text copied into names Interfaces, field and method names and descriptors, signatures, constant values, thrown and caught types, inner classes and annotation types each copy their constant-pool text. Many entries can name one 65,535-byte Utf8, so a class file under 100 KiB could make parse() copy gigabytes. parse() now copies at most 64 MiB of such text per class. Past that, names are kept as pool-index placeholders (, ) and a warning is added; every row is still listed. --- crates/java-class/src/java_class.rs | 124 +++++++++--- crates/java-class/src/lib.rs | 4 + .../src/regressions/java_copied_names.rs | 183 ++++++++++++++++++ 3 files changed, 279 insertions(+), 32 deletions(-) create mode 100644 crates/java-class/src/regressions/java_copied_names.rs diff --git a/crates/java-class/src/java_class.rs b/crates/java-class/src/java_class.rs index 4b751ec3ee..5b44236da0 100644 --- a/crates/java-class/src/java_class.rs +++ b/crates/java-class/src/java_class.rs @@ -18,6 +18,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 +350,55 @@ fn utf8_of(pool: &[Const], idx: u16) -> &str { } } +/// Copies constant-pool text into the parse result within `MAX_COPIED_TEXT` bytes in total. +struct Names<'p> { + pool: &'p [Const], + left: usize, + exhausted: bool, +} + +impl<'p> Names<'p> { + fn new(pool: &'p [Const]) -> Self { + Names { pool, left: MAX_COPIED_TEXT, exhausted: false } + } + + /// 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 + } + } + } + + /// Keep `text` when the budget covers it, otherwise the placeholder ``. + fn keep(&mut self, text: String, kind: &str, idx: u16) -> String { + 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 +421,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 +432,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 +452,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 +574,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 +583,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.keep(const_display(pool, i), "const", i)); } } - "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 +609,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 +620,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 +637,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 +665,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(field_type(utf8_of(names.pool, idx)), "utf8", 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<()> { 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..2fcee6499d --- /dev/null +++ b/crates/java-class/src/regressions/java_copied_names.rs @@ -0,0 +1,183 @@ +use crate::java_class::{self, ClassFile, MAX_COPIED_TEXT}; + +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, +} + +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. 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, 10); + 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"] { + utf8(&mut out, text); // 7..9 + } + 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::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()); + } + } + } + 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:?}"); + let full = names.iter().filter(|n| n.len() == BIG).count(); + assert!(full >= 1, "{scope:?}: the first names are copied in full"); + assert!(full * BIG <= MAX_COPIED_TEXT, "{scope:?}: {} bytes of names copied", full * BIG); + 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); +}