fabric-rs-codegen 0.3.2

Pure-Rust JVM classfile writer, JAR SDK indexer, Rust binding emitter, and Mixin/Subclass bytecode generator for FLR v2
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
//! Custom Java subclass `.class` and `SubclassTrampolines.class` bytecode generators.

use std::collections::HashMap;

use fabric_rs_core::descriptor::{remap_descriptor, MethodDescriptor};
use fabric_rs_core::index::SdkIndex;
use fabric_rs_core::metadata::SubclassMeta;

use crate::bootstrap_gen::bootstrap_class_name;
use crate::jvm_writer::access_flags::*;
use crate::jvm_writer::opcodes::*;
use crate::jvm_writer::{ClassWriter, CodeWriter, FieldWriter, MethodWriter};

pub fn subclass_trampoline_class(clean_id: &str) -> String {
    format!("dev/fabricrs/mod_{clean_id}/SubclassTrampolines")
}

pub fn resolve_subclass_internal_name(clean_id: &str, raw: &str) -> String {
    if raw.contains('/') || raw.contains('.') {
        raw.replace('.', "/")
    } else {
        format!("dev/fabricrs/mod_{clean_id}/sub/{raw}")
    }
}

/// Synthesizes `SubclassTrampolines.class` holding the `public static native` entrypoints
/// for all custom Java subclasses declared by the mod.
pub fn generate_subclass_trampolines(
    clean_id: &str,
    subclasses: &[SubclassMeta],
    java_version: u16,
) -> Result<Option<Vec<u8>>, String> {
    if subclasses.is_empty() {
        return Ok(None);
    }
    let this_cls = subclass_trampoline_class(clean_id);
    let bootstrap_cls = bootstrap_class_name(clean_id);
    let mut cw = ClassWriter::new(&this_cls, "java/lang/Object", ACC_PUBLIC | ACC_SUPER, java_version);

    let ensure_mref = cw.cp.add_methodref(&bootstrap_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(),
    });

    for sub in subclasses {
        for m in &sub.methods {
            let tail = m
                .jni_symbol
                .rsplit('_')
                .next()
                .unwrap_or(&m.jni_symbol)
                .to_string();
            // Trampoline native method name equals the exact suffix after class prefix, or `m.jni_symbol` short name
            let method_name = if let Some(rest) = m.jni_symbol.strip_prefix("trampoline:") {
                rest.to_string()
            } else {
                tail
            };
            cw.add_method(MethodWriter {
                access_flags: ACC_PUBLIC | ACC_STATIC | ACC_NATIVE,
                name: method_name,
                descriptor: "(JLjava/lang/Object;[Ljava/lang/Object;)Ljava/lang/Object;".to_string(),
                code: None,
                annotations: Vec::new(),
            });
        }
    }

    cw.finish().map(Some)
}

fn resolve_subclass_method<'a>(
    idx: &'a SdkIndex,
    super_named: &str,
    interfaces: &[String],
    name: &str,
    desc: &str,
) -> Option<(
    &'a fabric_rs_core::index::ClassEntry,
    &'a fabric_rs_core::index::MethodEntry,
)> {
    if let Some(res) = idx.resolve_method(super_named, name, Some(desc)) {
        return Some(res);
    }
    for iface in interfaces {
        let iface_named = iface.replace('.', "/");
        if let Some(res) = idx.resolve_method(&iface_named, name, Some(desc)) {
            return Some(res);
        }
    }
    None
}

