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 crate::{
10    binary::{Binary, Il2CppType},
11    error::{Error, Result},
12    generate::{generate, GeneratedAssembly},
13    metadata::{
14        FieldDefinition, Metadata, MethodDefinition, ParameterDefinition, TypeDefinition,
15        TypeDefinitionIndex,
16    },
17};
18
19const FIELD_STATIC: u16 = 0x10;
20const METHOD_STATIC: u16 = 0x10;
21
22/// A Unity Il2Cpp game: its metadata and the type table from its binary.
23#[cfg_attr(feature = "reflect", derive(facet::Facet))]
24pub struct Game {
25    metadata: Metadata,
26    binary: Binary,
27    by_name: HashMap<String, TypeDefinitionIndex>,
28}
29
30impl Game {
31    /// Opens a game folder: the one holding `GameAssembly.so` and `<Game>_Data`.
32    pub fn open(dir: impl AsRef<Path>) -> Result<Self> {
33        let dir = dir.as_ref();
34        let metadata = std::fs::read_dir(dir)?
35            .filter_map(|e| {
36                e.ok()
37                    .map(|e| e.path().join("il2cpp_data/Metadata/global-metadata.dat"))
38            })
39            .find(|p| p.exists())
40            .ok_or_else(|| {
41                Error::NotFound(format!(
42                    "*_Data/il2cpp_data/Metadata/global-metadata.dat in {}",
43                    dir.display()
44                ))
45            })?;
46        let binary = ["GameAssembly.so", "GameAssembly.dll"]
47            .iter()
48            .map(|name| dir.join(name))
49            .find(|p| p.exists())
50            .ok_or_else(|| Error::NotFound(format!("GameAssembly in {}", dir.display())))?;
51        Self::from_files(metadata, binary)
52    }
53
54    /// Opens a `global-metadata.dat` and its `GameAssembly` binary.
55    pub fn from_files(metadata: impl AsRef<Path>, binary: impl AsRef<Path>) -> Result<Self> {
56        Self::from_bytes(std::fs::read(metadata)?, &std::fs::read(binary)?)
57    }
58
59    /// Reads a game from the contents of its `global-metadata.dat` and `GameAssembly`,
60    /// e.g. files uploaded to a web page.
61    pub fn from_bytes(metadata: Vec<u8>, binary: &[u8]) -> Result<Self> {
62        let metadata = Metadata::parse(metadata)?;
63        // pewter detects ELF (`GameAssembly.so`) or PE (`GameAssembly.dll`).
64        let image =
65            pewter::image::AnyImage::load(binary).map_err(|e| Error::Binary(format!("{:?}", e)))?;
66        let binary = Binary::read(&image, &metadata)?;
67        Ok(Self::new(metadata, binary))
68    }
69
70    pub fn new(metadata: Metadata, binary: Binary) -> Self {
71        let by_name = (0..metadata.type_definitions.len() as TypeDefinitionIndex)
72            .map(|i| (metadata.type_full_name(i), i))
73            .collect();
74        Self {
75            metadata,
76            binary,
77            by_name,
78        }
79    }
80
81    pub fn metadata(&self) -> &Metadata {
82        &self.metadata
83    }
84
85    pub fn binary(&self) -> &Binary {
86        &self.binary
87    }
88
89    /// Every type definition in the game.
90    pub fn types(&self) -> impl Iterator<Item = TypeView<'_>> {
91        (0..self.metadata.type_definitions.len() as TypeDefinitionIndex)
92            .map(|index| TypeView { game: self, index })
93    }
94
95    /// Finds a type by its full name (`Namespace.Name`, `Outer/Nested`, `List`1`).
96    pub fn find_type(&self, full_name: &str) -> Option<TypeView<'_>> {
97        self.by_name.get(full_name).map(|index| TypeView {
98            game: self,
99            index: *index,
100        })
101    }
102
103    /// The assembly names in the game, e.g. `Assembly-CSharp.dll`.
104    pub fn image_names(&self) -> impl Iterator<Item = &str> {
105        self.metadata
106            .images
107            .iter()
108            .map(|i| self.metadata.image_name(i))
109    }
110
111    /// Builds a declaration assembly for every image.
112    pub fn generate(&self) -> Result<Vec<GeneratedAssembly>> {
113        generate(&self.metadata, &self.binary)
114    }
115
116    /// Generates the declaration assemblies and writes them to `dir`, returning their paths.
117    pub fn write_assemblies(&self, dir: impl AsRef<Path>) -> Result<Vec<PathBuf>> {
118        let dir = dir.as_ref();
119        std::fs::create_dir_all(dir)?;
120        self.generate()?
121            .into_iter()
122            .map(|assembly| {
123                let path = dir.join(&assembly.file_name);
124                assembly.module.write_to_path(&path)?;
125                Ok(path)
126            })
127            .collect()
128    }
129
130    fn type_name(&self, index: i32) -> String {
131        self.binary
132            .type_at(index)
133            .map(|t| t.name(&self.metadata))
134            .unwrap_or_else(|| format!("<type {}>", index))
135    }
136}
137
138#[derive(Clone, Copy)]
139#[cfg_attr(feature = "reflect", derive(facet::Facet))]
140pub struct TypeView<'g> {
141    game: &'g Game,
142    index: TypeDefinitionIndex,
143}
144
145impl<'g> TypeView<'g> {
146    pub fn index(&self) -> TypeDefinitionIndex {
147        self.index
148    }
149
150    pub fn definition(&self) -> &'g TypeDefinition {
151        &self.game.metadata.type_definitions[self.index as usize]
152    }
153
154    pub fn name(&self) -> &'g str {
155        self.game.metadata.string(self.definition().name_index)
156    }
157
158    pub fn namespace(&self) -> &'g str {
159        self.game.metadata.string(self.definition().namespace_index)
160    }
161
162    /// `Namespace.Name`, with `/` separating nested types.
163    pub fn full_name(&self) -> String {
164        self.game.metadata.type_full_name(self.index)
165    }
166
167    /// The assembly the type is in, e.g. `Assembly-CSharp.dll`.
168    pub fn image_name(&self) -> &'g str {
169        let metadata = &self.game.metadata;
170        metadata
171            .images
172            .iter()
173            .find(|i| metadata.image_types(i).contains(&self.index))
174            .map_or("", |i| metadata.image_name(i))
175    }
176
177    /// `TypeAttributes` flags.
178    pub fn flags(&self) -> u32 {
179        self.definition().flags
180    }
181
182    /// The base type, e.g. `UnityEngine.MonoBehaviour`.
183    pub fn base_type_name(&self) -> Option<String> {
184        let parent = self.definition().parent_index;
185        (parent >= 0).then(|| self.game.type_name(parent))
186    }
187
188    pub fn declaring_type(&self) -> Option<TypeView<'g>> {
189        self.game
190            .metadata
191            .declaring_type_definition(self.index)
192            .map(|index| TypeView {
193                game: self.game,
194                index,
195            })
196    }
197
198    pub fn nested_types(&self) -> impl Iterator<Item = TypeView<'g>> + 'g {
199        let def = self.definition();
200        let start = def.nested_types_start.max(0) as usize;
201        let game = self.game;
202        game.metadata
203            .nested_types
204            .get(start..start + def.nested_type_count as usize)
205            .unwrap_or(&[])
206            .iter()
207            .map(move |index| TypeView {
208                game,
209                index: *index,
210            })
211    }
212
213    pub fn fields(&self) -> impl Iterator<Item = FieldView<'g>> + 'g {
214        let game = self.game;
215        game.metadata
216            .type_fields(self.definition())
217            .iter()
218            .map(move |field| FieldView { game, field })
219    }
220
221    pub fn methods(&self) -> impl Iterator<Item = MethodView<'g>> + 'g {
222        let game = self.game;
223        game.metadata
224            .type_methods(self.definition())
225            .iter()
226            .map(move |method| MethodView { game, method })
227    }
228
229    pub fn find_field(&self, name: &str) -> Option<FieldView<'g>> {
230        self.fields().find(|f| f.name() == name)
231    }
232
233    /// The first method called `name`. Use [`TypeView::methods`] to see all overloads.
234    pub fn find_method(&self, name: &str) -> Option<MethodView<'g>> {
235        self.methods().find(|m| m.name() == name)
236    }
237}
238
239impl std::fmt::Debug for TypeView<'_> {
240    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
241        write!(f, "TypeView({})", self.full_name())
242    }
243}
244
245#[derive(Clone, Copy)]
246#[cfg_attr(feature = "reflect", derive(facet::Facet))]
247pub struct FieldView<'g> {
248    game: &'g Game,
249    field: &'g FieldDefinition,
250}
251
252impl<'g> FieldView<'g> {
253    pub fn name(&self) -> &'g str {
254        self.game.metadata.string(self.field.name_index)
255    }
256
257    pub fn ty(&self) -> Option<&'g Il2CppType> {
258        self.game.binary.type_at(self.field.type_index)
259    }
260
261    /// A C#-like type name, e.g. `List<int>`.
262    pub fn type_name(&self) -> String {
263        self.game.type_name(self.field.type_index)
264    }
265
266    pub fn is_static(&self) -> bool {
267        self.ty().is_some_and(|t| t.attrs & FIELD_STATIC != 0)
268    }
269}
270
271impl std::fmt::Display for FieldView<'_> {
272    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
273        if self.is_static() {
274            write!(f, "static ")?;
275        }
276        write!(f, "{} {}", self.type_name(), self.name())
277    }
278}
279
280#[derive(Clone, Copy)]
281#[cfg_attr(feature = "reflect", derive(facet::Facet))]
282pub struct MethodView<'g> {
283    game: &'g Game,
284    method: &'g MethodDefinition,
285}
286
287#[derive(Clone, Copy)]
288#[cfg_attr(feature = "reflect", derive(facet::Facet))]
289pub struct ParameterView<'g> {
290    game: &'g Game,
291    parameter: &'g ParameterDefinition,
292}
293
294impl<'g> ParameterView<'g> {
295    pub fn name(&self) -> &'g str {
296        self.game.metadata.string(self.parameter.name_index)
297    }
298
299    pub fn ty(&self) -> Option<&'g Il2CppType> {
300        self.game.binary.type_at(self.parameter.type_index)
301    }
302
303    pub fn type_name(&self) -> String {
304        self.game.type_name(self.parameter.type_index)
305    }
306}
307
308impl<'g> MethodView<'g> {
309    pub fn definition(&self) -> &'g MethodDefinition {
310        self.method
311    }
312
313    pub fn name(&self) -> &'g str {
314        self.game.metadata.string(self.method.name_index)
315    }
316
317    pub fn is_static(&self) -> bool {
318        self.method.flags & METHOD_STATIC != 0
319    }
320
321    pub fn return_type(&self) -> Option<&'g Il2CppType> {
322        self.game.binary.type_at(self.method.return_type)
323    }
324
325    pub fn return_type_name(&self) -> String {
326        self.game.type_name(self.method.return_type)
327    }
328
329    pub fn parameters(&self) -> impl Iterator<Item = ParameterView<'g>> + 'g {
330        let game = self.game;
331        game.metadata
332            .method_parameters(self.method)
333            .iter()
334            .map(move |parameter| ParameterView { game, parameter })
335    }
336
337    /// The types of the parameters, e.g. `["string", "string"]`.
338    pub fn parameter_type_names(&self) -> Vec<String> {
339        self.parameters().map(|p| p.type_name()).collect()
340    }
341}
342
343impl std::fmt::Display for MethodView<'_> {
344    /// `static string Concat(string str0, string str1)`
345    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
346        if self.is_static() {
347            write!(f, "static ")?;
348        }
349        let params: Vec<String> = self
350            .parameters()
351            .map(|p| format!("{} {}", p.type_name(), p.name()))
352            .collect();
353        write!(
354            f,
355            "{} {}({})",
356            self.return_type_name(),
357            self.name(),
358            params.join(", ")
359        )
360    }
361}