fabric-rs-codegen 0.2.0

Pure-Rust JVM classfile writer, JAR SDK indexer, Rust binding emitter, and Mixin/Subclass bytecode generator for FLR v2
Documentation
//! Isolated per-mod `FlrLoader.class`, `RustBootstrap.class`, and `NativeBridge.class` generators.

use fabric_rs_core::metadata::EntrypointMeta;

use crate::class_reader::relocate_class_bytes;
use crate::jvm_writer::access_flags::*;
use crate::jvm_writer::opcodes::*;
use crate::jvm_writer::{ClassWriter, CodeWriter, FieldWriter, MethodWriter, VerificationType};

pub const FLR_RUNTIME_LOADER_CLASS: &[u8] =
    include_bytes!("../assets/dev/fabricrs/loader/FlrRuntimeLoader.class");
pub const FLR_THIN_LOADER_CLASS: &[u8] =
    include_bytes!("../assets/dev/fabricrs/loader/FlrThinLoader.class");

/// Returns the isolated loader internal class name for a mod (`dev/fabricrs/mod_<clean_id>/FlrLoader`).
pub fn loader_class_name(clean_id: &str) -> String {
    format!("dev/fabricrs/mod_{clean_id}/FlrLoader")
}

/// Returns the isolated bootstrap internal class name for a mod (`dev/fabricrs/mod_<clean_id>/RustBootstrap`).
pub fn bootstrap_class_name(clean_id: &str) -> String {
    format!("dev/fabricrs/mod_{clean_id}/RustBootstrap")
}

/// Returns the isolated dynamic event bridge class name (`dev/fabricrs/mod_<clean_id>/NativeBridge`).
pub fn bridge_class_name(clean_id: &str) -> String {
    format!("dev/fabricrs/mod_{clean_id}/NativeBridge")
}

/// Relocates either `FlrRuntimeLoader` (when source fallback is active) or `FlrThinLoader`
/// into the mod's isolated namespace so mods never clash at runtime.
pub fn relocate_runtime_loader(clean_id: &str, include_source_fallback: bool) -> Result<Vec<u8>, String> {
    let target = loader_class_name(clean_id);
    if include_source_fallback {
        relocate_class_bytes(
            FLR_RUNTIME_LOADER_CLASS,
            &[("dev/fabricrs/loader/FlrRuntimeLoader", target.as_str())],
        )
    } else {
        relocate_class_bytes(
            FLR_THIN_LOADER_CLASS,
            &[("dev/fabricrs/loader/FlrThinLoader", target.as_str())],
        )
    }
}

