Extract Java class reader and JVM opcode decoder (#2048)

* Port Java class source: Craft Anything

Source: storytold/craft-anything@f64ae3bf3c

* Port Java class source: Find class usage in multidimensional object arrays (R0.5) (#437)

Source: storytold/craft-anything@ffe15c9165

* Port Java class source: More format parsers keep to their declared lengths and refuse impossible values (#722)

Source: storytold/craft-anything@b9ca099903

* Port Java class source: Address the parser review findings from #722 (#766)

Source: storytold/craft-anything@eab6a0f01b

* Port Java class source: Read JVM method parameters containing parentheses in class names (R3.12) (#1342)

Source: storytold/craft-anything@fb4c437fe6

* Port Java class source: Reject Java constants that exceed the constant-pool slots (R3.12) (#1373)

Source: storytold/craft-anything@1c4f233f08

* Port Java class source: Validate JVM switch tables before allocating decoded pairs (R3.12) (#1503)

Source: storytold/craft-anything@b40c56ef5c

* Port Java class source: Reuse constant-pool names while reading Java attributes (R3.12) (#1549)

Source: storytold/craft-anything@76fcdaadb7

* Port Java class source: Trace JVM bootstrap dependencies at their bytecode use sites (R3.12) (#1648)

Source: storytold/craft-anything@c5e524dd08

* Port Java class source: Reject impossible JVM array allocation operands (R3.12) (#1675)

Source: storytold/craft-anything@f04d7456e0

* Port Java class source: Report truncated Java class attribute tables (R3.12)

Source: storytold/craft-anything@420552ff74

* Expose neutral Java class API and retain checked reader and synthetic fixtures

* Retain Java regression: java_array_operands

Source: storytold/craft-anything@f04d7456e0

* Retain Java regression: java_attribute_names

Source: storytold/craft-anything@76fcdaadb7

* Retain Java regression: java_constant_pool_slots

Source: storytold/craft-anything@1c4f233f08

* Retain Java regression: java_invoke_operands

Source: storytold/craft-anything@eab6a0f01b

* Retain Java regression: java_linkage_references

Source: storytold/craft-anything@c5e524dd08

* Retain Java regression: java_truncated_attributes

Source: storytold/craft-anything@420552ff74

* Retain Java regression: java_wide_opcodes

Source: storytold/craft-anything@b9ca099903

* Register Java class reader and retain source regression coverage

---------

Co-authored-by: Brandon Thomas <echelon@gmail.com>
Co-authored-by: Afloat <132809511+Afloat16@users.noreply.github.com>
Co-authored-by: BFlat <bombayapirat@gmail.com>
Co-authored-by: Afloat <ShuffleMonkey@163.com>
Co-authored-by: RRFZ <247457381+Plastic-time@users.noreply.github.com>
This commit is contained in:
authored and GitHub committed 2026-11-17 16:13:18 -05:00
1 parent 93dac78c93
commit d118983bf9
17 files changed
+2740

No files matched your search

+51
View File
@@ -0,0 +1,51 @@
//! 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 slice(&self, off: usize, len: usize) -> Option<&'a [u8]> {
let end = off.checked_add(len)?;
self.data.get(off..end)
}
pub fn u8(&self, off: usize) -> Option<u8> {
self.data.get(off).copied()
}
fn arr<const N: usize>(&self, off: usize) -> Option<[u8; N]> {
self.slice(off, N)?.try_into().ok()
}
pub fn u16_be(&self, off: usize) -> Option<u16> {
self.arr(off).map(u16::from_be_bytes)
}
pub fn u32_be(&self, off: usize) -> Option<u32> {
self.arr(off).map(u32::from_be_bytes)
}
pub fn u64_be(&self, off: usize) -> Option<u64> {
self.arr(off).map(u64::from_be_bytes)
}
}
/// 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),
}
}
+19
View File
@@ -0,0 +1,19 @@
// Descriptor display helper retained from the source DEX reader.
pub fn java_name(desc: &str) -> String {
let dims = desc.chars().take_while(|&c| c == '[').count();
let base = desc.get(dims..).unwrap_or("");
let name = match base {
"V" => "void".to_string(),
"Z" => "boolean".to_string(),
"B" => "byte".to_string(),
"S" => "short".to_string(),
"C" => "char".to_string(),
"I" => "int".to_string(),
"J" => "long".to_string(),
"F" => "float".to_string(),
"D" => "double".to_string(),
b if b.starts_with('L') && b.ends_with(';') => b.get(1..b.len() - 1).unwrap_or("").replace('/', "."),
b => b.to_string(),
};
format!("{name}{}", "[]".repeat(dims.min(255)))
}
File diff suppressed because it is too large. Load diff
+711
View File
@@ -0,0 +1,711 @@
//! JVM bytecode: the opcode table (every defined opcode plus the `wide`, `tableswitch` and
//! `lookupswitch` variable-length forms) and a decoder for each instruction. Pure decoding;
//! constant-pool index operands are resolved by the caller (see [`crate::java_class`]).
use serde::Serialize;
/// The shape of an opcode's operands.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
pub enum Operands {
/// No operands.
None,
/// One signed byte immediate (`bipush`).
Byte,
/// One signed short immediate (`sipush`).
Short,
/// A one-byte local-variable index.
Local,
/// `iinc`: a one-byte local index and a signed byte increment.
LocalConst,
/// A two-byte signed branch offset.
Branch2,
/// A four-byte signed branch offset (`goto_w`, `jsr_w`).
Branch4,
/// A one-byte constant-pool index (`ldc`).
Cp1,
/// A two-byte constant-pool index.
Cp2,
/// `newarray`: a one-byte primitive array type.
NewArray,
/// `invokeinterface`: a two-byte index, a count byte and a zero byte.
InvokeInterface,
/// `invokedynamic`: a two-byte index and two zero bytes.
InvokeDynamic,
/// `multianewarray`: a two-byte class index and a dimension byte.
MultiANewArray,
/// `tableswitch` (variable length, 4-byte aligned).
TableSwitch,
/// `lookupswitch` (variable length, 4-byte aligned).
LookupSwitch,
/// `wide`: a prefix that widens the following load/store/ret/iinc.
Wide,
/// A reserved or unknown opcode.
Reserved,
}
/// One opcode slot.
#[derive(Debug, Clone, Copy)]
pub struct Op {
pub name: &'static str,
pub operands: Operands,
}
const fn op(name: &'static str, operands: Operands) -> Op {
Op { name, operands }
}
/// The opcode table entry for `b`.
pub fn opcode(b: u8) -> Op {
use Operands as O;
match b {
0x00 => op("nop", O::None),
0x01 => op("aconst_null", O::None),
0x02 => op("iconst_m1", O::None),
0x03 => op("iconst_0", O::None),
0x04 => op("iconst_1", O::None),
0x05 => op("iconst_2", O::None),
0x06 => op("iconst_3", O::None),
0x07 => op("iconst_4", O::None),
0x08 => op("iconst_5", O::None),
0x09 => op("lconst_0", O::None),
0x0a => op("lconst_1", O::None),
0x0b => op("fconst_0", O::None),
0x0c => op("fconst_1", O::None),
0x0d => op("fconst_2", O::None),
0x0e => op("dconst_0", O::None),
0x0f => op("dconst_1", O::None),
0x10 => op("bipush", O::Byte),
0x11 => op("sipush", O::Short),
0x12 => op("ldc", O::Cp1),
0x13 => op("ldc_w", O::Cp2),
0x14 => op("ldc2_w", O::Cp2),
0x15 => op("iload", O::Local),
0x16 => op("lload", O::Local),
0x17 => op("fload", O::Local),
0x18 => op("dload", O::Local),
0x19 => op("aload", O::Local),
0x1a => op("iload_0", O::None),
0x1b => op("iload_1", O::None),
0x1c => op("iload_2", O::None),
0x1d => op("iload_3", O::None),
0x1e => op("lload_0", O::None),
0x1f => op("lload_1", O::None),
0x20 => op("lload_2", O::None),
0x21 => op("lload_3", O::None),
0x22 => op("fload_0", O::None),
0x23 => op("fload_1", O::None),
0x24 => op("fload_2", O::None),
0x25 => op("fload_3", O::None),
0x26 => op("dload_0", O::None),
0x27 => op("dload_1", O::None),
0x28 => op("dload_2", O::None),
0x29 => op("dload_3", O::None),
0x2a => op("aload_0", O::None),
0x2b => op("aload_1", O::None),
0x2c => op("aload_2", O::None),
0x2d => op("aload_3", O::None),
0x2e => op("iaload", O::None),
0x2f => op("laload", O::None),
0x30 => op("faload", O::None),
0x31 => op("daload", O::None),
0x32 => op("aaload", O::None),
0x33 => op("baload", O::None),
0x34 => op("caload", O::None),
0x35 => op("saload", O::None),
0x36 => op("istore", O::Local),
0x37 => op("lstore", O::Local),
0x38 => op("fstore", O::Local),
0x39 => op("dstore", O::Local),
0x3a => op("astore", O::Local),
0x3b => op("istore_0", O::None),
0x3c => op("istore_1", O::None),
0x3d => op("istore_2", O::None),
0x3e => op("istore_3", O::None),
0x3f => op("lstore_0", O::None),
0x40 => op("lstore_1", O::None),
0x41 => op("lstore_2", O::None),
0x42 => op("lstore_3", O::None),
0x43 => op("fstore_0", O::None),
0x44 => op("fstore_1", O::None),
0x45 => op("fstore_2", O::None),
0x46 => op("fstore_3", O::None),
0x47 => op("dstore_0", O::None),
0x48 => op("dstore_1", O::None),
0x49 => op("dstore_2", O::None),
0x4a => op("dstore_3", O::None),
0x4b => op("astore_0", O::None),
0x4c => op("astore_1", O::None),
0x4d => op("astore_2", O::None),
0x4e => op("astore_3", O::None),
0x4f => op("iastore", O::None),
0x50 => op("lastore", O::None),
0x51 => op("fastore", O::None),
0x52 => op("dastore", O::None),
0x53 => op("aastore", O::None),
0x54 => op("bastore", O::None),
0x55 => op("castore", O::None),
0x56 => op("sastore", O::None),
0x57 => op("pop", O::None),
0x58 => op("pop2", O::None),
0x59 => op("dup", O::None),
0x5a => op("dup_x1", O::None),
0x5b => op("dup_x2", O::None),
0x5c => op("dup2", O::None),
0x5d => op("dup2_x1", O::None),
0x5e => op("dup2_x2", O::None),
0x5f => op("swap", O::None),
0x60 => op("iadd", O::None),
0x61 => op("ladd", O::None),
0x62 => op("fadd", O::None),
0x63 => op("dadd", O::None),
0x64 => op("isub", O::None),
0x65 => op("lsub", O::None),
0x66 => op("fsub", O::None),
0x67 => op("dsub", O::None),
0x68 => op("imul", O::None),
0x69 => op("lmul", O::None),
0x6a => op("fmul", O::None),
0x6b => op("dmul", O::None),
0x6c => op("idiv", O::None),
0x6d => op("ldiv", O::None),
0x6e => op("fdiv", O::None),
0x6f => op("ddiv", O::None),
0x70 => op("irem", O::None),
0x71 => op("lrem", O::None),
0x72 => op("frem", O::None),
0x73 => op("drem", O::None),
0x74 => op("ineg", O::None),
0x75 => op("lneg", O::None),
0x76 => op("fneg", O::None),
0x77 => op("dneg", O::None),
0x78 => op("ishl", O::None),
0x79 => op("lshl", O::None),
0x7a => op("ishr", O::None),
0x7b => op("lshr", O::None),
0x7c => op("iushr", O::None),
0x7d => op("lushr", O::None),
0x7e => op("iand", O::None),
0x7f => op("land", O::None),
0x80 => op("ior", O::None),
0x81 => op("lor", O::None),
0x82 => op("ixor", O::None),
0x83 => op("lxor", O::None),
0x84 => op("iinc", O::LocalConst),
0x85 => op("i2l", O::None),
0x86 => op("i2f", O::None),
0x87 => op("i2d", O::None),
0x88 => op("l2i", O::None),
0x89 => op("l2f", O::None),
0x8a => op("l2d", O::None),
0x8b => op("f2i", O::None),
0x8c => op("f2l", O::None),
0x8d => op("f2d", O::None),
0x8e => op("d2i", O::None),
0x8f => op("d2l", O::None),
0x90 => op("d2f", O::None),
0x91 => op("i2b", O::None),
0x92 => op("i2c", O::None),
0x93 => op("i2s", O::None),
0x94 => op("lcmp", O::None),
0x95 => op("fcmpl", O::None),
0x96 => op("fcmpg", O::None),
0x97 => op("dcmpl", O::None),
0x98 => op("dcmpg", O::None),
0x99 => op("ifeq", O::Branch2),
0x9a => op("ifne", O::Branch2),
0x9b => op("iflt", O::Branch2),
0x9c => op("ifge", O::Branch2),
0x9d => op("ifgt", O::Branch2),
0x9e => op("ifle", O::Branch2),
0x9f => op("if_icmpeq", O::Branch2),
0xa0 => op("if_icmpne", O::Branch2),
0xa1 => op("if_icmplt", O::Branch2),
0xa2 => op("if_icmpge", O::Branch2),
0xa3 => op("if_icmpgt", O::Branch2),
0xa4 => op("if_icmple", O::Branch2),
0xa5 => op("if_acmpeq", O::Branch2),
0xa6 => op("if_acmpne", O::Branch2),
0xa7 => op("goto", O::Branch2),
0xa8 => op("jsr", O::Branch2),
0xa9 => op("ret", O::Local),
0xaa => op("tableswitch", O::TableSwitch),
0xab => op("lookupswitch", O::LookupSwitch),
0xac => op("ireturn", O::None),
0xad => op("lreturn", O::None),
0xae => op("freturn", O::None),
0xaf => op("dreturn", O::None),
0xb0 => op("areturn", O::None),
0xb1 => op("return", O::None),
0xb2 => op("getstatic", O::Cp2),
0xb3 => op("putstatic", O::Cp2),
0xb4 => op("getfield", O::Cp2),
0xb5 => op("putfield", O::Cp2),
0xb6 => op("invokevirtual", O::Cp2),
0xb7 => op("invokespecial", O::Cp2),
0xb8 => op("invokestatic", O::Cp2),
0xb9 => op("invokeinterface", O::InvokeInterface),
0xba => op("invokedynamic", O::InvokeDynamic),
0xbb => op("new", O::Cp2),
0xbc => op("newarray", O::NewArray),
0xbd => op("anewarray", O::Cp2),
0xbe => op("arraylength", O::None),
0xbf => op("athrow", O::None),
0xc0 => op("checkcast", O::Cp2),
0xc1 => op("instanceof", O::Cp2),
0xc2 => op("monitorenter", O::None),
0xc3 => op("monitorexit", O::None),
0xc4 => op("wide", O::Wide),
0xc5 => op("multianewarray", O::MultiANewArray),
0xc6 => op("ifnull", O::Branch2),
0xc7 => op("ifnonnull", O::Branch2),
0xc8 => op("goto_w", O::Branch4),
0xc9 => op("jsr_w", O::Branch4),
0xca => op("breakpoint", O::None),
0xfe => op("impdep1", O::None),
0xff => op("impdep2", O::None),
_ => op("unknown", O::Reserved),
}
}
/// The primitive array type for a `newarray` atype operand.
pub fn array_type(atype: i32) -> &'static str {
match atype {
4 => "boolean",
5 => "char",
6 => "float",
7 => "double",
8 => "byte",
9 => "short",
10 => "int",
11 => "long",
_ => "?",
}
}
/// A decoded `tableswitch`/`lookupswitch`.
#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
pub struct Switch {
/// Absolute byte offset of the default branch.
pub default: i64,
/// `(key, absolute target)` pairs in listing order.
pub pairs: Vec<(i32, i64)>,
}
/// One decoded instruction.
#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
pub struct Insn {
/// Byte offset from the start of the method's code.
pub pc: u32,
pub opcode: u8,
pub name: &'static str,
/// Total length in bytes, including operands.
pub len: u32,
/// Local-variable index operand (load/store/ret/iinc).
#[serde(skip_serializing_if = "Option::is_none")]
pub local: Option<u16>,
/// Integer immediate (`bipush`/`sipush`/`iinc` increment/`newarray` type/`multianewarray` dims).
#[serde(skip_serializing_if = "Option::is_none")]
pub int: Option<i32>,
/// Constant-pool index operand (resolved by the caller).
#[serde(skip_serializing_if = "Option::is_none")]
pub cp_index: Option<u16>,
/// Absolute byte offset of a branch target.
#[serde(skip_serializing_if = "Option::is_none")]
pub branch: Option<i64>,
/// A switch table when the opcode is `tableswitch`/`lookupswitch`.
#[serde(skip_serializing_if = "Option::is_none")]
pub switch: Option<Switch>,
/// True when this instruction was prefixed by `wide`.
#[serde(skip_serializing_if = "std::ops::Not::not")]
pub wide: bool,
}
/// Most entries decoded from one switch table.
const MAX_SWITCH: usize = 1 << 20;
fn s8(code: &[u8], at: usize) -> Option<i32> {
code.get(at).map(|&b| i32::from(b as i8))
}
fn u16b(code: &[u8], at: usize) -> Option<u16> {
Some(u16::from(*code.get(at)?) << 8 | u16::from(*code.get(at + 1)?))
}
fn s16(code: &[u8], at: usize) -> Option<i32> {
u16b(code, at).map(|v| i32::from(v as i16))
}
fn s32(code: &[u8], at: usize) -> Option<i32> {
Some(i32::from(*code.get(at)?) << 24 | i32::from(*code.get(at + 1)?) << 16 | i32::from(*code.get(at + 2)?) << 8 | i32::from(*code.get(at + 3)?))
}
fn base(pc: usize, opcode: u8, name: &'static str) -> Insn {
Insn { pc: pc as u32, opcode, name, len: 1, local: None, int: None, cp_index: None, branch: None, switch: None, wide: false }
}
/// Decode one instruction at `pc`, or `None` for invalid or incomplete operands.
pub fn decode_one(code: &[u8], pc: usize) -> Option<Insn> {
let b = *code.get(pc)?;
let o = opcode(b);
let mut insn = base(pc, b, o.name);
let rel = |d: i32| pc as i64 + i64::from(d);
match o.operands {
Operands::None | Operands::Reserved => {}
Operands::Byte => {
insn.int = Some(s8(code, pc + 1)?);
insn.len = 2;
}
Operands::Short => {
insn.int = Some(s16(code, pc + 1)?);
insn.len = 3;
}
Operands::Local => {
insn.local = Some(u16::from(*code.get(pc + 1)?));
insn.len = 2;
}
Operands::LocalConst => {
insn.local = Some(u16::from(*code.get(pc + 1)?));
insn.int = Some(s8(code, pc + 2)?);
insn.len = 3;
}
Operands::Branch2 => {
insn.branch = Some(rel(s16(code, pc + 1)?));
insn.len = 3;
}
Operands::Branch4 => {
insn.branch = Some(rel(s32(code, pc + 1)?));
insn.len = 5;
}
Operands::Cp1 => {
insn.cp_index = Some(u16::from(*code.get(pc + 1)?));
insn.len = 2;
}
Operands::Cp2 => {
insn.cp_index = Some(u16b(code, pc + 1)?);
insn.len = 3;
}
Operands::NewArray => {
let atype = *code.get(pc + 1)?;
if !(4..=11).contains(&atype) {
return None;
}
insn.int = Some(i32::from(atype));
insn.len = 2;
}
Operands::InvokeInterface => {
insn.cp_index = Some(u16b(code, pc + 1)?);
if *code.get(pc + 3)? == 0 || *code.get(pc + 4)? != 0 {
return None;
}
insn.len = 5;
}
Operands::InvokeDynamic => {
insn.cp_index = Some(u16b(code, pc + 1)?);
if *code.get(pc + 3)? != 0 || *code.get(pc + 4)? != 0 {
return None;
}
insn.len = 5;
}
Operands::MultiANewArray => {
insn.cp_index = Some(u16b(code, pc + 1)?);
let dimensions = *code.get(pc + 3)?;
if dimensions == 0 {
return None;
}
insn.int = Some(i32::from(dimensions));
insn.len = 4;
}
Operands::Wide => return decode_wide(code, pc),
Operands::TableSwitch => return decode_tableswitch(code, pc),
Operands::LookupSwitch => return decode_lookupswitch(code, pc),
}
if pc.checked_add(insn.len as usize)? > code.len() {
return None;
}
Some(insn)
}
fn decode_wide(code: &[u8], pc: usize) -> Option<Insn> {
let real = *code.get(pc + 1)?;
if !matches!(real, 0x15..=0x19 | 0x36..=0x3a | 0x84 | 0xa9) {
return None;
}
let o = opcode(real);
let mut insn = base(pc, real, o.name);
insn.wide = true;
if real == 0x84 {
// wide iinc: 2-byte local, 2-byte signed const
insn.local = Some(u16b(code, pc + 2)?);
insn.int = Some(s16(code, pc + 4)?);
insn.len = 6;
} else {
// wide load/store/ret: 2-byte local
insn.local = Some(u16b(code, pc + 2)?);
insn.len = 4;
}
if pc.checked_add(insn.len as usize)? > code.len() {
return None;
}
Some(insn)
}
/// Padding so the operand word after a switch opcode is 4-byte aligned from the code start.
fn switch_pad(pc: usize) -> usize {
(4 - ((pc + 1) % 4)) % 4
}
fn decode_tableswitch(code: &[u8], pc: usize) -> Option<Insn> {
let mut at = pc + 1 + switch_pad(pc);
let default = rel_i64(pc, s32(code, at)?);
let low = s32(code, at + 4)?;
let high = s32(code, at + 8)?;
at += 12;
if high < low {
return None;
}
let count = usize::try_from(i64::from(high) - i64::from(low) + 1).ok()?;
if count > MAX_SWITCH {
return None;
}
let end = at.checked_add(count.checked_mul(4)?)?;
code.get(at..end)?;
let mut pairs = Vec::with_capacity(count);
for i in 0..count {
let off = s32(code, at + i * 4)?;
pairs.push((low.wrapping_add(i as i32), rel_i64(pc, off)));
}
let mut insn = base(pc, 0xaa, "tableswitch");
insn.switch = Some(Switch { default, pairs });
insn.len = (end - pc) as u32;
Some(insn)
}
fn decode_lookupswitch(code: &[u8], pc: usize) -> Option<Insn> {
let mut at = pc + 1 + switch_pad(pc);
let default = rel_i64(pc, s32(code, at)?);
let npairs = s32(code, at + 4)?;
at += 8;
if npairs < 0 {
return None;
}
let count = npairs as usize;
if count > MAX_SWITCH {
return None;
}
let end = at.checked_add(count.checked_mul(8)?)?;
code.get(at..end)?;
let mut pairs = Vec::with_capacity(count);
let mut previous = None;
for i in 0..count {
let key = s32(code, at + i * 8)?;
if previous.is_some_and(|previous| key <= previous) {
return None;
}
previous = Some(key);
let off = s32(code, at + i * 8 + 4)?;
pairs.push((key, rel_i64(pc, off)));
}
let mut insn = base(pc, 0xab, "lookupswitch");
insn.switch = Some(Switch { default, pairs });
insn.len = (end - pc) as u32;
Some(insn)
}
fn rel_i64(pc: usize, off: i32) -> i64 {
pc as i64 + i64::from(off)
}
/// Decode a whole method body, stopping at `max` instructions. `complete` is false when a
/// instruction has invalid/incomplete operands or the cap was hit.
pub fn decode(code: &[u8], max: usize) -> (Vec<Insn>, bool) {
let mut out = Vec::new();
let mut pc = 0usize;
let mut complete = true;
while pc < code.len() {
if out.len() >= max {
complete = false;
break;
}
match decode_one(code, pc) {
Some(i) => {
pc += (i.len as usize).max(1);
out.push(i);
}
None => {
complete = false;
break;
}
}
}
(out, complete)
}
#[cfg(test)]
mod tests {
use super::*;
fn lookup(pc: usize, keys: &[i32]) -> Vec<u8> {
let mut code = vec![0; pc];
code.push(0xab);
while !code.len().is_multiple_of(4) {
code.push(0);
}
code.extend_from_slice(&0i32.to_be_bytes());
code.extend_from_slice(&(keys.len() as i32).to_be_bytes());
for key in keys {
code.extend_from_slice(&key.to_be_bytes());
code.extend_from_slice(&0i32.to_be_bytes());
}
code
}
#[test]
fn lookup_keys_must_increase_strictly() {
for keys in [&[1, 1][..], &[1, 0], &[0, -1], &[i32::MIN, i32::MAX, i32::MIN]] {
for pc in 0..4 {
let mut code = lookup(pc, keys);
code.push(0xb1);
assert!(decode_one(&code, pc).is_none(), "pc {pc}, keys {keys:?}");
let (decoded, complete) = decode(&code, 100);
assert!(!complete);
assert_eq!(decoded.len(), pc, "preserve preceding nops, stop before the bad switch");
}
}
}
#[test]
fn lookup_keys_use_signed_order_at_every_alignment() {
for keys in [&[][..], &[i32::MIN, -1, 0, i32::MAX]] {
for pc in 0..4 {
let code = lookup(pc, keys);
let insn = decode_one(&code, pc).unwrap();
assert_eq!(insn.len as usize, code.len() - pc);
let switch = insn.switch.unwrap();
assert_eq!(switch.default, pc as i64);
assert_eq!(switch.pairs, keys.iter().map(|&key| (key, pc as i64)).collect::<Vec<_>>());
assert!(decode(&code, 100).1);
}
}
}
#[test]
fn switch_payloads_must_be_complete() {
for pc in 0..4 {
let lookup = lookup(pc, &[-1, 1]);
let mut dense = vec![0; pc];
dense.push(0xaa);
while !dense.len().is_multiple_of(4) {
dense.push(0);
}
for word in [0i32, i32::MAX - 1, i32::MAX, 0, 0] {
dense.extend_from_slice(&word.to_be_bytes());
}
for code in [lookup, dense] {
assert!(decode_one(&code, pc).is_some());
for end in pc + 1..code.len() {
assert!(decode_one(&code[..end], pc).is_none(), "pc {pc}, end {end}");
}
}
}
}
#[test]
fn switch_counts_cannot_reserve_an_absent_table() {
let mut lookup = lookup(0, &[]);
lookup[8..12].copy_from_slice(&(MAX_SWITCH as i32).to_be_bytes());
assert!(decode_one(&lookup, 0).is_none());
for (low, high) in [(0i32, MAX_SWITCH as i32 - 1), (i32::MIN, i32::MAX)] {
let mut dense = vec![0xaa, 0, 0, 0];
for word in [0, low, high] {
dense.extend_from_slice(&word.to_be_bytes());
}
assert!(decode_one(&dense, 0).is_none());
}
}
#[test]
fn table_covers_defined_opcodes() {
let mut named = 0;
for b in 0..=255u8 {
if opcode(b).name != "unknown" {
named += 1;
}
}
// 0x00..=0xca is 203 opcodes, plus impdep1/impdep2.
assert_eq!(named, 203 + 2);
assert_eq!(opcode(0xb6).name, "invokevirtual");
assert_eq!(opcode(0x10).name, "bipush");
assert_eq!(opcode(0xc4).name, "wide");
}
#[test]
fn decodes_core_formats() {
// iconst_1; bipush 7; istore_1; goto +3 ; (pad to reach len) return
let code = [0x04, 0x10, 0x07, 0x3c, 0xa7, 0x00, 0x03, 0xb1];
let (ins, complete) = decode(&code, 100);
assert!(complete, "{ins:?}");
assert_eq!(ins[0].name, "iconst_1");
assert_eq!(ins[1].name, "bipush");
assert_eq!(ins[1].int, Some(7));
assert_eq!(ins[2].name, "istore_1");
assert_eq!(ins[3].name, "goto");
assert_eq!(ins[3].branch, Some(7)); // pc 4 + 3
assert_eq!(ins[4].name, "return");
}
#[test]
fn decodes_invoke_and_wide() {
// invokevirtual #5 ; invokeinterface #6 count 2 ; wide iload 300
let code = [0xb6, 0x00, 0x05, 0xb9, 0x00, 0x06, 0x02, 0x00, 0xc4, 0x15, 0x01, 0x2c];
let (ins, complete) = decode(&code, 100);
assert!(complete);
assert_eq!(ins[0].name, "invokevirtual");
assert_eq!(ins[0].cp_index, Some(5));
assert_eq!(ins[0].len, 3);
assert_eq!(ins[1].name, "invokeinterface");
assert_eq!(ins[1].cp_index, Some(6));
assert_eq!(ins[1].len, 5);
assert_eq!(ins[2].name, "iload");
assert!(ins[2].wide);
assert_eq!(ins[2].local, Some(300));
assert_eq!(ins[2].len, 4);
}
#[test]
fn decodes_switches() {
// tableswitch at pc 0: pad 3, default +40, low 1, high 2, offsets +10, +20
let mut code = vec![0xaa, 0, 0, 0];
code.extend_from_slice(&40i32.to_be_bytes());
code.extend_from_slice(&1i32.to_be_bytes());
code.extend_from_slice(&2i32.to_be_bytes());
code.extend_from_slice(&10i32.to_be_bytes());
code.extend_from_slice(&20i32.to_be_bytes());
let i = decode_one(&code, 0).unwrap();
assert_eq!(i.name, "tableswitch");
let sw = i.switch.unwrap();
assert_eq!(sw.default, 40);
assert_eq!(sw.pairs, vec![(1, 10), (2, 20)]);
assert_eq!(i.len as usize, code.len());
// lookupswitch at pc 0: pad 3, default +4, npairs 1, (key 99 -> +8)
let mut lk = vec![0xab, 0, 0, 0];
lk.extend_from_slice(&4i32.to_be_bytes());
lk.extend_from_slice(&1i32.to_be_bytes());
lk.extend_from_slice(&99i32.to_be_bytes());
lk.extend_from_slice(&8i32.to_be_bytes());
let l = decode_one(&lk, 0).unwrap();
let sw = l.switch.unwrap();
assert_eq!(sw.default, 4);
assert_eq!(sw.pairs, vec![(99, 8)]);
}
#[test]
fn hostile() {
for seed in 0..256 {
let n = crate::test_support::noise(seed, 512);
let _ = decode(&n, 10_000);
}
// truncated operands never panic
let _ = decode(&[0xb6, 0x00], 10);
let _ = decode(&[0xaa, 0, 0, 0, 0, 0, 0, 0], 10);
let _ = decode(&[0xab, 0, 0, 0, 0, 0, 0, 0, 0x7f, 0xff, 0xff, 0xff], 10);
let _ = decode(&[0xc4], 10);
}
}
+50
View File
@@ -0,0 +1,50 @@
#![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)]
#![forbid(unsafe_code)]
//! Java class-file inspection and JVM bytecode decoding. Never executes bytecode.
//! Retains source item, attribute and annotation-depth limits and partial reports.
mod bytes;
mod descriptor;
pub mod java_class;
pub mod java_ops;
pub use java_class::*;
#[cfg(test)]
mod test_support;
/// File admission errors; damaged optional structures retain partial-report warnings.
#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
pub enum JavaClassError {
#[error("the file ends early ({0})")]
Truncated(String),
#[error("the file is malformed ({0})")]
Malformed(String),
#[error("not supported: {0}")]
Unsupported(String),
}
use JavaClassError as FormatError;
#[cfg(test)]
#[path = "regressions/java_array_operands.rs"]
mod java_array_operands;
#[cfg(test)]
#[path = "regressions/java_attribute_names.rs"]
mod java_attribute_names;
#[cfg(test)]
#[path = "regressions/java_constant_pool_slots.rs"]
mod java_constant_pool_slots;
#[cfg(test)]
#[path = "regressions/java_invoke_operands.rs"]
mod java_invoke_operands;
#[cfg(test)]
#[path = "regressions/java_linkage_references.rs"]
mod java_linkage_references;
#[cfg(test)]
#[path = "regressions/java_truncated_attributes.rs"]
mod java_truncated_attributes;
#[cfg(test)]
#[path = "regressions/java_wide_opcodes.rs"]
mod java_wide_opcodes;
@@ -0,0 +1,48 @@
use crate::java_ops::{decode, decode_one};
#[test]
fn invalid_primitive_array_types_stop_before_the_allocation() {
for atype in (0..=u8::MAX).filter(|value| !(4..=11).contains(value)) {
assert!(decode_one(&[0xbc, atype], 0).is_none(), "atype {atype}");
let (instructions, complete) = decode(&[0, 0xbc, atype, 0xb1], 100);
assert!(!complete, "atype {atype}");
assert_eq!(instructions.len(), 1);
assert_eq!(instructions[0].name, "nop");
}
}
#[test]
fn zero_dimension_multidimensional_allocations_are_not_complete_bytecode() {
assert!(decode_one(&[0xc5, 0, 1, 0], 0).is_none());
let (instructions, complete) = decode(&[0, 0xc5, 0, 1, 0, 0xb1], 100);
assert!(!complete);
assert_eq!(instructions.len(), 1);
assert_eq!(instructions[0].name, "nop");
}
#[test]
fn every_defined_primitive_type_and_nonzero_dimension_remains_decodable() {
for atype in 4..=11 {
let (instructions, complete) = decode(&[0xbc, atype, 0xb1], 100);
assert!(complete);
assert_eq!(instructions.len(), 2);
assert_eq!(instructions[0].int, Some(i32::from(atype)));
assert_eq!(instructions[0].len, 2);
}
for dimensions in 1..=u8::MAX {
let instruction = decode_one(&[0, 0xc5, 0x12, 0x34, dimensions], 1).unwrap();
assert_eq!(instruction.pc, 1);
assert_eq!(instruction.cp_index, Some(0x1234));
assert_eq!(instruction.int, Some(i32::from(dimensions)));
assert_eq!(instruction.len, 4);
}
}
#[test]
fn incomplete_array_operands_remain_rejected() {
for instruction in [&[0xbc, 10][..], &[0xc5, 0, 1, 2][..]] {
for end in 1..instruction.len() {
assert!(decode_one(&instruction[..end], 0).is_none());
}
}
}
@@ -0,0 +1,132 @@
use crate::java_class::{self, ClassFile, Const};
#[derive(Clone, Copy, Debug)]
enum Scope {
Class,
Field,
Method,
Code,
}
fn u16b(out: &mut Vec<u8>, n: u16) {
out.extend_from_slice(&n.to_be_bytes());
}
fn u32b(out: &mut Vec<u8>, n: u32) {
out.extend_from_slice(&n.to_be_bytes());
}
fn utf8(out: &mut Vec<u8>, text: &str) {
out.push(1);
u16b(out, text.len() as u16);
out.extend_from_slice(text.as_bytes());
}
fn attr(name: u16, info: &[u8]) -> Vec<u8> {
let mut out = Vec::new();
u16b(&mut out, name);
u32b(&mut out, info.len() as u32);
out.extend_from_slice(info);
out
}
fn attributes(out: &mut Vec<u8>, repeated: u16, known: &[Vec<u8>]) {
u16b(out, repeated + known.len() as u16);
for _ in 0..repeated {
out.extend_from_slice(&attr(5, &[]));
}
for bytes in known {
out.extend_from_slice(bytes);
}
}
// A valid shared CONSTANT_Utf8 is named by every unknown attribute. Known
// attributes follow it, so avoiding name copies must not discard their facts.
fn fixture(scope: Scope, repeated: u16) -> Vec<u8> {
let mut out = vec![0xca, 0xfe, 0xba, 0xbe, 0, 0, 0, 52];
u16b(&mut out, 17);
utf8(&mut out, "AttributeFixture"); // 1
out.push(7);
u16b(&mut out, 1); // 2: this class
utf8(&mut out, "java/lang/Object"); // 3
out.push(7);
u16b(&mut out, 3); // 4: superclass
utf8(&mut out, &format!("org.example.{}", "A".repeat(usize::from(u16::MAX) - 12))); // 5
for text in ["SourceFile", "AttributeFixture.java", "field", "I"] {
utf8(&mut out, text); // 6..9
}
out.push(3);
u32b(&mut out, 42); // 10
for text in ["ConstantValue", "run", "()V", "Code", "LineNumberTable", "Deprecated"] {
utf8(&mut out, text); // 11..16
}
for word in [0x0021, 2, 4, 0, 1, 0x0019, 8, 9] {
u16b(&mut out, word);
}
attributes(&mut out, if matches!(scope, Scope::Field) { repeated } else { 0 }, &[attr(11, &10u16.to_be_bytes()), attr(16, &[])]);
for word in [1, 0x0009, 12, 13] {
u16b(&mut out, word);
}
let mut code = vec![0, 0, 0, 0, 0, 0, 0, 1, 0xb1, 0, 0];
attributes(&mut code, if matches!(scope, Scope::Code) { repeated } else { 0 }, &[attr(15, &[0, 1, 0, 0, 0, 7])]);
attributes(&mut out, if matches!(scope, Scope::Method) { repeated } else { 0 }, &[attr(14, &code)]);
attributes(&mut out, if matches!(scope, Scope::Class) { repeated } else { 0 }, &[attr(6, &7u16.to_be_bytes())]);
out
}
fn check_facts(parsed: &ClassFile) {
assert!(parsed.warnings.is_empty(), "{:?}", parsed.warnings);
assert_eq!(parsed.this_class, "AttributeFixture");
assert_eq!(parsed.super_class.as_deref(), Some("java/lang/Object"));
assert_eq!(parsed.source_file.as_deref(), Some("AttributeFixture.java"));
assert_eq!(parsed.fields.len(), 1);
assert_eq!(parsed.fields[0].name, "field");
assert_eq!(parsed.fields[0].constant_value.as_deref(), Some("42"));
assert!(parsed.fields[0].deprecated);
assert_eq!(parsed.methods.len(), 1);
assert_eq!(parsed.methods[0].name, "run");
let code = parsed.methods[0].code.as_ref().unwrap();
assert_eq!(code.bytecode, [0xb1]);
assert_eq!(code.line_numbers, [(0, 7)]);
assert!(matches!(&parsed.pool[5], Const::Utf8(name) if name.len() == usize::from(u16::MAX)));
}
#[test]
fn known_attributes_survive_repeated_unknown_names_at_every_scope() {
for scope in [Scope::Class, Scope::Field, Scope::Method, Scope::Code] {
check_facts(&java_class::parse(&fixture(scope, 64)).unwrap());
}
}
fn memory_case(scope: Scope) {
let bytes = fixture(scope, 4096);
assert!(bytes.len() < 100_000);
check_facts(&java_class::parse(&bytes).unwrap());
}
// Run each ignored case separately with a 128 MiB process address-space limit.
// The original parser copies 256 MiB of one attribute name; the fixture itself
// is under 100 KiB. These checks deliberately make no timing assertion.
#[test]
#[ignore = "run separately under a process memory limit"]
fn repeated_class_attribute_names_fit_in_bounded_memory() {
memory_case(Scope::Class);
}
#[test]
#[ignore = "run separately under a process memory limit"]
fn repeated_field_attribute_names_fit_in_bounded_memory() {
memory_case(Scope::Field);
}
#[test]
#[ignore = "run separately under a process memory limit"]
fn repeated_method_attribute_names_fit_in_bounded_memory() {
memory_case(Scope::Method);
}
#[test]
#[ignore = "run separately under a process memory limit"]
fn repeated_code_attribute_names_fit_in_bounded_memory() {
memory_case(Scope::Code);
}
@@ -0,0 +1,53 @@
use crate::{FormatError, java_class};
fn class_with_pool(count: u16, pool: &[u8]) -> Vec<u8> {
let mut bytes = vec![0xca, 0xfe, 0xba, 0xbe, 0, 0, 0, 52];
bytes.extend_from_slice(&count.to_be_bytes());
bytes.extend_from_slice(pool);
bytes.extend_from_slice(&[0; 14]);
bytes
}
#[test]
fn a_wide_constant_needs_its_reserved_slot() {
for tag in [5, 6] {
let mut pool = vec![tag];
pool.extend_from_slice(&[0; 8]);
let bytes = class_with_pool(2, &pool);
assert!(matches!(java_class::parse(&bytes), Err(FormatError::Malformed(message)) if message.contains("second slot")));
}
}
#[test]
fn the_largest_pool_cannot_overflow_on_a_trailing_wide_constant() {
for tag in [5, 6] {
let mut pool = [3, 0, 0, 0, 0].repeat(usize::from(u16::MAX) - 2);
pool.push(tag);
pool.extend_from_slice(&[0; 8]);
let bytes = class_with_pool(u16::MAX, &pool);
assert!(matches!(java_class::parse(&bytes), Err(FormatError::Malformed(message)) if message.contains("second slot")));
}
}
#[test]
fn a_wide_constant_with_two_remaining_slots_is_retained() {
for tag in [5, 6] {
for count in [3, u16::MAX] {
let mut pool = [3, 0, 0, 0, 0].repeat(usize::from(count) - 3);
pool.push(tag);
pool.extend_from_slice(&[0; 8]);
let parsed = java_class::parse(&class_with_pool(count, &pool)).unwrap();
assert_eq!(parsed.pool.len(), usize::from(count));
assert!(matches!(parsed.pool.last(), Some(java_class::Const::Unusable)));
assert!(matches!(parsed.pool[usize::from(count) - 2], java_class::Const::Long(_) | java_class::Const::Double(_)));
}
}
}
#[test]
fn ordinary_final_constants_and_existing_classes_still_parse() {
let parsed = java_class::parse(&class_with_pool(2, &[3, 0, 0, 0, 7])).unwrap();
assert_eq!(parsed.pool, vec![java_class::Const::Unusable, java_class::Const::Integer(7)]);
let parsed = java_class::parse(&crate::test_support::java::hello_class()).unwrap();
assert!(!parsed.methods.is_empty());
}
@@ -0,0 +1,76 @@
use crate::java_class;
use crate::java_ops::{decode, decode_one};
#[test]
fn invokeinterface_requires_a_count_and_zero_reserved_byte() {
for code in [[0xb9, 0, 1, 0, 0], [0xb9, 0, 1, 1, 1], [0xb9, 0, 1, 255, 255]] {
assert!(decode_one(&code, 0).is_none(), "{code:?}");
assert!(!decode(&code, 16).1);
}
}
#[test]
fn invokedynamic_requires_both_reserved_bytes_to_be_zero() {
for code in [[0xba, 0, 1, 1, 0], [0xba, 0, 1, 0, 1], [0xba, 0, 1, 255, 255]] {
assert!(decode_one(&code, 0).is_none(), "{code:?}");
assert!(!decode(&code, 16).1);
}
}
#[test]
fn valid_and_truncated_invocations_keep_their_boundaries() {
for count in [1, 2, 255] {
let instruction = decode_one(&[0xb9, 0x12, 0x34, count, 0], 0).unwrap();
assert_eq!(instruction.cp_index, Some(0x1234));
assert_eq!(instruction.len, 5);
}
let instruction = decode_one(&[0xba, 0x12, 0x34, 0, 0], 0).unwrap();
assert_eq!(instruction.cp_index, Some(0x1234));
for code in [[0xb9, 0, 1, 1, 0], [0xba, 0, 1, 0, 0]] {
for len in 1..5 {
assert!(decode_one(&code[..len], 0).is_none());
}
}
let (instructions, complete) = decode(&[0xb9, 0, 1, 1, 0, 0xba, 0, 2, 0, 0, 0xb1], 16);
assert!(complete);
assert_eq!(instructions.len(), 3);
assert_eq!(instructions[2].pc, 10);
}
fn reference_class() -> java_class::ClassFile {
let mut class = java_class::parse(&crate::test_support::java::hello_class()).unwrap();
class.methods.retain(|method| method.name == "run");
class
}
#[test]
fn malformed_invocations_mark_reference_scans_incomplete() {
let valid = reference_class();
let (expected, incomplete) = java_class::references(&valid, "java/io/PrintStream", None, 10);
assert!(!incomplete);
assert_eq!(expected.len(), 1);
for invalid in [[0xb9, 0, 1, 0, 0], [0xb9, 0, 1, 1, 1], [0xba, 0, 1, 1, 0], [0xba, 0, 1, 0, 1]] {
let mut class = valid.clone();
let code = &mut class.methods[0].code.as_mut().unwrap().bytecode;
let later_reference = code.clone();
*code = invalid.to_vec();
code.extend_from_slice(&later_reference);
let (found, incomplete) = java_class::references(&class, "java/io/PrintStream", None, 10);
assert!(found.is_empty());
assert!(incomplete, "invalid invocation must not hide an unfinished reference scan: {invalid:?}");
}
}
#[test]
fn incomplete_scans_keep_earlier_references_and_scan_other_methods() {
let mut class = reference_class();
let mut later_method = class.methods[0].clone();
later_method.name = "later".into();
class.methods[0].code.as_mut().unwrap().bytecode.extend_from_slice(&[0xba, 0, 1, 1, 0]);
class.methods.push(later_method);
let (found, incomplete) = java_class::references(&class, "java/io/PrintStream", None, 10);
assert!(incomplete);
assert_eq!(found.len(), 2);
assert!(found[0].caller.contains(".run:("));
assert!(found[1].caller.contains(".later:("));
}
@@ -0,0 +1,97 @@
use crate::java_class::{parse, references};
/// A method with a chosen load or call, plus a dynamic call site and a dynamic constant with distinct bootstrap signatures.
fn class(code: &[u8]) -> Vec<u8> {
fn utf(s: &str) -> Vec<u8> {
let mut b = vec![1];
b.extend((s.len() as u16).to_be_bytes());
b.extend(s.bytes());
b
}
let pool = [
utf("Uses"),
vec![7, 0, 1],
utf("java/lang/Object"),
vec![7, 0, 3],
utf("run"),
utf("()V"),
utf("Code"),
utf("BootstrapMethods"),
utf("Target"),
vec![7, 0, 9],
utf("apply"),
vec![12, 0, 11, 0, 6],
vec![10, 0, 10, 0, 12],
vec![15, 6, 0, 13],
utf("Factory"),
vec![7, 0, 15],
utf("boot"),
vec![12, 0, 17, 0, 28],
vec![10, 0, 16, 0, 18],
vec![15, 6, 0, 19],
utf("([LTarget;)V"),
vec![16, 0, 21],
vec![18, 0, 0, 0, 12],
utf("value"),
utf("I"),
vec![12, 0, 24, 0, 25],
vec![17, 0, 1, 0, 26],
utf(
"(Ljava/lang/invoke/MethodHandles$Lookup;Ljava/lang/String;Ljava/lang/invoke/MethodType;Ljava/lang/invoke/MethodHandle;)Ljava/lang/invoke/CallSite;",
),
utf("(Ljava/lang/invoke/MethodHandles$Lookup;Ljava/lang/String;Ljava/lang/Class;)I"),
vec![12, 0, 17, 0, 29],
vec![10, 0, 16, 0, 30],
vec![15, 6, 0, 31],
];
let mut bytes = vec![0xca, 0xfe, 0xba, 0xbe, 0, 0, 0, 55];
bytes.extend((pool.len() as u16 + 1).to_be_bytes());
for e in pool {
bytes.extend(e);
}
bytes.extend([0, 0x21, 0, 2, 0, 4, 0, 0, 0, 0, 0, 1, 0, 9, 0, 5, 0, 6, 0, 1, 0, 7]);
bytes.extend(((12 + code.len()) as u32).to_be_bytes());
bytes.extend([0, 3, 0, 0]);
bytes.extend((code.len() as u32).to_be_bytes());
bytes.extend(code);
bytes.extend([0, 0, 0, 0]);
let boots = [0, 2, 0, 20, 0, 1, 0, 14, 0, 32, 0, 0];
bytes.extend([0, 1, 0, 8]);
bytes.extend((boots.len() as u32).to_be_bytes());
bytes.extend(boots);
bytes
}
fn kinds(code: &[u8], owner: &str, method: Option<&str>) -> Vec<&'static str> {
let cf = parse(&class(code)).unwrap();
let (hits, partial) = references(&cf, owner, method, 10);
assert!(!partial);
hits.into_iter().map(|r| r.kind).collect()
}
#[test]
fn class_literal_has_a_use_site() {
assert_eq!(kinds(&[0x12, 10, 0x57, 0xb1], "Target", None), ["type"]);
}
#[test]
fn literal_method_handle_finds_its_member() {
assert_eq!(kinds(&[0x12, 14, 0x57, 0xb1], "Target", Some("apply")), ["method-handle"]);
}
#[test]
fn method_type_mentions_object_array_components() {
assert_eq!(kinds(&[0x12, 22, 0x57, 0xb1], "Target", None), ["method-type"]);
}
#[test]
fn dynamic_call_exposes_factory_dependency() {
assert_eq!(kinds(&[0xba, 0, 23, 0, 0, 0xb1], "Factory", Some("boot")), ["bootstrap-method"]);
}
#[test]
fn dynamic_call_exposes_static_method_handle_argument() {
assert_eq!(kinds(&[0xba, 0, 23, 0, 0, 0xb1], "Target", Some("apply")), ["method-handle"]);
}
#[test]
fn dynamic_constant_exposes_bootstrap_dependency() {
assert_eq!(kinds(&[0x12, 27, 0x57, 0xb1], "Factory", Some("boot")), ["bootstrap-method"]);
}
#[test]
fn unused_bootstrap_does_not_introduce_a_reference() {
assert!(kinds(&[0xb1], "Factory", None).is_empty());
}
@@ -0,0 +1,46 @@
use crate::java_class::parse;
use crate::test_support::java::hello_class;
/// The fixture ends in a class attribute count and a single two-byte SourceFile attribute.
const ATTRIBUTE_TABLE_BYTES: usize = 10;
/// Every cut of the attribute count, header or body leaves a partial class report.
#[test]
fn incomplete_class_attribute_table_reports_a_warning() {
let data = hello_class();
let start = data.len() - ATTRIBUTE_TABLE_BYTES;
for end in start..data.len() {
let class = parse(&data[..end]).unwrap();
assert_eq!(class.methods.len(), 4);
assert!(class.source_file.is_none());
assert!(class.warnings.iter().any(|warning| warning.contains("class attribute table")), "cut at {}", end - start);
}
}
/// A complete attribute stays available when a subsequent attribute is cut short.
#[test]
fn completed_class_attributes_survive_a_truncated_record() {
let mut data = hello_class();
let start = data.len() - ATTRIBUTE_TABLE_BYTES;
data[start..start + 2].copy_from_slice(&2u16.to_be_bytes());
data.extend_from_slice(&[0, 1, 0, 0, 0, 2, 0]);
let class = parse(&data).unwrap();
assert_eq!(class.source_file.as_deref(), Some("Hello.java"));
assert!(class.warnings.iter().any(|warning| warning.contains("class attribute table")));
}
/// Complete, empty and unknown class attributes do not trigger a truncation warning.
#[test]
fn complete_class_attribute_tables_are_accepted() {
let mut data = hello_class();
let start = data.len() - ATTRIBUTE_TABLE_BYTES;
let original = parse(&data).unwrap();
assert_eq!(original.source_file.as_deref(), Some("Hello.java"));
assert!(original.warnings.is_empty());
data[start..start + 2].copy_from_slice(&2u16.to_be_bytes());
data.extend_from_slice(&[0, 1, 0, 0, 0, 1, 0]);
assert!(parse(&data).unwrap().warnings.is_empty());
data.truncate(start + 2);
data[start..].fill(0);
assert!(parse(&data).unwrap().warnings.is_empty());
}
@@ -0,0 +1,33 @@
use crate::java_ops::{decode, decode_one};
#[test]
fn only_defined_wide_opcodes_are_accepted() {
for op in 0..=255u8 {
let valid = matches!(op, 0x15..=0x19 | 0x36..=0x3a | 0x84 | 0xa9);
let code = [0xc4, op, 0x01, 0x2c, 0xff, 0xfe];
assert_eq!(decode_one(&code, 0).is_some(), valid, "opcode {op:#x}");
}
}
#[test]
fn invalid_wide_does_not_invent_a_method_body() {
let (instructions, complete) = decode(&[0x00, 0xc4, 0xb1, 0, 1, 0xb1], 32);
assert!(!complete);
assert_eq!(instructions.len(), 1);
assert_eq!(instructions[0].name, "nop");
}
#[test]
fn wide_locals_and_signed_increments_are_preserved() {
for op in [0x15, 0x16, 0x17, 0x18, 0x19, 0x36, 0x37, 0x38, 0x39, 0x3a, 0xa9] {
let instruction = decode_one(&[0xc4, op, 0xff, 0xff], 0).unwrap();
assert_eq!(instruction.local, Some(u16::MAX));
assert_eq!(instruction.len, 4);
assert!(instruction.wide);
}
let instruction = decode_one(&[0xc4, 0x84, 0x01, 0x2c, 0xff, 0xfe], 0).unwrap();
assert_eq!(instruction.local, Some(300));
assert_eq!(instruction.int, Some(-2));
assert_eq!(instruction.len, 6);
assert!(decode_one(&[0xc4, 0x84, 0x00, 1], 0).is_none());
}
+316
View File
@@ -0,0 +1,316 @@
/// Deterministic pseudo-random bytes (xorshift) for fuzz-like loops.
pub fn noise(seed: u64, len: usize) -> Vec<u8> {
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<Vec<u8>> {
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 java {
use std::collections::HashMap;
/// A constant-pool builder that interns entries and tracks the double slot after `Long`/`Double`.
#[derive(Default)]
struct Pool {
items: Vec<Vec<u8>>,
/// Next free index (1-based; accounts for long/double taking two slots).
count: u16,
cache: HashMap<String, u16>,
}
impl Pool {
fn new() -> Self {
Pool { items: Vec::new(), count: 1, cache: HashMap::new() }
}
fn add(&mut self, bytes: Vec<u8>, slots: u16) -> u16 {
let idx = self.count;
self.items.push(bytes);
self.count += slots;
idx
}
fn utf8(&mut self, s: &str) -> u16 {
let key = format!("u:{s}");
if let Some(&i) = self.cache.get(&key) {
return i;
}
let mut b = vec![1u8];
b.extend_from_slice(&(s.len() as u16).to_be_bytes());
b.extend_from_slice(s.as_bytes());
let i = self.add(b, 1);
self.cache.insert(key, i);
i
}
fn class(&mut self, name: &str) -> u16 {
let n = self.utf8(name);
let key = format!("c:{name}");
if let Some(&i) = self.cache.get(&key) {
return i;
}
let mut b = vec![7u8];
b.extend_from_slice(&n.to_be_bytes());
let i = self.add(b, 1);
self.cache.insert(key, i);
i
}
fn string(&mut self, s: &str) -> u16 {
let u = self.utf8(s);
let mut b = vec![8u8];
b.extend_from_slice(&u.to_be_bytes());
self.add(b, 1)
}
fn nat(&mut self, name: &str, desc: &str) -> u16 {
let n = self.utf8(name);
let d = self.utf8(desc);
let mut b = vec![12u8];
b.extend_from_slice(&n.to_be_bytes());
b.extend_from_slice(&d.to_be_bytes());
self.add(b, 1)
}
fn reff(&mut self, tag: u8, owner: &str, name: &str, desc: &str) -> u16 {
let c = self.class(owner);
let nt = self.nat(name, desc);
let mut b = vec![tag];
b.extend_from_slice(&c.to_be_bytes());
b.extend_from_slice(&nt.to_be_bytes());
self.add(b, 1)
}
fn long(&mut self, v: i64) -> u16 {
let mut b = vec![5u8];
b.extend_from_slice(&v.to_be_bytes());
self.add(b, 2)
}
/// The serialized constant pool and the count field.
fn finish(&self) -> (Vec<u8>, u16) {
(self.items.concat(), self.count)
}
}
fn u16b(v: &mut Vec<u8>, x: u16) {
v.extend_from_slice(&x.to_be_bytes());
}
fn u32b(v: &mut Vec<u8>, x: u32) {
v.extend_from_slice(&x.to_be_bytes());
}
/// Build an attribute: name_index, length, body.
fn attr(name_idx: u16, body: Vec<u8>) -> Vec<u8> {
let mut v = Vec::new();
u16b(&mut v, name_idx);
u32b(&mut v, body.len() as u32);
v.extend_from_slice(&body);
v
}
/// A method's `Code` attribute body (max_stack, max_locals, code, exception table, no nested attrs).
fn code_body(max_stack: u16, max_locals: u16, code: &[u8], exc: &[(u16, u16, u16, u16)]) -> Vec<u8> {
let mut v = Vec::new();
u16b(&mut v, max_stack);
u16b(&mut v, max_locals);
u32b(&mut v, code.len() as u32);
v.extend_from_slice(code);
u16b(&mut v, exc.len() as u16);
for (s, e, h, t) in exc {
u16b(&mut v, *s);
u16b(&mut v, *e);
u16b(&mut v, *h);
u16b(&mut v, *t);
}
u16b(&mut v, 0); // nested attributes count
v
}
/// A method_info: access, name, descriptor, and one already-built Code attribute.
fn method(p: &mut Pool, access: u16, name: &str, desc: &str, code_attribute: Vec<u8>) -> Vec<u8> {
let name_idx = p.utf8(name);
let desc_idx = p.utf8(desc);
let mut v = Vec::new();
u16b(&mut v, access);
u16b(&mut v, name_idx);
u16b(&mut v, desc_idx);
u16b(&mut v, 1); // one attribute
v.extend_from_slice(&code_attribute);
v
}
/// Assemble a whole class from its parts.
#[allow(clippy::too_many_arguments)]
fn assemble(
pool: &Pool,
access: u16,
this_c: u16,
super_c: u16,
interfaces: &[u16],
fields: &[Vec<u8>],
methods: &[Vec<u8>],
class_attrs: &[Vec<u8>],
) -> Vec<u8> {
let (cp, count) = pool.finish();
let mut v = Vec::new();
v.extend_from_slice(&[0xca, 0xfe, 0xba, 0xbe]);
u16b(&mut v, 0); // minor
u16b(&mut v, 52); // major (Java 8)
u16b(&mut v, count);
v.extend_from_slice(&cp);
u16b(&mut v, access);
u16b(&mut v, this_c);
u16b(&mut v, super_c);
u16b(&mut v, interfaces.len() as u16);
for i in interfaces {
u16b(&mut v, *i);
}
u16b(&mut v, fields.len() as u16);
for f in fields {
v.extend_from_slice(f);
}
u16b(&mut v, methods.len() as u16);
for m in methods {
v.extend_from_slice(m);
}
u16b(&mut v, class_attrs.len() as u16);
for a in class_attrs {
v.extend_from_slice(a);
}
v
}
pub const HELLO: &str = "Hello, Craft!";
/// `public class com.example.Hello implements Runnable` with a `count` field, a `BIG` long
/// constant, `<init>`, `run()` (System.out.println("Hello, Craft!")), `pick(int)` (a tableswitch)
/// and `guarded()` (a try/catch over the println call).
pub fn hello_class() -> Vec<u8> {
let mut p = Pool::new();
let this_c = p.class("com/example/Hello");
let obj_c = p.class("java/lang/Object");
let runnable_c = p.class("java/lang/Runnable");
let code_attr = p.utf8("Code");
// fields: int count; static final long BIG;
let count_name = p.utf8("count");
let i_desc = p.utf8("I");
let big_name = p.utf8("BIG");
let j_desc = p.utf8("J");
let constval_attr = p.utf8("ConstantValue");
let big_val = p.long(0x1122_3344_5566_7788);
// refs used by code
let obj_init = p.reff(10, "java/lang/Object", "<init>", "()V");
let sysout = p.reff(9, "java/lang/System", "out", "Ljava/io/PrintStream;");
let hello = p.string(HELLO);
let println = p.reff(10, "java/io/PrintStream", "println", "(Ljava/lang/String;)V");
let rt_exc = p.class("java/lang/RuntimeException");
// <init>(): aload_0; invokespecial Object.<init>; return
let mut init = vec![0x2a, 0xb7];
init.extend_from_slice(&obj_init.to_be_bytes());
init.push(0xb1);
let init_m = method(&mut p, 0x0001, "<init>", "()V", attr(code_attr, code_body(1, 1, &init, &[])));
// run(): getstatic System.out; ldc "Hello"; invokevirtual println; return
let mut run = vec![0xb2];
run.extend_from_slice(&sysout.to_be_bytes());
run.push(0x12);
run.push(hello as u8); // ldc (1-byte index; pool is small)
run.push(0xb6);
run.extend_from_slice(&println.to_be_bytes());
run.push(0xb1);
let run_m = method(&mut p, 0x0001, "run", "()V", attr(code_attr, code_body(2, 1, &run, &[])));
// pick(int): iload_0; tableswitch{0->L0,1->L1,default->Ldef}; L0: bipush 10; ireturn; L1: bipush 20; ireturn; Ldef: iconst_m1; ireturn
// offsets: iload_1@0; tableswitch@1 (pad 2) ends @24; L0@24; L1@27; Ldef@30
let mut pick = vec![0x1b, 0xaa, 0x00, 0x00];
u32b(&mut pick, 29); // default -> 1+29 = 30
u32b(&mut pick, 0); // low
u32b(&mut pick, 1); // high
u32b(&mut pick, 23); // case 0 -> 1+23 = 24
u32b(&mut pick, 26); // case 1 -> 1+26 = 27
debug_assert_eq!(pick.len(), 24);
pick.extend_from_slice(&[0x10, 10, 0xac]); // @24: bipush 10; ireturn
pick.extend_from_slice(&[0x10, 20, 0xac]); // @27: bipush 20; ireturn
pick.extend_from_slice(&[0x02, 0xac]); // @30: iconst_m1; ireturn
let pick_m = method(&mut p, 0x0001, "pick", "(I)I", attr(code_attr, code_body(1, 1, &pick, &[])));
// guarded(): try { System.out.println("Hello"); } catch (RuntimeException e) {} (then return)
// 0: getstatic(3) ; 3: ldc(2) ; 5: invokevirtual(3) ; 8: goto +5 ->13 ; 11: astore_1 ; 12: return ; 13: return
let mut g = vec![0xb2];
g.extend_from_slice(&sysout.to_be_bytes());
g.push(0x12);
g.push(hello as u8);
g.push(0xb6);
g.extend_from_slice(&println.to_be_bytes());
g.extend_from_slice(&[0xa7, 0x00, 0x05]); // @8 goto -> 13
g.push(0x4c); // @11 astore_1
g.push(0xb1); // @12 return
g.push(0xb1); // @13 return
let guarded_m = method(&mut p, 0x0001, "guarded", "()V", attr(code_attr, code_body(2, 2, &g, &[(0, 8, 11, rt_exc)])));
// field infos
let field = |p: &mut Pool, access: u16, name_idx: u16, desc_idx: u16, attrs: &[Vec<u8>]| -> Vec<u8> {
let _ = p;
let mut v = Vec::new();
u16b(&mut v, access);
u16b(&mut v, name_idx);
u16b(&mut v, desc_idx);
u16b(&mut v, attrs.len() as u16);
for a in attrs {
v.extend_from_slice(a);
}
v
};
let count_f = field(&mut p, 0x0002, count_name, i_desc, &[]); // private int count
let mut cv = Vec::new();
u16b(&mut cv, big_val);
let big_f = field(&mut p, 0x0019, big_name, j_desc, &[attr(constval_attr, cv)]); // public static final long BIG
let source_attr = p.utf8("SourceFile");
let source_val = p.utf8("Hello.java");
let mut sf = Vec::new();
u16b(&mut sf, source_val);
let source = attr(source_attr, sf);
assemble(
&p,
0x0021, // public super
this_c,
obj_c,
&[runnable_c],
&[count_f, big_f],
&[init_m, run_m, pick_m, guarded_m],
&[source],
)
}
}