1pub use pewter::image::{ElfImage, LoadedImage, PeImage};
8
9use crate::{
10 error::{Error, Result},
11 metadata::{Metadata, TypeDefinitionIndex},
12};
13
14pub mod element {
16 pub const VOID: u8 = 0x01;
17 pub const BOOLEAN: u8 = 0x02;
18 pub const CHAR: u8 = 0x03;
19 pub const I1: u8 = 0x04;
20 pub const U1: u8 = 0x05;
21 pub const I2: u8 = 0x06;
22 pub const U2: u8 = 0x07;
23 pub const I4: u8 = 0x08;
24 pub const U4: u8 = 0x09;
25 pub const I8: u8 = 0x0A;
26 pub const U8: u8 = 0x0B;
27 pub const R4: u8 = 0x0C;
28 pub const R8: u8 = 0x0D;
29 pub const STRING: u8 = 0x0E;
30 pub const PTR: u8 = 0x0F;
31 pub const BYREF: u8 = 0x10;
32 pub const VALUETYPE: u8 = 0x11;
33 pub const CLASS: u8 = 0x12;
34 pub const VAR: u8 = 0x13;
35 pub const ARRAY: u8 = 0x14;
36 pub const GENERICINST: u8 = 0x15;
37 pub const TYPEDBYREF: u8 = 0x16;
38 pub const FNPTR: u8 = 0x1B;
39 pub const OBJECT: u8 = 0x1C;
40 pub const SZARRAY: u8 = 0x1D;
41 pub const MVAR: u8 = 0x1E;
42}
43
44#[derive(Debug, Clone, PartialEq)]
45#[cfg_attr(feature = "reflect", derive(facet::Facet))]
46#[cfg_attr(feature = "reflect", repr(C))]
47pub enum TypeKind {
48 Primitive(u8),
50 Class(TypeDefinitionIndex),
51 ValueType(TypeDefinitionIndex),
52 SzArray(Box<Il2CppType>),
53 Array {
54 element: Box<Il2CppType>,
55 rank: u8,
56 },
57 Ptr(Box<Il2CppType>),
58 GenericInst {
59 generic: Box<Il2CppType>,
60 args: Vec<Il2CppType>,
61 },
62 Var(i32),
64 MVar(i32),
65 FnPtr,
66 Unknown(u8),
67}
68
69#[derive(Debug, Clone, PartialEq)]
70#[cfg_attr(feature = "reflect", derive(facet::Facet))]
71pub struct Il2CppType {
72 pub kind: TypeKind,
73 pub attrs: u16,
74 pub byref: bool,
75}
76
77#[derive(Debug, Clone, PartialEq, Eq)]
79#[cfg_attr(feature = "reflect", derive(facet::Facet))]
80pub struct MetadataRegistration {
81 pub address: u64,
82 pub generic_classes: (u64, u64),
83 pub generic_insts: (u64, u64),
84 pub generic_method_table: (u64, u64),
85 pub types: (u64, u64),
86 pub method_specs: (u64, u64),
87 pub field_offsets: (u64, u64),
88 pub type_definition_sizes: (u64, u64),
89}
90
91impl MetadataRegistration {
92 pub fn find(image: &impl LoadedImage, metadata: &Metadata) -> Result<Self> {
95 let p = image.pointer_size();
96 let count = metadata.type_definitions.len() as u64;
97 let word = |v: u64| image.pointer(v).unwrap_or(0);
98 let pair = |v: u64| (word(v), word(v + p));
99 let mut found = Vec::new();
100 for segment in image.data_segments() {
101 let start = segment.0;
102 for vaddr in image
104 .pointer_slots(segment)
105 .filter(|v| *v >= start + 10 * p)
106 {
107 if word(vaddr) == count
108 && word(vaddr + 2 * p) == count
109 && image.is_mapped(word(vaddr + p))
110 && image.is_mapped(word(vaddr + 3 * p))
111 {
112 let base = vaddr - 10 * p;
113 let types = pair(base + 6 * p);
114 if types.0 >= count && image.is_mapped(types.1) {
115 found.push(Self {
116 address: base,
117 generic_classes: pair(base),
118 generic_insts: pair(base + 2 * p),
119 generic_method_table: pair(base + 4 * p),
120 types,
121 method_specs: pair(base + 8 * p),
122 field_offsets: pair(base + 10 * p),
123 type_definition_sizes: pair(base + 12 * p),
124 });
125 }
126 }
127 }
128 }
129 match found.len() {
130 1 => Ok(found.remove(0)),
131 0 => Err(Error::Binary("MetadataRegistration not found".into())),
132 n => Err(Error::Binary(format!(
133 "{} candidates for MetadataRegistration",
134 n
135 ))),
136 }
137 }
138}
139
140#[derive(Debug, Clone)]
142#[cfg_attr(feature = "reflect", derive(facet::Facet))]
143pub struct CodeGenModule {
144 pub name: String,
145 pub method_pointers: Vec<u64>,
146}
147
148#[derive(Debug, Clone)]
151#[cfg_attr(feature = "reflect", derive(facet::Facet))]
152pub struct CodeRegistration {
153 pub modules: Vec<CodeGenModule>,
154}
155
156impl CodeRegistration {
157 pub fn find(image: &impl LoadedImage, metadata: &Metadata) -> Result<Self> {
161 let p = image.pointer_size();
162 let image_count = metadata.images.len() as u64;
163 let image_names: std::collections::HashSet<&str> = metadata
164 .images
165 .iter()
166 .map(|i| metadata.image_name(i))
167 .collect();
168
169 for segment in image.data_segments() {
173 let start = segment.0;
174 for vaddr in image.pointer_slots(segment).filter(|v| *v >= start) {
175 let array_ptr = match image.pointer(vaddr) {
176 Some(a) if image.is_mapped(a) => a,
177 _ => continue,
178 };
179 let first_module = match image.pointer(array_ptr) {
180 Some(m) if image.is_mapped(m) => m,
181 _ => continue,
182 };
183 let name_ptr = match image.pointer(first_module) {
184 Some(n) if image.is_mapped(n) => n,
185 _ => continue,
186 };
187 let name = match image.c_str(name_ptr) {
188 Some(n) => n,
189 None => continue,
190 };
191 if !image_names.contains(name.as_str()) {
192 continue;
193 }
194
195 let module_ptrs = match image.pointers(array_ptr, image_count) {
196 Some(ptrs) => ptrs,
197 None => continue,
198 };
199
200 let mut modules = Vec::with_capacity(image_count as usize);
202 let mut ok = true;
203 for module_ptr in &module_ptrs {
204 let mp = *module_ptr;
205 if !image.is_mapped(mp) {
206 ok = false;
207 break;
208 }
209 let mn_ptr = image.pointer(mp).unwrap_or(0);
210 let mn = match image.c_str(mn_ptr) {
211 Some(n) if image_names.contains(n.as_str()) => n,
212 _ => {
213 ok = false;
214 break;
215 }
216 };
217 let raw_count = image.pointer(mp + p).unwrap_or(0);
222 let mp_count = if raw_count < 100_000 {
223 raw_count
224 } else {
225 image.u32(mp + p).unwrap_or(0) as u64
226 };
227 let mp_array = image.pointer(mp + 2 * p).unwrap_or(0);
228 let pointers = if mp_count > 0 && image.is_mapped(mp_array) {
229 image.pointers(mp_array, mp_count).unwrap_or_default()
230 } else {
231 Vec::new()
232 };
233 modules.push(CodeGenModule {
234 name: mn,
235 method_pointers: pointers,
236 });
237 }
238 if ok && modules.len() == image_count as usize {
239 return Ok(Self { modules });
240 }
241 }
242 }
243 Err(Error::Binary("CodeRegistration not found".into()))
244 }
245}
246
247#[cfg_attr(feature = "reflect", derive(facet::Facet))]
249pub struct Binary {
250 pub metadata_registration: MetadataRegistration,
251 pub code_registration: Option<CodeRegistration>,
252 pub types: Vec<Il2CppType>,
253}
254
255impl Binary {
256 pub fn read(image: &impl LoadedImage, metadata: &Metadata) -> Result<Self> {
257 let registration = MetadataRegistration::find(image, metadata)?;
258 let (count, array) = registration.types;
259 let types = image
260 .pointers(array, count)
261 .ok_or_else(|| Error::Binary("the Il2CppType pointer table is unmapped".into()))?
262 .into_iter()
263 .map(|address| read_type(image, address, 0))
264 .collect::<Result<Vec<_>>>()?;
265 let code_registration = CodeRegistration::find(image, metadata).ok();
266 Ok(Self {
267 metadata_registration: registration,
268 code_registration,
269 types,
270 })
271 }
272
273 pub fn type_at(&self, index: i32) -> Option<&Il2CppType> {
274 usize::try_from(index).ok().and_then(|i| self.types.get(i))
275 }
276
277 pub fn method_pointer(&self, image_name: &str, token: u32) -> Option<u64> {
280 let code = self.code_registration.as_ref()?;
281 let module = code.modules.iter().find(|m| m.name == image_name)?;
282 let rid = (token & 0x00FF_FFFF) as usize;
283 if rid == 0 {
284 return None;
285 }
286 let ptr = *module.method_pointers.get(rid - 1)?;
287 if ptr == 0 {
288 None
289 } else {
290 Some(ptr)
291 }
292 }
293}
294
295fn read_type(image: &impl LoadedImage, address: u64, depth: usize) -> Result<Il2CppType> {
296 if depth > 32 {
297 return Err(Error::Binary("type nesting is too deep".into()));
298 }
299 let p = image.pointer_size();
300 let unmapped = || Error::Binary(format!("Il2CppType at {:#x} is unmapped", address));
301 let data = image.pointer(address).ok_or_else(unmapped)?;
302 let bits = image.u32(address + p).ok_or_else(unmapped)?;
303 let attrs = (bits & 0xFFFF) as u16;
304 let element = ((bits >> 16) & 0xFF) as u8;
305 let byref = (bits >> 29) & 1 == 1;
306 let nested = |address: u64| read_type(image, address, depth + 1).map(Box::new);
307
308 let kind = match element {
309 element::CLASS => TypeKind::Class(data as i32),
310 element::VALUETYPE => TypeKind::ValueType(data as i32),
311 element::VAR => TypeKind::Var(data as i32),
312 element::MVAR => TypeKind::MVar(data as i32),
313 element::SZARRAY => TypeKind::SzArray(nested(data)?),
314 element::PTR => TypeKind::Ptr(nested(data)?),
315 element::ARRAY => TypeKind::Array {
316 element: nested(image.pointer(data).ok_or_else(unmapped)?)?,
317 rank: image.u8(data + p).ok_or_else(unmapped)?,
318 },
319 element::GENERICINST => {
320 let generic = nested(image.pointer(data).ok_or_else(unmapped)?)?;
322 let class_inst = image.pointer(data + p).ok_or_else(unmapped)?;
323 let argc = image.pointer(class_inst).ok_or_else(unmapped)?;
325 let argv = image.pointer(class_inst + p).ok_or_else(unmapped)?;
326 if argc > 64 {
327 return Err(Error::Binary(format!(
328 "generic instance at {:#x} has {} arguments",
329 data, argc
330 )));
331 }
332 let args = (0..argc)
333 .map(|i| {
334 let arg = image.pointer(argv + i * p).ok_or_else(unmapped)?;
335 read_type(image, arg, depth + 1)
336 })
337 .collect::<Result<_>>()?;
338 TypeKind::GenericInst { generic, args }
339 }
340 element::FNPTR => TypeKind::FnPtr,
341 0x01..=0x0E | element::TYPEDBYREF | 0x18 | 0x19 | element::OBJECT => {
342 TypeKind::Primitive(element)
343 }
344 other => TypeKind::Unknown(other),
345 };
346 Ok(Il2CppType { kind, attrs, byref })
347}
348
349fn primitive_name(element: u8) -> &'static str {
350 match element {
351 0x01 => "void",
352 0x02 => "bool",
353 0x03 => "char",
354 0x04 => "sbyte",
355 0x05 => "byte",
356 0x06 => "short",
357 0x07 => "ushort",
358 0x08 => "int",
359 0x09 => "uint",
360 0x0A => "long",
361 0x0B => "ulong",
362 0x0C => "float",
363 0x0D => "double",
364 0x0E => "string",
365 0x16 => "TypedReference",
366 0x18 => "nint",
367 0x19 => "nuint",
368 0x1C => "object",
369 _ => "?",
370 }
371}
372
373fn strip_arity(name: &str) -> String {
375 let mut out = String::with_capacity(name.len());
376 let mut chars = name.chars().peekable();
377 while let Some(c) = chars.next() {
378 if c == '`' {
379 while chars.peek().is_some_and(|d| d.is_ascii_digit()) {
380 chars.next();
381 }
382 } else {
383 out.push(c);
384 }
385 }
386 out
387}
388
389impl Il2CppType {
390 pub fn name(&self, metadata: &Metadata) -> String {
392 let name = match &self.kind {
393 TypeKind::Primitive(e) => primitive_name(*e).to_owned(),
394 TypeKind::Class(t) | TypeKind::ValueType(t) => metadata.type_full_name(*t),
395 TypeKind::SzArray(e) => format!("{}[]", e.name(metadata)),
396 TypeKind::Array { element, rank } => {
397 format!(
398 "{}[{}]",
399 element.name(metadata),
400 ",".repeat(rank.saturating_sub(1) as usize)
401 )
402 }
403 TypeKind::Ptr(e) => format!("{}*", e.name(metadata)),
404 TypeKind::GenericInst { generic, args } => {
405 let base = strip_arity(&generic.name(metadata));
406 let args: Vec<String> = args.iter().map(|a| a.name(metadata)).collect();
407 format!("{}<{}>", base, args.join(", "))
408 }
409 TypeKind::Var(i) | TypeKind::MVar(i) => metadata
410 .generic_parameters
411 .get(*i as usize)
412 .map(|g| metadata.string(g.name_index).to_owned())
413 .unwrap_or_else(|| format!("T{}", i)),
414 TypeKind::FnPtr => "fnptr".to_owned(),
415 TypeKind::Unknown(e) => format!("<unknown {:#x}>", e),
416 };
417 if self.byref {
418 format!("ref {}", name)
419 } else {
420 name
421 }
422 }
423}