/// Synthesizes `dev/fabricrs/mod_<clean_id>/RustBootstrap.class` strictly implementing only
/// the Fabric entrypoint interfaces declared by the mod.
pub fn generate_rust_bootstrap(
    mod_id: &str,
    lib_stem: &str,
    clean_id: &str,
    entrypoints: &[EntrypointMeta],
    allow_source_fallback: bool,
    java_version: u16,
) -> Result<Vec<u8>, String> {
    let this_cls = bootstrap_class_name(clean_id);
    let loader_cls = loader_class_name(clean_id);

    let mut cw = ClassWriter::new(&this_cls, "java/lang/Object", ACC_PUBLIC | ACC_SUPER, java_version);

    let has_prelaunch = entrypoints.iter().any(|e| e.entry_type == "preLaunch");
    let has_main = entrypoints.iter().any(|e| e.entry_type == "main");
    let has_client = entrypoints.iter().any(|e| e.entry_type == "client");
    let has_server = entrypoints.iter().any(|e| e.entry_type == "server");

    // Always implement PreLaunchEntrypoint so native lib loads early even for Mixin/Subclass mods.
    cw.add_interface("net/fabricmc/loader/api/entrypoint/PreLaunchEntrypoint");
    if has_main {
        cw.add_interface("net/fabricmc/api/ModInitializer");
    }
    if has_client {
        cw.add_interface("net/fabricmc/api/ClientModInitializer");
    }
    if has_server {
        cw.add_interface("net/fabricmc/api/DedicatedServerModInitializer");
    }

    // private static boolean loaded;
    cw.add_field(FieldWriter {
        access_flags: ACC_PRIVATE | ACC_STATIC,
        name: "loaded".to_string(),
        descriptor: "Z".to_string(),
    });

    // Public no-arg constructor
    let obj_init = cw.cp.add_methodref("java/lang/Object", "<init>", "()V");
    let mut ctor = CodeWriter::new(1, 1);
    ctor.emit_aload(0);
    ctor.emit_u8(INVOKESPECIAL);
    ctor.emit_u16(obj_init);
    ctor.emit_u8(RETURN);
    cw.add_method(MethodWriter {
        access_flags: ACC_PUBLIC,
        name: "<init>".to_string(),
        descriptor: "()V".to_string(),
        code: Some(ctor),
        annotations: Vec::new(),
    });

    // public static synchronized void ensureLoaded()
    let loaded_ref = cw.cp.add_fieldref(&this_cls, "loaded", "Z");
    let self_cls_ldc = cw.cp.add_class(&this_cls);
    let mod_id_ldc = cw.cp.add_string(mod_id);
    let lib_stem_ldc = cw.cp.add_string(lib_stem);
    let loader_mref = cw.cp.add_methodref(
        &loader_cls,
        "loadNative",
        "(Ljava/lang/Class;Ljava/lang/String;Ljava/lang/String;Z)Z",
    );

    let mut ensure = CodeWriter::new(4, 0);
    let not_loaded_lbl = ensure.new_label();
    ensure.emit_u8(GETSTATIC);
    ensure.emit_u16(loaded_ref);
    ensure.emit_jump(IFEQ, not_loaded_lbl);
    ensure.emit_u8(RETURN);
    ensure.bind_label_with_frame(not_loaded_lbl, Vec::new(), Vec::new());
    ensure.emit_ldc(self_cls_ldc);
    ensure.emit_ldc(mod_id_ldc);
    ensure.emit_ldc(lib_stem_ldc);
    ensure.emit_u8(if allow_source_fallback { ICONST_1 } else { ICONST_0 });
    ensure.emit_u8(INVOKESTATIC);
    ensure.emit_u16(loader_mref);
    ensure.emit_u8(PUTSTATIC);
    ensure.emit_u16(loaded_ref);
    ensure.emit_u8(RETURN);

    cw.add_method(MethodWriter {
        access_flags: ACC_PUBLIC | ACC_STATIC | ACC_SYNCHRONIZED,
        name: "ensureLoaded".to_string(),
        descriptor: "()V".to_string(),
        code: Some(ensure),
        annotations: Vec::new(),
    });

    // static { ensureLoaded(); }
    let ensure_mref = cw.cp.add_methodref(&this_cls, "ensureLoaded", "()V");
    let mut clinit = CodeWriter::new(0, 0);
    clinit.emit_u8(INVOKESTATIC);
    clinit.emit_u16(ensure_mref);
    clinit.emit_u8(RETURN);
    cw.add_method(MethodWriter {
        access_flags: ACC_STATIC,
        name: "<clinit>".to_string(),
        descriptor: "()V".to_string(),
        code: Some(clinit),
        annotations: Vec::new(),
    });

    // Emit native method declarations for every entrypoint using the unmangled Java method name
    // stored in `ep.rust_fn`, which the JVM will mangle to match `ep.jni_symbol`.
    let mut method_names_for_type: Vec<(&str, Vec<String>)> = vec![
        ("preLaunch", Vec::new()),
        ("main", Vec::new()),
        ("client", Vec::new()),
        ("server", Vec::new()),
    ];

    for ep in entrypoints {
        let native_name = ep.rust_fn.clone();
        cw.add_method(MethodWriter {
            access_flags: ACC_PUBLIC | ACC_STATIC | ACC_NATIVE,
            name: native_name.clone(),
            descriptor: "()V".to_string(),
            code: None,
            annotations: Vec::new(),
        });
        if let Some((_, list)) = method_names_for_type
            .iter_mut()
            .find(|(k, _)| *k == ep.entry_type)
        {
            list.push(native_name);
        }
    }

    // onPreLaunch()
    let mut pre_code = CodeWriter::new(1, 1);
    pre_code.emit_u8(INVOKESTATIC);
    pre_code.emit_u16(ensure_mref);
    if has_prelaunch {
        for mname in &method_names_for_type[0].1 {
            let mref = cw.cp.add_methodref(&this_cls, mname, "()V");
            pre_code.emit_u8(INVOKESTATIC);
            pre_code.emit_u16(mref);
        }
    }
    pre_code.emit_u8(RETURN);
    cw.add_method(MethodWriter {
        access_flags: ACC_PUBLIC,
        name: "onPreLaunch".to_string(),
        descriptor: "()V".to_string(),
        code: Some(pre_code),
        annotations: Vec::new(),
    });

    let emit_entrypoint_method = |cw: &mut ClassWriter, java_name: &str, natives: &[String]| {
        let mut code = CodeWriter::new(1, 1);
        let ensure_ref = cw.cp.add_methodref(&this_cls, "ensureLoaded", "()V");
        code.emit_u8(INVOKESTATIC);
        code.emit_u16(ensure_ref);
        for mname in natives {
            let mref = cw.cp.add_methodref(&this_cls, mname, "()V");
            code.emit_u8(INVOKESTATIC);
            code.emit_u16(mref);
        }
        code.emit_u8(RETURN);
        cw.add_method(MethodWriter {
            access_flags: ACC_PUBLIC,
            name: java_name.to_string(),
            descriptor: "()V".to_string(),
            code: Some(code),
            annotations: Vec::new(),
        });
    };

    if has_main {
        emit_entrypoint_method(&mut cw, "onInitialize", &method_names_for_type[1].1);
    }
    if has_client {
        emit_entrypoint_method(&mut cw, "onInitializeClient", &method_names_for_type[2].1);
    }
    if has_server {
        emit_entrypoint_method(&mut cw, "onInitializeServer", &method_names_for_type[3].1);
    }

    cw.finish()
}

