Skip to main content

fabric_rs_codegen/
stack_map.rs

1//! Automatic JVM CFG dataflow analyzer for `StackMapTable` generation and `max_stack`/`max_locals`.
2
3use std::collections::{BTreeMap, BTreeSet, VecDeque};
4
5use fabric_rs_core::descriptor::{JvmType, MethodDescriptor};
6
7use crate::jvm_writer::{opcodes, ConstantPool, ExceptionHandler, FrameEntry, VerificationType};
8
9/// Slot representation inside the dataflow local-variable table.
10///
11/// The second slot of a `long` or `double` local variable is represented as [`LocalSlot::WideSecond`]
12/// so slot indices match JVM `xload`/`xstore` numbering while [`to_stack_map_locals`] skips it per
13/// JVMS ยง4.7.4 (`ITEM_Long` and `ITEM_Double` encode two local slots in one verification entry).
14#[derive(Debug, Clone, PartialEq, Eq)]
15enum LocalSlot {
16    Val(VerificationType),
17    WideSecond,
18}
19
20#[derive(Debug, Clone, PartialEq, Eq)]
21struct AbstractFrame {
22    locals: Vec<LocalSlot>,
23    stack: Vec<VerificationType>,
24}
25
26impl AbstractFrame {
27    fn ensure_local_len(&mut self, len: usize) {
28        if self.locals.len() < len {
29            self.locals.resize(len, LocalSlot::Val(VerificationType::Top));
30        }
31    }
32
33    fn set_local(&mut self, slot: usize, vtype: VerificationType) {
34        let wide = is_wide_vtype(&vtype);
35        let needed = slot + if wide { 2 } else { 1 };
36        self.ensure_local_len(needed);
37        // If overwriting slot `s` which used to hold the second half of a wide variable at `s - 1`,
38        // invalidate `s - 1` so verifier state remains consistent.
39        if slot > 0 && self.locals[slot] == LocalSlot::WideSecond {
40            self.locals[slot - 1] = LocalSlot::Val(VerificationType::Top);
41        }
42        // If overwriting slot `s` that used to be the first half of a wide variable, invalidate `s + 1`.
43        if slot + 1 < self.locals.len() && self.locals[slot + 1] == LocalSlot::WideSecond {
44            self.locals[slot + 1] = LocalSlot::Val(VerificationType::Top);
45        }
46        self.locals[slot] = LocalSlot::Val(vtype);
47        if wide {
48            if slot + 2 < self.locals.len() && self.locals[slot + 2] == LocalSlot::WideSecond {
49                // slot + 1 was itself a 1st half of a wide value (impossible after invalidation unless malformed); keep clean.
50            }
51            self.locals[slot + 1] = LocalSlot::WideSecond;
52        }
53    }
54
55    fn get_local(&self, slot: usize) -> VerificationType {
56        match self.locals.get(slot) {
57            Some(LocalSlot::Val(v)) => v.clone(),
58            _ => VerificationType::Top,
59        }
60    }
61
62    fn push(&mut self, vtype: VerificationType) {
63        self.stack.push(vtype);
64    }
65
66    fn pop(&mut self) -> Result<VerificationType, String> {
67        self.stack
68            .pop()
69            .ok_or_else(|| "Operand stack underflow during CFG analysis".to_string())
70    }
71
72    fn pop_n(&mut self, n: usize) -> Result<Vec<VerificationType>, String> {
73        if self.stack.len() < n {
74            return Err(format!(
75                "Operand stack underflow: needed {n} values, found {}",
76                self.stack.len()
77            ));
78        }
79        let start = self.stack.len() - n;
80        Ok(self.stack.drain(start..).collect())
81    }
82
83    fn stack_units(&self) -> u16 {
84        self.stack
85            .iter()
86            .map(|v| if is_wide_vtype(v) { 2 } else { 1 })
87            .sum()
88    }
89
90    fn replace_uninitialized(&mut self, target: &VerificationType, initialized: VerificationType) {
91        for slot in &mut self.locals {
92            if let LocalSlot::Val(v) = slot
93                && v == target {
94                    *v = initialized.clone();
95                }
96        }
97        for v in &mut self.stack {
98            if v == target {
99                *v = initialized.clone();
100            }
101        }
102    }
103
104    fn to_frame_entry(&self, pc: u16) -> FrameEntry {
105        let mut locals = Vec::new();
106        for slot in &self.locals {
107            if let LocalSlot::Val(v) = slot {
108                locals.push(v.clone());
109            }
110        }
111        while matches!(locals.last(), Some(VerificationType::Top)) {
112            locals.pop();
113        }
114        FrameEntry {
115            pc,
116            locals,
117            stack: self.stack.clone(),
118        }
119    }
120}
121
122fn is_wide_vtype(v: &VerificationType) -> bool {
123    matches!(v, VerificationType::Long | VerificationType::Double)
124}
125
126fn read_i16(code: &[u8], pos: usize) -> Result<i16, String> {
127    if pos + 2 > code.len() {
128        return Err("Unexpected end of bytecode reading i16".to_string());
129    }
130    Ok(i16::from_be_bytes([code[pos], code[pos + 1]]))
131}
132
133fn read_u16(code: &[u8], pos: usize) -> Result<u16, String> {
134    if pos + 2 > code.len() {
135        return Err("Unexpected end of bytecode reading u16".to_string());
136    }
137    Ok(u16::from_be_bytes([code[pos], code[pos + 1]]))
138}
139
140fn read_i32(code: &[u8], pos: usize) -> Result<i32, String> {
141    if pos + 4 > code.len() {
142        return Err("Unexpected end of bytecode reading i32".to_string());
143    }
144    Ok(i32::from_be_bytes([
145        code[pos],
146        code[pos + 1],
147        code[pos + 2],
148        code[pos + 3],
149    ]))
150}
151
152#[derive(Debug)]
153struct DecodedInsn {
154    op: u8,
155    next_pc: usize,
156    fallthrough: bool,
157    branch_targets: Vec<u16>,
158    operand_u16: u16,
159    operand_u8: u8,
160    wide_slot: Option<u16>,
161    multi_dims: u8,
162}
163
164fn decode_insn(code: &[u8], pc: usize) -> Result<DecodedInsn, String> {
165    let op = *code
166        .get(pc)
167        .ok_or_else(|| format!("Invalid bytecode PC {pc}"))?;
168    let mut d = DecodedInsn {
169        op,
170        next_pc: pc + 1,
171        fallthrough: true,
172        branch_targets: Vec::new(),
173        operand_u16: 0,
174        operand_u8: 0,
175        wide_slot: None,
176        multi_dims: 0,
177    };
178
179    match op {
180        // 1-byte zero-operand opcodes
181        0x00..=0x0F
182        | 0x1A..=0x35
183        | 0x3B..=0x83
184        | 0x85..=0x98
185        | 0xBE
186        | 0xC2
187        | 0xC3 => {}
188        0xAC..=0xB1 | 0xBF => {
189            d.fallthrough = false;
190        }
191        // 2-byte local/byte operand
192        0x10 | 0x12 | 0x15..=0x19 | 0x36..=0x3A | 0xBC => {
193            d.operand_u8 = *code
194                .get(pc + 1)
195                .ok_or_else(|| format!("Truncated opcode 0x{op:02X} at pc {pc}"))?;
196            d.next_pc = pc + 2;
197        }
198        // 3-byte u16 CP/i16 operand (non-branch)
199        0x11 | 0x13 | 0x14 | 0x84 | 0xB2..=0xB8 | 0xBB | 0xBD | 0xC0 | 0xC1 => {
200            d.operand_u16 = read_u16(code, pc + 1)?;
201            d.next_pc = pc + 3;
202        }
203        // Conditional branches (3-byte)
204        0x99..=0xA6 | 0xC6 | 0xC7 => {
205            let rel = read_i16(code, pc + 1)?;
206            let target = (pc as i32 + rel as i32) as u16;
207            d.next_pc = pc + 3;
208            d.branch_targets.push(target);
209        }
210        // Unconditional GOTO
211        0xA7 => {
212            let rel = read_i16(code, pc + 1)?;
213            let target = (pc as i32 + rel as i32) as u16;
214            d.next_pc = pc + 3;
215            d.fallthrough = false;
216            d.branch_targets.push(target);
217        }
218        // GOTO_W
219        0xC8 => {
220            let rel = read_i32(code, pc + 1)?;
221            let target = (pc as i64 + rel as i64) as u16;
222            d.next_pc = pc + 5;
223            d.fallthrough = false;
224            d.branch_targets.push(target);
225        }
226        // INVOKEINTERFACE (opcode, u16, count, 0) & INVOKEDYNAMIC (opcode, u16, 0, 0)
227        0xB9 | 0xBA => {
228            if pc + 5 > code.len() {
229                return Err(format!("Truncated 5-byte invoke at pc {pc}"));
230            }
231            d.operand_u16 = read_u16(code, pc + 1)?;
232            d.next_pc = pc + 5;
233        }
234        // MULTIANEWARRAY
235        0xC5 => {
236            if pc + 4 > code.len() {
237                return Err(format!("Truncated multianewarray at pc {pc}"));
238            }
239            d.operand_u16 = read_u16(code, pc + 1)?;
240            d.multi_dims = code[pc + 3];
241            d.next_pc = pc + 4;
242        }
243        // TABLESWITCH
244        0xAA => {
245            let pad = (4 - ((pc + 1) % 4)) % 4;
246            let mut cursor = pc + 1 + pad;
247            let def_rel = read_i32(code, cursor)?;
248            cursor += 4;
249            let low = read_i32(code, cursor)?;
250            cursor += 4;
251            let high = read_i32(code, cursor)?;
252            cursor += 4;
253            d.branch_targets.push((pc as i64 + def_rel as i64) as u16);
254            if high >= low {
255                let count = (high - low + 1) as usize;
256                for _ in 0..count {
257                    let rel = read_i32(code, cursor)?;
258                    cursor += 4;
259                    d.branch_targets.push((pc as i64 + rel as i64) as u16);
260                }
261            }
262            d.next_pc = cursor;
263            d.fallthrough = false;
264        }
265        // LOOKUPSWITCH
266        0xAB => {
267            let pad = (4 - ((pc + 1) % 4)) % 4;
268            let mut cursor = pc + 1 + pad;
269            let def_rel = read_i32(code, cursor)?;
270            cursor += 4;
271            let npairs = read_i32(code, cursor)?.max(0) as usize;
272            cursor += 4;
273            d.branch_targets.push((pc as i64 + def_rel as i64) as u16);
274            for _ in 0..npairs {
275                cursor += 4; // match value
276                let rel = read_i32(code, cursor)?;
277                cursor += 4;
278                d.branch_targets.push((pc as i64 + rel as i64) as u16);
279            }
280            d.next_pc = cursor;
281            d.fallthrough = false;
282        }
283        // WIDE
284        0xC4 => {
285            let wide_op = *code
286                .get(pc + 1)
287                .ok_or_else(|| format!("Truncated WIDE at pc {pc}"))?;
288            let slot = read_u16(code, pc + 2)?;
289            d.op = wide_op;
290            d.wide_slot = Some(slot);
291            d.next_pc = if wide_op == 0x84 { pc + 6 } else { pc + 4 };
292        }
293        other => {
294            return Err(format!("Unsupported opcode 0x{other:02X} at pc {pc}"));
295        }
296    }
297
298    Ok(d)
299}
300
301fn merge_vtype(
302    a: &VerificationType,
303    b: &VerificationType,
304    obj_idx: u16,
305) -> Result<VerificationType, String> {
306    if a == b {
307        return Ok(a.clone());
308    }
309    match (a, b) {
310        (VerificationType::Top, _) | (_, VerificationType::Top) => Ok(VerificationType::Top),
311        (VerificationType::Null, VerificationType::Object(c))
312        | (VerificationType::Object(c), VerificationType::Null) => Ok(VerificationType::Object(*c)),
313        (VerificationType::Null, VerificationType::Uninitialized(_))
314        | (VerificationType::Uninitialized(_), VerificationType::Null) => {
315            Ok(VerificationType::Object(obj_idx))
316        }
317        (VerificationType::Object(_), VerificationType::Object(_)) => {
318            Ok(VerificationType::Object(obj_idx))
319        }
320        (VerificationType::Uninitialized(_), _) | (_, VerificationType::Uninitialized(_)) => {
321            Ok(VerificationType::Top)
322        }
323        _ => Ok(VerificationType::Top),
324    }
325}
326
327fn merge_frames(
328    existing: &mut AbstractFrame,
329    incoming: &AbstractFrame,
330    obj_idx: u16,
331) -> Result<bool, String> {
332    let mut changed = false;
333    let max_locals = existing.locals.len().max(incoming.locals.len());
334    existing.ensure_local_len(max_locals);
335
336    for i in 0..max_locals {
337        let cur = existing
338            .locals
339            .get(i)
340            .cloned()
341            .unwrap_or(LocalSlot::Val(VerificationType::Top));
342        let inc = incoming
343            .locals
344            .get(i)
345            .cloned()
346            .unwrap_or(LocalSlot::Val(VerificationType::Top));
347        let merged = match (&cur, &inc) {
348            (LocalSlot::WideSecond, LocalSlot::WideSecond) => LocalSlot::WideSecond,
349            (LocalSlot::Val(a), LocalSlot::Val(b)) => LocalSlot::Val(merge_vtype(a, b, obj_idx)?),
350            _ => LocalSlot::Val(VerificationType::Top),
351        };
352        if merged != cur {
353            existing.locals[i] = merged;
354            changed = true;
355        }
356    }
357
358    if existing.stack.len() != incoming.stack.len() {
359        return Err(format!(
360            "Inconsistent stack depth at merge point: existing {} vs incoming {}",
361            existing.stack.len(),
362            incoming.stack.len()
363        ));
364    }
365    for (cur, inc) in existing.stack.iter_mut().zip(incoming.stack.iter()) {
366        let merged = if *cur == *inc {
367            cur.clone()
368        } else {
369            match (&*cur, inc) {
370                (VerificationType::Null, VerificationType::Object(c))
371                | (VerificationType::Object(c), VerificationType::Null) => {
372                    VerificationType::Object(*c)
373                }
374                (VerificationType::Object(_), VerificationType::Object(_)) => {
375                    VerificationType::Object(obj_idx)
376                }
377                _ => {
378                    return Err(format!(
379                        "Incompatible operand stack types at merge point: {cur:?} vs {inc:?}"
380                    ))
381                }
382            }
383        };
384        if merged != *cur {
385            *cur = merged;
386            changed = true;
387        }
388    }
389
390    Ok(changed)
391}
392
393fn initial_frame(
394    this_class: &str,
395    method_name: &str,
396    method_desc: &str,
397    is_static: bool,
398    cp: &mut ConstantPool,
399) -> Result<AbstractFrame, String> {
400    let parsed = MethodDescriptor::parse(method_desc)?;
401    let mut frame = AbstractFrame {
402        locals: Vec::new(),
403        stack: Vec::new(),
404    };
405    let mut slot = 0usize;
406    if !is_static {
407        let this_v = if method_name == "<init>" {
408            VerificationType::UninitializedThis
409        } else {
410            VerificationType::Object(cp.add_class(this_class))
411        };
412        frame.set_local(0, this_v);
413        slot = 1;
414    }
415    for p in &parsed.params {
416        let vt = VerificationType::from_jvm_type(p, cp);
417        frame.set_local(slot, vt);
418        slot += p.slot_size() as usize;
419    }
420    Ok(frame)
421}
422
423fn step_insn(
424    pc: u16,
425    insn: &DecodedInsn,
426    frame: &mut AbstractFrame,
427    cp: &mut ConstantPool,
428    this_class_idx: u16,
429    obj_class_idx: u16,
430    str_class_idx: u16,
431    cls_class_idx: u16,
432    throwable_idx: u16,
433) -> Result<(), String> {
434    let slot_or_u8 = || insn.wide_slot.unwrap_or(insn.operand_u8 as u16) as usize;
435
436    match insn.op {
437        opcodes::NOP => {}
438        opcodes::ACONST_NULL => frame.push(VerificationType::Null),
439        0x02..=0x08 | opcodes::BIPUSH | opcodes::SIPUSH => frame.push(VerificationType::Integer),
440        0x09 | 0x0A => frame.push(VerificationType::Long),
441        0x0B..=0x0D => frame.push(VerificationType::Float),
442        0x0E | 0x0F => frame.push(VerificationType::Double),
443
444        opcodes::LDC => {
445            let vt = cp
446                .ldc_verification_type(insn.operand_u8 as u16, str_class_idx, cls_class_idx)
447                .ok_or_else(|| format!("Invalid LDC index {} at pc {pc}", insn.operand_u8))?;
448            frame.push(vt);
449        }
450        opcodes::LDC_W | opcodes::LDC2_W => {
451            let vt = cp
452                .ldc_verification_type(insn.operand_u16, str_class_idx, cls_class_idx)
453                .ok_or_else(|| format!("Invalid LDC_W index {} at pc {pc}", insn.operand_u16))?;
454            frame.push(vt);
455        }
456
457        // Local loads
458        opcodes::ILOAD => frame.push(VerificationType::Integer),
459        opcodes::LLOAD => frame.push(VerificationType::Long),
460        opcodes::FLOAD => frame.push(VerificationType::Float),
461        opcodes::DLOAD => frame.push(VerificationType::Double),
462        opcodes::ALOAD => frame.push(frame.get_local(slot_or_u8())),
463        0x1A..=0x1D => frame.push(VerificationType::Integer),
464        0x1E..=0x21 => frame.push(VerificationType::Long),
465        0x22..=0x25 => frame.push(VerificationType::Float),
466        0x26..=0x29 => frame.push(VerificationType::Double),
467        0x2A..=0x2D => frame.push(frame.get_local((insn.op - 0x2A) as usize)),
468
469        // Array loads
470        0x2E | 0x33 | 0x34 | 0x35 => {
471            frame.pop_n(2)?;
472            frame.push(VerificationType::Integer);
473        }
474        0x2F => {
475            frame.pop_n(2)?;
476            frame.push(VerificationType::Long);
477        }
478        0x30 => {
479            frame.pop_n(2)?;
480            frame.push(VerificationType::Float);
481        }
482        0x31 => {
483            frame.pop_n(2)?;
484            frame.push(VerificationType::Double);
485        }
486        opcodes::AALOAD => {
487            let _idx = frame.pop()?;
488            let arr = frame.pop()?;
489            let elem = match arr {
490                VerificationType::Object(cp_idx) => cp
491                    .get_class_name(cp_idx)
492                    .and_then(|desc| desc.strip_prefix('[').and_then(|rest| JvmType::parse(rest).ok()))
493                    .map(|t| VerificationType::from_jvm_type(&t, cp))
494                    .unwrap_or(VerificationType::Object(obj_class_idx)),
495                VerificationType::Null => VerificationType::Null,
496                _ => VerificationType::Object(obj_class_idx),
497            };
498            frame.push(elem);
499        }
500
501        // Local stores
502        opcodes::ISTORE => {
503            let v = frame.pop()?;
504            frame.set_local(slot_or_u8(), v);
505        }
506        opcodes::LSTORE => {
507            frame.pop()?;
508            frame.set_local(slot_or_u8(), VerificationType::Long);
509        }
510        opcodes::FSTORE => {
511            frame.pop()?;
512            frame.set_local(slot_or_u8(), VerificationType::Float);
513        }
514        opcodes::DSTORE => {
515            frame.pop()?;
516            frame.set_local(slot_or_u8(), VerificationType::Double);
517        }
518        opcodes::ASTORE => {
519            let v = frame.pop()?;
520            frame.set_local(slot_or_u8(), v);
521        }
522        0x3B..=0x3E => {
523            frame.pop()?;
524            frame.set_local((insn.op - 0x3B) as usize, VerificationType::Integer);
525        }
526        0x3F..=0x42 => {
527            frame.pop()?;
528            frame.set_local((insn.op - 0x3F) as usize, VerificationType::Long);
529        }
530        0x43..=0x46 => {
531            frame.pop()?;
532            frame.set_local((insn.op - 0x43) as usize, VerificationType::Float);
533        }
534        0x47..=0x4A => {
535            frame.pop()?;
536            frame.set_local((insn.op - 0x47) as usize, VerificationType::Double);
537        }
538        0x4B..=0x4E => {
539            let v = frame.pop()?;
540            frame.set_local((insn.op - 0x4B) as usize, v);
541        }
542
543        // Array stores
544        0x4F..=0x56 => {
545            frame.pop_n(3)?;
546        }
547
548        // Stack manipulation
549        opcodes::POP => {
550            frame.pop()?;
551        }
552        opcodes::POP2 => {
553            let top = frame.pop()?;
554            if !is_wide_vtype(&top) {
555                frame.pop()?;
556            }
557        }
558        opcodes::DUP => {
559            let top = frame.pop()?;
560            frame.push(top.clone());
561            frame.push(top);
562        }
563        0x5A => {
564            // DUP_X1
565            let v1 = frame.pop()?;
566            let v2 = frame.pop()?;
567            frame.push(v1.clone());
568            frame.push(v2);
569            frame.push(v1);
570        }
571        0x5B => {
572            // DUP_X2
573            let v1 = frame.pop()?;
574            let v2 = frame.pop()?;
575            if is_wide_vtype(&v2) {
576                frame.push(v1.clone());
577                frame.push(v2);
578                frame.push(v1);
579            } else {
580                let v3 = frame.pop()?;
581                frame.push(v1.clone());
582                frame.push(v3);
583                frame.push(v2);
584                frame.push(v1);
585            }
586        }
587        0x5C => {
588            // DUP2
589            let v1 = frame.pop()?;
590            if is_wide_vtype(&v1) {
591                frame.push(v1.clone());
592                frame.push(v1);
593            } else {
594                let v2 = frame.pop()?;
595                frame.push(v2.clone());
596                frame.push(v1.clone());
597                frame.push(v2);
598                frame.push(v1);
599            }
600        }
601        0x5D => {
602            // DUP2_X1
603            let v1 = frame.pop()?;
604            let v2 = frame.pop()?;
605            if is_wide_vtype(&v1) {
606                frame.push(v1.clone());
607                frame.push(v2);
608                frame.push(v1);
609            } else {
610                let v3 = frame.pop()?;
611                frame.push(v2.clone());
612                frame.push(v1.clone());
613                frame.push(v3);
614                frame.push(v2);
615                frame.push(v1);
616            }
617        }
618        0x5E => {
619            // DUP2_X2 (standard narrow form / wide combinations)
620            let v1 = frame.pop()?;
621            let v2 = frame.pop()?;
622            if is_wide_vtype(&v1) && is_wide_vtype(&v2) {
623                frame.push(v1.clone());
624                frame.push(v2);
625                frame.push(v1);
626            } else if is_wide_vtype(&v1) {
627                let v3 = frame.pop()?;
628                frame.push(v1.clone());
629                frame.push(v3);
630                frame.push(v2);
631                frame.push(v1);
632            } else {
633                let v3 = frame.pop()?;
634                if is_wide_vtype(&v3) {
635                    frame.push(v2.clone());
636                    frame.push(v1.clone());
637                    frame.push(v3);
638                    frame.push(v2);
639                    frame.push(v1);
640                } else {
641                    let v4 = frame.pop()?;
642                    frame.push(v2.clone());
643                    frame.push(v1.clone());
644                    frame.push(v4);
645                    frame.push(v3);
646                    frame.push(v2);
647                    frame.push(v1);
648                }
649            }
650        }
651        0x5F => {
652            // SWAP
653            let v1 = frame.pop()?;
654            let v2 = frame.pop()?;
655            frame.push(v1);
656            frame.push(v2);
657        }
658
659        // Arithmetic & bitwise & conversions
660        0x60 | 0x64 | 0x68 | 0x6C | 0x70 | 0x78 | 0x7A | 0x7C | 0x7E | 0x80 | 0x82 => {
661            frame.pop_n(2)?;
662            frame.push(VerificationType::Integer);
663        }
664        0x61 | 0x65 | 0x69 | 0x6D | 0x71 | 0x79 | 0x7B | 0x7D | 0x7F | 0x81 | 0x83 => {
665            frame.pop_n(2)?;
666            frame.push(VerificationType::Long);
667        }
668        0x62 | 0x66 | 0x6A | 0x6E | 0x72 => {
669            frame.pop_n(2)?;
670            frame.push(VerificationType::Float);
671        }
672        0x63 | 0x67 | 0x6B | 0x6F | 0x73 => {
673            frame.pop_n(2)?;
674            frame.push(VerificationType::Double);
675        }
676        0x74..=0x77 => {} // xNEG keeps same top type
677        0x84 => {}                      // IINC
678        0x85 | 0x8C | 0x8F => {
679            frame.pop()?;
680            frame.push(VerificationType::Long);
681        }
682        0x86 | 0x89 | 0x90 => {
683            frame.pop()?;
684            frame.push(VerificationType::Float);
685        }
686        0x87 | 0x8A | 0x8D => {
687            frame.pop()?;
688            frame.push(VerificationType::Double);
689        }
690        0x88 | 0x8B | 0x8E | 0x91 | 0x92 | 0x93 => {
691            frame.pop()?;
692            frame.push(VerificationType::Integer);
693        }
694        0x94..=0x98 => {
695            frame.pop_n(2)?;
696            frame.push(VerificationType::Integer);
697        }
698
699        // Jumps & Switches
700        0x99..=0x9E | 0xC6 | 0xC7 | 0xAA | 0xAB => {
701            frame.pop()?;
702        }
703        0x9F..=0xA6 => {
704            frame.pop_n(2)?;
705        }
706        0xA7 | 0xC8 => {}
707        0xAC..=0xB0 => {
708            frame.pop()?;
709        }
710        0xB1 => {}
711
712        // Fields
713        opcodes::GETSTATIC => {
714            let (_, _, desc) = cp
715                .get_member_ref(insn.operand_u16)
716                .ok_or_else(|| format!("Invalid Fieldref at pc {pc}"))?
717                .clone();
718            let ty = JvmType::parse(&desc)?;
719            frame.push(VerificationType::from_jvm_type(&ty, cp));
720        }
721        opcodes::PUTSTATIC => {
722            frame.pop()?;
723        }
724        opcodes::GETFIELD => {
725            let (_, _, desc) = cp
726                .get_member_ref(insn.operand_u16)
727                .ok_or_else(|| format!("Invalid Fieldref at pc {pc}"))?
728                .clone();
729            frame.pop()?;
730            let ty = JvmType::parse(&desc)?;
731            frame.push(VerificationType::from_jvm_type(&ty, cp));
732        }
733        opcodes::PUTFIELD => {
734            frame.pop_n(2)?;
735        }
736
737        // Invocations
738        opcodes::INVOKEVIRTUAL
739        | opcodes::INVOKESPECIAL
740        | opcodes::INVOKESTATIC
741        | opcodes::INVOKEINTERFACE => {
742            let (owner, name, desc) = cp
743                .get_member_ref(insn.operand_u16)
744                .ok_or_else(|| format!("Invalid Methodref at pc {pc}"))?
745                .clone();
746            let parsed = MethodDescriptor::parse(&desc)?;
747            frame.pop_n(parsed.params.len())?;
748            if insn.op != opcodes::INVOKESTATIC {
749                let recv = frame.pop()?;
750                if insn.op == opcodes::INVOKESPECIAL && name == "<init>" {
751                    match recv {
752                        VerificationType::Uninitialized(_) => {
753                            let target_cls = cp.add_class(&owner);
754                            frame.replace_uninitialized(&recv, VerificationType::Object(target_cls));
755                        }
756                        VerificationType::UninitializedThis => {
757                            frame.replace_uninitialized(
758                                &VerificationType::UninitializedThis,
759                                VerificationType::Object(this_class_idx),
760                            );
761                        }
762                        _ => {}
763                    }
764                }
765            }
766            if parsed.return_type != JvmType::Void {
767                frame.push(VerificationType::from_jvm_type(&parsed.return_type, cp));
768            }
769        }
770        opcodes::INVOKEDYNAMIC => {
771            let (_, desc) = cp
772                .get_invoke_dynamic(insn.operand_u16)
773                .ok_or_else(|| format!("Invalid InvokeDynamic CP entry at pc {pc}"))?
774                .clone();
775            let parsed = MethodDescriptor::parse(&desc)?;
776            frame.pop_n(parsed.params.len())?;
777            if parsed.return_type != JvmType::Void {
778                frame.push(VerificationType::from_jvm_type(&parsed.return_type, cp));
779            }
780        }
781
782        // Allocations & Type checks
783        opcodes::NEW => frame.push(VerificationType::Uninitialized(pc)),
784        0xBC => {
785            // NEWARRAY
786            frame.pop()?;
787            let desc = match insn.operand_u8 {
788                4 => "[Z",
789                5 => "[C",
790                6 => "[F",
791                7 => "[D",
792                8 => "[B",
793                9 => "[S",
794                10 => "[I",
795                11 => "[J",
796                _ => "[I",
797            };
798            frame.push(VerificationType::Object(cp.add_class(desc)));
799        }
800        opcodes::ANEWARRAY => {
801            frame.pop()?;
802            let elem = cp
803                .get_class_name(insn.operand_u16)
804                .ok_or_else(|| format!("Invalid Class CP index at pc {pc}"))?;
805            let arr_desc = if elem.starts_with('[') {
806                format!("[{elem}")
807            } else {
808                format!("[L{elem};")
809            };
810            frame.push(VerificationType::Object(cp.add_class(&arr_desc)));
811        }
812        opcodes::ARRAYLENGTH => {
813            frame.pop()?;
814            frame.push(VerificationType::Integer);
815        }
816        opcodes::ATHROW => {
817            let _ = frame.pop().unwrap_or(VerificationType::Object(throwable_idx));
818            frame.stack.clear();
819        }
820        opcodes::CHECKCAST => {
821            frame.pop()?;
822            frame.push(VerificationType::Object(insn.operand_u16));
823        }
824        0xC1 => {
825            // INSTANCEOF
826            frame.pop()?;
827            frame.push(VerificationType::Integer);
828        }
829        0xC2 | 0xC3 => {
830            // MONITORENTER / MONITOREXIT
831            frame.pop()?;
832        }
833        0xC5 => {
834            // MULTIANEWARRAY
835            frame.pop_n(insn.multi_dims as usize)?;
836            frame.push(VerificationType::Object(insn.operand_u16));
837        }
838        _ => {}
839    }
840
841    Ok(())
842}
843
844/// Computes `(max_stack, max_locals, frames)` over a finalized bytecode buffer using abstract CFG interpretation.
845pub fn compute_stack_maps(
846    this_class: &str,
847    method_name: &str,
848    method_desc: &str,
849    is_static: bool,
850    bytecode: &[u8],
851    exception_table: &[ExceptionHandler],
852    cp: &mut ConstantPool,
853) -> Result<(u16, u16, Vec<FrameEntry>), String> {
854    if bytecode.is_empty() {
855        return Ok((0, 0, Vec::new()));
856    }
857
858    let this_class_idx = cp.add_class(this_class);
859    let obj_class_idx = cp.add_class("java/lang/Object");
860    let str_class_idx = cp.add_class("java/lang/String");
861    let cls_class_idx = cp.add_class("java/lang/Class");
862    let throwable_idx = cp.add_class("java/lang/Throwable");
863
864    // Pre-decode instructions and identify all jump targets and exception handlers.
865    let mut decoded: BTreeMap<u16, DecodedInsn> = BTreeMap::new();
866    let mut frame_pcs: BTreeSet<u16> = BTreeSet::new();
867    let mut cursor = 0usize;
868    while cursor < bytecode.len() {
869        let insn = decode_insn(bytecode, cursor)?;
870        for &target in &insn.branch_targets {
871            frame_pcs.insert(target);
872        }
873        let next = insn.next_pc;
874        decoded.insert(cursor as u16, insn);
875        cursor = next;
876    }
877    for ex in exception_table {
878        frame_pcs.insert(ex.handler_pc);
879    }
880
881    let entry_frame = initial_frame(this_class, method_name, method_desc, is_static, cp)?;
882    let mut max_locals = entry_frame.locals.len() as u16;
883    let mut max_stack = 0u16;
884
885    let mut block_entries: BTreeMap<u16, AbstractFrame> = BTreeMap::new();
886    block_entries.insert(0, entry_frame);
887
888    let mut worklist: VecDeque<u16> = VecDeque::new();
889    worklist.push_back(0);
890
891    let propagate = |target: u16,
892                     state: &AbstractFrame,
893                     entries: &mut BTreeMap<u16, AbstractFrame>,
894                     queue: &mut VecDeque<u16>|
895     -> Result<(), String> {
896        match entries.get_mut(&target) {
897            None => {
898                entries.insert(target, state.clone());
899                queue.push_back(target);
900            }
901            Some(existing) => {
902                if merge_frames(existing, state, obj_class_idx)? {
903                    queue.push_back(target);
904                }
905            }
906        }
907        Ok(())
908    };
909
910    while let Some(start_pc) = worklist.pop_front() {
911        let mut state = block_entries
912            .get(&start_pc)
913            .expect("worklist PC missing from block_entries")
914            .clone();
915        let mut pc = start_pc;
916
917        loop {
918            let Some(insn) = decoded.get(&pc) else {
919                break;
920            };
921
922            max_locals = max_locals.max(state.locals.len() as u16);
923            max_stack = max_stack.max(state.stack_units());
924
925            // Propagate pre-instruction locals + caught exception object to matching try/catch handlers.
926            for ex in exception_table {
927                if pc >= ex.start_pc && pc < ex.end_pc {
928                    let catch_vt = if ex.catch_type == 0 {
929                        VerificationType::Object(throwable_idx)
930                    } else {
931                        VerificationType::Object(ex.catch_type)
932                    };
933                    let mut ex_state = AbstractFrame {
934                        locals: state.locals.clone(),
935                        stack: vec![catch_vt],
936                    };
937                    max_stack = max_stack.max(ex_state.stack_units());
938                    propagate(ex.handler_pc, &mut ex_state, &mut block_entries, &mut worklist)?;
939                }
940            }
941
942            step_insn(
943                pc,
944                insn,
945                &mut state,
946                cp,
947                this_class_idx,
948                obj_class_idx,
949                str_class_idx,
950                cls_class_idx,
951                throwable_idx,
952            )?;
953
954            max_locals = max_locals.max(state.locals.len() as u16);
955            max_stack = max_stack.max(state.stack_units());
956
957            for &target in &insn.branch_targets {
958                propagate(target, &state, &mut block_entries, &mut worklist)?;
959            }
960
961            if !insn.fallthrough || insn.next_pc >= bytecode.len() {
962                break;
963            }
964            let next_pc = insn.next_pc as u16;
965            if frame_pcs.contains(&next_pc) {
966                propagate(next_pc, &state, &mut block_entries, &mut worklist)?;
967                break;
968            }
969            pc = next_pc;
970        }
971    }
972
973    let mut frames = Vec::new();
974    for pc in frame_pcs {
975        if let Some(frame) = block_entries.get(&pc) {
976            frames.push(frame.to_frame_entry(pc));
977        }
978    }
979    Ok((max_stack, max_locals, frames))
980}