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