/// Synthesizes `dev/fabricrs/mod_<clean_id>/NativeBridge.class` ONLY when the mod uses dynamic proxies/events.
/// Handles `Object.hashCode()`, `Object.equals(Object)`, and `Object.toString()` safely on the proxy
/// without forwarding JVM Object methods into Rust event closures.
pub fn generate_native_bridge(clean_id: &str, java_version: u16) -> Result<Vec<u8>, String> {
    let this_cls = bridge_class_name(clean_id);
    let mut cw = ClassWriter::new(&this_cls, "java/lang/Object", ACC_PUBLIC | ACC_SUPER, java_version);
    cw.add_interface("java/lang/reflect/InvocationHandler");

    cw.add_field(FieldWriter {
        access_flags: ACC_PRIVATE | ACC_FINAL,
        name: "rustClosurePtr".to_string(),
        descriptor: "J".to_string(),
    });

    // Constructor(long ptr)
    let obj_init = cw.cp.add_methodref("java/lang/Object", "<init>", "()V");
    let ptr_field = cw.cp.add_fieldref(&this_cls, "rustClosurePtr", "J");
    let mut ctor = CodeWriter::new(3, 3);
    ctor.emit_aload(0);
    ctor.emit_u8(INVOKESPECIAL);
    ctor.emit_u16(obj_init);
    ctor.emit_aload(0);
    ctor.emit_u8(LLOAD_1);
    ctor.emit_u8(PUTFIELD);
    ctor.emit_u16(ptr_field);
    ctor.emit_u8(RETURN);
    cw.add_method(MethodWriter {
        access_flags: ACC_PUBLIC,
        name: "<init>".to_string(),
        descriptor: "(J)V".to_string(),
        code: Some(ctor),
        annotations: Vec::new(),
    });

    // Native trampoline
    cw.add_method(MethodWriter {
        access_flags: ACC_PUBLIC | ACC_STATIC | ACC_NATIVE,
        name: "invokeNativeClosure".to_string(),
        descriptor: "(JLjava/lang/Object;Ljava/lang/reflect/Method;[Ljava/lang/Object;)Ljava/lang/Object;".to_string(),
        code: None,
        annotations: Vec::new(),
    });

    // InvocationHandler.invoke(Object proxy, Method method, Object[] args)
    let get_declaring_class = cw
        .cp
        .add_methodref("java/lang/reflect/Method", "getDeclaringClass", "()Ljava/lang/Class;");
    let obj_cls_ldc = cw.cp.add_class("java/lang/Object");
    let get_method_name = cw
        .cp
        .add_methodref("java/lang/reflect/Method", "getName", "()Ljava/lang/String;");
    let hash_str = cw.cp.add_string("hashCode");
    let eq_str = cw.cp.add_string("equals");
    let str_eq = cw
        .cp
        .add_methodref("java/lang/String", "equals", "(Ljava/lang/Object;)Z");
    let id_hash = cw
        .cp
        .add_methodref("java/lang/System", "identityHashCode", "(Ljava/lang/Object;)I");
    let box_int = cw
        .cp
        .add_methodref("java/lang/Integer", "valueOf", "(I)Ljava/lang/Integer;");
    let box_bool = cw
        .cp
        .add_methodref("java/lang/Boolean", "valueOf", "(Z)Ljava/lang/Boolean;");
    let to_str_val = cw
        .cp
        .add_string("FabricRsDynamicProxy");
    let native_invoke = cw.cp.add_methodref(
        &this_cls,
        "invokeNativeClosure",
        "(JLjava/lang/Object;Ljava/lang/reflect/Method;[Ljava/lang/Object;)Ljava/lang/Object;",
    );

    let this_ver = VerificationType::Object(cw.cp.add_class(&this_cls));
    let obj_ver = VerificationType::Object(cw.cp.add_class("java/lang/Object"));
    let method_ver = VerificationType::Object(cw.cp.add_class("java/lang/reflect/Method"));
    let args_ver = VerificationType::Object(cw.cp.add_class("[Ljava/lang/Object;"));
    let str_ver = VerificationType::Object(cw.cp.add_class("java/lang/String"));
    let locals_frame = vec![this_ver.clone(), obj_ver.clone(), method_ver.clone(), args_ver.clone()];
    let locals_with_str = vec![this_ver, obj_ver, method_ver, args_ver, str_ver];

    let mut inv = CodeWriter::new(6, 5);
    let forward_rust_lbl = inv.new_label();
    let check_eq_lbl = inv.new_label();
    let to_str_lbl = inv.new_label();

    // if (method.getDeclaringClass() == Object.class) handle Object methods cleanly
    inv.emit_aload(2);
    inv.emit_u8(INVOKEVIRTUAL);
    inv.emit_u16(get_declaring_class);
    inv.emit_ldc(obj_cls_ldc);
    let is_obj_method_lbl = inv.new_label();
    // Compare reference equality with IF_ACMPEQ (0xA5)
    inv.emit_jump(0xA5, is_obj_method_lbl);
    inv.emit_jump(GOTO, forward_rust_lbl);

    inv.bind_label_with_frame(is_obj_method_lbl, locals_frame.clone(), Vec::new());
    inv.emit_aload(2);
    inv.emit_u8(INVOKEVIRTUAL);
    inv.emit_u16(get_method_name);
    inv.emit_astore(4);

    // "hashCode".equals(name)
    inv.emit_ldc(hash_str);
    inv.emit_aload(4);
    inv.emit_u8(INVOKEVIRTUAL);
    inv.emit_u16(str_eq);
    inv.emit_jump(IFEQ, check_eq_lbl);
    inv.emit_aload(1);
    inv.emit_u8(INVOKESTATIC);
    inv.emit_u16(id_hash);
    inv.emit_u8(INVOKESTATIC);
    inv.emit_u16(box_int);
    inv.emit_u8(ARETURN);

    // "equals".equals(name)
    inv.bind_label_with_frame(check_eq_lbl, locals_with_str.clone(), Vec::new());
    inv.emit_ldc(eq_str);
    inv.emit_aload(4);
    inv.emit_u8(INVOKEVIRTUAL);
    inv.emit_u16(str_eq);
    inv.emit_jump(IFEQ, to_str_lbl);
    inv.emit_aload(1);
    inv.emit_aload(3);
    inv.emit_u8(ICONST_0);
    inv.emit_u8(AALOAD);
    let eq_true = inv.new_label();
    let eq_done = inv.new_label();
    inv.emit_jump(0xA5, eq_true); // IF_ACMPEQ
    inv.emit_u8(ICONST_0);
    inv.emit_jump(GOTO, eq_done);
    inv.bind_label_with_frame(eq_true, locals_with_str.clone(), Vec::new());
    inv.emit_u8(ICONST_1);
    inv.bind_label_with_frame(eq_done, locals_with_str.clone(), vec![VerificationType::Integer]);
    inv.emit_u8(INVOKESTATIC);
    inv.emit_u16(box_bool);
    inv.emit_u8(ARETURN);

    // toString()
    inv.bind_label_with_frame(to_str_lbl, locals_with_str, Vec::new());
    inv.emit_ldc(to_str_val);
    inv.emit_u8(ARETURN);

    // Forward to Rust native closure
    inv.bind_label_with_frame(forward_rust_lbl, locals_frame, Vec::new());
    inv.emit_aload(0);
    inv.emit_u8(GETFIELD);
    inv.emit_u16(ptr_field);
    inv.emit_aload(1);
    inv.emit_aload(2);
    inv.emit_aload(3);
    inv.emit_u8(INVOKESTATIC);
    inv.emit_u16(native_invoke);
    inv.emit_u8(ARETURN);

    cw.add_method(MethodWriter {
        access_flags: ACC_PUBLIC,
        name: "invoke".to_string(),
        descriptor: "(Ljava/lang/Object;Ljava/lang/reflect/Method;[Ljava/lang/Object;)Ljava/lang/Object;".to_string(),
        code: Some(inv),
        annotations: Vec::new(),
    });

    cw.finish()
}