use std::collections::HashMap;
use fabric_rs_core::descriptor::JvmType;
#[allow(dead_code)]
pub mod opcodes {
pub const NOP: u8 = 0x00;
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 FCONST_1: u8 = 0x0C;
pub const FCONST_2: u8 = 0x0D;
pub const DCONST_0: u8 = 0x0E;
pub const DCONST_1: u8 = 0x0F;
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 IALOAD: u8 = 0x2E;
pub const LALOAD: u8 = 0x2F;
pub const FALOAD: u8 = 0x30;
pub const DALOAD: u8 = 0x31;
pub const AALOAD: u8 = 0x32;
pub const BALOAD: u8 = 0x33;
pub const CALOAD: u8 = 0x34;
pub const SALOAD: u8 = 0x35;
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 ISTORE_0: u8 = 0x3B;
pub const ISTORE_1: u8 = 0x3C;
pub const ISTORE_2: u8 = 0x3D;
pub const ISTORE_3: u8 = 0x3E;
pub const LSTORE_0: u8 = 0x3F;
pub const LSTORE_1: u8 = 0x40;
pub const LSTORE_2: u8 = 0x41;
pub const LSTORE_3: u8 = 0x42;
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 DUP_X1: u8 = 0x5A;
pub const DUP_X2: u8 = 0x5B;
pub const DUP2: u8 = 0x5C;
pub const SWAP: u8 = 0x5F;
pub const IADD: u8 = 0x60;
pub const LADD: u8 = 0x61;
pub const ISUB: u8 = 0x64;
pub const IMUL: u8 = 0x68;
pub const IDIV: u8 = 0x6C;
pub const IINC: u8 = 0x84;
pub const I2L: u8 = 0x85;
pub const L2I: u8 = 0x88;
pub const LCMP: u8 = 0x94;
pub const IFEQ: u8 = 0x99;
pub const IFNE: u8 = 0x9A;
pub const IFLT: u8 = 0x9B;
pub const IFGE: u8 = 0x9C;
pub const IFGT: u8 = 0x9D;
pub const IFLE: u8 = 0x9E;
pub const IF_ICMPEQ: u8 = 0x9F;
pub const IF_ICMPNE: u8 = 0xA0;
pub const IF_ICMPLT: u8 = 0xA1;
pub const IF_ICMPGE: u8 = 0xA2;
pub const IF_ICMPGT: u8 = 0xA3;
pub const IF_ICMPLE: u8 = 0xA4;
pub const IF_ACMPEQ: u8 = 0xA5;
pub const IF_ACMPNE: u8 = 0xA6;
pub const GOTO: u8 = 0xA7;
pub const TABLESWITCH: u8 = 0xAA;
pub const LOOKUPSWITCH: u8 = 0xAB;
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 INVOKEDYNAMIC: u8 = 0xBA;
pub const NEW: u8 = 0xBB;
pub const NEWARRAY: u8 = 0xBC;
pub const ANEWARRAY: u8 = 0xBD;
pub const ARRAYLENGTH: u8 = 0xBE;
pub const ATHROW: u8 = 0xBF;
pub const CHECKCAST: u8 = 0xC0;
pub const INSTANCEOF: u8 = 0xC1;
pub const MONITORENTER: u8 = 0xC2;
pub const MONITOREXIT: u8 = 0xC3;
pub const IFNULL: u8 = 0xC6;
pub const IFNONNULL: u8 = 0xC7;
pub const GOTO_W: u8 = 0xC8;
}
#[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());
}
}
}
}
#[repr(u8)]
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum MethodHandleKind {
GetField = 1,
GetStatic = 2,
PutField = 3,
PutStatic = 4,
InvokeVirtual = 5,
InvokeStatic = 6,
InvokeSpecial = 7,
NewInvokeSpecial = 8,
InvokeInterface = 9,
}
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct BootstrapMethod {
pub bootstrap_method_ref: u16,
pub bootstrap_arguments: Vec<u16>,
}
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct InnerClassEntry {
pub inner_class: String,
pub outer_class: Option<String>,
pub inner_name: Option<String>,
pub access_flags: u16,
}
#[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,
is_wide: bool,
}
#[derive(Debug, Clone)]
pub struct FrameEntry {
pub pc: u16,
pub locals: Vec<VerificationType>,
pub 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>,
pub auto_stack_map: bool,
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(),
auto_stack_map: false,
labels: Vec::new(),
jumps: Vec::new(),
frames: Vec::new(),
}
}
pub fn with_auto_frames() -> Self {
Self {
max_stack: 0,
max_locals: 0,
bytecode: Vec::new(),
exception_table: Vec::new(),
auto_stack_map: true,
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,
is_wide: false,
});
}
pub fn emit_goto_w(&mut self, target: LabelId) {
let opcode_pc = self.bytecode.len();
self.emit_u8(opcodes::GOTO_W);
let operand_pc = self.bytecode.len();
self.bytecode.extend_from_slice(&0i32.to_be_bytes());
self.jumps.push(JumpPatch {
opcode_pc,
operand_pc,
target,
is_wide: true,
});
}
pub fn emit_tableswitch(
&mut self,
low: i32,
high: i32,
default: LabelId,
targets: &[LabelId],
) {
let opcode_pc = self.bytecode.len();
self.emit_u8(opcodes::TABLESWITCH);
while !self.bytecode.len().is_multiple_of(4) {
self.emit_u8(0);
}
let def_pos = self.bytecode.len();
self.bytecode.extend_from_slice(&0i32.to_be_bytes());
self.jumps.push(JumpPatch {
opcode_pc,
operand_pc: def_pos,
target: default,
is_wide: true,
});
self.bytecode.extend_from_slice(&low.to_be_bytes());
self.bytecode.extend_from_slice(&high.to_be_bytes());
for tgt in targets {
let pos = self.bytecode.len();
self.bytecode.extend_from_slice(&0i32.to_be_bytes());
self.jumps.push(JumpPatch {
opcode_pc,
operand_pc: pos,
target: *tgt,
is_wide: true,
});
}
}
pub fn emit_lookupswitch(&mut self, default: LabelId, pairs: &[(i32, LabelId)]) {
let opcode_pc = self.bytecode.len();
self.emit_u8(opcodes::LOOKUPSWITCH);
while !self.bytecode.len().is_multiple_of(4) {
self.emit_u8(0);
}
let def_pos = self.bytecode.len();
self.bytecode.extend_from_slice(&0i32.to_be_bytes());
self.jumps.push(JumpPatch {
opcode_pc,
operand_pc: def_pos,
target: default,
is_wide: true,
});
self.bytecode
.extend_from_slice(&(pairs.len() as i32).to_be_bytes());
for (key, tgt) in pairs {
self.bytecode.extend_from_slice(&key.to_be_bytes());
let pos = self.bytecode.len();
self.bytecode.extend_from_slice(&0i32.to_be_bytes());
self.jumps.push(JumpPatch {
opcode_pc,
operand_pc: pos,
target: *tgt,
is_wide: true,
});
}
}
pub fn emit_invokedynamic(&mut self, invoke_dynamic_cp_idx: u16) {
self.emit_u8(opcodes::INVOKEDYNAMIC);
self.emit_u16(invoke_dynamic_cp_idx);
self.emit_u8(0);
self.emit_u8(0);
}
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);
if j.is_wide {
let bytes = rel.to_be_bytes();
self.bytecode[j.operand_pc..j.operand_pc + 4].copy_from_slice(&bytes);
} else {
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),
Float(u32),
Long(i64),
Double(u64),
Class(u16),
String(u16),
NameAndType(u16, u16),
Fieldref(u16, u16),
Methodref(u16, u16),
InterfaceMethodref(u16, u16),
MethodHandle(u8, u16),
MethodType(u16),
Dynamic(u16, u16),
InvokeDynamic(u16, u16),
}
#[derive(Debug, Clone)]
enum CpMeta {
Utf8,
Integer,
Float,
Long,
Double,
Class(String),
String,
NameAndType,
MemberRef(String, String, String),
MethodHandle,
MethodType,
Dynamic(String),
InvokeDynamic(String, String),
}
pub struct ConstantPool {
entries: Vec<Vec<u8>>,
metas: Vec<Option<CpMeta>>,
index: HashMap<CpKey, u16>,
}
impl ConstantPool {
pub fn new() -> Self {
Self {
entries: vec![Vec::new()], metas: vec![None],
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.metas.push(Some(CpMeta::Utf8));
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.metas.push(Some(CpMeta::Integer));
self.index.insert(key, idx);
idx
}
pub fn add_float(&mut self, val: f32) -> u16 {
let bits = val.to_bits();
let key = CpKey::Float(bits);
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(4);
entry.extend_from_slice(&bits.to_be_bytes());
self.entries.push(entry);
self.metas.push(Some(CpMeta::Float));
self.index.insert(key, idx);
idx
}
pub fn add_long(&mut self, val: i64) -> u16 {
let key = CpKey::Long(val);
if let Some(&idx) = self.index.get(&key) {
return idx;
}
let idx = self.entries.len() as u16;
let mut entry = Vec::with_capacity(9);
entry.push(5);
entry.extend_from_slice(&val.to_be_bytes());
self.entries.push(entry);
self.metas.push(Some(CpMeta::Long));
self.entries.push(Vec::new());
self.metas.push(None);
self.index.insert(key, idx);
idx
}
pub fn add_double(&mut self, val: f64) -> u16 {
let bits = val.to_bits();
let key = CpKey::Double(bits);
if let Some(&idx) = self.index.get(&key) {
return idx;
}
let idx = self.entries.len() as u16;
let mut entry = Vec::with_capacity(9);
entry.push(6);
entry.extend_from_slice(&bits.to_be_bytes());
self.entries.push(entry);
self.metas.push(Some(CpMeta::Double));
self.entries.push(Vec::new());
self.metas.push(None);
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.metas.push(Some(CpMeta::Class(norm)));
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.metas.push(Some(CpMeta::String));
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.metas.push(Some(CpMeta::NameAndType));
self.index.insert(key, idx);
idx
}
fn add_member_ref_raw(&mut self, tag: u8, owner: &str, name: &str, desc: &str) -> u16 {
let norm_owner = owner.replace('.', "/");
let cls_idx = self.add_class(&norm_owner);
let nat_idx = self.add_name_and_type(name, desc);
let key = match tag {
9 => CpKey::Fieldref(cls_idx, nat_idx),
10 => CpKey::Methodref(cls_idx, nat_idx),
_ => 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(tag);
entry.extend_from_slice(&cls_idx.to_be_bytes());
entry.extend_from_slice(&nat_idx.to_be_bytes());
self.entries.push(entry);
self.metas.push(Some(CpMeta::MemberRef(
norm_owner,
name.to_string(),
desc.to_string(),
)));
self.index.insert(key, idx);
idx
}
pub fn add_fieldref(&mut self, owner: &str, name: &str, desc: &str) -> u16 {
self.add_member_ref_raw(9, owner, name, desc)
}
pub fn add_methodref(&mut self, owner: &str, name: &str, desc: &str) -> u16 {
self.add_member_ref_raw(10, owner, name, desc)
}
pub fn add_interface_methodref(&mut self, owner: &str, name: &str, desc: &str) -> u16 {
self.add_member_ref_raw(11, owner, name, desc)
}
pub fn add_method_handle(&mut self, kind: MethodHandleKind, reference_index: u16) -> u16 {
let kind_u8 = kind as u8;
let key = CpKey::MethodHandle(kind_u8, reference_index);
if let Some(&idx) = self.index.get(&key) {
return idx;
}
let idx = self.entries.len() as u16;
let mut entry = Vec::with_capacity(4);
entry.push(15);
entry.push(kind_u8);
entry.extend_from_slice(&reference_index.to_be_bytes());
self.entries.push(entry);
self.metas.push(Some(CpMeta::MethodHandle));
self.index.insert(key, idx);
idx
}
pub fn add_method_type(&mut self, descriptor: &str) -> u16 {
let desc_idx = self.add_utf8(descriptor);
let key = CpKey::MethodType(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(3);
entry.push(16);
entry.extend_from_slice(&desc_idx.to_be_bytes());
self.entries.push(entry);
self.metas.push(Some(CpMeta::MethodType));
self.index.insert(key, idx);
idx
}
pub fn add_dynamic(&mut self, bsm_attr_idx: u16, name: &str, descriptor: &str) -> u16 {
let nat_idx = self.add_name_and_type(name, descriptor);
let key = CpKey::Dynamic(bsm_attr_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(17);
entry.extend_from_slice(&bsm_attr_idx.to_be_bytes());
entry.extend_from_slice(&nat_idx.to_be_bytes());
self.entries.push(entry);
self.metas
.push(Some(CpMeta::Dynamic(descriptor.to_string())));
self.index.insert(key, idx);
idx
}
pub fn add_invoke_dynamic(&mut self, bsm_attr_idx: u16, name: &str, descriptor: &str) -> u16 {
let nat_idx = self.add_name_and_type(name, descriptor);
let key = CpKey::InvokeDynamic(bsm_attr_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(18);
entry.extend_from_slice(&bsm_attr_idx.to_be_bytes());
entry.extend_from_slice(&nat_idx.to_be_bytes());
self.entries.push(entry);
self.metas.push(Some(CpMeta::InvokeDynamic(
name.to_string(),
descriptor.to_string(),
)));
self.index.insert(key, idx);
idx
}
pub(crate) fn get_class_name(&self, cp_idx: u16) -> Option<String> {
match self.metas.get(cp_idx as usize).and_then(|o| o.as_ref()) {
Some(CpMeta::Class(name)) => Some(name.clone()),
_ => None,
}
}
pub(crate) fn get_member_ref(&self, cp_idx: u16) -> Option<(String, String, String)> {
match self.metas.get(cp_idx as usize).and_then(|o| o.as_ref()) {
Some(CpMeta::MemberRef(o, n, d)) => Some((o.clone(), n.clone(), d.clone())),
_ => None,
}
}
pub(crate) fn get_invoke_dynamic(&self, cp_idx: u16) -> Option<(String, String)> {
match self.metas.get(cp_idx as usize).and_then(|o| o.as_ref()) {
Some(CpMeta::InvokeDynamic(n, d)) => Some((n.clone(), d.clone())),
_ => None,
}
}
pub(crate) fn ldc_verification_type(
&mut self,
cp_idx: u16,
str_class_idx: u16,
cls_class_idx: u16,
) -> Option<VerificationType> {
let meta = self.metas.get(cp_idx as usize).and_then(|o| o.clone())?;
match meta {
CpMeta::Integer => Some(VerificationType::Integer),
CpMeta::Float => Some(VerificationType::Float),
CpMeta::Long => Some(VerificationType::Long),
CpMeta::Double => Some(VerificationType::Double),
CpMeta::String => Some(VerificationType::Object(str_class_idx)),
CpMeta::Class(_) => Some(VerificationType::Object(cls_class_idx)),
CpMeta::MethodHandle => Some(VerificationType::Object(
self.add_class("java/lang/invoke/MethodHandle"),
)),
CpMeta::MethodType => Some(VerificationType::Object(
self.add_class("java/lang/invoke/MethodType"),
)),
CpMeta::Dynamic(desc) => JvmType::parse(&desc)
.ok()
.map(|t| VerificationType::from_jvm_type(&t, self)),
_ => None,
}
}
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) {
if !entry.is_empty() {
out.extend_from_slice(entry);
}
}
}
}
impl Default for ConstantPool {
fn default() -> Self {
Self::new()
}
}
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>,
field_signatures: HashMap<usize, String>,
methods: Vec<MethodWriter>,
method_signatures: HashMap<usize, String>,
annotations: Vec<Annotation>,
invisible_annotations: Vec<Annotation>,
signature: Option<String>,
bootstrap_methods: Vec<BootstrapMethod>,
inner_classes: Vec<InnerClassEntry>,
nest_host: Option<String>,
nest_members: Vec<String>,
}
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(),
field_signatures: HashMap::new(),
methods: Vec::new(),
method_signatures: HashMap::new(),
annotations: Vec::new(),
invisible_annotations: Vec::new(),
signature: None,
bootstrap_methods: Vec::new(),
inner_classes: Vec::new(),
nest_host: None,
nest_members: 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 set_signature(&mut self, signature: impl Into<String>) {
self.signature = Some(signature.into());
}
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_field_with_signature(&mut self, field: FieldWriter, signature: impl Into<String>) {
let idx = self.fields.len();
self.fields.push(field);
self.field_signatures.insert(idx, signature.into());
}
pub fn add_method(&mut self, method: MethodWriter) {
self.methods.push(method);
}
pub fn add_method_with_signature(&mut self, method: MethodWriter, signature: impl Into<String>) {
let idx = self.methods.len();
self.methods.push(method);
self.method_signatures.insert(idx, signature.into());
}
pub fn add_bootstrap_method(&mut self, bootstrap_method_ref: u16, bootstrap_arguments: Vec<u16>) -> u16 {
let entry = BootstrapMethod {
bootstrap_method_ref,
bootstrap_arguments,
};
if let Some(pos) = self.bootstrap_methods.iter().position(|b| b == &entry) {
return pos as u16;
}
let idx = self.bootstrap_methods.len() as u16;
self.bootstrap_methods.push(entry);
idx
}
#[allow(clippy::too_many_arguments)]
pub fn add_lambda_metafactory_bsm(
&mut self,
sam_desc: &str,
impl_kind: MethodHandleKind,
impl_owner: &str,
impl_name: &str,
impl_desc: &str,
impl_is_iface: bool,
instantiated_desc: &str,
) -> u16 {
let bsm_mref = self.cp.add_methodref(
"java/lang/invoke/LambdaMetafactory",
"metafactory",
"(Ljava/lang/invoke/MethodHandles$Lookup;Ljava/lang/String;Ljava/lang/invoke/MethodType;Ljava/lang/invoke/MethodType;Ljava/lang/invoke/MethodHandle;Ljava/lang/invoke/MethodType;)Ljava/lang/invoke/CallSite;",
);
let bsm_handle = self
.cp
.add_method_handle(MethodHandleKind::InvokeStatic, bsm_mref);
let sam_mt = self.cp.add_method_type(sam_desc);
let impl_ref = if impl_is_iface {
self.cp.add_interface_methodref(impl_owner, impl_name, impl_desc)
} else {
self.cp.add_methodref(impl_owner, impl_name, impl_desc)
};
let impl_handle = self.cp.add_method_handle(impl_kind, impl_ref);
let inst_mt = self.cp.add_method_type(instantiated_desc);
self.add_bootstrap_method(bsm_handle, vec![sam_mt, impl_handle, inst_mt])
}
pub fn add_inner_class(&mut self, entry: InnerClassEntry) {
if !self.inner_classes.contains(&entry) {
self.inner_classes.push(entry);
}
}
pub fn set_nest_host(&mut self, host_internal: impl Into<String>) {
self.nest_host = Some(host_internal.into().replace('.', "/"));
}
pub fn add_nest_member(&mut self, member_internal: impl Into<String>) {
let norm = member_internal.into().replace('.', "/");
if !self.nest_members.contains(&norm) {
self.nest_members.push(norm);
}
}
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 (idx, f) in self.fields.iter().enumerate() {
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());
if let Some(sig) = self.field_signatures.get(&idx) {
let sig_attr = cp.add_utf8("Signature");
let sig_idx = cp.add_utf8(sig);
field_bytes.extend_from_slice(&1u16.to_be_bytes());
field_bytes.extend_from_slice(&sig_attr.to_be_bytes());
field_bytes.extend_from_slice(&2u32.to_be_bytes());
field_bytes.extend_from_slice(&sig_idx.to_be_bytes());
} else {
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 (idx, m) in self.methods.iter_mut().enumerate() {
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()?;
if code.auto_stack_map {
let is_static = (m.access_flags & access_flags::ACC_STATIC) != 0;
let (max_stack, max_locals, frames) = crate::stack_map::compute_stack_maps(
&self.this_class_name,
&m.name,
&m.descriptor,
is_static,
&code.bytecode,
&code.exception_table,
&mut cp,
)?;
code.max_stack = code.max_stack.max(max_stack);
code.max_locals = code.max_locals.max(max_locals);
code.frames = frames;
}
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 let Some(sig) = self.method_signatures.get(&idx) {
let sig_name = cp.add_utf8("Signature");
let sig_idx = cp.add_utf8(sig);
attrs.push((sig_name, sig_idx.to_be_bytes().to_vec()));
}
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 let Some(sig) = &self.signature {
let sig_name = cp.add_utf8("Signature");
let sig_idx = cp.add_utf8(sig);
class_attrs.push((sig_name, sig_idx.to_be_bytes().to_vec()));
}
if !self.inner_classes.is_empty() {
let ic_name = cp.add_utf8("InnerClasses");
let mut ic_body = Vec::new();
ic_body.extend_from_slice(&(self.inner_classes.len() as u16).to_be_bytes());
for ic in &self.inner_classes {
let inner_idx = cp.add_class(&ic.inner_class);
let outer_idx = ic
.outer_class
.as_deref()
.map(|s| cp.add_class(s))
.unwrap_or(0);
let name_idx = ic
.inner_name
.as_deref()
.map(|s| cp.add_utf8(s))
.unwrap_or(0);
ic_body.extend_from_slice(&inner_idx.to_be_bytes());
ic_body.extend_from_slice(&outer_idx.to_be_bytes());
ic_body.extend_from_slice(&name_idx.to_be_bytes());
ic_body.extend_from_slice(&ic.access_flags.to_be_bytes());
}
class_attrs.push((ic_name, ic_body));
}
if let Some(host) = &self.nest_host {
let nh_name = cp.add_utf8("NestHost");
let host_idx = cp.add_class(host);
class_attrs.push((nh_name, host_idx.to_be_bytes().to_vec()));
}
if !self.nest_members.is_empty() {
let nm_name = cp.add_utf8("NestMembers");
let mut nm_body = Vec::new();
nm_body.extend_from_slice(&(self.nest_members.len() as u16).to_be_bytes());
for m in &self.nest_members {
let m_idx = cp.add_class(m);
nm_body.extend_from_slice(&m_idx.to_be_bytes());
}
class_attrs.push((nm_name, nm_body));
}
if !self.bootstrap_methods.is_empty() {
let bsm_name = cp.add_utf8("BootstrapMethods");
let mut bsm_body = Vec::new();
bsm_body.extend_from_slice(&(self.bootstrap_methods.len() as u16).to_be_bytes());
for bsm in &self.bootstrap_methods {
bsm_body.extend_from_slice(&bsm.bootstrap_method_ref.to_be_bytes());
bsm_body.extend_from_slice(&(bsm.bootstrap_arguments.len() as u16).to_be_bytes());
for &arg in &bsm.bootstrap_arguments {
bsm_body.extend_from_slice(&arg.to_be_bytes());
}
}
class_attrs.push((bsm_name, bsm_body));
}
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)
}
}