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