1use std::collections::HashMap;
4
5use fabric_rs_core::descriptor::JvmType;
6
7#[allow(dead_code)]
8pub mod opcodes {
9 pub const ACONST_NULL: u8 = 0x01;
10 pub const ICONST_M1: u8 = 0x02;
11 pub const ICONST_0: u8 = 0x03;
12 pub const ICONST_1: u8 = 0x04;
13 pub const ICONST_2: u8 = 0x05;
14 pub const ICONST_3: u8 = 0x06;
15 pub const ICONST_4: u8 = 0x07;
16 pub const ICONST_5: u8 = 0x08;
17 pub const LCONST_0: u8 = 0x09;
18 pub const LCONST_1: u8 = 0x0A;
19 pub const FCONST_0: u8 = 0x0B;
20 pub const DCONST_0: u8 = 0x0E;
21 pub const BIPUSH: u8 = 0x10;
22 pub const SIPUSH: u8 = 0x11;
23 pub const LDC: u8 = 0x12;
24 pub const LDC_W: u8 = 0x13;
25 pub const LDC2_W: u8 = 0x14;
26 pub const ILOAD: u8 = 0x15;
27 pub const LLOAD: u8 = 0x16;
28 pub const FLOAD: u8 = 0x17;
29 pub const DLOAD: u8 = 0x18;
30 pub const ALOAD: u8 = 0x19;
31 pub const ILOAD_0: u8 = 0x1A;
32 pub const ILOAD_1: u8 = 0x1B;
33 pub const ILOAD_2: u8 = 0x1C;
34 pub const ILOAD_3: u8 = 0x1D;
35 pub const LLOAD_0: u8 = 0x1E;
36 pub const LLOAD_1: u8 = 0x1F;
37 pub const LLOAD_2: u8 = 0x20;
38 pub const LLOAD_3: u8 = 0x21;
39 pub const FLOAD_0: u8 = 0x22;
40 pub const FLOAD_1: u8 = 0x23;
41 pub const FLOAD_2: u8 = 0x24;
42 pub const FLOAD_3: u8 = 0x25;
43 pub const DLOAD_0: u8 = 0x26;
44 pub const DLOAD_1: u8 = 0x27;
45 pub const DLOAD_2: u8 = 0x28;
46 pub const DLOAD_3: u8 = 0x29;
47 pub const ALOAD_0: u8 = 0x2A;
48 pub const ALOAD_1: u8 = 0x2B;
49 pub const ALOAD_2: u8 = 0x2C;
50 pub const ALOAD_3: u8 = 0x2D;
51 pub const AALOAD: u8 = 0x32;
52 pub const ISTORE: u8 = 0x36;
53 pub const LSTORE: u8 = 0x37;
54 pub const FSTORE: u8 = 0x38;
55 pub const DSTORE: u8 = 0x39;
56 pub const ASTORE: u8 = 0x3A;
57 pub const ASTORE_0: u8 = 0x4B;
58 pub const ASTORE_1: u8 = 0x4C;
59 pub const ASTORE_2: u8 = 0x4D;
60 pub const ASTORE_3: u8 = 0x4E;
61 pub const AASTORE: u8 = 0x53;
62 pub const POP: u8 = 0x57;
63 pub const POP2: u8 = 0x58;
64 pub const DUP: u8 = 0x59;
65 pub const LCMP: u8 = 0x94;
66 pub const IFEQ: u8 = 0x99;
67 pub const IFNE: u8 = 0x9A;
68 pub const GOTO: u8 = 0xA7;
69 pub const IRETURN: u8 = 0xAC;
70 pub const LRETURN: u8 = 0xAD;
71 pub const FRETURN: u8 = 0xAE;
72 pub const DRETURN: u8 = 0xAF;
73 pub const ARETURN: u8 = 0xB0;
74 pub const RETURN: u8 = 0xB1;
75 pub const GETSTATIC: u8 = 0xB2;
76 pub const PUTSTATIC: u8 = 0xB3;
77 pub const GETFIELD: u8 = 0xB4;
78 pub const PUTFIELD: u8 = 0xB5;
79 pub const INVOKEVIRTUAL: u8 = 0xB6;
80 pub const INVOKESPECIAL: u8 = 0xB7;
81 pub const INVOKESTATIC: u8 = 0xB8;
82 pub const INVOKEINTERFACE: u8 = 0xB9;
83 pub const NEW: u8 = 0xBB;
84 pub const ANEWARRAY: u8 = 0xBD;
85 pub const ATHROW: u8 = 0xBF;
86 pub const CHECKCAST: u8 = 0xC0;
87 pub const IFNULL: u8 = 0xC6;
88 pub const IFNONNULL: u8 = 0xC7;
89}
90
91#[allow(dead_code)]
92pub mod access_flags {
93 pub const ACC_PUBLIC: u16 = 0x0001;
94 pub const ACC_PRIVATE: u16 = 0x0002;
95 pub const ACC_PROTECTED: u16 = 0x0004;
96 pub const ACC_STATIC: u16 = 0x0008;
97 pub const ACC_FINAL: u16 = 0x0010;
98 pub const ACC_SUPER: u16 = 0x0020;
99 pub const ACC_SYNCHRONIZED: u16 = 0x0020;
100 pub const ACC_VOLATILE: u16 = 0x0040;
101 pub const ACC_BRIDGE: u16 = 0x0040;
102 pub const ACC_VARARGS: u16 = 0x0080;
103 pub const ACC_NATIVE: u16 = 0x0100;
104 pub const ACC_INTERFACE: u16 = 0x0200;
105 pub const ACC_ABSTRACT: u16 = 0x0400;
106 pub const ACC_SYNTHETIC: u16 = 0x1000;
107 pub const ACC_ANNOTATION: u16 = 0x2000;
108 pub const ACC_ENUM: u16 = 0x4000;
109}
110
111#[allow(dead_code)]
112#[derive(Debug, Clone)]
113pub enum ElementValue {
114 String(String),
115 Class(String),
116 Int(i32),
117 Boolean(bool),
118 Enum { type_descriptor: String, const_name: String },
119 Array(Vec<ElementValue>),
120 Annotation(Annotation),
121}
122
123#[derive(Debug, Clone)]
124pub struct Annotation {
125 pub type_descriptor: String,
126 pub element_value_pairs: Vec<(String, ElementValue)>,
127}
128
129#[derive(Debug, Clone, PartialEq, Eq)]
131pub enum VerificationType {
132 Top,
133 Integer,
134 Float,
135 Double,
136 Long,
137 Null,
138 UninitializedThis,
139 Object(u16), Uninitialized(u16),
141}
142
143impl VerificationType {
144 pub fn from_jvm_type(ty: &JvmType, cp: &mut ConstantPool) -> Self {
145 match ty {
146 JvmType::Boolean | JvmType::Byte | JvmType::Char | JvmType::Short | JvmType::Int => {
147 VerificationType::Integer
148 }
149 JvmType::Float => VerificationType::Float,
150 JvmType::Long => VerificationType::Long,
151 JvmType::Double => VerificationType::Double,
152 JvmType::Object(internal) => VerificationType::Object(cp.add_class(internal)),
153 JvmType::Array(_) => VerificationType::Object(cp.add_class(&ty.to_descriptor())),
154 JvmType::Void => VerificationType::Top,
155 }
156 }
157
158 fn write(&self, buf: &mut Vec<u8>) {
159 match self {
160 VerificationType::Top => buf.push(0),
161 VerificationType::Integer => buf.push(1),
162 VerificationType::Float => buf.push(2),
163 VerificationType::Double => buf.push(3),
164 VerificationType::Long => buf.push(4),
165 VerificationType::Null => buf.push(5),
166 VerificationType::UninitializedThis => buf.push(6),
167 VerificationType::Object(cp_idx) => {
168 buf.push(7);
169 buf.extend_from_slice(&cp_idx.to_be_bytes());
170 }
171 VerificationType::Uninitialized(offset) => {
172 buf.push(8);
173 buf.extend_from_slice(&offset.to_be_bytes());
174 }
175 }
176 }
177}
178
179#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
180pub struct LabelId(pub usize);
181
182#[derive(Debug, Clone)]
183struct JumpPatch {
184 opcode_pc: usize,
185 operand_pc: usize,
186 target: LabelId,
187}
188
189#[derive(Debug, Clone)]
190struct FrameEntry {
191 pc: u16,
192 locals: Vec<VerificationType>,
193 stack: Vec<VerificationType>,
194}
195
196#[derive(Debug, Clone)]
197pub struct ExceptionHandler {
198 pub start_pc: u16,
199 pub end_pc: u16,
200 pub handler_pc: u16,
201 pub catch_type: u16, }
203
204#[derive(Debug, Clone)]
205pub struct FieldWriter {
206 pub access_flags: u16,
207 pub name: String,
208 pub descriptor: String,
209}
210
211#[derive(Debug, Clone)]
212pub struct CodeWriter {
213 pub max_stack: u16,
214 pub max_locals: u16,
215 pub bytecode: Vec<u8>,
216 pub exception_table: Vec<ExceptionHandler>,
217 labels: Vec<Option<u16>>,
218 jumps: Vec<JumpPatch>,
219 frames: Vec<FrameEntry>,
220}
221
222impl CodeWriter {
223 pub fn new(max_stack: u16, max_locals: u16) -> Self {
224 Self {
225 max_stack,
226 max_locals,
227 bytecode: Vec::new(),
228 exception_table: Vec::new(),
229 labels: Vec::new(),
230 jumps: Vec::new(),
231 frames: Vec::new(),
232 }
233 }
234
235 pub fn current_pc(&self) -> u16 {
236 self.bytecode.len() as u16
237 }
238
239 pub fn new_label(&mut self) -> LabelId {
240 let id = LabelId(self.labels.len());
241 self.labels.push(None);
242 id
243 }
244
245 pub fn bind_label(&mut self, label: LabelId) {
246 self.labels[label.0] = Some(self.current_pc());
247 }
248
249 pub fn bind_label_with_frame(
251 &mut self,
252 label: LabelId,
253 locals: Vec<VerificationType>,
254 stack: Vec<VerificationType>,
255 ) {
256 let pc = self.current_pc();
257 self.labels[label.0] = Some(pc);
258 self.frames.push(FrameEntry { pc, locals, stack });
259 }
260
261 pub fn emit_u8(&mut self, b: u8) {
262 self.bytecode.push(b);
263 }
264
265 pub fn emit_u16(&mut self, val: u16) {
266 self.bytecode.extend_from_slice(&val.to_be_bytes());
267 }
268
269 pub fn emit_i16(&mut self, val: i16) {
270 self.bytecode.extend_from_slice(&val.to_be_bytes());
271 }
272
273 pub fn emit_jump(&mut self, opcode: u8, target: LabelId) {
274 let opcode_pc = self.bytecode.len();
275 self.emit_u8(opcode);
276 let operand_pc = self.bytecode.len();
277 self.emit_i16(0);
278 self.jumps.push(JumpPatch {
279 opcode_pc,
280 operand_pc,
281 target,
282 });
283 }
284
285 pub fn emit_int_const(&mut self, value: i32) {
286 match value {
287 -1 => self.emit_u8(opcodes::ICONST_M1),
288 0 => self.emit_u8(opcodes::ICONST_0),
289 1 => self.emit_u8(opcodes::ICONST_1),
290 2 => self.emit_u8(opcodes::ICONST_2),
291 3 => self.emit_u8(opcodes::ICONST_3),
292 4 => self.emit_u8(opcodes::ICONST_4),
293 5 => self.emit_u8(opcodes::ICONST_5),
294 -128..=127 => {
295 self.emit_u8(opcodes::BIPUSH);
296 self.emit_u8(value as i8 as u8);
297 }
298 -32768..=32767 => {
299 self.emit_u8(opcodes::SIPUSH);
300 self.emit_i16(value as i16);
301 }
302 _ => panic!("emit_int_const out of i16 range: use LDC with cp.add_integer"),
303 }
304 }
305
306 pub fn emit_ldc(&mut self, cp_idx: u16) {
307 if cp_idx <= 255 {
308 self.emit_u8(opcodes::LDC);
309 self.emit_u8(cp_idx as u8);
310 } else {
311 self.emit_u8(opcodes::LDC_W);
312 self.emit_u16(cp_idx);
313 }
314 }
315
316 pub fn emit_load(&mut self, ty: &JvmType, slot: u16) {
317 match ty {
318 JvmType::Boolean
319 | JvmType::Byte
320 | JvmType::Char
321 | JvmType::Short
322 | JvmType::Int => match slot {
323 0 => self.emit_u8(opcodes::ILOAD_0),
324 1 => self.emit_u8(opcodes::ILOAD_1),
325 2 => self.emit_u8(opcodes::ILOAD_2),
326 3 => self.emit_u8(opcodes::ILOAD_3),
327 _ => {
328 self.emit_u8(opcodes::ILOAD);
329 self.emit_u8(slot as u8);
330 }
331 },
332 JvmType::Long => match slot {
333 0 => self.emit_u8(opcodes::LLOAD_0),
334 1 => self.emit_u8(opcodes::LLOAD_1),
335 2 => self.emit_u8(opcodes::LLOAD_2),
336 3 => self.emit_u8(opcodes::LLOAD_3),
337 _ => {
338 self.emit_u8(opcodes::LLOAD);
339 self.emit_u8(slot as u8);
340 }
341 },
342 JvmType::Float => match slot {
343 0 => self.emit_u8(opcodes::FLOAD_0),
344 1 => self.emit_u8(opcodes::FLOAD_1),
345 2 => self.emit_u8(opcodes::FLOAD_2),
346 3 => self.emit_u8(opcodes::FLOAD_3),
347 _ => {
348 self.emit_u8(opcodes::FLOAD);
349 self.emit_u8(slot as u8);
350 }
351 },
352 JvmType::Double => match slot {
353 0 => self.emit_u8(opcodes::DLOAD_0),
354 1 => self.emit_u8(opcodes::DLOAD_1),
355 2 => self.emit_u8(opcodes::DLOAD_2),
356 3 => self.emit_u8(opcodes::DLOAD_3),
357 _ => {
358 self.emit_u8(opcodes::DLOAD);
359 self.emit_u8(slot as u8);
360 }
361 },
362 JvmType::Object(_) | JvmType::Array(_) => match slot {
363 0 => self.emit_u8(opcodes::ALOAD_0),
364 1 => self.emit_u8(opcodes::ALOAD_1),
365 2 => self.emit_u8(opcodes::ALOAD_2),
366 3 => self.emit_u8(opcodes::ALOAD_3),
367 _ => {
368 self.emit_u8(opcodes::ALOAD);
369 self.emit_u8(slot as u8);
370 }
371 },
372 JvmType::Void => {}
373 }
374 }
375
376 pub fn emit_aload(&mut self, slot: u16) {
377 self.emit_load(&JvmType::Object("java/lang/Object".to_string()), slot);
378 }
379
380 pub fn emit_astore(&mut self, slot: u16) {
381 match slot {
382 0 => self.emit_u8(opcodes::ASTORE_0),
383 1 => self.emit_u8(opcodes::ASTORE_1),
384 2 => self.emit_u8(opcodes::ASTORE_2),
385 3 => self.emit_u8(opcodes::ASTORE_3),
386 _ => {
387 self.emit_u8(opcodes::ASTORE);
388 self.emit_u8(slot as u8);
389 }
390 }
391 }
392
393 pub fn emit_return(&mut self, ty: &JvmType) {
394 match ty {
395 JvmType::Void => self.emit_u8(opcodes::RETURN),
396 JvmType::Boolean
397 | JvmType::Byte
398 | JvmType::Char
399 | JvmType::Short
400 | JvmType::Int => self.emit_u8(opcodes::IRETURN),
401 JvmType::Long => self.emit_u8(opcodes::LRETURN),
402 JvmType::Float => self.emit_u8(opcodes::FRETURN),
403 JvmType::Double => self.emit_u8(opcodes::DRETURN),
404 JvmType::Object(_) | JvmType::Array(_) => self.emit_u8(opcodes::ARETURN),
405 }
406 }
407
408 pub fn emit_box_if_primitive(&mut self, cp: &mut ConstantPool, ty: &JvmType) {
410 let (box_cls, desc) = match ty {
411 JvmType::Boolean => ("java/lang/Boolean", "(Z)Ljava/lang/Boolean;"),
412 JvmType::Byte => ("java/lang/Byte", "(B)Ljava/lang/Byte;"),
413 JvmType::Char => ("java/lang/Character", "(C)Ljava/lang/Character;"),
414 JvmType::Short => ("java/lang/Short", "(S)Ljava/lang/Short;"),
415 JvmType::Int => ("java/lang/Integer", "(I)Ljava/lang/Integer;"),
416 JvmType::Long => ("java/lang/Long", "(J)Ljava/lang/Long;"),
417 JvmType::Float => ("java/lang/Float", "(F)Ljava/lang/Float;"),
418 JvmType::Double => ("java/lang/Double", "(D)Ljava/lang/Double;"),
419 JvmType::Void | JvmType::Object(_) | JvmType::Array(_) => return,
420 };
421 let mref = cp.add_methodref(box_cls, "valueOf", desc);
422 self.emit_u8(opcodes::INVOKESTATIC);
423 self.emit_u16(mref);
424 }
425
426 pub fn emit_unbox_or_cast(&mut self, cp: &mut ConstantPool, ty: &JvmType) {
428 match ty {
429 JvmType::Void => {
430 self.emit_u8(opcodes::POP);
431 }
432 JvmType::Boolean => {
433 let c = cp.add_class("java/lang/Boolean");
434 let m = cp.add_methodref("java/lang/Boolean", "booleanValue", "()Z");
435 self.emit_u8(opcodes::CHECKCAST);
436 self.emit_u16(c);
437 self.emit_u8(opcodes::INVOKEVIRTUAL);
438 self.emit_u16(m);
439 }
440 JvmType::Byte => {
441 let c = cp.add_class("java/lang/Number");
442 let m = cp.add_methodref("java/lang/Number", "byteValue", "()B");
443 self.emit_u8(opcodes::CHECKCAST);
444 self.emit_u16(c);
445 self.emit_u8(opcodes::INVOKEVIRTUAL);
446 self.emit_u16(m);
447 }
448 JvmType::Short => {
449 let c = cp.add_class("java/lang/Number");
450 let m = cp.add_methodref("java/lang/Number", "shortValue", "()S");
451 self.emit_u8(opcodes::CHECKCAST);
452 self.emit_u16(c);
453 self.emit_u8(opcodes::INVOKEVIRTUAL);
454 self.emit_u16(m);
455 }
456 JvmType::Char => {
457 let c = cp.add_class("java/lang/Character");
458 let m = cp.add_methodref("java/lang/Character", "charValue", "()C");
459 self.emit_u8(opcodes::CHECKCAST);
460 self.emit_u16(c);
461 self.emit_u8(opcodes::INVOKEVIRTUAL);
462 self.emit_u16(m);
463 }
464 JvmType::Int => {
465 let c = cp.add_class("java/lang/Number");
466 let m = cp.add_methodref("java/lang/Number", "intValue", "()I");
467 self.emit_u8(opcodes::CHECKCAST);
468 self.emit_u16(c);
469 self.emit_u8(opcodes::INVOKEVIRTUAL);
470 self.emit_u16(m);
471 }
472 JvmType::Long => {
473 let c = cp.add_class("java/lang/Number");
474 let m = cp.add_methodref("java/lang/Number", "longValue", "()J");
475 self.emit_u8(opcodes::CHECKCAST);
476 self.emit_u16(c);
477 self.emit_u8(opcodes::INVOKEVIRTUAL);
478 self.emit_u16(m);
479 }
480 JvmType::Float => {
481 let c = cp.add_class("java/lang/Number");
482 let m = cp.add_methodref("java/lang/Number", "floatValue", "()F");
483 self.emit_u8(opcodes::CHECKCAST);
484 self.emit_u16(c);
485 self.emit_u8(opcodes::INVOKEVIRTUAL);
486 self.emit_u16(m);
487 }
488 JvmType::Double => {
489 let c = cp.add_class("java/lang/Number");
490 let m = cp.add_methodref("java/lang/Number", "doubleValue", "()D");
491 self.emit_u8(opcodes::CHECKCAST);
492 self.emit_u16(c);
493 self.emit_u8(opcodes::INVOKEVIRTUAL);
494 self.emit_u16(m);
495 }
496 JvmType::Object(internal) => {
497 if internal != "java/lang/Object" {
498 let c = cp.add_class(internal);
499 self.emit_u8(opcodes::CHECKCAST);
500 self.emit_u16(c);
501 }
502 }
503 JvmType::Array(_) => {
504 let c = cp.add_class(&ty.to_descriptor());
505 self.emit_u8(opcodes::CHECKCAST);
506 self.emit_u16(c);
507 }
508 }
509 }
510
511 pub fn finalize_jumps(&mut self) -> Result<(), String> {
512 for j in &self.jumps {
513 let target_pc = self.labels[j.target.0]
514 .ok_or_else(|| format!("Unbound jump label {:?}", j.target))?;
515 let rel = (target_pc as i32) - (j.opcode_pc as i32);
516 let rel16 = i16::try_from(rel).map_err(|_| "Jump offset overflow".to_string())?;
517 let bytes = rel16.to_be_bytes();
518 self.bytecode[j.operand_pc] = bytes[0];
519 self.bytecode[j.operand_pc + 1] = bytes[1];
520 }
521 Ok(())
522 }
523
524 fn encode_stack_map_table(&self) -> Option<Vec<u8>> {
525 if self.frames.is_empty() {
526 return None;
527 }
528 let mut sorted = self.frames.clone();
529 sorted.sort_by_key(|f| f.pc);
530 sorted.dedup_by_key(|f| f.pc);
531
532 let mut buf = Vec::new();
533 buf.extend_from_slice(&(sorted.len() as u16).to_be_bytes());
534 let mut prev_pc: Option<u16> = None;
535
536 for frame in sorted {
537 let offset_delta = match prev_pc {
538 None => frame.pc,
539 Some(p) => frame.pc - p - 1,
540 };
541 prev_pc = Some(frame.pc);
542
543 buf.push(255);
545 buf.extend_from_slice(&offset_delta.to_be_bytes());
546 buf.extend_from_slice(&(frame.locals.len() as u16).to_be_bytes());
547 for loc in &frame.locals {
548 loc.write(&mut buf);
549 }
550 buf.extend_from_slice(&(frame.stack.len() as u16).to_be_bytes());
551 for st in &frame.stack {
552 st.write(&mut buf);
553 }
554 }
555 Some(buf)
556 }
557}
558
559#[derive(Debug, Clone)]
560pub struct MethodWriter {
561 pub access_flags: u16,
562 pub name: String,
563 pub descriptor: String,
564 pub code: Option<CodeWriter>,
565 pub annotations: Vec<Annotation>,
566}
567
568#[derive(Debug, Clone, PartialEq, Eq, Hash)]
569enum CpKey {
570 Utf8(String),
571 Integer(i32),
572 Class(u16),
573 String(u16),
574 NameAndType(u16, u16),
575 Fieldref(u16, u16),
576 Methodref(u16, u16),
577 InterfaceMethodref(u16, u16),
578}
579
580pub struct ConstantPool {
581 entries: Vec<Vec<u8>>,
582 index: HashMap<CpKey, u16>,
583}
584
585impl ConstantPool {
586 pub fn new() -> Self {
587 Self {
588 entries: vec![Vec::new()], index: HashMap::new(),
590 }
591 }
592
593 pub fn add_utf8(&mut self, s: &str) -> u16 {
594 let key = CpKey::Utf8(s.to_string());
595 if let Some(&idx) = self.index.get(&key) {
596 return idx;
597 }
598 let idx = self.entries.len() as u16;
599 let bytes = s.as_bytes();
600 let mut entry = Vec::with_capacity(3 + bytes.len());
601 entry.push(1);
602 entry.extend_from_slice(&(bytes.len() as u16).to_be_bytes());
603 entry.extend_from_slice(bytes);
604 self.entries.push(entry);
605 self.index.insert(key, idx);
606 idx
607 }
608
609 pub fn add_integer(&mut self, val: i32) -> u16 {
610 let key = CpKey::Integer(val);
611 if let Some(&idx) = self.index.get(&key) {
612 return idx;
613 }
614 let idx = self.entries.len() as u16;
615 let mut entry = Vec::with_capacity(5);
616 entry.push(3);
617 entry.extend_from_slice(&val.to_be_bytes());
618 self.entries.push(entry);
619 self.index.insert(key, idx);
620 idx
621 }
622
623 pub fn add_class(&mut self, internal_name: &str) -> u16 {
624 let norm = internal_name.replace('.', "/");
625 let name_idx = self.add_utf8(&norm);
626 let key = CpKey::Class(name_idx);
627 if let Some(&idx) = self.index.get(&key) {
628 return idx;
629 }
630 let idx = self.entries.len() as u16;
631 let mut entry = Vec::with_capacity(3);
632 entry.push(7);
633 entry.extend_from_slice(&name_idx.to_be_bytes());
634 self.entries.push(entry);
635 self.index.insert(key, idx);
636 idx
637 }
638
639 pub fn add_string(&mut self, s: &str) -> u16 {
640 let utf8_idx = self.add_utf8(s);
641 let key = CpKey::String(utf8_idx);
642 if let Some(&idx) = self.index.get(&key) {
643 return idx;
644 }
645 let idx = self.entries.len() as u16;
646 let mut entry = Vec::with_capacity(3);
647 entry.push(8);
648 entry.extend_from_slice(&utf8_idx.to_be_bytes());
649 self.entries.push(entry);
650 self.index.insert(key, idx);
651 idx
652 }
653
654 pub fn add_name_and_type(&mut self, name: &str, desc: &str) -> u16 {
655 let name_idx = self.add_utf8(name);
656 let desc_idx = self.add_utf8(desc);
657 let key = CpKey::NameAndType(name_idx, desc_idx);
658 if let Some(&idx) = self.index.get(&key) {
659 return idx;
660 }
661 let idx = self.entries.len() as u16;
662 let mut entry = Vec::with_capacity(5);
663 entry.push(12);
664 entry.extend_from_slice(&name_idx.to_be_bytes());
665 entry.extend_from_slice(&desc_idx.to_be_bytes());
666 self.entries.push(entry);
667 self.index.insert(key, idx);
668 idx
669 }
670
671 pub fn add_fieldref(&mut self, owner: &str, name: &str, desc: &str) -> u16 {
672 let cls_idx = self.add_class(owner);
673 let nat_idx = self.add_name_and_type(name, desc);
674 let key = CpKey::Fieldref(cls_idx, nat_idx);
675 if let Some(&idx) = self.index.get(&key) {
676 return idx;
677 }
678 let idx = self.entries.len() as u16;
679 let mut entry = Vec::with_capacity(5);
680 entry.push(9);
681 entry.extend_from_slice(&cls_idx.to_be_bytes());
682 entry.extend_from_slice(&nat_idx.to_be_bytes());
683 self.entries.push(entry);
684 self.index.insert(key, idx);
685 idx
686 }
687
688 pub fn add_methodref(&mut self, owner: &str, name: &str, desc: &str) -> u16 {
689 let cls_idx = self.add_class(owner);
690 let nat_idx = self.add_name_and_type(name, desc);
691 let key = CpKey::Methodref(cls_idx, nat_idx);
692 if let Some(&idx) = self.index.get(&key) {
693 return idx;
694 }
695 let idx = self.entries.len() as u16;
696 let mut entry = Vec::with_capacity(5);
697 entry.push(10);
698 entry.extend_from_slice(&cls_idx.to_be_bytes());
699 entry.extend_from_slice(&nat_idx.to_be_bytes());
700 self.entries.push(entry);
701 self.index.insert(key, idx);
702 idx
703 }
704
705 pub fn add_interface_methodref(&mut self, owner: &str, name: &str, desc: &str) -> u16 {
706 let cls_idx = self.add_class(owner);
707 let nat_idx = self.add_name_and_type(name, desc);
708 let key = CpKey::InterfaceMethodref(cls_idx, nat_idx);
709 if let Some(&idx) = self.index.get(&key) {
710 return idx;
711 }
712 let idx = self.entries.len() as u16;
713 let mut entry = Vec::with_capacity(5);
714 entry.push(11);
715 entry.extend_from_slice(&cls_idx.to_be_bytes());
716 entry.extend_from_slice(&nat_idx.to_be_bytes());
717 self.entries.push(entry);
718 self.index.insert(key, idx);
719 idx
720 }
721
722 fn write(&self, out: &mut Vec<u8>) {
723 out.extend_from_slice(&(self.entries.len() as u16).to_be_bytes());
724 for entry in self.entries.iter().skip(1) {
725 out.extend_from_slice(entry);
726 }
727 }
728}
729
730pub struct ClassWriter {
732 pub major_version: u16,
733 pub access_flags: u16,
734 pub this_class_name: String,
735 pub cp: ConstantPool,
736 this_class: u16,
737 super_class: u16,
738 interfaces: Vec<u16>,
739 fields: Vec<FieldWriter>,
740 methods: Vec<MethodWriter>,
741 annotations: Vec<Annotation>,
742 invisible_annotations: Vec<Annotation>,
743}
744
745impl ClassWriter {
746 pub fn new(
747 this_class: &str,
748 super_class: &str,
749 access_flags: u16,
750 java_version: u16,
751 ) -> Self {
752 let mut cp = ConstantPool::new();
753 let this_idx = cp.add_class(this_class);
754 let super_idx = cp.add_class(super_class);
755 let major_version = match java_version {
756 8 => 52,
757 16 => 60,
758 17 => 61,
759 21 => 65,
760 25 => 69,
761 v if v >= 45 => v,
762 _ => 65,
763 };
764 Self {
765 major_version,
766 access_flags,
767 this_class_name: this_class.replace('.', "/"),
768 cp,
769 this_class: this_idx,
770 super_class: super_idx,
771 interfaces: Vec::new(),
772 fields: Vec::new(),
773 methods: Vec::new(),
774 annotations: Vec::new(),
775 invisible_annotations: Vec::new(),
776 }
777 }
778
779 pub fn add_interface(&mut self, iface: &str) {
780 let idx = self.cp.add_class(iface);
781 if !self.interfaces.contains(&idx) {
782 self.interfaces.push(idx);
783 }
784 }
785
786 pub fn add_annotation(&mut self, ann: Annotation) {
787 self.annotations.push(ann);
788 }
789
790 pub fn add_invisible_annotation(&mut self, ann: Annotation) {
791 self.invisible_annotations.push(ann);
792 }
793
794 pub fn add_field(&mut self, field: FieldWriter) {
795 self.fields.push(field);
796 }
797
798 pub fn add_method(&mut self, method: MethodWriter) {
799 self.methods.push(method);
800 }
801
802 fn write_element_value(cp: &mut ConstantPool, ev: &ElementValue, out: &mut Vec<u8>) {
803 match ev {
804 ElementValue::String(s) => {
805 out.push(b's');
806 out.extend_from_slice(&cp.add_utf8(s).to_be_bytes());
807 }
808 ElementValue::Class(desc) => {
809 out.push(b'c');
810 out.extend_from_slice(&cp.add_utf8(desc).to_be_bytes());
811 }
812 ElementValue::Int(v) => {
813 out.push(b'I');
814 out.extend_from_slice(&cp.add_integer(*v).to_be_bytes());
815 }
816 ElementValue::Boolean(b) => {
817 out.push(b'Z');
818 out.extend_from_slice(&cp.add_integer(if *b { 1 } else { 0 }).to_be_bytes());
819 }
820 ElementValue::Enum {
821 type_descriptor,
822 const_name,
823 } => {
824 out.push(b'e');
825 out.extend_from_slice(&cp.add_utf8(type_descriptor).to_be_bytes());
826 out.extend_from_slice(&cp.add_utf8(const_name).to_be_bytes());
827 }
828 ElementValue::Array(items) => {
829 out.push(b'[');
830 out.extend_from_slice(&(items.len() as u16).to_be_bytes());
831 for item in items {
832 Self::write_element_value(cp, item, out);
833 }
834 }
835 ElementValue::Annotation(ann) => {
836 out.push(b'@');
837 Self::write_annotation(cp, ann, out);
838 }
839 }
840 }
841
842 fn write_annotation(cp: &mut ConstantPool, ann: &Annotation, out: &mut Vec<u8>) {
843 let type_idx = cp.add_utf8(&ann.type_descriptor);
844 out.extend_from_slice(&type_idx.to_be_bytes());
845 out.extend_from_slice(&(ann.element_value_pairs.len() as u16).to_be_bytes());
846 for (name, val) in &ann.element_value_pairs {
847 let name_idx = cp.add_utf8(name);
848 out.extend_from_slice(&name_idx.to_be_bytes());
849 Self::write_element_value(cp, val, out);
850 }
851 }
852
853 fn encode_annotations_attr(cp: &mut ConstantPool, anns: &[Annotation]) -> Vec<u8> {
854 let mut attr = Vec::new();
855 attr.extend_from_slice(&(anns.len() as u16).to_be_bytes());
856 for ann in anns {
857 Self::write_annotation(cp, ann, &mut attr);
858 }
859 attr
860 }
861
862 pub fn finish(mut self) -> Result<Vec<u8>, String> {
863 let mut cp = self.cp;
864
865 let mut field_bytes = Vec::new();
866 field_bytes.extend_from_slice(&(self.fields.len() as u16).to_be_bytes());
867 for f in &self.fields {
868 field_bytes.extend_from_slice(&f.access_flags.to_be_bytes());
869 field_bytes.extend_from_slice(&cp.add_utf8(&f.name).to_be_bytes());
870 field_bytes.extend_from_slice(&cp.add_utf8(&f.descriptor).to_be_bytes());
871 field_bytes.extend_from_slice(&0u16.to_be_bytes()); }
873
874 let mut method_bytes = Vec::new();
875 method_bytes.extend_from_slice(&(self.methods.len() as u16).to_be_bytes());
876 for m in &mut self.methods {
877 method_bytes.extend_from_slice(&m.access_flags.to_be_bytes());
878 method_bytes.extend_from_slice(&cp.add_utf8(&m.name).to_be_bytes());
879 method_bytes.extend_from_slice(&cp.add_utf8(&m.descriptor).to_be_bytes());
880
881 let mut attrs: Vec<(u16, Vec<u8>)> = Vec::new();
882 if let Some(code) = m.code.as_mut() {
883 code.finalize_jumps()?;
884 let code_attr_name = cp.add_utf8("Code");
885 let mut code_body = Vec::new();
886 code_body.extend_from_slice(&code.max_stack.to_be_bytes());
887 code_body.extend_from_slice(&code.max_locals.to_be_bytes());
888 code_body.extend_from_slice(&(code.bytecode.len() as u32).to_be_bytes());
889 code_body.extend_from_slice(&code.bytecode);
890
891 code_body.extend_from_slice(&(code.exception_table.len() as u16).to_be_bytes());
892 for ex in &code.exception_table {
893 code_body.extend_from_slice(&ex.start_pc.to_be_bytes());
894 code_body.extend_from_slice(&ex.end_pc.to_be_bytes());
895 code_body.extend_from_slice(&ex.handler_pc.to_be_bytes());
896 code_body.extend_from_slice(&ex.catch_type.to_be_bytes());
897 }
898
899 if let Some(smt) = code.encode_stack_map_table() {
900 let smt_name = cp.add_utf8("StackMapTable");
901 code_body.extend_from_slice(&1u16.to_be_bytes());
902 code_body.extend_from_slice(&smt_name.to_be_bytes());
903 code_body.extend_from_slice(&(smt.len() as u32).to_be_bytes());
904 code_body.extend_from_slice(&smt);
905 } else {
906 code_body.extend_from_slice(&0u16.to_be_bytes());
907 }
908 attrs.push((code_attr_name, code_body));
909 }
910
911 if !m.annotations.is_empty() {
912 let rva_name = cp.add_utf8("RuntimeVisibleAnnotations");
913 let rva_body = Self::encode_annotations_attr(&mut cp, &m.annotations);
914 attrs.push((rva_name, rva_body));
915 }
916
917 method_bytes.extend_from_slice(&(attrs.len() as u16).to_be_bytes());
918 for (name_idx, body) in attrs {
919 method_bytes.extend_from_slice(&name_idx.to_be_bytes());
920 method_bytes.extend_from_slice(&(body.len() as u32).to_be_bytes());
921 method_bytes.extend_from_slice(&body);
922 }
923 }
924
925 let mut class_attrs: Vec<(u16, Vec<u8>)> = Vec::new();
926 if !self.annotations.is_empty() {
927 let rva_name = cp.add_utf8("RuntimeVisibleAnnotations");
928 let rva_body = Self::encode_annotations_attr(&mut cp, &self.annotations);
929 class_attrs.push((rva_name, rva_body));
930 }
931 if !self.invisible_annotations.is_empty() {
932 let ria_name = cp.add_utf8("RuntimeInvisibleAnnotations");
933 let ria_body = Self::encode_annotations_attr(&mut cp, &self.invisible_annotations);
934 class_attrs.push((ria_name, ria_body));
935 }
936
937 let mut out = Vec::with_capacity(512);
938 out.extend_from_slice(&0xCAFEBABEu32.to_be_bytes());
939 out.extend_from_slice(&0u16.to_be_bytes());
940 out.extend_from_slice(&self.major_version.to_be_bytes());
941 cp.write(&mut out);
942 out.extend_from_slice(&self.access_flags.to_be_bytes());
943 out.extend_from_slice(&self.this_class.to_be_bytes());
944 out.extend_from_slice(&self.super_class.to_be_bytes());
945 out.extend_from_slice(&(self.interfaces.len() as u16).to_be_bytes());
946 for iface in &self.interfaces {
947 out.extend_from_slice(&iface.to_be_bytes());
948 }
949 out.extend_from_slice(&field_bytes);
950 out.extend_from_slice(&method_bytes);
951 out.extend_from_slice(&(class_attrs.len() as u16).to_be_bytes());
952 for (name_idx, body) in class_attrs {
953 out.extend_from_slice(&name_idx.to_be_bytes());
954 out.extend_from_slice(&(body.len() as u32).to_be_bytes());
955 out.extend_from_slice(&body);
956 }
957
958 Ok(out)
959 }
960}