hao-il2cpp 0.0.14

Read Unity Il2Cpp metadata and generate .net proxy assemblies with hao
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
//! The game binary (`GameAssembly`): the registration tables and the
//! `Il2CppType` table that metadata type indices refer to.
//!
//! The binary is read through pewter's [`LoadedImage`], which abstracts over
//! ELF (`.so`) and PE (`.dll`) and resolves virtual addresses after relocation.
//!
//! ```no_run
//! use hao_il2cpp::{AnyImage, Binary, Metadata};
//!
//! let metadata = Metadata::from_path("Game_Data/il2cpp_data/Metadata/global-metadata.dat")?;
//! let bytes = std::fs::read("GameAssembly.so")?;
//! let image = AnyImage::load(&bytes).expect("not an ELF or PE file");
//! let binary = Binary::read(&image, &metadata)?;
//!
//! // A field's type index points into the binary's type table.
//! let field = &metadata.fields[0];
//! if let Some(ty) = binary.type_at(field.type_index) {
//!     println!("{} {}", ty.name(&metadata), metadata.string(field.name_index));
//! }
//! # Ok::<(), hao_il2cpp::Error>(())
//! ```

pub use pewter::image::{ElfImage, LoadedImage, PeImage};

use hao::dotnet::signature::{ElementType, PrimitiveType};

use crate::{
    error::{Error, Result},
    metadata::{Metadata, TypeDefinitionIndex},
};

/// What an [`Il2CppType`] is: its element type and the data that goes with it.
///
/// Mirrors `Il2CppTypeEnum` plus the `data` union of IL2CPP's `Il2CppType`.
#[derive(Debug, Clone, PartialEq)]
#[cfg_attr(feature = "reflect", derive(facet::Facet))]
#[cfg_attr(feature = "reflect", repr(C))]
pub enum TypeKind {
    /// `void`, `bool`, ..., `string`, `object`, `IntPtr`, `TypedReference`.
    Primitive(PrimitiveType),
    /// A reference type, by index into [`Metadata::type_definitions`].
    Class(TypeDefinitionIndex),
    /// A value type, by index into [`Metadata::type_definitions`].
    ValueType(TypeDefinitionIndex),
    /// A single-dimension, zero-based array (`T[]`).
    SzArray(Box<Il2CppType>),
    /// A multi-dimensional array (`T[,]`).
    Array {
        /// The type of each element.
        element: Box<Il2CppType>,
        /// The number of dimensions.
        rank: u8,
    },
    /// An unmanaged pointer (`T*`).
    Ptr(Box<Il2CppType>),
    /// A constructed generic type, e.g. `List<int>`.
    GenericInst {
        /// The generic type definition, e.g. `List<T>`.
        generic: Box<Il2CppType>,
        /// The type arguments, in order.
        args: Vec<Il2CppType>,
    },
    /// A type's generic parameter, by index into [`Metadata::generic_parameters`].
    Var(i32),
    /// A method's generic parameter, by index into [`Metadata::generic_parameters`].
    MVar(i32),
    /// A function pointer. Its signature isn't decoded.
    FnPtr,
    /// An element type this reader doesn't know, with its raw `Il2CppTypeEnum` value.
    Unknown(u8),
}

/// One entry of the binary's `Il2CppType` table: the type of a field,
/// parameter or return value, which metadata refers to by type index.
#[derive(Debug, Clone, PartialEq)]
#[cfg_attr(feature = "reflect", derive(facet::Facet))]
pub struct Il2CppType {
    /// What the type is, with its element or definition.
    pub kind: TypeKind,
    /// The low 16 bits of the bitfield: the owning field's or parameter's
    /// attributes (`FieldAttributes` / `ParamAttributes`) where it has them.
    pub attrs: u16,
    /// Passed by reference (`ref`, `out` or `in`).
    pub byref: bool,
}

/// `Il2CppMetadataRegistration` (v29).
#[derive(Debug, Clone, PartialEq, Eq)]
#[cfg_attr(feature = "reflect", derive(facet::Facet))]
///
/// Each table is a `(count, address)` pair, as the struct lays them out.
pub struct MetadataRegistration {
    /// Where the struct itself is, as a virtual address.
    pub address: u64,
    /// `genericClasses`: every generic type instance the game uses.
    pub generic_classes: (u64, u64),
    /// `genericInsts`: the type argument lists those instances share.
    pub generic_insts: (u64, u64),
    /// `genericMethodTable`: generic method instances and their code.
    pub generic_method_table: (u64, u64),
    /// `types`: the `Il2CppType` pointer table that metadata type indices refer to.
    pub types: (u64, u64),
    /// `methodSpecs`: generic method instances, as (method, class args, method args).
    pub method_specs: (u64, u64),
    /// `fieldOffsets`: per type definition, its fields' offsets in the object.
    pub field_offsets: (u64, u64),
    /// `typeDefinitionsSizes`: per type definition, its instance and static sizes.
    pub type_definition_sizes: (u64, u64),
}

