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//! Two metadata versions are supported:
7//! - **v29** (Unity 2021.2 – 2023.x): header entries are `(offset, size)` pairs.
8//! - **v39** (Unity 6): each header entry also carries a record count, so the
9//!   entries are 12 bytes. Several records shrank: `type_definitions` dropped
10//!   `element_type_index` and narrowed `generic_container_index`; `methods`
11//!   narrowed its middle index fields (moving `parameter_start`); `images` and
12//!   `assemblies` were reordered; `generic_parameters` narrowed `owner_index`.
13//!   The v39 layout was reverse-engineered and validated against real Unity 6
14//!   games (which ship Windows PE binaries, read via pewter's PE support).
15
16use std::collections::HashMap;
17
18use crate::error::{Error, Result};
19
20const SANITY: u32 = 0xFAB1_1BAF;
21
22/// Section names in header order, per metadata version.
23fn section_names(version: u32) -> Option<&'static [&'static str]> {
24    const V29: &[&str] = &[
25        "string_literal",
26        "string_literal_data",
27        "string",
28        "events",
29        "properties",
30        "methods",
31        "parameter_default_values",
32        "field_default_values",
33        "field_and_parameter_default_value_data",
34        "field_marshaled_sizes",
35        "parameters",
36        "fields",
37        "generic_parameters",
38        "generic_parameter_constraints",
39        "generic_containers",
40        "nested_types",
41        "interfaces",
42        "vtable_methods",
43        "interface_offsets",
44        "type_definitions",
45        "images",
46        "assemblies",
47        "field_refs",
48        "referenced_assemblies",
49        "attribute_data",
50        "attribute_data_range",
51        "unresolved_virtual_call_parameter_types",
52        "unresolved_virtual_call_parameter_ranges",
53        "windows_runtime_type_names",
54        "windows_runtime_strings",
55        "exported_type_definitions",
56    ];
57    // v39 (Unity 6) keeps the same sections in the same order as v29; only the
58    // per-entry header size and some record layouts differ (see `read_tables`).
59    match version {
60        29 | 39 => Some(V29),
61        _ => None,
62    }
63}
64
65/// Bytes per header section entry: `(offset, size)` for v29, plus a record-count
66/// `u32` for v39.
67fn header_entry_size(version: u32) -> usize {
68    if version >= 39 {
69        12
70    } else {
71        8
72    }
73}
74
75struct Cursor<'a> {
76    data: &'a [u8],
77    position: usize,
78}
79
80impl Cursor<'_> {
81    fn bytes<const N: usize>(&mut self) -> [u8; N] {
82        let value = self.data[self.position..self.position + N]
83            .try_into()
84            .unwrap();
85        self.position += N;
86        value
87    }
88    fn u16(&mut self) -> u16 {
89        u16::from_le_bytes(self.bytes())
90    }
91    fn i16(&mut self) -> i16 {
92        i16::from_le_bytes(self.bytes())
93    }
94    fn u32(&mut self) -> u32 {
95        u32::from_le_bytes(self.bytes())
96    }
97    fn i32(&mut self) -> i32 {
98        i32::from_le_bytes(self.bytes())
99    }
100}
101
102/// An index into the binary's `Il2CppType` table.
103pub type TypeIndex = i32;
104/// An index into [`Metadata::type_definitions`].
105pub type TypeDefinitionIndex = i32;
106
107#[derive(Debug, Clone)]
108#[cfg_attr(feature = "reflect", derive(facet::Facet))]
109pub struct ImageDefinition {
110    pub name_index: u32,
111    pub assembly_index: i32,
112    pub type_start: i32,
113    pub type_count: u32,
114    pub exported_type_start: i32,
115    pub exported_type_count: u32,
116    pub entry_point_index: i32,
117    pub token: u32,
118    pub custom_attribute_start: i32,
119    pub custom_attribute_count: u32,
120}
121
122#[derive(Debug, Clone)]
123#[cfg_attr(feature = "reflect", derive(facet::Facet))]
124pub struct AssemblyDefinition {
125    pub image_index: i32,
126    pub token: u32,
127    pub referenced_assembly_start: i32,
128    pub referenced_assembly_count: i32,
129    pub name_index: u32,
130    pub culture_index: u32,
131    pub public_key_index: u32,
132    pub hash_alg: u32,
133    pub hash_len: i32,
134    pub flags: u32,
135    pub version: [i32; 4],
136    pub public_key_token: [u8; 8],
137}
138
139#[derive(Debug, Clone)]
140#[cfg_attr(feature = "reflect", derive(facet::Facet))]
141pub struct TypeDefinition {
142    pub name_index: u32,
143    pub namespace_index: u32,
144    pub byval_type_index: TypeIndex,
145    pub declaring_type_index: TypeIndex,
146    pub parent_index: TypeIndex,
147    pub element_type_index: TypeIndex,
148    pub generic_container_index: i32,
149    pub flags: u32,
150    pub field_start: i32,
151    pub method_start: i32,
152    pub event_start: i32,
153    pub property_start: i32,
154    pub nested_types_start: i32,
155    pub interfaces_start: i32,
156    pub vtable_start: i32,
157    pub interface_offsets_start: i32,
158    pub method_count: u16,
159    pub property_count: u16,
160    pub field_count: u16,
161    pub event_count: u16,
162    pub nested_type_count: u16,
163    pub vtable_count: u16,
164    pub interfaces_count: u16,
165    pub interface_offsets_count: u16,
166    pub bitfield: u32,
167    pub token: u32,
168}
169
170#[derive(Debug, Clone)]
171#[cfg_attr(feature = "reflect", derive(facet::Facet))]
172pub struct MethodDefinition {
173    pub name_index: u32,
174    pub declaring_type: TypeDefinitionIndex,
175    pub return_type: TypeIndex,
176    pub parameter_start: i32,
177    pub generic_container_index: i32,
178    pub token: u32,
179    pub flags: u16,
180    pub iflags: u16,
181    pub slot: u16,
182    pub parameter_count: u16,
183}
184
185#[derive(Debug, Clone)]
186#[cfg_attr(feature = "reflect", derive(facet::Facet))]
187pub struct FieldDefinition {
188    pub name_index: u32,
189    pub type_index: TypeIndex,
190    pub token: u32,
191}
192
193#[derive(Debug, Clone)]
194#[cfg_attr(feature = "reflect", derive(facet::Facet))]
195pub struct ParameterDefinition {
196    pub name_index: u32,
197    pub token: u32,
198    pub type_index: TypeIndex,
199}
200
201#[derive(Debug, Clone)]
202#[cfg_attr(feature = "reflect", derive(facet::Facet))]
203pub struct PropertyDefinition {
204    pub name_index: u32,
205    /// Method index relative to the declaring type's `method_start`, or -1.
206    pub get: i32,
207    pub set: i32,
208    pub attrs: u32,
209    pub token: u32,
210}
211
212#[derive(Debug, Clone)]
213#[cfg_attr(feature = "reflect", derive(facet::Facet))]
214pub struct EventDefinition {
215    pub name_index: u32,
216    pub type_index: TypeIndex,
217    pub add: i32,
218    pub remove: i32,
219    pub raise: i32,
220    pub token: u32,
221}
222
223#[derive(Debug, Clone)]
224#[cfg_attr(feature = "reflect", derive(facet::Facet))]
225pub struct GenericContainer {
226    /// A type definition index, or a method index when `is_method`.
227    pub owner_index: i32,
228    pub type_argc: i32,
229    pub is_method: bool,
230    pub generic_parameter_start: i32,
231}
232
233#[derive(Debug, Clone)]
234#[cfg_attr(feature = "reflect", derive(facet::Facet))]
235pub struct GenericParameter {
236    pub owner_index: i32,
237    pub name_index: u32,
238    pub constraints_start: i16,
239    pub constraints_count: i16,
240    pub num: u16,
241    pub flags: u16,
242}
243
244#[cfg_attr(feature = "reflect", derive(facet::Facet))]
245pub struct Metadata {
246    pub version: u32,
247    data: Vec<u8>,
248    sections: HashMap<&'static str, (usize, usize)>,
249    pub images: Vec<ImageDefinition>,
250    pub assemblies: Vec<AssemblyDefinition>,
251    pub type_definitions: Vec<TypeDefinition>,
252    pub methods: Vec<MethodDefinition>,
253    pub fields: Vec<FieldDefinition>,
254    pub parameters: Vec<ParameterDefinition>,
255    pub properties: Vec<PropertyDefinition>,
256    pub events: Vec<EventDefinition>,
257    pub generic_containers: Vec<GenericContainer>,
258    pub generic_parameters: Vec<GenericParameter>,
259    pub nested_types: Vec<TypeDefinitionIndex>,
260    pub interfaces: Vec<TypeIndex>,
261    pub generic_parameter_constraints: Vec<TypeIndex>,
262    pub field_default_values: Vec<FieldDefaultValue>,
263    declaring_types: Vec<Option<TypeDefinitionIndex>>,
264}
265
266/// A constant value for a field, stored in the default value data section.
267#[derive(Debug, Clone)]
268#[cfg_attr(feature = "reflect", derive(facet::Facet))]
269pub struct FieldDefaultValue {
270    pub field_index: i32,
271    pub type_index: TypeIndex,
272    pub data_index: i32,
273}
274
275impl Metadata {
276    pub fn from_path(path: impl AsRef<std::path::Path>) -> Result<Self> {
277        Self::parse(std::fs::read(path)?)
278    }
279
280    pub fn parse(data: Vec<u8>) -> Result<Self> {
281        if data.len() < 8 {
282            return Err(Error::BadSection("header"));
283        }
284        let mut c = Cursor {
285            data: &data,
286            position: 0,
287        };
288        let sanity = c.u32();
289        if sanity != SANITY {
290            return Err(Error::BadSanity(sanity));
291        }
292        let version = c.u32();
293        let names = section_names(version).ok_or(Error::UnsupportedVersion(version))?;
294        let entry = header_entry_size(version);
295        let header_end = 8 + names.len() * entry;
296        if data.len() < header_end {
297            return Err(Error::BadSection("header"));
298        }
299        let mut sections = HashMap::new();
300        for name in names {
301            let offset = c.u32() as usize;
302            let size = c.i32().max(0) as usize;
303            // v39 stores a record count after each (offset, size); skip it.
304            c.position += entry - 8;
305            if offset < header_end && size != 0 || offset + size > data.len() {
306                return Err(Error::BadSection(name));
307            }
308            sections.insert(*name, (offset, size));
309        }
310
311        let mut metadata = Self {
312            version,
313            sections,
314            images: Vec::new(),
315            assemblies: Vec::new(),
316            type_definitions: Vec::new(),
317            methods: Vec::new(),
318            fields: Vec::new(),
319            parameters: Vec::new(),
320            properties: Vec::new(),
321            events: Vec::new(),
322            generic_containers: Vec::new(),
323            generic_parameters: Vec::new(),
324            nested_types: Vec::new(),
325            interfaces: Vec::new(),
326            generic_parameter_constraints: Vec::new(),
327            field_default_values: Vec::new(),
328            declaring_types: Vec::new(),
329            data: Vec::new(),
330        };
331        metadata.data = data;
332        metadata.read_tables()?;
333        Ok(metadata)
334    }
335
336    fn table<T>(
337        &self,
338        name: &'static str,
339        size: usize,
340        read: impl Fn(&mut Cursor) -> T,
341    ) -> Result<Vec<T>> {
342        let (offset, length) = self.sections[name];
343        if length % size != 0 {
344            return Err(Error::BadSection(name));
345        }
346        let mut c = Cursor {
347            data: &self.data[offset..offset + length],
348            position: 0,
349        };
350        Ok((0..length / size).map(|_| read(&mut c)).collect())
351    }
352
353    fn read_tables(&mut self) -> Result<()> {
354        let v39 = self.version >= 39;
355        if v39 {
356            // Unity 6 packs the image record unaligned and no longer stores
357            // type_start; type_count is at offset 10 and types are laid out in
358            // image order, so type_start is filled in as a running total below.
359            self.images = self.table("images", 36, |c| {
360                let name_index = c.u32();
361                let assembly_index = c.i32();
362                let _pad = c.u16();
363                let type_count = c.u32();
364                let (token, entry_point_index, exported_type_start) = (c.u32(), c.i32(), c.i32());
365                let (exported_type_count, custom_attribute_start) = (c.u32(), c.i32());
366                let _tail = c.u16();
367                ImageDefinition {
368                    name_index,
369                    assembly_index,
370                    token,
371                    entry_point_index,
372                    exported_type_start,
373                    exported_type_count,
374                    custom_attribute_start,
375                    custom_attribute_count: 0,
376                    type_start: 0,
377                    type_count,
378                }
379            })?;
380            let mut start = 0;
381            for image in &mut self.images {
382                image.type_start = start;
383                start += image.type_count as i32;
384            }
385            self.assemblies = self.table("assemblies", 68, |c| {
386                let (image_index, token) = (c.i32(), c.u32());
387                let (referenced_assembly_start, referenced_assembly_count) = (c.i32(), c.i32());
388                let _custom_attribute_start = c.i32();
389                AssemblyDefinition {
390                    image_index,
391                    token,
392                    referenced_assembly_start,
393                    referenced_assembly_count,
394                    name_index: c.u32(),
395                    culture_index: c.u32(),
396                    public_key_index: c.u32(),
397                    hash_alg: c.u32(),
398                    hash_len: c.i32(),
399                    flags: c.u32(),
400                    version: [c.i32(), c.i32(), c.i32(), c.i32()],
401                    public_key_token: c.bytes(),
402                }
403            })?;
404        } else {
405            self.images = self.table("images", 40, |c| ImageDefinition {
406                name_index: c.u32(),
407                assembly_index: c.i32(),
408                type_start: c.i32(),
409                type_count: c.u32(),
410                exported_type_start: c.i32(),
411                exported_type_count: c.u32(),
412                entry_point_index: c.i32(),
413                token: c.u32(),
414                custom_attribute_start: c.i32(),
415                custom_attribute_count: c.u32(),
416            })?;
417            self.assemblies = self.table("assemblies", 64, |c| AssemblyDefinition {
418                image_index: c.i32(),
419                token: c.u32(),
420                referenced_assembly_start: c.i32(),
421                referenced_assembly_count: c.i32(),
422                name_index: c.u32(),
423                culture_index: c.u32(),
424                public_key_index: c.u32(),
425                hash_alg: c.u32(),
426                hash_len: c.i32(),
427                flags: c.u32(),
428                version: [c.i32(), c.i32(), c.i32(), c.i32()],
429                public_key_token: c.bytes(),
430            })?;
431        }
432        // v39 dropped `element_type_index` and shrank `generic_container_index`
433        // to 16-bit; everything from `field_start` on is the same, 6 bytes earlier.
434        let (type_size, read_type): (usize, fn(&mut Cursor) -> TypeDefinition) = if v39 {
435            (82, |c| TypeDefinition {
436                name_index: c.u32(),
437                namespace_index: c.u32(),
438                byval_type_index: c.i32(),
439                declaring_type_index: c.i32(),
440                parent_index: c.i32(),
441                element_type_index: -1,
442                generic_container_index: c.i16() as i32,
443                flags: c.u32(),
444                field_start: c.i32(),
445                method_start: c.i32(),
446                event_start: c.i32(),
447                property_start: c.i32(),
448                nested_types_start: c.i32(),
449                interfaces_start: c.i32(),
450                vtable_start: c.i32(),
451                interface_offsets_start: c.i32(),
452                method_count: c.u16(),
453                property_count: c.u16(),
454                field_count: c.u16(),
455                event_count: c.u16(),
456                nested_type_count: c.u16(),
457                vtable_count: c.u16(),
458                interfaces_count: c.u16(),
459                interface_offsets_count: c.u16(),
460                bitfield: c.u32(),
461                token: c.u32(),
462            })
463        } else {
464            (88, |c| TypeDefinition {
465                name_index: c.u32(),
466                namespace_index: c.u32(),
467                byval_type_index: c.i32(),
468                declaring_type_index: c.i32(),
469                parent_index: c.i32(),
470                element_type_index: c.i32(),
471                generic_container_index: c.i32(),
472                flags: c.u32(),
473                field_start: c.i32(),
474                method_start: c.i32(),
475                event_start: c.i32(),
476                property_start: c.i32(),
477                nested_types_start: c.i32(),
478                interfaces_start: c.i32(),
479                vtable_start: c.i32(),
480                interface_offsets_start: c.i32(),
481                method_count: c.u16(),
482                property_count: c.u16(),
483                field_count: c.u16(),
484                event_count: c.u16(),
485                nested_type_count: c.u16(),
486                vtable_count: c.u16(),
487                interfaces_count: c.u16(),
488                interface_offsets_count: c.u16(),
489                bitfield: c.u32(),
490                token: c.u32(),
491            })
492        };
493        self.type_definitions = self.table("type_definitions", type_size, read_type)?;
494        // v39 packs the 32-byte method record unaligned: declaring_type is 16-bit,
495        // return_type sits at offset 6, and parameter_start at offset 14. token and
496        // the trailing flags/slot/count u16s stay where v29 had them.
497        self.methods = if v39 {
498            self.table("methods", 32, |c| {
499                let name_index = c.u32();
500                let declaring_type = c.u16() as i32;
501                let return_type = c.i32();
502                let generic_container_index = c.i32();
503                let parameter_start = c.i32();
504                let _pad = c.u16();
505                MethodDefinition {
506                    name_index,
507                    declaring_type,
508                    return_type,
509                    parameter_start,
510                    generic_container_index,
511                    token: c.u32(),
512                    flags: c.u16(),
513                    iflags: c.u16(),
514                    slot: c.u16(),
515                    parameter_count: c.u16(),
516                }
517            })?
518        } else {
519            self.table("methods", 32, |c| MethodDefinition {
520                name_index: c.u32(),
521                declaring_type: c.i32(),
522                return_type: c.i32(),
523                parameter_start: c.i32(),
524                generic_container_index: c.i32(),
525                token: c.u32(),
526                flags: c.u16(),
527                iflags: c.u16(),
528                slot: c.u16(),
529                parameter_count: c.u16(),
530            })?
531        };
532        self.fields = self.table("fields", 12, |c| FieldDefinition {
533            name_index: c.u32(),
534            type_index: c.i32(),
535            token: c.u32(),
536        })?;
537        self.parameters = self.table("parameters", 12, |c| ParameterDefinition {
538            name_index: c.u32(),
539            token: c.u32(),
540            type_index: c.i32(),
541        })?;
542        self.properties = self.table("properties", 20, |c| PropertyDefinition {
543            name_index: c.u32(),
544            get: c.i32(),
545            set: c.i32(),
546            attrs: c.u32(),
547            token: c.u32(),
548        })?;
549        self.events = self.table("events", 24, |c| EventDefinition {
550            name_index: c.u32(),
551            type_index: c.i32(),
552            add: c.i32(),
553            remove: c.i32(),
554            raise: c.i32(),
555            token: c.u32(),
556        })?;
557        self.generic_containers = self.table("generic_containers", 16, |c| GenericContainer {
558            owner_index: c.i32(),
559            type_argc: c.i32(),
560            is_method: c.i32() != 0,
561            generic_parameter_start: c.i32(),
562        })?;
563        // v39 shrank owner_index to 16-bit (name_index then sits at offset 2).
564        let (gp_size, read_gp): (usize, fn(&mut Cursor) -> GenericParameter) = if v39 {
565            (14, |c| GenericParameter {
566                owner_index: c.u16() as i32,
567                name_index: c.u32(),
568                constraints_start: c.i16(),
569                constraints_count: c.i16(),
570                num: c.u16(),
571                flags: c.u16(),
572            })
573        } else {
574            (16, |c| GenericParameter {
575                owner_index: c.i32(),
576                name_index: c.u32(),
577                constraints_start: c.i16(),
578                constraints_count: c.i16(),
579                num: c.u16(),
580                flags: c.u16(),
581            })
582        };
583        self.generic_parameters = self.table("generic_parameters", gp_size, read_gp)?;
584        self.nested_types = self.table("nested_types", 4, |c| c.i32())?;
585        self.interfaces = self.table("interfaces", 4, |c| c.i32())?;
586        self.generic_parameter_constraints =
587            self.table("generic_parameter_constraints", 4, |c| c.i32())?;
588        self.field_default_values =
589            self.table("field_default_values", 12, |c| FieldDefaultValue {
590                field_index: c.i32(),
591                type_index: c.i32(),
592                data_index: c.i32(),
593            })?;
594        self.declaring_types = vec![None; self.type_definitions.len()];
595        for (i, t) in self.type_definitions.iter().enumerate() {
596            let start = t.nested_types_start.max(0) as usize;
597            for nested in self
598                .nested_types
599                .get(start..start + t.nested_type_count as usize)
600                .unwrap_or(&[])
601            {
602                if let Some(slot) = usize::try_from(*nested)
603                    .ok()
604                    .and_then(|n| self.declaring_types.get_mut(n))
605                {
606                    *slot = Some(i as TypeDefinitionIndex);
607                }
608            }
609        }
610        Ok(())
611    }
612
613    /// A string from the `#Strings`-like string section.
614    pub fn string(&self, index: u32) -> &str {
615        let (offset, size) = self.sections["string"];
616        let heap = &self.data[offset..offset + size];
617        let start = (index as usize).min(heap.len());
618        let end = heap[start..]
619            .iter()
620            .position(|b| *b == 0)
621            .map_or(heap.len(), |p| start + p);
622        std::str::from_utf8(&heap[start..end]).unwrap_or("")
623    }
624
625    pub fn type_name(&self, index: TypeDefinitionIndex) -> &str {
626        self.string(self.type_definitions[index as usize].name_index)
627    }
628
629    /// `Namespace.Name`, with `/` separating nested types.
630    pub fn type_full_name(&self, index: TypeDefinitionIndex) -> String {
631        let t = &self.type_definitions[index as usize];
632        let name = self.string(t.name_index);
633        if let Some(parent) = self.declaring_type_definition(index) {
634            return format!("{}/{}", self.type_full_name(parent), name);
635        }
636        match self.string(t.namespace_index) {
637            "" => name.to_owned(),
638            ns => format!("{}.{}", ns, name),
639        }
640    }
641
642    /// The enclosing type definition, found through the nested type lists.
643    pub fn declaring_type_definition(
644        &self,
645        index: TypeDefinitionIndex,
646    ) -> Option<TypeDefinitionIndex> {
647        self.declaring_types.get(index as usize).copied().flatten()
648    }
649
650    pub fn image_name(&self, image: &ImageDefinition) -> &str {
651        self.string(image.name_index)
652    }
653
654    /// Type definition indices belonging to `image`.
655    pub fn image_types(&self, image: &ImageDefinition) -> std::ops::Range<TypeDefinitionIndex> {
656        image.type_start..image.type_start + image.type_count as i32
657    }
658
659    pub fn type_methods(&self, t: &TypeDefinition) -> &[MethodDefinition] {
660        let start = t.method_start.max(0) as usize;
661        self.methods
662            .get(start..start + t.method_count as usize)
663            .unwrap_or(&[])
664    }
665
666    pub fn type_fields(&self, t: &TypeDefinition) -> &[FieldDefinition] {
667        let start = t.field_start.max(0) as usize;
668        self.fields
669            .get(start..start + t.field_count as usize)
670            .unwrap_or(&[])
671    }
672
673    /// Bytes of the default value data section from `index` on.
674    pub fn default_value_data(&self, index: i32) -> &[u8] {
675        let (offset, size) = self.sections["field_and_parameter_default_value_data"];
676        let data = &self.data[offset..offset + size];
677        usize::try_from(index)
678            .ok()
679            .and_then(|i| data.get(i..))
680            .unwrap_or(&[])
681    }
682
683    pub fn generic_container_parameters(&self, container: i32) -> &[GenericParameter] {
684        let Some(c) = usize::try_from(container)
685            .ok()
686            .and_then(|i| self.generic_containers.get(i))
687        else {
688            return &[];
689        };
690        let start = c.generic_parameter_start.max(0) as usize;
691        self.generic_parameters
692            .get(start..start + c.type_argc.max(0) as usize)
693            .unwrap_or(&[])
694    }
695
696    pub fn method_parameters(&self, m: &MethodDefinition) -> &[ParameterDefinition] {
697        let start = m.parameter_start.max(0) as usize;
698        self.parameters
699            .get(start..start + m.parameter_count as usize)
700            .unwrap_or(&[])
701    }
702}