fabric-rs-codegen 0.3.0

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
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
//! JVM classfile parser for SDK indexing and constant-pool class relocation.

use std::collections::HashMap;
use std::io::{Cursor, Read};
use std::path::Path;

use fabric_rs_core::descriptor::remap_descriptor;
use fabric_rs_core::index::{ClassEntry, FieldEntry, MethodEntry, SdkIndex, SourceOrigin};
use fabric_rs_core::tiny::TinyMappings;
use zip::ZipArchive;

#[allow(dead_code)]
#[derive(Debug, Clone)]
enum CpEntry {
    Empty,
    Utf8(String),
    Integer,
    Float,
    Long,
    Double,
    Class { name_idx: u16 },
    String { utf8_idx: u16 },
    Fieldref,
    Methodref,
    InterfaceMethodref,
    NameAndType { name_idx: u16, desc_idx: u16 },
    MethodHandle,
    MethodType { desc_idx: u16 },
    Dynamic,
    InvokeDynamic,
    Module { name_idx: u16 },
    Package { name_idx: u16 },
}

struct Reader<'a> {
    data: &'a [u8],
    pos: usize,
}

impl<'a> Reader<'a> {
    fn new(data: &'a [u8]) -> Self {
        Self { data, pos: 0 }
    }

    fn read_u8(&mut self) -> Result<u8, String> {
        let b = *self
            .data
            .get(self.pos)
            .ok_or_else(|| "Unexpected EOF reading u8".to_string())?;
        self.pos += 1;
        Ok(b)
    }

    fn read_u16(&mut self) -> Result<u16, String> {
        let slice = self
            .data
            .get(self.pos..self.pos + 2)
            .ok_or_else(|| "Unexpected EOF reading u16".to_string())?;
        self.pos += 2;
        Ok(u16::from_be_bytes([slice[0], slice[1]]))
    }

    fn read_u32(&mut self) -> Result<u32, String> {
        let slice = self
            .data
            .get(self.pos..self.pos + 4)
            .ok_or_else(|| "Unexpected EOF reading u32".to_string())?;
        self.pos += 4;
        Ok(u32::from_be_bytes([slice[0], slice[1], slice[2], slice[3]]))
    }

    fn skip(&mut self, len: usize) -> Result<(), String> {
        if self.pos + len > self.data.len() {
            return Err("Unexpected EOF skipping bytes".to_string());
        }
        self.pos += len;
        Ok(())
    }

    fn read_bytes(&mut self, len: usize) -> Result<&'a [u8], String> {
        let slice = self
            .data
            .get(self.pos..self.pos + len)
            .ok_or_else(|| "Unexpected EOF reading bytes".to_string())?;
        self.pos += len;
        Ok(slice)
    }
}

/// Decodes JVM Modified UTF-8 cleanly into a Rust `String`.
fn decode_mutf8(bytes: &[u8]) -> String {
    String::from_utf8_lossy(bytes).into_owned()
}

fn read_constant_pool(r: &mut Reader<'_>) -> Result<Vec<CpEntry>, String> {
    let cp_count = r.read_u16()? as usize;
    let mut cp = vec![CpEntry::Empty; cp_count];
    let mut i = 1;
    while i < cp_count {
        let tag = r.read_u8()?;
        let entry = match tag {
            1 => {
                let len = r.read_u16()? as usize;
                let bytes = r.read_bytes(len)?;
                CpEntry::Utf8(decode_mutf8(bytes))
            }
            3 => {
                r.skip(4)?;
                CpEntry::Integer
            }
            4 => {
                r.skip(4)?;
                CpEntry::Float
            }
            5 => {
                r.skip(8)?;
                cp[i] = CpEntry::Long;
                i += 2;
                continue;
            }
            6 => {
                r.skip(8)?;
                cp[i] = CpEntry::Double;
                i += 2;
                continue;
            }
            7 => CpEntry::Class {
                name_idx: r.read_u16()?,
            },
            8 => CpEntry::String {
                utf8_idx: r.read_u16()?,
            },
            9 => {
                r.skip(4)?;
                CpEntry::Fieldref
            }
            10 => {
                r.skip(4)?;
                CpEntry::Methodref
            }
            11 => {
                r.skip(4)?;
                CpEntry::InterfaceMethodref
            }
            12 => CpEntry::NameAndType {
                name_idx: r.read_u16()?,
                desc_idx: r.read_u16()?,
            },
            15 => {
                r.skip(3)?;
                CpEntry::MethodHandle
            }
            16 => CpEntry::MethodType {
                desc_idx: r.read_u16()?,
            },
            17 => {
                r.skip(4)?;
                CpEntry::Dynamic
            }
            18 => {
                r.skip(4)?;
                CpEntry::InvokeDynamic
            }
            19 => CpEntry::Module {
                name_idx: r.read_u16()?,
            },
            20 => CpEntry::Package {
                name_idx: r.read_u16()?,
            },
            other => return Err(format!("Unknown JVM ConstantPool tag {other} at index {i}")),
        };
        cp[i] = entry;
        i += 1;
    }
    Ok(cp)
}

