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
7pub use pewter::image::{ElfImage, LoadedImage, PeImage};
8
9use crate::{
10    error::{Error, Result},
11    metadata::{Metadata, TypeDefinitionIndex},
12};
13
14/// `Il2CppTypeEnum`, the same values as ECMA-335 element types.
15pub mod element {
16    pub const VOID: u8 = 0x01;
17    pub const BOOLEAN: u8 = 0x02;
18    pub const CHAR: u8 = 0x03;
19    pub const I1: u8 = 0x04;
20    pub const U1: u8 = 0x05;
21    pub const I2: u8 = 0x06;
22    pub const U2: u8 = 0x07;
23    pub const I4: u8 = 0x08;
24    pub const U4: u8 = 0x09;
25    pub const I8: u8 = 0x0A;
26    pub const U8: u8 = 0x0B;
27    pub const R4: u8 = 0x0C;
28    pub const R8: u8 = 0x0D;
29    pub const STRING: u8 = 0x0E;
30    pub const PTR: u8 = 0x0F;
31    pub const BYREF: u8 = 0x10;
32    pub const VALUETYPE: u8 = 0x11;
33    pub const CLASS: u8 = 0x12;
34    pub const VAR: u8 = 0x13;
35    pub const ARRAY: u8 = 0x14;
36    pub const GENERICINST: u8 = 0x15;
37    pub const TYPEDBYREF: u8 = 0x16;
38    pub const FNPTR: u8 = 0x1B;
39    pub const OBJECT: u8 = 0x1C;
40    pub const SZARRAY: u8 = 0x1D;
41    pub const MVAR: u8 = 0x1E;
42}
43
44#[derive(Debug, Clone, PartialEq)]
45#[cfg_attr(feature = "reflect", derive(facet::Facet))]
46#[cfg_attr(feature = "reflect", repr(C))]
47pub enum TypeKind {
48    /// `void`, `bool`, ..., `string`, `object`, `IntPtr`, `TypedReference`.
49    Primitive(u8),
50    Class(TypeDefinitionIndex),
51    ValueType(TypeDefinitionIndex),
52    SzArray(Box<Il2CppType>),
53    Array {
54        element: Box<Il2CppType>,
55        rank: u8,
56    },
57    Ptr(Box<Il2CppType>),
58    GenericInst {
59        generic: Box<Il2CppType>,
60        args: Vec<Il2CppType>,
61    },
62    /// Index into [`Metadata::generic_parameters`].
63    Var(i32),
64    MVar(i32),
65    FnPtr,
66    Unknown(u8),
67}
68
69#[derive(Debug, Clone, PartialEq)]
70#[cfg_attr(feature = "reflect", derive(facet::Facet))]
71pub struct Il2CppType {
72    pub kind: TypeKind,
73    pub attrs: u16,
74    pub byref: bool,
75}
76
77/// `Il2CppMetadataRegistration` (v29).
78#[derive(Debug, Clone, PartialEq, Eq)]
79#[cfg_attr(feature = "reflect", derive(facet::Facet))]
80pub struct MetadataRegistration {
81    pub address: u64,
82    pub generic_classes: (u64, u64),
83    pub generic_insts: (u64, u64),
84    pub generic_method_table: (u64, u64),
85    pub types: (u64, u64),
86    pub method_specs: (u64, u64),
87    pub field_offsets: (u64, u64),
88    pub type_definition_sizes: (u64, u64),
89}
90
91impl MetadataRegistration {
92    /// Finds the registration by its two counts that equal the number of type definitions
93    /// (`fieldOffsetsCount` and `typeDefinitionsSizesCount`).
94    pub fn find(image: &impl LoadedImage, metadata: &Metadata) -> Result<Self> {
95        let p = image.pointer_size();
96        let count = metadata.type_definitions.len() as u64;
97        let word = |v: u64| image.pointer(v).unwrap_or(0);
98        let pair = |v: u64| (word(v), word(v + p));
99        let mut found = Vec::new();
100        for segment in image.data_segments() {
101            let start = segment.0;
102            // Reads past the mapping just return 0, so the window needs no upper bound.
103            for vaddr in image
104                .pointer_slots(segment)
105                .filter(|v| *v >= start + 10 * p)
106            {
107                if word(vaddr) == count
108                    && word(vaddr + 2 * p) == count
109                    && image.is_mapped(word(vaddr + p))
110                    && image.is_mapped(word(vaddr + 3 * p))
111                {
112                    let base = vaddr - 10 * p;
113                    let types = pair(base + 6 * p);
114                    if types.0 >= count && image.is_mapped(types.1) {
115                        found.push(Self {
116                            address: base,
117                            generic_classes: pair(base),
118                            generic_insts: pair(base + 2 * p),
119                            generic_method_table: pair(base + 4 * p),
120                            types,
121                            method_specs: pair(base + 8 * p),
122                            field_offsets: pair(base + 10 * p),
123                            type_definition_sizes: pair(base + 12 * p),
124                        });
125                    }
126                }
127            }
128        }
129        match found.len() {
130            1 => Ok(found.remove(0)),
131            0 => Err(Error::Binary("MetadataRegistration not found".into())),
132            n => Err(Error::Binary(format!(
133                "{} candidates for MetadataRegistration",
134                n
135            ))),
136        }
137    }
138}
139
140/// Per-image method pointer table, from `Il2CppCodeGenModule`.
141#[derive(Debug, Clone)]
142#[cfg_attr(feature = "reflect", derive(facet::Facet))]
143pub struct CodeGenModule {
144    pub name: String,
145    pub method_pointers: Vec<u64>,
146}
147
148/// `Il2CppCodeRegistration` — the code-side registration that holds method
149/// pointers, invoker pointers, and per-module code generation tables.
150#[derive(Debug, Clone)]
151#[cfg_attr(feature = "reflect", derive(facet::Facet))]
152pub struct CodeRegistration {
153    pub modules: Vec<CodeGenModule>,
154}
155
156impl CodeRegistration {
157    /// Finds the code registration by locating `codeGenModules` — an array of
158    /// pointers to `Il2CppCodeGenModule` structs whose `moduleName` fields
159    /// match the image names from metadata.
160    pub fn find(image: &impl LoadedImage, metadata: &Metadata) -> Result<Self> {
161        let p = image.pointer_size();
162        let image_count = metadata.images.len() as u64;
163        let image_names: std::collections::HashSet<&str> = metadata
164            .images
165            .iter()
166            .map(|i| metadata.image_name(i))
167            .collect();
168
169        // Scan data segments for the codeGenModules array — a contiguous
170        // run of `image_count` pointers to `Il2CppCodeGenModule` structs.
171        // The array order may differ from metadata order (often alphabetical).
172        for segment in image.data_segments() {
173            let start = segment.0;
174            for vaddr in image.pointer_slots(segment).filter(|v| *v >= start) {
175                let array_ptr = match image.pointer(vaddr) {
176                    Some(a) if image.is_mapped(a) => a,
177                    _ => continue,
178                };
179                let first_module = match image.pointer(array_ptr) {
180                    Some(m) if image.is_mapped(m) => m,
181                    _ => continue,
182                };
183                let name_ptr = match image.pointer(first_module) {
184                    Some(n) if image.is_mapped(n) => n,
185                    _ => continue,
186                };
187                let name = match image.c_str(name_ptr) {
188                    Some(n) => n,
189                    None => continue,
190                };
191                if !image_names.contains(name.as_str()) {
192                    continue;
193                }
194
195                let module_ptrs = match image.pointers(array_ptr, image_count) {
196                    Some(ptrs) => ptrs,
197                    None => continue,
198                };
199
200                // Read all modules and verify every name is a known image.
201                let mut modules = Vec::with_capacity(image_count as usize);
202                let mut ok = true;
203                for module_ptr in &module_ptrs {
204                    let mp = *module_ptr;
205                    if !image.is_mapped(mp) {
206                        ok = false;
207                        break;
208                    }
209                    let mn_ptr = image.pointer(mp).unwrap_or(0);
210                    let mn = match image.c_str(mn_ptr) {
211                        Some(n) if image_names.contains(n.as_str()) => n,
212                        _ => {
213                            ok = false;
214                            break;
215                        }
216                    };
217                    // Il2CppCodeGenModule (v29):
218                    //   0:  const char* moduleName
219                    //   p:  methodPointerCount (ptr-width or i32+pad)
220                    //   2p: Il2CppMethodPointer* methodPointers
221                    let raw_count = image.pointer(mp + p).unwrap_or(0);
222                    let mp_count = if raw_count < 100_000 {
223                        raw_count
224                    } else {
225                        image.u32(mp + p).unwrap_or(0) as u64
226                    };
227                    let mp_array = image.pointer(mp + 2 * p).unwrap_or(0);
228                    let pointers = if mp_count > 0 && image.is_mapped(mp_array) {
229                        image.pointers(mp_array, mp_count).unwrap_or_default()
230                    } else {
231                        Vec::new()
232                    };
233                    modules.push(CodeGenModule {
234                        name: mn,
235                        method_pointers: pointers,
236                    });
237                }
238                if ok && modules.len() == image_count as usize {
239                    return Ok(Self { modules });
240                }
241            }
242        }
243        Err(Error::Binary("CodeRegistration not found".into()))
244    }
245}
246
247/// The game binary's type table, decoded.
248#[cfg_attr(feature = "reflect", derive(facet::Facet))]
249pub struct Binary {
250    pub metadata_registration: MetadataRegistration,
251    pub code_registration: Option<CodeRegistration>,
252    pub types: Vec<Il2CppType>,
253}
254
255impl Binary {
256    pub fn read(image: &impl LoadedImage, metadata: &Metadata) -> Result<Self> {
257        let registration = MetadataRegistration::find(image, metadata)?;
258        let (count, array) = registration.types;
259        let types = image
260            .pointers(array, count)
261            .ok_or_else(|| Error::Binary("the Il2CppType pointer table is unmapped".into()))?
262            .into_iter()
263            .map(|address| read_type(image, address, 0))
264            .collect::<Result<Vec<_>>>()?;
265        let code_registration = CodeRegistration::find(image, metadata).ok();
266        Ok(Self {
267            metadata_registration: registration,
268            code_registration,
269            types,
270        })
271    }
272
273    pub fn type_at(&self, index: i32) -> Option<&Il2CppType> {
274        usize::try_from(index).ok().and_then(|i| self.types.get(i))
275    }
276
277    /// Look up the native code address for a method by its image name and
278    /// token (RID = token & 0xFFFFFF, 1-based).
279    pub fn method_pointer(&self, image_name: &str, token: u32) -> Option<u64> {
280        let code = self.code_registration.as_ref()?;
281        let module = code.modules.iter().find(|m| m.name == image_name)?;
282        let rid = (token & 0x00FF_FFFF) as usize;
283        if rid == 0 {
284            return None;
285        }
286        let ptr = *module.method_pointers.get(rid - 1)?;
287        if ptr == 0 { None } else { Some(ptr) }
288    }
289}
290
291fn read_type(image: &impl LoadedImage, address: u64, depth: usize) -> Result<Il2CppType> {
292    if depth > 32 {
293        return Err(Error::Binary("type nesting is too deep".into()));
294    }
295    let p = image.pointer_size();
296    let unmapped = || Error::Binary(format!("Il2CppType at {:#x} is unmapped", address));
297    let data = image.pointer(address).ok_or_else(unmapped)?;
298    let bits = image.u32(address + p).ok_or_else(unmapped)?;
299    let attrs = (bits & 0xFFFF) as u16;
300    let element = ((bits >> 16) & 0xFF) as u8;
301    let byref = (bits >> 29) & 1 == 1;
302    let nested = |address: u64| read_type(image, address, depth + 1).map(Box::new);
303
304    let kind = match element {
305        element::CLASS => TypeKind::Class(data as i32),
306        element::VALUETYPE => TypeKind::ValueType(data as i32),
307        element::VAR => TypeKind::Var(data as i32),
308        element::MVAR => TypeKind::MVar(data as i32),
309        element::SZARRAY => TypeKind::SzArray(nested(data)?),
310        element::PTR => TypeKind::Ptr(nested(data)?),
311        element::ARRAY => TypeKind::Array {
312            element: nested(image.pointer(data).ok_or_else(unmapped)?)?,
313            rank: image.u8(data + p).ok_or_else(unmapped)?,
314        },
315        element::GENERICINST => {
316            // Il2CppGenericClass { type, context { class_inst, method_inst }, cached_class }
317            let generic = nested(image.pointer(data).ok_or_else(unmapped)?)?;
318            let class_inst = image.pointer(data + p).ok_or_else(unmapped)?;
319            // Il2CppGenericInst { type_argc, type_argv }
320            let argc = image.pointer(class_inst).ok_or_else(unmapped)?;
321            let argv = image.pointer(class_inst + p).ok_or_else(unmapped)?;
322            if argc > 64 {
323                return Err(Error::Binary(format!(
324                    "generic instance at {:#x} has {} arguments",
325                    data, argc
326                )));
327            }
328            let args = (0..argc)
329                .map(|i| {
330                    let arg = image.pointer(argv + i * p).ok_or_else(unmapped)?;
331                    read_type(image, arg, depth + 1)
332                })
333                .collect::<Result<_>>()?;
334            TypeKind::GenericInst { generic, args }
335        }
336        element::FNPTR => TypeKind::FnPtr,
337        0x01..=0x0E | element::TYPEDBYREF | 0x18 | 0x19 | element::OBJECT => {
338            TypeKind::Primitive(element)
339        }
340        other => TypeKind::Unknown(other),
341    };
342    Ok(Il2CppType { kind, attrs, byref })
343}
344
345fn primitive_name(element: u8) -> &'static str {
346    match element {
347        0x01 => "void",
348        0x02 => "bool",
349        0x03 => "char",
350        0x04 => "sbyte",
351        0x05 => "byte",
352        0x06 => "short",
353        0x07 => "ushort",
354        0x08 => "int",
355        0x09 => "uint",
356        0x0A => "long",
357        0x0B => "ulong",
358        0x0C => "float",
359        0x0D => "double",
360        0x0E => "string",
361        0x16 => "TypedReference",
362        0x18 => "nint",
363        0x19 => "nuint",
364        0x1C => "object",
365        _ => "?",
366    }
367}
368
369/// Removes the `` `N `` generic arity suffixes from every part of a type name.
370fn strip_arity(name: &str) -> String {
371    let mut out = String::with_capacity(name.len());
372    let mut chars = name.chars().peekable();
373    while let Some(c) = chars.next() {
374        if c == '`' {
375            while chars.peek().is_some_and(|d| d.is_ascii_digit()) {
376                chars.next();
377            }
378        } else {
379            out.push(c);
380        }
381    }
382    out
383}
384
385impl Il2CppType {
386    /// A C#-like name, e.g. `List<int>[]`.
387    pub fn name(&self, metadata: &Metadata) -> String {
388        let name = match &self.kind {
389            TypeKind::Primitive(e) => primitive_name(*e).to_owned(),
390            TypeKind::Class(t) | TypeKind::ValueType(t) => metadata.type_full_name(*t),
391            TypeKind::SzArray(e) => format!("{}[]", e.name(metadata)),
392            TypeKind::Array { element, rank } => {
393                format!(
394                    "{}[{}]",
395                    element.name(metadata),
396                    ",".repeat(rank.saturating_sub(1) as usize)
397                )
398            }
399            TypeKind::Ptr(e) => format!("{}*", e.name(metadata)),
400            TypeKind::GenericInst { generic, args } => {
401                let base = strip_arity(&generic.name(metadata));
402                let args: Vec<String> = args.iter().map(|a| a.name(metadata)).collect();
403                format!("{}<{}>", base, args.join(", "))
404            }
405            TypeKind::Var(i) | TypeKind::MVar(i) => metadata
406                .generic_parameters
407                .get(*i as usize)
408                .map(|g| metadata.string(g.name_index).to_owned())
409                .unwrap_or_else(|| format!("T{}", i)),
410            TypeKind::FnPtr => "fnptr".to_owned(),
411            TypeKind::Unknown(e) => format!("<unknown {:#x}>", e),
412        };
413        if self.byref {
414            format!("ref {}", name)
415        } else {
416            name
417        }
418    }
419}