impl MetadataRegistration {
    /// Finds the registration by its two counts that equal the number of type definitions
    /// (`fieldOffsetsCount` and `typeDefinitionsSizesCount`).
    pub fn find(image: &impl LoadedImage, metadata: &Metadata) -> Result<Self> {
        let p = image.pointer_size();
        let count = metadata.type_definitions.len() as u64;
        let word = |v: u64| image.pointer(v).unwrap_or(0);
        let pair = |v: u64| (word(v), word(v + p));
        let mut found = Vec::new();
        for segment in image.data_segments() {
            let start = segment.0;
            // Reads past the mapping just return 0, so the window needs no upper bound.
            for vaddr in image
                .pointer_slots(segment)
                .filter(|v| *v >= start + 10 * p)
            {
                if word(vaddr) == count
                    && word(vaddr + 2 * p) == count
                    && image.is_mapped(word(vaddr + p))
                    && image.is_mapped(word(vaddr + 3 * p))
                {
                    let base = vaddr - 10 * p;
                    let types = pair(base + 6 * p);
                    if types.0 >= count && image.is_mapped(types.1) {
                        found.push(Self {
                            address: base,
                            generic_classes: pair(base),
                            generic_insts: pair(base + 2 * p),
                            generic_method_table: pair(base + 4 * p),
                            types,
                            method_specs: pair(base + 8 * p),
                            field_offsets: pair(base + 10 * p),
                            type_definition_sizes: pair(base + 12 * p),
                        });
                    }
                }
            }
        }
        match found.len() {
            1 => Ok(found.remove(0)),
            0 => Err(Error::Binary("MetadataRegistration not found".into())),
            n => Err(Error::Binary(format!(
                "{} candidates for MetadataRegistration",
                n
            ))),
        }
    }
}

/// Per-image method pointer table, from `Il2CppCodeGenModule`.
#[derive(Debug, Clone)]
#[cfg_attr(feature = "reflect", derive(facet::Facet))]
pub struct CodeGenModule {
    /// The image this module was generated from, e.g. `Assembly-CSharp.dll`.
    pub name: String,
    /// The native code address of each method, indexed by its token's RID
    /// minus one; `0` where a method has no code (abstract, or stripped).
    pub method_pointers: Vec<u64>,
}

/// `Il2CppCodeRegistration` — the code-side registration that holds method
/// pointers, invoker pointers, and per-module code generation tables.
#[derive(Debug, Clone)]
#[cfg_attr(feature = "reflect", derive(facet::Facet))]
pub struct CodeRegistration {
    /// One code generation module per image.
    pub modules: Vec<CodeGenModule>,
}