fn cp_utf8(cp: &[CpEntry], idx: u16) -> Result<&str, String> {
    match cp.get(idx as usize) {
        Some(CpEntry::Utf8(s)) => Ok(s.as_str()),
        _ => Err(format!("CP index {idx} is not Utf8")),
    }
}

fn cp_class_name(cp: &[CpEntry], idx: u16) -> Result<String, String> {
    match cp.get(idx as usize) {
        Some(CpEntry::Class { name_idx }) => Ok(cp_utf8(cp, *name_idx)?.to_string()),
        _ => Err(format!("CP index {idx} is not Class")),
    }
}

#[derive(Debug, Clone)]
pub struct ParsedClassFile {
    pub major_version: u16,
    pub access_flags: u16,
    pub this_class: String,
    pub super_class: Option<String>,
    pub interfaces: Vec<String>,
    pub methods: Vec<(u16, String, String, Option<String>)>,
    pub fields: Vec<(u16, String, String)>,
}

/// Parses a raw JVM `.class` file into structural metadata.
pub fn parse_class_bytes(bytes: &[u8]) -> Result<ParsedClassFile, String> {
    let mut r = Reader::new(bytes);
    let magic = r.read_u32()?;
    if magic != 0xCAFEBABE {
        return Err(format!("Invalid classfile magic 0x{magic:08X}"));
    }
    let _minor = r.read_u16()?;
    let major_version = r.read_u16()?;
    let cp = read_constant_pool(&mut r)?;

    let access_flags = r.read_u16()?;
    let this_idx = r.read_u16()?;
    let super_idx = r.read_u16()?;
    let this_class = cp_class_name(&cp, this_idx)?;
    let super_class = if super_idx == 0 {
        None
    } else {
        Some(cp_class_name(&cp, super_idx)?)
    };

    let ifaces_count = r.read_u16()? as usize;
    let mut interfaces = Vec::with_capacity(ifaces_count);
    for _ in 0..ifaces_count {
        let iface_idx = r.read_u16()?;
        interfaces.push(cp_class_name(&cp, iface_idx)?);
    }

    let fields_count = r.read_u16()? as usize;
    let mut fields = Vec::with_capacity(fields_count);
    for _ in 0..fields_count {
        let f_flags = r.read_u16()?;
        let f_name = cp_utf8(&cp, r.read_u16()?)?.to_string();
        let f_desc = cp_utf8(&cp, r.read_u16()?)?.to_string();
        let attr_count = r.read_u16()? as usize;
        for _ in 0..attr_count {
            let _name_idx = r.read_u16()?;
            let len = r.read_u32()? as usize;
            r.skip(len)?;
        }
        fields.push((f_flags, f_name, f_desc));
    }

    let methods_count = r.read_u16()? as usize;
    let mut methods = Vec::with_capacity(methods_count);
    for _ in 0..methods_count {
        let m_flags = r.read_u16()?;
        let m_name = cp_utf8(&cp, r.read_u16()?)?.to_string();
        let m_desc = cp_utf8(&cp, r.read_u16()?)?.to_string();
        let attr_count = r.read_u16()? as usize;
        let mut signature = None;
        for _ in 0..attr_count {
            let attr_name = cp_utf8(&cp, r.read_u16()?)?;
            let len = r.read_u32()? as usize;
            if attr_name == "Signature" && len == 2 {
                let sig_idx = r.read_u16()?;
                signature = cp_utf8(&cp, sig_idx).ok().map(str::to_string);
            } else {
                r.skip(len)?;
            }
        }
        methods.push((m_flags, m_name, m_desc, signature));
    }

    Ok(ParsedClassFile {
        major_version,
        access_flags,
        this_class,
        super_class,
        interfaces,
        methods,
        fields,
    })
}

