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//!
4//! [`Game`] owns the parsed metadata and binary; [`TypeView`], [`FieldView`],
5//! [`MethodView`] and [`ParameterView`] are cheap borrowed views into it.
6//!
7//! ```no_run
8//! use hao_il2cpp::Game;
9//!
10//! let game = Game::open("path/to/game")?;
11//! let player = game.find_type("PlayerController").expect("no such type");
12//! println!("{} : {:?}", player.full_name(), player.base_type_name());
13//! for field in player.fields() {
14//!     println!("    {field}"); // `float speed`, `static int count = 3`
15//! }
16//! if let Some(update) = player.find_method("Update") {
17//!     println!("Update is at {:#x?}", update.code_address());
18//! }
19//! # Ok::<(), hao_il2cpp::Error>(())
20//! ```
21
22use 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/// A Unity Il2Cpp game: its metadata and the type table from its binary.
44#[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    /// Opens a game folder: the one holding `GameAssembly.so` (or
54    /// `GameAssembly.dll`) and `<Game>_Data`.
55    ///
56    /// Fails with [`Error::NotFound`] if either file isn't there.
57    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    /// Opens a `global-metadata.dat` and its `GameAssembly` binary.
80    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    /// Reads a game from the contents of its `global-metadata.dat` and `GameAssembly`,
85    /// e.g. files uploaded to a web page.
86    pub fn from_bytes(metadata: Vec<u8>, binary_bytes: &[u8]) -> Result<Self> {
87        let metadata = Metadata::parse(metadata)?;
88        // pewter detects ELF (`GameAssembly.so`) or PE (`GameAssembly.dll`).
89        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    /// Builds a game from metadata and a binary you've already read.
100    ///
101    /// Without the binary's bytes, [`bytes_at`](Self::bytes_at) returns `None`;
102    /// use [`new_with_image`](Self::new_with_image) to keep them.
103    pub fn new(metadata: Metadata, binary: Binary) -> Self {
104        Self::new_with_image(metadata, binary, Vec::new())
105    }
106
107    /// Like [`new`](Self::new), also keeping the binary's file contents for
108    /// [`bytes_at`](Self::bytes_at).
109    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    /// The parsed `global-metadata.dat`, for what the views don't cover.
122    pub fn metadata(&self) -> &Metadata {
123        &self.metadata
124    }
125
126    /// The decoded type and code tables of `GameAssembly`.
127    pub fn binary(&self) -> &Binary {
128        &self.binary
129    }
130
131    /// Every type definition in the game.
132    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    /// Finds a type by its full name (`Namespace.Name`, `Outer/Nested`, `List`1`).
138    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    /// The assembly names in the game, e.g. `Assembly-CSharp.dll`.
146    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    /// Builds a declaration assembly for every image.
154    pub fn generate(&self) -> Result<Vec<GeneratedAssembly>> {
155        generate(&self.metadata, &self.binary)
156    }
157
158    /// Generates the declaration assemblies and writes them to `dir`, returning their paths.
159    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    /// Reads raw bytes from the game binary at a virtual address, or `None` if
180    /// it's unmapped or the game was built without the binary's bytes.
181    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    /// Looks up the native code address of a method definition, or `None` if
190    /// it has no code (abstract, generic or stripped) or `CodeRegistration`
191    /// wasn't found.
192    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/// A type definition in a [`Game`], from [`Game::types`] or [`Game::find_type`].
204#[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    /// The type's index into [`Metadata::type_definitions`].
213    pub fn index(&self) -> TypeDefinitionIndex {
214        self.index
215    }
216
217    /// The raw metadata record behind this view.
218    pub fn definition(&self) -> &'g TypeDefinition {
219        &self.game.metadata.type_definitions[self.index as usize]
220    }
221
222    /// The type's own name, e.g. `List`1`; see [`full_name`](Self::full_name)
223    /// for the qualified one.
224    pub fn name(&self) -> &'g str {
225        self.game.metadata.string(self.definition().name_index)
226    }
227
228    /// The type's namespace; empty for nested types and the global namespace.
229    pub fn namespace(&self) -> &'g str {
230        self.game.metadata.string(self.definition().namespace_index)
231    }
232
233    /// `Namespace.Name`, with `/` separating nested types.
234    pub fn full_name(&self) -> String {
235        self.game.metadata.type_full_name(self.index)
236    }
237
238    /// The assembly the type is in, e.g. `Assembly-CSharp.dll`.
239    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    /// `TypeAttributes` flags.
249    pub fn flags(&self) -> u32 {
250        self.definition().flags
251    }
252
253    /// The base type, e.g. `UnityEngine.MonoBehaviour`.
254    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    /// The type this one is nested in, if any.
260    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    /// The types nested directly in this one.
271    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    /// The fields the type declares, static and instance, in declaration order.
287    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    /// For an enum type, each member's `(name, value)`; empty otherwise. The
302    /// synthetic `value__` field is skipped.
303    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    /// The methods the type declares, including constructors (`.ctor`,
311    /// `.cctor`) and accessors.
312    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    /// The field called `name`, if the type declares one.
321    pub fn find_field(&self, name: &str) -> Option<FieldView<'g>> {
322        self.fields().find(|f| f.name() == name)
323    }
324
325    /// The first method called `name`. Use [`TypeView::methods`] to see all overloads.
326    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/// A field of a [`TypeView`]. Its `Display` is C#-like: `static int count = 3`.
338#[derive(Clone, Copy)]
339#[cfg_attr(feature = "reflect", derive(facet::Facet))]
340pub struct FieldView<'g> {
341    game: &'g Game,
342    /// The field's global index, matched against the constant-value table.
343    index: i32,
344    field: &'g FieldDefinition,
345}
346
347impl<'g> FieldView<'g> {
348    /// The field's name.
349    pub fn name(&self) -> &'g str {
350        self.game.metadata.string(self.field.name_index)
351    }
352
353    /// The field's type from the binary's type table, or `None` if its index
354    /// is out of range.
355    pub fn ty(&self) -> Option<&'g Il2CppType> {
356        self.game.binary.type_at(self.field.type_index)
357    }
358
359    /// A C#-like type name, e.g. `List<int>`.
360    pub fn type_name(&self) -> String {
361        self.game.type_name(self.field.type_index)
362    }
363
364    /// Whether the field is `static` (from its type's `FieldAttributes`).
365    pub fn is_static(&self) -> bool {
366        self.ty().is_some_and(|t| t.attrs & FIELD_STATIC != 0)
367    }
368
369    /// The field's compile-time constant, if it has one (enum members and
370    /// `const` fields). The common case is an enum member's integer value.
371    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
389/// Decodes an il2cpp default-value blob (ECMA element type `code`) into a typed
390/// [`ConstantValue`]. The blob is il2cpp's own wire layout: little-endian scalars
391/// and a length-prefixed UTF-8 string (unlike hao's UTF-16 `Constant` blob).
392fn 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/// A method of a [`TypeView`]. Its `Display` is a C#-like signature:
431/// `static string Concat(string str0, string str1)`.
432#[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/// A parameter of a [`MethodView`].
440#[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    /// The parameter's name.
449    pub fn name(&self) -> &'g str {
450        self.game.metadata.string(self.parameter.name_index)
451    }
452
453    /// The parameter's type from the binary's type table; `byref` is set for
454    /// `ref` / `out` parameters.
455    pub fn ty(&self) -> Option<&'g Il2CppType> {
456        self.game.binary.type_at(self.parameter.type_index)
457    }
458
459    /// A C#-like type name, e.g. `ref int`.
460    pub fn type_name(&self) -> String {
461        self.game.type_name(self.parameter.type_index)
462    }
463}
464
465impl<'g> MethodView<'g> {
466    /// The raw metadata record behind this view, e.g. for its token or flags.
467    pub fn definition(&self) -> &'g MethodDefinition {
468        self.method
469    }
470
471    /// The method's name, e.g. `Update` or `.ctor`.
472    pub fn name(&self) -> &'g str {
473        self.game.metadata.string(self.method.name_index)
474    }
475
476    /// Whether the method is `static` (takes no `this`).
477    pub fn is_static(&self) -> bool {
478        self.method.flags & METHOD_STATIC != 0
479    }
480
481    /// The return type from the binary's type table.
482    pub fn return_type(&self) -> Option<&'g Il2CppType> {
483        self.game.binary.type_at(self.method.return_type)
484    }
485
486    /// A C#-like return type name, e.g. `void` or `List<int>`.
487    pub fn return_type_name(&self) -> String {
488        self.game.type_name(self.method.return_type)
489    }
490
491    /// The parameters in order, not counting `this`.
492    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    /// The types of the parameters, e.g. `["string", "string"]`.
501    pub fn parameter_type_names(&self) -> Vec<String> {
502        self.parameters().map(|p| p.type_name()).collect()
503    }
504
505    /// The native code address of this method in the game binary, if known.
506    pub fn code_address(&self) -> Option<u64> {
507        self.game.method_pointer(self.method)
508    }
509}
510
511impl std::fmt::Display for MethodView<'_> {
512    /// `static string Concat(string str0, string str1)`
513    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}