1use 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
90fn 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
203pub 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
278pub 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 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 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 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.ends_with(".jar")
380 && seen_jar_names.insert(name.clone()) {
381 let mut nested = Vec::with_capacity(file.size() as usize);
382 if file.read_to_end(&mut nested).is_ok() {
383 let _ = ingest_jar_bytes(&nested, origin, classes_raw, max_major, seen_jar_names);
384 }
385 }
386 }
387 Ok(())
388}
389
390pub fn build_sdk_index_from_jars(
393 mc_version: &str,
394 fabric_loader_version: &str,
395 fabric_api_version: &str,
396 jars: &[(SourceOrigin, &Path)],
397 mappings: Option<&TinyMappings>,
398) -> Result<SdkIndex, String> {
399 let mut raw_classes = Vec::new();
400 let mut max_major = 52u16;
401 let mut seen_nested = std::collections::HashSet::new();
402
403 for (origin, path) in jars {
404 let bytes = std::fs::read(path)
405 .map_err(|e| format!("Failed to read JAR {path:?}: {e}"))?;
406 ingest_jar_bytes(&bytes, *origin, &mut raw_classes, &mut max_major, &mut seen_nested)?;
407 }
408
409 let has_unobf_item = raw_classes
411 .iter()
412 .any(|(_, c)| c.this_class == "net/minecraft/world/item/Item");
413 let has_inter_class = raw_classes
414 .iter()
415 .any(|(_, c)| c.this_class.starts_with("net/minecraft/class_"));
416 let is_obfuscated = !has_unobf_item && (has_inter_class || mappings.is_some());
417
418 let mut inter_to_named_cls: HashMap<&str, &str> = HashMap::new();
420 let mut inter_to_named_method: HashMap<(&str, &str, &str), &str> = HashMap::new();
421 let mut inter_to_named_field: HashMap<(&str, &str), &str> = HashMap::new();
422 let mut inter_to_named_cls_owned: HashMap<String, String> = HashMap::new();
423
424 if let Some(m) = mappings {
425 for cls in &m.classes {
426 if cls.names.len() >= 2 {
427 let inter = cls.names[0].as_str();
428 let named = cls.names[1].as_str();
429 inter_to_named_cls.insert(inter, named);
430 inter_to_named_cls_owned.insert(inter.to_string(), named.to_string());
431 for mm in &cls.methods {
432 if mm.names.len() >= 2 {
433 inter_to_named_method.insert((inter, mm.names[0].as_str(), mm.desc.as_str()), mm.names[1].as_str());
434 }
435 }
436 for ff in &cls.fields {
437 if ff.names.len() >= 2 {
438 inter_to_named_field.insert((inter, ff.names[0].as_str()), ff.names[1].as_str());
439 }
440 }
441 }
442 }
443 }
444
445 let mut index = SdkIndex::new(
446 mc_version,
447 fabric_loader_version,
448 fabric_api_version,
449 is_obfuscated,
450 max_major,
451 );
452
453 for (origin, parsed) in raw_classes {
454 let runtime_name = parsed.this_class.clone();
455 let named_class = if is_obfuscated {
456 inter_to_named_cls
457 .get(runtime_name.as_str())
458 .map(|s| (*s).to_string())
459 .unwrap_or_else(|| runtime_name.clone())
460 } else {
461 runtime_name.clone()
462 };
463
464 let super_name = parsed.super_class.as_ref().map(|s| {
465 if is_obfuscated {
466 inter_to_named_cls
467 .get(s.as_str())
468 .map(|n| (*n).to_string())
469 .unwrap_or_else(|| s.clone())
470 } else {
471 s.clone()
472 }
473 });
474
475 let interfaces = parsed
476 .interfaces
477 .iter()
478 .map(|iface| {
479 if is_obfuscated {
480 inter_to_named_cls
481 .get(iface.as_str())
482 .map(|n| (*n).to_string())
483 .unwrap_or_else(|| iface.clone())
484 } else {
485 iface.clone()
486 }
487 })
488 .collect();
489
490 let methods = parsed
491 .methods
492 .into_iter()
493 .map(|(flags, m_runtime, m_runtime_desc, sig)| {
494 let m_named = if is_obfuscated {
495 inter_to_named_method
496 .get(&(runtime_name.as_str(), m_runtime.as_str(), m_runtime_desc.as_str()))
497 .map(|s| (*s).to_string())
498 .unwrap_or_else(|| m_runtime.clone())
499 } else {
500 m_runtime.clone()
501 };
502 let m_named_desc = if is_obfuscated && !inter_to_named_cls_owned.is_empty() {
503 remap_descriptor(&m_runtime_desc, &inter_to_named_cls_owned)
504 } else {
505 m_runtime_desc.clone()
506 };
507 MethodEntry {
508 name: m_named,
509 runtime_name: m_runtime,
510 descriptor: m_named_desc,
511 runtime_descriptor: m_runtime_desc,
512 access_flags: flags,
513 signature: sig,
514 }
515 })
516 .collect();
517
518 let fields = parsed
519 .fields
520 .into_iter()
521 .map(|(flags, f_runtime, f_runtime_desc)| {
522 let f_named = if is_obfuscated {
523 inter_to_named_field
524 .get(&(runtime_name.as_str(), f_runtime.as_str()))
525 .map(|s| (*s).to_string())
526 .unwrap_or_else(|| f_runtime.clone())
527 } else {
528 f_runtime.clone()
529 };
530 let f_named_desc = if is_obfuscated && !inter_to_named_cls_owned.is_empty() {
531 remap_descriptor(&f_runtime_desc, &inter_to_named_cls_owned)
532 } else {
533 f_runtime_desc.clone()
534 };
535 FieldEntry {
536 name: f_named,
537 runtime_name: f_runtime,
538 descriptor: f_named_desc,
539 runtime_descriptor: f_runtime_desc,
540 access_flags: flags,
541 }
542 })
543 .collect();
544
545 index.classes.insert(
546 named_class.clone(),
547 ClassEntry {
548 name: named_class,
549 runtime_name,
550 super_name,
551 interfaces,
552 access_flags: parsed.access_flags,
553 methods,
554 fields,
555 origin,
556 },
557 );
558 }
559
560 Ok(index)
561}