Skip to main content

hao_il2cpp/
metadata.rs

1//! `global-metadata.dat`: names and the shape of every type, method and field.
2//!
3//! Types of fields, parameters and return values are indices into the
4//! `Il2CppType` table, which lives in the game binary, not in this file.
5//!
6//! Three metadata versions are supported:
7//! - **v29** (Unity 2021.2 – 2023.x): header entries are `(offset, size)` pairs.
8//! - **v31** (later Unity 2022.3 LTS / 2023.x): identical to v29 except the
9//!   method record gained a `returnParameterToken` field (so each record is 4
10//!   bytes larger). The section list, header-entry size and all other record
11//!   layouts match v29. Implemented from the Il2CppDumper/Il2CppInspector
12//!   reference layouts; **unverified against a real v31 game** (none available).
13//! - **v39** (Unity 6): each header entry also carries a record count, so the
14//!   entries are 12 bytes. Several records shrank: `type_definitions` dropped
15//!   `element_type_index` and narrowed `generic_container_index`; `methods`
16//!   narrowed its middle index fields (moving `parameter_start`); `images` and
17//!   `assemblies` were reordered; `generic_parameters` narrowed `owner_index`.
18//!   The v39 layout was reverse-engineered and validated against real Unity 6
19//!   games (which ship Windows PE binaries, read via pewter's PE support).
20//!
21//! ```no_run
22//! use hao_il2cpp::Metadata;
23//!
24//! let metadata = Metadata::from_path("Game_Data/il2cpp_data/Metadata/global-metadata.dat")?;
25//! println!("metadata v{}", metadata.version);
26//! for image in &metadata.images {
27//!     println!("{}:", metadata.image_name(image));
28//!     for index in metadata.image_types(image) {
29//!         let ty = &metadata.type_definitions[index as usize];
30//!         println!("    {} ({} methods)", metadata.type_full_name(index), ty.method_count);
31//!     }
32//! }
33//! # Ok::<(), hao_il2cpp::Error>(())
34//! ```
35
36use std::collections::HashMap;
37
38use hao::dotnet::entries::well_known::TypeName;
39
40use crate::error::{Error, Result};
41
42const SANITY: u32 = 0xFAB1_1BAF;
43
44/// Section names in header order, per metadata version.
45fn section_names(version: u32) -> Option<&'static [&'static str]> {
46    const V29: &[&str] = &[
47        "string_literal",
48        "string_literal_data",
49        "string",
50        "events",
51        "properties",
52        "methods",
53        "parameter_default_values",
54        "field_default_values",
55        "field_and_parameter_default_value_data",
56        "field_marshaled_sizes",
57        "parameters",
58        "fields",
59        "generic_parameters",
60        "generic_parameter_constraints",
61        "generic_containers",
62        "nested_types",
63        "interfaces",
64        "vtable_methods",
65        "interface_offsets",
66        "type_definitions",
67        "images",
68        "assemblies",
69        "field_refs",
70        "referenced_assemblies",
71        "attribute_data",
72        "attribute_data_range",
73        "unresolved_virtual_call_parameter_types",
74        "unresolved_virtual_call_parameter_ranges",
75        "windows_runtime_type_names",
76        "windows_runtime_strings",
77        "exported_type_definitions",
78    ];
79    // v31 and v39 keep the same sections in the same order as v29. v31 only
80    // widens the method record (see `read_tables`); v39 additionally changes the
81    // per-entry header size and several record layouts.
82    match version {
83        29 | 31 | 39 => Some(V29),
84        _ => None,
85    }
86}
87
88/// Bytes per header section entry: `(offset, size)` for v29, plus a record-count
89/// `u32` for v39.
90fn header_entry_size(version: u32) -> usize {
91    if version >= 39 {
92        12
93    } else {
94        8
95    }
96}
97
98struct Cursor<'a> {
99    data: &'a [u8],
100    position: usize,
101}
102
103impl Cursor<'_> {
104    fn bytes<const N: usize>(&mut self) -> [u8; N] {
105        let value = self.data[self.position..self.position + N]
106            .try_into()
107            .unwrap();
108        self.position += N;
109        value
110    }
111    fn u16(&mut self) -> u16 {
112        u16::from_le_bytes(self.bytes())
113    }
114    fn i16(&mut self) -> i16 {
115        i16::from_le_bytes(self.bytes())
116    }
117    fn u32(&mut self) -> u32 {
118        u32::from_le_bytes(self.bytes())
119    }
120    fn i32(&mut self) -> i32 {
121        i32::from_le_bytes(self.bytes())
122    }
123}
124
125/// An index into the binary's `Il2CppType` table.
126pub type TypeIndex = i32;
127/// An index into [`Metadata::type_definitions`].
128pub type TypeDefinitionIndex = i32;
129
130/// `Il2CppImageDefinition`: one image (module) of the game, e.g.
131/// `Assembly-CSharp.dll`, and the range of type definitions it owns.
132#[derive(Debug, Clone)]
133#[cfg_attr(feature = "reflect", derive(facet::Facet))]
134pub struct ImageDefinition {
135    /// The image's file name, e.g. `Assembly-CSharp.dll`. Index into the string pool; read it with [`Metadata::string`].
136    pub name_index: u32,
137    /// Index into [`Metadata::assemblies`] of the assembly this image belongs to.
138    pub assembly_index: i32,
139    /// Index into [`Metadata::type_definitions`] of this image's first type.
140    ///
141    /// v39 doesn't store it; it's computed as a running total, since types are laid out in image order.
142    pub type_start: i32,
143    /// How many type definitions the image owns, from `type_start` on.
144    pub type_count: u32,
145    /// Index into the `exported_type_definitions` section of this image's first exported type.
146    pub exported_type_start: i32,
147    /// How many exported types (e.g. type forwarders) the image has.
148    pub exported_type_count: u32,
149    /// Index into [`Metadata::methods`] of the entry point (`Main`), or -1.
150    pub entry_point_index: i32,
151    /// The image's module metadata token.
152    pub token: u32,
153    /// Index into the `attribute_data_range` section of this image's first attribute range.
154    pub custom_attribute_start: i32,
155    /// How many attribute ranges the image has. Always 0 for v39, which doesn't store it.
156    pub custom_attribute_count: u32,
157}
158
159/// `Il2CppAssemblyDefinition`: an assembly's identity and the image that holds it.
160#[derive(Debug, Clone)]
161#[cfg_attr(feature = "reflect", derive(facet::Facet))]
162pub struct AssemblyDefinition {
163    /// Index into [`Metadata::images`] of this assembly's image.
164    pub image_index: i32,
165    /// The assembly's metadata token.
166    pub token: u32,
167    /// Index into the `referenced_assemblies` section of the first assembly this one references.
168    pub referenced_assembly_start: i32,
169    /// How many assemblies this one references.
170    pub referenced_assembly_count: i32,
171    /// The assembly's simple name, e.g. `Assembly-CSharp`. Index into the string pool; read it with [`Metadata::string`].
172    pub name_index: u32,
173    /// The assembly's culture, empty for neutral. Index into the string pool; read it with [`Metadata::string`].
174    pub culture_index: u32,
175    /// The assembly's public key, as an escaped string. Index into the string pool; read it with [`Metadata::string`].
176    pub public_key_index: u32,
177    /// The hash algorithm id (`AssemblyHashAlgorithm`).
178    pub hash_alg: u32,
179    /// The length of the assembly hash.
180    pub hash_len: i32,
181    /// `AssemblyFlags`, e.g. whether the public key is full or a token.
182    pub flags: u32,
183    /// `[major, minor, build, revision]`.
184    pub version: [i32; 4],
185    /// The last 8 bytes of the public key's hash; all zero for an unsigned assembly.
186    pub public_key_token: [u8; 8],
187}
188
189/// `Il2CppTypeDefinition`: one type's name, flags, base type and the ranges
190/// of its members in the other tables.
191///
192/// Each `*_start` indexes the matching [`Metadata`] table and pairs with its
193/// `*_count`; [`Metadata::type_methods`] and [`Metadata::type_fields`] slice
194/// them for you.
195#[derive(Debug, Clone)]
196#[cfg_attr(feature = "reflect", derive(facet::Facet))]
197pub struct TypeDefinition {
198    /// The type's name, with the `` `N `` arity suffix for generics. Index into the string pool; read it with [`Metadata::string`].
199    pub name_index: u32,
200    /// The type's namespace, empty for nested types and the global namespace. Index into the string pool; read it with [`Metadata::string`].
201    pub namespace_index: u32,
202    /// This type itself in the binary's `Il2CppType` table (see [`Binary::type_at`](crate::Binary::type_at)).
203    pub byval_type_index: TypeIndex,
204    /// The enclosing type, as a [`TypeIndex`], or -1 for a top-level type.
205    pub declaring_type_index: TypeIndex,
206    /// The base type, as a [`TypeIndex`], or -1 (`System.Object`, interfaces).
207    pub parent_index: TypeIndex,
208    /// For an enum, its underlying type as a [`TypeIndex`]; otherwise -1.
209    ///
210    /// v39 doesn't store it, so it's always -1 there.
211    pub element_type_index: TypeIndex,
212    /// Index into [`Metadata::generic_containers`] if the type is generic, or -1.
213    pub generic_container_index: i32,
214    /// `TypeAttributes`: visibility, layout, class semantics (class or interface), etc.
215    pub flags: u32,
216    /// Index into [`Metadata::fields`] of the first field.
217    pub field_start: i32,
218    /// Index into [`Metadata::methods`] of the first method.
219    pub method_start: i32,
220    /// Index into [`Metadata::events`] of the first event.
221    pub event_start: i32,
222    /// Index into [`Metadata::properties`] of the first property.
223    pub property_start: i32,
224    /// Index into [`Metadata::nested_types`] of the first nested type.
225    pub nested_types_start: i32,
226    /// Index into [`Metadata::interfaces`] of the first implemented interface.
227    pub interfaces_start: i32,
228    /// Index into the `vtable_methods` section of the first vtable slot.
229    pub vtable_start: i32,
230    /// Index into the `interface_offsets` section of the first interface's vtable offset.
231    pub interface_offsets_start: i32,
232    /// How many methods the type declares.
233    pub method_count: u16,
234    /// How many properties the type declares.
235    pub property_count: u16,
236    /// How many fields the type declares.
237    pub field_count: u16,
238    /// How many events the type declares.
239    pub event_count: u16,
240    /// How many types are nested directly in this one.
241    pub nested_type_count: u16,
242    /// How many vtable slots the type has.
243    pub vtable_count: u16,
244    /// How many interfaces the type implements directly.
245    pub interfaces_count: u16,
246    /// How many interface vtable offsets the type has.
247    pub interface_offsets_count: u16,
248    /// Packed flags (IL2CPP's `bitfield`): value type, enum, has finalizer, has cctor, blittable, and the packing size.
249    pub bitfield: u32,
250    /// The type's `TypeDef` metadata token in its image.
251    pub token: u32,
252}
253
254/// `Il2CppMethodDefinition`: one method's name, signature and flags.
255#[derive(Debug, Clone)]
256#[cfg_attr(feature = "reflect", derive(facet::Facet))]
257pub struct MethodDefinition {
258    /// The method's name, e.g. `.ctor` or `Update`. Index into the string pool; read it with [`Metadata::string`].
259    pub name_index: u32,
260    /// The type that declares the method.
261    pub declaring_type: TypeDefinitionIndex,
262    /// The return type, as a [`TypeIndex`].
263    pub return_type: TypeIndex,
264    /// Index into [`Metadata::parameters`] of the first parameter; see [`Metadata::method_parameters`].
265    pub parameter_start: i32,
266    /// Index into [`Metadata::generic_containers`] if the method is generic, or -1.
267    pub generic_container_index: i32,
268    /// The method's `MethodDef` metadata token in its image; its RID indexes the image's method pointers in [`CodeGenModule`](crate::binary::CodeGenModule).
269    pub token: u32,
270    /// `MethodAttributes`: visibility, `static`, `virtual`, `abstract`, etc.
271    pub flags: u16,
272    /// `MethodImplAttributes`: e.g. `InternalCall`, `Synchronized`.
273    pub iflags: u16,
274    /// The method's vtable slot, or `0xFFFF` if it has none.
275    pub slot: u16,
276    /// How many parameters the method takes, not counting `this`.
277    pub parameter_count: u16,
278}
279
280/// `Il2CppFieldDefinition`: one field's name and type.
281#[derive(Debug, Clone)]
282#[cfg_attr(feature = "reflect", derive(facet::Facet))]
283pub struct FieldDefinition {
284    /// The field's name. Index into the string pool; read it with [`Metadata::string`].
285    pub name_index: u32,
286    /// The field's type, as a [`TypeIndex`]. Its `attrs` carry the field's `FieldAttributes` (e.g. `static`).
287    pub type_index: TypeIndex,
288    /// The field's `Field` metadata token in its image.
289    pub token: u32,
290}
291
292/// `Il2CppParameterDefinition`: one method parameter's name and type.
293#[derive(Debug, Clone)]
294#[cfg_attr(feature = "reflect", derive(facet::Facet))]
295pub struct ParameterDefinition {
296    /// The parameter's name. Index into the string pool; read it with [`Metadata::string`].
297    pub name_index: u32,
298    /// The parameter's `Param` metadata token in its image.
299    pub token: u32,
300    /// The parameter's type, as a [`TypeIndex`]. Its `attrs` carry the `ParamAttributes` (e.g. `out`).
301    pub type_index: TypeIndex,
302}
303
304/// `Il2CppPropertyDefinition`: a property and its accessors.
305#[derive(Debug, Clone)]
306#[cfg_attr(feature = "reflect", derive(facet::Facet))]
307pub struct PropertyDefinition {
308    /// The property's name. Index into the string pool; read it with [`Metadata::string`].
309    pub name_index: u32,
310    /// Method index relative to the declaring type's `method_start`, or -1.
311    pub get: i32,
312    /// The setter, as for `get`.
313    pub set: i32,
314    /// `PropertyAttributes`.
315    pub attrs: u32,
316    /// The property's `Property` metadata token in its image.
317    pub token: u32,
318}
319
320/// `Il2CppEventDefinition`: an event and its accessors.
321///
322/// Each accessor is a method index relative to the declaring type's
323/// `method_start`, or -1 if it has none.
324#[derive(Debug, Clone)]
325#[cfg_attr(feature = "reflect", derive(facet::Facet))]
326pub struct EventDefinition {
327    /// The event's name. Index into the string pool; read it with [`Metadata::string`].
328    pub name_index: u32,
329    /// The event's delegate type, as a [`TypeIndex`].
330    pub type_index: TypeIndex,
331    /// The `add` accessor.
332    pub add: i32,
333    /// The `remove` accessor.
334    pub remove: i32,
335    /// The `raise` accessor; C# never emits one, so usually -1.
336    pub raise: i32,
337    /// The event's `Event` metadata token in its image.
338    pub token: u32,
339}
340
341/// `Il2CppGenericContainer`: the generic parameter list of a generic type or method.
342#[derive(Debug, Clone)]
343#[cfg_attr(feature = "reflect", derive(facet::Facet))]
344pub struct GenericContainer {
345    /// A type definition index, or a method index when `is_method`.
346    pub owner_index: i32,
347    /// How many generic parameters it has.
348    pub type_argc: i32,
349    /// Whether the owner is a method rather than a type.
350    pub is_method: bool,
351    /// Index into [`Metadata::generic_parameters`] of the first parameter; see [`Metadata::generic_container_parameters`].
352    pub generic_parameter_start: i32,
353}
354
355/// `Il2CppGenericParameter`: one generic parameter, e.g. the `T` of `List<T>`.
356#[derive(Debug, Clone)]
357#[cfg_attr(feature = "reflect", derive(facet::Facet))]
358pub struct GenericParameter {
359    /// Index into [`Metadata::generic_containers`] of the container it belongs to.
360    pub owner_index: i32,
361    /// The parameter's name, e.g. `T`. Index into the string pool; read it with [`Metadata::string`].
362    pub name_index: u32,
363    /// Index into [`Metadata::generic_parameter_constraints`] of its first constraint.
364    pub constraints_start: i16,
365    /// How many type constraints it has.
366    pub constraints_count: i16,
367    /// Its position in the owner's parameter list, from 0.
368    pub num: u16,
369    /// `GenericParameterAttributes`: variance and `class` / `struct` / `new()` constraints.
370    pub flags: u16,
371}
372
373/// A parsed `global-metadata.dat`: its tables, decoded, and its string and
374/// data sections, read on demand.
375///
376/// The public tables are the raw records, in file order; indices stored in
377/// one record (e.g. [`TypeDefinition::method_start`]) index into these
378/// vectors.
379#[cfg_attr(feature = "reflect", derive(facet::Facet))]
380pub struct Metadata {
381    /// The metadata version: 29, 31 or 39.
382    pub version: u32,
383    data: Vec<u8>,
384    sections: HashMap<&'static str, (usize, usize)>,
385    /// Every image (module), e.g. `Assembly-CSharp.dll`.
386    pub images: Vec<ImageDefinition>,
387    /// Every assembly, one per image.
388    pub assemblies: Vec<AssemblyDefinition>,
389    /// Every type definition in the game, grouped by image; a [`TypeDefinitionIndex`] indexes this.
390    pub type_definitions: Vec<TypeDefinition>,
391    /// Every method definition, grouped by declaring type.
392    pub methods: Vec<MethodDefinition>,
393    /// Every field definition, grouped by declaring type.
394    pub fields: Vec<FieldDefinition>,
395    /// Every method parameter, grouped by method.
396    pub parameters: Vec<ParameterDefinition>,
397    /// Every property, grouped by declaring type.
398    pub properties: Vec<PropertyDefinition>,
399    /// Every event, grouped by declaring type.
400    pub events: Vec<EventDefinition>,
401    /// Generic parameter lists of generic types and methods.
402    pub generic_containers: Vec<GenericContainer>,
403    /// Every generic parameter; [`TypeKind::Var`](crate::binary::TypeKind::Var) and `MVar` index this.
404    pub generic_parameters: Vec<GenericParameter>,
405    /// Nested type lists, sliced by each type's `nested_types_start` and `nested_type_count`.
406    pub nested_types: Vec<TypeDefinitionIndex>,
407    /// Implemented interface lists, sliced by each type's `interfaces_start` and `interfaces_count`.
408    pub interfaces: Vec<TypeIndex>,
409    /// Constraint type lists, sliced by each generic parameter's `constraints_start` and `constraints_count`.
410    pub generic_parameter_constraints: Vec<TypeIndex>,
411    /// Constant values of `const` fields and enum members.
412    pub field_default_values: Vec<FieldDefaultValue>,
413    declaring_types: Vec<Option<TypeDefinitionIndex>>,
414}
415
416/// `Il2CppFieldDefaultValue`: a constant value for a field, stored in the
417/// default value data section.
418#[derive(Debug, Clone)]
419#[cfg_attr(feature = "reflect", derive(facet::Facet))]
420pub struct FieldDefaultValue {
421    /// Index into [`Metadata::fields`] of the field it belongs to.
422    pub field_index: i32,
423    /// The constant's type, as a [`TypeIndex`], which says how to decode the data.
424    pub type_index: TypeIndex,
425    /// Where the value starts in the default value data; read it with [`Metadata::default_value_data`].
426    pub data_index: i32,
427}
428
429impl Metadata {
430    /// Reads and parses a `global-metadata.dat` file.
431    pub fn from_path(path: impl AsRef<std::path::Path>) -> Result<Self> {
432        Self::parse(std::fs::read(path)?)
433    }
434
435    /// Parses `global-metadata.dat` from its bytes, decoding every table.
436    ///
437    /// Fails with [`Error::BadSanity`] if it isn't IL2CPP metadata,
438    /// [`Error::UnsupportedVersion`] for a version other than 29, 31 or 39,
439    /// and [`Error::BadSection`] if the header is inconsistent with the file.
440    pub fn parse(data: Vec<u8>) -> Result<Self> {
441        if data.len() < 8 {
442            return Err(Error::BadSection("header"));
443        }
444        let mut c = Cursor {
445            data: &data,
446            position: 0,
447        };
448        let sanity = c.u32();
449        if sanity != SANITY {
450            return Err(Error::BadSanity(sanity));
451        }
452        let version = c.u32();
453        let names = section_names(version).ok_or(Error::UnsupportedVersion(version))?;
454        let entry = header_entry_size(version);
455        let header_end = 8 + names.len() * entry;
456        if data.len() < header_end {
457            return Err(Error::BadSection("header"));
458        }
459        let mut sections = HashMap::new();
460        for name in names {
461            let offset = c.u32() as usize;
462            let size = c.i32().max(0) as usize;
463            // v39 stores a record count after each (offset, size); skip it.
464            c.position += entry - 8;
465            if offset < header_end && size != 0 || offset + size > data.len() {
466                return Err(Error::BadSection(name));
467            }
468            sections.insert(*name, (offset, size));
469        }
470
471        let mut metadata = Self {
472            version,
473            sections,
474            images: Vec::new(),
475            assemblies: Vec::new(),
476            type_definitions: Vec::new(),
477            methods: Vec::new(),
478            fields: Vec::new(),
479            parameters: Vec::new(),
480            properties: Vec::new(),
481            events: Vec::new(),
482            generic_containers: Vec::new(),
483            generic_parameters: Vec::new(),
484            nested_types: Vec::new(),
485            interfaces: Vec::new(),
486            generic_parameter_constraints: Vec::new(),
487            field_default_values: Vec::new(),
488            declaring_types: Vec::new(),
489            data: Vec::new(),
490        };
491        metadata.data = data;
492        metadata.read_tables()?;
493        Ok(metadata)
494    }
495
496    fn table<T>(
497        &self,
498        name: &'static str,
499        size: usize,
500        read: impl Fn(&mut Cursor) -> T,
501    ) -> Result<Vec<T>> {
502        let (offset, length) = self.sections[name];
503        if length % size != 0 {
504            return Err(Error::BadSection(name));
505        }
506        let mut c = Cursor {
507            data: &self.data[offset..offset + length],
508            position: 0,
509        };
510        Ok((0..length / size).map(|_| read(&mut c)).collect())
511    }
512
513    fn read_tables(&mut self) -> Result<()> {
514        let v39 = self.version >= 39;
515        if v39 {
516            // Unity 6 packs the image record unaligned and no longer stores
517            // type_start; type_count is at offset 10 and types are laid out in
518            // image order, so type_start is filled in as a running total below.
519            self.images = self.table("images", 36, |c| {
520                let name_index = c.u32();
521                let assembly_index = c.i32();
522                let _pad = c.u16();
523                let type_count = c.u32();
524                let (token, entry_point_index, exported_type_start) = (c.u32(), c.i32(), c.i32());
525                let (exported_type_count, custom_attribute_start) = (c.u32(), c.i32());
526                let _tail = c.u16();
527                ImageDefinition {
528                    name_index,
529                    assembly_index,
530                    token,
531                    entry_point_index,
532                    exported_type_start,
533                    exported_type_count,
534                    custom_attribute_start,
535                    custom_attribute_count: 0,
536                    type_start: 0,
537                    type_count,
538                }
539            })?;
540            let mut start = 0;
541            for image in &mut self.images {
542                image.type_start = start;
543                start += image.type_count as i32;
544            }
545            self.assemblies = self.table("assemblies", 68, |c| {
546                let (image_index, token) = (c.i32(), c.u32());
547                let (referenced_assembly_start, referenced_assembly_count) = (c.i32(), c.i32());
548                let _custom_attribute_start = c.i32();
549                AssemblyDefinition {
550                    image_index,
551                    token,
552                    referenced_assembly_start,
553                    referenced_assembly_count,
554                    name_index: c.u32(),
555                    culture_index: c.u32(),
556                    public_key_index: c.u32(),
557                    hash_alg: c.u32(),
558                    hash_len: c.i32(),
559                    flags: c.u32(),
560                    version: [c.i32(), c.i32(), c.i32(), c.i32()],
561                    public_key_token: c.bytes(),
562                }
563            })?;
564        } else {
565            self.images = self.table("images", 40, |c| ImageDefinition {
566                name_index: c.u32(),
567                assembly_index: c.i32(),
568                type_start: c.i32(),
569                type_count: c.u32(),
570                exported_type_start: c.i32(),
571                exported_type_count: c.u32(),
572                entry_point_index: c.i32(),
573                token: c.u32(),
574                custom_attribute_start: c.i32(),
575                custom_attribute_count: c.u32(),
576            })?;
577            self.assemblies = self.table("assemblies", 64, |c| AssemblyDefinition {
578                image_index: c.i32(),
579                token: c.u32(),
580                referenced_assembly_start: c.i32(),
581                referenced_assembly_count: c.i32(),
582                name_index: c.u32(),
583                culture_index: c.u32(),
584                public_key_index: c.u32(),
585                hash_alg: c.u32(),
586                hash_len: c.i32(),
587                flags: c.u32(),
588                version: [c.i32(), c.i32(), c.i32(), c.i32()],
589                public_key_token: c.bytes(),
590            })?;
591        }
592        // v39 dropped `element_type_index` and shrank `generic_container_index`
593        // to 16-bit; everything from `field_start` on is the same, 6 bytes earlier.
594        let (type_size, read_type): (usize, fn(&mut Cursor) -> TypeDefinition) = if v39 {
595            (82, |c| TypeDefinition {
596                name_index: c.u32(),
597                namespace_index: c.u32(),
598                byval_type_index: c.i32(),
599                declaring_type_index: c.i32(),
600                parent_index: c.i32(),
601                element_type_index: -1,
602                generic_container_index: c.i16() as i32,
603                flags: c.u32(),
604                field_start: c.i32(),
605                method_start: c.i32(),
606                event_start: c.i32(),
607                property_start: c.i32(),
608                nested_types_start: c.i32(),
609                interfaces_start: c.i32(),
610                vtable_start: c.i32(),
611                interface_offsets_start: c.i32(),
612                method_count: c.u16(),
613                property_count: c.u16(),
614                field_count: c.u16(),
615                event_count: c.u16(),
616                nested_type_count: c.u16(),
617                vtable_count: c.u16(),
618                interfaces_count: c.u16(),
619                interface_offsets_count: c.u16(),
620                bitfield: c.u32(),
621                token: c.u32(),
622            })
623        } else {
624            (88, |c| TypeDefinition {
625                name_index: c.u32(),
626                namespace_index: c.u32(),
627                byval_type_index: c.i32(),
628                declaring_type_index: c.i32(),
629                parent_index: c.i32(),
630                element_type_index: c.i32(),
631                generic_container_index: c.i32(),
632                flags: c.u32(),
633                field_start: c.i32(),
634                method_start: c.i32(),
635                event_start: c.i32(),
636                property_start: c.i32(),
637                nested_types_start: c.i32(),
638                interfaces_start: c.i32(),
639                vtable_start: c.i32(),
640                interface_offsets_start: c.i32(),
641                method_count: c.u16(),
642                property_count: c.u16(),
643                field_count: c.u16(),
644                event_count: c.u16(),
645                nested_type_count: c.u16(),
646                vtable_count: c.u16(),
647                interfaces_count: c.u16(),
648                interface_offsets_count: c.u16(),
649                bitfield: c.u32(),
650                token: c.u32(),
651            })
652        };
653        self.type_definitions = self.table("type_definitions", type_size, read_type)?;
654        // v39 packs the 32-byte method record unaligned: declaring_type is 16-bit,
655        // return_type sits at offset 6, and parameter_start at offset 14. token and
656        // the trailing flags/slot/count u16s stay where v29 had them.
657        self.methods = if v39 {
658            self.table("methods", 32, |c| {
659                let name_index = c.u32();
660                let declaring_type = c.u16() as i32;
661                let return_type = c.i32();
662                let generic_container_index = c.i32();
663                let parameter_start = c.i32();
664                let _pad = c.u16();
665                MethodDefinition {
666                    name_index,
667                    declaring_type,
668                    return_type,
669                    parameter_start,
670                    generic_container_index,
671                    token: c.u32(),
672                    flags: c.u16(),
673                    iflags: c.u16(),
674                    slot: c.u16(),
675                    parameter_count: c.u16(),
676                }
677            })?
678        } else if self.version >= 31 {
679            // v31 inserted a `returnParameterToken` (u32) right after `return_type`,
680            // growing the aligned record to 36 bytes; the field is unused here and
681            // discarded. This layout is taken from the Il2CppDumper/Il2CppInspector
682            // reference and is unverified against a real v31 game.
683            self.table("methods", 36, |c| {
684                let name_index = c.u32();
685                let declaring_type = c.i32();
686                let return_type = c.i32();
687                let _return_parameter_token = c.u32();
688                MethodDefinition {
689                    name_index,
690                    declaring_type,
691                    return_type,
692                    parameter_start: c.i32(),
693                    generic_container_index: c.i32(),
694                    token: c.u32(),
695                    flags: c.u16(),
696                    iflags: c.u16(),
697                    slot: c.u16(),
698                    parameter_count: c.u16(),
699                }
700            })?
701        } else {
702            self.table("methods", 32, |c| MethodDefinition {
703                name_index: c.u32(),
704                declaring_type: c.i32(),
705                return_type: c.i32(),
706                parameter_start: c.i32(),
707                generic_container_index: c.i32(),
708                token: c.u32(),
709                flags: c.u16(),
710                iflags: c.u16(),
711                slot: c.u16(),
712                parameter_count: c.u16(),
713            })?
714        };
715        self.fields = self.table("fields", 12, |c| FieldDefinition {
716            name_index: c.u32(),
717            type_index: c.i32(),
718            token: c.u32(),
719        })?;
720        self.parameters = self.table("parameters", 12, |c| ParameterDefinition {
721            name_index: c.u32(),
722            token: c.u32(),
723            type_index: c.i32(),
724        })?;
725        self.properties = self.table("properties", 20, |c| PropertyDefinition {
726            name_index: c.u32(),
727            get: c.i32(),
728            set: c.i32(),
729            attrs: c.u32(),
730            token: c.u32(),
731        })?;
732        self.events = self.table("events", 24, |c| EventDefinition {
733            name_index: c.u32(),
734            type_index: c.i32(),
735            add: c.i32(),
736            remove: c.i32(),
737            raise: c.i32(),
738            token: c.u32(),
739        })?;
740        self.generic_containers = self.table("generic_containers", 16, |c| GenericContainer {
741            owner_index: c.i32(),
742            type_argc: c.i32(),
743            is_method: c.i32() != 0,
744            generic_parameter_start: c.i32(),
745        })?;
746        // v39 shrank owner_index to 16-bit (name_index then sits at offset 2).
747        let (gp_size, read_gp): (usize, fn(&mut Cursor) -> GenericParameter) = if v39 {
748            (14, |c| GenericParameter {
749                owner_index: c.u16() as i32,
750                name_index: c.u32(),
751                constraints_start: c.i16(),
752                constraints_count: c.i16(),
753                num: c.u16(),
754                flags: c.u16(),
755            })
756        } else {
757            (16, |c| GenericParameter {
758                owner_index: c.i32(),
759                name_index: c.u32(),
760                constraints_start: c.i16(),
761                constraints_count: c.i16(),
762                num: c.u16(),
763                flags: c.u16(),
764            })
765        };
766        self.generic_parameters = self.table("generic_parameters", gp_size, read_gp)?;
767        self.nested_types = self.table("nested_types", 4, |c| c.i32())?;
768        self.interfaces = self.table("interfaces", 4, |c| c.i32())?;
769        self.generic_parameter_constraints =
770            self.table("generic_parameter_constraints", 4, |c| c.i32())?;
771        self.field_default_values =
772            self.table("field_default_values", 12, |c| FieldDefaultValue {
773                field_index: c.i32(),
774                type_index: c.i32(),
775                data_index: c.i32(),
776            })?;
777        self.declaring_types = vec![None; self.type_definitions.len()];
778        for (i, t) in self.type_definitions.iter().enumerate() {
779            let start = t.nested_types_start.max(0) as usize;
780            for nested in self
781                .nested_types
782                .get(start..start + t.nested_type_count as usize)
783                .unwrap_or(&[])
784            {
785                if let Some(slot) = usize::try_from(*nested)
786                    .ok()
787                    .and_then(|n| self.declaring_types.get_mut(n))
788                {
789                    *slot = Some(i as TypeDefinitionIndex);
790                }
791            }
792        }
793        Ok(())
794    }
795
796    /// A string from the `#Strings`-like string section.
797    pub fn string(&self, index: u32) -> &str {
798        let (offset, size) = self.sections["string"];
799        let heap = &self.data[offset..offset + size];
800        let start = (index as usize).min(heap.len());
801        let end = heap[start..]
802            .iter()
803            .position(|b| *b == 0)
804            .map_or(heap.len(), |p| start + p);
805        std::str::from_utf8(&heap[start..end]).unwrap_or("")
806    }
807
808    /// A type definition's own name, without namespace or declaring type.
809    ///
810    /// Panics if `index` is out of range.
811    pub fn type_name(&self, index: TypeDefinitionIndex) -> &str {
812        self.string(self.type_definitions[index as usize].name_index)
813    }
814
815    /// `Namespace.Name`, with `/` separating nested types.
816    pub fn type_full_name(&self, index: TypeDefinitionIndex) -> String {
817        let t = &self.type_definitions[index as usize];
818        let name = self.string(t.name_index);
819        if let Some(parent) = self.declaring_type_definition(index) {
820            return format!("{}/{}", self.type_full_name(parent), name);
821        }
822        match self.string(t.namespace_index) {
823            "" => name.to_owned(),
824            ns => format!("{}.{}", ns, name),
825        }
826    }
827
828    /// The index of the top-level type definition named `ty`, e.g.
829    /// `metadata.find_type(WellKnown::System(SystemType::String))` or
830    /// `metadata.find_type(("System", "String"))`.
831    pub fn find_type(&self, ty: impl TypeName) -> Option<TypeDefinitionIndex> {
832        let (namespace, name) = ty.type_name();
833        self.type_definitions
834            .iter()
835            .position(|t| {
836                t.declaring_type_index < 0
837                    && self.string(t.namespace_index) == namespace.as_ref()
838                    && self.string(t.name_index) == name.as_ref()
839            })
840            .map(|i| i as TypeDefinitionIndex)
841    }
842
843    /// The enclosing type definition, found through the nested type lists.
844    pub fn declaring_type_definition(
845        &self,
846        index: TypeDefinitionIndex,
847    ) -> Option<TypeDefinitionIndex> {
848        self.declaring_types.get(index as usize).copied().flatten()
849    }
850
851    /// An image's file name, e.g. `Assembly-CSharp.dll`.
852    pub fn image_name(&self, image: &ImageDefinition) -> &str {
853        self.string(image.name_index)
854    }
855
856    /// Type definition indices belonging to `image`.
857    pub fn image_types(&self, image: &ImageDefinition) -> std::ops::Range<TypeDefinitionIndex> {
858        image.type_start..image.type_start + image.type_count as i32
859    }
860
861    /// The methods a type declares; empty if its range is out of bounds.
862    pub fn type_methods(&self, t: &TypeDefinition) -> &[MethodDefinition] {
863        let start = t.method_start.max(0) as usize;
864        self.methods
865            .get(start..start + t.method_count as usize)
866            .unwrap_or(&[])
867    }
868
869    /// The fields a type declares; empty if its range is out of bounds.
870    pub fn type_fields(&self, t: &TypeDefinition) -> &[FieldDefinition] {
871        let start = t.field_start.max(0) as usize;
872        self.fields
873            .get(start..start + t.field_count as usize)
874            .unwrap_or(&[])
875    }
876
877    /// Bytes of the default value data section from `index` on.
878    pub fn default_value_data(&self, index: i32) -> &[u8] {
879        let (offset, size) = self.sections["field_and_parameter_default_value_data"];
880        let data = &self.data[offset..offset + size];
881        usize::try_from(index)
882            .ok()
883            .and_then(|i| data.get(i..))
884            .unwrap_or(&[])
885    }
886
887    /// The generic parameters of a [`GenericContainer`], by index into
888    /// [`Metadata::generic_containers`] (e.g. a type's `generic_container_index`);
889    /// empty for -1.
890    pub fn generic_container_parameters(&self, container: i32) -> &[GenericParameter] {
891        let Some(c) = usize::try_from(container)
892            .ok()
893            .and_then(|i| self.generic_containers.get(i))
894        else {
895            return &[];
896        };
897        let start = c.generic_parameter_start.max(0) as usize;
898        self.generic_parameters
899            .get(start..start + c.type_argc.max(0) as usize)
900            .unwrap_or(&[])
901    }
902
903    /// A method's parameters, in order; empty if its range is out of bounds.
904    pub fn method_parameters(&self, m: &MethodDefinition) -> &[ParameterDefinition] {
905        let start = m.parameter_start.max(0) as usize;
906        self.parameters
907            .get(start..start + m.parameter_count as usize)
908            .unwrap_or(&[])
909    }
910
911    /// The `(token, start_offset)` entries of the `attribute_data_range` section
912    /// (v29+). Each `start_offset` indexes into [`Metadata::attribute_data`]; a
913    /// range ends where the next entry begins, as the section is laid out in global
914    /// offset order (`Il2CppCustomAttributeDataRange`).
915    pub fn attribute_data_ranges(&self) -> Vec<(u32, u32)> {
916        let (offset, size) = self.sections["attribute_data_range"];
917        self.data[offset..offset + size]
918            .as_chunks::<8>()
919            .0
920            .iter()
921            .map(|c| {
922                (
923                    u32::from_le_bytes(c[0..4].try_into().unwrap()),
924                    u32::from_le_bytes(c[4..8].try_into().unwrap()),
925                )
926            })
927            .collect()
928    }
929
930    /// The raw `attribute_data` blob holding v29+ custom attribute values.
931    pub fn attribute_data(&self) -> &[u8] {
932        let (offset, size) = self.sections["attribute_data"];
933        &self.data[offset..offset + size]
934    }
935}
936
937#[cfg(test)]
938mod tests {
939    use super::*;
940
941    /// Build a minimal valid `global-metadata.dat` for `version` whose only
942    /// non-empty section is `methods`, carrying the raw bytes `method`.
943    fn metadata_with_method(version: u32, method: &[u8]) -> Vec<u8> {
944        let names = section_names(version).unwrap();
945        let header_end = 8 + names.len() * header_entry_size(version);
946        let methods_index = names.iter().position(|n| *n == "methods").unwrap();
947
948        let mut buf = Vec::new();
949        buf.extend_from_slice(&SANITY.to_le_bytes());
950        buf.extend_from_slice(&version.to_le_bytes());
951        for (i, _) in names.iter().enumerate() {
952            if i == methods_index {
953                buf.extend_from_slice(&(header_end as u32).to_le_bytes());
954                buf.extend_from_slice(&(method.len() as u32).to_le_bytes());
955            } else {
956                buf.extend_from_slice(&0u32.to_le_bytes());
957                buf.extend_from_slice(&0u32.to_le_bytes());
958            }
959        }
960        assert_eq!(buf.len(), header_end);
961        buf.extend_from_slice(method);
962        buf
963    }
964
965    /// v31 dispatch: the method record is 36 bytes with a `returnParameterToken`
966    /// inserted after `return_type` that must be skipped, not surfaced as any
967    /// later field. (Reference layout; no real v31 game to validate against.)
968    #[test]
969    fn v31_method_record_skips_return_parameter_token() {
970        let mut m = Vec::new();
971        for v in [11u32, 22, 33, 0xDEAD_BEEF, 44, 55, 66] {
972            m.extend_from_slice(&v.to_le_bytes());
973        }
974        for v in [7u16, 8, 9, 10] {
975            m.extend_from_slice(&v.to_le_bytes());
976        }
977        assert_eq!(m.len(), 36);
978
979        let md = Metadata::parse(metadata_with_method(31, &m)).unwrap();
980        assert_eq!(md.version, 31);
981        assert_eq!(md.methods.len(), 1);
982        let method = &md.methods[0];
983        assert_eq!(method.name_index, 11);
984        assert_eq!(method.declaring_type, 22);
985        assert_eq!(method.return_type, 33);
986        // 0xDEADBEEF was the returnParameterToken and must be discarded.
987        assert_eq!(method.parameter_start, 44);
988        assert_eq!(method.generic_container_index, 55);
989        assert_eq!(method.token, 66);
990        assert_eq!(method.flags, 7);
991        assert_eq!(method.parameter_count, 10);
992    }
993
994    /// v29 stays a 32-byte record with no `returnParameterToken`.
995    #[test]
996    fn v29_method_record_is_unchanged() {
997        let mut m = Vec::new();
998        for v in [11u32, 22, 33, 44, 55, 66] {
999            m.extend_from_slice(&v.to_le_bytes());
1000        }
1001        for v in [7u16, 8, 9, 10] {
1002            m.extend_from_slice(&v.to_le_bytes());
1003        }
1004        assert_eq!(m.len(), 32);
1005
1006        let md = Metadata::parse(metadata_with_method(29, &m)).unwrap();
1007        assert_eq!(md.methods.len(), 1);
1008        let method = &md.methods[0];
1009        assert_eq!(method.return_type, 33);
1010        assert_eq!(method.parameter_start, 44);
1011        assert_eq!(method.generic_container_index, 55);
1012    }
1013
1014    #[test]
1015    fn unknown_version_is_rejected() {
1016        let mut buf = Vec::new();
1017        buf.extend_from_slice(&SANITY.to_le_bytes());
1018        buf.extend_from_slice(&30u32.to_le_bytes());
1019        assert!(matches!(
1020            Metadata::parse(buf),
1021            Err(Error::UnsupportedVersion(30))
1022        ));
1023    }
1024}