Skip to main content

hao_il2cpp/
game.rs

1//! A high level view of an Il2Cpp game: types, fields and methods by name,
2//! with their types already resolved.
3
4use std::{
5    collections::HashMap,
6    path::{Path, PathBuf},
7};
8
9use pewter::image::LoadedImage;
10
11use crate::{
12    binary::{Binary, Il2CppType},
13    error::{Error, Result},
14    generate::{generate, GeneratedAssembly},
15    metadata::{
16        FieldDefinition, Metadata, MethodDefinition, ParameterDefinition, TypeDefinition,
17        TypeDefinitionIndex,
18    },
19};
20
21const FIELD_STATIC: u16 = 0x10;
22const METHOD_STATIC: u16 = 0x10;
23
24/// A Unity Il2Cpp game: its metadata and the type table from its binary.
25#[cfg_attr(feature = "reflect", derive(facet::Facet))]
26pub struct Game {
27    metadata: Metadata,
28    binary: Binary,
29    image_bytes: Vec<u8>,
30    by_name: HashMap<String, TypeDefinitionIndex>,
31}
32
33impl Game {
34    /// Opens a game folder: the one holding `GameAssembly.so` and `<Game>_Data`.
35    pub fn open(dir: impl AsRef<Path>) -> Result<Self> {
36        let dir = dir.as_ref();
37        let metadata = std::fs::read_dir(dir)?
38            .filter_map(|e| {
39                e.ok()
40                    .map(|e| e.path().join("il2cpp_data/Metadata/global-metadata.dat"))
41            })
42            .find(|p| p.exists())
43            .ok_or_else(|| {
44                Error::NotFound(format!(
45                    "*_Data/il2cpp_data/Metadata/global-metadata.dat in {}",
46                    dir.display()
47                ))
48            })?;
49        let binary = ["GameAssembly.so", "GameAssembly.dll"]
50            .iter()
51            .map(|name| dir.join(name))
52            .find(|p| p.exists())
53            .ok_or_else(|| Error::NotFound(format!("GameAssembly in {}", dir.display())))?;
54        Self::from_files(metadata, binary)
55    }
56
57    /// Opens a `global-metadata.dat` and its `GameAssembly` binary.
58    pub fn from_files(metadata: impl AsRef<Path>, binary: impl AsRef<Path>) -> Result<Self> {
59        Self::from_bytes(std::fs::read(metadata)?, &std::fs::read(binary)?)
60    }
61
62    /// Reads a game from the contents of its `global-metadata.dat` and `GameAssembly`,
63    /// e.g. files uploaded to a web page.
64    pub fn from_bytes(metadata: Vec<u8>, binary_bytes: &[u8]) -> Result<Self> {
65        let metadata = Metadata::parse(metadata)?;
66        // pewter detects ELF (`GameAssembly.so`) or PE (`GameAssembly.dll`).
67        let image = pewter::image::AnyImage::load(binary_bytes)
68            .map_err(|e| Error::Binary(format!("{:?}", e)))?;
69        let binary = Binary::read(&image, &metadata)?;
70        Ok(Self::new_with_image(metadata, binary, binary_bytes.to_vec()))
71    }
72
73    pub fn new(metadata: Metadata, binary: Binary) -> Self {
74        Self::new_with_image(metadata, binary, Vec::new())
75    }
76
77    pub fn new_with_image(metadata: Metadata, binary: Binary, image_bytes: Vec<u8>) -> Self {
78        let by_name = (0..metadata.type_definitions.len() as TypeDefinitionIndex)
79            .map(|i| (metadata.type_full_name(i), i))
80            .collect();
81        Self {
82            metadata,
83            binary,
84            image_bytes,
85            by_name,
86        }
87    }
88
89    pub fn metadata(&self) -> &Metadata {
90        &self.metadata
91    }
92
93    pub fn binary(&self) -> &Binary {
94        &self.binary
95    }
96
97    /// Every type definition in the game.
98    pub fn types(&self) -> impl Iterator<Item = TypeView<'_>> {
99        (0..self.metadata.type_definitions.len() as TypeDefinitionIndex)
100            .map(|index| TypeView { game: self, index })
101    }
102
103    /// Finds a type by its full name (`Namespace.Name`, `Outer/Nested`, `List`1`).
104    pub fn find_type(&self, full_name: &str) -> Option<TypeView<'_>> {
105        self.by_name.get(full_name).map(|index| TypeView {
106            game: self,
107            index: *index,
108        })
109    }
110
111    /// The assembly names in the game, e.g. `Assembly-CSharp.dll`.
112    pub fn image_names(&self) -> impl Iterator<Item = &str> {
113        self.metadata
114            .images
115            .iter()
116            .map(|i| self.metadata.image_name(i))
117    }
118
119    /// Builds a declaration assembly for every image.
120    pub fn generate(&self) -> Result<Vec<GeneratedAssembly>> {
121        generate(&self.metadata, &self.binary)
122    }
123
124    /// Generates the declaration assemblies and writes them to `dir`, returning their paths.
125    pub fn write_assemblies(&self, dir: impl AsRef<Path>) -> Result<Vec<PathBuf>> {
126        let dir = dir.as_ref();
127        std::fs::create_dir_all(dir)?;
128        self.generate()?
129            .into_iter()
130            .map(|assembly| {
131                let path = dir.join(&assembly.file_name);
132                assembly.module.write_to_path(&path)?;
133                Ok(path)
134            })
135            .collect()
136    }
137
138    fn type_name(&self, index: i32) -> String {
139        self.binary
140            .type_at(index)
141            .map(|t| t.name(&self.metadata))
142            .unwrap_or_else(|| format!("<type {}>", index))
143    }
144
145    /// Read raw bytes from the game binary at a virtual address.
146    pub fn bytes_at(&self, vaddr: u64, len: usize) -> Option<Vec<u8>> {
147        if self.image_bytes.is_empty() {
148            return None;
149        }
150        let image = pewter::image::AnyImage::load(&self.image_bytes).ok()?;
151        LoadedImage::bytes(&image, vaddr, len).map(|b| b.to_vec())
152    }
153
154    /// Look up the native code address for a method definition.
155    pub fn method_pointer(&self, method: &MethodDefinition) -> Option<u64> {
156        let image = self.metadata.images.iter().find(|img| {
157            let start = img.type_start;
158            let end = start + img.type_count as i32;
159            method.declaring_type >= start && method.declaring_type < end
160        })?;
161        let name = self.metadata.image_name(image);
162        self.binary.method_pointer(name, method.token)
163    }
164}
165
166#[derive(Clone, Copy)]
167#[cfg_attr(feature = "reflect", derive(facet::Facet))]
168pub struct TypeView<'g> {
169    game: &'g Game,
170    index: TypeDefinitionIndex,
171}
172
173impl<'g> TypeView<'g> {
174    pub fn index(&self) -> TypeDefinitionIndex {
175        self.index
176    }
177
178    pub fn definition(&self) -> &'g TypeDefinition {
179        &self.game.metadata.type_definitions[self.index as usize]
180    }
181
182    pub fn name(&self) -> &'g str {
183        self.game.metadata.string(self.definition().name_index)
184    }
185
186    pub fn namespace(&self) -> &'g str {
187        self.game.metadata.string(self.definition().namespace_index)
188    }
189
190    /// `Namespace.Name`, with `/` separating nested types.
191    pub fn full_name(&self) -> String {
192        self.game.metadata.type_full_name(self.index)
193    }
194
195    /// The assembly the type is in, e.g. `Assembly-CSharp.dll`.
196    pub fn image_name(&self) -> &'g str {
197        let metadata = &self.game.metadata;
198        metadata
199            .images
200            .iter()
201            .find(|i| metadata.image_types(i).contains(&self.index))
202            .map_or("", |i| metadata.image_name(i))
203    }
204
205    /// `TypeAttributes` flags.
206    pub fn flags(&self) -> u32 {
207        self.definition().flags
208    }
209
210    /// The base type, e.g. `UnityEngine.MonoBehaviour`.
211    pub fn base_type_name(&self) -> Option<String> {
212        let parent = self.definition().parent_index;
213        (parent >= 0).then(|| self.game.type_name(parent))
214    }
215
216    pub fn declaring_type(&self) -> Option<TypeView<'g>> {
217        self.game
218            .metadata
219            .declaring_type_definition(self.index)
220            .map(|index| TypeView {
221                game: self.game,
222                index,
223            })
224    }
225
226    pub fn nested_types(&self) -> impl Iterator<Item = TypeView<'g>> + 'g {
227        let def = self.definition();
228        let start = def.nested_types_start.max(0) as usize;
229        let game = self.game;
230        game.metadata
231            .nested_types
232            .get(start..start + def.nested_type_count as usize)
233            .unwrap_or(&[])
234            .iter()
235            .map(move |index| TypeView {
236                game,
237                index: *index,
238            })
239    }
240
241    pub fn fields(&self) -> impl Iterator<Item = FieldView<'g>> + 'g {
242        let game = self.game;
243        let start = self.definition().field_start;
244        game.metadata
245            .type_fields(self.definition())
246            .iter()
247            .enumerate()
248            .map(move |(i, field)| FieldView {
249                game,
250                index: start + i as i32,
251                field,
252            })
253    }
254
255    /// For an enum type, each member's `(name, value)`; empty otherwise. The
256    /// synthetic `value__` field is skipped.
257    pub fn enum_values(&self) -> Vec<(&'g str, i64)> {
258        self.fields()
259            .filter(|f| f.name() != "value__")
260            .filter_map(|f| Some((f.name(), f.constant()?.as_i64()?)))
261            .collect()
262    }
263
264    pub fn methods(&self) -> impl Iterator<Item = MethodView<'g>> + 'g {
265        let game = self.game;
266        game.metadata
267            .type_methods(self.definition())
268            .iter()
269            .map(move |method| MethodView { game, method })
270    }
271
272    pub fn find_field(&self, name: &str) -> Option<FieldView<'g>> {
273        self.fields().find(|f| f.name() == name)
274    }
275
276    /// The first method called `name`. Use [`TypeView::methods`] to see all overloads.
277    pub fn find_method(&self, name: &str) -> Option<MethodView<'g>> {
278        self.methods().find(|m| m.name() == name)
279    }
280}
281
282impl std::fmt::Debug for TypeView<'_> {
283    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
284        write!(f, "TypeView({})", self.full_name())
285    }
286}
287
288#[derive(Clone, Copy)]
289#[cfg_attr(feature = "reflect", derive(facet::Facet))]
290pub struct FieldView<'g> {
291    game: &'g Game,
292    /// The field's global index, matched against the constant-value table.
293    index: i32,
294    field: &'g FieldDefinition,
295}
296
297impl<'g> FieldView<'g> {
298    pub fn name(&self) -> &'g str {
299        self.game.metadata.string(self.field.name_index)
300    }
301
302    pub fn ty(&self) -> Option<&'g Il2CppType> {
303        self.game.binary.type_at(self.field.type_index)
304    }
305
306    /// A C#-like type name, e.g. `List<int>`.
307    pub fn type_name(&self) -> String {
308        self.game.type_name(self.field.type_index)
309    }
310
311    pub fn is_static(&self) -> bool {
312        self.ty().is_some_and(|t| t.attrs & FIELD_STATIC != 0)
313    }
314
315    /// The field's compile-time constant, if it has one (enum members and
316    /// `const` fields). The common case is an enum member's integer value.
317    pub fn constant(&self) -> Option<ConstValue> {
318        let value = self
319            .game
320            .metadata
321            .field_default_values
322            .iter()
323            .find(|v| v.field_index == self.index)?;
324        let code = match &self.game.binary.type_at(value.type_index)?.kind {
325            crate::binary::TypeKind::Primitive(code) => *code,
326            _ => return None,
327        };
328        ConstValue::decode(code, self.game.metadata.default_value_data(value.data_index))
329    }
330}
331
332/// A field's compile-time constant value (an enum member or a `const`).
333#[derive(Debug, Clone, PartialEq)]
334pub enum ConstValue {
335    Bool(bool),
336    Char(u16),
337    I8(i8),
338    U8(u8),
339    I16(i16),
340    U16(u16),
341    I32(i32),
342    U32(u32),
343    I64(i64),
344    U64(u64),
345    F32(f32),
346    F64(f64),
347    String(String),
348}
349
350impl ConstValue {
351    /// Decodes a constant of ECMA element type `code` from the front of `bytes`.
352    fn decode(code: u8, bytes: &[u8]) -> Option<Self> {
353        use crate::binary::element::*;
354        fn le<const N: usize>(bytes: &[u8]) -> Option<[u8; N]> {
355            bytes.get(..N)?.try_into().ok()
356        }
357        Some(match code {
358            BOOLEAN => Self::Bool(*bytes.first()? != 0),
359            CHAR => Self::Char(u16::from_le_bytes(le(bytes)?)),
360            I1 => Self::I8(*bytes.first()? as i8),
361            U1 => Self::U8(*bytes.first()?),
362            I2 => Self::I16(i16::from_le_bytes(le(bytes)?)),
363            U2 => Self::U16(u16::from_le_bytes(le(bytes)?)),
364            I4 => Self::I32(i32::from_le_bytes(le(bytes)?)),
365            U4 => Self::U32(u32::from_le_bytes(le(bytes)?)),
366            I8 => Self::I64(i64::from_le_bytes(le(bytes)?)),
367            U8 => Self::U64(u64::from_le_bytes(le(bytes)?)),
368            R4 => Self::F32(f32::from_le_bytes(le(bytes)?)),
369            R8 => Self::F64(f64::from_le_bytes(le(bytes)?)),
370            STRING => {
371                let len = usize::try_from(i32::from_le_bytes(le(bytes)?)).ok()?;
372                Self::String(String::from_utf8_lossy(bytes.get(4..4 + len)?).into_owned())
373            }
374            _ => return None,
375        })
376    }
377
378    /// The value as a signed integer, for bool/char/integer constants.
379    pub fn as_i64(&self) -> Option<i64> {
380        Some(match self {
381            Self::Bool(b) => *b as i64,
382            Self::Char(c) => *c as i64,
383            Self::I8(v) => *v as i64,
384            Self::U8(v) => *v as i64,
385            Self::I16(v) => *v as i64,
386            Self::U16(v) => *v as i64,
387            Self::I32(v) => *v as i64,
388            Self::U32(v) => *v as i64,
389            Self::I64(v) => *v,
390            Self::U64(v) => *v as i64,
391            _ => return None,
392        })
393    }
394}
395
396impl std::fmt::Display for ConstValue {
397    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
398        match self {
399            Self::Bool(v) => write!(f, "{v}"),
400            Self::Char(v) => write!(f, "{v}"),
401            Self::I8(v) => write!(f, "{v}"),
402            Self::U8(v) => write!(f, "{v}"),
403            Self::I16(v) => write!(f, "{v}"),
404            Self::U16(v) => write!(f, "{v}"),
405            Self::I32(v) => write!(f, "{v}"),
406            Self::U32(v) => write!(f, "{v}"),
407            Self::I64(v) => write!(f, "{v}"),
408            Self::U64(v) => write!(f, "{v}"),
409            Self::F32(v) => write!(f, "{v}"),
410            Self::F64(v) => write!(f, "{v}"),
411            Self::String(v) => write!(f, "{v:?}"),
412        }
413    }
414}
415
416impl std::fmt::Display for FieldView<'_> {
417    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
418        if self.is_static() {
419            write!(f, "static ")?;
420        }
421        write!(f, "{} {}", self.type_name(), self.name())?;
422        if let Some(constant) = self.constant() {
423            write!(f, " = {constant}")?;
424        }
425        Ok(())
426    }
427}
428
429#[derive(Clone, Copy)]
430#[cfg_attr(feature = "reflect", derive(facet::Facet))]
431pub struct MethodView<'g> {
432    game: &'g Game,
433    method: &'g MethodDefinition,
434}
435
436#[derive(Clone, Copy)]
437#[cfg_attr(feature = "reflect", derive(facet::Facet))]
438pub struct ParameterView<'g> {
439    game: &'g Game,
440    parameter: &'g ParameterDefinition,
441}
442
443impl<'g> ParameterView<'g> {
444    pub fn name(&self) -> &'g str {
445        self.game.metadata.string(self.parameter.name_index)
446    }
447
448    pub fn ty(&self) -> Option<&'g Il2CppType> {
449        self.game.binary.type_at(self.parameter.type_index)
450    }
451
452    pub fn type_name(&self) -> String {
453        self.game.type_name(self.parameter.type_index)
454    }
455}
456
457impl<'g> MethodView<'g> {
458    pub fn definition(&self) -> &'g MethodDefinition {
459        self.method
460    }
461
462    pub fn name(&self) -> &'g str {
463        self.game.metadata.string(self.method.name_index)
464    }
465
466    pub fn is_static(&self) -> bool {
467        self.method.flags & METHOD_STATIC != 0
468    }
469
470    pub fn return_type(&self) -> Option<&'g Il2CppType> {
471        self.game.binary.type_at(self.method.return_type)
472    }
473
474    pub fn return_type_name(&self) -> String {
475        self.game.type_name(self.method.return_type)
476    }
477
478    pub fn parameters(&self) -> impl Iterator<Item = ParameterView<'g>> + 'g {
479        let game = self.game;
480        game.metadata
481            .method_parameters(self.method)
482            .iter()
483            .map(move |parameter| ParameterView { game, parameter })
484    }
485
486    /// The types of the parameters, e.g. `["string", "string"]`.
487    pub fn parameter_type_names(&self) -> Vec<String> {
488        self.parameters().map(|p| p.type_name()).collect()
489    }
490
491    /// The native code address of this method in the game binary, if known.
492    pub fn code_address(&self) -> Option<u64> {
493        self.game.method_pointer(self.method)
494    }
495}
496
497impl std::fmt::Display for MethodView<'_> {
498    /// `static string Concat(string str0, string str1)`
499    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
500        if self.is_static() {
501            write!(f, "static ")?;
502        }
503        let params: Vec<String> = self
504            .parameters()
505            .map(|p| format!("{} {}", p.type_name(), p.name()))
506            .collect();
507        write!(
508            f,
509            "{} {}({})",
510            self.return_type_name(),
511            self.name(),
512            params.join(", ")
513        )
514    }
515}