use std::collections::{BTreeMap, BTreeSet, VecDeque};
use fabric_rs_core::descriptor::{JvmType, MethodDescriptor};
use crate::jvm_writer::{opcodes, ConstantPool, ExceptionHandler, FrameEntry, VerificationType};
#[derive(Debug, Clone, PartialEq, Eq)]
enum LocalSlot {
Val(VerificationType),
WideSecond,
}
#[derive(Debug, Clone, PartialEq, Eq)]
struct AbstractFrame {
locals: Vec<LocalSlot>,
stack: Vec<VerificationType>,
}
impl AbstractFrame {
fn ensure_local_len(&mut self, len: usize) {
if self.locals.len() < len {
self.locals.resize(len, LocalSlot::Val(VerificationType::Top));
}
}
fn set_local(&mut self, slot: usize, vtype: VerificationType) {
let wide = is_wide_vtype(&vtype);
let needed = slot + if wide { 2 } else { 1 };
self.ensure_local_len(needed);
if slot > 0 && self.locals[slot] == LocalSlot::WideSecond {
self.locals[slot - 1] = LocalSlot::Val(VerificationType::Top);
}
if slot + 1 < self.locals.len() && self.locals[slot + 1] == LocalSlot::WideSecond {
self.locals[slot + 1] = LocalSlot::Val(VerificationType::Top);
}
self.locals[slot] = LocalSlot::Val(vtype);
if wide {
if slot + 2 < self.locals.len() && self.locals[slot + 2] == LocalSlot::WideSecond {
}
self.locals[slot + 1] = LocalSlot::WideSecond;
}
}
fn get_local(&self, slot: usize) -> VerificationType {
match self.locals.get(slot) {
Some(LocalSlot::Val(v)) => v.clone(),
_ => VerificationType::Top,
}
}
fn push(&mut self, vtype: VerificationType) {
self.stack.push(vtype);
}
fn pop(&mut self) -> Result<VerificationType, String> {
self.stack
.pop()
.ok_or_else(|| "Operand stack underflow during CFG analysis".to_string())
}
fn pop_n(&mut self, n: usize) -> Result<Vec<VerificationType>, String> {
if self.stack.len() < n {
return Err(format!(
"Operand stack underflow: needed {n} values, found {}",
self.stack.len()
));
}
let start = self.stack.len() - n;
Ok(self.stack.drain(start..).collect())
}
fn stack_units(&self) -> u16 {
self.stack
.iter()
.map(|v| if is_wide_vtype(v) { 2 } else { 1 })
.sum()
}
fn replace_uninitialized(&mut self, target: &VerificationType, initialized: VerificationType) {
for slot in &mut self.locals {
if let LocalSlot::Val(v) = slot
&& v == target {
*v = initialized.clone();
}
}
for v in &mut self.stack {
if v == target {
*v = initialized.clone();
}
}
}
fn to_frame_entry(&self, pc: u16) -> FrameEntry {
let mut locals = Vec::new();
for slot in &self.locals {
if let LocalSlot::Val(v) = slot {
locals.push(v.clone());
}
}
while matches!(locals.last(), Some(VerificationType::Top)) {
locals.pop();
}
FrameEntry {
pc,
locals,
stack: self.stack.clone(),
}
}
}
fn is_wide_vtype(v: &VerificationType) -> bool {
matches!(v, VerificationType::Long | VerificationType::Double)
}
fn read_i16(code: &[u8], pos: usize) -> Result<i16, String> {
if pos + 2 > code.len() {
return Err("Unexpected end of bytecode reading i16".to_string());
}
Ok(i16::from_be_bytes([code[pos], code[pos + 1]]))
}
fn read_u16(code: &[u8], pos: usize) -> Result<u16, String> {
if pos + 2 > code.len() {
return Err("Unexpected end of bytecode reading u16".to_string());
}
Ok(u16::from_be_bytes([code[pos], code[pos + 1]]))
}
fn read_i32(code: &[u8], pos: usize) -> Result<i32, String> {
if pos + 4 > code.len() {
return Err("Unexpected end of bytecode reading i32".to_string());
}
Ok(i32::from_be_bytes([
code[pos],
code[pos + 1],
code[pos + 2],
code[pos + 3],
]))
}
#[derive(Debug)]
struct DecodedInsn {
op: u8,
next_pc: usize,
fallthrough: bool,
branch_targets: Vec<u16>,
operand_u16: u16,
operand_u8: u8,
wide_slot: Option<u16>,
multi_dims: u8,
}
fn decode_insn(code: &[u8], pc: usize) -> Result<DecodedInsn, String> {
let op = *code
.get(pc)
.ok_or_else(|| format!("Invalid bytecode PC {pc}"))?;
let mut d = DecodedInsn {
op,
next_pc: pc + 1,
fallthrough: true,
branch_targets: Vec::new(),
operand_u16: 0,
operand_u8: 0,
wide_slot: None,
multi_dims: 0,
};
match op {
0x00..=0x0F
| 0x1A..=0x35
| 0x3B..=0x83
| 0x85..=0x98
| 0xBE
| 0xC2
| 0xC3 => {}
0xAC..=0xB1 | 0xBF => {
d.fallthrough = false;
}
0x10 | 0x12 | 0x15..=0x19 | 0x36..=0x3A | 0xBC => {
d.operand_u8 = *code
.get(pc + 1)
.ok_or_else(|| format!("Truncated opcode 0x{op:02X} at pc {pc}"))?;
d.next_pc = pc + 2;
}
0x11 | 0x13 | 0x14 | 0x84 | 0xB2..=0xB8 | 0xBB | 0xBD | 0xC0 | 0xC1 => {
d.operand_u16 = read_u16(code, pc + 1)?;
d.next_pc = pc + 3;
}
0x99..=0xA6 | 0xC6 | 0xC7 => {
let rel = read_i16(code, pc + 1)?;
let target = (pc as i32 + rel as i32) as u16;
d.next_pc = pc + 3;
d.branch_targets.push(target);
}
0xA7 => {
let rel = read_i16(code, pc + 1)?;
let target = (pc as i32 + rel as i32) as u16;
d.next_pc = pc + 3;
d.fallthrough = false;
d.branch_targets.push(target);
}
0xC8 => {
let rel = read_i32(code, pc + 1)?;
let target = (pc as i64 + rel as i64) as u16;
d.next_pc = pc + 5;
d.fallthrough = false;
d.branch_targets.push(target);
}
0xB9 | 0xBA => {
if pc + 5 > code.len() {
return Err(format!("Truncated 5-byte invoke at pc {pc}"));
}
d.operand_u16 = read_u16(code, pc + 1)?;
d.next_pc = pc + 5;
}
0xC5 => {
if pc + 4 > code.len() {
return Err(format!("Truncated multianewarray at pc {pc}"));
}
d.operand_u16 = read_u16(code, pc + 1)?;
d.multi_dims = code[pc + 3];
d.next_pc = pc + 4;
}
0xAA => {
let pad = (4 - ((pc + 1) % 4)) % 4;
let mut cursor = pc + 1 + pad;
let def_rel = read_i32(code, cursor)?;
cursor += 4;
let low = read_i32(code, cursor)?;
cursor += 4;
let high = read_i32(code, cursor)?;
cursor += 4;
d.branch_targets.push((pc as i64 + def_rel as i64) as u16);
if high >= low {
let count = (high - low + 1) as usize;
for _ in 0..count {
let rel = read_i32(code, cursor)?;
cursor += 4;
d.branch_targets.push((pc as i64 + rel as i64) as u16);
}
}
d.next_pc = cursor;
d.fallthrough = false;
}
0xAB => {
let pad = (4 - ((pc + 1) % 4)) % 4;
let mut cursor = pc + 1 + pad;
let def_rel = read_i32(code, cursor)?;
cursor += 4;
let npairs = read_i32(code, cursor)?.max(0) as usize;
cursor += 4;
d.branch_targets.push((pc as i64 + def_rel as i64) as u16);
for _ in 0..npairs {
cursor += 4; let rel = read_i32(code, cursor)?;
cursor += 4;
d.branch_targets.push((pc as i64 + rel as i64) as u16);
}
d.next_pc = cursor;
d.fallthrough = false;
}
0xC4 => {
let wide_op = *code
.get(pc + 1)
.ok_or_else(|| format!("Truncated WIDE at pc {pc}"))?;
let slot = read_u16(code, pc + 2)?;
d.op = wide_op;
d.wide_slot = Some(slot);
d.next_pc = if wide_op == 0x84 { pc + 6 } else { pc + 4 };
}
other => {
return Err(format!("Unsupported opcode 0x{other:02X} at pc {pc}"));
}
}
Ok(d)
}
fn merge_vtype(
a: &VerificationType,
b: &VerificationType,
obj_idx: u16,
) -> Result<VerificationType, String> {
if a == b {
return Ok(a.clone());
}
match (a, b) {
(VerificationType::Top, _) | (_, VerificationType::Top) => Ok(VerificationType::Top),
(VerificationType::Null, VerificationType::Object(c))
| (VerificationType::Object(c), VerificationType::Null) => Ok(VerificationType::Object(*c)),
(VerificationType::Null, VerificationType::Uninitialized(_))
| (VerificationType::Uninitialized(_), VerificationType::Null) => {
Ok(VerificationType::Object(obj_idx))
}
(VerificationType::Object(_), VerificationType::Object(_)) => {
Ok(VerificationType::Object(obj_idx))
}
(VerificationType::Uninitialized(_), _) | (_, VerificationType::Uninitialized(_)) => {
Ok(VerificationType::Top)
}
_ => Ok(VerificationType::Top),
}
}
fn merge_frames(
existing: &mut AbstractFrame,
incoming: &AbstractFrame,
obj_idx: u16,
) -> Result<bool, String> {
let mut changed = false;
let max_locals = existing.locals.len().max(incoming.locals.len());
existing.ensure_local_len(max_locals);
for i in 0..max_locals {
let cur = existing
.locals
.get(i)
.cloned()
.unwrap_or(LocalSlot::Val(VerificationType::Top));
let inc = incoming
.locals
.get(i)
.cloned()
.unwrap_or(LocalSlot::Val(VerificationType::Top));
let merged = match (&cur, &inc) {
(LocalSlot::WideSecond, LocalSlot::WideSecond) => LocalSlot::WideSecond,
(LocalSlot::Val(a), LocalSlot::Val(b)) => LocalSlot::Val(merge_vtype(a, b, obj_idx)?),
_ => LocalSlot::Val(VerificationType::Top),
};
if merged != cur {
existing.locals[i] = merged;
changed = true;
}
}
if existing.stack.len() != incoming.stack.len() {
return Err(format!(
"Inconsistent stack depth at merge point: existing {} vs incoming {}",
existing.stack.len(),
incoming.stack.len()
));
}
for (cur, inc) in existing.stack.iter_mut().zip(incoming.stack.iter()) {
let merged = if *cur == *inc {
cur.clone()
} else {
match (&*cur, inc) {
(VerificationType::Null, VerificationType::Object(c))
| (VerificationType::Object(c), VerificationType::Null) => {
VerificationType::Object(*c)
}
(VerificationType::Object(_), VerificationType::Object(_)) => {
VerificationType::Object(obj_idx)
}
_ => {
return Err(format!(
"Incompatible operand stack types at merge point: {cur:?} vs {inc:?}"
))
}
}
};
if merged != *cur {
*cur = merged;
changed = true;
}
}
Ok(changed)
}
fn initial_frame(
this_class: &str,
method_name: &str,
method_desc: &str,
is_static: bool,
cp: &mut ConstantPool,
) -> Result<AbstractFrame, String> {
let parsed = MethodDescriptor::parse(method_desc)?;
let mut frame = AbstractFrame {
locals: Vec::new(),
stack: Vec::new(),
};
let mut slot = 0usize;
if !is_static {
let this_v = if method_name == "<init>" {
VerificationType::UninitializedThis
} else {
VerificationType::Object(cp.add_class(this_class))
};
frame.set_local(0, this_v);
slot = 1;
}
for p in &parsed.params {
let vt = VerificationType::from_jvm_type(p, cp);
frame.set_local(slot, vt);
slot += p.slot_size() as usize;
}
Ok(frame)
}
fn step_insn(
pc: u16,
insn: &DecodedInsn,
frame: &mut AbstractFrame,
cp: &mut ConstantPool,
this_class_idx: u16,
obj_class_idx: u16,
str_class_idx: u16,
cls_class_idx: u16,
throwable_idx: u16,
) -> Result<(), String> {
let slot_or_u8 = || insn.wide_slot.unwrap_or(insn.operand_u8 as u16) as usize;
match insn.op {
opcodes::NOP => {}
opcodes::ACONST_NULL => frame.push(VerificationType::Null),
0x02..=0x08 | opcodes::BIPUSH | opcodes::SIPUSH => frame.push(VerificationType::Integer),
0x09 | 0x0A => frame.push(VerificationType::Long),
0x0B..=0x0D => frame.push(VerificationType::Float),
0x0E | 0x0F => frame.push(VerificationType::Double),
opcodes::LDC => {
let vt = cp
.ldc_verification_type(insn.operand_u8 as u16, str_class_idx, cls_class_idx)
.ok_or_else(|| format!("Invalid LDC index {} at pc {pc}", insn.operand_u8))?;
frame.push(vt);
}
opcodes::LDC_W | opcodes::LDC2_W => {
let vt = cp
.ldc_verification_type(insn.operand_u16, str_class_idx, cls_class_idx)
.ok_or_else(|| format!("Invalid LDC_W index {} at pc {pc}", insn.operand_u16))?;
frame.push(vt);
}
opcodes::ILOAD => frame.push(VerificationType::Integer),
opcodes::LLOAD => frame.push(VerificationType::Long),
opcodes::FLOAD => frame.push(VerificationType::Float),
opcodes::DLOAD => frame.push(VerificationType::Double),
opcodes::ALOAD => frame.push(frame.get_local(slot_or_u8())),
0x1A..=0x1D => frame.push(VerificationType::Integer),
0x1E..=0x21 => frame.push(VerificationType::Long),
0x22..=0x25 => frame.push(VerificationType::Float),
0x26..=0x29 => frame.push(VerificationType::Double),
0x2A..=0x2D => frame.push(frame.get_local((insn.op - 0x2A) as usize)),
0x2E | 0x33 | 0x34 | 0x35 => {
frame.pop_n(2)?;
frame.push(VerificationType::Integer);
}
0x2F => {
frame.pop_n(2)?;
frame.push(VerificationType::Long);
}
0x30 => {
frame.pop_n(2)?;
frame.push(VerificationType::Float);
}
0x31 => {
frame.pop_n(2)?;
frame.push(VerificationType::Double);
}
opcodes::AALOAD => {
let _idx = frame.pop()?;
let arr = frame.pop()?;
let elem = match arr {
VerificationType::Object(cp_idx) => cp
.get_class_name(cp_idx)
.and_then(|desc| desc.strip_prefix('[').and_then(|rest| JvmType::parse(rest).ok()))
.map(|t| VerificationType::from_jvm_type(&t, cp))
.unwrap_or(VerificationType::Object(obj_class_idx)),
VerificationType::Null => VerificationType::Null,
_ => VerificationType::Object(obj_class_idx),
};
frame.push(elem);
}
opcodes::ISTORE => {
let v = frame.pop()?;
frame.set_local(slot_or_u8(), v);
}
opcodes::LSTORE => {
frame.pop()?;
frame.set_local(slot_or_u8(), VerificationType::Long);
}
opcodes::FSTORE => {
frame.pop()?;
frame.set_local(slot_or_u8(), VerificationType::Float);
}
opcodes::DSTORE => {
frame.pop()?;
frame.set_local(slot_or_u8(), VerificationType::Double);
}
opcodes::ASTORE => {
let v = frame.pop()?;
frame.set_local(slot_or_u8(), v);
}
0x3B..=0x3E => {
frame.pop()?;
frame.set_local((insn.op - 0x3B) as usize, VerificationType::Integer);
}
0x3F..=0x42 => {
frame.pop()?;
frame.set_local((insn.op - 0x3F) as usize, VerificationType::Long);
}
0x43..=0x46 => {
frame.pop()?;
frame.set_local((insn.op - 0x43) as usize, VerificationType::Float);
}
0x47..=0x4A => {
frame.pop()?;
frame.set_local((insn.op - 0x47) as usize, VerificationType::Double);
}
0x4B..=0x4E => {
let v = frame.pop()?;
frame.set_local((insn.op - 0x4B) as usize, v);
}
0x4F..=0x56 => {
frame.pop_n(3)?;
}
opcodes::POP => {
frame.pop()?;
}
opcodes::POP2 => {
let top = frame.pop()?;
if !is_wide_vtype(&top) {
frame.pop()?;
}
}
opcodes::DUP => {
let top = frame.pop()?;
frame.push(top.clone());
frame.push(top);
}
0x5A => {
let v1 = frame.pop()?;
let v2 = frame.pop()?;
frame.push(v1.clone());
frame.push(v2);
frame.push(v1);
}
0x5B => {
let v1 = frame.pop()?;
let v2 = frame.pop()?;
if is_wide_vtype(&v2) {
frame.push(v1.clone());
frame.push(v2);
frame.push(v1);
} else {
let v3 = frame.pop()?;
frame.push(v1.clone());
frame.push(v3);
frame.push(v2);
frame.push(v1);
}
}
0x5C => {
let v1 = frame.pop()?;
if is_wide_vtype(&v1) {
frame.push(v1.clone());
frame.push(v1);
} else {
let v2 = frame.pop()?;
frame.push(v2.clone());
frame.push(v1.clone());
frame.push(v2);
frame.push(v1);
}
}
0x5D => {
let v1 = frame.pop()?;
let v2 = frame.pop()?;
if is_wide_vtype(&v1) {
frame.push(v1.clone());
frame.push(v2);
frame.push(v1);
} else {
let v3 = frame.pop()?;
frame.push(v2.clone());
frame.push(v1.clone());
frame.push(v3);
frame.push(v2);
frame.push(v1);
}
}
0x5E => {
let v1 = frame.pop()?;
let v2 = frame.pop()?;
if is_wide_vtype(&v1) && is_wide_vtype(&v2) {
frame.push(v1.clone());
frame.push(v2);
frame.push(v1);
} else if is_wide_vtype(&v1) {
let v3 = frame.pop()?;
frame.push(v1.clone());
frame.push(v3);
frame.push(v2);
frame.push(v1);
} else {
let v3 = frame.pop()?;
if is_wide_vtype(&v3) {
frame.push(v2.clone());
frame.push(v1.clone());
frame.push(v3);
frame.push(v2);
frame.push(v1);
} else {
let v4 = frame.pop()?;
frame.push(v2.clone());
frame.push(v1.clone());
frame.push(v4);
frame.push(v3);
frame.push(v2);
frame.push(v1);
}
}
}
0x5F => {
let v1 = frame.pop()?;
let v2 = frame.pop()?;
frame.push(v1);
frame.push(v2);
}
0x60 | 0x64 | 0x68 | 0x6C | 0x70 | 0x78 | 0x7A | 0x7C | 0x7E | 0x80 | 0x82 => {
frame.pop_n(2)?;
frame.push(VerificationType::Integer);
}
0x61 | 0x65 | 0x69 | 0x6D | 0x71 | 0x79 | 0x7B | 0x7D | 0x7F | 0x81 | 0x83 => {
frame.pop_n(2)?;
frame.push(VerificationType::Long);
}
0x62 | 0x66 | 0x6A | 0x6E | 0x72 => {
frame.pop_n(2)?;
frame.push(VerificationType::Float);
}
0x63 | 0x67 | 0x6B | 0x6F | 0x73 => {
frame.pop_n(2)?;
frame.push(VerificationType::Double);
}
0x74..=0x77 => {} 0x84 => {} 0x85 | 0x8C | 0x8F => {
frame.pop()?;
frame.push(VerificationType::Long);
}
0x86 | 0x89 | 0x90 => {
frame.pop()?;
frame.push(VerificationType::Float);
}
0x87 | 0x8A | 0x8D => {
frame.pop()?;
frame.push(VerificationType::Double);
}
0x88 | 0x8B | 0x8E | 0x91 | 0x92 | 0x93 => {
frame.pop()?;
frame.push(VerificationType::Integer);
}
0x94..=0x98 => {
frame.pop_n(2)?;
frame.push(VerificationType::Integer);
}
0x99..=0x9E | 0xC6 | 0xC7 | 0xAA | 0xAB => {
frame.pop()?;
}
0x9F..=0xA6 => {
frame.pop_n(2)?;
}
0xA7 | 0xC8 => {}
0xAC..=0xB0 => {
frame.pop()?;
}
0xB1 => {}
opcodes::GETSTATIC => {
let (_, _, desc) = cp
.get_member_ref(insn.operand_u16)
.ok_or_else(|| format!("Invalid Fieldref at pc {pc}"))?
.clone();
let ty = JvmType::parse(&desc)?;
frame.push(VerificationType::from_jvm_type(&ty, cp));
}
opcodes::PUTSTATIC => {
frame.pop()?;
}
opcodes::GETFIELD => {
let (_, _, desc) = cp
.get_member_ref(insn.operand_u16)
.ok_or_else(|| format!("Invalid Fieldref at pc {pc}"))?
.clone();
frame.pop()?;
let ty = JvmType::parse(&desc)?;
frame.push(VerificationType::from_jvm_type(&ty, cp));
}
opcodes::PUTFIELD => {
frame.pop_n(2)?;
}
opcodes::INVOKEVIRTUAL
| opcodes::INVOKESPECIAL
| opcodes::INVOKESTATIC
| opcodes::INVOKEINTERFACE => {
let (owner, name, desc) = cp
.get_member_ref(insn.operand_u16)
.ok_or_else(|| format!("Invalid Methodref at pc {pc}"))?
.clone();
let parsed = MethodDescriptor::parse(&desc)?;
frame.pop_n(parsed.params.len())?;
if insn.op != opcodes::INVOKESTATIC {
let recv = frame.pop()?;
if insn.op == opcodes::INVOKESPECIAL && name == "<init>" {
match recv {
VerificationType::Uninitialized(_) => {
let target_cls = cp.add_class(&owner);
frame.replace_uninitialized(&recv, VerificationType::Object(target_cls));
}
VerificationType::UninitializedThis => {
frame.replace_uninitialized(
&VerificationType::UninitializedThis,
VerificationType::Object(this_class_idx),
);
}
_ => {}
}
}
}
if parsed.return_type != JvmType::Void {
frame.push(VerificationType::from_jvm_type(&parsed.return_type, cp));
}
}
opcodes::INVOKEDYNAMIC => {
let (_, desc) = cp
.get_invoke_dynamic(insn.operand_u16)
.ok_or_else(|| format!("Invalid InvokeDynamic CP entry at pc {pc}"))?
.clone();
let parsed = MethodDescriptor::parse(&desc)?;
frame.pop_n(parsed.params.len())?;
if parsed.return_type != JvmType::Void {
frame.push(VerificationType::from_jvm_type(&parsed.return_type, cp));
}
}
opcodes::NEW => frame.push(VerificationType::Uninitialized(pc)),
0xBC => {
frame.pop()?;
let desc = match insn.operand_u8 {
4 => "[Z",
5 => "[C",
6 => "[F",
7 => "[D",
8 => "[B",
9 => "[S",
10 => "[I",
11 => "[J",
_ => "[I",
};
frame.push(VerificationType::Object(cp.add_class(desc)));
}
opcodes::ANEWARRAY => {
frame.pop()?;
let elem = cp
.get_class_name(insn.operand_u16)
.ok_or_else(|| format!("Invalid Class CP index at pc {pc}"))?;
let arr_desc = if elem.starts_with('[') {
format!("[{elem}")
} else {
format!("[L{elem};")
};
frame.push(VerificationType::Object(cp.add_class(&arr_desc)));
}
opcodes::ARRAYLENGTH => {
frame.pop()?;
frame.push(VerificationType::Integer);
}
opcodes::ATHROW => {
let _ = frame.pop().unwrap_or(VerificationType::Object(throwable_idx));
frame.stack.clear();
}
opcodes::CHECKCAST => {
frame.pop()?;
frame.push(VerificationType::Object(insn.operand_u16));
}
0xC1 => {
frame.pop()?;
frame.push(VerificationType::Integer);
}
0xC2 | 0xC3 => {
frame.pop()?;
}
0xC5 => {
frame.pop_n(insn.multi_dims as usize)?;
frame.push(VerificationType::Object(insn.operand_u16));
}
_ => {}
}
Ok(())
}
pub fn compute_stack_maps(
this_class: &str,
method_name: &str,
method_desc: &str,
is_static: bool,
bytecode: &[u8],
exception_table: &[ExceptionHandler],
cp: &mut ConstantPool,
) -> Result<(u16, u16, Vec<FrameEntry>), String> {
if bytecode.is_empty() {
return Ok((0, 0, Vec::new()));
}
let this_class_idx = cp.add_class(this_class);
let obj_class_idx = cp.add_class("java/lang/Object");
let str_class_idx = cp.add_class("java/lang/String");
let cls_class_idx = cp.add_class("java/lang/Class");
let throwable_idx = cp.add_class("java/lang/Throwable");
let mut decoded: BTreeMap<u16, DecodedInsn> = BTreeMap::new();
let mut frame_pcs: BTreeSet<u16> = BTreeSet::new();
let mut cursor = 0usize;
while cursor < bytecode.len() {
let insn = decode_insn(bytecode, cursor)?;
for &target in &insn.branch_targets {
frame_pcs.insert(target);
}
let next = insn.next_pc;
decoded.insert(cursor as u16, insn);
cursor = next;
}
for ex in exception_table {
frame_pcs.insert(ex.handler_pc);
}
let entry_frame = initial_frame(this_class, method_name, method_desc, is_static, cp)?;
let mut max_locals = entry_frame.locals.len() as u16;
let mut max_stack = 0u16;
let mut block_entries: BTreeMap<u16, AbstractFrame> = BTreeMap::new();
block_entries.insert(0, entry_frame);
let mut worklist: VecDeque<u16> = VecDeque::new();
worklist.push_back(0);
let propagate = |target: u16,
state: &AbstractFrame,
entries: &mut BTreeMap<u16, AbstractFrame>,
queue: &mut VecDeque<u16>|
-> Result<(), String> {
match entries.get_mut(&target) {
None => {
entries.insert(target, state.clone());
queue.push_back(target);
}
Some(existing) => {
if merge_frames(existing, state, obj_class_idx)? {
queue.push_back(target);
}
}
}
Ok(())
};
while let Some(start_pc) = worklist.pop_front() {
let mut state = block_entries
.get(&start_pc)
.expect("worklist PC missing from block_entries")
.clone();
let mut pc = start_pc;
loop {
let Some(insn) = decoded.get(&pc) else {
break;
};
max_locals = max_locals.max(state.locals.len() as u16);
max_stack = max_stack.max(state.stack_units());
for ex in exception_table {
if pc >= ex.start_pc && pc < ex.end_pc {
let catch_vt = if ex.catch_type == 0 {
VerificationType::Object(throwable_idx)
} else {
VerificationType::Object(ex.catch_type)
};
let mut ex_state = AbstractFrame {
locals: state.locals.clone(),
stack: vec![catch_vt],
};
max_stack = max_stack.max(ex_state.stack_units());
propagate(ex.handler_pc, &mut ex_state, &mut block_entries, &mut worklist)?;
}
}
step_insn(
pc,
insn,
&mut state,
cp,
this_class_idx,
obj_class_idx,
str_class_idx,
cls_class_idx,
throwable_idx,
)?;
max_locals = max_locals.max(state.locals.len() as u16);
max_stack = max_stack.max(state.stack_units());
for &target in &insn.branch_targets {
propagate(target, &state, &mut block_entries, &mut worklist)?;
}
if !insn.fallthrough || insn.next_pc >= bytecode.len() {
break;
}
let next_pc = insn.next_pc as u16;
if frame_pcs.contains(&next_pc) {
propagate(next_pc, &state, &mut block_entries, &mut worklist)?;
break;
}
pc = next_pc;
}
}
let mut frames = Vec::new();
for pc in frame_pcs {
if let Some(frame) = block_entries.get(&pc) {
frames.push(frame.to_frame_entry(pc));
}
}
Ok((max_stack, max_locals, frames))
}