impl CodeRegistration {
    /// Finds the code registration by locating `codeGenModules` — an array of
    /// pointers to `Il2CppCodeGenModule` structs whose `moduleName` fields
    /// match the image names from metadata.
    pub fn find(image: &impl LoadedImage, metadata: &Metadata) -> Result<Self> {
        let p = image.pointer_size();
        let image_count = metadata.images.len() as u64;
        let image_names: std::collections::HashSet<&str> = metadata
            .images
            .iter()
            .map(|i| metadata.image_name(i))
            .collect();

        // Scan data segments for the codeGenModules array — a contiguous
        // run of `image_count` pointers to `Il2CppCodeGenModule` structs.
        // The array order may differ from metadata order (often alphabetical).
        for segment in image.data_segments() {
            let start = segment.0;
            for vaddr in image.pointer_slots(segment).filter(|v| *v >= start) {
                let array_ptr = match image.pointer(vaddr) {
                    Some(a) if image.is_mapped(a) => a,
                    _ => continue,
                };
                let first_module = match image.pointer(array_ptr) {
                    Some(m) if image.is_mapped(m) => m,
                    _ => continue,
                };
                let name_ptr = match image.pointer(first_module) {
                    Some(n) if image.is_mapped(n) => n,
                    _ => continue,
                };
                let name = match image.c_str(name_ptr) {
                    Some(n) => n,
                    None => continue,
                };
                if !image_names.contains(name.as_str()) {
                    continue;
                }

                let module_ptrs = match image.pointers(array_ptr, image_count) {
                    Some(ptrs) => ptrs,
                    None => continue,
                };

                // Read all modules and verify every name is a known image.
                let mut modules = Vec::with_capacity(image_count as usize);
                let mut ok = true;
                for module_ptr in &module_ptrs {
                    let mp = *module_ptr;
                    if !image.is_mapped(mp) {
                        ok = false;
                        break;
                    }
                    let mn_ptr = image.pointer(mp).unwrap_or(0);
                    let mn = match image.c_str(mn_ptr) {
                        Some(n) if image_names.contains(n.as_str()) => n,
                        _ => {
                            ok = false;
                            break;
                        }
                    };
                    // Il2CppCodeGenModule (v29):
                    //   0:  const char* moduleName
                    //   p:  methodPointerCount (ptr-width or i32+pad)
                    //   2p: Il2CppMethodPointer* methodPointers
                    let raw_count = image.pointer(mp + p).unwrap_or(0);
                    let mp_count = if raw_count < 100_000 {
                        raw_count
                    } else {
                        image.u32(mp + p).unwrap_or(0) as u64
                    };
                    let mp_array = image.pointer(mp + 2 * p).unwrap_or(0);
                    let pointers = if mp_count > 0 && image.is_mapped(mp_array) {
                        image.pointers(mp_array, mp_count).unwrap_or_default()
                    } else {
                        Vec::new()
                    };
                    modules.push(CodeGenModule {
                        name: mn,
                        method_pointers: pointers,
                    });
                }
                if ok && modules.len() == image_count as usize {
                    return Ok(Self { modules });
                }
            }
        }
        Err(Error::Binary("CodeRegistration not found".into()))
    }
}

/// The game binary's type table, decoded.
#[cfg_attr(feature = "reflect", derive(facet::Facet))]
pub struct Binary {
    /// Where the binary's type and generic tables are.
    pub metadata_registration: MetadataRegistration,
    /// The method code tables, or `None` if `CodeRegistration` wasn't found
    /// (then [`method_pointer`](Self::method_pointer) always returns `None`).
    pub code_registration: Option<CodeRegistration>,
    /// The `Il2CppType` table, decoded; metadata type indices index into it.
    pub types: Vec<Il2CppType>,
}

impl Binary {
    /// Finds the registration structs in a loaded game binary and decodes
    /// its type table, using `metadata` to recognise them.
    ///
    /// Fails if `MetadataRegistration` isn't found or a type can't be read;
    /// a missing `CodeRegistration` only leaves
    /// [`code_registration`](Self::code_registration) `None`.
    pub fn read(image: &impl LoadedImage, metadata: &Metadata) -> Result<Self> {
        let registration = MetadataRegistration::find(image, metadata)?;
        let (count, array) = registration.types;
        let types = image
            .pointers(array, count)
            .ok_or_else(|| Error::Binary("the Il2CppType pointer table is unmapped".into()))?
            .into_iter()
            .map(|address| read_type(image, address, 0))
            .collect::<Result<Vec<_>>>()?;
        let code_registration = CodeRegistration::find(image, metadata).ok();
        Ok(Self {
            metadata_registration: registration,
            code_registration,
            types,
        })
    }

    /// The type at a metadata type index (e.g. a field's `type_index`), or
    /// `None` if it's negative or out of range.
    pub fn type_at(&self, index: i32) -> Option<&Il2CppType> {
        usize::try_from(index).ok().and_then(|i| self.types.get(i))
    }

    /// Look up the native code address for a method by its image name and
    /// token (RID = token & 0xFFFFFF, 1-based).
    pub fn method_pointer(&self, image_name: &str, token: u32) -> Option<u64> {
        let code = self.code_registration.as_ref()?;
        let module = code.modules.iter().find(|m| m.name == image_name)?;
        let rid = (token & 0x00FF_FFFF) as usize;
        if rid == 0 {
            return None;
        }
        let ptr = *module.method_pointers.get(rid - 1)?;
        if ptr == 0 {
            None
        } else {
            Some(ptr)
        }
    }
}

