Skip to content

52: support standard library #60

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

Merged
merged 7 commits into from
Aug 19, 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
32 changes: 13 additions & 19 deletions src/classloader/bootstrap_class_loader.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,13 +7,10 @@ use crate::classloader::constant_pool::{decode_constant_pool, utf8_info_as_strin
use crate::classloader::java_class_file::{decode_access_flags, decode_fields, decode_interfaces, decode_methods, decode_this_or_super_class, JavaClassFile};
use crate::classloader::attributes::decode_attributes;

const MAGIC: u32 = 0xCAFEBABE;
const SUPPORTED_MINOR_VERSION: f32 = 45.0;
const SUPPORTED_MAJOR_VERSION: f32 = 61.0;

use thiserror::Error;
use crate::classloader::constant_pool::ConstantPoolInfo::Class;
use crate::{error, STORAGE};
use crate::{error, get_class};
use crate::consts::{JAVA_LANG_OBJECT_SUPER_CLASS_INDEX, JAVA_MAGIC, SUPPORTED_MAJOR_VERSION, SUPPORTED_MINOR_VERSION};
use crate::core::method_area::{RuntimeClass};
use crate::core::runtime_data_area::RuntimeDataArea;

Expand Down Expand Up @@ -41,7 +38,7 @@ impl BootstrapClassLoader {

// Check Magic
let magic = buffer.get_u32();
if magic != MAGIC {
if magic != JAVA_MAGIC {
error("ClassFormatError");
return Err(anyhow!(ErrorType::InvalidInputError));
}
Expand Down Expand Up @@ -74,16 +71,16 @@ impl BootstrapClassLoader {
};
}

let this_class = decode_this_or_super_class(&mut buffer, &constant_pool)?;
let this_class = decode_this_or_super_class(class_name.to_string(), &mut buffer, &constant_pool, false)?;

if !check_class_name!(this_class) {
error("NoClassDefFoundError");
panic!();
}

let super_class = decode_this_or_super_class(&mut buffer, &constant_pool)?;
let super_class = decode_this_or_super_class(class_name.to_string(), &mut buffer, &constant_pool, true)?;

if check_class_name!(super_class) {
if super_class != JAVA_LANG_OBJECT_SUPER_CLASS_INDEX && check_class_name!(super_class) {
error("ClassCircularityError");
panic!();
}
Expand All @@ -94,6 +91,7 @@ impl BootstrapClassLoader {
let attributes = decode_attributes(&mut buffer, &constant_pool)?;

time_end();
wasm_rs_dbg::dbg!(this_class, super_class);

Ok(JavaClassFile {
constant_pool,
Expand All @@ -115,16 +113,12 @@ impl BootstrapClassLoader {
}
_ => {
let data = {
let storage = STORAGE.lock().unwrap();
let d = storage.get(class_name.to_string());

match d {
// TODO: remove clone...
Some(v) => Some(v.clone()),
_ => {
error(format!("Binary for {} is not found on storage!", class_name).as_str());
None
}
let d = get_class(class_name.as_str());
if d.len() > 0 {
Some(d.to_vec())
} else {
error(format!("Binary for {} is not found on storage!", class_name).as_str());
None
}
};

Expand Down
7 changes: 6 additions & 1 deletion src/classloader/java_class_file.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ use crate::classloader::constant_pool::{ConstantPoolInfo};
use crate::classloader::attributes::{AttributeInfo, decode_attributes};

use thiserror::Error;
use crate::consts::{JAVA_LANG_OBJECT_NAME, JAVA_LANG_OBJECT_SUPER_CLASS_INDEX};

#[derive(Debug, Error)]
enum ErrorType {
Expand Down Expand Up @@ -104,9 +105,13 @@ pub fn decode_access_flags(flags: u16) -> anyhow::Result<Vec<AccessFlag>> {
}

/// Decodes this_class or super_class
pub fn decode_this_or_super_class(buffer: &mut BytesMut, constant_pool: &[ConstantPoolInfo]) -> anyhow::Result<usize> {
pub fn decode_this_or_super_class(class_name: String, buffer: &mut BytesMut, constant_pool: &[ConstantPoolInfo], is_super: bool) -> anyhow::Result<usize> {
let class_index = buffer.get_u16() as usize;

if is_super && class_name == JAVA_LANG_OBJECT_NAME {
return Ok(JAVA_LANG_OBJECT_SUPER_CLASS_INDEX);
}

if !matches!(&constant_pool[class_index], ConstantPoolInfo::Class(_)) {
return Err(anyhow!(ErrorType::InvalidThisOrSuperClassError));
}
Expand Down
14 changes: 14 additions & 0 deletions src/consts.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
/// The magic number for a Java class file.
pub const JAVA_MAGIC: u32 = 0xCAFEBABE;

/// The minor version of the Java class file.
pub const SUPPORTED_MINOR_VERSION: f32 = 45.0;

/// The major version of the Java class file.
pub const SUPPORTED_MAJOR_VERSION: f32 = 61.0;

/// super_class value for java/lang/Object
pub const JAVA_LANG_OBJECT_SUPER_CLASS_INDEX: usize = 0;

/// The name of the java/lang/Object class
pub const JAVA_LANG_OBJECT_NAME: &str = "java/lang/Object";
19 changes: 10 additions & 9 deletions src/core/method_area.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ use crate::classloader::attributes::AttributeInfo::Code;
use crate::classloader::bootstrap_class_loader::{BootstrapClassLoader};
use crate::classloader::constant_pool::{class_name_as_string, ConstantPoolInfo, utf8_info_as_string};
use crate::classloader::java_class_file::{AccessFlag, Descriptor, FieldInfo, JavaClassFile, MethodInfo};
use crate::consts::JAVA_LANG_OBJECT_SUPER_CLASS_INDEX;

use crate::execution::interpreter::Value;
use crate::execution::utils::parse_descriptor;
Expand Down Expand Up @@ -48,19 +49,21 @@ pub struct RuntimeClass /*<'a>*/ {

impl RuntimeClass {
pub fn new(class_loader: &mut BootstrapClassLoader, mut java_class_file: JavaClassFile) -> RuntimeClass {
let super_class_name = class_name_as_string!(
let super_class_name = if *&java_class_file.super_class == JAVA_LANG_OBJECT_SUPER_CLASS_INDEX { "" } else {
class_name_as_string!(
java_class_file.constant_pool,
*&java_class_file.super_class
);
)
};

let this_class_name = class_name_as_string!(
java_class_file.constant_pool,
*&java_class_file.this_class
);

let name = this_class_name.to_string();

// TODO: if this class name is Object then return None
let super_class = if super_class_name == "java/lang/Object" { None } else {
let super_class = if *&java_class_file.super_class == JAVA_LANG_OBJECT_SUPER_CLASS_INDEX { None } else {
class_loader.load_class(super_class_name.to_string())
};

Expand Down Expand Up @@ -149,8 +152,8 @@ impl RuntimeClass {
attributes: HashMap::with_capacity(0),
name,
}
},
}
}
};
}

fn build_fields(java_class_file: &mut JavaClassFile) -> HashMap<String, Rc<Mutex<Field>>> {
Expand Down Expand Up @@ -196,7 +199,7 @@ impl RuntimeClass {
Some(Rc::clone(method))
}
_ => {
let Some(super_class) = &class.super_class else { return None };
let Some(super_class) = &class.super_class else { return None; };
Self::lookup_method(Rc::clone(super_class), name)
}
}
Expand Down Expand Up @@ -225,6 +228,4 @@ impl MethodArea {
_ => None
}
}


}
7 changes: 3 additions & 4 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ mod jvm;
mod execution;
mod storage;
mod wasm_utils;
mod consts;

use std::rc::Rc;
use std::sync::{Mutex};
Expand All @@ -28,9 +29,9 @@ extern "C" {
fn log(text: &str);
fn error(text: &str);
fn update_local_variables(class: &str, method: &str, locals: &str);
}

pub static STORAGE: Lazy<Mutex<Storage>> = Lazy::new(|| Mutex::new(Storage::new()));
fn get_class(class_name: &str) -> Box<[u8]>;
}

#[wasm_bindgen]
pub fn launch(main_class: &str, bytes: &[u8]) {
Expand All @@ -39,8 +40,6 @@ pub fn launch(main_class: &str, bytes: &[u8]) {

let main_method = "main([Ljava/lang/String;)V";

STORAGE.lock().unwrap().add_binary(main_class.to_string(), bytes.to_vec());

let jvm = Rc::new(Mutex::new(JVM::new()));
let class = jvm.lock().unwrap().bootstrap_class_loader.lock().unwrap().load_class(main_class.to_string());

Expand Down
6 changes: 6 additions & 0 deletions web/package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions web/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@
"vite": "^5.2.0"
},
"dependencies": {
"fflate": "^0.8.2",
"react": "^18.3.1",
"react-dom": "^18.3.1",
"react-router-dom": "^6.26.0",
Expand Down
Binary file added web/public/java/lib/rt.zip
Binary file not shown.
43 changes: 40 additions & 3 deletions web/src/main.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -9,11 +9,17 @@ import {
EVENT_CONSOLE_STDERR,
EVENT_CONSOLE_STDOUT
} from "./consts/constants.ts";
import {unzip} from "fflate";

const MAIN_CLASS_NAME = "Variables";
const MAIN_CLASS_NAME = "Instance";
const MAIN_CLASS = `java/${MAIN_CLASS_NAME}.class`;
const DEBUG = true;

// pathes for standard libraries
const LIBRARIES = ['java/lib/rt.zip'];

let classes: Record<string, Uint8Array> = {};

/**
* Dispatch a custom event
* @param type
Expand Down Expand Up @@ -56,13 +62,35 @@ const launchBJVM = async () => {
dispatchEvent<InformationEvent>(EVENT_BJVM_INFORMATION, {type: "mainClass", value: MAIN_CLASS});
dispatchEvent<InformationEvent>(EVENT_BJVM_INFORMATION, {type: "debug", value: DEBUG});

const data = await fetchAsUint8Array(MAIN_CLASS);
const unzipSync = async (data: Uint8Array) => {
return new Promise<Record<string, Uint8Array>>((resolve, reject) => {
unzip(data, (err, result) => {
if (err) {
reject(err);
} else {
resolve(result);
}
});
});
}

for (const library of LIBRARIES) {
const lib = await fetchAsUint8Array(library);
const inflated = await unzipSync(lib);

for (const [key, value] of Object.entries(inflated)) {
classes[key.replace(".class", "")] = value;
}
}

const mainClassBytes = await fetchAsUint8Array(MAIN_CLASS);
classes[MAIN_CLASS_NAME] = mainClassBytes;

debug("Launching BJVM...");

try {
await init();
launch(MAIN_CLASS_NAME, data);
launch(MAIN_CLASS_NAME, mainClassBytes);
} catch (e) {
console.log(e);
}
Expand All @@ -71,6 +99,15 @@ const launchBJVM = async () => {
}
(window as any).launchBJVM = launchBJVM;

/**
* Get class by name
* @param className
*/
const get_class = (className: string) => {
return classes[className] ?? [];
}
(window as any).get_class = get_class;

// for debug
const consoleLog = (text: string) => {
const date = new Date();
Expand Down
Loading