Skip to main content

fabric_rs_codegen/
class_reader.rs

1//! JVM classfile parser for SDK indexing and constant-pool class relocation.
2
3use std::collections::HashMap;
4use std::io::{Cursor, Read};
5use std::path::Path;
6
7use fabric_rs_core::descriptor::remap_descriptor;
8use fabric_rs_core::index::{ClassEntry, FieldEntry, MethodEntry, SdkIndex, SourceOrigin};
9use fabric_rs_core::tiny::TinyMappings;
10use zip::ZipArchive;
11
12#[allow(dead_code)]
13#[derive(Debug, Clone)]
14enum CpEntry {
15    Empty,
16    Utf8(String),
17    Integer,
18    Float,
19    Long,
20    Double,
21    Class { name_idx: u16 },
22    String { utf8_idx: u16 },
23    Fieldref,
24    Methodref,
25    InterfaceMethodref,
26    NameAndType { name_idx: u16, desc_idx: u16 },
27    MethodHandle,
28    MethodType { desc_idx: u16 },
29    Dynamic,
30    InvokeDynamic,
31    Module { name_idx: u16 },
32    Package { name_idx: u16 },
33}
34
35struct Reader<'a> {
36    data: &'a [u8],
37    pos: usize,
38}
39
40impl<'a> Reader<'a> {
41    fn new(data: &'a [u8]) -> Self {
42        Self { data, pos: 0 }
43    }
44
45    fn read_u8(&mut self) -> Result<u8, String> {
46        let b = *self
47            .data
48            .get(self.pos)
49            .ok_or_else(|| "Unexpected EOF reading u8".to_string())?;
50        self.pos += 1;
51        Ok(b)
52    }
53
54    fn read_u16(&mut self) -> Result<u16, String> {
55        let slice = self
56            .data
57            .get(self.pos..self.pos + 2)
58            .ok_or_else(|| "Unexpected EOF reading u16".to_string())?;
59        self.pos += 2;
60        Ok(u16::from_be_bytes([slice[0], slice[1]]))
61    }
62
63    fn read_u32(&mut self) -> Result<u32, String> {
64        let slice = self
65            .data
66            .get(self.pos..self.pos + 4)
67            .ok_or_else(|| "Unexpected EOF reading u32".to_string())?;
68        self.pos += 4;
69        Ok(u32::from_be_bytes([slice[0], slice[1], slice[2], slice[3]]))
70    }
71
72    fn skip(&mut self, len: usize) -> Result<(), String> {
73        if self.pos + len > self.data.len() {
74            return Err("Unexpected EOF skipping bytes".to_string());
75        }
76        self.pos += len;
77        Ok(())
78    }
79
80    fn read_bytes(&mut self, len: usize) -> Result<&'a [u8], String> {
81        let slice = self
82            .data
83            .get(self.pos..self.pos + len)
84            .ok_or_else(|| "Unexpected EOF reading bytes".to_string())?;
85        self.pos += len;
86        Ok(slice)
87    }
88}
89
90/// Decodes JVM Modified UTF-8 cleanly into a Rust `String`.
91fn decode_mutf8(bytes: &[u8]) -> String {
92    String::from_utf8_lossy(bytes).into_owned()
93}
94
95fn read_constant_pool(r: &mut Reader<'_>) -> Result<Vec<CpEntry>, String> {
96    let cp_count = r.read_u16()? as usize;
97    let mut cp = vec![CpEntry::Empty; cp_count];
98    let mut i = 1;
99    while i < cp_count {
100        let tag = r.read_u8()?;
101        let entry = match tag {
102            1 => {
103                let len = r.read_u16()? as usize;
104                let bytes = r.read_bytes(len)?;
105                CpEntry::Utf8(decode_mutf8(bytes))
106            }
107            3 => {
108                r.skip(4)?;
109                CpEntry::Integer
110            }
111            4 => {
112                r.skip(4)?;
113                CpEntry::Float
114            }
115            5 => {
116                r.skip(8)?;
117                cp[i] = CpEntry::Long;
118                i += 2;
119                continue;
120            }
121            6 => {
122                r.skip(8)?;
123                cp[i] = CpEntry::Double;
124                i += 2;
125                continue;
126            }
127            7 => CpEntry::Class {
128                name_idx: r.read_u16()?,
129            },
130            8 => CpEntry::String {
131                utf8_idx: r.read_u16()?,
132            },
133            9 => {
134                r.skip(4)?;
135                CpEntry::Fieldref
136            }
137            10 => {
138                r.skip(4)?;
139                CpEntry::Methodref
140            }
141            11 => {
142                r.skip(4)?;
143                CpEntry::InterfaceMethodref
144            }
145            12 => CpEntry::NameAndType {
146                name_idx: r.read_u16()?,
147                desc_idx: r.read_u16()?,
148            },
149            15 => {
150                r.skip(3)?;
151                CpEntry::MethodHandle
152            }
153            16 => CpEntry::MethodType {
154                desc_idx: r.read_u16()?,
155            },
156            17 => {
157                r.skip(4)?;
158                CpEntry::Dynamic
159            }
160            18 => {
161                r.skip(4)?;
162                CpEntry::InvokeDynamic
163            }
164            19 => CpEntry::Module {
165                name_idx: r.read_u16()?,
166            },
167            20 => CpEntry::Package {
168                name_idx: r.read_u16()?,
169            },
170            other => return Err(format!("Unknown JVM ConstantPool tag {other} at index {i}")),
171        };
172        cp[i] = entry;
173        i += 1;
174    }
175    Ok(cp)
176}
177
178fn cp_utf8(cp: &[CpEntry], idx: u16) -> Result<&str, String> {
179    match cp.get(idx as usize) {
180        Some(CpEntry::Utf8(s)) => Ok(s.as_str()),
181        _ => Err(format!("CP index {idx} is not Utf8")),
182    }
183}
184
185fn cp_class_name(cp: &[CpEntry], idx: u16) -> Result<String, String> {
186    match cp.get(idx as usize) {
187        Some(CpEntry::Class { name_idx }) => Ok(cp_utf8(cp, *name_idx)?.to_string()),
188        _ => Err(format!("CP index {idx} is not Class")),
189    }
190}
191
192#[derive(Debug, Clone)]
193pub struct ParsedClassFile {
194    pub major_version: u16,
195    pub access_flags: u16,
196    pub this_class: String,
197    pub super_class: Option<String>,
198    pub interfaces: Vec<String>,
199    pub methods: Vec<(u16, String, String, Option<String>)>,
200    pub fields: Vec<(u16, String, String)>,
201}
202
203/// Parses a raw JVM `.class` file into structural metadata.
204pub fn parse_class_bytes(bytes: &[u8]) -> Result<ParsedClassFile, String> {
205    let mut r = Reader::new(bytes);
206    let magic = r.read_u32()?;
207    if magic != 0xCAFEBABE {
208        return Err(format!("Invalid classfile magic 0x{magic:08X}"));
209    }
210    let _minor = r.read_u16()?;
211    let major_version = r.read_u16()?;
212    let cp = read_constant_pool(&mut r)?;
213
214    let access_flags = r.read_u16()?;
215    let this_idx = r.read_u16()?;
216    let super_idx = r.read_u16()?;
217    let this_class = cp_class_name(&cp, this_idx)?;
218    let super_class = if super_idx == 0 {
219        None
220    } else {
221        Some(cp_class_name(&cp, super_idx)?)
222    };
223
224    let ifaces_count = r.read_u16()? as usize;
225    let mut interfaces = Vec::with_capacity(ifaces_count);
226    for _ in 0..ifaces_count {
227        let iface_idx = r.read_u16()?;
228        interfaces.push(cp_class_name(&cp, iface_idx)?);
229    }
230
231    let fields_count = r.read_u16()? as usize;
232    let mut fields = Vec::with_capacity(fields_count);
233    for _ in 0..fields_count {
234        let f_flags = r.read_u16()?;
235        let f_name = cp_utf8(&cp, r.read_u16()?)?.to_string();
236        let f_desc = cp_utf8(&cp, r.read_u16()?)?.to_string();
237        let attr_count = r.read_u16()? as usize;
238        for _ in 0..attr_count {
239            let _name_idx = r.read_u16()?;
240            let len = r.read_u32()? as usize;
241            r.skip(len)?;
242        }
243        fields.push((f_flags, f_name, f_desc));
244    }
245
246    let methods_count = r.read_u16()? as usize;
247    let mut methods = Vec::with_capacity(methods_count);
248    for _ in 0..methods_count {
249        let m_flags = r.read_u16()?;
250        let m_name = cp_utf8(&cp, r.read_u16()?)?.to_string();
251        let m_desc = cp_utf8(&cp, r.read_u16()?)?.to_string();
252        let attr_count = r.read_u16()? as usize;
253        let mut signature = None;
254        for _ in 0..attr_count {
255            let attr_name = cp_utf8(&cp, r.read_u16()?)?;
256            let len = r.read_u32()? as usize;
257            if attr_name == "Signature" && len == 2 {
258                let sig_idx = r.read_u16()?;
259                signature = cp_utf8(&cp, sig_idx).ok().map(str::to_string);
260            } else {
261                r.skip(len)?;
262            }
263        }
264        methods.push((m_flags, m_name, m_desc, signature));
265    }
266
267    Ok(ParsedClassFile {
268        major_version,
269        access_flags,
270        this_class,
271        super_class,
272        interfaces,
273        methods,
274        fields,
275    })
276}
277
278/// Safely relocates internal class names and `L...;` descriptors inside a compiled `.class`
279/// by parsing the ConstantPool structure and rewriting `CONSTANT_Utf8` entries cleanly.
280pub fn relocate_class_bytes(
281    bytes: &[u8],
282    replacements: &[(&str, &str)],
283) -> Result<Vec<u8>, String> {
284    if bytes.len() < 10 {
285        return Err("Class file too short".to_string());
286    }
287    let mut r = Reader::new(bytes);
288    if r.read_u32()? != 0xCAFEBABE {
289        return Err("Invalid classfile magic".to_string());
290    }
291    let _minor = r.read_u16()?;
292    let _major = r.read_u16()?;
293    let cp_count = r.read_u16()? as usize;
294
295    let mut out = Vec::with_capacity(bytes.len() + 128);
296    // Copy magic + minor + major + cp_count
297    out.extend_from_slice(&bytes[..10]);
298
299    let mut i = 1;
300    while i < cp_count {
301        let tag = r.read_u8()?;
302        out.push(tag);
303        match tag {
304            1 => {
305                let len = r.read_u16()? as usize;
306                let raw = r.read_bytes(len)?;
307                let mut s = decode_mutf8(raw);
308                for (old, new) in replacements {
309                    if s == *old {
310                        s = (*new).to_string();
311                    } else if s.contains(old) {
312                        // Replace descriptor occurrences like `Lold;` or exact prefixes `old$`
313                        let old_desc = format!("L{old};");
314                        let new_desc = format!("L{new};");
315                        if s.contains(&old_desc) {
316                            s = s.replace(&old_desc, &new_desc);
317                        }
318                        if s.starts_with(&format!("{old}$")) {
319                            s = format!("{new}{}", &s[old.len()..]);
320                        }
321                    }
322                }
323                let encoded = s.as_bytes();
324                out.extend_from_slice(&(encoded.len() as u16).to_be_bytes());
325                out.extend_from_slice(encoded);
326            }
327            3 | 4 | 9 | 10 | 11 | 12 | 17 | 18 => {
328                let slice = r.read_bytes(4)?;
329                out.extend_from_slice(slice);
330            }
331            5 | 6 => {
332                let slice = r.read_bytes(8)?;
333                out.extend_from_slice(slice);
334                i += 2;
335                continue;
336            }
337            7 | 8 | 16 | 19 | 20 => {
338                let slice = r.read_bytes(2)?;
339                out.extend_from_slice(slice);
340            }
341            15 => {
342                let slice = r.read_bytes(3)?;
343                out.extend_from_slice(slice);
344            }
345            other => return Err(format!("Unsupported ConstantPool tag {other}")),
346        }
347        i += 1;
348    }
349
350    // Copy remaining class body verbatim
351    out.extend_from_slice(&bytes[r.pos..]);
352    Ok(out)
353}
354
355fn ingest_jar_bytes(
356    jar_bytes: &[u8],
357    origin: SourceOrigin,
358    classes_raw: &mut Vec<(SourceOrigin, ParsedClassFile)>,
359    max_major: &mut u16,
360    seen_jar_names: &mut std::collections::HashSet<String>,
361) -> Result<(), String> {
362    let mut archive = ZipArchive::new(Cursor::new(jar_bytes))
363        .map_err(|e| format!("Failed to open JAR archive: {e}"))?;
364
365    for idx in 0..archive.len() {
366        let mut file = archive
367            .by_index(idx)
368            .map_err(|e| format!("Zip entry error: {e}"))?;
369        let name = file.name().to_string();
370        if name.ends_with(".class") && !name.ends_with("module-info.class") && !name.ends_with("package-info.class") {
371            let mut buf = Vec::with_capacity(file.size() as usize);
372            if file.read_to_end(&mut buf).is_ok()
373                && let Ok(parsed) = parse_class_bytes(&buf) {
374                    if parsed.major_version > *max_major {
375                        *max_major = parsed.major_version;
376                    }
377                    classes_raw.push((origin, parsed));
378                }
379        } else if (name.starts_with("META-INF/jars/") || name.starts_with("META-INF/versions/"))
380            && name.ends_with(".jar")
381            && seen_jar_names.insert(name.clone())
382        {
383                let mut nested = Vec::with_capacity(file.size() as usize);
384                if file.read_to_end(&mut nested).is_ok() {
385                    let _ = ingest_jar_bytes(&nested, origin, classes_raw, max_major, seen_jar_names);
386                }
387            }
388    }
389    Ok(())
390}
391
392/// Builds a full `SdkIndex` from local Minecraft, Fabric Loader, Fabric API, and dependency JARs,
393/// applying `mappings` (`intermediary <-> named`) if the Minecraft JAR is obfuscated.
394pub fn build_sdk_index_from_jars(
395    mc_version: &str,
396    fabric_loader_version: &str,
397    fabric_api_version: &str,
398    jars: &[(SourceOrigin, &Path)],
399    mappings: Option<&TinyMappings>,
400) -> Result<SdkIndex, String> {
401    let mut raw_classes = Vec::new();
402    let mut max_major = 52u16;
403    let mut seen_nested = std::collections::HashSet::new();
404
405    for (origin, path) in jars {
406        let bytes = std::fs::read(path)
407            .map_err(|e| format!("Failed to read JAR {path:?}: {e}"))?;
408        ingest_jar_bytes(&bytes, *origin, &mut raw_classes, &mut max_major, &mut seen_nested)?;
409    }
410
411    // Detect whether MC jar uses obfuscated Intermediary (`class_...`) or Mojang unobfuscated names (`net/minecraft/world/item/Item`).
412    let has_unobf_item = raw_classes
413        .iter()
414        .any(|(_, c)| c.this_class == "net/minecraft/world/item/Item");
415    let has_inter_class = raw_classes
416        .iter()
417        .any(|(_, c)| c.this_class.starts_with("net/minecraft/class_"));
418    let is_obfuscated = !has_unobf_item && (has_inter_class || mappings.is_some());
419
420    // Build reverse lookup maps if mappings are provided (`runtime/intermediary -> named`)
421    let mut inter_to_named_cls: HashMap<&str, &str> = HashMap::new();
422    let mut inter_to_named_method: HashMap<(&str, &str, &str), &str> = HashMap::new();
423    let mut inter_to_named_field: HashMap<(&str, &str), &str> = HashMap::new();
424    let mut inter_to_named_cls_owned: HashMap<String, String> = HashMap::new();
425
426    if let Some(m) = mappings {
427        for cls in &m.classes {
428            if cls.names.len() >= 2 {
429                let inter = cls.names[0].as_str();
430                let named = cls.names[1].as_str();
431                inter_to_named_cls.insert(inter, named);
432                inter_to_named_cls_owned.insert(inter.to_string(), named.to_string());
433                for mm in &cls.methods {
434                    if mm.names.len() >= 2 {
435                        inter_to_named_method.insert((inter, mm.names[0].as_str(), mm.desc.as_str()), mm.names[1].as_str());
436                    }
437                }
438                for ff in &cls.fields {
439                    if ff.names.len() >= 2 {
440                        inter_to_named_field.insert((inter, ff.names[0].as_str()), ff.names[1].as_str());
441                    }
442                }
443            }
444        }
445    }
446
447    let mut index = SdkIndex::new(
448        mc_version,
449        fabric_loader_version,
450        fabric_api_version,
451        is_obfuscated,
452        max_major,
453    );
454
455    for (origin, parsed) in raw_classes {
456        let runtime_name = parsed.this_class.clone();
457        let named_class = if is_obfuscated {
458            inter_to_named_cls
459                .get(runtime_name.as_str())
460                .map(|s| (*s).to_string())
461                .unwrap_or_else(|| runtime_name.clone())
462        } else {
463            runtime_name.clone()
464        };
465
466        let super_name = parsed.super_class.as_ref().map(|s| {
467            if is_obfuscated {
468                inter_to_named_cls
469                    .get(s.as_str())
470                    .map(|n| (*n).to_string())
471                    .unwrap_or_else(|| s.clone())
472            } else {
473                s.clone()
474            }
475        });
476
477        let interfaces = parsed
478            .interfaces
479            .iter()
480            .map(|iface| {
481                if is_obfuscated {
482                    inter_to_named_cls
483                        .get(iface.as_str())
484                        .map(|n| (*n).to_string())
485                        .unwrap_or_else(|| iface.clone())
486                } else {
487                    iface.clone()
488                }
489            })
490            .collect();
491
492        let methods = parsed
493            .methods
494            .into_iter()
495            .map(|(flags, m_runtime, m_runtime_desc, sig)| {
496                let m_named = if is_obfuscated {
497                    inter_to_named_method
498                        .get(&(runtime_name.as_str(), m_runtime.as_str(), m_runtime_desc.as_str()))
499                        .map(|s| (*s).to_string())
500                        .unwrap_or_else(|| m_runtime.clone())
501                } else {
502                    m_runtime.clone()
503                };
504                let m_named_desc = if is_obfuscated && !inter_to_named_cls_owned.is_empty() {
505                    remap_descriptor(&m_runtime_desc, &inter_to_named_cls_owned)
506                } else {
507                    m_runtime_desc.clone()
508                };
509                MethodEntry {
510                    name: m_named,
511                    runtime_name: m_runtime,
512                    descriptor: m_named_desc,
513                    runtime_descriptor: m_runtime_desc,
514                    access_flags: flags,
515                    signature: sig,
516                }
517            })
518            .collect();
519
520        let fields = parsed
521            .fields
522            .into_iter()
523            .map(|(flags, f_runtime, f_runtime_desc)| {
524                let f_named = if is_obfuscated {
525                    inter_to_named_field
526                        .get(&(runtime_name.as_str(), f_runtime.as_str()))
527                        .map(|s| (*s).to_string())
528                        .unwrap_or_else(|| f_runtime.clone())
529                } else {
530                    f_runtime.clone()
531                };
532                let f_named_desc = if is_obfuscated && !inter_to_named_cls_owned.is_empty() {
533                    remap_descriptor(&f_runtime_desc, &inter_to_named_cls_owned)
534                } else {
535                    f_runtime_desc.clone()
536                };
537                FieldEntry {
538                    name: f_named,
539                    runtime_name: f_runtime,
540                    descriptor: f_named_desc,
541                    runtime_descriptor: f_runtime_desc,
542                    access_flags: flags,
543                }
544            })
545            .collect();
546
547        index.classes.insert(
548            named_class.clone(),
549            ClassEntry {
550                name: named_class,
551                runtime_name,
552                super_name,
553                interfaces,
554                access_flags: parsed.access_flags,
555                methods,
556                fields,
557                origin,
558            },
559        );
560    }
561
562    Ok(index)
563}