1use std::{
23 collections::HashMap,
24 path::{Path, PathBuf},
25};
26
27use hao::dotnet::{entries::ConstantValue, signature::ElementType};
28use pewter::image::LoadedImage;
29
30use crate::{
31 binary::{Binary, Il2CppType},
32 error::{Error, Result},
33 generate::{generate, GeneratedAssembly},
34 metadata::{
35 FieldDefinition, Metadata, MethodDefinition, ParameterDefinition, TypeDefinition,
36 TypeDefinitionIndex,
37 },
38};
39
40const FIELD_STATIC: u16 = 0x10;
41const METHOD_STATIC: u16 = 0x10;
42
43#[cfg_attr(feature = "reflect", derive(facet::Facet))]
45pub struct Game {
46 metadata: Metadata,
47 binary: Binary,
48 image_bytes: Vec<u8>,
49 by_name: HashMap<String, TypeDefinitionIndex>,
50}
51
52impl Game {
53 pub fn open(dir: impl AsRef<Path>) -> Result<Self> {
58 let dir = dir.as_ref();
59 let metadata = std::fs::read_dir(dir)?
60 .filter_map(|e| {
61 e.ok()
62 .map(|e| e.path().join("il2cpp_data/Metadata/global-metadata.dat"))
63 })
64 .find(|p| p.exists())
65 .ok_or_else(|| {
66 Error::NotFound(format!(
67 "*_Data/il2cpp_data/Metadata/global-metadata.dat in {}",
68 dir.display()
69 ))
70 })?;
71 let binary = ["GameAssembly.so", "GameAssembly.dll"]
72 .iter()
73 .map(|name| dir.join(name))
74 .find(|p| p.exists())
75 .ok_or_else(|| Error::NotFound(format!("GameAssembly in {}", dir.display())))?;
76 Self::from_files(metadata, binary)
77 }
78
79 pub fn from_files(metadata: impl AsRef<Path>, binary: impl AsRef<Path>) -> Result<Self> {
81 Self::from_bytes(std::fs::read(metadata)?, &std::fs::read(binary)?)
82 }
83
84 pub fn from_bytes(metadata: Vec<u8>, binary_bytes: &[u8]) -> Result<Self> {
87 let metadata = Metadata::parse(metadata)?;
88 let image = pewter::image::AnyImage::load(binary_bytes)
90 .map_err(|e| Error::Binary(format!("{:?}", e)))?;
91 let binary = Binary::read(&image, &metadata)?;
92 Ok(Self::new_with_image(
93 metadata,
94 binary,
95 binary_bytes.to_vec(),
96 ))
97 }
98
99 pub fn new(metadata: Metadata, binary: Binary) -> Self {
104 Self::new_with_image(metadata, binary, Vec::new())
105 }
106
107 pub fn new_with_image(metadata: Metadata, binary: Binary, image_bytes: Vec<u8>) -> Self {
110 let by_name = (0..metadata.type_definitions.len() as TypeDefinitionIndex)
111 .map(|i| (metadata.type_full_name(i), i))
112 .collect();
113 Self {
114 metadata,
115 binary,
116 image_bytes,
117 by_name,
118 }
119 }
120
121 pub fn metadata(&self) -> &Metadata {
123 &self.metadata
124 }
125
126 pub fn binary(&self) -> &Binary {
128 &self.binary
129 }
130
131 pub fn types(&self) -> impl Iterator<Item = TypeView<'_>> {
133 (0..self.metadata.type_definitions.len() as TypeDefinitionIndex)
134 .map(|index| TypeView { game: self, index })
135 }
136
137 pub fn find_type(&self, full_name: &str) -> Option<TypeView<'_>> {
139 self.by_name.get(full_name).map(|index| TypeView {
140 game: self,
141 index: *index,
142 })
143 }
144
145 pub fn image_names(&self) -> impl Iterator<Item = &str> {
147 self.metadata
148 .images
149 .iter()
150 .map(|i| self.metadata.image_name(i))
151 }
152
153 pub fn generate(&self) -> Result<Vec<GeneratedAssembly>> {
155 generate(&self.metadata, &self.binary)
156 }
157
158 pub fn write_assemblies(&self, dir: impl AsRef<Path>) -> Result<Vec<PathBuf>> {
160 let dir = dir.as_ref();
161 std::fs::create_dir_all(dir)?;
162 self.generate()?
163 .into_iter()
164 .map(|assembly| {
165 let path = dir.join(&assembly.file_name);
166 assembly.module.write_to_path(&path)?;
167 Ok(path)
168 })
169 .collect()
170 }
171
172 fn type_name(&self, index: i32) -> String {
173 self.binary
174 .type_at(index)
175 .map(|t| t.name(&self.metadata))
176 .unwrap_or_else(|| format!("<type {}>", index))
177 }
178
179 pub fn bytes_at(&self, vaddr: u64, len: usize) -> Option<Vec<u8>> {
182 if self.image_bytes.is_empty() {
183 return None;
184 }
185 let image = pewter::image::AnyImage::load(&self.image_bytes).ok()?;
186 LoadedImage::bytes(&image, vaddr, len).map(|b| b.to_vec())
187 }
188
189 pub fn method_pointer(&self, method: &MethodDefinition) -> Option<u64> {
193 let image = self.metadata.images.iter().find(|img| {
194 let start = img.type_start;
195 let end = start + img.type_count as i32;
196 method.declaring_type >= start && method.declaring_type < end
197 })?;
198 let name = self.metadata.image_name(image);
199 self.binary.method_pointer(name, method.token)
200 }
201}
202
203#[derive(Clone, Copy)]
205#[cfg_attr(feature = "reflect", derive(facet::Facet))]
206pub struct TypeView<'g> {
207 game: &'g Game,
208 index: TypeDefinitionIndex,
209}
210
211impl<'g> TypeView<'g> {
212 pub fn index(&self) -> TypeDefinitionIndex {
214 self.index
215 }
216
217 pub fn definition(&self) -> &'g TypeDefinition {
219 &self.game.metadata.type_definitions[self.index as usize]
220 }
221
222 pub fn name(&self) -> &'g str {
225 self.game.metadata.string(self.definition().name_index)
226 }
227
228 pub fn namespace(&self) -> &'g str {
230 self.game.metadata.string(self.definition().namespace_index)
231 }
232
233 pub fn full_name(&self) -> String {
235 self.game.metadata.type_full_name(self.index)
236 }
237
238 pub fn image_name(&self) -> &'g str {
240 let metadata = &self.game.metadata;
241 metadata
242 .images
243 .iter()
244 .find(|i| metadata.image_types(i).contains(&self.index))
245 .map_or("", |i| metadata.image_name(i))
246 }
247
248 pub fn flags(&self) -> u32 {
250 self.definition().flags
251 }
252
253 pub fn base_type_name(&self) -> Option<String> {
255 let parent = self.definition().parent_index;
256 (parent >= 0).then(|| self.game.type_name(parent))
257 }
258
259 pub fn declaring_type(&self) -> Option<TypeView<'g>> {
261 self.game
262 .metadata
263 .declaring_type_definition(self.index)
264 .map(|index| TypeView {
265 game: self.game,
266 index,
267 })
268 }
269
270 pub fn nested_types(&self) -> impl Iterator<Item = TypeView<'g>> + 'g {
272 let def = self.definition();
273 let start = def.nested_types_start.max(0) as usize;
274 let game = self.game;
275 game.metadata
276 .nested_types
277 .get(start..start + def.nested_type_count as usize)
278 .unwrap_or(&[])
279 .iter()
280 .map(move |index| TypeView {
281 game,
282 index: *index,
283 })
284 }
285
286 pub fn fields(&self) -> impl Iterator<Item = FieldView<'g>> + 'g {
288 let game = self.game;
289 let start = self.definition().field_start;
290 game.metadata
291 .type_fields(self.definition())
292 .iter()
293 .enumerate()
294 .map(move |(i, field)| FieldView {
295 game,
296 index: start + i as i32,
297 field,
298 })
299 }
300
301 pub fn enum_values(&self) -> Vec<(&'g str, i64)> {
304 self.fields()
305 .filter(|f| f.name() != "value__")
306 .filter_map(|f| Some((f.name(), f.constant()?.as_i64()?)))
307 .collect()
308 }
309
310 pub fn methods(&self) -> impl Iterator<Item = MethodView<'g>> + 'g {
313 let game = self.game;
314 game.metadata
315 .type_methods(self.definition())
316 .iter()
317 .map(move |method| MethodView { game, method })
318 }
319
320 pub fn find_field(&self, name: &str) -> Option<FieldView<'g>> {
322 self.fields().find(|f| f.name() == name)
323 }
324
325 pub fn find_method(&self, name: &str) -> Option<MethodView<'g>> {
327 self.methods().find(|m| m.name() == name)
328 }
329}
330
331impl std::fmt::Debug for TypeView<'_> {
332 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
333 write!(f, "TypeView({})", self.full_name())
334 }
335}
336
337#[derive(Clone, Copy)]
339#[cfg_attr(feature = "reflect", derive(facet::Facet))]
340pub struct FieldView<'g> {
341 game: &'g Game,
342 index: i32,
344 field: &'g FieldDefinition,
345}
346
347impl<'g> FieldView<'g> {
348 pub fn name(&self) -> &'g str {
350 self.game.metadata.string(self.field.name_index)
351 }
352
353 pub fn ty(&self) -> Option<&'g Il2CppType> {
356 self.game.binary.type_at(self.field.type_index)
357 }
358
359 pub fn type_name(&self) -> String {
361 self.game.type_name(self.field.type_index)
362 }
363
364 pub fn is_static(&self) -> bool {
366 self.ty().is_some_and(|t| t.attrs & FIELD_STATIC != 0)
367 }
368
369 pub fn constant(&self) -> Option<ConstantValue> {
372 let value = self
373 .game
374 .metadata
375 .field_default_values
376 .iter()
377 .find(|v| v.field_index == self.index)?;
378 let code = match &self.game.binary.type_at(value.type_index)?.kind {
379 crate::binary::TypeKind::Primitive(code) => *code,
380 _ => return None,
381 };
382 decode_constant(
383 code as u8,
384 self.game.metadata.default_value_data(value.data_index),
385 )
386 }
387}
388
389fn decode_constant(code: u8, bytes: &[u8]) -> Option<ConstantValue> {
393 fn le<const N: usize>(bytes: &[u8]) -> Option<[u8; N]> {
394 bytes.get(..N)?.try_into().ok()
395 }
396 Some(match ElementType::from_repr(code)? {
397 ElementType::Boolean => ConstantValue::Bool(*bytes.first()? != 0),
398 ElementType::Char => ConstantValue::Char(u16::from_le_bytes(le(bytes)?)),
399 ElementType::I1 => ConstantValue::I1(*bytes.first()? as i8),
400 ElementType::U1 => ConstantValue::U1(*bytes.first()?),
401 ElementType::I2 => ConstantValue::I2(i16::from_le_bytes(le(bytes)?)),
402 ElementType::U2 => ConstantValue::U2(u16::from_le_bytes(le(bytes)?)),
403 ElementType::I4 => ConstantValue::I4(i32::from_le_bytes(le(bytes)?)),
404 ElementType::U4 => ConstantValue::U4(u32::from_le_bytes(le(bytes)?)),
405 ElementType::I8 => ConstantValue::I8(i64::from_le_bytes(le(bytes)?)),
406 ElementType::U8 => ConstantValue::U8(u64::from_le_bytes(le(bytes)?)),
407 ElementType::R4 => ConstantValue::R4(f32::from_le_bytes(le(bytes)?)),
408 ElementType::R8 => ConstantValue::R8(f64::from_le_bytes(le(bytes)?)),
409 ElementType::String => {
410 let len = usize::try_from(i32::from_le_bytes(le(bytes)?)).ok()?;
411 ConstantValue::String(String::from_utf8_lossy(bytes.get(4..4 + len)?).into_owned())
412 }
413 _ => return None,
414 })
415}
416
417impl std::fmt::Display for FieldView<'_> {
418 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
419 if self.is_static() {
420 write!(f, "static ")?;
421 }
422 write!(f, "{} {}", self.type_name(), self.name())?;
423 if let Some(constant) = self.constant() {
424 write!(f, " = {constant}")?;
425 }
426 Ok(())
427 }
428}
429
430#[derive(Clone, Copy)]
433#[cfg_attr(feature = "reflect", derive(facet::Facet))]
434pub struct MethodView<'g> {
435 game: &'g Game,
436 method: &'g MethodDefinition,
437}
438
439#[derive(Clone, Copy)]
441#[cfg_attr(feature = "reflect", derive(facet::Facet))]
442pub struct ParameterView<'g> {
443 game: &'g Game,
444 parameter: &'g ParameterDefinition,
445}
446
447impl<'g> ParameterView<'g> {
448 pub fn name(&self) -> &'g str {
450 self.game.metadata.string(self.parameter.name_index)
451 }
452
453 pub fn ty(&self) -> Option<&'g Il2CppType> {
456 self.game.binary.type_at(self.parameter.type_index)
457 }
458
459 pub fn type_name(&self) -> String {
461 self.game.type_name(self.parameter.type_index)
462 }
463}
464
465impl<'g> MethodView<'g> {
466 pub fn definition(&self) -> &'g MethodDefinition {
468 self.method
469 }
470
471 pub fn name(&self) -> &'g str {
473 self.game.metadata.string(self.method.name_index)
474 }
475
476 pub fn is_static(&self) -> bool {
478 self.method.flags & METHOD_STATIC != 0
479 }
480
481 pub fn return_type(&self) -> Option<&'g Il2CppType> {
483 self.game.binary.type_at(self.method.return_type)
484 }
485
486 pub fn return_type_name(&self) -> String {
488 self.game.type_name(self.method.return_type)
489 }
490
491 pub fn parameters(&self) -> impl Iterator<Item = ParameterView<'g>> + 'g {
493 let game = self.game;
494 game.metadata
495 .method_parameters(self.method)
496 .iter()
497 .map(move |parameter| ParameterView { game, parameter })
498 }
499
500 pub fn parameter_type_names(&self) -> Vec<String> {
502 self.parameters().map(|p| p.type_name()).collect()
503 }
504
505 pub fn code_address(&self) -> Option<u64> {
507 self.game.method_pointer(self.method)
508 }
509}
510
511impl std::fmt::Display for MethodView<'_> {
512 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
514 if self.is_static() {
515 write!(f, "static ")?;
516 }
517 let params: Vec<String> = self
518 .parameters()
519 .map(|p| format!("{} {}", p.type_name(), p.name()))
520 .collect();
521 write!(
522 f,
523 "{} {}({})",
524 self.return_type_name(),
525 self.name(),
526 params.join(", ")
527 )
528 }
529}