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