/// Safely relocates internal class names and `L...;` descriptors inside a compiled `.class`
/// by parsing the ConstantPool structure and rewriting `CONSTANT_Utf8` entries cleanly.
pub fn relocate_class_bytes(
    bytes: &[u8],
    replacements: &[(&str, &str)],
) -> Result<Vec<u8>, String> {
    if bytes.len() < 10 {
        return Err("Class file too short".to_string());
    }
    let mut r = Reader::new(bytes);
    if r.read_u32()? != 0xCAFEBABE {
        return Err("Invalid classfile magic".to_string());
    }
    let _minor = r.read_u16()?;
    let _major = r.read_u16()?;
    let cp_count = r.read_u16()? as usize;

    let mut out = Vec::with_capacity(bytes.len() + 128);
    // Copy magic + minor + major + cp_count
    out.extend_from_slice(&bytes[..10]);

    let mut i = 1;
    while i < cp_count {
        let tag = r.read_u8()?;
        out.push(tag);
        match tag {
            1 => {
                let len = r.read_u16()? as usize;
                let raw = r.read_bytes(len)?;
                let mut s = decode_mutf8(raw);
                for (old, new) in replacements {
                    if s == *old {
                        s = (*new).to_string();
                    } else if s.contains(old) {
                        // Replace descriptor occurrences like `Lold;` or exact prefixes `old$`
                        let old_desc = format!("L{old};");
                        let new_desc = format!("L{new};");
                        if s.contains(&old_desc) {
                            s = s.replace(&old_desc, &new_desc);
                        }
                        if s.starts_with(&format!("{old}$")) {
                            s = format!("{new}{}", &s[old.len()..]);
                        }
                    }
                }
                let encoded = s.as_bytes();
                out.extend_from_slice(&(encoded.len() as u16).to_be_bytes());
                out.extend_from_slice(encoded);
            }
            3 | 4 | 9 | 10 | 11 | 12 | 17 | 18 => {
                let slice = r.read_bytes(4)?;
                out.extend_from_slice(slice);
            }
            5 | 6 => {
                let slice = r.read_bytes(8)?;
                out.extend_from_slice(slice);
                i += 2;
                continue;
            }
            7 | 8 | 16 | 19 | 20 => {
                let slice = r.read_bytes(2)?;
                out.extend_from_slice(slice);
            }
            15 => {
                let slice = r.read_bytes(3)?;
                out.extend_from_slice(slice);
            }
            other => return Err(format!("Unsupported ConstantPool tag {other}")),
        }
        i += 1;
    }

    // Copy remaining class body verbatim
    out.extend_from_slice(&bytes[r.pos..]);
    Ok(out)
}

fn ingest_jar_bytes(
    jar_bytes: &[u8],
    origin: SourceOrigin,
    classes_raw: &mut Vec<(SourceOrigin, ParsedClassFile)>,
    max_major: &mut u16,
    seen_jar_names: &mut std::collections::HashSet<String>,
) -> Result<(), String> {
    let mut archive = ZipArchive::new(Cursor::new(jar_bytes))
        .map_err(|e| format!("Failed to open JAR archive: {e}"))?;

    for idx in 0..archive.len() {
        let mut file = archive
            .by_index(idx)
            .map_err(|e| format!("Zip entry error: {e}"))?;
        let name = file.name().to_string();
        if name.ends_with(".class") && !name.ends_with("module-info.class") && !name.ends_with("package-info.class") {
            let mut buf = Vec::with_capacity(file.size() as usize);
            if file.read_to_end(&mut buf).is_ok()
                && let Ok(parsed) = parse_class_bytes(&buf) {
                    if parsed.major_version > *max_major {
                        *max_major = parsed.major_version;
                    }
                    classes_raw.push((origin, parsed));
                }
        } else if name.starts_with("META-INF/jars/") && name.ends_with(".jar")
            && seen_jar_names.insert(name.clone()) {
                let mut nested = Vec::with_capacity(file.size() as usize);
                if file.read_to_end(&mut nested).is_ok() {
                    let _ = ingest_jar_bytes(&nested, origin, classes_raw, max_major, seen_jar_names);
                }
            }
    }
    Ok(())
}

