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.binary.type_at(self.metadata.type_fields(ty).first()?.type_index)?.kind {
489            TypeKind::Primitive(e) => Some(*e),
490            _ => None,
491        }
492    }
493
494    /// `Namespace.Outer+Inner`, the reflection form used in serialized attributes.
495    fn serialized_type_name(&self, def: TypeDefinitionIndex) -> Option<String> {
496        if def < 0 || def as usize >= self.metadata.type_definitions.len() {
497            return None;
498        }
499        Some(self.metadata.type_full_name(def).replace('/', "+"))
500    }
501
502    /// A reflection type name for a `System.Type` argument's `Il2CppType` index.
503    fn type_argument_name(&self, il_type_index: i32) -> Option<String> {
504        match &self.binary.type_at(il_type_index)?.kind {
505            TypeKind::Class(d) | TypeKind::ValueType(d) => self.serialized_type_name(*d),
506            TypeKind::Primitive(e) => self.serialized_type_name(*self.primitive_types.get(e)?),
507            _ => None,
508        }
509    }
510
511    /// Reads a self-describing type tag (`ReadEncodedTypeEnum`): the element type
512    /// byte, and the enum's definition when the tag is an enum (the byte is then the
513    /// enum's underlying primitive). `None` when an enum can't be resolved, as its
514    /// value width is then unknown.
515    fn read_encoded_type(
516        &self,
517        blob: &[u8],
518        pos: &mut usize,
519    ) -> Option<(u8, Option<TypeDefinitionIndex>)> {
520        let tag = read_u8(blob, pos)?;
521        if tag == TAG_ENUM {
522            let type_index = read_compressed_i32(blob, pos)?;
523            let def = self.type_def_index_of(type_index)?;
524            Some((self.enum_underlying(def)?, Some(def)))
525        } else {
526            Some((tag, None))
527        }
528    }
529
530    /// Reads one attribute argument (`ReadAttributeDataValue`), always advancing
531    /// past a well-formed value. `Arg::Skip` marks a value that parsed but can't be
532    /// represented, so the attribute is dropped without mis-encoding it.
533    fn read_arg(&self, blob: &[u8], pos: &mut usize) -> Option<Arg> {
534        let (tag, enum_def) = self.read_encoded_type(blob, pos)?;
535        self.read_value(blob, pos, tag, enum_def)
536    }
537
538    fn read_value(
539        &self,
540        blob: &[u8],
541        pos: &mut usize,
542        tag: u8,
543        enum_def: Option<TypeDefinitionIndex>,
544    ) -> Option<Arg> {
545        use element::*;
546        if let Some(def) = enum_def {
547            // Read the underlying value, then wrap it with the enum's name.
548            let Arg::Value(inner) = self.read_value(blob, pos, tag, None)? else {
549                return Some(Arg::Skip);
550            };
551            return Some(match self.serialized_type_name(def) {
552                Some(type_name) => Arg::Value(CAValue::Enum {
553                    type_name,
554                    value: Box::new(inner),
555                }),
556                None => Arg::Skip,
557            });
558        }
559        let value = match tag {
560            BOOLEAN => CAValue::Bool(read_u8(blob, pos)? != 0),
561            I1 => CAValue::I1(read_u8(blob, pos)? as i8),
562            U1 => CAValue::U1(read_u8(blob, pos)?),
563            CHAR => CAValue::Char(u16::from_le_bytes(read_fixed(blob, pos)?)),
564            I2 => CAValue::I2(i16::from_le_bytes(read_fixed(blob, pos)?)),
565            U2 => CAValue::U2(u16::from_le_bytes(read_fixed(blob, pos)?)),
566            I4 => CAValue::I4(read_compressed_i32(blob, pos)?),
567            U4 => CAValue::U4(read_compressed_u32(blob, pos)?),
568            I8 => CAValue::I8(i64::from_le_bytes(read_fixed(blob, pos)?)),
569            U8 => CAValue::U8(u64::from_le_bytes(read_fixed(blob, pos)?)),
570            R4 => CAValue::R4(f32::from_le_bytes(read_fixed(blob, pos)?)),
571            R8 => CAValue::R8(f64::from_le_bytes(read_fixed(blob, pos)?)),
572            STRING => CAValue::String(read_ser_string(blob, pos)?),
573            TAG_TYPE_INDEX => {
574                let type_index = read_compressed_i32(blob, pos)?;
575                if type_index < 0 {
576                    CAValue::Type(None)
577                } else {
578                    match self.type_argument_name(type_index) {
579                        Some(name) => CAValue::Type(Some(name)),
580                        None => return Some(Arg::Skip),
581                    }
582                }
583            }
584            SZARRAY => return self.read_array(blob, pos),
585            _ => return None,
586        };
587        Some(Arg::Value(value))
588    }
589
590    fn read_array(&self, blob: &[u8], pos: &mut usize) -> Option<Arg> {
591        let len = read_compressed_i32(blob, pos)?;
592        if len < 0 {
593            return Some(Arg::Value(CAValue::Array {
594                element: CAType::Object,
595                values: None,
596            }));
597        }
598        let (base_tag, base_enum) = self.read_encoded_type(blob, pos)?;
599        let different = read_u8(blob, pos)? == 1;
600        let mut values = Vec::new();
601        let mut skip = false;
602        for _ in 0..len as usize {
603            let (tag, enum_def) = if different {
604                self.read_encoded_type(blob, pos)?
605            } else {
606                (base_tag, base_enum)
607            };
608            match self.read_value(blob, pos, tag, enum_def)? {
609                Arg::Value(v) => values.push(v),
610                Arg::Skip => skip = true,
611            }
612        }
613        if skip {
614            return Some(Arg::Skip);
615        }
616        Some(match self.array_element_type(base_tag, base_enum) {
617            Some(element) => Arg::Value(CAValue::Array {
618                element,
619                values: Some(values),
620            }),
621            None => Arg::Skip,
622        })
623    }
624
625    fn array_element_type(&self, tag: u8, enum_def: Option<TypeDefinitionIndex>) -> Option<CAType> {
626        use element::*;
627        if let Some(def) = enum_def {
628            return Some(CAType::Enum {
629                type_name: self.serialized_type_name(def)?,
630                underlying: PrimitiveType::from_repr(tag)?,
631            });
632        }
633        Some(match tag {
634            TAG_TYPE_INDEX => CAType::Type,
635            BOOLEAN | CHAR | I1 | U1 | I2 | U2 | I4 | U4 | I8 | U8 | R4 | R8 | STRING => {
636                CAType::Primitive(PrimitiveType::from_repr(tag)?)
637            }
638            _ => return None,
639        })
640    }
641
642    /// The name of a named-argument field or property, from its declaring type and
643    /// member index (`ReadCustomAttributeNamedArgumentClassAndIndex`). Always
644    /// advances; the inner `None` means the member couldn't be resolved.
645    fn read_named_member(
646        &self,
647        blob: &[u8],
648        pos: &mut usize,
649        ctor_type: Option<TypeDefinitionIndex>,
650        is_field: bool,
651    ) -> Option<Option<String>> {
652        let member = read_compressed_i32(blob, pos)?;
653        let (decl, index) = if member >= 0 {
654            (ctor_type, member as usize)
655        } else {
656            let type_index = read_compressed_u32(blob, pos)? as TypeDefinitionIndex;
657            (Some(type_index), (-(member + 1)) as usize)
658        };
659        Some(decl.and_then(|d| self.member_name(d, index, is_field)))
660    }
661
662    fn member_name(
663        &self,
664        decl: TypeDefinitionIndex,
665        index: usize,
666        is_field: bool,
667    ) -> Option<String> {
668        let ty = self.metadata.type_definitions.get(usize::try_from(decl).ok()?)?;
669        let name_index = if is_field {
670            let start = ty.field_start.max(0) as usize;
671            self.metadata.fields.get(start + index)?.name_index
672        } else {
673            let start = ty.property_start.max(0) as usize;
674            self.metadata.properties.get(start + index)?.name_index
675        };
676        Some(self.metadata.string(name_index).to_owned())
677    }
678
679    /// Parses one attribute's argument block: the fixed arguments, then the named
680    /// fields and properties. Must stay byte-aligned, so returns `None` (stopping
681    /// the token) on malformed data.
682    #[allow(clippy::type_complexity)]
683    fn parse_arguments(
684        &self,
685        blob: &[u8],
686        pos: &mut usize,
687        ctor_type: Option<TypeDefinitionIndex>,
688    ) -> Option<(Vec<Arg>, Vec<(bool, String, Arg)>)> {
689        let arg_count = read_compressed_u32(blob, pos)?;
690        let field_count = read_compressed_u32(blob, pos)?;
691        let property_count = read_compressed_u32(blob, pos)?;
692        let mut fixed = Vec::new();
693        for _ in 0..arg_count {
694            fixed.push(self.read_arg(blob, pos)?);
695        }
696        let mut named = Vec::new();
697        for (is_field, count) in [(true, field_count), (false, property_count)] {
698            for _ in 0..count {
699                let value = self.read_arg(blob, pos)?;
700                match self.read_named_member(blob, pos, ctor_type, is_field)? {
701                    Some(name) => named.push((is_field, name, value)),
702                    None => named.push((is_field, String::new(), Arg::Skip)),
703                }
704            }
705        }
706        Some((fixed, named))
707    }
708
709    /// The custom attributes applied to `token` in `module`, reconstructed from the
710    /// v29+ `attribute_data` blob.
711    fn custom_attributes(&mut self, module: usize, token: u32) -> Vec<CustomAttribute> {
712        let Some(blob) = self.attribute_blob(module, token) else {
713            return Vec::new();
714        };
715        let mut pos = 0;
716        let Some(count) = read_compressed_u32(&blob, &mut pos) else {
717            return Vec::new();
718        };
719        let ctor_base = pos;
720        let mut data_pos = ctor_base + count as usize * 4;
721        let mut out = Vec::new();
722        for i in 0..count as usize {
723            let Some(ctor_bytes) = blob.get(ctor_base + i * 4..ctor_base + i * 4 + 4) else {
724                break;
725            };
726            let ctor_index = i32::from_le_bytes(ctor_bytes.try_into().unwrap());
727            let ctor_type = self
728                .metadata
729                .methods
730                .get(usize::try_from(ctor_index).unwrap_or(usize::MAX))
731                .map(|m| m.declaring_type);
732            let Some((fixed, named)) = self.parse_arguments(&blob, &mut data_pos, ctor_type) else {
733                break;
734            };
735            if let Some(attribute) = self.build_attribute(module, ctor_index, fixed, named) {
736                out.push(attribute);
737            }
738        }
739        out
740    }
741
742    fn build_attribute(
743        &mut self,
744        module: usize,
745        ctor_index: i32,
746        fixed: Vec<Arg>,
747        named: Vec<(bool, String, Arg)>,
748    ) -> Option<CustomAttribute> {
749        let method = self
750            .metadata
751            .methods
752            .get(usize::try_from(ctor_index).ok()?)?
753            .clone();
754        let decl = method.declaring_type;
755        let params: Vec<TypeSig> = self
756            .metadata
757            .method_parameters(&method)
758            .to_vec()
759            .iter()
760            .map(|p| self.sig_at(module, p.type_index))
761            .collect();
762        if params.len() != fixed.len() || params.iter().any(needs_boxing) {
763            return None;
764        }
765        let fixed = fixed
766            .into_iter()
767            .map(|a| match a {
768                Arg::Value(v) => Some(v),
769                Arg::Skip => None,
770            })
771            .collect::<Option<Vec<_>>>()?;
772        let named = named
773            .into_iter()
774            .map(|(is_field, name, a)| match a {
775                Arg::Value(v) if is_field => Some(CANamedArgument::field(name, v)),
776                Arg::Value(v) => Some(CANamedArgument::property(name, v)),
777                Arg::Skip => None,
778            })
779            .collect::<Option<Vec<_>>>()?;
780        let constructor = self.attribute_ctor(module, decl, ctor_index, params)?;
781        CustomAttribute::new(constructor, &CustomAttributeValue { fixed, named }).ok()
782    }
783
784    fn attribute_ctor(
785        &mut self,
786        module: usize,
787        decl: TypeDefinitionIndex,
788        ctor_index: i32,
789        params: Vec<TypeSig>,
790    ) -> Option<CustomAttributeCtor> {
791        match self.type_ref(module, decl) {
792            TypeDefOrRef::TypeDef(def) => {
793                let method_start = self.metadata.type_definitions.get(decl as usize)?.method_start;
794                let local = usize::try_from(ctor_index - method_start).ok()?;
795                Some(CustomAttributeCtor::Method(
796                    def.get().methods.get(local)?.clone(),
797                ))
798            }
799            TypeDefOrRef::TypeRef(r) => Some(CustomAttributeCtor::MemberRef(Entry::new(MemberRef {
800                parent: MemberRefParent::TypeRef(r),
801                name: ".ctor".into(),
802                signature: MemberRefSig::Method(MethodSig::new_instance(TypeSig::VOID, params)),
803                custom_attributes: Vec::new(),
804            }))),
805            TypeDefOrRef::TypeSpec(_) => None,
806        }
807    }
808
809    fn create_types(&mut self) {
810        self.types = (0..self.metadata.type_definitions.len())
811            .map(|i| {
812                let def = &self.metadata.type_definitions[i];
813                Entry::new(TypeDef {
814                    flags: TypeAttributes::from_bits_retain(def.flags),
815                    name: self.metadata.string(def.name_index).to_owned(),
816                    namespace: self.metadata.string(def.namespace_index).to_owned(),
817                    ..Default::default()
818                })
819            })
820            .collect();
821
822        for (i, def) in self.metadata.type_definitions.iter().enumerate() {
823            let start = def.nested_types_start.max(0) as usize;
824            let nested = self
825                .metadata
826                .nested_types
827                .get(start..start + def.nested_type_count as usize)
828                .unwrap_or(&[]);
829            for n in nested {
830                let child = &self.types[*n as usize];
831                child.get_mut().declaring_type = self.types[i].downgrade();
832                child.get_mut().namespace.clear();
833                self.types[i].get_mut().nested_types.push(child.clone());
834            }
835        }
836
837        // `<Module>` first, as metadata requires.
838        for (i, ty) in self.types.iter().enumerate() {
839            if ty.get().declaring_type.upgrade().is_none() {
840                let module = &mut self.modules[self.type_image[i]];
841                if ty.get().name == "<Module>" {
842                    module.types.insert(0, ty.clone());
843                } else {
844                    module.types.push(ty.clone());
845                }
846            }
847        }
848        for module in &mut self.modules {
849            if module
850                .types
851                .first()
852                .is_none_or(|t| t.get().name != "<Module>")
853            {
854                module.types.insert(
855                    0,
856                    Entry::new(TypeDef::new(TypeAttributes::empty(), "", "<Module>", None)),
857                );
858            }
859        }
860    }
861
862    fn fill_type(&mut self, index: usize) {
863        let module = self.type_image[index];
864        let def = self.metadata.type_definitions[index].clone();
865        let entry = self.types[index].clone();
866
867        let is_interface = def.flags & TypeAttributes::ClassSemanticsMask.bits()
868            == TypeAttributes::Interface.bits();
869        let extends = if def.parent_index >= 0 && !is_interface {
870            self.type_def_or_ref(module, def.parent_index)
871        } else {
872            None
873        };
874        let generic_params = self.generic_params(module, def.generic_container_index);
875        let start = def.interfaces_start.max(0) as usize;
876        let interfaces = self
877            .metadata
878            .interfaces
879            .get(start..start + def.interfaces_count as usize)
880            .unwrap_or(&[])
881            .to_vec()
882            .into_iter()
883            .filter_map(|i| self.type_def_or_ref(module, i))
884            .map(InterfaceImpl::new)
885            .collect();
886        {
887            let mut t = entry.get_mut();
888            t.extends = extends;
889            t.generic_params = generic_params;
890            t.interfaces = interfaces;
891        }
892
893        let field_start = def.field_start.max(0) as usize;
894        for (offset, f) in self.metadata.type_fields(&def).to_vec().iter().enumerate() {
895            let ty = self.binary.type_at(f.type_index).cloned();
896            let attrs = ty.as_ref().map_or(0, |t| t.attrs);
897            let mut flags = FieldFlags::from_bits_retain(attrs);
898            flags.remove(
899                FieldFlags::HasFieldRVA | FieldFlags::HasFieldMarshal | FieldFlags::HasDefault,
900            );
901            let signature = FieldSig {
902                ty: ty.map(|t| self.sig(module, &t)).unwrap_or(TypeSig::OBJECT),
903            };
904            let mut field = Field::new(flags, self.metadata.string(f.name_index), signature);
905            let field_index = (field_start + offset) as i32;
906            if let Some(default) = self
907                .metadata
908                .field_default_values
909                .iter()
910                .find(|d| d.field_index == field_index)
911            {
912                let element = self
913                    .binary
914                    .type_at(default.type_index)
915                    .and_then(|t| match t.kind {
916                        TypeKind::Primitive(e) => Some(e),
917                        _ => None,
918                    });
919                field.constant = element.and_then(|e| {
920                    constant(e, self.metadata.default_value_data(default.data_index))
921                });
922                if field.constant.is_some() {
923                    field.flags.insert(FieldFlags::HasDefault);
924                }
925            }
926            TypeDef::add_field(&entry, field);
927        }
928
929        let mut methods = Vec::new();
930        for m in self.metadata.type_methods(&def).to_vec() {
931            let mut flags = MethodFlags::from_bits_retain(m.flags);
932            let impl_flags = MethodImplFlags::from_bits_retain(m.iflags);
933            let parameters = self.metadata.method_parameters(&m).to_vec();
934            let params: Vec<TypeSig> = parameters
935                .iter()
936                .map(|p| self.sig_at(module, p.type_index))
937                .collect();
938            let generic_params = self.generic_params(module, m.generic_container_index);
939            let signature = MethodSig {
940                calling_convention: CallingConvention::Default,
941                flags: if flags.contains(MethodFlags::Static) {
942                    SignatureFlags::empty()
943                } else {
944                    SignatureFlags::HAS_THIS
945                },
946                generic_param_count: generic_params.len() as u32,
947                ret: self.sig_at(module, m.return_type),
948                params,
949                varargs: Vec::new(),
950            };
951            flags.remove(MethodFlags::PinvokeImpl | MethodFlags::UnmanagedExport);
952            let mut method = Method::new(flags, self.metadata.string(m.name_index), signature);
953            method.impl_flags = impl_flags;
954            method.generic_params = generic_params;
955            method.params = parameters
956                .iter()
957                .enumerate()
958                .map(|(i, p)| {
959                    let attrs = self.binary.type_at(p.type_index).map_or(0, |t| t.attrs);
960                    let mut flags = ParamFlags::from_bits_retain(attrs);
961                    flags.remove(ParamFlags::HasDefault | ParamFlags::HasFieldMarshal);
962                    Entry::new(Param {
963                        flags,
964                        ..Param::new(i as u16 + 1, self.metadata.string(p.name_index))
965                    })
966                })
967                .collect();
968            let code_type = impl_flags & MethodImplFlags::CodeTypeMask;
969            let has_body = !flags.contains(MethodFlags::Abstract)
970                && code_type != MethodImplFlags::Runtime
971                && !impl_flags.contains(MethodImplFlags::InternalCall);
972            if has_body {
973                method.body = Some(MethodBody {
974                    instructions: vec![
975                        Instruction::simple(OpCode::Ldnull),
976                        Instruction::simple(OpCode::Throw),
977                    ],
978                    ..Default::default()
979                });
980            }
981            methods.push(TypeDef::add_method(&entry, method));
982        }
983
984        let property_start = def.property_start.max(0) as usize;
985        for p in self
986            .metadata
987            .properties
988            .get(property_start..property_start + def.property_count as usize)
989            .unwrap_or(&[])
990            .to_vec()
991        {
992            let method = |i: i32| {
993                usize::try_from(i)
994                    .ok()
995                    .and_then(|i| methods.get(i))
996                    .cloned()
997            };
998            let (getter, setter) = (method(p.get), method(p.set));
999            let (has_this, ty, params) = match (&getter, &setter) {
1000                (Some(g), _) => {
1001                    let g = g.get();
1002                    (
1003                        g.signature.has_this(),
1004                        g.signature.ret.clone(),
1005                        g.signature.params.clone(),
1006                    )
1007                }
1008                (None, Some(s)) => {
1009                    let s = s.get();
1010                    let mut params = s.signature.params.clone();
1011                    let ty = params.pop().unwrap_or(TypeSig::OBJECT);
1012                    (s.signature.has_this(), ty, params)
1013                }
1014                (None, None) => continue,
1015            };
1016            let property = Property {
1017                flags: PropertyFlags::from_bits_retain(p.attrs as u16),
1018                name: self.metadata.string(p.name_index).to_owned(),
1019                signature: PropertySig {
1020                    has_this,
1021                    ty,
1022                    params,
1023                },
1024                getter,
1025                setter,
1026                ..Default::default()
1027            };
1028            entry.get_mut().properties.push(Entry::new(property));
1029        }
1030
1031        let event_start = def.event_start.max(0) as usize;
1032        for e in self
1033            .metadata
1034            .events
1035            .get(event_start..event_start + def.event_count as usize)
1036            .unwrap_or(&[])
1037            .to_vec()
1038        {
1039            let method = |i: i32| {
1040                usize::try_from(i)
1041                    .ok()
1042                    .and_then(|i| methods.get(i))
1043                    .cloned()
1044            };
1045            let event = Event {
1046                flags: EventFlags::empty(),
1047                name: self.metadata.string(e.name_index).to_owned(),
1048                event_type: self.type_def_or_ref(module, e.type_index),
1049                add: method(e.add),
1050                remove: method(e.remove),
1051                fire: method(e.raise),
1052                ..Default::default()
1053            };
1054            entry.get_mut().events.push(Entry::new(event));
1055        }
1056    }
1057}
1058
1059fn version(v: [i32; 4]) -> Version {
1060    Version {
1061        major: v[0] as u16,
1062        minor: v[1] as u16,
1063        build: v[2] as u16,
1064        revision: v[3] as u16,
1065    }
1066}
1067
1068/// Builds a declaration assembly for every image in the game. Method bodies are
1069/// stubs that throw.
1070pub fn generate(metadata: &Metadata, binary: &Binary) -> Result<Vec<GeneratedAssembly>> {
1071    let mut generator = Generator::new(metadata, binary);
1072    generator.create_types();
1073    for i in 0..metadata.type_definitions.len() {
1074        generator.fill_type(i);
1075    }
1076    // Attach the game's own custom attributes (recovered from the v29+ attribute
1077    // data) to every entity, by matching metadata tokens. Generated member lists
1078    // mirror the metadata order, so they zip one-to-one.
1079    for i in 0..metadata.type_definitions.len() {
1080        let module = generator.type_image[i];
1081        let def = metadata.type_definitions[i].clone();
1082        let entry = generator.types[i].clone();
1083
1084        let attrs = generator.custom_attributes(module, def.token);
1085        entry.get_mut().custom_attributes.extend(attrs);
1086
1087        let methods = entry.get().methods.clone();
1088        for (method, m_def) in methods.iter().zip(metadata.type_methods(&def)) {
1089            let attrs = generator.custom_attributes(module, m_def.token);
1090            method.get_mut().custom_attributes.extend(attrs);
1091            let params = method.get().params.clone();
1092            for (param, p_def) in params.iter().zip(metadata.method_parameters(m_def)) {
1093                let attrs = generator.custom_attributes(module, p_def.token);
1094                param.get_mut().custom_attributes.extend(attrs);
1095            }
1096        }
1097
1098        let fields = entry.get().fields.clone();
1099        for (field, f_def) in fields.iter().zip(metadata.type_fields(&def)) {
1100            let attrs = generator.custom_attributes(module, f_def.token);
1101            field.get_mut().custom_attributes.extend(attrs);
1102        }
1103
1104        let properties = entry.get().properties.clone();
1105        let prop_start = def.property_start.max(0) as usize;
1106        let prop_defs = metadata
1107            .properties
1108            .get(prop_start..prop_start + def.property_count as usize)
1109            .unwrap_or(&[]);
1110        for (property, pr_def) in properties.iter().zip(prop_defs) {
1111            let attrs = generator.custom_attributes(module, pr_def.token);
1112            property.get_mut().custom_attributes.extend(attrs);
1113        }
1114
1115        let events = entry.get().events.clone();
1116        let event_start = def.event_start.max(0) as usize;
1117        let event_defs = metadata
1118            .events
1119            .get(event_start..event_start + def.event_count as usize)
1120            .unwrap_or(&[]);
1121        for (event, ev_def) in events.iter().zip(event_defs) {
1122            let attrs = generator.custom_attributes(module, ev_def.token);
1123            event.get_mut().custom_attributes.extend(attrs);
1124        }
1125    }
1126    for i in 0..metadata.type_definitions.len() {
1127        let entry = generator.types[i].clone();
1128        let has_indexer = entry
1129            .get()
1130            .properties
1131            .iter()
1132            .any(|p| !p.get().signature.params.is_empty());
1133        // Add the synthetic `[DefaultMember("Item")]` unless the game already
1134        // carries one (recovered above), so indexers compile in C#.
1135        let has_default_member = entry
1136            .get()
1137            .custom_attributes
1138            .iter()
1139            .any(|a| a.type_name() == "System.Reflection.DefaultMemberAttribute");
1140        if has_indexer && !has_default_member {
1141            if let Some(attribute) =
1142                generator.default_member_attribute(generator.type_image[i], "Item")
1143            {
1144                entry.get_mut().custom_attributes.push(attribute);
1145            }
1146        }
1147    }
1148    Ok(metadata
1149        .images
1150        .iter()
1151        .zip(generator.modules)
1152        .map(|(image, module)| GeneratedAssembly {
1153            file_name: metadata.image_name(image).to_owned(),
1154            module,
1155        })
1156        .collect())
1157}
1158
1159#[cfg(test)]
1160mod tests {
1161    use super::*;
1162
1163    #[test]
1164    fn compressed_integers() {
1165        let decode = |bytes: &[u8]| read_compressed_i32(bytes, &mut 0).unwrap();
1166        assert_eq!(decode(&[0x00]), 0);
1167        assert_eq!(decode(&[0x02]), 1);
1168        assert_eq!(decode(&[0x01]), -1);
1169        assert_eq!(decode(&[0xFF]), i32::MIN);
1170        assert_eq!(
1171            read_compressed_u32(&[0xF0, 0x78, 0x56, 0x34, 0x12], &mut 0),
1172            Some(0x1234_5678)
1173        );
1174        assert_eq!(read_compressed_u32(&[0x81, 0x02], &mut 0), Some(0x102));
1175    }
1176
1177    /// Runs against a real game. Set `HAO_IL2CPP_GAME` to an Il2Cpp game folder
1178    /// with a v29 `GameAssembly.so`. Skipped otherwise.
1179    #[test]
1180    fn recovers_custom_attributes() {
1181        let Some(dir) = std::env::var_os("HAO_IL2CPP_GAME") else {
1182            eprintln!("skipping: set HAO_IL2CPP_GAME to an Il2Cpp game folder");
1183            return;
1184        };
1185        let game = crate::game::Game::open(dir).unwrap();
1186        let assemblies = game.generate().unwrap();
1187
1188        let mut type_attributes = std::collections::BTreeSet::new();
1189        let mut member_attributes = 0usize;
1190        let mut default_member_item = false;
1191
1192        for assembly in &assemblies {
1193            for ty in assembly.module.all_types() {
1194                let t = ty.get();
1195                for attribute in &t.custom_attributes {
1196                    type_attributes.insert(attribute.type_name());
1197                    // The recovered DefaultMember still carries its string argument.
1198                    if attribute.type_name() == "System.Reflection.DefaultMemberAttribute" {
1199                        if let Ok(value) = attribute.decode(&assembly.module) {
1200                            default_member_item |=
1201                                value.fixed.iter().any(|v| v.as_str() == Some("Item"));
1202                        }
1203                    }
1204                }
1205                for method in &t.methods {
1206                    member_attributes += method.get().custom_attributes.len();
1207                    for param in &method.get().params {
1208                        member_attributes += param.get().custom_attributes.len();
1209                    }
1210                }
1211                member_attributes += t.fields.iter().map(|f| f.get().custom_attributes.len()).sum::<usize>();
1212            }
1213        }
1214
1215        // The game's own attributes now appear, not just the synthetic DefaultMember:
1216        // every enum carries [Flags]? no — but many do, and extension methods carry
1217        // [Extension]. These are cross-assembly, exercising the MemberRef path.
1218        assert!(
1219            type_attributes.contains("System.FlagsAttribute"),
1220            "expected recovered [Flags] attributes among {} distinct type attributes",
1221            type_attributes.len()
1222        );
1223        assert!(
1224            type_attributes.contains("System.Runtime.CompilerServices.ExtensionAttribute"),
1225            "expected recovered [Extension] attributes"
1226        );
1227        assert!(
1228            type_attributes.contains("System.Reflection.DefaultMemberAttribute"),
1229            "DefaultMember should still be present"
1230        );
1231        assert!(default_member_item, "DefaultMember(\"Item\") argument should round-trip");
1232        assert!(member_attributes > 0, "expected recovered method/field/param attributes");
1233    }
1234}