hao-il2cpp 0.0.14

Read Unity Il2Cpp metadata and generate .net proxy assemblies with hao
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
//! `global-metadata.dat`: names and the shape of every type, method and field.
//!
//! Types of fields, parameters and return values are indices into the
//! `Il2CppType` table, which lives in the game binary, not in this file.
//!
//! Three metadata versions are supported:
//! - **v29** (Unity 2021.2 – 2023.x): header entries are `(offset, size)` pairs.
//! - **v31** (later Unity 2022.3 LTS / 2023.x): identical to v29 except the
//!   method record gained a `returnParameterToken` field (so each record is 4
//!   bytes larger). The section list, header-entry size and all other record
//!   layouts match v29. Implemented from the Il2CppDumper/Il2CppInspector
//!   reference layouts; **unverified against a real v31 game** (none available).
//! - **v39** (Unity 6): each header entry also carries a record count, so the
//!   entries are 12 bytes. Several records shrank: `type_definitions` dropped
//!   `element_type_index` and narrowed `generic_container_index`; `methods`
//!   narrowed its middle index fields (moving `parameter_start`); `images` and
//!   `assemblies` were reordered; `generic_parameters` narrowed `owner_index`.
//!   The v39 layout was reverse-engineered and validated against real Unity 6
//!   games (which ship Windows PE binaries, read via pewter's PE support).
//!
//! ```no_run
//! use hao_il2cpp::Metadata;
//!
//! let metadata = Metadata::from_path("Game_Data/il2cpp_data/Metadata/global-metadata.dat")?;
//! println!("metadata v{}", metadata.version);
//! for image in &metadata.images {
//!     println!("{}:", metadata.image_name(image));
//!     for index in metadata.image_types(image) {
//!         let ty = &metadata.type_definitions[index as usize];
//!         println!("    {} ({} methods)", metadata.type_full_name(index), ty.method_count);
//!     }
//! }
//! # Ok::<(), hao_il2cpp::Error>(())
//! ```

use std::collections::HashMap;

use hao::dotnet::entries::well_known::TypeName;

use crate::error::{Error, Result};

const SANITY: u32 = 0xFAB1_1BAF;

/// Section names in header order, per metadata version.
fn section_names(version: u32) -> Option<&'static [&'static str]> {
    const V29: &[&str] = &[
        "string_literal",
        "string_literal_data",
        "string",
        "events",
        "properties",
        "methods",
        "parameter_default_values",
        "field_default_values",
        "field_and_parameter_default_value_data",
        "field_marshaled_sizes",
        "parameters",
        "fields",
        "generic_parameters",
        "generic_parameter_constraints",
        "generic_containers",
        "nested_types",
        "interfaces",
        "vtable_methods",
        "interface_offsets",
        "type_definitions",
        "images",
        "assemblies",
        "field_refs",
        "referenced_assemblies",
        "attribute_data",
        "attribute_data_range",
        "unresolved_virtual_call_parameter_types",
        "unresolved_virtual_call_parameter_ranges",
        "windows_runtime_type_names",
        "windows_runtime_strings",
        "exported_type_definitions",
    ];
    // v31 and v39 keep the same sections in the same order as v29. v31 only
    // widens the method record (see `read_tables`); v39 additionally changes the
    // per-entry header size and several record layouts.
    match version {
        29 | 31 | 39 => Some(V29),
        _ => None,
    }
}

/// Bytes per header section entry: `(offset, size)` for v29, plus a record-count
/// `u32` for v39.
fn header_entry_size(version: u32) -> usize {
    if version >= 39 {
        12
    } else {
        8
    }
}

struct Cursor<'a> {
    data: &'a [u8],
    position: usize,
}

impl Cursor<'_> {
    fn bytes<const N: usize>(&mut self) -> [u8; N] {
        let value = self.data[self.position..self.position + N]
            .try_into()
            .unwrap();
        self.position += N;
        value
    }
    fn u16(&mut self) -> u16 {
        u16::from_le_bytes(self.bytes())
    }
    fn i16(&mut self) -> i16 {
        i16::from_le_bytes(self.bytes())
    }
    fn u32(&mut self) -> u32 {
        u32::from_le_bytes(self.bytes())
    }
    fn i32(&mut self) -> i32 {
        i32::from_le_bytes(self.bytes())
    }
}

/// An index into the binary's `Il2CppType` table.
pub type TypeIndex = i32;
/// An index into [`Metadata::type_definitions`].
pub type TypeDefinitionIndex = i32;

