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