Skip to main content

hao_il2cpp/
generate.rs

1//! Generates declaration assemblies ("dummy DLLs") from Il2Cpp metadata: every
2//! type, field, method signature, property and event, with stub method bodies.
3
4use std::collections::HashMap;
5
6use hao::{
7    dotnet::{
8        entries::MemberRef,
9        entries::{
10            AssemblyRef, CANamedArgument, CAType, CAValue, Constant, CustomAttribute,
11            CustomAttributeCtor, CustomAttributeValue, Entry, Event, Field, GenericParam,
12            GenericParamConstraint, InterfaceImpl, MemberRefParent, Method, Param, Property,
13            ResolutionScope, TypeDef, TypeDefOrRef, TypeRef, TypeSpec, Version,
14        },
15        il::{Instruction, MethodBody, OpCode},
16        md::streams::tables_stream::{
17            EventFlags, FieldFlags, GenericParamFlags, MethodFlags, MethodImplFlags, ParamFlags,
18            PropertyFlags, TypeAttributes,
19        },
20        module::{ModuleKind, TargetRuntime},
21        signature::{
22            ArrayShape, CallingConvention, ElementType, FieldSig, MemberRefSig, MethodSig,
23            PrimitiveType, PropertySig, SignatureFlags, TypeSig,
24        },
25    },
26    Module,
27};
28
29use crate::{
30    binary::{element, Binary, Il2CppType, TypeKind},
31    error::Result,
32    metadata::{Metadata, TypeDefinitionIndex},
33};
34
35/// One generated assembly per Il2Cpp image.
36#[cfg_attr(feature = "reflect", derive(facet::Facet))]
37pub struct GeneratedAssembly {
38    /// The image name, e.g. `Assembly-CSharp.dll`.
39    pub file_name: String,
40    pub module: Module,
41}
42
43struct Generator<'a> {
44    metadata: &'a Metadata,
45    binary: &'a Binary,
46    modules: Vec<Module>,
47    types: Vec<Entry<TypeDef>>,
48    type_image: Vec<usize>,
49    type_refs: Vec<HashMap<TypeDefinitionIndex, Entry<TypeRef>>>,
50    primitive_types: HashMap<u8, TypeDefinitionIndex>,
51    default_member: Option<TypeDefinitionIndex>,
52    /// `attribute_data_range` entries `(token, start_offset)`, in global order.
53    attribute_ranges: Vec<(u32, u32)>,
54    /// Per image, a map from a metadata token to its index into `attribute_ranges`.
55    /// Tokens are only unique within an image, so the lookup is scoped per image.
56    attribute_tokens: Vec<HashMap<u32, usize>>,
57}
58
59/// A fixed constructor argument recovered from the attribute blob, or `Skip` when
60/// the value was parsed (so the stream stays aligned) but can't be represented
61/// faithfully — in which case the whole attribute is dropped rather than guessed.
62enum Arg {
63    Value(CAValue),
64    Skip,
65}
66
67/// The il2cpp attribute blob tags that aren't plain ECMA element types.
68const TAG_ENUM: u8 = 0x55;
69const TAG_TYPE_INDEX: u8 = 0xFF;
70
71fn read_compressed_u32(data: &[u8], position: &mut usize) -> Option<u32> {
72    let mut next = || {
73        let b = *data.get(*position)?;
74        *position += 1;
75        Some(b as u32)
76    };
77    let b = next()?;
78    Some(if b & 0x80 == 0 {
79        b
80    } else if b & 0xC0 == 0x80 {
81        ((b & 0x3F) << 8) | next()?
82    } else if b & 0xE0 == 0xC0 {
83        ((b & 0x1F) << 24) | (next()? << 16) | (next()? << 8) | next()?
84    } else if b == 0xF0 {
85        u32::from_le_bytes([next()? as u8, next()? as u8, next()? as u8, next()? as u8])
86    } else if b == 0xFE {
87        u32::MAX - 1
88    } else if b == 0xFF {
89        u32::MAX
90    } else {
91        return None;
92    })
93}
94
95fn read_compressed_i32(data: &[u8], position: &mut usize) -> Option<i32> {
96    let encoded = read_compressed_u32(data, position)?;
97    if encoded == u32::MAX {
98        return Some(i32::MIN);
99    }
100    let value = (encoded >> 1) as i32;
101    Some(if encoded & 1 != 0 { -value - 1 } else { value })
102}
103
104fn read_u8(data: &[u8], position: &mut usize) -> Option<u8> {
105    let b = *data.get(*position)?;
106    *position += 1;
107    Some(b)
108}
109
110fn read_fixed<const N: usize>(data: &[u8], position: &mut usize) -> Option<[u8; N]> {
111    let bytes = data.get(*position..*position + N)?;
112    *position += N;
113    Some(bytes.try_into().unwrap())
114}
115
116/// A serialized string (II.23.3): a compressed length, or `-1` for `null`.
117fn read_ser_string(data: &[u8], position: &mut usize) -> Option<Option<String>> {
118    let len = read_compressed_i32(data, position)?;
119    if len < 0 {
120        return Some(None);
121    }
122    let len = len as usize;
123    let bytes = data.get(*position..*position + len)?;
124    *position += len;
125    Some(Some(String::from_utf8_lossy(bytes).into_owned()))
126}
127
128/// Whether a constructor parameter would need ECMA boxing to serialize (an
129/// `object` or `object[]` parameter). We don't emit boxed fixed arguments, so such
130/// attributes are dropped rather than mis-encoded.
131fn needs_boxing(sig: &TypeSig) -> bool {
132    match sig.unmodified() {
133        TypeSig::Primitive(PrimitiveType::Object) => true,
134        TypeSig::Class(t) => t.full_name_is("System", "Object"),
135        TypeSig::SzArray(element) => needs_boxing(element),
136        _ => false,
137    }
138}
139
140/// Decodes a constant from the default value data (v29 compresses 32 bit values and string lengths).
141fn constant(element_type: u8, data: &[u8]) -> Option<Constant> {
142    let mut position = 0;
143    let fixed = |n: usize| data.get(..n).map(<[u8]>::to_vec);
144    let value = match element_type {
145        0x02 | 0x04 | 0x05 => fixed(1)?,
146        0x03 | 0x06 | 0x07 => fixed(2)?,
147        0x08 => read_compressed_i32(data, &mut position)?
148            .to_le_bytes()
149            .to_vec(),
150        0x09 => read_compressed_u32(data, &mut position)?
151            .to_le_bytes()
152            .to_vec(),
153        0x0A | 0x0B | 0x0D => fixed(8)?,
154        0x0C => fixed(4)?,
155        element::STRING => {
156            let length = read_compressed_i32(data, &mut position)?;
157            if length < 0 {
158                return None;
159            }
160            let bytes = data.get(position..position + length as usize)?;
161            let text = std::str::from_utf8(bytes).ok()?;
162            text.encode_utf16().flat_map(u16::to_le_bytes).collect()
163        }
164        _ => return None,
165    };
166    Some(Constant {
167        element_type: ElementType::from_repr(element_type)?,
168        value,
169    })
170}
171
172impl<'a> Generator<'a> {
173    fn new(metadata: &'a Metadata, binary: &'a Binary) -> Self {
174        let mut type_image = vec![0; metadata.type_definitions.len()];
175        let modules = metadata
176            .images
177            .iter()
178            .enumerate()
179            .map(|(i, image)| {
180                for t in metadata.image_types(image) {
181                    if let Some(slot) = type_image.get_mut(t as usize) {
182                        *slot = i;
183                    }
184                }
185                let assembly = &metadata.assemblies[image.assembly_index as usize];
186                let file_name = metadata.image_name(image);
187                let name = metadata.string(assembly.name_index);
188                let mut module = Module::new(name, ModuleKind::Dll, TargetRuntime::NetFramework);
189                module.module.get_mut().name = file_name.to_owned();
190                if let Some(manifest) = &module.assembly {
191                    let mut manifest = manifest.get_mut();
192                    manifest.version = version(assembly.version);
193                }
194                if name == "mscorlib" {
195                    module.assembly_refs.clear();
196                }
197                module.types.clear();
198                module
199            })
200            .collect::<Vec<_>>();
201
202        let names = [
203            (0x01, "Void"),
204            (0x02, "Boolean"),
205            (0x03, "Char"),
206            (0x04, "SByte"),
207            (0x05, "Byte"),
208            (0x06, "Int16"),
209            (0x07, "UInt16"),
210            (0x08, "Int32"),
211            (0x09, "UInt32"),
212            (0x0A, "Int64"),
213            (0x0B, "UInt64"),
214            (0x0C, "Single"),
215            (0x0D, "Double"),
216            (0x0E, "String"),
217            (0x16, "TypedReference"),
218            (0x18, "IntPtr"),
219            (0x19, "UIntPtr"),
220            (0x1C, "Object"),
221        ];
222        let mut primitive_types = HashMap::new();
223        for (i, t) in metadata.type_definitions.iter().enumerate() {
224            if metadata.string(t.namespace_index) == "System" && t.declaring_type_index < 0 {
225                let name = metadata.string(t.name_index);
226                if let Some((element, _)) = names.iter().find(|(_, n)| *n == name) {
227                    primitive_types.insert(*element, i as TypeDefinitionIndex);
228                }
229            }
230        }
231
232        let default_member = (0..metadata.type_definitions.len() as i32)
233            .find(|i| metadata.type_full_name(*i) == "System.Reflection.DefaultMemberAttribute");
234
235        // Custom attribute data (v29+): the global range table maps each entity's
236        // metadata token to an offset into the `attribute_data` blob. The ranges are
237        // partitioned per image; a token is only unique within its image.
238        let attribute_ranges = metadata.attribute_data_ranges();
239        let attribute_tokens = metadata
240            .images
241            .iter()
242            .map(|image| {
243                let start = image.custom_attribute_start.max(0) as usize;
244                // v29 stores the count; v39 (Unity 6) leaves it zero, so no custom
245                // attributes are recovered there until its image layout is confirmed.
246                let end = start
247                    .saturating_add(image.custom_attribute_count as usize)
248                    .min(attribute_ranges.len());
249                (start.min(end)..end)
250                    .map(|i| (attribute_ranges[i].0, i))
251                    .collect()
252            })
253            .collect();
254
255        Self {
256            default_member,
257            type_refs: vec![HashMap::new(); modules.len()],
258            modules,
259            types: Vec::new(),
260            type_image,
261            primitive_types,
262            attribute_ranges,
263            attribute_tokens,
264            metadata,
265            binary,
266        }
267    }
268
269    fn assembly_ref(&mut self, module: usize, image: usize) -> Entry<AssemblyRef> {
270        let image = &self.metadata.images[image];
271        let assembly = &self.metadata.assemblies[image.assembly_index as usize];
272        let token = if assembly.public_key_token == [0; 8] {
273            Vec::new()
274        } else {
275            assembly.public_key_token.to_vec()
276        };
277        self.modules[module].add_assembly_ref(
278            self.metadata.string(assembly.name_index),
279            version(assembly.version),
280            &token,
281        )
282    }
283
284    /// A reference from `module` to type definition `index`.
285    fn type_ref(&mut self, module: usize, index: TypeDefinitionIndex) -> TypeDefOrRef {
286        if self.type_image[index as usize] == module {
287            return TypeDefOrRef::TypeDef(self.types[index as usize].clone());
288        }
289        if let Some(existing) = self.type_refs[module].get(&index) {
290            return TypeDefOrRef::TypeRef(existing.clone());
291        }
292        let def = &self.metadata.type_definitions[index as usize];
293        let name = self.metadata.string(def.name_index).to_owned();
294        let scope = match self.metadata.declaring_type_definition(index) {
295            Some(parent) => match self.type_ref(module, parent) {
296                TypeDefOrRef::TypeRef(r) => ResolutionScope::TypeRef(r),
297                _ => unreachable!("the parent is in another image"),
298            },
299            None => ResolutionScope::AssemblyRef(
300                self.assembly_ref(module, self.type_image[index as usize]),
301            ),
302        };
303        let namespace = if matches!(scope, ResolutionScope::TypeRef(_)) {
304            String::new()
305        } else {
306            self.metadata.string(def.namespace_index).to_owned()
307        };
308        let type_ref = Entry::new(TypeRef::new(scope, namespace, name));
309        self.type_refs[module].insert(index, type_ref.clone());
310        TypeDefOrRef::TypeRef(type_ref)
311    }
312
313    fn generic_number(&self, index: i32) -> u32 {
314        self.metadata
315            .generic_parameters
316            .get(index as usize)
317            .map_or(0, |g| g.num as u32)
318    }
319
320    fn sig(&mut self, module: usize, ty: &Il2CppType) -> TypeSig {
321        let sig = match &ty.kind {
322            TypeKind::Primitive(e) => match PrimitiveType::from_repr(*e) {
323                Some(p) => TypeSig::Primitive(p),
324                None => TypeSig::OBJECT,
325            },
326            TypeKind::Class(t) => TypeSig::Class(self.type_ref(module, *t)),
327            TypeKind::ValueType(t) => TypeSig::ValueType(self.type_ref(module, *t)),
328            TypeKind::SzArray(e) => TypeSig::SzArray(Box::new(self.sig(module, e))),
329            TypeKind::Array { element, rank } => TypeSig::Array {
330                element: Box::new(self.sig(module, element)),
331                shape: ArrayShape {
332                    rank: (*rank).max(1) as u32,
333                    ..Default::default()
334                },
335            },
336            TypeKind::Ptr(e) => TypeSig::Ptr(Box::new(self.sig(module, e))),
337            TypeKind::GenericInst { generic, args } => TypeSig::GenericInst {
338                generic: Box::new(self.sig(module, generic)),
339                args: args.iter().map(|a| self.sig(module, a)).collect(),
340            },
341            TypeKind::Var(i) => TypeSig::Var(self.generic_number(*i)),
342            TypeKind::MVar(i) => TypeSig::MVar(self.generic_number(*i)),
343            TypeKind::FnPtr | TypeKind::Unknown(_) => TypeSig::Primitive(PrimitiveType::I),
344        };
345        if ty.byref {
346            TypeSig::ByRef(Box::new(sig))
347        } else {
348            sig
349        }
350    }
351
352    fn sig_at(&mut self, module: usize, index: i32) -> TypeSig {
353        match self.binary.type_at(index).cloned() {
354            Some(ty) => self.sig(module, &ty),
355            None => TypeSig::OBJECT,
356        }
357    }
358
359    fn type_def_or_ref(&mut self, module: usize, index: i32) -> Option<TypeDefOrRef> {
360        let ty = self.binary.type_at(index)?.clone();
361        Some(match &ty.kind {
362            TypeKind::Class(t) | TypeKind::ValueType(t) => self.type_ref(module, *t),
363            TypeKind::Primitive(e) => self.type_ref(module, *self.primitive_types.get(e)?),
364            _ => {
365                let signature = self.sig(module, &ty);
366                TypeDefOrRef::TypeSpec(Entry::new(TypeSpec {
367                    signature,
368                    custom_attributes: Vec::new(),
369                }))
370            }
371        })
372    }
373
374    fn generic_params(&mut self, module: usize, container: i32) -> Vec<Entry<GenericParam>> {
375        let params = self
376            .metadata
377            .generic_container_parameters(container)
378            .to_vec();
379        params
380            .iter()
381            .map(|g| {
382                let start = g.constraints_start.max(0) as usize;
383                let constraints = self
384                    .metadata
385                    .generic_parameter_constraints
386                    .get(start..start + g.constraints_count.max(0) as usize)
387                    .unwrap_or(&[])
388                    .to_vec()
389                    .into_iter()
390                    .filter_map(|c| self.type_def_or_ref(module, c))
391                    .map(|constraint| GenericParamConstraint {
392                        constraint,
393                        custom_attributes: Vec::new(),
394                    })
395                    .collect();
396                Entry::new(GenericParam {
397                    number: g.num,
398                    flags: GenericParamFlags::from_bits_retain(g.flags),
399                    name: self.metadata.string(g.name_index).to_owned(),
400                    constraints,
401                    custom_attributes: Vec::new(),
402                })
403            })
404            .collect()
405    }
406
407    /// `[DefaultMember(name)]`, which C# needs to see indexers.
408    fn default_member_attribute(&mut self, module: usize, name: &str) -> Option<CustomAttribute> {
409        let index = self.default_member?;
410        let signature = MethodSig::new_instance(TypeSig::VOID, vec![TypeSig::STRING]);
411        let constructor = match self.type_ref(module, index) {
412            TypeDefOrRef::TypeDef(def) => {
413                let ctor = def
414                    .get()
415                    .methods
416                    .iter()
417                    .find(|m| m.get().is_ctor() && m.get().signature == signature)
418                    .cloned()?;
419                CustomAttributeCtor::Method(ctor)
420            }
421            TypeDefOrRef::TypeRef(r) => CustomAttributeCtor::MemberRef(Entry::new(MemberRef {
422                parent: hao::dotnet::entries::MemberRefParent::TypeRef(r),
423                name: ".ctor".into(),
424                signature: MemberRefSig::Method(signature),
425                custom_attributes: Vec::new(),
426            })),
427            TypeDefOrRef::TypeSpec(_) => return None,
428        };
429        let value = CustomAttributeValue {
430            fixed: vec![name.into()],
431            named: Vec::new(),
432        };
433        CustomAttribute::new(constructor, &value).ok()
434    }
435
436    // ---- Recovered custom attributes (v29+) --------------------------------
437    //
438    // il2cpp v29 reintroduced per-token attribute data into metadata (earlier
439    // versions kept only the attribute *types*, with arguments baked into
440    // generated C++). The `attribute_data` blob stores, for each token, the
441    // applied attributes with their constructor index and full argument values,
442    // and `attribute_data_range` maps each token to its slice of that blob. We
443    // reconstruct the attributes faithfully from this, re-encoding into ECMA-335
444    // custom attribute blobs. Fidelity caveats (we drop rather than guess):
445    //  * `object`/`object[]` constructor parameters would need ECMA boxing we
446    //    don't emit, so those attributes are skipped (`needs_boxing`).
447    //  * named arguments are typed by their recovered *value* (correct unless the
448    //    field/property is declared `object`, where the static type is lost).
449    //  * generic/array `System.Type` arguments and nested-array element types
450    //    aren't reconstructed, so such attributes are skipped.
451    // v39 (Unity 6) uses the same blob format, but its image record doesn't yet
452    // expose the per-image attribute count, so nothing is recovered there.
453
454    /// The `attribute_data` bytes for `token` in `module`'s image, if any.
455    fn attribute_blob(&self, module: usize, token: u32) -> Option<Vec<u8>> {
456        let index = *self.attribute_tokens.get(module)?.get(&token)?;
457        let blob = self.metadata.attribute_data();
458        let start = self.attribute_ranges[index].1 as usize;
459        let end = self
460            .attribute_ranges
461            .get(index + 1)
462            .map_or(blob.len(), |r| r.1 as usize)
463            .clamp(start, blob.len());
464        blob.get(start..end).map(<[u8]>::to_vec)
465    }
466
467    /// Resolves an `Il2CppType` index to the type definition it names, if it is a
468    /// plain class or value type.
469    fn type_def_index_of(&self, il_type_index: i32) -> Option<TypeDefinitionIndex> {
470        match &self.binary.type_at(il_type_index)?.kind {
471            TypeKind::Class(d) | TypeKind::ValueType(d) => Some(*d),
472            _ => None,
473        }
474    }
475
476    /// The ECMA element type byte backing an enum's values.
477    fn enum_underlying(&self, def: TypeDefinitionIndex) -> Option<u8> {
478        let ty = self.metadata.type_definitions.get(def as usize)?;
479        // v29 points `element_type_index` at the underlying primitive; v39 drops
480        // it, so fall back to the enum's instance field (`value__`).
481        if ty.element_type_index >= 0 {
482            if let Some(TypeKind::Primitive(e)) =
483                self.binary.type_at(ty.element_type_index).map(|t| &t.kind)
484            {
485                return Some(*e);
486            }
487        }
488        match &self
489            .binary
490            .type_at(self.metadata.type_fields(ty).first()?.type_index)?
491            .kind
492        {
493            TypeKind::Primitive(e) => Some(*e),
494            _ => None,
495        }
496    }
497
498    /// `Namespace.Outer+Inner`, the reflection form used in serialized attributes.
499    fn serialized_type_name(&self, def: TypeDefinitionIndex) -> Option<String> {
500        if def < 0 || def as usize >= self.metadata.type_definitions.len() {
501            return None;
502        }
503        Some(self.metadata.type_full_name(def).replace('/', "+"))
504    }
505
506    /// A reflection type name for a `System.Type` argument's `Il2CppType` index.
507    fn type_argument_name(&self, il_type_index: i32) -> Option<String> {
508        match &self.binary.type_at(il_type_index)?.kind {
509            TypeKind::Class(d) | TypeKind::ValueType(d) => self.serialized_type_name(*d),
510            TypeKind::Primitive(e) => self.serialized_type_name(*self.primitive_types.get(e)?),
511            _ => None,
512        }
513    }
514
515    /// Reads a self-describing type tag (`ReadEncodedTypeEnum`): the element type
516    /// byte, and the enum's definition when the tag is an enum (the byte is then the
517    /// enum's underlying primitive). `None` when an enum can't be resolved, as its
518    /// value width is then unknown.
519    fn read_encoded_type(
520        &self,
521        blob: &[u8],
522        pos: &mut usize,
523    ) -> Option<(u8, Option<TypeDefinitionIndex>)> {
524        let tag = read_u8(blob, pos)?;
525        if tag == TAG_ENUM {
526            let type_index = read_compressed_i32(blob, pos)?;
527            let def = self.type_def_index_of(type_index)?;
528            Some((self.enum_underlying(def)?, Some(def)))
529        } else {
530            Some((tag, None))
531        }
532    }
533
534    /// Reads one attribute argument (`ReadAttributeDataValue`), always advancing
535    /// past a well-formed value. `Arg::Skip` marks a value that parsed but can't be
536    /// represented, so the attribute is dropped without mis-encoding it.
537    fn read_arg(&self, blob: &[u8], pos: &mut usize) -> Option<Arg> {
538        let (tag, enum_def) = self.read_encoded_type(blob, pos)?;
539        self.read_value(blob, pos, tag, enum_def)
540    }
541
542    fn read_value(
543        &self,
544        blob: &[u8],
545        pos: &mut usize,
546        tag: u8,
547        enum_def: Option<TypeDefinitionIndex>,
548    ) -> Option<Arg> {
549        use element::*;
550        if let Some(def) = enum_def {
551            // Read the underlying value, then wrap it with the enum's name.
552            let Arg::Value(inner) = self.read_value(blob, pos, tag, None)? else {
553                return Some(Arg::Skip);
554            };
555            return Some(match self.serialized_type_name(def) {
556                Some(type_name) => Arg::Value(CAValue::Enum {
557                    type_name,
558                    value: Box::new(inner),
559                }),
560                None => Arg::Skip,
561            });
562        }
563        let value = match tag {
564            BOOLEAN => CAValue::Bool(read_u8(blob, pos)? != 0),
565            I1 => CAValue::I1(read_u8(blob, pos)? as i8),
566            U1 => CAValue::U1(read_u8(blob, pos)?),
567            CHAR => CAValue::Char(u16::from_le_bytes(read_fixed(blob, pos)?)),
568            I2 => CAValue::I2(i16::from_le_bytes(read_fixed(blob, pos)?)),
569            U2 => CAValue::U2(u16::from_le_bytes(read_fixed(blob, pos)?)),
570            I4 => CAValue::I4(read_compressed_i32(blob, pos)?),
571            U4 => CAValue::U4(read_compressed_u32(blob, pos)?),
572            I8 => CAValue::I8(i64::from_le_bytes(read_fixed(blob, pos)?)),
573            U8 => CAValue::U8(u64::from_le_bytes(read_fixed(blob, pos)?)),
574            R4 => CAValue::R4(f32::from_le_bytes(read_fixed(blob, pos)?)),
575            R8 => CAValue::R8(f64::from_le_bytes(read_fixed(blob, pos)?)),
576            STRING => CAValue::String(read_ser_string(blob, pos)?),
577            TAG_TYPE_INDEX => {
578                let type_index = read_compressed_i32(blob, pos)?;
579                if type_index < 0 {
580                    CAValue::Type(None)
581                } else {
582                    match self.type_argument_name(type_index) {
583                        Some(name) => CAValue::Type(Some(name)),
584                        None => return Some(Arg::Skip),
585                    }
586                }
587            }
588            SZARRAY => return self.read_array(blob, pos),
589            _ => return None,
590        };
591        Some(Arg::Value(value))
592    }
593
594    fn read_array(&self, blob: &[u8], pos: &mut usize) -> Option<Arg> {
595        let len = read_compressed_i32(blob, pos)?;
596        if len < 0 {
597            return Some(Arg::Value(CAValue::Array {
598                element: CAType::Object,
599                values: None,
600            }));
601        }
602        let (base_tag, base_enum) = self.read_encoded_type(blob, pos)?;
603        let different = read_u8(blob, pos)? == 1;
604        let mut values = Vec::new();
605        let mut skip = false;
606        for _ in 0..len as usize {
607            let (tag, enum_def) = if different {
608                self.read_encoded_type(blob, pos)?
609            } else {
610                (base_tag, base_enum)
611            };
612            match self.read_value(blob, pos, tag, enum_def)? {
613                Arg::Value(v) => values.push(v),
614                Arg::Skip => skip = true,
615            }
616        }
617        if skip {
618            return Some(Arg::Skip);
619        }
620        Some(match self.array_element_type(base_tag, base_enum) {
621            Some(element) => Arg::Value(CAValue::Array {
622                element,
623                values: Some(values),
624            }),
625            None => Arg::Skip,
626        })
627    }
628
629    fn array_element_type(&self, tag: u8, enum_def: Option<TypeDefinitionIndex>) -> Option<CAType> {
630        use element::*;
631        if let Some(def) = enum_def {
632            return Some(CAType::Enum {
633                type_name: self.serialized_type_name(def)?,
634                underlying: PrimitiveType::from_repr(tag)?,
635            });
636        }
637        Some(match tag {
638            TAG_TYPE_INDEX => CAType::Type,
639            BOOLEAN | CHAR | I1 | U1 | I2 | U2 | I4 | U4 | I8 | U8 | R4 | R8 | STRING => {
640                CAType::Primitive(PrimitiveType::from_repr(tag)?)
641            }
642            _ => return None,
643        })
644    }
645
646    /// The name of a named-argument field or property, from its declaring type and
647    /// member index (`ReadCustomAttributeNamedArgumentClassAndIndex`). Always
648    /// advances; the inner `None` means the member couldn't be resolved.
649    fn read_named_member(
650        &self,
651        blob: &[u8],
652        pos: &mut usize,
653        ctor_type: Option<TypeDefinitionIndex>,
654        is_field: bool,
655    ) -> Option<Option<String>> {
656        let member = read_compressed_i32(blob, pos)?;
657        let (decl, index) = if member >= 0 {
658            (ctor_type, member as usize)
659        } else {
660            let type_index = read_compressed_u32(blob, pos)? as TypeDefinitionIndex;
661            (Some(type_index), (-(member + 1)) as usize)
662        };
663        Some(decl.and_then(|d| self.member_name(d, index, is_field)))
664    }
665
666    fn member_name(
667        &self,
668        decl: TypeDefinitionIndex,
669        index: usize,
670        is_field: bool,
671    ) -> Option<String> {
672        let ty = self
673            .metadata
674            .type_definitions
675            .get(usize::try_from(decl).ok()?)?;
676        let name_index = if is_field {
677            let start = ty.field_start.max(0) as usize;
678            self.metadata.fields.get(start + index)?.name_index
679        } else {
680            let start = ty.property_start.max(0) as usize;
681            self.metadata.properties.get(start + index)?.name_index
682        };
683        Some(self.metadata.string(name_index).to_owned())
684    }
685
686    /// Parses one attribute's argument block: the fixed arguments, then the named
687    /// fields and properties. Must stay byte-aligned, so returns `None` (stopping
688    /// the token) on malformed data.
689    #[allow(clippy::type_complexity)]
690    fn parse_arguments(
691        &self,
692        blob: &[u8],
693        pos: &mut usize,
694        ctor_type: Option<TypeDefinitionIndex>,
695    ) -> Option<(Vec<Arg>, Vec<(bool, String, Arg)>)> {
696        let arg_count = read_compressed_u32(blob, pos)?;
697        let field_count = read_compressed_u32(blob, pos)?;
698        let property_count = read_compressed_u32(blob, pos)?;
699        let mut fixed = Vec::new();
700        for _ in 0..arg_count {
701            fixed.push(self.read_arg(blob, pos)?);
702        }
703        let mut named = Vec::new();
704        for (is_field, count) in [(true, field_count), (false, property_count)] {
705            for _ in 0..count {
706                let value = self.read_arg(blob, pos)?;
707                match self.read_named_member(blob, pos, ctor_type, is_field)? {
708                    Some(name) => named.push((is_field, name, value)),
709                    None => named.push((is_field, String::new(), Arg::Skip)),
710                }
711            }
712        }
713        Some((fixed, named))
714    }
715
716    /// The custom attributes applied to `token` in `module`, reconstructed from the
717    /// v29+ `attribute_data` blob.
718    fn custom_attributes(&mut self, module: usize, token: u32) -> Vec<CustomAttribute> {
719        let Some(blob) = self.attribute_blob(module, token) else {
720            return Vec::new();
721        };
722        let mut pos = 0;
723        let Some(count) = read_compressed_u32(&blob, &mut pos) else {
724            return Vec::new();
725        };
726        let ctor_base = pos;
727        let mut data_pos = ctor_base + count as usize * 4;
728        let mut out = Vec::new();
729        for i in 0..count as usize {
730            let Some(ctor_bytes) = blob.get(ctor_base + i * 4..ctor_base + i * 4 + 4) else {
731                break;
732            };
733            let ctor_index = i32::from_le_bytes(ctor_bytes.try_into().unwrap());
734            let ctor_type = self
735                .metadata
736                .methods
737                .get(usize::try_from(ctor_index).unwrap_or(usize::MAX))
738                .map(|m| m.declaring_type);
739            let Some((fixed, named)) = self.parse_arguments(&blob, &mut data_pos, ctor_type) else {
740                break;
741            };
742            if let Some(attribute) = self.build_attribute(module, ctor_index, fixed, named) {
743                out.push(attribute);
744            }
745        }
746        out
747    }
748
749    fn build_attribute(
750        &mut self,
751        module: usize,
752        ctor_index: i32,
753        fixed: Vec<Arg>,
754        named: Vec<(bool, String, Arg)>,
755    ) -> Option<CustomAttribute> {
756        let method = self
757            .metadata
758            .methods
759            .get(usize::try_from(ctor_index).ok()?)?
760            .clone();
761        let decl = method.declaring_type;
762        let params: Vec<TypeSig> = self
763            .metadata
764            .method_parameters(&method)
765            .to_vec()
766            .iter()
767            .map(|p| self.sig_at(module, p.type_index))
768            .collect();
769        if params.len() != fixed.len() || params.iter().any(needs_boxing) {
770            return None;
771        }
772        let fixed = fixed
773            .into_iter()
774            .map(|a| match a {
775                Arg::Value(v) => Some(v),
776                Arg::Skip => None,
777            })
778            .collect::<Option<Vec<_>>>()?;
779        let named = named
780            .into_iter()
781            .map(|(is_field, name, a)| match a {
782                Arg::Value(v) if is_field => Some(CANamedArgument::field(name, v)),
783                Arg::Value(v) => Some(CANamedArgument::property(name, v)),
784                Arg::Skip => None,
785            })
786            .collect::<Option<Vec<_>>>()?;
787        let constructor = self.attribute_ctor(module, decl, ctor_index, params)?;
788        CustomAttribute::new(constructor, &CustomAttributeValue { fixed, named }).ok()
789    }
790
791    fn attribute_ctor(
792        &mut self,
793        module: usize,
794        decl: TypeDefinitionIndex,
795        ctor_index: i32,
796        params: Vec<TypeSig>,
797    ) -> Option<CustomAttributeCtor> {
798        match self.type_ref(module, decl) {
799            TypeDefOrRef::TypeDef(def) => {
800                let method_start = self
801                    .metadata
802                    .type_definitions
803                    .get(decl as usize)?
804                    .method_start;
805                let local = usize::try_from(ctor_index - method_start).ok()?;
806                Some(CustomAttributeCtor::Method(
807                    def.get().methods.get(local)?.clone(),
808                ))
809            }
810            TypeDefOrRef::TypeRef(r) => {
811                Some(CustomAttributeCtor::MemberRef(Entry::new(MemberRef {
812                    parent: MemberRefParent::TypeRef(r),
813                    name: ".ctor".into(),
814                    signature: MemberRefSig::Method(MethodSig::new_instance(TypeSig::VOID, params)),
815                    custom_attributes: Vec::new(),
816                })))
817            }
818            TypeDefOrRef::TypeSpec(_) => None,
819        }
820    }
821
822    fn create_types(&mut self) {
823        self.types = (0..self.metadata.type_definitions.len())
824            .map(|i| {
825                let def = &self.metadata.type_definitions[i];
826                Entry::new(TypeDef {
827                    flags: TypeAttributes::from_bits_retain(def.flags),
828                    name: self.metadata.string(def.name_index).to_owned(),
829                    namespace: self.metadata.string(def.namespace_index).to_owned(),
830                    ..Default::default()
831                })
832            })
833            .collect();
834
835        for (i, def) in self.metadata.type_definitions.iter().enumerate() {
836            let start = def.nested_types_start.max(0) as usize;
837            let nested = self
838                .metadata
839                .nested_types
840                .get(start..start + def.nested_type_count as usize)
841                .unwrap_or(&[]);
842            for n in nested {
843                let child = &self.types[*n as usize];
844                child.get_mut().declaring_type = self.types[i].downgrade();
845                child.get_mut().namespace.clear();
846                self.types[i].get_mut().nested_types.push(child.clone());
847            }
848        }
849
850        // `<Module>` first, as metadata requires.
851        for (i, ty) in self.types.iter().enumerate() {
852            if ty.get().declaring_type.upgrade().is_none() {
853                let module = &mut self.modules[self.type_image[i]];
854                if ty.get().name == "<Module>" {
855                    module.types.insert(0, ty.clone());
856                } else {
857                    module.types.push(ty.clone());
858                }
859            }
860        }
861        for module in &mut self.modules {
862            if module
863                .types
864                .first()
865                .is_none_or(|t| t.get().name != "<Module>")
866            {
867                module.types.insert(
868                    0,
869                    Entry::new(TypeDef::new(TypeAttributes::empty(), "", "<Module>", None)),
870                );
871            }
872        }
873    }
874
875    fn fill_type(&mut self, index: usize) {
876        let module = self.type_image[index];
877        let def = self.metadata.type_definitions[index].clone();
878        let entry = self.types[index].clone();
879
880        let is_interface = def.flags & TypeAttributes::ClassSemanticsMask.bits()
881            == TypeAttributes::Interface.bits();
882        let extends = if def.parent_index >= 0 && !is_interface {
883            self.type_def_or_ref(module, def.parent_index)
884        } else {
885            None
886        };
887        let generic_params = self.generic_params(module, def.generic_container_index);
888        let start = def.interfaces_start.max(0) as usize;
889        let interfaces = self
890            .metadata
891            .interfaces
892            .get(start..start + def.interfaces_count as usize)
893            .unwrap_or(&[])
894            .to_vec()
895            .into_iter()
896            .filter_map(|i| self.type_def_or_ref(module, i))
897            .map(InterfaceImpl::new)
898            .collect();
899        {
900            let mut t = entry.get_mut();
901            t.extends = extends;
902            t.generic_params = generic_params;
903            t.interfaces = interfaces;
904        }
905
906        let field_start = def.field_start.max(0) as usize;
907        for (offset, f) in self.metadata.type_fields(&def).to_vec().iter().enumerate() {
908            let ty = self.binary.type_at(f.type_index).cloned();
909            let attrs = ty.as_ref().map_or(0, |t| t.attrs);
910            let mut flags = FieldFlags::from_bits_retain(attrs);
911            flags.remove(
912                FieldFlags::HasFieldRVA | FieldFlags::HasFieldMarshal | FieldFlags::HasDefault,
913            );
914            let signature = FieldSig {
915                ty: ty.map(|t| self.sig(module, &t)).unwrap_or(TypeSig::OBJECT),
916            };
917            let mut field = Field::new(flags, self.metadata.string(f.name_index), signature);
918            let field_index = (field_start + offset) as i32;
919            if let Some(default) = self
920                .metadata
921                .field_default_values
922                .iter()
923                .find(|d| d.field_index == field_index)
924            {
925                let element = self
926                    .binary
927                    .type_at(default.type_index)
928                    .and_then(|t| match t.kind {
929                        TypeKind::Primitive(e) => Some(e),
930                        _ => None,
931                    });
932                field.constant = element.and_then(|e| {
933                    constant(e, self.metadata.default_value_data(default.data_index))
934                });
935                if field.constant.is_some() {
936                    field.flags.insert(FieldFlags::HasDefault);
937                }
938            }
939            entry.add_field(field);
940        }
941
942        let mut methods = Vec::new();
943        for m in self.metadata.type_methods(&def).to_vec() {
944            let mut flags = MethodFlags::from_bits_retain(m.flags);
945            let impl_flags = MethodImplFlags::from_bits_retain(m.iflags);
946            let parameters = self.metadata.method_parameters(&m).to_vec();
947            let params: Vec<TypeSig> = parameters
948                .iter()
949                .map(|p| self.sig_at(module, p.type_index))
950                .collect();
951            let generic_params = self.generic_params(module, m.generic_container_index);
952            let signature = MethodSig {
953                calling_convention: CallingConvention::Default,
954                flags: if flags.contains(MethodFlags::Static) {
955                    SignatureFlags::empty()
956                } else {
957                    SignatureFlags::HAS_THIS
958                },
959                generic_param_count: generic_params.len() as u32,
960                ret: self.sig_at(module, m.return_type),
961                params,
962                varargs: Vec::new(),
963            };
964            flags.remove(MethodFlags::PinvokeImpl | MethodFlags::UnmanagedExport);
965            let mut method = Method::new(flags, self.metadata.string(m.name_index), signature);
966            method.impl_flags = impl_flags;
967            method.generic_params = generic_params;
968            method.params = parameters
969                .iter()
970                .enumerate()
971                .map(|(i, p)| {
972                    let attrs = self.binary.type_at(p.type_index).map_or(0, |t| t.attrs);
973                    let mut flags = ParamFlags::from_bits_retain(attrs);
974                    flags.remove(ParamFlags::HasDefault | ParamFlags::HasFieldMarshal);
975                    Entry::new(Param {
976                        flags,
977                        ..Param::new(i as u16 + 1, self.metadata.string(p.name_index))
978                    })
979                })
980                .collect();
981            let code_type = impl_flags & MethodImplFlags::CodeTypeMask;
982            let has_body = !flags.contains(MethodFlags::Abstract)
983                && code_type != MethodImplFlags::Runtime
984                && !impl_flags.contains(MethodImplFlags::InternalCall);
985            if has_body {
986                method.body = Some(MethodBody {
987                    instructions: vec![
988                        Instruction::simple(OpCode::Ldnull),
989                        Instruction::simple(OpCode::Throw),
990                    ],
991                    ..Default::default()
992                });
993            }
994            methods.push(entry.add_method(method));
995        }
996
997        let property_start = def.property_start.max(0) as usize;
998        for p in self
999            .metadata
1000            .properties
1001            .get(property_start..property_start + def.property_count as usize)
1002            .unwrap_or(&[])
1003            .to_vec()
1004        {
1005            let method = |i: i32| {
1006                usize::try_from(i)
1007                    .ok()
1008                    .and_then(|i| methods.get(i))
1009                    .cloned()
1010            };
1011            let (getter, setter) = (method(p.get), method(p.set));
1012            let (has_this, ty, params) = match (&getter, &setter) {
1013                (Some(g), _) => {
1014                    let g = g.get();
1015                    (
1016                        g.signature.has_this(),
1017                        g.signature.ret.clone(),
1018                        g.signature.params.clone(),
1019                    )
1020                }
1021                (None, Some(s)) => {
1022                    let s = s.get();
1023                    let mut params = s.signature.params.clone();
1024                    let ty = params.pop().unwrap_or(TypeSig::OBJECT);
1025                    (s.signature.has_this(), ty, params)
1026                }
1027                (None, None) => continue,
1028            };
1029            let property = Property {
1030                flags: PropertyFlags::from_bits_retain(p.attrs as u16),
1031                name: self.metadata.string(p.name_index).to_owned(),
1032                signature: PropertySig {
1033                    has_this,
1034                    ty,
1035                    params,
1036                },
1037                getter,
1038                setter,
1039                ..Default::default()
1040            };
1041            entry.get_mut().properties.push(Entry::new(property));
1042        }
1043
1044        let event_start = def.event_start.max(0) as usize;
1045        for e in self
1046            .metadata
1047            .events
1048            .get(event_start..event_start + def.event_count as usize)
1049            .unwrap_or(&[])
1050            .to_vec()
1051        {
1052            let method = |i: i32| {
1053                usize::try_from(i)
1054                    .ok()
1055                    .and_then(|i| methods.get(i))
1056                    .cloned()
1057            };
1058            let event = Event {
1059                flags: EventFlags::empty(),
1060                name: self.metadata.string(e.name_index).to_owned(),
1061                event_type: self.type_def_or_ref(module, e.type_index),
1062                add: method(e.add),
1063                remove: method(e.remove),
1064                fire: method(e.raise),
1065                ..Default::default()
1066            };
1067            entry.get_mut().events.push(Entry::new(event));
1068        }
1069    }
1070}
1071
1072fn version(v: [i32; 4]) -> Version {
1073    Version {
1074        major: v[0] as u16,
1075        minor: v[1] as u16,
1076        build: v[2] as u16,
1077        revision: v[3] as u16,
1078    }
1079}
1080
1081/// Builds a declaration assembly for every image in the game. Method bodies are
1082/// stubs that throw.
1083pub fn generate(metadata: &Metadata, binary: &Binary) -> Result<Vec<GeneratedAssembly>> {
1084    let mut generator = Generator::new(metadata, binary);
1085    generator.create_types();
1086    for i in 0..metadata.type_definitions.len() {
1087        generator.fill_type(i);
1088    }
1089    // Attach the game's own custom attributes (recovered from the v29+ attribute
1090    // data) to every entity, by matching metadata tokens. Generated member lists
1091    // mirror the metadata order, so they zip one-to-one.
1092    for i in 0..metadata.type_definitions.len() {
1093        let module = generator.type_image[i];
1094        let def = metadata.type_definitions[i].clone();
1095        let entry = generator.types[i].clone();
1096
1097        let attrs = generator.custom_attributes(module, def.token);
1098        entry.get_mut().custom_attributes.extend(attrs);
1099
1100        let methods = entry.get().methods.clone();
1101        for (method, m_def) in methods.iter().zip(metadata.type_methods(&def)) {
1102            let attrs = generator.custom_attributes(module, m_def.token);
1103            method.get_mut().custom_attributes.extend(attrs);
1104            let params = method.get().params.clone();
1105            for (param, p_def) in params.iter().zip(metadata.method_parameters(m_def)) {
1106                let attrs = generator.custom_attributes(module, p_def.token);
1107                param.get_mut().custom_attributes.extend(attrs);
1108            }
1109        }
1110
1111        let fields = entry.get().fields.clone();
1112        for (field, f_def) in fields.iter().zip(metadata.type_fields(&def)) {
1113            let attrs = generator.custom_attributes(module, f_def.token);
1114            field.get_mut().custom_attributes.extend(attrs);
1115        }
1116
1117        let properties = entry.get().properties.clone();
1118        let prop_start = def.property_start.max(0) as usize;
1119        let prop_defs = metadata
1120            .properties
1121            .get(prop_start..prop_start + def.property_count as usize)
1122            .unwrap_or(&[]);
1123        for (property, pr_def) in properties.iter().zip(prop_defs) {
1124            let attrs = generator.custom_attributes(module, pr_def.token);
1125            property.get_mut().custom_attributes.extend(attrs);
1126        }
1127
1128        let events = entry.get().events.clone();
1129        let event_start = def.event_start.max(0) as usize;
1130        let event_defs = metadata
1131            .events
1132            .get(event_start..event_start + def.event_count as usize)
1133            .unwrap_or(&[]);
1134        for (event, ev_def) in events.iter().zip(event_defs) {
1135            let attrs = generator.custom_attributes(module, ev_def.token);
1136            event.get_mut().custom_attributes.extend(attrs);
1137        }
1138    }
1139    for i in 0..metadata.type_definitions.len() {
1140        let entry = generator.types[i].clone();
1141        let has_indexer = entry
1142            .get()
1143            .properties
1144            .iter()
1145            .any(|p| !p.get().signature.params.is_empty());
1146        // Add the synthetic `[DefaultMember("Item")]` unless the game already
1147        // carries one (recovered above), so indexers compile in C#.
1148        let has_default_member = entry
1149            .get()
1150            .custom_attributes
1151            .iter()
1152            .any(|a| a.type_name() == "System.Reflection.DefaultMemberAttribute");
1153        if has_indexer && !has_default_member {
1154            if let Some(attribute) =
1155                generator.default_member_attribute(generator.type_image[i], "Item")
1156            {
1157                entry.get_mut().custom_attributes.push(attribute);
1158            }
1159        }
1160    }
1161    Ok(metadata
1162        .images
1163        .iter()
1164        .zip(generator.modules)
1165        .map(|(image, module)| GeneratedAssembly {
1166            file_name: metadata.image_name(image).to_owned(),
1167            module,
1168        })
1169        .collect())
1170}
1171
1172#[cfg(test)]
1173mod tests {
1174    use super::*;
1175
1176    #[test]
1177    fn compressed_integers() {
1178        let decode = |bytes: &[u8]| read_compressed_i32(bytes, &mut 0).unwrap();
1179        assert_eq!(decode(&[0x00]), 0);
1180        assert_eq!(decode(&[0x02]), 1);
1181        assert_eq!(decode(&[0x01]), -1);
1182        assert_eq!(decode(&[0xFF]), i32::MIN);
1183        assert_eq!(
1184            read_compressed_u32(&[0xF0, 0x78, 0x56, 0x34, 0x12], &mut 0),
1185            Some(0x1234_5678)
1186        );
1187        assert_eq!(read_compressed_u32(&[0x81, 0x02], &mut 0), Some(0x102));
1188    }
1189
1190    /// Runs against a real game. Set `HAO_IL2CPP_GAME` to an Il2Cpp game folder
1191    /// with a v29 `GameAssembly.so`. Skipped otherwise.
1192    #[test]
1193    fn recovers_custom_attributes() {
1194        let Some(dir) = std::env::var_os("HAO_IL2CPP_GAME") else {
1195            eprintln!("skipping: set HAO_IL2CPP_GAME to an Il2Cpp game folder");
1196            return;
1197        };
1198        let game = crate::game::Game::open(dir).unwrap();
1199        let assemblies = game.generate().unwrap();
1200
1201        let mut type_attributes = std::collections::BTreeSet::new();
1202        let mut member_attributes = 0usize;
1203        let mut default_member_item = false;
1204
1205        for assembly in &assemblies {
1206            for ty in assembly.module.all_types() {
1207                let t = ty.get();
1208                for attribute in &t.custom_attributes {
1209                    type_attributes.insert(attribute.type_name());
1210                    // The recovered DefaultMember still carries its string argument.
1211                    if attribute.type_name() == "System.Reflection.DefaultMemberAttribute" {
1212                        if let Ok(value) = attribute.decode(&assembly.module) {
1213                            default_member_item |=
1214                                value.fixed.iter().any(|v| v.as_str() == Some("Item"));
1215                        }
1216                    }
1217                }
1218                for method in &t.methods {
1219                    member_attributes += method.get().custom_attributes.len();
1220                    for param in &method.get().params {
1221                        member_attributes += param.get().custom_attributes.len();
1222                    }
1223                }
1224                member_attributes += t
1225                    .fields
1226                    .iter()
1227                    .map(|f| f.get().custom_attributes.len())
1228                    .sum::<usize>();
1229            }
1230        }
1231
1232        // The game's own attributes now appear, not just the synthetic DefaultMember:
1233        // every enum carries [Flags]? no — but many do, and extension methods carry
1234        // [Extension]. These are cross-assembly, exercising the MemberRef path.
1235        assert!(
1236            type_attributes.contains("System.FlagsAttribute"),
1237            "expected recovered [Flags] attributes among {} distinct type attributes",
1238            type_attributes.len()
1239        );
1240        assert!(
1241            type_attributes.contains("System.Runtime.CompilerServices.ExtensionAttribute"),
1242            "expected recovered [Extension] attributes"
1243        );
1244        assert!(
1245            type_attributes.contains("System.Reflection.DefaultMemberAttribute"),
1246            "DefaultMember should still be present"
1247        );
1248        assert!(
1249            default_member_item,
1250            "DefaultMember(\"Item\") argument should round-trip"
1251        );
1252        assert!(
1253            member_attributes > 0,
1254            "expected recovered method/field/param attributes"
1255        );
1256    }
1257}