/// `Il2CppImageDefinition`: one image (module) of the game, e.g.
/// `Assembly-CSharp.dll`, and the range of type definitions it owns.
#[derive(Debug, Clone)]
#[cfg_attr(feature = "reflect", derive(facet::Facet))]
pub struct ImageDefinition {
    /// The image's file name, e.g. `Assembly-CSharp.dll`. Index into the string pool; read it with [`Metadata::string`].
    pub name_index: u32,
    /// Index into [`Metadata::assemblies`] of the assembly this image belongs to.
    pub assembly_index: i32,
    /// Index into [`Metadata::type_definitions`] of this image's first type.
    ///
    /// v39 doesn't store it; it's computed as a running total, since types are laid out in image order.
    pub type_start: i32,
    /// How many type definitions the image owns, from `type_start` on.
    pub type_count: u32,
    /// Index into the `exported_type_definitions` section of this image's first exported type.
    pub exported_type_start: i32,
    /// How many exported types (e.g. type forwarders) the image has.
    pub exported_type_count: u32,
    /// Index into [`Metadata::methods`] of the entry point (`Main`), or -1.
    pub entry_point_index: i32,
    /// The image's module metadata token.
    pub token: u32,
    /// Index into the `attribute_data_range` section of this image's first attribute range.
    pub custom_attribute_start: i32,
    /// How many attribute ranges the image has. Always 0 for v39, which doesn't store it.
    pub custom_attribute_count: u32,
}

/// `Il2CppAssemblyDefinition`: an assembly's identity and the image that holds it.
#[derive(Debug, Clone)]
#[cfg_attr(feature = "reflect", derive(facet::Facet))]
pub struct AssemblyDefinition {
    /// Index into [`Metadata::images`] of this assembly's image.
    pub image_index: i32,
    /// The assembly's metadata token.
    pub token: u32,
    /// Index into the `referenced_assemblies` section of the first assembly this one references.
    pub referenced_assembly_start: i32,
    /// How many assemblies this one references.
    pub referenced_assembly_count: i32,
    /// The assembly's simple name, e.g. `Assembly-CSharp`. Index into the string pool; read it with [`Metadata::string`].
    pub name_index: u32,
    /// The assembly's culture, empty for neutral. Index into the string pool; read it with [`Metadata::string`].
    pub culture_index: u32,
    /// The assembly's public key, as an escaped string. Index into the string pool; read it with [`Metadata::string`].
    pub public_key_index: u32,
    /// The hash algorithm id (`AssemblyHashAlgorithm`).
    pub hash_alg: u32,
    /// The length of the assembly hash.
    pub hash_len: i32,
    /// `AssemblyFlags`, e.g. whether the public key is full or a token.
    pub flags: u32,
    /// `[major, minor, build, revision]`.
    pub version: [i32; 4],
    /// The last 8 bytes of the public key's hash; all zero for an unsigned assembly.
    pub public_key_token: [u8; 8],
}

/// `Il2CppTypeDefinition`: one type's name, flags, base type and the ranges
/// of its members in the other tables.
///
/// Each `*_start` indexes the matching [`Metadata`] table and pairs with its
/// `*_count`; [`Metadata::type_methods`] and [`Metadata::type_fields`] slice
/// them for you.
#[derive(Debug, Clone)]
#[cfg_attr(feature = "reflect", derive(facet::Facet))]
pub struct TypeDefinition {
    /// The type's name, with the `` `N `` arity suffix for generics. Index into the string pool; read it with [`Metadata::string`].
    pub name_index: u32,
    /// The type's namespace, empty for nested types and the global namespace. Index into the string pool; read it with [`Metadata::string`].
    pub namespace_index: u32,
    /// This type itself in the binary's `Il2CppType` table (see [`Binary::type_at`](crate::Binary::type_at)).
    pub byval_type_index: TypeIndex,
    /// The enclosing type, as a [`TypeIndex`], or -1 for a top-level type.
    pub declaring_type_index: TypeIndex,
    /// The base type, as a [`TypeIndex`], or -1 (`System.Object`, interfaces).
    pub parent_index: TypeIndex,
    /// For an enum, its underlying type as a [`TypeIndex`]; otherwise -1.
    ///
    /// v39 doesn't store it, so it's always -1 there.
    pub element_type_index: TypeIndex,
    /// Index into [`Metadata::generic_containers`] if the type is generic, or -1.
    pub generic_container_index: i32,
    /// `TypeAttributes`: visibility, layout, class semantics (class or interface), etc.
    pub flags: u32,
    /// Index into [`Metadata::fields`] of the first field.
    pub field_start: i32,
    /// Index into [`Metadata::methods`] of the first method.
    pub method_start: i32,
    /// Index into [`Metadata::events`] of the first event.
    pub event_start: i32,
    /// Index into [`Metadata::properties`] of the first property.
    pub property_start: i32,
    /// Index into [`Metadata::nested_types`] of the first nested type.
    pub nested_types_start: i32,
    /// Index into [`Metadata::interfaces`] of the first implemented interface.
    pub interfaces_start: i32,
    /// Index into the `vtable_methods` section of the first vtable slot.
    pub vtable_start: i32,
    /// Index into the `interface_offsets` section of the first interface's vtable offset.
    pub interface_offsets_start: i32,
    /// How many methods the type declares.
    pub method_count: u16,
    /// How many properties the type declares.
    pub property_count: u16,
    /// How many fields the type declares.
    pub field_count: u16,
    /// How many events the type declares.
    pub event_count: u16,
    /// How many types are nested directly in this one.
    pub nested_type_count: u16,
    /// How many vtable slots the type has.
    pub vtable_count: u16,
    /// How many interfaces the type implements directly.
    pub interfaces_count: u16,
    /// How many interface vtable offsets the type has.
    pub interface_offsets_count: u16,
    /// Packed flags (IL2CPP's `bitfield`): value type, enum, has finalizer, has cctor, blittable, and the packing size.
    pub bitfield: u32,
    /// The type's `TypeDef` metadata token in its image.
    pub token: u32,
}

