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