fn read_type(image: &impl LoadedImage, address: u64, depth: usize) -> Result<Il2CppType> {
    if depth > 32 {
        return Err(Error::Binary("type nesting is too deep".into()));
    }
    let p = image.pointer_size();
    let unmapped = || Error::Binary(format!("Il2CppType at {:#x} is unmapped", address));
    let data = image.pointer(address).ok_or_else(unmapped)?;
    let bits = image.u32(address + p).ok_or_else(unmapped)?;
    let attrs = (bits & 0xFFFF) as u16;
    let element = ((bits >> 16) & 0xFF) as u8;
    let byref = (bits >> 29) & 1 == 1;
    let nested = |address: u64| read_type(image, address, depth + 1).map(Box::new);

    let kind = match ElementType::from_repr(element) {
        Some(ElementType::Class) => TypeKind::Class(data as i32),
        Some(ElementType::ValueType) => TypeKind::ValueType(data as i32),
        Some(ElementType::Var) => TypeKind::Var(data as i32),
        Some(ElementType::MVar) => TypeKind::MVar(data as i32),
        Some(ElementType::SzArray) => TypeKind::SzArray(nested(data)?),
        Some(ElementType::Ptr) => TypeKind::Ptr(nested(data)?),
        Some(ElementType::Array) => TypeKind::Array {
            element: nested(image.pointer(data).ok_or_else(unmapped)?)?,
            rank: image.u8(data + p).ok_or_else(unmapped)?,
        },
        Some(ElementType::GenericInst) => {
            // Il2CppGenericClass { type, context { class_inst, method_inst }, cached_class }
            let generic = nested(image.pointer(data).ok_or_else(unmapped)?)?;
            let class_inst = image.pointer(data + p).ok_or_else(unmapped)?;
            // Il2CppGenericInst { type_argc, type_argv }
            let argc = image.pointer(class_inst).ok_or_else(unmapped)?;
            let argv = image.pointer(class_inst + p).ok_or_else(unmapped)?;
            if argc > 64 {
                return Err(Error::Binary(format!(
                    "generic instance at {:#x} has {} arguments",
                    data, argc
                )));
            }
            let args = (0..argc)
                .map(|i| {
                    let arg = image.pointer(argv + i * p).ok_or_else(unmapped)?;
                    read_type(image, arg, depth + 1)
                })
                .collect::<Result<_>>()?;
            TypeKind::GenericInst { generic, args }
        }
        Some(ElementType::FnPtr) => TypeKind::FnPtr,
        _ => match PrimitiveType::from_repr(element) {
            Some(p) => TypeKind::Primitive(p),
            None => TypeKind::Unknown(element),
        },
    };
    Ok(Il2CppType { kind, attrs, byref })
}

/// Removes the `` `N `` generic arity suffixes from every part of a type name.
fn strip_arity(name: &str) -> String {
    let mut out = String::with_capacity(name.len());
    let mut chars = name.chars().peekable();
    while let Some(c) = chars.next() {
        if c == '`' {
            while chars.peek().is_some_and(|d| d.is_ascii_digit()) {
                chars.next();
            }
        } else {
            out.push(c);
        }
    }
    out
}

impl Il2CppType {
    /// A C#-like name, e.g. `List<int>[]`.
    pub fn name(&self, metadata: &Metadata) -> String {
        let name = match &self.kind {
            TypeKind::Primitive(p) => p.keyword().to_owned(),
            TypeKind::Class(t) | TypeKind::ValueType(t) => metadata.type_full_name(*t),
            TypeKind::SzArray(e) => format!("{}[]", e.name(metadata)),
            TypeKind::Array { element, rank } => {
                format!(
                    "{}[{}]",
                    element.name(metadata),
                    ",".repeat(rank.saturating_sub(1) as usize)
                )
            }
            TypeKind::Ptr(e) => format!("{}*", e.name(metadata)),
            TypeKind::GenericInst { generic, args } => {
                let base = strip_arity(&generic.name(metadata));
                let args: Vec<String> = args.iter().map(|a| a.name(metadata)).collect();
                format!("{}<{}>", base, args.join(", "))
            }
            TypeKind::Var(i) | TypeKind::MVar(i) => metadata
                .generic_parameters
                .get(*i as usize)
                .map(|g| metadata.string(g.name_index).to_owned())
                .unwrap_or_else(|| format!("T{}", i)),
            TypeKind::FnPtr => "fnptr".to_owned(),
            TypeKind::Unknown(e) => format!("<unknown {:#x}>", e),
        };
        if self.byref {
            format!("ref {}", name)
        } else {
            name
        }
    }
}