/// Builds a full `SdkIndex` from local Minecraft, Fabric Loader, Fabric API, and dependency JARs,
/// applying `mappings` (`intermediary <-> named`) if the Minecraft JAR is obfuscated.
pub fn build_sdk_index_from_jars(
    mc_version: &str,
    fabric_loader_version: &str,
    fabric_api_version: &str,
    jars: &[(SourceOrigin, &Path)],
    mappings: Option<&TinyMappings>,
) -> Result<SdkIndex, String> {
    let mut raw_classes = Vec::new();
    let mut max_major = 52u16;
    let mut seen_nested = std::collections::HashSet::new();

    for (origin, path) in jars {
        let bytes = std::fs::read(path)
            .map_err(|e| format!("Failed to read JAR {path:?}: {e}"))?;
        ingest_jar_bytes(&bytes, *origin, &mut raw_classes, &mut max_major, &mut seen_nested)?;
    }

    // Detect whether MC jar uses obfuscated Intermediary (`class_...`) or Mojang unobfuscated names (`net/minecraft/world/item/Item`).
    let has_unobf_item = raw_classes
        .iter()
        .any(|(_, c)| c.this_class == "net/minecraft/world/item/Item");
    let has_inter_class = raw_classes
        .iter()
        .any(|(_, c)| c.this_class.starts_with("net/minecraft/class_"));
    let is_obfuscated = !has_unobf_item && (has_inter_class || mappings.is_some());

    // Build reverse lookup maps if mappings are provided (`runtime/intermediary -> named`)
    let mut inter_to_named_cls: HashMap<&str, &str> = HashMap::new();
    let mut inter_to_named_method: HashMap<(&str, &str, &str), &str> = HashMap::new();
    let mut inter_to_named_field: HashMap<(&str, &str), &str> = HashMap::new();
    let mut inter_to_named_cls_owned: HashMap<String, String> = HashMap::new();

    if let Some(m) = mappings {
        for cls in &m.classes {
            if cls.names.len() >= 2 {
                let inter = cls.names[0].as_str();
                let named = cls.names[1].as_str();
                inter_to_named_cls.insert(inter, named);
                inter_to_named_cls_owned.insert(inter.to_string(), named.to_string());
                for mm in &cls.methods {
                    if mm.names.len() >= 2 {
                        inter_to_named_method.insert((inter, mm.names[0].as_str(), mm.desc.as_str()), mm.names[1].as_str());
                    }
                }
                for ff in &cls.fields {
                    if ff.names.len() >= 2 {
                        inter_to_named_field.insert((inter, ff.names[0].as_str()), ff.names[1].as_str());
                    }
                }
            }
        }
    }

    let mut index = SdkIndex::new(
        mc_version,
        fabric_loader_version,
        fabric_api_version,
        is_obfuscated,
        max_major,
    );

    for (origin, parsed) in raw_classes {
        let runtime_name = parsed.this_class.clone();
        let named_class = if is_obfuscated {
            inter_to_named_cls
                .get(runtime_name.as_str())
                .map(|s| (*s).to_string())
                .unwrap_or_else(|| runtime_name.clone())
        } else {
            runtime_name.clone()
        };

        let super_name = parsed.super_class.as_ref().map(|s| {
            if is_obfuscated {
                inter_to_named_cls
                    .get(s.as_str())
                    .map(|n| (*n).to_string())
                    .unwrap_or_else(|| s.clone())
            } else {
                s.clone()
            }
        });

        let interfaces = parsed
            .interfaces
            .iter()
            .map(|iface| {
                if is_obfuscated {
                    inter_to_named_cls
                        .get(iface.as_str())
                        .map(|n| (*n).to_string())
                        .unwrap_or_else(|| iface.clone())
                } else {
                    iface.clone()
                }
            })
            .collect();

        let methods = parsed
            .methods
            .into_iter()
            .map(|(flags, m_runtime, m_runtime_desc, sig)| {
                let m_named = if is_obfuscated {
                    inter_to_named_method
                        .get(&(runtime_name.as_str(), m_runtime.as_str(), m_runtime_desc.as_str()))
                        .map(|s| (*s).to_string())
                        .unwrap_or_else(|| m_runtime.clone())
                } else {
                    m_runtime.clone()
                };
                let m_named_desc = if is_obfuscated && !inter_to_named_cls_owned.is_empty() {
                    remap_descriptor(&m_runtime_desc, &inter_to_named_cls_owned)
                } else {
                    m_runtime_desc.clone()
                };
                MethodEntry {
                    name: m_named,
                    runtime_name: m_runtime,
                    descriptor: m_named_desc,
                    runtime_descriptor: m_runtime_desc,
                    access_flags: flags,
                    signature: sig,
                }
            })
            .collect();

        let fields = parsed
            .fields
            .into_iter()
            .map(|(flags, f_runtime, f_runtime_desc)| {
                let f_named = if is_obfuscated {
                    inter_to_named_field
                        .get(&(runtime_name.as_str(), f_runtime.as_str()))
                        .map(|s| (*s).to_string())
                        .unwrap_or_else(|| f_runtime.clone())
                } else {
                    f_runtime.clone()
                };
                let f_named_desc = if is_obfuscated && !inter_to_named_cls_owned.is_empty() {
                    remap_descriptor(&f_runtime_desc, &inter_to_named_cls_owned)
                } else {
                    f_runtime_desc.clone()
                };
                FieldEntry {
                    name: f_named,
                    runtime_name: f_runtime,
                    descriptor: f_named_desc,
                    runtime_descriptor: f_runtime_desc,
                    access_flags: flags,
                }
            })
            .collect();

        index.classes.insert(
            named_class.clone(),
            ClassEntry {
                name: named_class,
                runtime_name,
                super_name,
                interfaces,
                access_flags: parsed.access_flags,
                methods,
                fields,
                origin,
            },
        );
    }

    Ok(index)
}