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