/// Synthesizes a bespoke `.class` for a Rust `#[subclass]`, emitting ONLY the requested
/// constructors and overridden methods and remapping superclass/method descriptors when obfuscated.
pub fn generate_subclass_bytes(
    clean_id: &str,
    sub: &SubclassMeta,
    index: Option<&SdkIndex>,
    java_version: u16,
) -> Result<Vec<u8>, String> {
    let this_cls = resolve_subclass_internal_name(clean_id, &sub.java_class_name);
    let super_named = sub.super_class.replace('.', "/");
    let tramp_cls = subclass_trampoline_class(clean_id);
    let bootstrap_cls = bootstrap_class_name(clean_id);

    let (super_rt, is_obfuscated, class_map) = match index {
        Some(idx) => {
            let rt = idx
                .find_class(&super_named)
                .map(|c| c.runtime_name.clone())
                .unwrap_or_else(|| super_named.clone());
            let mut map = HashMap::new();
            if idx.is_obfuscated {
                for (named, entry) in &idx.classes {
                    if named != &entry.runtime_name {
                        map.insert(named.clone(), entry.runtime_name.clone());
                    }
                }
                for (modern, legacy) in [
                    (
                        "net/minecraft/world/level/block/state/BlockBehaviour$Properties",
                        "net/minecraft/world/level/block/Block$Properties",
                    ),
                    (
                        "net/minecraft/world/level/block/state/BlockBehaviour",
                        "net/minecraft/world/level/block/Block",
                    ),
                    (
                        "net/minecraft/resources/Identifier",
                        "net/minecraft/resources/ResourceLocation",
                    ),
                ] {
                    if !map.contains_key(modern)
                        && idx.find_class(modern).is_none()
                        && let Some(legacy_entry) = idx.find_class(legacy)
                    {
                        map.insert(modern.to_string(), legacy_entry.runtime_name.clone());
                    }
                }
            }
            (rt, idx.is_obfuscated, map)
        }
        None => (super_named.clone(), false, HashMap::new()),
    };

    let mut cw = ClassWriter::new(&this_cls, &super_rt, ACC_PUBLIC | ACC_SUPER, java_version);
    if let Some(sig) = &sub.signature {
        cw.set_signature(sig.clone());
    }

    for iface in &sub.interfaces {
        let iface_named = iface.replace('.', "/");
        let iface_rt = class_map.get(&iface_named).cloned().unwrap_or(iface_named);
        cw.add_interface(&iface_rt);
    }

    if sub.has_rust_handle {
        cw.add_field(FieldWriter {
            access_flags: ACC_PUBLIC,
            name: "flrHandle".to_string(),
            descriptor: "J".to_string(),
        });
    }

    // <clinit> ensures native library is loaded even if instantiated via Registry before entrypoint finishes
    let ensure_mref = cw.cp.add_methodref(&bootstrap_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(),
    });

    // Constructors
    let ctors = if sub.constructors.is_empty() {
        vec!["()V".to_string()]
    } else {
        sub.constructors.iter().map(|c| c.descriptor.clone()).collect()
    };

    for ctor_desc in ctors {
        let rt_ctor_desc = if is_obfuscated {
            remap_descriptor(&ctor_desc, &class_map)
        } else {
            ctor_desc.clone()
        };
        let parsed = MethodDescriptor::parse(&rt_ctor_desc)?;
        let super_init = cw.cp.add_methodref(&super_rt, "<init>", &rt_ctor_desc);

        // If `has_rust_handle`, add trailing `long handle` OR default `()V` constructor?
        // Provide matching signature `(args..., long flrHandle)` if `has_rust_handle` AND standard `(args...)` setting `flrHandle = 0`!
        let mut slot = 1u16;
        let mut param_slots = Vec::with_capacity(parsed.params.len());
        for p in &parsed.params {
            param_slots.push((slot, p.clone()));
            slot += p.slot_size();
        }

        let mut code = CodeWriter::new(slot + 2, slot);
        code.emit_aload(0);
        for (pslot, pty) in &param_slots {
            code.emit_load(pty, *pslot);
        }
        code.emit_u8(INVOKESPECIAL);
        code.emit_u16(super_init);
        if sub.has_rust_handle {
            let field_ref = cw.cp.add_fieldref(&this_cls, "flrHandle", "J");
            code.emit_aload(0);
            code.emit_u8(LCONST_0);
            code.emit_u8(PUTFIELD);
            code.emit_u16(field_ref);
        }
        code.emit_u8(RETURN);
        cw.add_method(MethodWriter {
            access_flags: ACC_PUBLIC,
            name: "<init>".to_string(),
            descriptor: rt_ctor_desc.clone(),
            code: Some(code),
            annotations: Vec::new(),
        });

        if sub.has_rust_handle {
            let mut handle_params = parsed.params.clone();
            handle_params.push(fabric_rs_core::descriptor::JvmType::Long);
            let handle_desc = MethodDescriptor {
                params: handle_params,
                return_type: fabric_rs_core::descriptor::JvmType::Void,
            }
            .to_descriptor();
            let handle_slot = slot;
            let field_ref = cw.cp.add_fieldref(&this_cls, "flrHandle", "J");
            let mut hcode = CodeWriter::new(slot + 2, slot + 2);
            hcode.emit_aload(0);
            for (pslot, pty) in &param_slots {
                hcode.emit_load(pty, *pslot);
            }
            hcode.emit_u8(INVOKESPECIAL);
            hcode.emit_u16(super_init);
            hcode.emit_aload(0);
            hcode.emit_load(&fabric_rs_core::descriptor::JvmType::Long, handle_slot);
            hcode.emit_u8(PUTFIELD);
            hcode.emit_u16(field_ref);
            hcode.emit_u8(RETURN);
            cw.add_method(MethodWriter {
                access_flags: ACC_PUBLIC,
                name: "<init>".to_string(),
                descriptor: handle_desc,
                code: Some(hcode),
                annotations: Vec::new(),
            });
        }
    }

    // Overridden methods (search superclass chain and implemented interfaces)
    for m in &sub.methods {
        let (rt_name, rt_desc) = if let Some(idx) = index {
            if let Some((_, found)) = resolve_subclass_method(
                idx,
                &super_named,
                &sub.interfaces,
                &m.method_name,
                &m.descriptor,
            ) {
                if is_obfuscated {
                    (found.runtime_name.clone(), found.runtime_descriptor.clone())
                } else {
                    (found.name.clone(), found.descriptor.clone())
                }
            } else if m.optional {
                continue;
            } else if is_obfuscated {
                (
                    m.method_name.clone(),
                    remap_descriptor(&m.descriptor, &class_map),
                )
            } else {
                (m.method_name.clone(), m.descriptor.clone())
            }
        } else {
            (m.method_name.clone(), m.descriptor.clone())
        };

        let parsed = MethodDescriptor::parse(&rt_desc)?;
        let mut slot = if m.is_static { 0u16 } else { 1u16 };
        let mut param_slots = Vec::with_capacity(parsed.params.len());
        for p in &parsed.params {
            param_slots.push((slot, p.clone()));
            slot += p.slot_size();
        }

        let tramp_fn = if let Some(rest) = m.jni_symbol.strip_prefix("trampoline:") {
            rest.to_string()
        } else {
            m.jni_symbol
                .rsplit('_')
                .next()
                .unwrap_or(&m.jni_symbol)
                .to_string()
        };

        let obj_cls = cw.cp.add_class("java/lang/Object");
        let tramp_mref = cw.cp.add_methodref(
            &tramp_cls,
            &tramp_fn,
            "(JLjava/lang/Object;[Ljava/lang/Object;)Ljava/lang/Object;",
        );
        let handle_field = if sub.has_rust_handle && !m.is_static {
            Some(cw.cp.add_fieldref(&this_cls, "flrHandle", "J"))
        } else {
            None
        };

        let mut code = CodeWriter::new(9, slot.max(1));
        if let Some(fref) = handle_field {
            code.emit_aload(0);
            code.emit_u8(GETFIELD);
            code.emit_u16(fref);
        } else {
            code.emit_u8(LCONST_0);
        }
        if m.is_static {
            code.emit_u8(ACONST_NULL);
        } else {
            code.emit_aload(0);
        }
        code.emit_int_const(param_slots.len() as i32);
        code.emit_u8(ANEWARRAY);
        code.emit_u16(obj_cls);
        for (idx, (pslot, pty)) in param_slots.iter().enumerate() {
            code.emit_u8(DUP);
            code.emit_int_const(idx as i32);
            code.emit_load(pty, *pslot);
            code.emit_box_if_primitive(&mut cw.cp, pty);
            code.emit_u8(AASTORE);
        }
        code.emit_u8(INVOKESTATIC);
        code.emit_u16(tramp_mref);
        code.emit_unbox_or_cast(&mut cw.cp, &parsed.return_type);
        code.emit_return(&parsed.return_type);

        let flags = if m.is_static {
            ACC_PUBLIC | ACC_STATIC
        } else {
            ACC_PUBLIC
        };
        let method_writer = MethodWriter {
            access_flags: flags,
            name: rt_name,
            descriptor: rt_desc,
            code: Some(code),
            annotations: Vec::new(),
        };
        if let Some(sig) = &m.signature {
            cw.add_method_with_signature(method_writer, sig.clone());
        } else {
            cw.add_method(method_writer);
        }
    }

    // Super-call bridges (`INVOKESPECIAL <super>.<method>`)
    for sc in &sub.super_calls {
        let (rt_name, rt_desc) = if let Some(idx) = index {
            if let Some((_, found)) =
                idx.resolve_method(&super_named, &sc.method_name, Some(&sc.descriptor))
            {
                if is_obfuscated {
                    (found.runtime_name.clone(), found.runtime_descriptor.clone())
                } else {
                    (found.name.clone(), found.descriptor.clone())
                }
            } else if is_obfuscated {
                (
                    sc.method_name.clone(),
                    remap_descriptor(&sc.descriptor, &class_map),
                )
            } else {
                (sc.method_name.clone(), sc.descriptor.clone())
            }
        } else {
            (sc.method_name.clone(), sc.descriptor.clone())
        };

        let parsed = MethodDescriptor::parse(&rt_desc)?;
        let mut slot = 1u16;
        let mut param_slots = Vec::with_capacity(parsed.params.len());
        for p in &parsed.params {
            param_slots.push((slot, p.clone()));
            slot += p.slot_size();
        }

        let super_mref = cw.cp.add_methodref(&super_rt, &rt_name, &rt_desc);
        let mut code = CodeWriter::new(slot.max(2), slot);
        code.emit_aload(0);
        for (pslot, pty) in &param_slots {
            code.emit_load(pty, *pslot);
        }
        code.emit_u8(INVOKESPECIAL);
        code.emit_u16(super_mref);
        code.emit_return(&parsed.return_type);

        cw.add_method(MethodWriter {
            access_flags: ACC_PUBLIC | ACC_FINAL,
            name: sc.bridge_name.clone(),
            descriptor: rt_desc,
            code: Some(code),
            annotations: Vec::new(),
        });
    }

    cw.finish()
}