/// `Il2CppMethodDefinition`: one method's name, signature and flags.
#[derive(Debug, Clone)]
#[cfg_attr(feature = "reflect", derive(facet::Facet))]
pub struct MethodDefinition {
    /// The method's name, e.g. `.ctor` or `Update`. Index into the string pool; read it with [`Metadata::string`].
    pub name_index: u32,
    /// The type that declares the method.
    pub declaring_type: TypeDefinitionIndex,
    /// The return type, as a [`TypeIndex`].
    pub return_type: TypeIndex,
    /// Index into [`Metadata::parameters`] of the first parameter; see [`Metadata::method_parameters`].
    pub parameter_start: i32,
    /// Index into [`Metadata::generic_containers`] if the method is generic, or -1.
    pub generic_container_index: i32,
    /// The method's `MethodDef` metadata token in its image; its RID indexes the image's method pointers in [`CodeGenModule`](crate::binary::CodeGenModule).
    pub token: u32,
    /// `MethodAttributes`: visibility, `static`, `virtual`, `abstract`, etc.
    pub flags: u16,
    /// `MethodImplAttributes`: e.g. `InternalCall`, `Synchronized`.
    pub iflags: u16,
    /// The method's vtable slot, or `0xFFFF` if it has none.
    pub slot: u16,
    /// How many parameters the method takes, not counting `this`.
    pub parameter_count: u16,
}

/// `Il2CppFieldDefinition`: one field's name and type.
#[derive(Debug, Clone)]
#[cfg_attr(feature = "reflect", derive(facet::Facet))]
pub struct FieldDefinition {
    /// The field's name. Index into the string pool; read it with [`Metadata::string`].
    pub name_index: u32,
    /// The field's type, as a [`TypeIndex`]. Its `attrs` carry the field's `FieldAttributes` (e.g. `static`).
    pub type_index: TypeIndex,
    /// The field's `Field` metadata token in its image.
    pub token: u32,
}

/// `Il2CppParameterDefinition`: one method parameter's name and type.
#[derive(Debug, Clone)]
#[cfg_attr(feature = "reflect", derive(facet::Facet))]
pub struct ParameterDefinition {
    /// The parameter's name. Index into the string pool; read it with [`Metadata::string`].
    pub name_index: u32,
    /// The parameter's `Param` metadata token in its image.
    pub token: u32,
    /// The parameter's type, as a [`TypeIndex`]. Its `attrs` carry the `ParamAttributes` (e.g. `out`).
    pub type_index: TypeIndex,
}

/// `Il2CppPropertyDefinition`: a property and its accessors.
#[derive(Debug, Clone)]
#[cfg_attr(feature = "reflect", derive(facet::Facet))]
pub struct PropertyDefinition {
    /// The property's name. Index into the string pool; read it with [`Metadata::string`].
    pub name_index: u32,
    /// Method index relative to the declaring type's `method_start`, or -1.
    pub get: i32,
    /// The setter, as for `get`.
    pub set: i32,
    /// `PropertyAttributes`.
    pub attrs: u32,
    /// The property's `Property` metadata token in its image.
    pub token: u32,
}

/// `Il2CppEventDefinition`: an event and its accessors.
///
/// Each accessor is a method index relative to the declaring type's
/// `method_start`, or -1 if it has none.
#[derive(Debug, Clone)]
#[cfg_attr(feature = "reflect", derive(facet::Facet))]
pub struct EventDefinition {
    /// The event's name. Index into the string pool; read it with [`Metadata::string`].
    pub name_index: u32,
    /// The event's delegate type, as a [`TypeIndex`].
    pub type_index: TypeIndex,
    /// The `add` accessor.
    pub add: i32,
    /// The `remove` accessor.
    pub remove: i32,
    /// The `raise` accessor; C# never emits one, so usually -1.
    pub raise: i32,
    /// The event's `Event` metadata token in its image.
    pub token: u32,
}

/// `Il2CppGenericContainer`: the generic parameter list of a generic type or method.
#[derive(Debug, Clone)]
#[cfg_attr(feature = "reflect", derive(facet::Facet))]
pub struct GenericContainer {
    /// A type definition index, or a method index when `is_method`.
    pub owner_index: i32,
    /// How many generic parameters it has.
    pub type_argc: i32,
    /// Whether the owner is a method rather than a type.
    pub is_method: bool,
    /// Index into [`Metadata::generic_parameters`] of the first parameter; see [`Metadata::generic_container_parameters`].
    pub generic_parameter_start: i32,
}

