hao-il2cpp 0.0.12

Read Unity Il2Cpp metadata and generate .net proxy assemblies with hao
Documentation
//! 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.

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

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

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

#[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),
    Class(TypeDefinitionIndex),
    ValueType(TypeDefinitionIndex),
    SzArray(Box<Il2CppType>),
    Array {
        element: Box<Il2CppType>,
        rank: u8,
    },
    Ptr(Box<Il2CppType>),
    GenericInst {
        generic: Box<Il2CppType>,
        args: Vec<Il2CppType>,
    },
    /// Index into [`Metadata::generic_parameters`].
    Var(i32),
    MVar(i32),
    FnPtr,
    Unknown(u8),
}

#[derive(Debug, Clone, PartialEq)]
#[cfg_attr(feature = "reflect", derive(facet::Facet))]
pub struct Il2CppType {
    pub kind: TypeKind,
    pub attrs: u16,
    pub byref: bool,
}

/// `Il2CppMetadataRegistration` (v29).
#[derive(Debug, Clone, PartialEq, Eq)]
#[cfg_attr(feature = "reflect", derive(facet::Facet))]
pub struct MetadataRegistration {
    pub address: u64,
    pub generic_classes: (u64, u64),
    pub generic_insts: (u64, u64),
    pub generic_method_table: (u64, u64),
    pub types: (u64, u64),
    pub method_specs: (u64, u64),
    pub field_offsets: (u64, u64),
    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 {
    pub name: String,
    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 {
    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 {
    pub metadata_registration: MetadataRegistration,
    pub code_registration: Option<CodeRegistration>,
    pub types: Vec<Il2CppType>,
}

impl Binary {
    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,
        })
    }

    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
        }
    }
}