Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: implement athrow instruction #78

Merged
merged 1 commit into from
Oct 18, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 1 addition & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -45,8 +45,7 @@ visit the [ristretto](https://theseus-rs.github.io/ristretto/ristretto_cli/) sit

### Limitations

- Instructions Athrow, Multianewarray and Invokedynamic are not implemented
- Exceptions are not implemented
- Instructions Multianewarray and Invokedynamic are not implemented
- Threading is not implemented
- Numerous JDK native methods are not implemented
- Finalizers are not implemented
Expand Down
1 change: 1 addition & 0 deletions ristretto_classfile/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,7 @@
#![deny(clippy::pedantic)]
#![deny(clippy::unwrap_in_result)]
#![deny(clippy::unwrap_used)]
extern crate core;

pub mod attributes;
mod base_type;
Expand Down
9 changes: 3 additions & 6 deletions ristretto_classloader/src/class_loader.rs
Original file line number Diff line number Diff line change
Expand Up @@ -206,13 +206,11 @@ mod tests {
let class_loader = ClassLoader::new("test", class_path);
let class_name = "HelloWorld";
let class = class_loader.load(class_name).await?;
let class_file = class.class_file();
assert_eq!(class_name, class_file.class_name()?);
assert_eq!(class_name, class.name());

// Load the same class again to test caching
let class = class_loader.load(class_name).await?;
let class_file = class.class_file();
assert_eq!(class_name, class_file.class_name()?);
assert_eq!(class_name, class.name());
Ok(())
}

Expand Down Expand Up @@ -252,8 +250,7 @@ mod tests {
class_loader.set_parent(Some(boot_class_loader));

let class = class_loader.load("HelloWorld").await?;
let class_file = class.class_file();
assert_eq!("HelloWorld", class_file.class_name()?);
assert_eq!("HelloWorld", class.name());
Ok(())
}

Expand Down
19 changes: 16 additions & 3 deletions ristretto_classloader/src/method.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
use crate::Error::InvalidMethodDescriptor;
use crate::Result;
use ristretto_classfile::attributes::{Attribute, Instruction, LineNumber};
use ristretto_classfile::attributes::{Attribute, ExceptionTableEntry, Instruction, LineNumber};
use ristretto_classfile::{BaseType, ClassFile, FieldType, MethodAccessFlags};
use std::fmt::Display;

Expand All @@ -15,13 +15,15 @@ pub struct Method {
max_locals: usize,
code: Vec<Instruction>,
line_numbers: Vec<LineNumber>,
exception_table: Vec<ExceptionTableEntry>,
}

impl Method {
/// Create a new class method
///
/// # Errors
/// if the method descriptor cannot be parsed
#[expect(clippy::too_many_arguments)]
pub fn new<S: AsRef<str>>(
access_flags: MethodAccessFlags,
name: S,
Expand All @@ -30,6 +32,7 @@ impl Method {
max_locals: usize,
code: Vec<Instruction>,
line_numbers: Vec<LineNumber>,
exception_table: Vec<ExceptionTableEntry>,
) -> Result<Self> {
let (parameters, return_type) = Method::parse_descriptor(descriptor.as_ref())?;
Ok(Self {
Expand All @@ -42,6 +45,7 @@ impl Method {
max_locals,
code,
line_numbers,
exception_table,
})
}

Expand All @@ -53,7 +57,7 @@ impl Method {
let constant_pool = &class_file.constant_pool;
let name = constant_pool.try_get_utf8(definition.name_index)?;
let descriptor = constant_pool.try_get_utf8(definition.descriptor_index)?;
let (max_stack, max_locals, code, line_numbers) = match definition
let (max_stack, max_locals, code, line_numbers, exception_table) = match definition
.attributes
.iter()
.find(|attribute| matches!(attribute, Attribute::Code { .. }))
Expand All @@ -63,6 +67,7 @@ impl Method {
max_locals,
code,
attributes,
exception_table,
..
}) => {
let line_numbers = match attributes
Expand All @@ -80,9 +85,10 @@ impl Method {
usize::from(*max_locals),
code.clone(), // TODO: avoid cloning code
line_numbers,
exception_table.clone(), // TODO: avoid cloning exception_table
)
}
_ => (0, 0, Vec::new(), Vec::new()),
_ => (0, 0, Vec::new(), Vec::new(), Vec::new()),
};

Method::new(
Expand All @@ -93,6 +99,7 @@ impl Method {
max_locals,
code,
line_numbers,
exception_table,
)
}

Expand Down Expand Up @@ -180,6 +187,12 @@ impl Method {
usize::from(line_number)
}

/// Get the exception table.
#[must_use]
pub fn exception_table(&self) -> &Vec<ExceptionTableEntry> {
&self.exception_table
}

/// Parse the method descriptor. The descriptor is a string representing the method signature.
/// The descriptor has the following format:
///
Expand Down
12 changes: 3 additions & 9 deletions ristretto_classloader/tests/class_loader.rs
Original file line number Diff line number Diff line change
Expand Up @@ -8,8 +8,7 @@ async fn test_load_class_from_class_path_directory() -> Result<()> {
let class_path = classes_directory.to_string_lossy();
let class_loader = ClassLoader::new("directory-test", ClassPath::from(&class_path));
let class = class_loader.load("HelloWorld").await?;
let class_file = class.class_file();
assert_eq!("HelloWorld", class_file.class_name()?);
assert_eq!("HelloWorld", class.name());
Ok(())
}

Expand All @@ -20,8 +19,7 @@ async fn test_load_class_from_class_path_jar() -> Result<()> {
let class_path = ClassPath::from(classes_directory.to_string_lossy());
let class_loader = ClassLoader::new("jar-test", class_path);
let class = class_loader.load("HelloWorld").await?;
let class_file = class.class_file();
assert_eq!("HelloWorld", class_file.class_name()?);
assert_eq!("HelloWorld", class.name());
Ok(())
}

Expand All @@ -34,10 +32,6 @@ async fn test_load_class_from_class_path_url() -> Result<()> {
let class = class_loader
.load("org/springframework/boot/SpringApplication")
.await?;
let class_file = class.class_file();
assert_eq!(
"org/springframework/boot/SpringApplication",
class_file.class_name()?
);
assert_eq!("org/springframework/boot/SpringApplication", class.name());
Ok(())
}
3 changes: 1 addition & 2 deletions ristretto_classloader/tests/runtime.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,8 +4,7 @@ async fn test_runtime(version: &str, class_name: &str) -> Result<()> {
let (runtime_version, class_loader) = runtime::class_loader(version).await?;
assert!(runtime_version.starts_with(version));
let class = class_loader.load(class_name).await?;
let class_file = class.class_file();
assert_eq!(class_name, class_file.class_name()?);
assert_eq!(class_name, class.name());
Ok(())
}

Expand Down
3 changes: 3 additions & 0 deletions ristretto_vm/src/error.rs
Original file line number Diff line number Diff line change
Expand Up @@ -58,6 +58,9 @@ pub enum Error {
/// Poisoned lock
#[error("Poisoned lock: {0}")]
PoisonedLock(String),
/// Error that represents a JVM throwable object
#[error("java.lang.Throwable: {0}")]
Throwable(ristretto_classloader::Object),
/// An error occurred while converting from an integer
#[error(transparent)]
TryFromIntError(#[from] std::num::TryFromIntError),
Expand Down
47 changes: 26 additions & 21 deletions ristretto_vm/src/frame.rs
Original file line number Diff line number Diff line change
@@ -1,24 +1,25 @@
use crate::frame::ExecutionResult::{Continue, ContinueAtPosition, Return};
use crate::instruction::{
aaload, aastore, aconst_null, aload, aload_0, aload_1, aload_2, aload_3, aload_w, anewarray,
areturn, arraylength, astore, astore_0, astore_1, astore_2, astore_3, astore_w, baload,
bastore, bipush, caload, castore, checkcast, d2f, d2i, d2l, dadd, daload, dastore, dcmpg,
dcmpl, dconst_0, dconst_1, ddiv, dload, dload_0, dload_1, dload_2, dload_3, dload_w, dmul,
dneg, drem, dreturn, dstore, dstore_0, dstore_1, dstore_2, dstore_3, dstore_w, dsub, dup, dup2,
dup2_x1, dup2_x2, dup_x1, dup_x2, f2d, f2i, f2l, fadd, faload, fastore, fcmpg, fcmpl, fconst_0,
fconst_1, fconst_2, fdiv, fload, fload_0, fload_1, fload_2, fload_3, fload_w, fmul, fneg, frem,
freturn, fstore, fstore_0, fstore_1, fstore_2, fstore_3, fstore_w, fsub, getfield, getstatic,
goto, goto_w, i2b, i2c, i2d, i2f, i2l, i2s, iadd, iaload, iand, iastore, iconst_0, iconst_1,
iconst_2, iconst_3, iconst_4, iconst_5, iconst_m1, idiv, if_acmpeq, if_acmpne, if_icmpeq,
if_icmpge, if_icmpgt, if_icmple, if_icmplt, if_icmpne, ifeq, ifge, ifgt, ifle, iflt, ifne,
ifnonnull, ifnull, iinc, iinc_w, iload, iload_0, iload_1, iload_2, iload_3, iload_w, imul,
ineg, instanceof, invokedynamic, invokeinterface, invokespecial, invokestatic, invokevirtual,
ior, irem, ireturn, ishl, ishr, istore, istore_0, istore_1, istore_2, istore_3, istore_w, isub,
iushr, ixor, jsr, jsr_w, l2d, l2f, l2i, ladd, laload, land, lastore, lcmp, lconst_0, lconst_1,
ldc, ldc2_w, ldc_w, ldiv, lload, lload_0, lload_1, lload_2, lload_3, lload_w, lmul, lneg,
lookupswitch, lor, lrem, lreturn, lshl, lshr, lstore, lstore_0, lstore_1, lstore_2, lstore_3,
lstore_w, lsub, lushr, lxor, multianewarray, new, newarray, pop, pop2, putfield, putstatic,
ret, ret_w, saload, sastore, sipush, swap, tableswitch,
areturn, arraylength, astore, astore_0, astore_1, astore_2, astore_3, astore_w, athrow, baload,
bastore, bipush, caload, castore, checkcast, convert_error_to_throwable, d2f, d2i, d2l, dadd,
daload, dastore, dcmpg, dcmpl, dconst_0, dconst_1, ddiv, dload, dload_0, dload_1, dload_2,
dload_3, dload_w, dmul, dneg, drem, dreturn, dstore, dstore_0, dstore_1, dstore_2, dstore_3,
dstore_w, dsub, dup, dup2, dup2_x1, dup2_x2, dup_x1, dup_x2, f2d, f2i, f2l, fadd, faload,
fastore, fcmpg, fcmpl, fconst_0, fconst_1, fconst_2, fdiv, fload, fload_0, fload_1, fload_2,
fload_3, fload_w, fmul, fneg, frem, freturn, fstore, fstore_0, fstore_1, fstore_2, fstore_3,
fstore_w, fsub, getfield, getstatic, goto, goto_w, i2b, i2c, i2d, i2f, i2l, i2s, iadd, iaload,
iand, iastore, iconst_0, iconst_1, iconst_2, iconst_3, iconst_4, iconst_5, iconst_m1, idiv,
if_acmpeq, if_acmpne, if_icmpeq, if_icmpge, if_icmpgt, if_icmple, if_icmplt, if_icmpne, ifeq,
ifge, ifgt, ifle, iflt, ifne, ifnonnull, ifnull, iinc, iinc_w, iload, iload_0, iload_1,
iload_2, iload_3, iload_w, imul, ineg, instanceof, invokedynamic, invokeinterface,
invokespecial, invokestatic, invokevirtual, ior, irem, ireturn, ishl, ishr, istore, istore_0,
istore_1, istore_2, istore_3, istore_w, isub, iushr, ixor, jsr, jsr_w, l2d, l2f, l2i, ladd,
laload, land, lastore, lcmp, lconst_0, lconst_1, ldc, ldc2_w, ldc_w, ldiv, lload, lload_0,
lload_1, lload_2, lload_3, lload_w, lmul, lneg, lookupswitch, lor, lrem, lreturn, lshl, lshr,
lstore, lstore_0, lstore_1, lstore_2, lstore_3, lstore_w, lsub, lushr, lxor, multianewarray,
new, newarray, pop, pop2, process_throwable, putfield, putstatic, ret, ret_w, saload, sastore,
sipush, swap, tableswitch,
};
use crate::Error::{InternalError, InvalidOperand, InvalidProgramCounter};
use crate::{CallStack, LocalVariables, OperandStack, Result};
Expand Down Expand Up @@ -125,6 +126,7 @@
/// * if an invalid instruction is encountered
pub async fn execute(&self) -> Result<Option<Value>> {
let code = self.method.code();

loop {
let program_counter = self.program_counter.load(Ordering::Relaxed);
let Some(instruction) = code.get(program_counter) else {
Expand All @@ -147,8 +149,11 @@
}
Ok(Return(value)) => return Ok(value.clone()),
Err(error) => {
// TODO: implement exception handling
return Err(error);
let vm = self.call_stack()?.vm()?;
let throwable = convert_error_to_throwable(vm, error).await?;
let handler_program_counter = process_throwable(self, throwable)?;
self.program_counter
.store(handler_program_counter, Ordering::Relaxed);

Check warning on line 156 in ristretto_vm/src/frame.rs

View check run for this annotation

Codecov / codecov/patch

ristretto_vm/src/frame.rs#L155-L156

Added lines #L155 - L156 were not covered by tests
}
}
}
Expand Down Expand Up @@ -390,7 +395,7 @@
Instruction::Newarray(array_type) => newarray(&self.stack, array_type),
Instruction::Anewarray(index) => anewarray(self, *index).await,
Instruction::Arraylength => arraylength(&self.stack),
Instruction::Athrow => todo!(),
Instruction::Athrow => athrow(self).await,
Instruction::Checkcast(class_index) => {
let constant_pool = self.class.constant_pool();
let class_name = constant_pool.try_get_class(*class_index)?;
Expand Down
3 changes: 3 additions & 0 deletions ristretto_vm/src/instruction/array.rs
Original file line number Diff line number Diff line change
Expand Up @@ -228,6 +228,7 @@ mod tests {
10,
Vec::new(),
Vec::new(),
Vec::new(),
)?;
let arguments = Vec::new();
let frame = Frame::new(
Expand Down Expand Up @@ -358,6 +359,7 @@ mod tests {
10,
Vec::new(),
Vec::new(),
Vec::new(),
)?;
let arguments = Vec::new();
let frame = Frame::new(
Expand Down Expand Up @@ -417,6 +419,7 @@ mod tests {
10,
Vec::new(),
Vec::new(),
Vec::new(),
)?;
let arguments = Vec::new();
let frame = Frame::new(
Expand Down
84 changes: 84 additions & 0 deletions ristretto_vm/src/instruction/exception.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,84 @@
use crate::frame::{ExecutionResult, Frame};
use crate::Error::{InternalError, Throwable};
use crate::{Error, Result, VM};
use ristretto_classloader::{Object, Reference};
use std::sync::Arc;

/// See: <https://docs.oracle.com/javase/specs/jvms/se23/html/jvms-6.html#jvms-6.5.athrow>
#[inline]
pub(crate) async fn athrow(frame: &Frame) -> Result<ExecutionResult> {
let stack = frame.stack();
let Some(Reference::Object(throwable)) = stack.pop_object()? else {
return Err(InternalError("Expected object on top of stack".to_string()));

Check warning on line 12 in ristretto_vm/src/instruction/exception.rs

View check run for this annotation

Codecov / codecov/patch

ristretto_vm/src/instruction/exception.rs#L12

Added line #L12 was not covered by tests
};
// Return the exception to the caller and let the frame error handler deal with it
Err(Throwable(throwable))
}

/// Process the throwable and return the next instruction to execute; if there is no exception
/// handler, the exception is returned as an error.
///
/// See: <https://docs.oracle.com/javase/specs/jvms/se23/html/jvms-4.html#jvms-4.7.3>
/// See: <https://docs.oracle.com/javase/specs/jvms/se23/html/jvms-6.html#jvms-6.5.athrow>
pub(crate) fn process_throwable(frame: &Frame, throwable: Object) -> Result<usize> {
let throwable_class = throwable.class();
let class = frame.class();
let constant_pool = class.constant_pool();
let method = frame.method();
let exception_table = method.exception_table();
let program_counter = u16::try_from(frame.program_counter())?;

for exception_table_entry in exception_table {
if !exception_table_entry.range_pc.contains(&program_counter) {
continue;
}

Check warning on line 34 in ristretto_vm/src/instruction/exception.rs

View check run for this annotation

Codecov / codecov/patch

ristretto_vm/src/instruction/exception.rs#L32-L34

Added lines #L32 - L34 were not covered by tests

let exception_class_name = constant_pool.try_get_class(exception_table_entry.catch_type)?;
if throwable_class.is_assignable_from(exception_class_name)? {
let stack = frame.stack();
let handler_program_counter = usize::from(exception_table_entry.handler_pc);
stack.push_object(Some(Reference::Object(throwable)))?;
return Ok(handler_program_counter);
}

Check warning on line 42 in ristretto_vm/src/instruction/exception.rs

View check run for this annotation

Codecov / codecov/patch

ristretto_vm/src/instruction/exception.rs#L36-L42

Added lines #L36 - L42 were not covered by tests
}

// If no exception handler is found, an error containing the throwable is returned
Err(Throwable(throwable))
}

/// Convert native Rust errors to Java throwables.
///
/// # Errors
/// if the error cannot be converted to a throwable
pub(crate) async fn convert_error_to_throwable(vm: Arc<VM>, error: Error) -> Result<Object> {
let throwable = match error {
Throwable(throwable) => throwable,
error => {
let class = vm.class("java/lang/InternalError").await?;
let message = format!("{error}");
let error_message = vm.string(&message).await?;
let throwable = Object::new(class)?;
let detail_message_field = throwable.field("detailMessage")?;
detail_message_field.set_value(error_message)?;
throwable

Check warning on line 63 in ristretto_vm/src/instruction/exception.rs

View check run for this annotation

Codecov / codecov/patch

ristretto_vm/src/instruction/exception.rs#L56-L63

Added lines #L56 - L63 were not covered by tests
}
};
Ok(throwable)
}

#[cfg(test)]
mod test {
use super::*;
use crate::VM;

#[tokio::test]
async fn test_process_throwable() -> Result<()> {
let vm = VM::default().await?;
let class = vm.class("java.lang.Integer").await?;
let method = class.try_get_method("parseInt", "(Ljava/lang/String;)I")?;
let value = vm.string("foo").await?;
let result = vm.invoke(&class, &method, vec![value]).await;
assert!(result.is_err());
Ok(())
}
}
1 change: 1 addition & 0 deletions ristretto_vm/src/instruction/field.rs
Original file line number Diff line number Diff line change
Expand Up @@ -86,6 +86,7 @@ mod test {
10,
Vec::new(),
Vec::new(),
Vec::new(),
)?;
let arguments = Vec::new();
let frame = Frame::new(
Expand Down
2 changes: 2 additions & 0 deletions ristretto_vm/src/instruction/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ mod byte;
mod char;
mod convert;
mod double;
mod exception;
mod field;
mod float;
mod integer;
Expand All @@ -22,6 +23,7 @@ pub(crate) use byte::*;
pub(crate) use char::*;
pub(crate) use convert::*;
pub(crate) use double::*;
pub(crate) use exception::*;
pub(crate) use field::*;
pub(crate) use float::*;
pub(crate) use integer::*;
Expand Down
Loading