/// `Il2CppGenericParameter`: one generic parameter, e.g. the `T` of `List<T>`.
#[derive(Debug, Clone)]
#[cfg_attr(feature = "reflect", derive(facet::Facet))]
pub struct GenericParameter {
    /// Index into [`Metadata::generic_containers`] of the container it belongs to.
    pub owner_index: i32,
    /// The parameter's name, e.g. `T`. Index into the string pool; read it with [`Metadata::string`].
    pub name_index: u32,
    /// Index into [`Metadata::generic_parameter_constraints`] of its first constraint.
    pub constraints_start: i16,
    /// How many type constraints it has.
    pub constraints_count: i16,
    /// Its position in the owner's parameter list, from 0.
    pub num: u16,
    /// `GenericParameterAttributes`: variance and `class` / `struct` / `new()` constraints.
    pub flags: u16,
}

/// A parsed `global-metadata.dat`: its tables, decoded, and its string and
/// data sections, read on demand.
///
/// The public tables are the raw records, in file order; indices stored in
/// one record (e.g. [`TypeDefinition::method_start`]) index into these
/// vectors.
#[cfg_attr(feature = "reflect", derive(facet::Facet))]
pub struct Metadata {
    /// The metadata version: 29, 31 or 39.
    pub version: u32,
    data: Vec<u8>,
    sections: HashMap<&'static str, (usize, usize)>,
    /// Every image (module), e.g. `Assembly-CSharp.dll`.
    pub images: Vec<ImageDefinition>,
    /// Every assembly, one per image.
    pub assemblies: Vec<AssemblyDefinition>,
    /// Every type definition in the game, grouped by image; a [`TypeDefinitionIndex`] indexes this.
    pub type_definitions: Vec<TypeDefinition>,
    /// Every method definition, grouped by declaring type.
    pub methods: Vec<MethodDefinition>,
    /// Every field definition, grouped by declaring type.
    pub fields: Vec<FieldDefinition>,
    /// Every method parameter, grouped by method.
    pub parameters: Vec<ParameterDefinition>,
    /// Every property, grouped by declaring type.
    pub properties: Vec<PropertyDefinition>,
    /// Every event, grouped by declaring type.
    pub events: Vec<EventDefinition>,
    /// Generic parameter lists of generic types and methods.
    pub generic_containers: Vec<GenericContainer>,
    /// Every generic parameter; [`TypeKind::Var`](crate::binary::TypeKind::Var) and `MVar` index this.
    pub generic_parameters: Vec<GenericParameter>,
    /// Nested type lists, sliced by each type's `nested_types_start` and `nested_type_count`.
    pub nested_types: Vec<TypeDefinitionIndex>,
    /// Implemented interface lists, sliced by each type's `interfaces_start` and `interfaces_count`.
    pub interfaces: Vec<TypeIndex>,
    /// Constraint type lists, sliced by each generic parameter's `constraints_start` and `constraints_count`.
    pub generic_parameter_constraints: Vec<TypeIndex>,
    /// Constant values of `const` fields and enum members.
    pub field_default_values: Vec<FieldDefaultValue>,
    declaring_types: Vec<Option<TypeDefinitionIndex>>,
}

/// `Il2CppFieldDefaultValue`: a constant value for a field, stored in the
/// default value data section.
#[derive(Debug, Clone)]
#[cfg_attr(feature = "reflect", derive(facet::Facet))]
pub struct FieldDefaultValue {
    /// Index into [`Metadata::fields`] of the field it belongs to.
    pub field_index: i32,
    /// The constant's type, as a [`TypeIndex`], which says how to decode the data.
    pub type_index: TypeIndex,
    /// Where the value starts in the default value data; read it with [`Metadata::default_value_data`].
    pub data_index: i32,
}

impl Metadata {
    /// Reads and parses a `global-metadata.dat` file.
    pub fn from_path(path: impl AsRef<std::path::Path>) -> Result<Self> {
        Self::parse(std::fs::read(path)?)
    }

    /// Parses `global-metadata.dat` from its bytes, decoding every table.
    ///
    /// Fails with [`Error::BadSanity`] if it isn't IL2CPP metadata,
    /// [`Error::UnsupportedVersion`] for a version other than 29, 31 or 39,
    /// and [`Error::BadSection`] if the header is inconsistent with the file.
    pub fn parse(data: Vec<u8>) -> Result<Self> {
        if data.len() < 8 {
            return Err(Error::BadSection("header"));
        }
        let mut c = Cursor {
            data: &data,
            position: 0,
        };
        let sanity = c.u32();
        if sanity != SANITY {
            return Err(Error::BadSanity(sanity));
        }
        let version = c.u32();
        let names = section_names(version).ok_or(Error::UnsupportedVersion(version))?;
        let entry = header_entry_size(version);
        let header_end = 8 + names.len() * entry;
        if data.len() < header_end {
            return Err(Error::BadSection("header"));
        }
        let mut sections = HashMap::new();
        for name in names {
            let offset = c.u32() as usize;
            let size = c.i32().max(0) as usize;
            // v39 stores a record count after each (offset, size); skip it.
            c.position += entry - 8;
            if offset < header_end && size != 0 || offset + size > data.len() {
                return Err(Error::BadSection(name));
            }
            sections.insert(*name, (offset, size));
        }

        let mut metadata = Self {
            version,
            sections,
            images: Vec::new(),
            assemblies: Vec::new(),
            type_definitions: Vec::new(),
            methods: Vec::new(),
            fields: Vec::new(),
            parameters: Vec::new(),
            properties: Vec::new(),
            events: Vec::new(),
            generic_containers: Vec::new(),
            generic_parameters: Vec::new(),
            nested_types: Vec::new(),
            interfaces: Vec::new(),
            generic_parameter_constraints: Vec::new(),
            field_default_values: Vec::new(),
            declaring_types: Vec::new(),
            data: Vec::new(),
        };
        metadata.data = data;
        metadata.read_tables()?;
        Ok(metadata)
    }

