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 {
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>,
},
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,
}
#[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 {
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;
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
))),
}
}
}
#[derive(Debug, Clone)]
#[cfg_attr(feature = "reflect", derive(facet::Facet))]
pub struct CodeGenModule {
pub name: String,
pub method_pointers: Vec<u64>,
}
#[derive(Debug, Clone)]
#[cfg_attr(feature = "reflect", derive(facet::Facet))]
pub struct CodeRegistration {
pub modules: Vec<CodeGenModule>,
}
impl CodeRegistration {
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();
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,
};
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;
}
};
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()))
}
}
#[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))
}
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) => {
let generic = nested(image.pointer(data).ok_or_else(unmapped)?)?;
let class_inst = image.pointer(data + p).ok_or_else(unmapped)?;
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 })
}
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 {
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
}
}
}