1pub use pewter::image::{ElfImage, LoadedImage, PeImage};
24
25use hao::dotnet::signature::{ElementType, PrimitiveType};
26
27use crate::{
28 error::{Error, Result},
29 metadata::{Metadata, TypeDefinitionIndex},
30};
31
32#[derive(Debug, Clone, PartialEq)]
36#[cfg_attr(feature = "reflect", derive(facet::Facet))]
37#[cfg_attr(feature = "reflect", repr(C))]
38pub enum TypeKind {
39 Primitive(PrimitiveType),
41 Class(TypeDefinitionIndex),
43 ValueType(TypeDefinitionIndex),
45 SzArray(Box<Il2CppType>),
47 Array {
49 element: Box<Il2CppType>,
51 rank: u8,
53 },
54 Ptr(Box<Il2CppType>),
56 GenericInst {
58 generic: Box<Il2CppType>,
60 args: Vec<Il2CppType>,
62 },
63 Var(i32),
65 MVar(i32),
67 FnPtr,
69 Unknown(u8),
71}
72
73#[derive(Debug, Clone, PartialEq)]
76#[cfg_attr(feature = "reflect", derive(facet::Facet))]
77pub struct Il2CppType {
78 pub kind: TypeKind,
80 pub attrs: u16,
83 pub byref: bool,
85}
86
87#[derive(Debug, Clone, PartialEq, Eq)]
89#[cfg_attr(feature = "reflect", derive(facet::Facet))]
90pub struct MetadataRegistration {
93 pub address: u64,
95 pub generic_classes: (u64, u64),
97 pub generic_insts: (u64, u64),
99 pub generic_method_table: (u64, u64),
101 pub types: (u64, u64),
103 pub method_specs: (u64, u64),
105 pub field_offsets: (u64, u64),
107 pub type_definition_sizes: (u64, u64),
109}
110
111impl MetadataRegistration {
112 pub fn find(image: &impl LoadedImage, metadata: &Metadata) -> Result<Self> {
115 let p = image.pointer_size();
116 let count = metadata.type_definitions.len() as u64;
117 let word = |v: u64| image.pointer(v).unwrap_or(0);
118 let pair = |v: u64| (word(v), word(v + p));
119 let mut found = Vec::new();
120 for segment in image.data_segments() {
121 let start = segment.0;
122 for vaddr in image
124 .pointer_slots(segment)
125 .filter(|v| *v >= start + 10 * p)
126 {
127 if word(vaddr) == count
128 && word(vaddr + 2 * p) == count
129 && image.is_mapped(word(vaddr + p))
130 && image.is_mapped(word(vaddr + 3 * p))
131 {
132 let base = vaddr - 10 * p;
133 let types = pair(base + 6 * p);
134 if types.0 >= count && image.is_mapped(types.1) {
135 found.push(Self {
136 address: base,
137 generic_classes: pair(base),
138 generic_insts: pair(base + 2 * p),
139 generic_method_table: pair(base + 4 * p),
140 types,
141 method_specs: pair(base + 8 * p),
142 field_offsets: pair(base + 10 * p),
143 type_definition_sizes: pair(base + 12 * p),
144 });
145 }
146 }
147 }
148 }
149 match found.len() {
150 1 => Ok(found.remove(0)),
151 0 => Err(Error::Binary("MetadataRegistration not found".into())),
152 n => Err(Error::Binary(format!(
153 "{} candidates for MetadataRegistration",
154 n
155 ))),
156 }
157 }
158}
159
160#[derive(Debug, Clone)]
162#[cfg_attr(feature = "reflect", derive(facet::Facet))]
163pub struct CodeGenModule {
164 pub name: String,
166 pub method_pointers: Vec<u64>,
169}
170
171#[derive(Debug, Clone)]
174#[cfg_attr(feature = "reflect", derive(facet::Facet))]
175pub struct CodeRegistration {
176 pub modules: Vec<CodeGenModule>,
178}
179
180impl CodeRegistration {
181 pub fn find(image: &impl LoadedImage, metadata: &Metadata) -> Result<Self> {
185 let p = image.pointer_size();
186 let image_count = metadata.images.len() as u64;
187 let image_names: std::collections::HashSet<&str> = metadata
188 .images
189 .iter()
190 .map(|i| metadata.image_name(i))
191 .collect();
192
193 for segment in image.data_segments() {
197 let start = segment.0;
198 for vaddr in image.pointer_slots(segment).filter(|v| *v >= start) {
199 let array_ptr = match image.pointer(vaddr) {
200 Some(a) if image.is_mapped(a) => a,
201 _ => continue,
202 };
203 let first_module = match image.pointer(array_ptr) {
204 Some(m) if image.is_mapped(m) => m,
205 _ => continue,
206 };
207 let name_ptr = match image.pointer(first_module) {
208 Some(n) if image.is_mapped(n) => n,
209 _ => continue,
210 };
211 let name = match image.c_str(name_ptr) {
212 Some(n) => n,
213 None => continue,
214 };
215 if !image_names.contains(name.as_str()) {
216 continue;
217 }
218
219 let module_ptrs = match image.pointers(array_ptr, image_count) {
220 Some(ptrs) => ptrs,
221 None => continue,
222 };
223
224 let mut modules = Vec::with_capacity(image_count as usize);
226 let mut ok = true;
227 for module_ptr in &module_ptrs {
228 let mp = *module_ptr;
229 if !image.is_mapped(mp) {
230 ok = false;
231 break;
232 }
233 let mn_ptr = image.pointer(mp).unwrap_or(0);
234 let mn = match image.c_str(mn_ptr) {
235 Some(n) if image_names.contains(n.as_str()) => n,
236 _ => {
237 ok = false;
238 break;
239 }
240 };
241 let raw_count = image.pointer(mp + p).unwrap_or(0);
246 let mp_count = if raw_count < 100_000 {
247 raw_count
248 } else {
249 image.u32(mp + p).unwrap_or(0) as u64
250 };
251 let mp_array = image.pointer(mp + 2 * p).unwrap_or(0);
252 let pointers = if mp_count > 0 && image.is_mapped(mp_array) {
253 image.pointers(mp_array, mp_count).unwrap_or_default()
254 } else {
255 Vec::new()
256 };
257 modules.push(CodeGenModule {
258 name: mn,
259 method_pointers: pointers,
260 });
261 }
262 if ok && modules.len() == image_count as usize {
263 return Ok(Self { modules });
264 }
265 }
266 }
267 Err(Error::Binary("CodeRegistration not found".into()))
268 }
269}
270
271#[cfg_attr(feature = "reflect", derive(facet::Facet))]
273pub struct Binary {
274 pub metadata_registration: MetadataRegistration,
276 pub code_registration: Option<CodeRegistration>,
279 pub types: Vec<Il2CppType>,
281}
282
283impl Binary {
284 pub fn read(image: &impl LoadedImage, metadata: &Metadata) -> Result<Self> {
291 let registration = MetadataRegistration::find(image, metadata)?;
292 let (count, array) = registration.types;
293 let types = image
294 .pointers(array, count)
295 .ok_or_else(|| Error::Binary("the Il2CppType pointer table is unmapped".into()))?
296 .into_iter()
297 .map(|address| read_type(image, address, 0))
298 .collect::<Result<Vec<_>>>()?;
299 let code_registration = CodeRegistration::find(image, metadata).ok();
300 Ok(Self {
301 metadata_registration: registration,
302 code_registration,
303 types,
304 })
305 }
306
307 pub fn type_at(&self, index: i32) -> Option<&Il2CppType> {
310 usize::try_from(index).ok().and_then(|i| self.types.get(i))
311 }
312
313 pub fn method_pointer(&self, image_name: &str, token: u32) -> Option<u64> {
316 let code = self.code_registration.as_ref()?;
317 let module = code.modules.iter().find(|m| m.name == image_name)?;
318 let rid = (token & 0x00FF_FFFF) as usize;
319 if rid == 0 {
320 return None;
321 }
322 let ptr = *module.method_pointers.get(rid - 1)?;
323 if ptr == 0 {
324 None
325 } else {
326 Some(ptr)
327 }
328 }
329}
330
331fn read_type(image: &impl LoadedImage, address: u64, depth: usize) -> Result<Il2CppType> {
332 if depth > 32 {
333 return Err(Error::Binary("type nesting is too deep".into()));
334 }
335 let p = image.pointer_size();
336 let unmapped = || Error::Binary(format!("Il2CppType at {:#x} is unmapped", address));
337 let data = image.pointer(address).ok_or_else(unmapped)?;
338 let bits = image.u32(address + p).ok_or_else(unmapped)?;
339 let attrs = (bits & 0xFFFF) as u16;
340 let element = ((bits >> 16) & 0xFF) as u8;
341 let byref = (bits >> 29) & 1 == 1;
342 let nested = |address: u64| read_type(image, address, depth + 1).map(Box::new);
343
344 let kind = match ElementType::from_repr(element) {
345 Some(ElementType::Class) => TypeKind::Class(data as i32),
346 Some(ElementType::ValueType) => TypeKind::ValueType(data as i32),
347 Some(ElementType::Var) => TypeKind::Var(data as i32),
348 Some(ElementType::MVar) => TypeKind::MVar(data as i32),
349 Some(ElementType::SzArray) => TypeKind::SzArray(nested(data)?),
350 Some(ElementType::Ptr) => TypeKind::Ptr(nested(data)?),
351 Some(ElementType::Array) => TypeKind::Array {
352 element: nested(image.pointer(data).ok_or_else(unmapped)?)?,
353 rank: image.u8(data + p).ok_or_else(unmapped)?,
354 },
355 Some(ElementType::GenericInst) => {
356 let generic = nested(image.pointer(data).ok_or_else(unmapped)?)?;
358 let class_inst = image.pointer(data + p).ok_or_else(unmapped)?;
359 let argc = image.pointer(class_inst).ok_or_else(unmapped)?;
361 let argv = image.pointer(class_inst + p).ok_or_else(unmapped)?;
362 if argc > 64 {
363 return Err(Error::Binary(format!(
364 "generic instance at {:#x} has {} arguments",
365 data, argc
366 )));
367 }
368 let args = (0..argc)
369 .map(|i| {
370 let arg = image.pointer(argv + i * p).ok_or_else(unmapped)?;
371 read_type(image, arg, depth + 1)
372 })
373 .collect::<Result<_>>()?;
374 TypeKind::GenericInst { generic, args }
375 }
376 Some(ElementType::FnPtr) => TypeKind::FnPtr,
377 _ => match PrimitiveType::from_repr(element) {
378 Some(p) => TypeKind::Primitive(p),
379 None => TypeKind::Unknown(element),
380 },
381 };
382 Ok(Il2CppType { kind, attrs, byref })
383}
384
385fn strip_arity(name: &str) -> String {
387 let mut out = String::with_capacity(name.len());
388 let mut chars = name.chars().peekable();
389 while let Some(c) = chars.next() {
390 if c == '`' {
391 while chars.peek().is_some_and(|d| d.is_ascii_digit()) {
392 chars.next();
393 }
394 } else {
395 out.push(c);
396 }
397 }
398 out
399}
400
401impl Il2CppType {
402 pub fn name(&self, metadata: &Metadata) -> String {
404 let name = match &self.kind {
405 TypeKind::Primitive(p) => p.keyword().to_owned(),
406 TypeKind::Class(t) | TypeKind::ValueType(t) => metadata.type_full_name(*t),
407 TypeKind::SzArray(e) => format!("{}[]", e.name(metadata)),
408 TypeKind::Array { element, rank } => {
409 format!(
410 "{}[{}]",
411 element.name(metadata),
412 ",".repeat(rank.saturating_sub(1) as usize)
413 )
414 }
415 TypeKind::Ptr(e) => format!("{}*", e.name(metadata)),
416 TypeKind::GenericInst { generic, args } => {
417 let base = strip_arity(&generic.name(metadata));
418 let args: Vec<String> = args.iter().map(|a| a.name(metadata)).collect();
419 format!("{}<{}>", base, args.join(", "))
420 }
421 TypeKind::Var(i) | TypeKind::MVar(i) => metadata
422 .generic_parameters
423 .get(*i as usize)
424 .map(|g| metadata.string(g.name_index).to_owned())
425 .unwrap_or_else(|| format!("T{}", i)),
426 TypeKind::FnPtr => "fnptr".to_owned(),
427 TypeKind::Unknown(e) => format!("<unknown {:#x}>", e),
428 };
429 if self.byref {
430 format!("ref {}", name)
431 } else {
432 name
433 }
434 }
435}