    fn table<T>(
        &self,
        name: &'static str,
        size: usize,
        read: impl Fn(&mut Cursor) -> T,
    ) -> Result<Vec<T>> {
        let (offset, length) = self.sections[name];
        if length % size != 0 {
            return Err(Error::BadSection(name));
        }
        let mut c = Cursor {
            data: &self.data[offset..offset + length],
            position: 0,
        };
        Ok((0..length / size).map(|_| read(&mut c)).collect())
    }

    fn read_tables(&mut self) -> Result<()> {
        let v39 = self.version >= 39;
        if v39 {
            // Unity 6 packs the image record unaligned and no longer stores
            // type_start; type_count is at offset 10 and types are laid out in
            // image order, so type_start is filled in as a running total below.
            self.images = self.table("images", 36, |c| {
                let name_index = c.u32();
                let assembly_index = c.i32();
                let _pad = c.u16();
                let type_count = c.u32();
                let (token, entry_point_index, exported_type_start) = (c.u32(), c.i32(), c.i32());
                let (exported_type_count, custom_attribute_start) = (c.u32(), c.i32());
                let _tail = c.u16();
                ImageDefinition {
                    name_index,
                    assembly_index,
                    token,
                    entry_point_index,
                    exported_type_start,
                    exported_type_count,
                    custom_attribute_start,
                    custom_attribute_count: 0,
                    type_start: 0,
                    type_count,
                }
            })?;
            let mut start = 0;
            for image in &mut self.images {
                image.type_start = start;
                start += image.type_count as i32;
            }
            self.assemblies = self.table("assemblies", 68, |c| {
                let (image_index, token) = (c.i32(), c.u32());
                let (referenced_assembly_start, referenced_assembly_count) = (c.i32(), c.i32());
                let _custom_attribute_start = c.i32();
                AssemblyDefinition {
                    image_index,
                    token,
                    referenced_assembly_start,
                    referenced_assembly_count,
                    name_index: c.u32(),
                    culture_index: c.u32(),
                    public_key_index: c.u32(),
                    hash_alg: c.u32(),
                    hash_len: c.i32(),
                    flags: c.u32(),
                    version: [c.i32(), c.i32(), c.i32(), c.i32()],
                    public_key_token: c.bytes(),
                }
            })?;
        } else {
            self.images = self.table("images", 40, |c| ImageDefinition {
                name_index: c.u32(),
                assembly_index: c.i32(),
                type_start: c.i32(),
                type_count: c.u32(),
                exported_type_start: c.i32(),
                exported_type_count: c.u32(),
                entry_point_index: c.i32(),
                token: c.u32(),
                custom_attribute_start: c.i32(),
                custom_attribute_count: c.u32(),
            })?;
            self.assemblies = self.table("assemblies", 64, |c| AssemblyDefinition {
                image_index: c.i32(),
                token: c.u32(),
                referenced_assembly_start: c.i32(),
                referenced_assembly_count: c.i32(),
                name_index: c.u32(),
                culture_index: c.u32(),
                public_key_index: c.u32(),
                hash_alg: c.u32(),
                hash_len: c.i32(),
                flags: c.u32(),
                version: [c.i32(), c.i32(), c.i32(), c.i32()],
                public_key_token: c.bytes(),
            })?;
        }
        // v39 dropped `element_type_index` and shrank `generic_container_index`
        // to 16-bit; everything from `field_start` on is the same, 6 bytes earlier.
        let (type_size, read_type): (usize, fn(&mut Cursor) -> TypeDefinition) = if v39 {
            (82, |c| TypeDefinition {
                name_index: c.u32(),
                namespace_index: c.u32(),
                byval_type_index: c.i32(),
                declaring_type_index: c.i32(),
                parent_index: c.i32(),
                element_type_index: -1,
                generic_container_index: c.i16() as i32,
                flags: c.u32(),
                field_start: c.i32(),
                method_start: c.i32(),
                event_start: c.i32(),
                property_start: c.i32(),
                nested_types_start: c.i32(),
                interfaces_start: c.i32(),
                vtable_start: c.i32(),
                interface_offsets_start: c.i32(),
                method_count: c.u16(),
                property_count: c.u16(),
                field_count: c.u16(),
                event_count: c.u16(),
                nested_type_count: c.u16(),
                vtable_count: c.u16(),
                interfaces_count: c.u16(),
                interface_offsets_count: c.u16(),
                bitfield: c.u32(),
                token: c.u32(),
            })
        } else {
            (88, |c| TypeDefinition {
                name_index: c.u32(),
                namespace_index: c.u32(),
                byval_type_index: c.i32(),
                declaring_type_index: c.i32(),
                parent_index: c.i32(),
                element_type_index: c.i32(),
                generic_container_index: c.i32(),
                flags: c.u32(),
                field_start: c.i32(),
                method_start: c.i32(),
                event_start: c.i32(),
                property_start: c.i32(),
                nested_types_start: c.i32(),
                interfaces_start: c.i32(),
                vtable_start: c.i32(),
                interface_offsets_start: c.i32(),
                method_count: c.u16(),
                property_count: c.u16(),
                field_count: c.u16(),
                event_count: c.u16(),
                nested_type_count: c.u16(),
                vtable_count: c.u16(),
                interfaces_count: c.u16(),
                interface_offsets_count: c.u16(),
                bitfield: c.u32(),
                token: c.u32(),
            })
        };
        self.type_definitions = self.table("type_definitions", type_size, read_type)?;
        // v39 packs the 32-byte method record unaligned: declaring_type is 16-bit,
        // return_type sits at offset 6, and parameter_start at offset 14. token and
        // the trailing flags/slot/count u16s stay where v29 had them.
        self.methods = if v39 {
            self.table("methods", 32, |c| {
                let name_index = c.u32();
                let declaring_type = c.u16() as i32;
                let return_type = c.i32();
                let generic_container_index = c.i32();
                let parameter_start = c.i32();
                let _pad = c.u16();
                MethodDefinition {
                    name_index,
                    declaring_type,
                    return_type,
                    parameter_start,
                    generic_container_index,
                    token: c.u32(),
                    flags: c.u16(),
                    iflags: c.u16(),
                    slot: c.u16(),
                    parameter_count: c.u16(),
                }
            })?
        } else if self.version >= 31 {
            // v31 inserted a `returnParameterToken` (u32) right after `return_type`,
            // growing the aligned record to 36 bytes; the field is unused here and
            // discarded. This layout is taken from the Il2CppDumper/Il2CppInspector
            // reference and is unverified against a real v31 game.
            self.table("methods", 36, |c| {
                let name_index = c.u32();
                let declaring_type = c.i32();
                let return_type = c.i32();
                let _return_parameter_token = c.u32();
                MethodDefinition {
                    name_index,
                    declaring_type,
                    return_type,
                    parameter_start: c.i32(),
                    generic_container_index: c.i32(),
                    token: c.u32(),
                    flags: c.u16(),
                    iflags: c.u16(),
                    slot: c.u16(),
                    parameter_count: c.u16(),
                }
            })?
        } else {
            self.table("methods", 32, |c| MethodDefinition {
                name_index: c.u32(),
                declaring_type: c.i32(),
                return_type: c.i32(),
                parameter_start: c.i32(),
                generic_container_index: c.i32(),
                token: c.u32(),
                flags: c.u16(),
                iflags: c.u16(),
                slot: c.u16(),
                parameter_count: c.u16(),
            })?
        };
        self.fields = self.table("fields", 12, |c| FieldDefinition {
            name_index: c.u32(),
            type_index: c.i32(),
            token: c.u32(),
        })?;
        self.parameters = self.table("parameters", 12, |c| ParameterDefinition {
            name_index: c.u32(),
            token: c.u32(),
            type_index: c.i32(),
        })?;
        self.properties = self.table("properties", 20, |c| PropertyDefinition {
            name_index: c.u32(),
            get: c.i32(),
            set: c.i32(),
            attrs: c.u32(),
            token: c.u32(),
        })?;
        self.events = self.table("events", 24, |c| EventDefinition {
            name_index: c.u32(),
            type_index: c.i32(),
            add: c.i32(),
            remove: c.i32(),
            raise: c.i32(),
            token: c.u32(),
        })?;
        self.generic_containers = self.table("generic_containers", 16, |c| GenericContainer {
            owner_index: c.i32(),
            type_argc: c.i32(),
            is_method: c.i32() != 0,
            generic_parameter_start: c.i32(),
        })?;
        // v39 shrank owner_index to 16-bit (name_index then sits at offset 2).
        let (gp_size, read_gp): (usize, fn(&mut Cursor) -> GenericParameter) = if v39 {
            (14, |c| GenericParameter {
                owner_index: c.u16() as i32,
                name_index: c.u32(),
                constraints_start: c.i16(),
                constraints_count: c.i16(),
                num: c.u16(),
                flags: c.u16(),
            })
        } else {
            (16, |c| GenericParameter {
                owner_index: c.i32(),
                name_index: c.u32(),
                constraints_start: c.i16(),
                constraints_count: c.i16(),
                num: c.u16(),
                flags: c.u16(),
            })
        };
        self.generic_parameters = self.table("generic_parameters", gp_size, read_gp)?;
        self.nested_types = self.table("nested_types", 4, |c| c.i32())?;
        self.interfaces = self.table("interfaces", 4, |c| c.i32())?;
        self.generic_parameter_constraints =
            self.table("generic_parameter_constraints", 4, |c| c.i32())?;
        self.field_default_values =
            self.table("field_default_values", 12, |c| FieldDefaultValue {
                field_index: c.i32(),
                type_index: c.i32(),
                data_index: c.i32(),
            })?;
        self.declaring_types = vec![None; self.type_definitions.len()];
        for (i, t) in self.type_definitions.iter().enumerate() {
            let start = t.nested_types_start.max(0) as usize;
            for nested in self
                .nested_types
                .get(start..start + t.nested_type_count as usize)
                .unwrap_or(&[])
            {
                if let Some(slot) = usize::try_from(*nested)
                    .ok()
                    .and_then(|n| self.declaring_types.get_mut(n))
                {
                    *slot = Some(i as TypeDefinitionIndex);
                }
            }
        }
        Ok(())
    }

