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 STRING: u8 = 0x0E;
18    pub const PTR: u8 = 0x0F;
19    pub const BYREF: u8 = 0x10;
20    pub const VALUETYPE: u8 = 0x11;
21    pub const CLASS: u8 = 0x12;
22    pub const VAR: u8 = 0x13;
23    pub const ARRAY: u8 = 0x14;
24    pub const GENERICINST: u8 = 0x15;
25    pub const TYPEDBYREF: u8 = 0x16;
26    pub const FNPTR: u8 = 0x1B;
27    pub const OBJECT: u8 = 0x1C;
28    pub const SZARRAY: u8 = 0x1D;
29    pub const MVAR: u8 = 0x1E;
30}
31
32#[derive(Debug, Clone, PartialEq)]
33pub enum TypeKind {
34    /// `void`, `bool`, ..., `string`, `object`, `IntPtr`, `TypedReference`.
35    Primitive(u8),
36    Class(TypeDefinitionIndex),
37    ValueType(TypeDefinitionIndex),
38    SzArray(Box<Il2CppType>),
39    Array {
40        element: Box<Il2CppType>,
41        rank: u8,
42    },
43    Ptr(Box<Il2CppType>),
44    GenericInst {
45        generic: Box<Il2CppType>,
46        args: Vec<Il2CppType>,
47    },
48    /// Index into [`Metadata::generic_parameters`].
49    Var(i32),
50    MVar(i32),
51    FnPtr,
52    Unknown(u8),
53}
54
55#[derive(Debug, Clone, PartialEq)]
56pub struct Il2CppType {
57    pub kind: TypeKind,
58    pub attrs: u16,
59    pub byref: bool,
60}
61
62/// `Il2CppMetadataRegistration` (v29).
63#[derive(Debug, Clone, PartialEq, Eq)]
64pub struct MetadataRegistration {
65    pub address: u64,
66    pub generic_classes: (u64, u64),
67    pub generic_insts: (u64, u64),
68    pub generic_method_table: (u64, u64),
69    pub types: (u64, u64),
70    pub method_specs: (u64, u64),
71    pub field_offsets: (u64, u64),
72    pub type_definition_sizes: (u64, u64),
73}
74
75impl MetadataRegistration {
76    /// Finds the registration by its two counts that equal the number of type definitions
77    /// (`fieldOffsetsCount` and `typeDefinitionsSizesCount`).
78    pub fn find(image: &impl LoadedImage, metadata: &Metadata) -> Result<Self> {
79        let p = image.pointer_size();
80        let count = metadata.type_definitions.len() as u64;
81        let word = |v: u64| image.pointer(v).unwrap_or(0);
82        let pair = |v: u64| (word(v), word(v + p));
83        let mut found = Vec::new();
84        for segment in image.data_segments() {
85            let start = segment.0;
86            // Reads past the mapping just return 0, so the window needs no upper bound.
87            for vaddr in image
88                .pointer_slots(segment)
89                .filter(|v| *v >= start + 10 * p)
90            {
91                if word(vaddr) == count
92                    && word(vaddr + 2 * p) == count
93                    && image.is_mapped(word(vaddr + p))
94                    && image.is_mapped(word(vaddr + 3 * p))
95                {
96                    let base = vaddr - 10 * p;
97                    let types = pair(base + 6 * p);
98                    if types.0 >= count && image.is_mapped(types.1) {
99                        found.push(Self {
100                            address: base,
101                            generic_classes: pair(base),
102                            generic_insts: pair(base + 2 * p),
103                            generic_method_table: pair(base + 4 * p),
104                            types,
105                            method_specs: pair(base + 8 * p),
106                            field_offsets: pair(base + 10 * p),
107                            type_definition_sizes: pair(base + 12 * p),
108                        });
109                    }
110                }
111            }
112        }
113        match found.len() {
114            1 => Ok(found.remove(0)),
115            0 => Err(Error::Binary("MetadataRegistration not found".into())),
116            n => Err(Error::Binary(format!(
117                "{} candidates for MetadataRegistration",
118                n
119            ))),
120        }
121    }
122}
123
124/// The game binary's type table, decoded.
125pub struct Binary {
126    pub metadata_registration: MetadataRegistration,
127    pub types: Vec<Il2CppType>,
128}
129
130impl Binary {
131    pub fn read(image: &impl LoadedImage, metadata: &Metadata) -> Result<Self> {
132        let registration = MetadataRegistration::find(image, metadata)?;
133        let (count, array) = registration.types;
134        let types = image
135            .pointers(array, count)
136            .ok_or_else(|| Error::Binary("the Il2CppType pointer table is unmapped".into()))?
137            .into_iter()
138            .map(|address| read_type(image, address, 0))
139            .collect::<Result<Vec<_>>>()?;
140        Ok(Self {
141            metadata_registration: registration,
142            types,
143        })
144    }
145
146    pub fn type_at(&self, index: i32) -> Option<&Il2CppType> {
147        usize::try_from(index).ok().and_then(|i| self.types.get(i))
148    }
149}
150
151fn read_type(image: &impl LoadedImage, address: u64, depth: usize) -> Result<Il2CppType> {
152    if depth > 32 {
153        return Err(Error::Binary("type nesting is too deep".into()));
154    }
155    let p = image.pointer_size();
156    let unmapped = || Error::Binary(format!("Il2CppType at {:#x} is unmapped", address));
157    let data = image.pointer(address).ok_or_else(unmapped)?;
158    let bits = image.u32(address + p).ok_or_else(unmapped)?;
159    let attrs = (bits & 0xFFFF) as u16;
160    let element = ((bits >> 16) & 0xFF) as u8;
161    let byref = (bits >> 29) & 1 == 1;
162    let nested = |address: u64| read_type(image, address, depth + 1).map(Box::new);
163
164    let kind = match element {
165        element::CLASS => TypeKind::Class(data as i32),
166        element::VALUETYPE => TypeKind::ValueType(data as i32),
167        element::VAR => TypeKind::Var(data as i32),
168        element::MVAR => TypeKind::MVar(data as i32),
169        element::SZARRAY => TypeKind::SzArray(nested(data)?),
170        element::PTR => TypeKind::Ptr(nested(data)?),
171        element::ARRAY => TypeKind::Array {
172            element: nested(image.pointer(data).ok_or_else(unmapped)?)?,
173            rank: image.u8(data + p).ok_or_else(unmapped)?,
174        },
175        element::GENERICINST => {
176            // Il2CppGenericClass { type, context { class_inst, method_inst }, cached_class }
177            let generic = nested(image.pointer(data).ok_or_else(unmapped)?)?;
178            let class_inst = image.pointer(data + p).ok_or_else(unmapped)?;
179            // Il2CppGenericInst { type_argc, type_argv }
180            let argc = image.pointer(class_inst).ok_or_else(unmapped)?;
181            let argv = image.pointer(class_inst + p).ok_or_else(unmapped)?;
182            if argc > 64 {
183                return Err(Error::Binary(format!(
184                    "generic instance at {:#x} has {} arguments",
185                    data, argc
186                )));
187            }
188            let args = (0..argc)
189                .map(|i| {
190                    let arg = image.pointer(argv + i * p).ok_or_else(unmapped)?;
191                    read_type(image, arg, depth + 1)
192                })
193                .collect::<Result<_>>()?;
194            TypeKind::GenericInst { generic, args }
195        }
196        element::FNPTR => TypeKind::FnPtr,
197        0x01..=0x0E | element::TYPEDBYREF | 0x18 | 0x19 | element::OBJECT => {
198            TypeKind::Primitive(element)
199        }
200        other => TypeKind::Unknown(other),
201    };
202    Ok(Il2CppType { kind, attrs, byref })
203}
204
205fn primitive_name(element: u8) -> &'static str {
206    match element {
207        0x01 => "void",
208        0x02 => "bool",
209        0x03 => "char",
210        0x04 => "sbyte",
211        0x05 => "byte",
212        0x06 => "short",
213        0x07 => "ushort",
214        0x08 => "int",
215        0x09 => "uint",
216        0x0A => "long",
217        0x0B => "ulong",
218        0x0C => "float",
219        0x0D => "double",
220        0x0E => "string",
221        0x16 => "TypedReference",
222        0x18 => "nint",
223        0x19 => "nuint",
224        0x1C => "object",
225        _ => "?",
226    }
227}
228
229/// Removes the `` `N `` generic arity suffixes from every part of a type name.
230fn strip_arity(name: &str) -> String {
231    let mut out = String::with_capacity(name.len());
232    let mut chars = name.chars().peekable();
233    while let Some(c) = chars.next() {
234        if c == '`' {
235            while chars.peek().is_some_and(|d| d.is_ascii_digit()) {
236                chars.next();
237            }
238        } else {
239            out.push(c);
240        }
241    }
242    out
243}
244
245impl Il2CppType {
246    /// A C#-like name, e.g. `List<int>[]`.
247    pub fn name(&self, metadata: &Metadata) -> String {
248        let name = match &self.kind {
249            TypeKind::Primitive(e) => primitive_name(*e).to_owned(),
250            TypeKind::Class(t) | TypeKind::ValueType(t) => metadata.type_full_name(*t),
251            TypeKind::SzArray(e) => format!("{}[]", e.name(metadata)),
252            TypeKind::Array { element, rank } => {
253                format!(
254                    "{}[{}]",
255                    element.name(metadata),
256                    ",".repeat(rank.saturating_sub(1) as usize)
257                )
258            }
259            TypeKind::Ptr(e) => format!("{}*", e.name(metadata)),
260            TypeKind::GenericInst { generic, args } => {
261                let base = strip_arity(&generic.name(metadata));
262                let args: Vec<String> = args.iter().map(|a| a.name(metadata)).collect();
263                format!("{}<{}>", base, args.join(", "))
264            }
265            TypeKind::Var(i) | TypeKind::MVar(i) => metadata
266                .generic_parameters
267                .get(*i as usize)
268                .map(|g| metadata.string(g.name_index).to_owned())
269                .unwrap_or_else(|| format!("T{}", i)),
270            TypeKind::FnPtr => "fnptr".to_owned(),
271            TypeKind::Unknown(e) => format!("<unknown {:#x}>", e),
272        };
273        if self.byref {
274            format!("ref {}", name)
275        } else {
276            name
277        }
278    }
279}