#![allow(clippy::double_must_use)]
use alloc::{boxed::Box, format, vec::Vec};
use classfile::{AttributeInfoCode, ConstantPoolReference, Opcode};
use jvm::{ClassInstance, JavaChar, JavaError, JavaValue, Jvm, Result};
use jvm_types::JavaType;
use crate::stack_frame::StackFrame;
pub struct Interpreter;
impl Interpreter {
pub async fn run(jvm: &Jvm, code_attribute: &AttributeInfoCode, args: Box<[JavaValue]>, return_type: &JavaType) -> Result<JavaValue> {
let mut stack_frame = StackFrame::new(code_attribute.max_locals as usize, code_attribute.max_stack as usize);
let mut local_index = 0;
for value in args {
let value = Self::to_stack_frame_type(value);
let slots = if matches!(value, JavaValue::Long(_) | JavaValue::Double(_)) {
2
} else {
1
};
stack_frame.local_variables[local_index] = value;
local_index += slots;
}
let mut next_index = 0;
loop {
let result = Self::execute(jvm, code_attribute, &mut next_index, &mut stack_frame, return_type).await;
match result {
Ok(value) => return Ok(value),
Err(JavaError::JavaException(e)) => {
let pc = code_attribute.code[next_index - 1].0;
let exception_handler = Self::find_exception_handler(jvm, &*e, code_attribute, pc).await;
if let Some(x) = exception_handler {
stack_frame.operand_stack.clear();
stack_frame.operand_stack.push(JavaValue::Object(Some(e)));
next_index = code_attribute.pc_to_index[x as usize] as usize;
} else {
return Err(JavaError::JavaException(e));
}
}
}
}
}
async fn execute(
jvm: &Jvm,
code_attribute: &AttributeInfoCode,
next_index: &mut usize,
stack_frame: &mut StackFrame,
return_type: &JavaType,
) -> Result<JavaValue> {
while let Some((_, opcode)) = code_attribute.code.get(*next_index) {
*next_index += 1;
tracing::trace!("Opcode {opcode:?}");
match opcode {
Opcode::Aaload
| Opcode::Baload
| Opcode::Caload
| Opcode::Daload
| Opcode::Faload
| Opcode::Iaload
| Opcode::Laload
| Opcode::Saload => {
let index: i32 = stack_frame.operand_stack.pop().unwrap().into();
if index < 0 {
return Err(jvm.exception("java/lang/ArrayIndexOutOfBoundsException", &format!("{}", index)).await);
}
let array: Option<Box<dyn ClassInstance>> = stack_frame.operand_stack.pop().unwrap().into();
if array.is_none() {
return Err(jvm.exception("java/lang/NullPointerException", "Array is null").await);
}
let value = jvm.load_array(&array.unwrap(), index as usize, 1).await?.pop().unwrap();
stack_frame.operand_stack.push(Self::to_stack_frame_type(value));
}
Opcode::Aastore
| Opcode::Bastore
| Opcode::Castore
| Opcode::Dastore
| Opcode::Fastore
| Opcode::Iastore
| Opcode::Lastore
| Opcode::Sastore => {
let value = stack_frame.operand_stack.pop().unwrap();
let index: i32 = stack_frame.operand_stack.pop().unwrap().into();
if index < 0 {
return Err(jvm.exception("java/lang/ArrayIndexOutOfBoundsException", &format!("{}", index)).await);
}
let array: Option<Box<dyn ClassInstance>> = stack_frame.operand_stack.pop().unwrap().into();
let Some(mut array) = array else {
return Err(jvm.exception("java/lang/NullPointerException", "Array is null").await);
};
let Some(length) = array.as_array_instance().map(|x| x.length()) else {
return Err(jvm.exception("java/lang/IllegalArgumentException", "Not an array").await);
};
if index as usize >= length {
return Err(jvm.exception("java/lang/ArrayIndexOutOfBoundsException", &format!("{}", index)).await);
}
let value = match opcode {
Opcode::Bastore if jvm.array_element_type(&array).await? == JavaType::Boolean => {
JavaValue::Boolean(i32::from(value) & 1 != 0)
}
Opcode::Bastore => JavaValue::Byte(i32::from(value) as _),
Opcode::Castore => JavaValue::Char(i32::from(value) as _),
Opcode::Sastore => JavaValue::Short(i32::from(value) as _),
_ => value,
};
if matches!(opcode, Opcode::Aastore) {
let stored: &Option<Box<dyn ClassInstance>> = (&value).into();
if let Some(stored) = stored
&& !jvm.array_store_allowed(&*array, &**stored)
{
return Err(jvm.exception("java/lang/ArrayStoreException", &stored.class_definition().name()).await);
}
}
jvm.store_array(&mut array, index as usize, [value]).await?;
}
Opcode::AconstNull => stack_frame.operand_stack.push(JavaValue::Object(None)),
Opcode::Aload(x) | Opcode::Dload(x) | Opcode::Fload(x) | Opcode::Iload(x) | Opcode::Lload(x) => {
let value = stack_frame.local_variables[*x as usize].clone();
stack_frame.operand_stack.push(value);
}
Opcode::Athrow => {
let exception: Option<Box<dyn ClassInstance>> = stack_frame.operand_stack.pop().unwrap().into();
if exception.is_none() {
return Err(jvm.exception("java/lang/NullPointerException", "null").await);
}
return Err(JavaError::JavaException(exception.unwrap()));
}
Opcode::Anewarray(x) => {
let length: i32 = stack_frame.operand_stack.pop().unwrap().into();
if length < 0 {
return Err(jvm.exception("java/lang/NegativeArraySizeException", &format!("{}", length)).await);
}
let class_name = x.as_class();
let element_type_name = if class_name.starts_with('[') {
alloc::string::String::from(class_name)
} else {
format!("L{};", class_name)
};
let array = jvm.instantiate_array(&element_type_name, length as _).await?;
stack_frame.operand_stack.push(JavaValue::Object(Some(array)));
}
Opcode::Areturn | Opcode::Dreturn | Opcode::Freturn | Opcode::Ireturn | Opcode::Lreturn => {
let return_value = stack_frame.operand_stack.pop().unwrap();
if matches!(opcode, Opcode::Ireturn) {
let value: i32 = return_value.into();
return Ok(match return_type {
JavaType::Boolean => JavaValue::Boolean(value & 1 != 0),
JavaType::Char => JavaValue::Char(value as _),
JavaType::Byte => JavaValue::Byte(value as _),
JavaType::Short => JavaValue::Short(value as _),
_ => JavaValue::Int(value),
});
}
return Ok(return_value);
}
Opcode::Arraylength => {
let array: Option<Box<dyn ClassInstance>> = stack_frame.operand_stack.pop().unwrap().into();
if array.is_none() {
return Err(jvm.exception("java/lang/NullPointerException", "Array is null").await);
}
let length = jvm.array_length(&array.unwrap()).await?;
stack_frame.operand_stack.push(JavaValue::Int(length as _));
}
Opcode::Astore(x) | Opcode::Dstore(x) | Opcode::Fstore(x) | Opcode::Istore(x) | Opcode::Lstore(x) => {
let value = stack_frame.operand_stack.pop();
stack_frame.local_variables[*x as usize] = value.unwrap();
}
Opcode::Bipush(x) => stack_frame.operand_stack.push(JavaValue::Int(*x as i32)),
Opcode::Checkcast(x) => {
let top_stack: &Option<Box<dyn ClassInstance>> = stack_frame.operand_stack.last().unwrap().into();
if !top_stack.is_none() && !jvm.is_instance(&**top_stack.as_ref().unwrap(), x.as_class()) {
return Err(jvm.exception("java/lang/ClassCastException", "Invalid cast").await);
}
}
Opcode::D2f => {
let value: f64 = stack_frame.operand_stack.pop().unwrap().into();
stack_frame.operand_stack.push(JavaValue::Float(value as _));
}
Opcode::D2i => {
let value: f64 = stack_frame.operand_stack.pop().unwrap().into();
stack_frame.operand_stack.push(JavaValue::Int(value as _));
}
Opcode::D2l => {
let value: f64 = stack_frame.operand_stack.pop().unwrap().into();
stack_frame.operand_stack.push(JavaValue::Long(value as _));
}
Opcode::Dadd => {
let value2: f64 = stack_frame.operand_stack.pop().unwrap().into();
let value1: f64 = stack_frame.operand_stack.pop().unwrap().into();
stack_frame.operand_stack.push(JavaValue::Double(value1 + value2));
}
Opcode::Dcmpg => {
let value2: f64 = stack_frame.operand_stack.pop().unwrap().into();
let value1: f64 = stack_frame.operand_stack.pop().unwrap().into();
if value1.is_nan() || value2.is_nan() {
stack_frame.operand_stack.push(JavaValue::Int(1));
} else {
stack_frame.operand_stack.push(JavaValue::Int(value1.partial_cmp(&value2).unwrap() as _));
}
}
Opcode::Dcmpl => {
let value2: f64 = stack_frame.operand_stack.pop().unwrap().into();
let value1: f64 = stack_frame.operand_stack.pop().unwrap().into();
if value1.is_nan() || value2.is_nan() {
stack_frame.operand_stack.push(JavaValue::Int(-1));
} else {
stack_frame.operand_stack.push(JavaValue::Int(value1.partial_cmp(&value2).unwrap() as _));
}
}
Opcode::Dconst(x) => {
stack_frame.operand_stack.push(JavaValue::Double(*x as f64));
}
Opcode::Ddiv => {
let value2: f64 = stack_frame.operand_stack.pop().unwrap().into();
let value1: f64 = stack_frame.operand_stack.pop().unwrap().into();
stack_frame.operand_stack.push(JavaValue::Double(value1 / value2));
}
Opcode::Dmul => {
let value2: f64 = stack_frame.operand_stack.pop().unwrap().into();
let value1: f64 = stack_frame.operand_stack.pop().unwrap().into();
stack_frame.operand_stack.push(JavaValue::Double(value1 * value2));
}
Opcode::Dneg => {
let value: f64 = stack_frame.operand_stack.pop().unwrap().into();
stack_frame.operand_stack.push(JavaValue::Double(-value));
}
Opcode::Dup => {
let value = stack_frame.operand_stack.pop().unwrap();
stack_frame.operand_stack.push(value.clone());
stack_frame.operand_stack.push(value);
}
Opcode::Dup2 => {
let value = stack_frame.operand_stack.pop().unwrap();
if matches!(value, JavaValue::Long(_) | JavaValue::Double(_)) {
stack_frame.operand_stack.push(value.clone());
stack_frame.operand_stack.push(value);
} else {
let value2 = stack_frame.operand_stack.pop().unwrap();
stack_frame.operand_stack.push(value2.clone());
stack_frame.operand_stack.push(value.clone());
stack_frame.operand_stack.push(value2);
stack_frame.operand_stack.push(value);
}
}
Opcode::Dup2X1 => {
let value1 = stack_frame.operand_stack.pop().unwrap();
let value2 = stack_frame.operand_stack.pop().unwrap();
if matches!(value1, JavaValue::Long(_) | JavaValue::Double(_)) {
stack_frame.operand_stack.push(value1.clone());
stack_frame.operand_stack.push(value2);
stack_frame.operand_stack.push(value1);
} else {
let value3 = stack_frame.operand_stack.pop().unwrap();
stack_frame.operand_stack.push(value2.clone());
stack_frame.operand_stack.push(value1.clone());
stack_frame.operand_stack.push(value3);
stack_frame.operand_stack.push(value2);
stack_frame.operand_stack.push(value1);
}
}
Opcode::Dup2X2 => {
let value1 = stack_frame.operand_stack.pop().unwrap();
let value2 = stack_frame.operand_stack.pop().unwrap();
if matches!(value1, JavaValue::Long(_) | JavaValue::Double(_)) && matches!(value2, JavaValue::Long(_) | JavaValue::Double(_)) {
stack_frame.operand_stack.push(value1.clone());
stack_frame.operand_stack.push(value2);
stack_frame.operand_stack.push(value1);
} else if matches!(value1, JavaValue::Long(_) | JavaValue::Double(_)) {
let value3 = stack_frame.operand_stack.pop().unwrap();
stack_frame.operand_stack.push(value1.clone());
stack_frame.operand_stack.push(value3);
stack_frame.operand_stack.push(value2);
stack_frame.operand_stack.push(value1);
} else {
let value3 = stack_frame.operand_stack.pop().unwrap();
if matches!(value3, JavaValue::Long(_) | JavaValue::Double(_)) {
stack_frame.operand_stack.push(value2.clone());
stack_frame.operand_stack.push(value1.clone());
stack_frame.operand_stack.push(value3);
stack_frame.operand_stack.push(value2);
stack_frame.operand_stack.push(value1);
} else {
let value4 = stack_frame.operand_stack.pop().unwrap();
stack_frame.operand_stack.push(value2.clone());
stack_frame.operand_stack.push(value1.clone());
stack_frame.operand_stack.push(value4);
stack_frame.operand_stack.push(value3);
stack_frame.operand_stack.push(value2);
stack_frame.operand_stack.push(value1);
}
}
}
Opcode::DupX1 => {
let value1 = stack_frame.operand_stack.pop().unwrap();
let value2 = stack_frame.operand_stack.pop().unwrap();
stack_frame.operand_stack.push(value1.clone());
stack_frame.operand_stack.push(value2.clone());
stack_frame.operand_stack.push(value1);
}
Opcode::DupX2 => {
let value1 = stack_frame.operand_stack.pop().unwrap();
let value2 = stack_frame.operand_stack.pop().unwrap();
if matches!(value2, JavaValue::Long(_) | JavaValue::Double(_)) {
stack_frame.operand_stack.push(value1.clone());
stack_frame.operand_stack.push(value2.clone());
stack_frame.operand_stack.push(value1);
} else {
let value3 = stack_frame.operand_stack.pop().unwrap();
stack_frame.operand_stack.push(value1.clone());
stack_frame.operand_stack.push(value3.clone());
stack_frame.operand_stack.push(value2.clone());
stack_frame.operand_stack.push(value1);
}
}
Opcode::Drem => {
let value2: f64 = stack_frame.operand_stack.pop().unwrap().into();
let value1: f64 = stack_frame.operand_stack.pop().unwrap().into();
stack_frame.operand_stack.push(JavaValue::Double(value1 % value2));
}
Opcode::Dsub => {
let value2: f64 = stack_frame.operand_stack.pop().unwrap().into();
let value1: f64 = stack_frame.operand_stack.pop().unwrap().into();
stack_frame.operand_stack.push(JavaValue::Double(value1 - value2));
}
Opcode::F2d => {
let value: f32 = stack_frame.operand_stack.pop().unwrap().into();
stack_frame.operand_stack.push(JavaValue::Double(value as _));
}
Opcode::F2i => {
let value: f32 = stack_frame.operand_stack.pop().unwrap().into();
stack_frame.operand_stack.push(JavaValue::Int(value as _));
}
Opcode::F2l => {
let value: f32 = stack_frame.operand_stack.pop().unwrap().into();
stack_frame.operand_stack.push(JavaValue::Long(value as _));
}
Opcode::Fadd => {
let value2: f32 = stack_frame.operand_stack.pop().unwrap().into();
let value1: f32 = stack_frame.operand_stack.pop().unwrap().into();
stack_frame.operand_stack.push(JavaValue::Float(value1 + value2));
}
Opcode::Fcmpg => {
let value2: f32 = stack_frame.operand_stack.pop().unwrap().into();
let value1: f32 = stack_frame.operand_stack.pop().unwrap().into();
if value1.is_nan() || value2.is_nan() {
stack_frame.operand_stack.push(JavaValue::Int(1));
} else {
stack_frame.operand_stack.push(JavaValue::Int(value1.partial_cmp(&value2).unwrap() as _));
}
}
Opcode::Fcmpl => {
let value2: f32 = stack_frame.operand_stack.pop().unwrap().into();
let value1: f32 = stack_frame.operand_stack.pop().unwrap().into();
if value1.is_nan() || value2.is_nan() {
stack_frame.operand_stack.push(JavaValue::Int(-1));
} else {
stack_frame.operand_stack.push(JavaValue::Int(value1.partial_cmp(&value2).unwrap() as _));
}
}
Opcode::Fconst(x) => {
stack_frame.operand_stack.push(JavaValue::Float(*x as f32));
}
Opcode::Fdiv => {
let value2: f32 = stack_frame.operand_stack.pop().unwrap().into();
let value1: f32 = stack_frame.operand_stack.pop().unwrap().into();
stack_frame.operand_stack.push(JavaValue::Float(value1 / value2));
}
Opcode::Fmul => {
let value2: f32 = stack_frame.operand_stack.pop().unwrap().into();
let value1: f32 = stack_frame.operand_stack.pop().unwrap().into();
stack_frame.operand_stack.push(JavaValue::Float(value1 * value2));
}
Opcode::Fneg => {
let value: f32 = stack_frame.operand_stack.pop().unwrap().into();
stack_frame.operand_stack.push(JavaValue::Float(-value));
}
Opcode::Frem => {
let value2: f32 = stack_frame.operand_stack.pop().unwrap().into();
let value1: f32 = stack_frame.operand_stack.pop().unwrap().into();
stack_frame.operand_stack.push(JavaValue::Float(value1 % value2));
}
Opcode::Fsub => {
let value2: f32 = stack_frame.operand_stack.pop().unwrap().into();
let value1: f32 = stack_frame.operand_stack.pop().unwrap().into();
stack_frame.operand_stack.push(JavaValue::Float(value1 - value2));
}
Opcode::Getfield(x) => {
let x = x.as_field_ref();
let instance: Option<Box<dyn ClassInstance>> = stack_frame.operand_stack.pop().unwrap().into();
if instance.is_none() {
return Err(jvm.exception("java/lang/NullPointerException", "null").await);
}
let value = jvm.get_field(&instance.unwrap(), &x.class, &x.name, &x.descriptor).await?;
stack_frame.operand_stack.push(Self::to_stack_frame_type(value));
}
Opcode::Getstatic(x) => {
let x = x.as_field_ref();
let value = jvm.get_static_field(&x.class, &x.name, &x.descriptor).await?;
stack_frame.operand_stack.push(Self::to_stack_frame_type(value));
}
Opcode::Goto(x) | Opcode::GotoW(x) => {
*next_index = *x as usize;
}
Opcode::I2b => {
let value: i32 = stack_frame.operand_stack.pop().unwrap().into();
stack_frame.operand_stack.push(JavaValue::Int((value as i8) as i32));
}
Opcode::I2c => {
let value: i32 = stack_frame.operand_stack.pop().unwrap().into();
stack_frame.operand_stack.push(JavaValue::Int(value as JavaChar as _));
}
Opcode::I2d => {
let value: i32 = stack_frame.operand_stack.pop().unwrap().into();
stack_frame.operand_stack.push(JavaValue::Double(value as _));
}
Opcode::I2f => {
let value: i32 = stack_frame.operand_stack.pop().unwrap().into();
stack_frame.operand_stack.push(JavaValue::Float(value as _));
}
Opcode::I2l => {
let value: i32 = stack_frame.operand_stack.pop().unwrap().into();
stack_frame.operand_stack.push(JavaValue::Long(value as _));
}
Opcode::I2s => {
let value: i32 = stack_frame.operand_stack.pop().unwrap().into();
stack_frame.operand_stack.push(JavaValue::Int((value as i16) as i32));
}
Opcode::Iadd => {
let value2: i32 = stack_frame.operand_stack.pop().unwrap().into();
let value1: i32 = stack_frame.operand_stack.pop().unwrap().into();
stack_frame.operand_stack.push(JavaValue::Int(value1.wrapping_add(value2)));
}
Opcode::Iand => {
let value2: i32 = stack_frame.operand_stack.pop().unwrap().into();
let value1: i32 = stack_frame.operand_stack.pop().unwrap().into();
stack_frame.operand_stack.push(JavaValue::Int(value1 & value2));
}
Opcode::Iconst(x) => stack_frame.operand_stack.push(JavaValue::Int(*x as i32)),
Opcode::Idiv => {
let value2: i32 = stack_frame.operand_stack.pop().unwrap().into();
let value1: i32 = stack_frame.operand_stack.pop().unwrap().into();
if value2 == 0 {
return Err(jvm.exception("java/lang/ArithmeticException", "Division by zero").await);
}
stack_frame.operand_stack.push(JavaValue::Int(value1.wrapping_div(value2)));
}
Opcode::IfAcmpeq(x) => {
let value2: Option<Box<dyn ClassInstance>> = stack_frame.operand_stack.pop().unwrap().into();
let value1: Option<Box<dyn ClassInstance>> = stack_frame.operand_stack.pop().unwrap().into();
if value1 == value2 {
*next_index = *x as usize;
}
}
Opcode::IfAcmpne(x) => {
let value2: Option<Box<dyn ClassInstance>> = stack_frame.operand_stack.pop().unwrap().into();
let value1: Option<Box<dyn ClassInstance>> = stack_frame.operand_stack.pop().unwrap().into();
if value1 != value2 {
*next_index = *x as usize;
}
}
Opcode::IfIcmpeq(x) => {
if Self::integer_condition(stack_frame, |x, y| x == y) {
*next_index = *x as usize;
}
}
Opcode::IfIcmpge(x) => {
if Self::integer_condition(stack_frame, |x, y| x >= y) {
*next_index = *x as usize;
}
}
Opcode::IfIcmpgt(x) => {
if Self::integer_condition(stack_frame, |x, y| x > y) {
*next_index = *x as usize;
}
}
Opcode::IfIcmple(x) => {
if Self::integer_condition(stack_frame, |x, y| x <= y) {
*next_index = *x as usize;
}
}
Opcode::IfIcmplt(x) => {
if Self::integer_condition(stack_frame, |x, y| x < y) {
*next_index = *x as usize;
}
}
Opcode::IfIcmpne(x) => {
if Self::integer_condition(stack_frame, |x, y| x != y) {
*next_index = *x as usize;
}
}
Opcode::Ifeq(x) => {
if Self::integer_condition_single(stack_frame, |x| x == 0) {
*next_index = *x as usize;
}
}
Opcode::Ifge(x) => {
if Self::integer_condition_single(stack_frame, |x| x >= 0) {
*next_index = *x as usize;
}
}
Opcode::Ifgt(x) => {
if Self::integer_condition_single(stack_frame, |x| x > 0) {
*next_index = *x as usize;
}
}
Opcode::Ifle(x) => {
if Self::integer_condition_single(stack_frame, |x| x <= 0) {
*next_index = *x as usize;
}
}
Opcode::Iflt(x) => {
if Self::integer_condition_single(stack_frame, |x| x < 0) {
*next_index = *x as usize;
}
}
Opcode::Ifne(x) => {
if Self::integer_condition_single(stack_frame, |x| x != 0) {
*next_index = *x as usize;
}
}
Opcode::Ifnonnull(x) => {
let value: Option<Box<dyn ClassInstance>> = stack_frame.operand_stack.pop().unwrap().into();
if value.is_some() {
*next_index = *x as usize;
}
}
Opcode::Ifnull(x) => {
let value: Option<Box<dyn ClassInstance>> = stack_frame.operand_stack.pop().unwrap().into();
if value.is_none() {
*next_index = *x as usize;
}
}
Opcode::Iinc(x, y) => {
let JavaValue::Int(value) = &mut stack_frame.local_variables[*x as usize] else {
panic!("Expected int local")
};
*value = value.wrapping_add(*y as i32);
}
Opcode::Imul => {
let value2: i32 = stack_frame.operand_stack.pop().unwrap().into();
let value1: i32 = stack_frame.operand_stack.pop().unwrap().into();
stack_frame.operand_stack.push(JavaValue::Int(value1.wrapping_mul(value2)));
}
Opcode::Ineg => {
let value: i32 = stack_frame.operand_stack.pop().unwrap().into();
stack_frame.operand_stack.push(JavaValue::Int(value.wrapping_neg()));
}
Opcode::Instanceof(x) => {
let instance: Option<Box<dyn ClassInstance>> = stack_frame.operand_stack.pop().unwrap().into();
let result = if let Some(instance) = instance {
jvm.is_instance(&*instance, x.as_class())
} else {
false
};
stack_frame.operand_stack.push(JavaValue::Int(result as _));
}
Opcode::Invokedynamic(_) => {
todo!()
}
Opcode::Invokeinterface(x, _count, _zero) => {
let x = x.as_interface_method_ref();
let params = Self::extract_invoke_params(stack_frame, &x.r#type);
let instance: Option<Box<dyn ClassInstance>> = stack_frame.operand_stack.pop().unwrap().into();
if instance.is_none() {
return Err(jvm
.exception(
"java/lang/NullPointerException",
&format!("Method {}::{}:{} is called on null", x.class, x.name, x.descriptor),
)
.await);
}
let instance = instance.unwrap();
let result = jvm
.invoke_virtual(&instance, &instance.class_definition().name(), &x.name, &x.descriptor, params)
.await?;
Self::push_invoke_result(stack_frame, result);
}
Opcode::Invokespecial(x) => {
let x = x.as_method_ref();
let params = Self::extract_invoke_params(stack_frame, &x.r#type);
let instance: Option<Box<dyn ClassInstance>> = stack_frame.operand_stack.pop().unwrap().into();
if instance.is_none() {
return Err(jvm
.exception(
"java/lang/NullPointerException",
&format!("Method {}::{}:{} is called on null", x.class, x.name, x.descriptor),
)
.await);
}
let result = jvm.invoke_special(&instance.unwrap(), &x.class, &x.name, &x.descriptor, params).await?;
Self::push_invoke_result(stack_frame, result);
}
Opcode::Invokestatic(x) => {
let x = x.as_method_ref();
let params = Self::extract_invoke_params(stack_frame, &x.r#type);
let result = jvm.invoke_static(&x.class, &x.name, &x.descriptor, params).await?;
Self::push_invoke_result(stack_frame, result);
}
Opcode::Invokevirtual(x) => {
let x = x.as_method_ref();
let params = Self::extract_invoke_params(stack_frame, &x.r#type);
let instance: Option<Box<dyn ClassInstance>> = stack_frame.operand_stack.pop().unwrap().into();
if instance.is_none() {
return Err(jvm
.exception(
"java/lang/NullPointerException",
&format!("Method {}::{}:{} is called on null", x.class, x.name, x.descriptor),
)
.await);
}
let result = jvm.invoke_virtual(&instance.unwrap(), &x.class, &x.name, &x.descriptor, params).await?;
Self::push_invoke_result(stack_frame, result);
}
Opcode::Ior => {
let value2: i32 = stack_frame.operand_stack.pop().unwrap().into();
let value1: i32 = stack_frame.operand_stack.pop().unwrap().into();
stack_frame.operand_stack.push(JavaValue::Int(value1 | value2));
}
Opcode::Irem => {
let value2: i32 = stack_frame.operand_stack.pop().unwrap().into();
let value1: i32 = stack_frame.operand_stack.pop().unwrap().into();
if value2 == 0 {
return Err(jvm.exception("java/lang/ArithmeticException", "Division by zero").await);
}
stack_frame.operand_stack.push(JavaValue::Int(value1.wrapping_rem(value2)));
}
Opcode::Ishl => {
let value2: i32 = stack_frame.operand_stack.pop().unwrap().into();
let value1: i32 = stack_frame.operand_stack.pop().unwrap().into();
stack_frame.operand_stack.push(JavaValue::Int(value1 << (value2 & 0x1f)));
}
Opcode::Ishr => {
let value2: i32 = stack_frame.operand_stack.pop().unwrap().into();
let value1: i32 = stack_frame.operand_stack.pop().unwrap().into();
stack_frame.operand_stack.push(JavaValue::Int(value1 >> (value2 & 0x1f)));
}
Opcode::Isub => {
let value2: i32 = stack_frame.operand_stack.pop().unwrap().into();
let value1: i32 = stack_frame.operand_stack.pop().unwrap().into();
stack_frame.operand_stack.push(JavaValue::Int(value1.wrapping_sub(value2)));
}
Opcode::Iushr => {
let value2: i32 = stack_frame.operand_stack.pop().unwrap().into();
let value1: i32 = stack_frame.operand_stack.pop().unwrap().into();
stack_frame
.operand_stack
.push(JavaValue::Int(((value1 as u32) >> ((value2 as u32) & 0x1f)) as _));
}
Opcode::Ixor => {
let value2: i32 = stack_frame.operand_stack.pop().unwrap().into();
let value1: i32 = stack_frame.operand_stack.pop().unwrap().into();
stack_frame.operand_stack.push(JavaValue::Int(value1 ^ value2));
}
Opcode::Jsr(x) | Opcode::JsrW(x) => {
stack_frame.operand_stack.push(JavaValue::Int(*next_index as i32));
*next_index = *x as usize;
}
Opcode::L2d => {
let value: i64 = stack_frame.operand_stack.pop().unwrap().into();
stack_frame.operand_stack.push(JavaValue::Double(value as _));
}
Opcode::L2f => {
let value: i64 = stack_frame.operand_stack.pop().unwrap().into();
stack_frame.operand_stack.push(JavaValue::Float(value as _));
}
Opcode::L2i => {
let value: i64 = stack_frame.operand_stack.pop().unwrap().into();
stack_frame.operand_stack.push(JavaValue::Int(value as _));
}
Opcode::Ladd => {
let value2: i64 = stack_frame.operand_stack.pop().unwrap().into();
let value1: i64 = stack_frame.operand_stack.pop().unwrap().into();
stack_frame.operand_stack.push(JavaValue::Long(value1.wrapping_add(value2)));
}
Opcode::Land => {
let value2: i64 = stack_frame.operand_stack.pop().unwrap().into();
let value1: i64 = stack_frame.operand_stack.pop().unwrap().into();
stack_frame.operand_stack.push(JavaValue::Long(value1 & value2));
}
Opcode::Lcmp => {
let value2: i64 = stack_frame.operand_stack.pop().unwrap().into();
let value1: i64 = stack_frame.operand_stack.pop().unwrap().into();
stack_frame.operand_stack.push(JavaValue::Int(value1.cmp(&value2) as _));
}
Opcode::Lconst(x) => stack_frame.operand_stack.push(JavaValue::Long(*x as i64)),
Opcode::Ldc(x) | Opcode::LdcW(x) | Opcode::Ldc2W(x) => {
let value = match x {
ConstantPoolReference::Integer(x) => JavaValue::Int(*x),
ConstantPoolReference::Float(x) => JavaValue::Float(*x),
ConstantPoolReference::Long(x) => JavaValue::Long(*x),
ConstantPoolReference::Double(x) => JavaValue::Double(*x),
ConstantPoolReference::String(x) => JavaValue::Object(Some(jvm.intern_string(x).await?)),
ConstantPoolReference::Class(x) => JavaValue::Object(Some(jvm.resolve_class(x).await?.java_class())),
_ => unimplemented!(),
};
stack_frame.operand_stack.push(value);
}
Opcode::Ldiv => {
let value2: i64 = stack_frame.operand_stack.pop().unwrap().into();
let value1: i64 = stack_frame.operand_stack.pop().unwrap().into();
if value2 == 0 {
return Err(jvm.exception("java/lang/ArithmeticException", "Division by zero").await);
}
stack_frame.operand_stack.push(JavaValue::Long(value1.wrapping_div(value2)));
}
Opcode::Lmul => {
let value2: i64 = stack_frame.operand_stack.pop().unwrap().into();
let value1: i64 = stack_frame.operand_stack.pop().unwrap().into();
stack_frame.operand_stack.push(JavaValue::Long(value1.wrapping_mul(value2)));
}
Opcode::Lneg => {
let value: i64 = stack_frame.operand_stack.pop().unwrap().into();
stack_frame.operand_stack.push(JavaValue::Long(value.wrapping_neg()));
}
Opcode::Lor => {
let value2: i64 = stack_frame.operand_stack.pop().unwrap().into();
let value1: i64 = stack_frame.operand_stack.pop().unwrap().into();
stack_frame.operand_stack.push(JavaValue::Long(value1 | value2));
}
Opcode::Lrem => {
let value2: i64 = stack_frame.operand_stack.pop().unwrap().into();
let value1: i64 = stack_frame.operand_stack.pop().unwrap().into();
if value2 == 0 {
return Err(jvm.exception("java/lang/ArithmeticException", "Division by zero").await);
}
stack_frame.operand_stack.push(JavaValue::Long(value1.wrapping_rem(value2)));
}
Opcode::Lshl => {
let value2: i32 = stack_frame.operand_stack.pop().unwrap().into();
let value1: i64 = stack_frame.operand_stack.pop().unwrap().into();
stack_frame.operand_stack.push(JavaValue::Long(value1 << (value2 & 0x3f)));
}
Opcode::Lshr => {
let value2: i32 = stack_frame.operand_stack.pop().unwrap().into();
let value1: i64 = stack_frame.operand_stack.pop().unwrap().into();
stack_frame.operand_stack.push(JavaValue::Long(value1 >> (value2 & 0x3f)));
}
Opcode::Lsub => {
let value2: i64 = stack_frame.operand_stack.pop().unwrap().into();
let value1: i64 = stack_frame.operand_stack.pop().unwrap().into();
stack_frame.operand_stack.push(JavaValue::Long(value1.wrapping_sub(value2)));
}
Opcode::Lushr => {
let value2: i32 = stack_frame.operand_stack.pop().unwrap().into();
let value1: i64 = stack_frame.operand_stack.pop().unwrap().into();
stack_frame
.operand_stack
.push(JavaValue::Long(((value1 as u64) >> ((value2 as u64) & 0x3f)) as _));
}
Opcode::Lxor => {
let value2: i64 = stack_frame.operand_stack.pop().unwrap().into();
let value1: i64 = stack_frame.operand_stack.pop().unwrap().into();
stack_frame.operand_stack.push(JavaValue::Long(value1 ^ value2));
}
Opcode::Lookupswitch(default, pairs) => {
let key: i32 = stack_frame.operand_stack.pop().unwrap().into();
*next_index = pairs.iter().find(|(k, _)| *k == key).map_or(*default, |(_, target)| *target) as usize;
}
Opcode::Tableswitch(default, pairs) => {
let key: i32 = stack_frame.operand_stack.pop().unwrap().into();
let index = key.wrapping_sub(pairs[0].0) as u32 as usize;
*next_index = pairs.get(index).map_or(*default, |(_, target)| *target) as usize;
}
Opcode::Monitorenter => {
let object: Option<Box<dyn ClassInstance>> = stack_frame.operand_stack.pop().unwrap().into();
let Some(object) = object else {
return Err(jvm.exception("java/lang/NullPointerException", "monitorenter on null").await);
};
jvm.monitor_enter(&object).await?;
}
Opcode::Monitorexit => {
let object: Option<Box<dyn ClassInstance>> = stack_frame.operand_stack.pop().unwrap().into();
let Some(object) = object else {
return Err(jvm.exception("java/lang/NullPointerException", "monitorexit on null").await);
};
jvm.monitor_exit(&object).await?;
}
Opcode::Multianewarray(x, d) => {
let mut dimensions: Vec<i32> = (0..*d).map(|_| stack_frame.operand_stack.pop().unwrap().into()).collect();
dimensions.reverse();
for dim in &dimensions {
if *dim < 0 {
return Err(jvm.exception("java/lang/NegativeArraySizeException", &format!("{}", dim)).await);
}
}
let array = Self::new_multi_array(jvm, x.as_class(), &dimensions).await?;
stack_frame.operand_stack.push(JavaValue::Object(Some(array)));
}
Opcode::New(x) => {
let class = jvm.instantiate_class(x.as_class()).await?;
stack_frame.operand_stack.push(JavaValue::Object(Some(class)));
}
Opcode::Newarray(x) => {
let element_type_name = match x {
4 => "Z",
5 => "C",
6 => "F",
7 => "D",
8 => "B",
9 => "S",
10 => "I",
11 => "J",
_ => panic!("Invalid array type {}", x),
};
let length: i32 = stack_frame.operand_stack.pop().unwrap().into();
if length < 0 {
return Err(jvm.exception("java/lang/NegativeArraySizeException", &format!("{}", length)).await);
}
let array = jvm.instantiate_array(element_type_name, length as _).await?;
stack_frame.operand_stack.push(JavaValue::Object(Some(array)));
}
Opcode::Nop => {}
Opcode::Pop => {
stack_frame.operand_stack.pop().unwrap();
}
Opcode::Pop2 => {
let value = stack_frame.operand_stack.pop().unwrap();
if !matches!(value, JavaValue::Long(_) | JavaValue::Double(_)) {
stack_frame.operand_stack.pop().unwrap();
}
}
Opcode::Putfield(x) => {
let x = x.as_field_ref();
let value = stack_frame.operand_stack.pop().unwrap();
let mut instance: Option<Box<dyn ClassInstance>> = stack_frame.operand_stack.pop().unwrap().into();
if instance.is_none() {
return Err(jvm.exception("java/lang/NullPointerException", "null").await);
}
let value = Self::to_field_type(&x.r#type, value);
jvm.put_field(instance.as_mut().unwrap(), &x.class, &x.name, &x.descriptor, value).await?;
}
Opcode::Putstatic(x) => {
let x = x.as_field_ref();
let value = Self::to_field_type(&x.r#type, stack_frame.operand_stack.pop().unwrap());
jvm.put_static_field(&x.class, &x.name, &x.descriptor, value).await?
}
Opcode::Ret(x) => {
let value = stack_frame.local_variables[*x as usize].clone();
let value: i32 = value.into();
*next_index = value as usize;
}
Opcode::Return => return Ok(JavaValue::Void),
Opcode::Sipush(x) => stack_frame.operand_stack.push(JavaValue::Int(*x as i32)),
Opcode::Swap => {
let value1 = stack_frame.operand_stack.pop().unwrap();
let value2 = stack_frame.operand_stack.pop().unwrap();
stack_frame.operand_stack.push(value1);
stack_frame.operand_stack.push(value2);
}
}
}
panic!("Should not reach here")
}
async fn find_exception_handler(jvm: &Jvm, exception: &dyn ClassInstance, code_attribute: &AttributeInfoCode, pc: u32) -> Option<u32> {
for exception_table in &code_attribute.exception_table {
if exception_table.start_pc <= pc as u16 && exception_table.end_pc > pc as u16 {
if exception_table.catch_type.is_none() {
return Some(exception_table.handler_pc as _);
}
let catch_type = exception_table.catch_type.as_ref().unwrap();
if jvm.is_instance(exception, catch_type) {
return Some(exception_table.handler_pc as _);
}
}
}
None
}
fn integer_condition<T>(stack_frame: &mut StackFrame, pred: T) -> bool
where
T: Fn(i32, i32) -> bool,
{
let value2 = stack_frame.operand_stack.pop().unwrap().into();
let value1 = stack_frame.operand_stack.pop().unwrap().into();
pred(value1, value2)
}
fn integer_condition_single<T>(stack_frame: &mut StackFrame, pred: T) -> bool
where
T: Fn(i32) -> bool,
{
let value = stack_frame.operand_stack.pop().unwrap().into();
pred(value)
}
fn extract_invoke_params(stack_frame: &mut StackFrame, method_type: &JavaType) -> Vec<JavaValue> {
let (param_types, _) = method_type.as_method();
let mut values = param_types
.iter()
.rev()
.map(|x| Self::to_field_type(x, stack_frame.operand_stack.pop().unwrap()))
.collect::<Vec<_>>();
values.reverse();
values
}
fn push_invoke_result(stack_frame: &mut StackFrame, value: JavaValue) {
match value {
JavaValue::Void => {}
_ => stack_frame.operand_stack.push(Self::to_stack_frame_type(value)),
}
}
fn to_field_type(r#type: &JavaType, value: JavaValue) -> JavaValue {
match r#type {
JavaType::Boolean => JavaValue::Boolean(i32::from(value) & 1 != 0),
JavaType::Byte => JavaValue::Byte(i32::from(value) as _),
JavaType::Char => JavaValue::Char(i32::from(value) as _),
JavaType::Short => JavaValue::Short(i32::from(value) as _),
_ => value,
}
}
fn to_stack_frame_type(value: JavaValue) -> JavaValue {
match value {
JavaValue::Boolean(x) => JavaValue::Int(x as _),
JavaValue::Byte(x) => JavaValue::Int(x as _),
JavaValue::Char(x) => JavaValue::Int(x as _),
JavaValue::Short(x) => JavaValue::Int(x as _),
_ => value,
}
}
#[async_recursion::async_recursion]
async fn new_multi_array(jvm: &Jvm, array_class: &str, dimensions: &[i32]) -> Result<Box<dyn ClassInstance>> {
let mut array = jvm.instantiate_array(&array_class[1..], dimensions[0] as _).await?;
if dimensions.len() > 1 {
for i in 0..dimensions[0] {
let element = Self::new_multi_array(jvm, &array_class[1..], &dimensions[1..]).await?;
jvm.store_array(&mut array, i as _, [element]).await?;
}
}
Ok(array)
}
}