    /// A string from the `#Strings`-like string section.
    pub fn string(&self, index: u32) -> &str {
        let (offset, size) = self.sections["string"];
        let heap = &self.data[offset..offset + size];
        let start = (index as usize).min(heap.len());
        let end = heap[start..]
            .iter()
            .position(|b| *b == 0)
            .map_or(heap.len(), |p| start + p);
        std::str::from_utf8(&heap[start..end]).unwrap_or("")
    }

    /// A type definition's own name, without namespace or declaring type.
    ///
    /// Panics if `index` is out of range.
    pub fn type_name(&self, index: TypeDefinitionIndex) -> &str {
        self.string(self.type_definitions[index as usize].name_index)
    }

    /// `Namespace.Name`, with `/` separating nested types.
    pub fn type_full_name(&self, index: TypeDefinitionIndex) -> String {
        let t = &self.type_definitions[index as usize];
        let name = self.string(t.name_index);
        if let Some(parent) = self.declaring_type_definition(index) {
            return format!("{}/{}", self.type_full_name(parent), name);
        }
        match self.string(t.namespace_index) {
            "" => name.to_owned(),
            ns => format!("{}.{}", ns, name),
        }
    }

    /// The index of the top-level type definition named `ty`, e.g.
    /// `metadata.find_type(WellKnown::System(SystemType::String))` or
    /// `metadata.find_type(("System", "String"))`.
    pub fn find_type(&self, ty: impl TypeName) -> Option<TypeDefinitionIndex> {
        let (namespace, name) = ty.type_name();
        self.type_definitions
            .iter()
            .position(|t| {
                t.declaring_type_index < 0
                    && self.string(t.namespace_index) == namespace.as_ref()
                    && self.string(t.name_index) == name.as_ref()
            })
            .map(|i| i as TypeDefinitionIndex)
    }

