Skip to main content

hao_il2cpp/
binary.rs

1//! The game binary (`GameAssembly`): the registration tables and the
2//! `Il2CppType` table that metadata type indices refer to.
3//!
4//! The binary is read through pewter's [`LoadedImage`], which abstracts over
5//! ELF (`.so`) and PE (`.dll`) and resolves virtual addresses after relocation.
6//!
7//! ```no_run
8//! use hao_il2cpp::{AnyImage, Binary, Metadata};
9//!
10//! let metadata = Metadata::from_path("Game_Data/il2cpp_data/Metadata/global-metadata.dat")?;
11//! let bytes = std::fs::read("GameAssembly.so")?;
12//! let image = AnyImage::load(&bytes).expect("not an ELF or PE file");
13//! let binary = Binary::read(&image, &metadata)?;
14//!
15//! // A field's type index points into the binary's type table.
16//! let field = &metadata.fields[0];
17//! if let Some(ty) = binary.type_at(field.type_index) {
18//!     println!("{} {}", ty.name(&metadata), metadata.string(field.name_index));
19//! }
20//! # Ok::<(), hao_il2cpp::Error>(())
21//! ```
22
23pub use pewter::image::{ElfImage, LoadedImage, PeImage};
24
25use hao::dotnet::signature::{ElementType, PrimitiveType};
26
27use crate::{
28    error::{Error, Result},
29    metadata::{Metadata, TypeDefinitionIndex},
30};
31
32/// What an [`Il2CppType`] is: its element type and the data that goes with it.
33///
34/// Mirrors `Il2CppTypeEnum` plus the `data` union of IL2CPP's `Il2CppType`.
35#[derive(Debug, Clone, PartialEq)]
36#[cfg_attr(feature = "reflect", derive(facet::Facet))]
37#[cfg_attr(feature = "reflect", repr(C))]
38pub enum TypeKind {
39    /// `void`, `bool`, ..., `string`, `object`, `IntPtr`, `TypedReference`.
40    Primitive(PrimitiveType),
41    /// A reference type, by index into [`Metadata::type_definitions`].
42    Class(TypeDefinitionIndex),
43    /// A value type, by index into [`Metadata::type_definitions`].
44    ValueType(TypeDefinitionIndex),
45    /// A single-dimension, zero-based array (`T[]`).
46    SzArray(Box<Il2CppType>),
47    /// A multi-dimensional array (`T[,]`).
48    Array {
49        /// The type of each element.
50        element: Box<Il2CppType>,
51        /// The number of dimensions.
52        rank: u8,
53    },
54    /// An unmanaged pointer (`T*`).
55    Ptr(Box<Il2CppType>),
56    /// A constructed generic type, e.g. `List<int>`.
57    GenericInst {
58        /// The generic type definition, e.g. `List<T>`.
59        generic: Box<Il2CppType>,
60        /// The type arguments, in order.
61        args: Vec<Il2CppType>,
62    },
63    /// A type's generic parameter, by index into [`Metadata::generic_parameters`].
64    Var(i32),
65    /// A method's generic parameter, by index into [`Metadata::generic_parameters`].
66    MVar(i32),
67    /// A function pointer. Its signature isn't decoded.
68    FnPtr,
69    /// An element type this reader doesn't know, with its raw `Il2CppTypeEnum` value.
70    Unknown(u8),
71}
72
73/// One entry of the binary's `Il2CppType` table: the type of a field,
74/// parameter or return value, which metadata refers to by type index.
75#[derive(Debug, Clone, PartialEq)]
76#[cfg_attr(feature = "reflect", derive(facet::Facet))]
77pub struct Il2CppType {
78    /// What the type is, with its element or definition.
79    pub kind: TypeKind,
80    /// The low 16 bits of the bitfield: the owning field's or parameter's
81    /// attributes (`FieldAttributes` / `ParamAttributes`) where it has them.
82    pub attrs: u16,
83    /// Passed by reference (`ref`, `out` or `in`).
84    pub byref: bool,
85}
86
87/// `Il2CppMetadataRegistration` (v29).
88#[derive(Debug, Clone, PartialEq, Eq)]
89#[cfg_attr(feature = "reflect", derive(facet::Facet))]
90///
91/// Each table is a `(count, address)` pair, as the struct lays them out.
92pub struct MetadataRegistration {
93    /// Where the struct itself is, as a virtual address.
94    pub address: u64,
95    /// `genericClasses`: every generic type instance the game uses.
96    pub generic_classes: (u64, u64),
97    /// `genericInsts`: the type argument lists those instances share.
98    pub generic_insts: (u64, u64),
99    /// `genericMethodTable`: generic method instances and their code.
100    pub generic_method_table: (u64, u64),
101    /// `types`: the `Il2CppType` pointer table that metadata type indices refer to.
102    pub types: (u64, u64),
103    /// `methodSpecs`: generic method instances, as (method, class args, method args).
104    pub method_specs: (u64, u64),
105    /// `fieldOffsets`: per type definition, its fields' offsets in the object.
106    pub field_offsets: (u64, u64),
107    /// `typeDefinitionsSizes`: per type definition, its instance and static sizes.
108    pub type_definition_sizes: (u64, u64),
109}
110
111impl MetadataRegistration {
112    /// Finds the registration by its two counts that equal the number of type definitions
113    /// (`fieldOffsetsCount` and `typeDefinitionsSizesCount`).
114    pub fn find(image: &impl LoadedImage, metadata: &Metadata) -> Result<Self> {
115        let p = image.pointer_size();
116        let count = metadata.type_definitions.len() as u64;
117        let word = |v: u64| image.pointer(v).unwrap_or(0);
118        let pair = |v: u64| (word(v), word(v + p));
119        let mut found = Vec::new();
120        for segment in image.data_segments() {
121            let start = segment.0;
122            // Reads past the mapping just return 0, so the window needs no upper bound.
123            for vaddr in image
124                .pointer_slots(segment)
125                .filter(|v| *v >= start + 10 * p)
126            {
127                if word(vaddr) == count
128                    && word(vaddr + 2 * p) == count
129                    && image.is_mapped(word(vaddr + p))
130                    && image.is_mapped(word(vaddr + 3 * p))
131                {
132                    let base = vaddr - 10 * p;
133                    let types = pair(base + 6 * p);
134                    if types.0 >= count && image.is_mapped(types.1) {
135                        found.push(Self {
136                            address: base,
137                            generic_classes: pair(base),
138                            generic_insts: pair(base + 2 * p),
139                            generic_method_table: pair(base + 4 * p),
140                            types,
141                            method_specs: pair(base + 8 * p),
142                            field_offsets: pair(base + 10 * p),
143                            type_definition_sizes: pair(base + 12 * p),
144                        });
145                    }
146                }
147            }
148        }
149        match found.len() {
150            1 => Ok(found.remove(0)),
151            0 => Err(Error::Binary("MetadataRegistration not found".into())),
152            n => Err(Error::Binary(format!(
153                "{} candidates for MetadataRegistration",
154                n
155            ))),
156        }
157    }
158}
159
160/// Per-image method pointer table, from `Il2CppCodeGenModule`.
161#[derive(Debug, Clone)]
162#[cfg_attr(feature = "reflect", derive(facet::Facet))]
163pub struct CodeGenModule {
164    /// The image this module was generated from, e.g. `Assembly-CSharp.dll`.
165    pub name: String,
166    /// The native code address of each method, indexed by its token's RID
167    /// minus one; `0` where a method has no code (abstract, or stripped).
168    pub method_pointers: Vec<u64>,
169}
170
171/// `Il2CppCodeRegistration` — the code-side registration that holds method
172/// pointers, invoker pointers, and per-module code generation tables.
173#[derive(Debug, Clone)]
174#[cfg_attr(feature = "reflect", derive(facet::Facet))]
175pub struct CodeRegistration {
176    /// One code generation module per image.
177    pub modules: Vec<CodeGenModule>,
178}
179
180impl CodeRegistration {
181    /// Finds the code registration by locating `codeGenModules` — an array of
182    /// pointers to `Il2CppCodeGenModule` structs whose `moduleName` fields
183    /// match the image names from metadata.
184    pub fn find(image: &impl LoadedImage, metadata: &Metadata) -> Result<Self> {
185        let p = image.pointer_size();
186        let image_count = metadata.images.len() as u64;
187        let image_names: std::collections::HashSet<&str> = metadata
188            .images
189            .iter()
190            .map(|i| metadata.image_name(i))
191            .collect();
192
193        // Scan data segments for the codeGenModules array — a contiguous
194        // run of `image_count` pointers to `Il2CppCodeGenModule` structs.
195        // The array order may differ from metadata order (often alphabetical).
196        for segment in image.data_segments() {
197            let start = segment.0;
198            for vaddr in image.pointer_slots(segment).filter(|v| *v >= start) {
199                let array_ptr = match image.pointer(vaddr) {
200                    Some(a) if image.is_mapped(a) => a,
201                    _ => continue,
202                };
203                let first_module = match image.pointer(array_ptr) {
204                    Some(m) if image.is_mapped(m) => m,
205                    _ => continue,
206                };
207                let name_ptr = match image.pointer(first_module) {
208                    Some(n) if image.is_mapped(n) => n,
209                    _ => continue,
210                };
211                let name = match image.c_str(name_ptr) {
212                    Some(n) => n,
213                    None => continue,
214                };
215                if !image_names.contains(name.as_str()) {
216                    continue;
217                }
218
219                let module_ptrs = match image.pointers(array_ptr, image_count) {
220                    Some(ptrs) => ptrs,
221                    None => continue,
222                };
223
224                // Read all modules and verify every name is a known image.
225                let mut modules = Vec::with_capacity(image_count as usize);
226                let mut ok = true;
227                for module_ptr in &module_ptrs {
228                    let mp = *module_ptr;
229                    if !image.is_mapped(mp) {
230                        ok = false;
231                        break;
232                    }
233                    let mn_ptr = image.pointer(mp).unwrap_or(0);
234                    let mn = match image.c_str(mn_ptr) {
235                        Some(n) if image_names.contains(n.as_str()) => n,
236                        _ => {
237                            ok = false;
238                            break;
239                        }
240                    };
241                    // Il2CppCodeGenModule (v29):
242                    //   0:  const char* moduleName
243                    //   p:  methodPointerCount (ptr-width or i32+pad)
244                    //   2p: Il2CppMethodPointer* methodPointers
245                    let raw_count = image.pointer(mp + p).unwrap_or(0);
246                    let mp_count = if raw_count < 100_000 {
247                        raw_count
248                    } else {
249                        image.u32(mp + p).unwrap_or(0) as u64
250                    };
251                    let mp_array = image.pointer(mp + 2 * p).unwrap_or(0);
252                    let pointers = if mp_count > 0 && image.is_mapped(mp_array) {
253                        image.pointers(mp_array, mp_count).unwrap_or_default()
254                    } else {
255                        Vec::new()
256                    };
257                    modules.push(CodeGenModule {
258                        name: mn,
259                        method_pointers: pointers,
260                    });
261                }
262                if ok && modules.len() == image_count as usize {
263                    return Ok(Self { modules });
264                }
265            }
266        }
267        Err(Error::Binary("CodeRegistration not found".into()))
268    }
269}
270
271/// The game binary's type table, decoded.
272#[cfg_attr(feature = "reflect", derive(facet::Facet))]
273pub struct Binary {
274    /// Where the binary's type and generic tables are.
275    pub metadata_registration: MetadataRegistration,
276    /// The method code tables, or `None` if `CodeRegistration` wasn't found
277    /// (then [`method_pointer`](Self::method_pointer) always returns `None`).
278    pub code_registration: Option<CodeRegistration>,
279    /// The `Il2CppType` table, decoded; metadata type indices index into it.
280    pub types: Vec<Il2CppType>,
281}
282
283impl Binary {
284    /// Finds the registration structs in a loaded game binary and decodes
285    /// its type table, using `metadata` to recognise them.
286    ///
287    /// Fails if `MetadataRegistration` isn't found or a type can't be read;
288    /// a missing `CodeRegistration` only leaves
289    /// [`code_registration`](Self::code_registration) `None`.
290    pub fn read(image: &impl LoadedImage, metadata: &Metadata) -> Result<Self> {
291        let registration = MetadataRegistration::find(image, metadata)?;
292        let (count, array) = registration.types;
293        let types = image
294            .pointers(array, count)
295            .ok_or_else(|| Error::Binary("the Il2CppType pointer table is unmapped".into()))?
296            .into_iter()
297            .map(|address| read_type(image, address, 0))
298            .collect::<Result<Vec<_>>>()?;
299        let code_registration = CodeRegistration::find(image, metadata).ok();
300        Ok(Self {
301            metadata_registration: registration,
302            code_registration,
303            types,
304        })
305    }
306
307    /// The type at a metadata type index (e.g. a field's `type_index`), or
308    /// `None` if it's negative or out of range.
309    pub fn type_at(&self, index: i32) -> Option<&Il2CppType> {
310        usize::try_from(index).ok().and_then(|i| self.types.get(i))
311    }
312
313    /// Look up the native code address for a method by its image name and
314    /// token (RID = token & 0xFFFFFF, 1-based).
315    pub fn method_pointer(&self, image_name: &str, token: u32) -> Option<u64> {
316        let code = self.code_registration.as_ref()?;
317        let module = code.modules.iter().find(|m| m.name == image_name)?;
318        let rid = (token & 0x00FF_FFFF) as usize;
319        if rid == 0 {
320            return None;
321        }
322        let ptr = *module.method_pointers.get(rid - 1)?;
323        if ptr == 0 {
324            None
325        } else {
326            Some(ptr)
327        }
328    }
329}
330
331fn read_type(image: &impl LoadedImage, address: u64, depth: usize) -> Result<Il2CppType> {
332    if depth > 32 {
333        return Err(Error::Binary("type nesting is too deep".into()));
334    }
335    let p = image.pointer_size();
336    let unmapped = || Error::Binary(format!("Il2CppType at {:#x} is unmapped", address));
337    let data = image.pointer(address).ok_or_else(unmapped)?;
338    let bits = image.u32(address + p).ok_or_else(unmapped)?;
339    let attrs = (bits & 0xFFFF) as u16;
340    let element = ((bits >> 16) & 0xFF) as u8;
341    let byref = (bits >> 29) & 1 == 1;
342    let nested = |address: u64| read_type(image, address, depth + 1).map(Box::new);
343
344    let kind = match ElementType::from_repr(element) {
345        Some(ElementType::Class) => TypeKind::Class(data as i32),
346        Some(ElementType::ValueType) => TypeKind::ValueType(data as i32),
347        Some(ElementType::Var) => TypeKind::Var(data as i32),
348        Some(ElementType::MVar) => TypeKind::MVar(data as i32),
349        Some(ElementType::SzArray) => TypeKind::SzArray(nested(data)?),
350        Some(ElementType::Ptr) => TypeKind::Ptr(nested(data)?),
351        Some(ElementType::Array) => TypeKind::Array {
352            element: nested(image.pointer(data).ok_or_else(unmapped)?)?,
353            rank: image.u8(data + p).ok_or_else(unmapped)?,
354        },
355        Some(ElementType::GenericInst) => {
356            // Il2CppGenericClass { type, context { class_inst, method_inst }, cached_class }
357            let generic = nested(image.pointer(data).ok_or_else(unmapped)?)?;
358            let class_inst = image.pointer(data + p).ok_or_else(unmapped)?;
359            // Il2CppGenericInst { type_argc, type_argv }
360            let argc = image.pointer(class_inst).ok_or_else(unmapped)?;
361            let argv = image.pointer(class_inst + p).ok_or_else(unmapped)?;
362            if argc > 64 {
363                return Err(Error::Binary(format!(
364                    "generic instance at {:#x} has {} arguments",
365                    data, argc
366                )));
367            }
368            let args = (0..argc)
369                .map(|i| {
370                    let arg = image.pointer(argv + i * p).ok_or_else(unmapped)?;
371                    read_type(image, arg, depth + 1)
372                })
373                .collect::<Result<_>>()?;
374            TypeKind::GenericInst { generic, args }
375        }
376        Some(ElementType::FnPtr) => TypeKind::FnPtr,
377        _ => match PrimitiveType::from_repr(element) {
378            Some(p) => TypeKind::Primitive(p),
379            None => TypeKind::Unknown(element),
380        },
381    };
382    Ok(Il2CppType { kind, attrs, byref })
383}
384
385/// Removes the `` `N `` generic arity suffixes from every part of a type name.
386fn strip_arity(name: &str) -> String {
387    let mut out = String::with_capacity(name.len());
388    let mut chars = name.chars().peekable();
389    while let Some(c) = chars.next() {
390        if c == '`' {
391            while chars.peek().is_some_and(|d| d.is_ascii_digit()) {
392                chars.next();
393            }
394        } else {
395            out.push(c);
396        }
397    }
398    out
399}
400
401impl Il2CppType {
402    /// A C#-like name, e.g. `List<int>[]`.
403    pub fn name(&self, metadata: &Metadata) -> String {
404        let name = match &self.kind {
405            TypeKind::Primitive(p) => p.keyword().to_owned(),
406            TypeKind::Class(t) | TypeKind::ValueType(t) => metadata.type_full_name(*t),
407            TypeKind::SzArray(e) => format!("{}[]", e.name(metadata)),
408            TypeKind::Array { element, rank } => {
409                format!(
410                    "{}[{}]",
411                    element.name(metadata),
412                    ",".repeat(rank.saturating_sub(1) as usize)
413                )
414            }
415            TypeKind::Ptr(e) => format!("{}*", e.name(metadata)),
416            TypeKind::GenericInst { generic, args } => {
417                let base = strip_arity(&generic.name(metadata));
418                let args: Vec<String> = args.iter().map(|a| a.name(metadata)).collect();
419                format!("{}<{}>", base, args.join(", "))
420            }
421            TypeKind::Var(i) | TypeKind::MVar(i) => metadata
422                .generic_parameters
423                .get(*i as usize)
424                .map(|g| metadata.string(g.name_index).to_owned())
425                .unwrap_or_else(|| format!("T{}", i)),
426            TypeKind::FnPtr => "fnptr".to_owned(),
427            TypeKind::Unknown(e) => format!("<unknown {:#x}>", e),
428        };
429        if self.byref {
430            format!("ref {}", name)
431        } else {
432            name
433        }
434    }
435}