use std::collections::HashMap;
use fabric_rs_core::descriptor::JvmType;
#[allow(dead_code)]
pub mod opcodes {
pub const ACONST_NULL: u8 = 0x01;
pub const ICONST_M1: u8 = 0x02;
pub const ICONST_0: u8 = 0x03;
pub const ICONST_1: u8 = 0x04;
pub const ICONST_2: u8 = 0x05;
pub const ICONST_3: u8 = 0x06;
pub const ICONST_4: u8 = 0x07;
pub const ICONST_5: u8 = 0x08;
pub const LCONST_0: u8 = 0x09;
pub const LCONST_1: u8 = 0x0A;
pub const FCONST_0: u8 = 0x0B;
pub const DCONST_0: u8 = 0x0E;
pub const BIPUSH: u8 = 0x10;
pub const SIPUSH: u8 = 0x11;
pub const LDC: u8 = 0x12;
pub const LDC_W: u8 = 0x13;
pub const LDC2_W: u8 = 0x14;
pub const ILOAD: u8 = 0x15;
pub const LLOAD: u8 = 0x16;
pub const FLOAD: u8 = 0x17;
pub const DLOAD: u8 = 0x18;
pub const ALOAD: u8 = 0x19;
pub const ILOAD_0: u8 = 0x1A;
pub const ILOAD_1: u8 = 0x1B;
pub const ILOAD_2: u8 = 0x1C;
pub const ILOAD_3: u8 = 0x1D;
pub const LLOAD_0: u8 = 0x1E;
pub const LLOAD_1: u8 = 0x1F;
pub const LLOAD_2: u8 = 0x20;
pub const LLOAD_3: u8 = 0x21;
pub const FLOAD_0: u8 = 0x22;
pub const FLOAD_1: u8 = 0x23;
pub const FLOAD_2: u8 = 0x24;
pub const FLOAD_3: u8 = 0x25;
pub const DLOAD_0: u8 = 0x26;
pub const DLOAD_1: u8 = 0x27;
pub const DLOAD_2: u8 = 0x28;
pub const DLOAD_3: u8 = 0x29;
pub const ALOAD_0: u8 = 0x2A;
pub const ALOAD_1: u8 = 0x2B;
pub const ALOAD_2: u8 = 0x2C;
pub const ALOAD_3: u8 = 0x2D;
pub const AALOAD: u8 = 0x32;
pub const ISTORE: u8 = 0x36;
pub const LSTORE: u8 = 0x37;
pub const FSTORE: u8 = 0x38;
pub const DSTORE: u8 = 0x39;
pub const ASTORE: u8 = 0x3A;
pub const ASTORE_0: u8 = 0x4B;
pub const ASTORE_1: u8 = 0x4C;
pub const ASTORE_2: u8 = 0x4D;
pub const ASTORE_3: u8 = 0x4E;
pub const AASTORE: u8 = 0x53;
pub const POP: u8 = 0x57;
pub const POP2: u8 = 0x58;
pub const DUP: u8 = 0x59;
pub const LCMP: u8 = 0x94;
pub const IFEQ: u8 = 0x99;
pub const IFNE: u8 = 0x9A;
pub const GOTO: u8 = 0xA7;
pub const IRETURN: u8 = 0xAC;
pub const LRETURN: u8 = 0xAD;
pub const FRETURN: u8 = 0xAE;
pub const DRETURN: u8 = 0xAF;
pub const ARETURN: u8 = 0xB0;
pub const RETURN: u8 = 0xB1;
pub const GETSTATIC: u8 = 0xB2;
pub const PUTSTATIC: u8 = 0xB3;
pub const GETFIELD: u8 = 0xB4;
pub const PUTFIELD: u8 = 0xB5;
pub const INVOKEVIRTUAL: u8 = 0xB6;
pub const INVOKESPECIAL: u8 = 0xB7;
pub const INVOKESTATIC: u8 = 0xB8;
pub const INVOKEINTERFACE: u8 = 0xB9;
pub const NEW: u8 = 0xBB;
pub const ANEWARRAY: u8 = 0xBD;
pub const ATHROW: u8 = 0xBF;
pub const CHECKCAST: u8 = 0xC0;
pub const IFNULL: u8 = 0xC6;
pub const IFNONNULL: u8 = 0xC7;
}
#[allow(dead_code)]
pub mod access_flags {
pub const ACC_PUBLIC: u16 = 0x0001;
pub const ACC_PRIVATE: u16 = 0x0002;
pub const ACC_PROTECTED: u16 = 0x0004;
pub const ACC_STATIC: u16 = 0x0008;
pub const ACC_FINAL: u16 = 0x0010;
pub const ACC_SUPER: u16 = 0x0020;
pub const ACC_SYNCHRONIZED: u16 = 0x0020;
pub const ACC_VOLATILE: u16 = 0x0040;
pub const ACC_BRIDGE: u16 = 0x0040;
pub const ACC_VARARGS: u16 = 0x0080;
pub const ACC_NATIVE: u16 = 0x0100;
pub const ACC_INTERFACE: u16 = 0x0200;
pub const ACC_ABSTRACT: u16 = 0x0400;
pub const ACC_SYNTHETIC: u16 = 0x1000;
pub const ACC_ANNOTATION: u16 = 0x2000;
pub const ACC_ENUM: u16 = 0x4000;
}
#[allow(dead_code)]
#[derive(Debug, Clone)]
pub enum ElementValue {
String(String),
Class(String),
Int(i32),
Boolean(bool),
Enum { type_descriptor: String, const_name: String },
Array(Vec<ElementValue>),
Annotation(Annotation),
}
#[derive(Debug, Clone)]
pub struct Annotation {
pub type_descriptor: String,
pub element_value_pairs: Vec<(String, ElementValue)>,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum VerificationType {
Top,
Integer,
Float,
Double,
Long,
Null,
UninitializedThis,
Object(u16), Uninitialized(u16),
}
impl VerificationType {
pub fn from_jvm_type(ty: &JvmType, cp: &mut ConstantPool) -> Self {
match ty {
JvmType::Boolean | JvmType::Byte | JvmType::Char | JvmType::Short | JvmType::Int => {
VerificationType::Integer
}
JvmType::Float => VerificationType::Float,
JvmType::Long => VerificationType::Long,
JvmType::Double => VerificationType::Double,
JvmType::Object(internal) => VerificationType::Object(cp.add_class(internal)),
JvmType::Array(_) => VerificationType::Object(cp.add_class(&ty.to_descriptor())),
JvmType::Void => VerificationType::Top,
}
}
fn write(&self, buf: &mut Vec<u8>) {
match self {
VerificationType::Top => buf.push(0),
VerificationType::Integer => buf.push(1),
VerificationType::Float => buf.push(2),
VerificationType::Double => buf.push(3),
VerificationType::Long => buf.push(4),
VerificationType::Null => buf.push(5),
VerificationType::UninitializedThis => buf.push(6),
VerificationType::Object(cp_idx) => {
buf.push(7);
buf.extend_from_slice(&cp_idx.to_be_bytes());
}
VerificationType::Uninitialized(offset) => {
buf.push(8);
buf.extend_from_slice(&offset.to_be_bytes());
}
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub struct LabelId(pub usize);
#[derive(Debug, Clone)]
struct JumpPatch {
opcode_pc: usize,
operand_pc: usize,
target: LabelId,
}
#[derive(Debug, Clone)]
struct FrameEntry {
pc: u16,
locals: Vec<VerificationType>,
stack: Vec<VerificationType>,
}
#[derive(Debug, Clone)]
pub struct ExceptionHandler {
pub start_pc: u16,
pub end_pc: u16,
pub handler_pc: u16,
pub catch_type: u16, }
#[derive(Debug, Clone)]
pub struct FieldWriter {
pub access_flags: u16,
pub name: String,
pub descriptor: String,
}
#[derive(Debug, Clone)]
pub struct CodeWriter {
pub max_stack: u16,
pub max_locals: u16,
pub bytecode: Vec<u8>,
pub exception_table: Vec<ExceptionHandler>,
labels: Vec<Option<u16>>,
jumps: Vec<JumpPatch>,
frames: Vec<FrameEntry>,
}
impl CodeWriter {
pub fn new(max_stack: u16, max_locals: u16) -> Self {
Self {
max_stack,
max_locals,
bytecode: Vec::new(),
exception_table: Vec::new(),
labels: Vec::new(),
jumps: Vec::new(),
frames: Vec::new(),
}
}
pub fn current_pc(&self) -> u16 {
self.bytecode.len() as u16
}
pub fn new_label(&mut self) -> LabelId {
let id = LabelId(self.labels.len());
self.labels.push(None);
id
}
pub fn bind_label(&mut self, label: LabelId) {
self.labels[label.0] = Some(self.current_pc());
}
pub fn bind_label_with_frame(
&mut self,
label: LabelId,
locals: Vec<VerificationType>,
stack: Vec<VerificationType>,
) {
let pc = self.current_pc();
self.labels[label.0] = Some(pc);
self.frames.push(FrameEntry { pc, locals, stack });
}
pub fn emit_u8(&mut self, b: u8) {
self.bytecode.push(b);
}
pub fn emit_u16(&mut self, val: u16) {
self.bytecode.extend_from_slice(&val.to_be_bytes());
}
pub fn emit_i16(&mut self, val: i16) {
self.bytecode.extend_from_slice(&val.to_be_bytes());
}
pub fn emit_jump(&mut self, opcode: u8, target: LabelId) {
let opcode_pc = self.bytecode.len();
self.emit_u8(opcode);
let operand_pc = self.bytecode.len();
self.emit_i16(0);
self.jumps.push(JumpPatch {
opcode_pc,
operand_pc,
target,
});
}
pub fn emit_int_const(&mut self, value: i32) {
match value {
-1 => self.emit_u8(opcodes::ICONST_M1),
0 => self.emit_u8(opcodes::ICONST_0),
1 => self.emit_u8(opcodes::ICONST_1),
2 => self.emit_u8(opcodes::ICONST_2),
3 => self.emit_u8(opcodes::ICONST_3),
4 => self.emit_u8(opcodes::ICONST_4),
5 => self.emit_u8(opcodes::ICONST_5),
-128..=127 => {
self.emit_u8(opcodes::BIPUSH);
self.emit_u8(value as i8 as u8);
}
-32768..=32767 => {
self.emit_u8(opcodes::SIPUSH);
self.emit_i16(value as i16);
}
_ => panic!("emit_int_const out of i16 range: use LDC with cp.add_integer"),
}
}
pub fn emit_ldc(&mut self, cp_idx: u16) {
if cp_idx <= 255 {
self.emit_u8(opcodes::LDC);
self.emit_u8(cp_idx as u8);
} else {
self.emit_u8(opcodes::LDC_W);
self.emit_u16(cp_idx);
}
}
pub fn emit_load(&mut self, ty: &JvmType, slot: u16) {
match ty {
JvmType::Boolean
| JvmType::Byte
| JvmType::Char
| JvmType::Short
| JvmType::Int => match slot {
0 => self.emit_u8(opcodes::ILOAD_0),
1 => self.emit_u8(opcodes::ILOAD_1),
2 => self.emit_u8(opcodes::ILOAD_2),
3 => self.emit_u8(opcodes::ILOAD_3),
_ => {
self.emit_u8(opcodes::ILOAD);
self.emit_u8(slot as u8);
}
},
JvmType::Long => match slot {
0 => self.emit_u8(opcodes::LLOAD_0),
1 => self.emit_u8(opcodes::LLOAD_1),
2 => self.emit_u8(opcodes::LLOAD_2),
3 => self.emit_u8(opcodes::LLOAD_3),
_ => {
self.emit_u8(opcodes::LLOAD);
self.emit_u8(slot as u8);
}
},
JvmType::Float => match slot {
0 => self.emit_u8(opcodes::FLOAD_0),
1 => self.emit_u8(opcodes::FLOAD_1),
2 => self.emit_u8(opcodes::FLOAD_2),
3 => self.emit_u8(opcodes::FLOAD_3),
_ => {
self.emit_u8(opcodes::FLOAD);
self.emit_u8(slot as u8);
}
},
JvmType::Double => match slot {
0 => self.emit_u8(opcodes::DLOAD_0),
1 => self.emit_u8(opcodes::DLOAD_1),
2 => self.emit_u8(opcodes::DLOAD_2),
3 => self.emit_u8(opcodes::DLOAD_3),
_ => {
self.emit_u8(opcodes::DLOAD);
self.emit_u8(slot as u8);
}
},
JvmType::Object(_) | JvmType::Array(_) => match slot {
0 => self.emit_u8(opcodes::ALOAD_0),
1 => self.emit_u8(opcodes::ALOAD_1),
2 => self.emit_u8(opcodes::ALOAD_2),
3 => self.emit_u8(opcodes::ALOAD_3),
_ => {
self.emit_u8(opcodes::ALOAD);
self.emit_u8(slot as u8);
}
},
JvmType::Void => {}
}
}
pub fn emit_aload(&mut self, slot: u16) {
self.emit_load(&JvmType::Object("java/lang/Object".to_string()), slot);
}
pub fn emit_astore(&mut self, slot: u16) {
match slot {
0 => self.emit_u8(opcodes::ASTORE_0),
1 => self.emit_u8(opcodes::ASTORE_1),
2 => self.emit_u8(opcodes::ASTORE_2),
3 => self.emit_u8(opcodes::ASTORE_3),
_ => {
self.emit_u8(opcodes::ASTORE);
self.emit_u8(slot as u8);
}
}
}
pub fn emit_return(&mut self, ty: &JvmType) {
match ty {
JvmType::Void => self.emit_u8(opcodes::RETURN),
JvmType::Boolean
| JvmType::Byte
| JvmType::Char
| JvmType::Short
| JvmType::Int => self.emit_u8(opcodes::IRETURN),
JvmType::Long => self.emit_u8(opcodes::LRETURN),
JvmType::Float => self.emit_u8(opcodes::FRETURN),
JvmType::Double => self.emit_u8(opcodes::DRETURN),
JvmType::Object(_) | JvmType::Array(_) => self.emit_u8(opcodes::ARETURN),
}
}
pub fn emit_box_if_primitive(&mut self, cp: &mut ConstantPool, ty: &JvmType) {
let (box_cls, desc) = match ty {
JvmType::Boolean => ("java/lang/Boolean", "(Z)Ljava/lang/Boolean;"),
JvmType::Byte => ("java/lang/Byte", "(B)Ljava/lang/Byte;"),
JvmType::Char => ("java/lang/Character", "(C)Ljava/lang/Character;"),
JvmType::Short => ("java/lang/Short", "(S)Ljava/lang/Short;"),
JvmType::Int => ("java/lang/Integer", "(I)Ljava/lang/Integer;"),
JvmType::Long => ("java/lang/Long", "(J)Ljava/lang/Long;"),
JvmType::Float => ("java/lang/Float", "(F)Ljava/lang/Float;"),
JvmType::Double => ("java/lang/Double", "(D)Ljava/lang/Double;"),
JvmType::Void | JvmType::Object(_) | JvmType::Array(_) => return,
};
let mref = cp.add_methodref(box_cls, "valueOf", desc);
self.emit_u8(opcodes::INVOKESTATIC);
self.emit_u16(mref);
}
pub fn emit_unbox_or_cast(&mut self, cp: &mut ConstantPool, ty: &JvmType) {
match ty {
JvmType::Void => {
self.emit_u8(opcodes::POP);
}
JvmType::Boolean => {
let c = cp.add_class("java/lang/Boolean");
let m = cp.add_methodref("java/lang/Boolean", "booleanValue", "()Z");
self.emit_u8(opcodes::CHECKCAST);
self.emit_u16(c);
self.emit_u8(opcodes::INVOKEVIRTUAL);
self.emit_u16(m);
}
JvmType::Byte => {
let c = cp.add_class("java/lang/Number");
let m = cp.add_methodref("java/lang/Number", "byteValue", "()B");
self.emit_u8(opcodes::CHECKCAST);
self.emit_u16(c);
self.emit_u8(opcodes::INVOKEVIRTUAL);
self.emit_u16(m);
}
JvmType::Short => {
let c = cp.add_class("java/lang/Number");
let m = cp.add_methodref("java/lang/Number", "shortValue", "()S");
self.emit_u8(opcodes::CHECKCAST);
self.emit_u16(c);
self.emit_u8(opcodes::INVOKEVIRTUAL);
self.emit_u16(m);
}
JvmType::Char => {
let c = cp.add_class("java/lang/Character");
let m = cp.add_methodref("java/lang/Character", "charValue", "()C");
self.emit_u8(opcodes::CHECKCAST);
self.emit_u16(c);
self.emit_u8(opcodes::INVOKEVIRTUAL);
self.emit_u16(m);
}
JvmType::Int => {
let c = cp.add_class("java/lang/Number");
let m = cp.add_methodref("java/lang/Number", "intValue", "()I");
self.emit_u8(opcodes::CHECKCAST);
self.emit_u16(c);
self.emit_u8(opcodes::INVOKEVIRTUAL);
self.emit_u16(m);
}
JvmType::Long => {
let c = cp.add_class("java/lang/Number");
let m = cp.add_methodref("java/lang/Number", "longValue", "()J");
self.emit_u8(opcodes::CHECKCAST);
self.emit_u16(c);
self.emit_u8(opcodes::INVOKEVIRTUAL);
self.emit_u16(m);
}
JvmType::Float => {
let c = cp.add_class("java/lang/Number");
let m = cp.add_methodref("java/lang/Number", "floatValue", "()F");
self.emit_u8(opcodes::CHECKCAST);
self.emit_u16(c);
self.emit_u8(opcodes::INVOKEVIRTUAL);
self.emit_u16(m);
}
JvmType::Double => {
let c = cp.add_class("java/lang/Number");
let m = cp.add_methodref("java/lang/Number", "doubleValue", "()D");
self.emit_u8(opcodes::CHECKCAST);
self.emit_u16(c);
self.emit_u8(opcodes::INVOKEVIRTUAL);
self.emit_u16(m);
}
JvmType::Object(internal) => {
if internal != "java/lang/Object" {
let c = cp.add_class(internal);
self.emit_u8(opcodes::CHECKCAST);
self.emit_u16(c);
}
}
JvmType::Array(_) => {
let c = cp.add_class(&ty.to_descriptor());
self.emit_u8(opcodes::CHECKCAST);
self.emit_u16(c);
}
}
}
pub fn finalize_jumps(&mut self) -> Result<(), String> {
for j in &self.jumps {
let target_pc = self.labels[j.target.0]
.ok_or_else(|| format!("Unbound jump label {:?}", j.target))?;
let rel = (target_pc as i32) - (j.opcode_pc as i32);
let rel16 = i16::try_from(rel).map_err(|_| "Jump offset overflow".to_string())?;
let bytes = rel16.to_be_bytes();
self.bytecode[j.operand_pc] = bytes[0];
self.bytecode[j.operand_pc + 1] = bytes[1];
}
Ok(())
}
fn encode_stack_map_table(&self) -> Option<Vec<u8>> {
if self.frames.is_empty() {
return None;
}
let mut sorted = self.frames.clone();
sorted.sort_by_key(|f| f.pc);
sorted.dedup_by_key(|f| f.pc);
let mut buf = Vec::new();
buf.extend_from_slice(&(sorted.len() as u16).to_be_bytes());
let mut prev_pc: Option<u16> = None;
for frame in sorted {
let offset_delta = match prev_pc {
None => frame.pc,
Some(p) => frame.pc - p - 1,
};
prev_pc = Some(frame.pc);
buf.push(255);
buf.extend_from_slice(&offset_delta.to_be_bytes());
buf.extend_from_slice(&(frame.locals.len() as u16).to_be_bytes());
for loc in &frame.locals {
loc.write(&mut buf);
}
buf.extend_from_slice(&(frame.stack.len() as u16).to_be_bytes());
for st in &frame.stack {
st.write(&mut buf);
}
}
Some(buf)
}
}
#[derive(Debug, Clone)]
pub struct MethodWriter {
pub access_flags: u16,
pub name: String,
pub descriptor: String,
pub code: Option<CodeWriter>,
pub annotations: Vec<Annotation>,
}
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
enum CpKey {
Utf8(String),
Integer(i32),
Class(u16),
String(u16),
NameAndType(u16, u16),
Fieldref(u16, u16),
Methodref(u16, u16),
InterfaceMethodref(u16, u16),
}
pub struct ConstantPool {
entries: Vec<Vec<u8>>,
index: HashMap<CpKey, u16>,
}
impl ConstantPool {
pub fn new() -> Self {
Self {
entries: vec![Vec::new()], index: HashMap::new(),
}
}
pub fn add_utf8(&mut self, s: &str) -> u16 {
let key = CpKey::Utf8(s.to_string());
if let Some(&idx) = self.index.get(&key) {
return idx;
}
let idx = self.entries.len() as u16;
let bytes = s.as_bytes();
let mut entry = Vec::with_capacity(3 + bytes.len());
entry.push(1);
entry.extend_from_slice(&(bytes.len() as u16).to_be_bytes());
entry.extend_from_slice(bytes);
self.entries.push(entry);
self.index.insert(key, idx);
idx
}
pub fn add_integer(&mut self, val: i32) -> u16 {
let key = CpKey::Integer(val);
if let Some(&idx) = self.index.get(&key) {
return idx;
}
let idx = self.entries.len() as u16;
let mut entry = Vec::with_capacity(5);
entry.push(3);
entry.extend_from_slice(&val.to_be_bytes());
self.entries.push(entry);
self.index.insert(key, idx);
idx
}
pub fn add_class(&mut self, internal_name: &str) -> u16 {
let norm = internal_name.replace('.', "/");
let name_idx = self.add_utf8(&norm);
let key = CpKey::Class(name_idx);
if let Some(&idx) = self.index.get(&key) {
return idx;
}
let idx = self.entries.len() as u16;
let mut entry = Vec::with_capacity(3);
entry.push(7);
entry.extend_from_slice(&name_idx.to_be_bytes());
self.entries.push(entry);
self.index.insert(key, idx);
idx
}
pub fn add_string(&mut self, s: &str) -> u16 {
let utf8_idx = self.add_utf8(s);
let key = CpKey::String(utf8_idx);
if let Some(&idx) = self.index.get(&key) {
return idx;
}
let idx = self.entries.len() as u16;
let mut entry = Vec::with_capacity(3);
entry.push(8);
entry.extend_from_slice(&utf8_idx.to_be_bytes());
self.entries.push(entry);
self.index.insert(key, idx);
idx
}
pub fn add_name_and_type(&mut self, name: &str, desc: &str) -> u16 {
let name_idx = self.add_utf8(name);
let desc_idx = self.add_utf8(desc);
let key = CpKey::NameAndType(name_idx, desc_idx);
if let Some(&idx) = self.index.get(&key) {
return idx;
}
let idx = self.entries.len() as u16;
let mut entry = Vec::with_capacity(5);
entry.push(12);
entry.extend_from_slice(&name_idx.to_be_bytes());
entry.extend_from_slice(&desc_idx.to_be_bytes());
self.entries.push(entry);
self.index.insert(key, idx);
idx
}
pub fn add_fieldref(&mut self, owner: &str, name: &str, desc: &str) -> u16 {
let cls_idx = self.add_class(owner);
let nat_idx = self.add_name_and_type(name, desc);
let key = CpKey::Fieldref(cls_idx, nat_idx);
if let Some(&idx) = self.index.get(&key) {
return idx;
}
let idx = self.entries.len() as u16;
let mut entry = Vec::with_capacity(5);
entry.push(9);
entry.extend_from_slice(&cls_idx.to_be_bytes());
entry.extend_from_slice(&nat_idx.to_be_bytes());
self.entries.push(entry);
self.index.insert(key, idx);
idx
}
pub fn add_methodref(&mut self, owner: &str, name: &str, desc: &str) -> u16 {
let cls_idx = self.add_class(owner);
let nat_idx = self.add_name_and_type(name, desc);
let key = CpKey::Methodref(cls_idx, nat_idx);
if let Some(&idx) = self.index.get(&key) {
return idx;
}
let idx = self.entries.len() as u16;
let mut entry = Vec::with_capacity(5);
entry.push(10);
entry.extend_from_slice(&cls_idx.to_be_bytes());
entry.extend_from_slice(&nat_idx.to_be_bytes());
self.entries.push(entry);
self.index.insert(key, idx);
idx
}
pub fn add_interface_methodref(&mut self, owner: &str, name: &str, desc: &str) -> u16 {
let cls_idx = self.add_class(owner);
let nat_idx = self.add_name_and_type(name, desc);
let key = CpKey::InterfaceMethodref(cls_idx, nat_idx);
if let Some(&idx) = self.index.get(&key) {
return idx;
}
let idx = self.entries.len() as u16;
let mut entry = Vec::with_capacity(5);
entry.push(11);
entry.extend_from_slice(&cls_idx.to_be_bytes());
entry.extend_from_slice(&nat_idx.to_be_bytes());
self.entries.push(entry);
self.index.insert(key, idx);
idx
}
fn write(&self, out: &mut Vec<u8>) {
out.extend_from_slice(&(self.entries.len() as u16).to_be_bytes());
for entry in self.entries.iter().skip(1) {
out.extend_from_slice(entry);
}
}
}
pub struct ClassWriter {
pub major_version: u16,
pub access_flags: u16,
pub this_class_name: String,
pub cp: ConstantPool,
this_class: u16,
super_class: u16,
interfaces: Vec<u16>,
fields: Vec<FieldWriter>,
methods: Vec<MethodWriter>,
annotations: Vec<Annotation>,
invisible_annotations: Vec<Annotation>,
}
impl ClassWriter {
pub fn new(
this_class: &str,
super_class: &str,
access_flags: u16,
java_version: u16,
) -> Self {
let mut cp = ConstantPool::new();
let this_idx = cp.add_class(this_class);
let super_idx = cp.add_class(super_class);
let major_version = match java_version {
8 => 52,
16 => 60,
17 => 61,
21 => 65,
25 => 69,
v if v >= 45 => v,
_ => 65,
};
Self {
major_version,
access_flags,
this_class_name: this_class.replace('.', "/"),
cp,
this_class: this_idx,
super_class: super_idx,
interfaces: Vec::new(),
fields: Vec::new(),
methods: Vec::new(),
annotations: Vec::new(),
invisible_annotations: Vec::new(),
}
}
pub fn add_interface(&mut self, iface: &str) {
let idx = self.cp.add_class(iface);
if !self.interfaces.contains(&idx) {
self.interfaces.push(idx);
}
}
pub fn add_annotation(&mut self, ann: Annotation) {
self.annotations.push(ann);
}
pub fn add_invisible_annotation(&mut self, ann: Annotation) {
self.invisible_annotations.push(ann);
}
pub fn add_field(&mut self, field: FieldWriter) {
self.fields.push(field);
}
pub fn add_method(&mut self, method: MethodWriter) {
self.methods.push(method);
}
fn write_element_value(cp: &mut ConstantPool, ev: &ElementValue, out: &mut Vec<u8>) {
match ev {
ElementValue::String(s) => {
out.push(b's');
out.extend_from_slice(&cp.add_utf8(s).to_be_bytes());
}
ElementValue::Class(desc) => {
out.push(b'c');
out.extend_from_slice(&cp.add_utf8(desc).to_be_bytes());
}
ElementValue::Int(v) => {
out.push(b'I');
out.extend_from_slice(&cp.add_integer(*v).to_be_bytes());
}
ElementValue::Boolean(b) => {
out.push(b'Z');
out.extend_from_slice(&cp.add_integer(if *b { 1 } else { 0 }).to_be_bytes());
}
ElementValue::Enum {
type_descriptor,
const_name,
} => {
out.push(b'e');
out.extend_from_slice(&cp.add_utf8(type_descriptor).to_be_bytes());
out.extend_from_slice(&cp.add_utf8(const_name).to_be_bytes());
}
ElementValue::Array(items) => {
out.push(b'[');
out.extend_from_slice(&(items.len() as u16).to_be_bytes());
for item in items {
Self::write_element_value(cp, item, out);
}
}
ElementValue::Annotation(ann) => {
out.push(b'@');
Self::write_annotation(cp, ann, out);
}
}
}
fn write_annotation(cp: &mut ConstantPool, ann: &Annotation, out: &mut Vec<u8>) {
let type_idx = cp.add_utf8(&ann.type_descriptor);
out.extend_from_slice(&type_idx.to_be_bytes());
out.extend_from_slice(&(ann.element_value_pairs.len() as u16).to_be_bytes());
for (name, val) in &ann.element_value_pairs {
let name_idx = cp.add_utf8(name);
out.extend_from_slice(&name_idx.to_be_bytes());
Self::write_element_value(cp, val, out);
}
}
fn encode_annotations_attr(cp: &mut ConstantPool, anns: &[Annotation]) -> Vec<u8> {
let mut attr = Vec::new();
attr.extend_from_slice(&(anns.len() as u16).to_be_bytes());
for ann in anns {
Self::write_annotation(cp, ann, &mut attr);
}
attr
}
pub fn finish(mut self) -> Result<Vec<u8>, String> {
let mut cp = self.cp;
let mut field_bytes = Vec::new();
field_bytes.extend_from_slice(&(self.fields.len() as u16).to_be_bytes());
for f in &self.fields {
field_bytes.extend_from_slice(&f.access_flags.to_be_bytes());
field_bytes.extend_from_slice(&cp.add_utf8(&f.name).to_be_bytes());
field_bytes.extend_from_slice(&cp.add_utf8(&f.descriptor).to_be_bytes());
field_bytes.extend_from_slice(&0u16.to_be_bytes()); }
let mut method_bytes = Vec::new();
method_bytes.extend_from_slice(&(self.methods.len() as u16).to_be_bytes());
for m in &mut self.methods {
method_bytes.extend_from_slice(&m.access_flags.to_be_bytes());
method_bytes.extend_from_slice(&cp.add_utf8(&m.name).to_be_bytes());
method_bytes.extend_from_slice(&cp.add_utf8(&m.descriptor).to_be_bytes());
let mut attrs: Vec<(u16, Vec<u8>)> = Vec::new();
if let Some(code) = m.code.as_mut() {
code.finalize_jumps()?;
let code_attr_name = cp.add_utf8("Code");
let mut code_body = Vec::new();
code_body.extend_from_slice(&code.max_stack.to_be_bytes());
code_body.extend_from_slice(&code.max_locals.to_be_bytes());
code_body.extend_from_slice(&(code.bytecode.len() as u32).to_be_bytes());
code_body.extend_from_slice(&code.bytecode);
code_body.extend_from_slice(&(code.exception_table.len() as u16).to_be_bytes());
for ex in &code.exception_table {
code_body.extend_from_slice(&ex.start_pc.to_be_bytes());
code_body.extend_from_slice(&ex.end_pc.to_be_bytes());
code_body.extend_from_slice(&ex.handler_pc.to_be_bytes());
code_body.extend_from_slice(&ex.catch_type.to_be_bytes());
}
if let Some(smt) = code.encode_stack_map_table() {
let smt_name = cp.add_utf8("StackMapTable");
code_body.extend_from_slice(&1u16.to_be_bytes());
code_body.extend_from_slice(&smt_name.to_be_bytes());
code_body.extend_from_slice(&(smt.len() as u32).to_be_bytes());
code_body.extend_from_slice(&smt);
} else {
code_body.extend_from_slice(&0u16.to_be_bytes());
}
attrs.push((code_attr_name, code_body));
}
if !m.annotations.is_empty() {
let rva_name = cp.add_utf8("RuntimeVisibleAnnotations");
let rva_body = Self::encode_annotations_attr(&mut cp, &m.annotations);
attrs.push((rva_name, rva_body));
}
method_bytes.extend_from_slice(&(attrs.len() as u16).to_be_bytes());
for (name_idx, body) in attrs {
method_bytes.extend_from_slice(&name_idx.to_be_bytes());
method_bytes.extend_from_slice(&(body.len() as u32).to_be_bytes());
method_bytes.extend_from_slice(&body);
}
}
let mut class_attrs: Vec<(u16, Vec<u8>)> = Vec::new();
if !self.annotations.is_empty() {
let rva_name = cp.add_utf8("RuntimeVisibleAnnotations");
let rva_body = Self::encode_annotations_attr(&mut cp, &self.annotations);
class_attrs.push((rva_name, rva_body));
}
if !self.invisible_annotations.is_empty() {
let ria_name = cp.add_utf8("RuntimeInvisibleAnnotations");
let ria_body = Self::encode_annotations_attr(&mut cp, &self.invisible_annotations);
class_attrs.push((ria_name, ria_body));
}
let mut out = Vec::with_capacity(512);
out.extend_from_slice(&0xCAFEBABEu32.to_be_bytes());
out.extend_from_slice(&0u16.to_be_bytes());
out.extend_from_slice(&self.major_version.to_be_bytes());
cp.write(&mut out);
out.extend_from_slice(&self.access_flags.to_be_bytes());
out.extend_from_slice(&self.this_class.to_be_bytes());
out.extend_from_slice(&self.super_class.to_be_bytes());
out.extend_from_slice(&(self.interfaces.len() as u16).to_be_bytes());
for iface in &self.interfaces {
out.extend_from_slice(&iface.to_be_bytes());
}
out.extend_from_slice(&field_bytes);
out.extend_from_slice(&method_bytes);
out.extend_from_slice(&(class_attrs.len() as u16).to_be_bytes());
for (name_idx, body) in class_attrs {
out.extend_from_slice(&name_idx.to_be_bytes());
out.extend_from_slice(&(body.len() as u32).to_be_bytes());
out.extend_from_slice(&body);
}
Ok(out)
}
}