    /// The enclosing type definition, found through the nested type lists.
    pub fn declaring_type_definition(
        &self,
        index: TypeDefinitionIndex,
    ) -> Option<TypeDefinitionIndex> {
        self.declaring_types.get(index as usize).copied().flatten()
    }

    /// An image's file name, e.g. `Assembly-CSharp.dll`.
    pub fn image_name(&self, image: &ImageDefinition) -> &str {
        self.string(image.name_index)
    }

    /// Type definition indices belonging to `image`.
    pub fn image_types(&self, image: &ImageDefinition) -> std::ops::Range<TypeDefinitionIndex> {
        image.type_start..image.type_start + image.type_count as i32
    }

    /// The methods a type declares; empty if its range is out of bounds.
    pub fn type_methods(&self, t: &TypeDefinition) -> &[MethodDefinition] {
        let start = t.method_start.max(0) as usize;
        self.methods
            .get(start..start + t.method_count as usize)
            .unwrap_or(&[])
    }

    /// The fields a type declares; empty if its range is out of bounds.
    pub fn type_fields(&self, t: &TypeDefinition) -> &[FieldDefinition] {
        let start = t.field_start.max(0) as usize;
        self.fields
            .get(start..start + t.field_count as usize)
            .unwrap_or(&[])
    }

    /// Bytes of the default value data section from `index` on.
    pub fn default_value_data(&self, index: i32) -> &[u8] {
        let (offset, size) = self.sections["field_and_parameter_default_value_data"];
        let data = &self.data[offset..offset + size];
        usize::try_from(index)
            .ok()
            .and_then(|i| data.get(i..))
            .unwrap_or(&[])
    }

    /// The generic parameters of a [`GenericContainer`], by index into
    /// [`Metadata::generic_containers`] (e.g. a type's `generic_container_index`);
    /// empty for -1.
    pub fn generic_container_parameters(&self, container: i32) -> &[GenericParameter] {
        let Some(c) = usize::try_from(container)
            .ok()
            .and_then(|i| self.generic_containers.get(i))
        else {
            return &[];
        };
        let start = c.generic_parameter_start.max(0) as usize;
        self.generic_parameters
            .get(start..start + c.type_argc.max(0) as usize)
            .unwrap_or(&[])
    }

    /// A method's parameters, in order; empty if its range is out of bounds.
    pub fn method_parameters(&self, m: &MethodDefinition) -> &[ParameterDefinition] {
        let start = m.parameter_start.max(0) as usize;
        self.parameters
            .get(start..start + m.parameter_count as usize)
            .unwrap_or(&[])
    }

    /// The `(token, start_offset)` entries of the `attribute_data_range` section
    /// (v29+). Each `start_offset` indexes into [`Metadata::attribute_data`]; a
    /// range ends where the next entry begins, as the section is laid out in global
    /// offset order (`Il2CppCustomAttributeDataRange`).
    pub fn attribute_data_ranges(&self) -> Vec<(u32, u32)> {
        let (offset, size) = self.sections["attribute_data_range"];
        self.data[offset..offset + size]
            .as_chunks::<8>()
            .0
            .iter()
            .map(|c| {
                (
                    u32::from_le_bytes(c[0..4].try_into().unwrap()),
                    u32::from_le_bytes(c[4..8].try_into().unwrap()),
                )
            })
            .collect()
    }

    /// The raw `attribute_data` blob holding v29+ custom attribute values.
    pub fn attribute_data(&self) -> &[u8] {
        let (offset, size) = self.sections["attribute_data"];
        &self.data[offset..offset + size]
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    /// Build a minimal valid `global-metadata.dat` for `version` whose only
    /// non-empty section is `methods`, carrying the raw bytes `method`.
    fn metadata_with_method(version: u32, method: &[u8]) -> Vec<u8> {
        let names = section_names(version).unwrap();
        let header_end = 8 + names.len() * header_entry_size(version);
        let methods_index = names.iter().position(|n| *n == "methods").unwrap();

        let mut buf = Vec::new();
        buf.extend_from_slice(&SANITY.to_le_bytes());
        buf.extend_from_slice(&version.to_le_bytes());
        for (i, _) in names.iter().enumerate() {
            if i == methods_index {
                buf.extend_from_slice(&(header_end as u32).to_le_bytes());
                buf.extend_from_slice(&(method.len() as u32).to_le_bytes());
            } else {
                buf.extend_from_slice(&0u32.to_le_bytes());
                buf.extend_from_slice(&0u32.to_le_bytes());
            }
        }
        assert_eq!(buf.len(), header_end);
        buf.extend_from_slice(method);
        buf
    }

    /// v31 dispatch: the method record is 36 bytes with a `returnParameterToken`
    /// inserted after `return_type` that must be skipped, not surfaced as any
    /// later field. (Reference layout; no real v31 game to validate against.)
    #[test]
    fn v31_method_record_skips_return_parameter_token() {
        let mut m = Vec::new();
        for v in [11u32, 22, 33, 0xDEAD_BEEF, 44, 55, 66] {
            m.extend_from_slice(&v.to_le_bytes());
        }
        for v in [7u16, 8, 9, 10] {
            m.extend_from_slice(&v.to_le_bytes());
        }
        assert_eq!(m.len(), 36);

        let md = Metadata::parse(metadata_with_method(31, &m)).unwrap();
        assert_eq!(md.version, 31);
        assert_eq!(md.methods.len(), 1);
        let method = &md.methods[0];
        assert_eq!(method.name_index, 11);
        assert_eq!(method.declaring_type, 22);
        assert_eq!(method.return_type, 33);
        // 0xDEADBEEF was the returnParameterToken and must be discarded.
        assert_eq!(method.parameter_start, 44);
        assert_eq!(method.generic_container_index, 55);
        assert_eq!(method.token, 66);
        assert_eq!(method.flags, 7);
        assert_eq!(method.parameter_count, 10);
    }

    /// v29 stays a 32-byte record with no `returnParameterToken`.
    #[test]
    fn v29_method_record_is_unchanged() {
        let mut m = Vec::new();
        for v in [11u32, 22, 33, 44, 55, 66] {
            m.extend_from_slice(&v.to_le_bytes());
        }
        for v in [7u16, 8, 9, 10] {
            m.extend_from_slice(&v.to_le_bytes());
        }
        assert_eq!(m.len(), 32);

        let md = Metadata::parse(metadata_with_method(29, &m)).unwrap();
        assert_eq!(md.methods.len(), 1);
        let method = &md.methods[0];
        assert_eq!(method.return_type, 33);
        assert_eq!(method.parameter_start, 44);
        assert_eq!(method.generic_container_index, 55);
    }

    #[test]
    fn unknown_version_is_rejected() {
        let mut buf = Vec::new();
        buf.extend_from_slice(&SANITY.to_le_bytes());
        buf.extend_from_slice(&30u32.to_le_bytes());
        assert!(matches!(
            Metadata::parse(buf),
            Err(Error::UnsupportedVersion(30))
        ));
    }
}