clrmeta 0.1.0

ECMA-335 CLI/.NET metadata parsing library with read/write support
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
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
//! High-level metadata API.

use crate::error::{Error, Result};
use crate::heaps::{BlobHeap, GuidHeap, StringsHeap, UserStringsHeap};
use crate::reader::Reader;
use crate::root::MetadataRoot;
use crate::stream::StreamHeader;
use crate::tables::{
    AssemblyOsRow, AssemblyProcessorRow, AssemblyRefOsRow, AssemblyRefProcessorRow, AssemblyRefRow,
    AssemblyRow, ClassLayoutRow, ConstantRow, CustomAttributeRow, DeclSecurityRow, EncLogRow,
    EncMapRow, EventMapRow, EventPtrRow, EventRow, ExportedTypeRow, FieldLayoutRow,
    FieldMarshalRow, FieldPtrRow, FieldRow, FieldRvaRow, FileRow, GenericParamConstraintRow,
    GenericParamRow, ImplMapRow, InterfaceImplRow, ManifestResourceRow, MemberRefRow, MethodDefRow,
    MethodImplRow, MethodPtrRow, MethodSemanticsRow, MethodSpecRow, ModuleRefRow, ModuleRow,
    NestedClassRow, ParamPtrRow, ParamRow, PropertyMapRow, PropertyPtrRow, PropertyRow,
    StandAloneSigRow, TableContext, TableId, TablesHeader, TypeDefRow, TypeRefRow, TypeSpecRow,
};
use crate::writer::Writer;

/// Parsed CLR metadata with read/write support.
#[derive(Debug, Clone)]
pub struct Metadata {
    /// The metadata root (BSJB header).
    pub root: MetadataRoot,
    /// The #Strings heap.
    pub strings: StringsHeap,
    /// The #US (user strings) heap.
    pub user_strings: UserStringsHeap,
    /// The #GUID heap.
    pub guids: GuidHeap,
    /// The #Blob heap.
    pub blobs: BlobHeap,
    /// The tables header.
    pub tables_header: TablesHeader,

    // Table rows - all tables in order by TableId
    /// Module table rows (0x00).
    pub modules: Vec<ModuleRow>,
    /// TypeRef table rows (0x01).
    pub type_refs: Vec<TypeRefRow>,
    /// TypeDef table rows (0x02).
    pub type_defs: Vec<TypeDefRow>,
    /// FieldPtr table rows (0x03) - only in uncompressed #- streams.
    pub field_ptrs: Vec<FieldPtrRow>,
    /// Field table rows (0x04).
    pub fields: Vec<FieldRow>,
    /// MethodPtr table rows (0x05) - only in uncompressed #- streams.
    pub method_ptrs: Vec<MethodPtrRow>,
    /// MethodDef table rows (0x06).
    pub method_defs: Vec<MethodDefRow>,
    /// ParamPtr table rows (0x07) - only in uncompressed #- streams.
    pub param_ptrs: Vec<ParamPtrRow>,
    /// Param table rows (0x08).
    pub params: Vec<ParamRow>,
    /// InterfaceImpl table rows (0x09).
    pub interface_impls: Vec<InterfaceImplRow>,
    /// MemberRef table rows (0x0A).
    pub member_refs: Vec<MemberRefRow>,
    /// Constant table rows (0x0B).
    pub constants: Vec<ConstantRow>,
    /// CustomAttribute table rows (0x0C).
    pub custom_attributes: Vec<CustomAttributeRow>,
    /// FieldMarshal table rows (0x0D).
    pub field_marshals: Vec<FieldMarshalRow>,
    /// DeclSecurity table rows (0x0E).
    pub decl_securities: Vec<DeclSecurityRow>,
    /// ClassLayout table rows (0x0F).
    pub class_layouts: Vec<ClassLayoutRow>,
    /// FieldLayout table rows (0x10).
    pub field_layouts: Vec<FieldLayoutRow>,
    /// StandAloneSig table rows (0x11).
    pub stand_alone_sigs: Vec<StandAloneSigRow>,
    /// EventMap table rows (0x12).
    pub event_maps: Vec<EventMapRow>,
    /// EventPtr table rows (0x13) - only in uncompressed #- streams.
    pub event_ptrs: Vec<EventPtrRow>,
    /// Event table rows (0x14).
    pub events: Vec<EventRow>,
    /// PropertyMap table rows (0x15).
    pub property_maps: Vec<PropertyMapRow>,
    /// PropertyPtr table rows (0x16) - only in uncompressed #- streams.
    pub property_ptrs: Vec<PropertyPtrRow>,
    /// Property table rows (0x17).
    pub properties: Vec<PropertyRow>,
    /// MethodSemantics table rows (0x18).
    pub method_semantics: Vec<MethodSemanticsRow>,
    /// MethodImpl table rows (0x19).
    pub method_impls: Vec<MethodImplRow>,
    /// ModuleRef table rows (0x1A).
    pub module_refs: Vec<ModuleRefRow>,
    /// TypeSpec table rows (0x1B).
    pub type_specs: Vec<TypeSpecRow>,
    /// ImplMap table rows (0x1C).
    pub impl_maps: Vec<ImplMapRow>,
    /// FieldRva table rows (0x1D).
    pub field_rvas: Vec<FieldRvaRow>,
    /// EncLog table rows (0x1E) - Edit-and-Continue log.
    pub enc_logs: Vec<EncLogRow>,
    /// EncMap table rows (0x1F) - Edit-and-Continue mapping.
    pub enc_maps: Vec<EncMapRow>,
    /// Assembly table rows (0x20, usually 0 or 1).
    pub assemblies: Vec<AssemblyRow>,
    /// AssemblyProcessor table rows (0x21) - deprecated.
    pub assembly_processors: Vec<AssemblyProcessorRow>,
    /// AssemblyOs table rows (0x22) - deprecated.
    pub assembly_oses: Vec<AssemblyOsRow>,
    /// AssemblyRef table rows (0x23).
    pub assembly_refs: Vec<AssemblyRefRow>,
    /// AssemblyRefProcessor table rows (0x24) - deprecated.
    pub assembly_ref_processors: Vec<AssemblyRefProcessorRow>,
    /// AssemblyRefOs table rows (0x25) - deprecated.
    pub assembly_ref_oses: Vec<AssemblyRefOsRow>,
    /// File table rows (0x26) - multi-file assemblies.
    pub files: Vec<FileRow>,
    /// ExportedType table rows (0x27) - type forwarders.
    pub exported_types: Vec<ExportedTypeRow>,
    /// ManifestResource table rows (0x28).
    pub manifest_resources: Vec<ManifestResourceRow>,
    /// NestedClass table rows (0x29).
    pub nested_classes: Vec<NestedClassRow>,
    /// GenericParam table rows (0x2A).
    pub generic_params: Vec<GenericParamRow>,
    /// MethodSpec table rows (0x2B).
    pub method_specs: Vec<MethodSpecRow>,
    /// GenericParamConstraint table rows (0x2C).
    pub generic_param_constraints: Vec<GenericParamConstraintRow>,
}

impl Metadata {
    /// Parse metadata from raw bytes.
    pub fn parse(data: &[u8]) -> Result<Self> {
        let root = MetadataRoot::parse(data)?;

        // Parse heaps
        let strings = Self::parse_heap(&root, data, StreamHeader::STRINGS, StringsHeap::parse)?;
        let user_strings = Self::parse_heap(
            &root,
            data,
            StreamHeader::USER_STRINGS,
            UserStringsHeap::parse,
        )?;
        let guids = Self::parse_heap(&root, data, StreamHeader::GUID, GuidHeap::parse)?;
        let blobs = Self::parse_heap(&root, data, StreamHeader::BLOB, BlobHeap::parse)?;

        // Parse tables stream (either #~ compressed or #- uncompressed)
        let tables_stream = root
            .tables_stream()
            .ok_or_else(|| Error::StreamNotFound(StreamHeader::TABLES.to_string()))?;
        let uncompressed = tables_stream.name == StreamHeader::TABLES_UNCOMPRESSED;
        let tables_data = &data
            [tables_stream.offset as usize..(tables_stream.offset + tables_stream.size) as usize];
        let mut reader = Reader::new(tables_data);
        let tables_header = TablesHeader::parse(&mut reader, uncompressed)?;
        let ctx = tables_header.context();

        // Parse all tables in order (tables must be read sequentially)
        // 0x00 Module
        let modules = Self::parse_table(&mut reader, &ctx, TableId::Module, ModuleRow::parse)?;
        // 0x01 TypeRef
        let type_refs = Self::parse_table(&mut reader, &ctx, TableId::TypeRef, TypeRefRow::parse)?;
        // 0x02 TypeDef
        let type_defs = Self::parse_table(&mut reader, &ctx, TableId::TypeDef, TypeDefRow::parse)?;
        // 0x03 FieldPtr (only in uncompressed #- streams)
        let field_ptrs =
            Self::parse_table(&mut reader, &ctx, TableId::FieldPtr, FieldPtrRow::parse)?;
        // 0x04 Field
        let fields = Self::parse_table(&mut reader, &ctx, TableId::Field, FieldRow::parse)?;
        // 0x05 MethodPtr (only in uncompressed #- streams)
        let method_ptrs =
            Self::parse_table(&mut reader, &ctx, TableId::MethodPtr, MethodPtrRow::parse)?;
        // 0x06 MethodDef
        let method_defs =
            Self::parse_table(&mut reader, &ctx, TableId::MethodDef, MethodDefRow::parse)?;
        // 0x07 ParamPtr (only in uncompressed #- streams)
        let param_ptrs =
            Self::parse_table(&mut reader, &ctx, TableId::ParamPtr, ParamPtrRow::parse)?;
        // 0x08 Param
        let params = Self::parse_table(&mut reader, &ctx, TableId::Param, ParamRow::parse)?;
        // 0x09 InterfaceImpl
        let interface_impls = Self::parse_table(
            &mut reader,
            &ctx,
            TableId::InterfaceImpl,
            InterfaceImplRow::parse,
        )?;
        // 0x0A MemberRef
        let member_refs =
            Self::parse_table(&mut reader, &ctx, TableId::MemberRef, MemberRefRow::parse)?;
        // 0x0B Constant
        let constants =
            Self::parse_table(&mut reader, &ctx, TableId::Constant, ConstantRow::parse)?;
        // 0x0C CustomAttribute
        let custom_attributes = Self::parse_table(
            &mut reader,
            &ctx,
            TableId::CustomAttribute,
            CustomAttributeRow::parse,
        )?;
        // 0x0D FieldMarshal
        let field_marshals = Self::parse_table(
            &mut reader,
            &ctx,
            TableId::FieldMarshal,
            FieldMarshalRow::parse,
        )?;
        // 0x0E DeclSecurity
        let decl_securities = Self::parse_table(
            &mut reader,
            &ctx,
            TableId::DeclSecurity,
            DeclSecurityRow::parse,
        )?;
        // 0x0F ClassLayout
        let class_layouts = Self::parse_table(
            &mut reader,
            &ctx,
            TableId::ClassLayout,
            ClassLayoutRow::parse,
        )?;
        // 0x10 FieldLayout
        let field_layouts = Self::parse_table(
            &mut reader,
            &ctx,
            TableId::FieldLayout,
            FieldLayoutRow::parse,
        )?;
        // 0x11 StandAloneSig
        let stand_alone_sigs = Self::parse_table(
            &mut reader,
            &ctx,
            TableId::StandAloneSig,
            StandAloneSigRow::parse,
        )?;
        // 0x12 EventMap
        let event_maps =
            Self::parse_table(&mut reader, &ctx, TableId::EventMap, EventMapRow::parse)?;
        // 0x13 EventPtr (only in uncompressed #- streams)
        let event_ptrs =
            Self::parse_table(&mut reader, &ctx, TableId::EventPtr, EventPtrRow::parse)?;
        // 0x14 Event
        let events = Self::parse_table(&mut reader, &ctx, TableId::Event, EventRow::parse)?;
        // 0x15 PropertyMap
        let property_maps = Self::parse_table(
            &mut reader,
            &ctx,
            TableId::PropertyMap,
            PropertyMapRow::parse,
        )?;
        // 0x16 PropertyPtr (only in uncompressed #- streams)
        let property_ptrs = Self::parse_table(
            &mut reader,
            &ctx,
            TableId::PropertyPtr,
            PropertyPtrRow::parse,
        )?;
        // 0x17 Property
        let properties =
            Self::parse_table(&mut reader, &ctx, TableId::Property, PropertyRow::parse)?;
        // 0x18 MethodSemantics
        let method_semantics = Self::parse_table(
            &mut reader,
            &ctx,
            TableId::MethodSemantics,
            MethodSemanticsRow::parse,
        )?;
        // 0x19 MethodImpl
        let method_impls =
            Self::parse_table(&mut reader, &ctx, TableId::MethodImpl, MethodImplRow::parse)?;
        // 0x1A ModuleRef
        let module_refs =
            Self::parse_table(&mut reader, &ctx, TableId::ModuleRef, ModuleRefRow::parse)?;
        // 0x1B TypeSpec
        let type_specs =
            Self::parse_table(&mut reader, &ctx, TableId::TypeSpec, TypeSpecRow::parse)?;
        // 0x1C ImplMap
        let impl_maps = Self::parse_table(&mut reader, &ctx, TableId::ImplMap, ImplMapRow::parse)?;
        // 0x1D FieldRva
        let field_rvas =
            Self::parse_table(&mut reader, &ctx, TableId::FieldRva, FieldRvaRow::parse)?;
        // 0x1E EncLog
        let enc_logs = Self::parse_table(&mut reader, &ctx, TableId::EncLog, EncLogRow::parse)?;
        // 0x1F EncMap
        let enc_maps = Self::parse_table(&mut reader, &ctx, TableId::EncMap, EncMapRow::parse)?;
        // 0x20 Assembly
        let assemblies =
            Self::parse_table(&mut reader, &ctx, TableId::Assembly, AssemblyRow::parse)?;
        // 0x21 AssemblyProcessor (deprecated)
        let assembly_processors = Self::parse_table(
            &mut reader,
            &ctx,
            TableId::AssemblyProcessor,
            AssemblyProcessorRow::parse,
        )?;
        // 0x22 AssemblyOs (deprecated)
        let assembly_oses =
            Self::parse_table(&mut reader, &ctx, TableId::AssemblyOs, AssemblyOsRow::parse)?;
        // 0x23 AssemblyRef
        let assembly_refs = Self::parse_table(
            &mut reader,
            &ctx,
            TableId::AssemblyRef,
            AssemblyRefRow::parse,
        )?;
        // 0x24 AssemblyRefProcessor (deprecated)
        let assembly_ref_processors = Self::parse_table(
            &mut reader,
            &ctx,
            TableId::AssemblyRefProcessor,
            AssemblyRefProcessorRow::parse,
        )?;
        // 0x25 AssemblyRefOs (deprecated)
        let assembly_ref_oses = Self::parse_table(
            &mut reader,
            &ctx,
            TableId::AssemblyRefOs,
            AssemblyRefOsRow::parse,
        )?;
        // 0x26 File
        let files = Self::parse_table(&mut reader, &ctx, TableId::File, FileRow::parse)?;
        // 0x27 ExportedType
        let exported_types = Self::parse_table(
            &mut reader,
            &ctx,
            TableId::ExportedType,
            ExportedTypeRow::parse,
        )?;
        // 0x28 ManifestResource
        let manifest_resources = Self::parse_table(
            &mut reader,
            &ctx,
            TableId::ManifestResource,
            ManifestResourceRow::parse,
        )?;
        // 0x29 NestedClass
        let nested_classes = Self::parse_table(
            &mut reader,
            &ctx,
            TableId::NestedClass,
            NestedClassRow::parse,
        )?;
        // 0x2A GenericParam
        let generic_params = Self::parse_table(
            &mut reader,
            &ctx,
            TableId::GenericParam,
            GenericParamRow::parse,
        )?;
        // 0x2B MethodSpec
        let method_specs =
            Self::parse_table(&mut reader, &ctx, TableId::MethodSpec, MethodSpecRow::parse)?;
        // 0x2C GenericParamConstraint
        let generic_param_constraints = Self::parse_table(
            &mut reader,
            &ctx,
            TableId::GenericParamConstraint,
            GenericParamConstraintRow::parse,
        )?;

        Ok(Self {
            root,
            strings,
            user_strings,
            guids,
            blobs,
            tables_header,
            modules,
            type_refs,
            type_defs,
            field_ptrs,
            fields,
            method_ptrs,
            method_defs,
            param_ptrs,
            params,
            interface_impls,
            member_refs,
            constants,
            custom_attributes,
            field_marshals,
            decl_securities,
            class_layouts,
            field_layouts,
            stand_alone_sigs,
            event_maps,
            event_ptrs,
            events,
            property_maps,
            property_ptrs,
            properties,
            method_semantics,
            method_impls,
            module_refs,
            type_specs,
            impl_maps,
            field_rvas,
            enc_logs,
            enc_maps,
            assemblies,
            assembly_processors,
            assembly_oses,
            assembly_refs,
            assembly_ref_processors,
            assembly_ref_oses,
            files,
            exported_types,
            manifest_resources,
            nested_classes,
            generic_params,
            method_specs,
            generic_param_constraints,
        })
    }

    fn parse_heap<T, F>(root: &MetadataRoot, data: &[u8], name: &str, parser: F) -> Result<T>
    where
        F: FnOnce(&[u8]) -> T,
        T: Default,
    {
        if let Some(stream) = root.find_stream(name) {
            let start = stream.offset as usize;
            let end = start + stream.size as usize;
            if end <= data.len() {
                return Ok(parser(&data[start..end]));
            }
        }
        Ok(T::default())
    }

    fn parse_table<T, F>(
        reader: &mut Reader<'_>,
        ctx: &TableContext,
        table: TableId,
        parser: F,
    ) -> Result<Vec<T>>
    where
        F: Fn(&mut Reader<'_>, &TableContext) -> Result<T>,
    {
        let count = ctx.row_count(table) as usize;
        let mut rows = Vec::with_capacity(count);
        for _ in 0..count {
            rows.push(parser(reader, ctx)?);
        }
        Ok(rows)
    }

    /// Get the runtime version string.
    #[must_use]
    pub fn version(&self) -> &str {
        &self.root.version
    }

    /// Get assembly information if this is an assembly (not a netmodule).
    #[must_use]
    pub fn assembly(&self) -> Option<AssemblyInfo> {
        self.assemblies.first().map(|row| {
            let name = self.strings.get(row.name).unwrap_or("").to_string();
            let culture = if row.culture != 0 {
                self.strings.get(row.culture).ok().map(|s| s.to_string())
            } else {
                None
            };
            let public_key = if row.public_key != 0 {
                self.blobs.get(row.public_key).ok().map(|b| b.to_vec())
            } else {
                None
            };

            AssemblyInfo {
                name,
                version: (
                    row.major_version,
                    row.minor_version,
                    row.build_number,
                    row.revision_number,
                ),
                culture,
                public_key,
                flags: row.flags,
                hash_alg_id: row.hash_alg_id,
            }
        })
    }

    /// Get all type definitions.
    pub fn types(&self) -> Vec<TypeInfo> {
        self.type_defs
            .iter()
            .map(|row| {
                let name = self.strings.get(row.type_name).unwrap_or("").to_string();
                let namespace = if row.type_namespace != 0 {
                    self.strings
                        .get(row.type_namespace)
                        .ok()
                        .map(|s| s.to_string())
                } else {
                    None
                };
                TypeInfo {
                    name,
                    namespace,
                    flags: row.flags,
                }
            })
            .collect()
    }

    /// Get all method definitions.
    pub fn methods(&self) -> Vec<MethodInfo> {
        self.method_defs
            .iter()
            .map(|row| {
                let name = self.strings.get(row.name).unwrap_or("").to_string();
                MethodInfo {
                    name,
                    rva: row.rva,
                    flags: row.flags,
                    impl_flags: row.impl_flags,
                }
            })
            .collect()
    }

    /// Get all assembly references.
    pub fn assembly_refs(&self) -> Vec<AssemblyRefInfo> {
        self.assembly_refs
            .iter()
            .map(|row| {
                let name = self.strings.get(row.name).unwrap_or("").to_string();
                let culture = if row.culture != 0 {
                    self.strings.get(row.culture).ok().map(|s| s.to_string())
                } else {
                    None
                };
                let public_key_token = if row.public_key_or_token != 0 {
                    self.blobs
                        .get(row.public_key_or_token)
                        .ok()
                        .map(|b| b.to_vec())
                } else {
                    None
                };

                AssemblyRefInfo {
                    name,
                    version: (
                        row.major_version,
                        row.minor_version,
                        row.build_number,
                        row.revision_number,
                    ),
                    culture,
                    public_key_token,
                    flags: row.flags,
                }
            })
            .collect()
    }

    // ========================================================================
    // Type Hierarchy Resolution
    // ========================================================================

    /// Get the TypeDef row at the given 1-based index.
    #[must_use]
    pub fn get_type_def(&self, index: u32) -> Option<&TypeDefRow> {
        if index == 0 || index as usize > self.type_defs.len() {
            return None;
        }
        Some(&self.type_defs[(index - 1) as usize])
    }

    /// Get the TypeRef row at the given 1-based index.
    #[must_use]
    pub fn get_type_ref(&self, index: u32) -> Option<&TypeRefRow> {
        if index == 0 || index as usize > self.type_refs.len() {
            return None;
        }
        Some(&self.type_refs[(index - 1) as usize])
    }

    /// Get the TypeSpec row at the given 1-based index.
    #[must_use]
    pub fn get_type_spec(&self, index: u32) -> Option<&TypeSpecRow> {
        if index == 0 || index as usize > self.type_specs.len() {
            return None;
        }
        Some(&self.type_specs[(index - 1) as usize])
    }

    /// Resolve a TypeDefOrRef coded index to a type reference.
    #[must_use]
    pub fn resolve_type(&self, coded_index: &crate::tables::CodedIndex) -> Option<ResolvedType> {
        if coded_index.is_null() {
            return None;
        }

        match coded_index.table? {
            TableId::TypeDef => {
                let row = self.get_type_def(coded_index.row)?;
                let name = self.strings.get(row.type_name).ok()?.to_string();
                let namespace = if row.type_namespace != 0 {
                    self.strings
                        .get(row.type_namespace)
                        .ok()
                        .map(|s| s.to_string())
                } else {
                    None
                };
                Some(ResolvedType::TypeDef {
                    index: coded_index.row,
                    name,
                    namespace,
                })
            }
            TableId::TypeRef => {
                let row = self.get_type_ref(coded_index.row)?;
                let name = self.strings.get(row.type_name).ok()?.to_string();
                let namespace = if row.type_namespace != 0 {
                    self.strings
                        .get(row.type_namespace)
                        .ok()
                        .map(|s| s.to_string())
                } else {
                    None
                };
                Some(ResolvedType::TypeRef {
                    index: coded_index.row,
                    name,
                    namespace,
                })
            }
            TableId::TypeSpec => {
                let row = self.get_type_spec(coded_index.row)?;
                Some(ResolvedType::TypeSpec {
                    index: coded_index.row,
                    signature: row.signature,
                })
            }
            _ => None,
        }
    }

    /// Get the base type of a TypeDef by index (1-based).
    #[must_use]
    pub fn get_base_type(&self, type_def_index: u32) -> Option<ResolvedType> {
        let row = self.get_type_def(type_def_index)?;
        self.resolve_type(&row.extends)
    }

    /// Get all interfaces implemented by a TypeDef (1-based index).
    pub fn get_interfaces(&self, type_def_index: u32) -> Vec<ResolvedType> {
        self.interface_impls
            .iter()
            .filter(|row| row.class == type_def_index)
            .filter_map(|row| self.resolve_type(&row.interface))
            .collect()
    }

    /// Get methods belonging to a TypeDef (1-based index).
    pub fn get_type_methods(&self, type_def_index: u32) -> Vec<(u32, &MethodDefRow)> {
        let row = match self.get_type_def(type_def_index) {
            Some(r) => r,
            None => return Vec::new(),
        };

        let start = row.method_list;
        let end = self
            .get_type_def(type_def_index + 1)
            .map(|r| r.method_list)
            .unwrap_or((self.method_defs.len() + 1) as u32);

        ((start as usize)..(end as usize))
            .filter_map(|i| {
                if i > 0 && i <= self.method_defs.len() {
                    Some((i as u32, &self.method_defs[i - 1]))
                } else {
                    None
                }
            })
            .collect()
    }

    /// Get fields belonging to a TypeDef (1-based index).
    pub fn get_type_fields(&self, type_def_index: u32) -> Vec<(u32, &FieldRow)> {
        let row = match self.get_type_def(type_def_index) {
            Some(r) => r,
            None => return Vec::new(),
        };

        let start = row.field_list;
        let end = self
            .get_type_def(type_def_index + 1)
            .map(|r| r.field_list)
            .unwrap_or((self.fields.len() + 1) as u32);

        ((start as usize)..(end as usize))
            .filter_map(|i| {
                if i > 0 && i <= self.fields.len() {
                    Some((i as u32, &self.fields[i - 1]))
                } else {
                    None
                }
            })
            .collect()
    }

    /// Find a TypeDef by name (exact match).
    pub fn find_type(&self, name: &str, namespace: Option<&str>) -> Option<(u32, &TypeDefRow)> {
        for (i, row) in self.type_defs.iter().enumerate() {
            let type_name = self.strings.get(row.type_name).ok()?;
            if type_name != name {
                continue;
            }

            let type_ns = if row.type_namespace != 0 {
                self.strings.get(row.type_namespace).ok()
            } else {
                None
            };

            match (namespace, type_ns) {
                (Some(ns), Some(tns)) if ns == tns => return Some(((i + 1) as u32, row)),
                (None, None) | (None, Some("")) => return Some(((i + 1) as u32, row)),
                (Some(""), None) | (Some(""), Some("")) => return Some(((i + 1) as u32, row)),
                _ => continue,
            }
        }
        None
    }

    /// Get the owning type of a method (1-based method index).
    #[must_use]
    pub fn get_method_owner(&self, method_index: u32) -> Option<(u32, &TypeDefRow)> {
        for (i, row) in self.type_defs.iter().enumerate() {
            let start = row.method_list;
            let end = self
                .get_type_def((i + 2) as u32)
                .map(|r| r.method_list)
                .unwrap_or((self.method_defs.len() + 1) as u32);

            if method_index >= start && method_index < end {
                return Some(((i + 1) as u32, row));
            }
        }
        None
    }

    /// Get the owning type of a field (1-based field index).
    #[must_use]
    pub fn get_field_owner(&self, field_index: u32) -> Option<(u32, &TypeDefRow)> {
        for (i, row) in self.type_defs.iter().enumerate() {
            let start = row.field_list;
            let end = self
                .get_type_def((i + 2) as u32)
                .map(|r| r.field_list)
                .unwrap_or((self.fields.len() + 1) as u32);

            if field_index >= start && field_index < end {
                return Some(((i + 1) as u32, row));
            }
        }
        None
    }

    // ========================================================================
    // Validation
    // ========================================================================

    /// Validate the metadata structure.
    ///
    /// Performs structural integrity checks including:
    /// - Required tables are present (Module must have at least 1 row)
    /// - String indices are within bounds
    /// - GUID indices are within bounds
    /// - Blob indices are within bounds
    /// - Table index references are valid
    ///
    /// Returns a list of validation errors. An empty list means the metadata is valid.
    #[must_use]
    pub fn validate(&self) -> Vec<String> {
        let mut errors = Vec::new();

        // Check required tables
        if self.modules.is_empty() {
            errors.push("Module table must have at least 1 row".to_string());
        }

        // Validate Module table
        for (i, row) in self.modules.iter().enumerate() {
            self.validate_string_index(&mut errors, "Module", i, "name", row.name);
            self.validate_guid_index(&mut errors, "Module", i, "mvid", row.mvid);
        }

        // Validate TypeRef table
        for (i, row) in self.type_refs.iter().enumerate() {
            self.validate_string_index(&mut errors, "TypeRef", i, "type_name", row.type_name);
            self.validate_string_index(
                &mut errors,
                "TypeRef",
                i,
                "type_namespace",
                row.type_namespace,
            );
        }

        // Validate TypeDef table
        for (i, row) in self.type_defs.iter().enumerate() {
            self.validate_string_index(&mut errors, "TypeDef", i, "type_name", row.type_name);
            self.validate_string_index(
                &mut errors,
                "TypeDef",
                i,
                "type_namespace",
                row.type_namespace,
            );
            self.validate_table_index(
                &mut errors,
                "TypeDef",
                i,
                "field_list",
                row.field_list,
                self.fields.len(),
            );
            self.validate_table_index(
                &mut errors,
                "TypeDef",
                i,
                "method_list",
                row.method_list,
                self.method_defs.len(),
            );
        }

        // Validate Field table
        for (i, row) in self.fields.iter().enumerate() {
            self.validate_string_index(&mut errors, "Field", i, "name", row.name);
            self.validate_blob_index(&mut errors, "Field", i, "signature", row.signature);
        }

        // Validate MethodDef table
        for (i, row) in self.method_defs.iter().enumerate() {
            self.validate_string_index(&mut errors, "MethodDef", i, "name", row.name);
            self.validate_blob_index(&mut errors, "MethodDef", i, "signature", row.signature);
            self.validate_table_index(
                &mut errors,
                "MethodDef",
                i,
                "param_list",
                row.param_list,
                self.params.len(),
            );
        }

        // Validate Param table
        for (i, row) in self.params.iter().enumerate() {
            self.validate_string_index(&mut errors, "Param", i, "name", row.name);
        }

        // Validate MemberRef table
        for (i, row) in self.member_refs.iter().enumerate() {
            self.validate_string_index(&mut errors, "MemberRef", i, "name", row.name);
            self.validate_blob_index(&mut errors, "MemberRef", i, "signature", row.signature);
        }

        // Validate Constant table
        for (i, row) in self.constants.iter().enumerate() {
            self.validate_blob_index(&mut errors, "Constant", i, "value", row.value);
        }

        // Validate CustomAttribute table
        for (i, row) in self.custom_attributes.iter().enumerate() {
            self.validate_blob_index(&mut errors, "CustomAttribute", i, "value", row.value);
        }

        // Validate Assembly table
        for (i, row) in self.assemblies.iter().enumerate() {
            self.validate_string_index(&mut errors, "Assembly", i, "name", row.name);
            self.validate_string_index(&mut errors, "Assembly", i, "culture", row.culture);
            self.validate_blob_index(&mut errors, "Assembly", i, "public_key", row.public_key);
        }

        // Validate AssemblyRef table
        for (i, row) in self.assembly_refs.iter().enumerate() {
            self.validate_string_index(&mut errors, "AssemblyRef", i, "name", row.name);
            self.validate_string_index(&mut errors, "AssemblyRef", i, "culture", row.culture);
            self.validate_blob_index(
                &mut errors,
                "AssemblyRef",
                i,
                "public_key_or_token",
                row.public_key_or_token,
            );
            self.validate_blob_index(&mut errors, "AssemblyRef", i, "hash_value", row.hash_value);
        }

        // Validate coded index references
        self.validate_coded_indices(&mut errors);

        // Validate sorted table requirements
        self.validate_sorted_tables(&mut errors);

        errors
    }

    /// Validate coded index references point to valid rows.
    fn validate_coded_indices(&self, errors: &mut Vec<String>) {
        use crate::tables::{CodedIndex, CodedIndexKind};

        // Helper to validate a coded index
        let validate_coded = |errors: &mut Vec<String>,
                              table: &str,
                              row: usize,
                              field: &str,
                              idx: &CodedIndex,
                              kind: CodedIndexKind| {
            if idx.is_null() {
                return;
            }
            if let Some(target_table) = idx.table {
                let max_row = self.table_row_count(target_table);
                if idx.row == 0 || idx.row > max_row {
                    errors.push(format!(
                        "{table}[{row}].{field}: invalid {kind:?} index pointing to {target_table:?} row {} (max: {max_row})",
                        idx.row
                    ));
                }
            } else {
                errors.push(format!(
                    "{table}[{row}].{field}: coded index has invalid table tag for {kind:?}"
                ));
            }
        };

        // TypeDef.extends
        for (i, row) in self.type_defs.iter().enumerate() {
            validate_coded(
                errors,
                "TypeDef",
                i,
                "extends",
                &row.extends,
                CodedIndexKind::TypeDefOrRef,
            );
        }

        // InterfaceImpl.interface
        for (i, row) in self.interface_impls.iter().enumerate() {
            validate_coded(
                errors,
                "InterfaceImpl",
                i,
                "interface",
                &row.interface,
                CodedIndexKind::TypeDefOrRef,
            );
        }

        // MemberRef.class
        for (i, row) in self.member_refs.iter().enumerate() {
            validate_coded(
                errors,
                "MemberRef",
                i,
                "class",
                &row.class,
                CodedIndexKind::MemberRefParent,
            );
        }

        // Constant.parent
        for (i, row) in self.constants.iter().enumerate() {
            validate_coded(
                errors,
                "Constant",
                i,
                "parent",
                &row.parent,
                CodedIndexKind::HasConstant,
            );
        }

        // CustomAttribute.parent and type
        for (i, row) in self.custom_attributes.iter().enumerate() {
            validate_coded(
                errors,
                "CustomAttribute",
                i,
                "parent",
                &row.parent,
                CodedIndexKind::HasCustomAttribute,
            );
            validate_coded(
                errors,
                "CustomAttribute",
                i,
                "type",
                &row.attr_type,
                CodedIndexKind::CustomAttributeType,
            );
        }

        // GenericParamConstraint.constraint
        for (i, row) in self.generic_param_constraints.iter().enumerate() {
            validate_coded(
                errors,
                "GenericParamConstraint",
                i,
                "constraint",
                &row.constraint,
                CodedIndexKind::TypeDefOrRef,
            );
        }
    }

    /// Validate that tables that should be sorted are actually sorted.
    fn validate_sorted_tables(&self, errors: &mut Vec<String>) {
        // InterfaceImpl must be sorted by Class
        for window in self.interface_impls.windows(2) {
            if window[1].class < window[0].class {
                errors.push("InterfaceImpl table is not sorted by Class column".to_string());
                break;
            }
        }

        // Constant must be sorted by Parent
        for window in self.constants.windows(2) {
            let key0 = self.coded_index_sort_key(&window[0].parent);
            let key1 = self.coded_index_sort_key(&window[1].parent);
            if key1 < key0 {
                errors.push("Constant table is not sorted by Parent column".to_string());
                break;
            }
        }

        // FieldMarshal must be sorted by Parent
        for window in self.field_marshals.windows(2) {
            let key0 = self.coded_index_sort_key(&window[0].parent);
            let key1 = self.coded_index_sort_key(&window[1].parent);
            if key1 < key0 {
                errors.push("FieldMarshal table is not sorted by Parent column".to_string());
                break;
            }
        }

        // MethodSemantics must be sorted by Association
        for window in self.method_semantics.windows(2) {
            let key0 = self.coded_index_sort_key(&window[0].association);
            let key1 = self.coded_index_sort_key(&window[1].association);
            if key1 < key0 {
                errors
                    .push("MethodSemantics table is not sorted by Association column".to_string());
                break;
            }
        }

        // ClassLayout must be sorted by Parent
        for window in self.class_layouts.windows(2) {
            if window[1].parent < window[0].parent {
                errors.push("ClassLayout table is not sorted by Parent column".to_string());
                break;
            }
        }

        // NestedClass must be sorted by NestedClass column
        for window in self.nested_classes.windows(2) {
            if window[1].nested_class < window[0].nested_class {
                errors.push("NestedClass table is not sorted by NestedClass column".to_string());
                break;
            }
        }

        // GenericParam must be sorted by Owner
        for window in self.generic_params.windows(2) {
            let key0 = self.coded_index_sort_key(&window[0].owner);
            let key1 = self.coded_index_sort_key(&window[1].owner);
            if key1 < key0 {
                errors.push("GenericParam table is not sorted by Owner column".to_string());
                break;
            }
        }
    }

    /// Get a sort key for coded index comparison.
    fn coded_index_sort_key(&self, idx: &crate::tables::CodedIndex) -> (u8, u32) {
        let table_id = idx.table.map_or(0xff, |t| t as u8);
        (table_id, idx.row)
    }

    /// Get the row count for a table.
    fn table_row_count(&self, table: TableId) -> u32 {
        match table {
            TableId::Module => self.modules.len() as u32,
            TableId::TypeRef => self.type_refs.len() as u32,
            TableId::TypeDef => self.type_defs.len() as u32,
            TableId::FieldPtr => self.field_ptrs.len() as u32,
            TableId::Field => self.fields.len() as u32,
            TableId::MethodPtr => self.method_ptrs.len() as u32,
            TableId::MethodDef => self.method_defs.len() as u32,
            TableId::ParamPtr => self.param_ptrs.len() as u32,
            TableId::Param => self.params.len() as u32,
            TableId::InterfaceImpl => self.interface_impls.len() as u32,
            TableId::MemberRef => self.member_refs.len() as u32,
            TableId::Constant => self.constants.len() as u32,
            TableId::CustomAttribute => self.custom_attributes.len() as u32,
            TableId::FieldMarshal => self.field_marshals.len() as u32,
            TableId::DeclSecurity => self.decl_securities.len() as u32,
            TableId::ClassLayout => self.class_layouts.len() as u32,
            TableId::FieldLayout => self.field_layouts.len() as u32,
            TableId::StandAloneSig => self.stand_alone_sigs.len() as u32,
            TableId::EventMap => self.event_maps.len() as u32,
            TableId::EventPtr => self.event_ptrs.len() as u32,
            TableId::Event => self.events.len() as u32,
            TableId::PropertyMap => self.property_maps.len() as u32,
            TableId::PropertyPtr => self.property_ptrs.len() as u32,
            TableId::Property => self.properties.len() as u32,
            TableId::MethodSemantics => self.method_semantics.len() as u32,
            TableId::MethodImpl => self.method_impls.len() as u32,
            TableId::ModuleRef => self.module_refs.len() as u32,
            TableId::TypeSpec => self.type_specs.len() as u32,
            TableId::ImplMap => self.impl_maps.len() as u32,
            TableId::FieldRva => self.field_rvas.len() as u32,
            TableId::EncLog => self.enc_logs.len() as u32,
            TableId::EncMap => self.enc_maps.len() as u32,
            TableId::Assembly => self.assemblies.len() as u32,
            TableId::AssemblyProcessor => self.assembly_processors.len() as u32,
            TableId::AssemblyOs => self.assembly_oses.len() as u32,
            TableId::AssemblyRef => self.assembly_refs.len() as u32,
            TableId::AssemblyRefProcessor => self.assembly_ref_processors.len() as u32,
            TableId::AssemblyRefOs => self.assembly_ref_oses.len() as u32,
            TableId::File => self.files.len() as u32,
            TableId::ExportedType => self.exported_types.len() as u32,
            TableId::ManifestResource => self.manifest_resources.len() as u32,
            TableId::NestedClass => self.nested_classes.len() as u32,
            TableId::GenericParam => self.generic_params.len() as u32,
            TableId::MethodSpec => self.method_specs.len() as u32,
            TableId::GenericParamConstraint => self.generic_param_constraints.len() as u32,
        }
    }

    /// Validate that the metadata is structurally correct.
    ///
    /// Returns `Ok(())` if valid, or `Err` with the first validation error.
    pub fn validate_strict(&self) -> Result<()> {
        let errors = self.validate();
        if let Some(first_error) = errors.into_iter().next() {
            Err(Error::ValidationError(first_error))
        } else {
            Ok(())
        }
    }

    fn validate_string_index(
        &self,
        errors: &mut Vec<String>,
        table: &str,
        row: usize,
        field: &str,
        index: u32,
    ) {
        if index != 0 && self.strings.get(index).is_err() {
            errors.push(format!(
                "{table}[{row}].{field}: invalid string index {index}"
            ));
        }
    }

    fn validate_guid_index(
        &self,
        errors: &mut Vec<String>,
        table: &str,
        row: usize,
        field: &str,
        index: u32,
    ) {
        if index != 0 && self.guids.get(index).is_err() {
            errors.push(format!(
                "{table}[{row}].{field}: invalid GUID index {index}"
            ));
        }
    }

    fn validate_blob_index(
        &self,
        errors: &mut Vec<String>,
        table: &str,
        row: usize,
        field: &str,
        index: u32,
    ) {
        if index != 0 && self.blobs.get(index).is_err() {
            errors.push(format!(
                "{table}[{row}].{field}: invalid blob index {index}"
            ));
        }
    }

    fn validate_table_index(
        &self,
        errors: &mut Vec<String>,
        table: &str,
        row: usize,
        field: &str,
        index: u32,
        max_rows: usize,
    ) {
        // Table indices are 1-based, 0 means null
        // A "list" index can be max_rows + 1 (meaning empty list at end)
        if index > (max_rows as u32) + 1 {
            errors.push(format!(
                "{table}[{row}].{field}: invalid table index {index} (max {max_rows})"
            ));
        }
    }
}

/// High-level assembly information.
#[derive(Debug, Clone)]
pub struct AssemblyInfo {
    /// Assembly name.
    pub name: String,
    /// Version (major, minor, build, revision).
    pub version: (u16, u16, u16, u16),
    /// Culture (e.g., "en-US"), or None for neutral.
    pub culture: Option<String>,
    /// Public key blob.
    pub public_key: Option<Vec<u8>>,
    /// Assembly flags.
    pub flags: u32,
    /// Hash algorithm ID.
    pub hash_alg_id: u32,
}

impl AssemblyInfo {
    /// Get a formatted version string (e.g., "1.2.3.4").
    #[must_use]
    pub fn version_string(&self) -> String {
        format!(
            "{}.{}.{}.{}",
            self.version.0, self.version.1, self.version.2, self.version.3
        )
    }

    /// Compute the public key token (last 8 bytes of SHA-1 hash, reversed).
    #[must_use]
    pub fn public_key_token(&self) -> Option<[u8; 8]> {
        self.public_key
            .as_ref()
            .map(|pk| crate::crypto::public_key_token(pk))
    }

    /// Format the public key token as a hex string (e.g., "b77a5c561934e089").
    #[must_use]
    pub fn public_key_token_string(&self) -> Option<String> {
        self.public_key_token()
            .map(|token| token.iter().map(|b| format!("{b:02x}")).collect::<String>())
    }
}

/// High-level type information.
#[derive(Debug, Clone)]
pub struct TypeInfo {
    /// Type name.
    pub name: String,
    /// Namespace (None if empty).
    pub namespace: Option<String>,
    /// Type attributes/flags.
    pub flags: u32,
}

impl TypeInfo {
    /// Get the full name (namespace.name or just name).
    #[must_use]
    pub fn full_name(&self) -> String {
        if let Some(ns) = &self.namespace
            && !ns.is_empty()
        {
            return format!("{}.{}", ns, self.name);
        }
        self.name.clone()
    }
}

/// High-level method information.
#[derive(Debug, Clone)]
pub struct MethodInfo {
    /// Method name.
    pub name: String,
    /// RVA of the method body (0 for abstract/runtime methods).
    pub rva: u32,
    /// Method flags.
    pub flags: u16,
    /// Implementation flags.
    pub impl_flags: u16,
}

/// High-level assembly reference information.
#[derive(Debug, Clone)]
pub struct AssemblyRefInfo {
    /// Assembly name.
    pub name: String,
    /// Version (major, minor, build, revision).
    pub version: (u16, u16, u16, u16),
    /// Culture (e.g., "en-US"), or None for neutral.
    pub culture: Option<String>,
    /// Public key token.
    pub public_key_token: Option<Vec<u8>>,
    /// Assembly flags.
    pub flags: u32,
}

impl AssemblyRefInfo {
    /// Get a formatted version string (e.g., "1.2.3.4").
    #[must_use]
    pub fn version_string(&self) -> String {
        format!(
            "{}.{}.{}.{}",
            self.version.0, self.version.1, self.version.2, self.version.3
        )
    }
}

/// A resolved type reference from a TypeDefOrRef coded index.
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub enum ResolvedType {
    /// A type defined in this assembly (TypeDef table).
    TypeDef {
        /// 1-based row index in TypeDef table.
        index: u32,
        /// Type name.
        name: String,
        /// Namespace (None if empty).
        namespace: Option<String>,
    },
    /// A type referenced from another assembly (TypeRef table).
    TypeRef {
        /// 1-based row index in TypeRef table.
        index: u32,
        /// Type name.
        name: String,
        /// Namespace (None if empty).
        namespace: Option<String>,
    },
    /// A generic type instantiation (TypeSpec table).
    TypeSpec {
        /// 1-based row index in TypeSpec table.
        index: u32,
        /// Signature blob index.
        signature: u32,
    },
}

impl ResolvedType {
    /// Get the full name of the type (namespace.name or just name).
    #[must_use]
    pub fn full_name(&self) -> String {
        match self {
            Self::TypeDef {
                name, namespace, ..
            }
            | Self::TypeRef {
                name, namespace, ..
            } => {
                if let Some(ns) = namespace
                    && !ns.is_empty()
                {
                    return format!("{ns}.{name}");
                }
                name.clone()
            }
            Self::TypeSpec { signature, .. } => format!("<TypeSpec sig={signature}>"),
        }
    }

    /// Check if this is a TypeDef (defined in current assembly).
    #[must_use]
    pub const fn is_type_def(&self) -> bool {
        matches!(self, Self::TypeDef { .. })
    }

    /// Check if this is a TypeRef (external reference).
    #[must_use]
    pub const fn is_type_ref(&self) -> bool {
        matches!(self, Self::TypeRef { .. })
    }

    /// Check if this is a TypeSpec (generic instantiation).
    #[must_use]
    pub const fn is_type_spec(&self) -> bool {
        matches!(self, Self::TypeSpec { .. })
    }
}

impl Metadata {
    /// Write the metadata to bytes.
    ///
    /// Note: This is a simplified write that may not produce byte-identical output
    /// for complex metadata. It's suitable for modified metadata that will be
    /// re-embedded into a PE file.
    #[must_use]
    pub fn write(&self) -> Vec<u8> {
        let mut writer = Writer::new();
        self.write_to(&mut writer);
        writer.into_inner()
    }

    /// Write the metadata to a writer.
    pub fn write_to(&self, writer: &mut Writer) {
        // For now, we'll write the original structure back
        // A full implementation would rebuild all streams and tables

        // Calculate heap sizes
        let heap_sizes = self.calculate_heap_sizes();

        // Build a modified root with correct offsets
        let mut root = self.root.clone();

        // Calculate stream offsets
        let header_size = root.header_size();
        let mut current_offset = header_size;

        // Update stream headers with new offsets
        for stream in &mut root.streams {
            stream.offset = current_offset as u32;
            match stream.name.as_str() {
                StreamHeader::TABLES | StreamHeader::TABLES_UNCOMPRESSED => {
                    // Tables stream size will be calculated
                    stream.size = self.calculate_tables_size() as u32;
                }
                StreamHeader::STRINGS => {
                    stream.size = self.strings.size() as u32;
                }
                StreamHeader::USER_STRINGS => {
                    stream.size = self.user_strings.size() as u32;
                }
                StreamHeader::GUID => {
                    stream.size = self.guids.size() as u32;
                }
                StreamHeader::BLOB => {
                    stream.size = self.blobs.size() as u32;
                }
                _ => {}
            }
            current_offset += stream.size as usize;
            // Align to 4 bytes
            current_offset = (current_offset + 3) & !3;
        }

        // Write root header
        root.write_to(writer);

        // Write streams in order
        for stream in &root.streams {
            match stream.name.as_str() {
                StreamHeader::TABLES | StreamHeader::TABLES_UNCOMPRESSED => {
                    self.write_tables(writer, heap_sizes);
                }
                StreamHeader::STRINGS => {
                    self.strings.write_to(writer);
                }
                StreamHeader::USER_STRINGS => {
                    self.user_strings.write_to(writer);
                }
                StreamHeader::GUID => {
                    self.guids.write_to(writer);
                }
                StreamHeader::BLOB => {
                    self.blobs.write_to(writer);
                }
                _ => {
                    // Unknown stream - skip
                }
            }
            // Align to 4 bytes
            writer.align(4);
        }
    }

    fn calculate_heap_sizes(&self) -> u8 {
        let mut heap_sizes = 0u8;
        if self.strings.uses_wide_indices() {
            heap_sizes |= 0x01;
        }
        if self.guids.uses_wide_indices() {
            heap_sizes |= 0x02;
        }
        if self.blobs.uses_wide_indices() {
            heap_sizes |= 0x04;
        }
        heap_sizes
    }

    fn calculate_tables_size(&self) -> usize {
        let ctx = self.tables_header.context();

        // Header size
        let mut size = self.tables_header.size();

        // Add size of each table
        for (table, count) in self.tables_header.tables() {
            size += count as usize * ctx.row_size(table);
        }

        size
    }

    fn write_tables(&self, writer: &mut Writer, heap_sizes: u8) {
        // Write tables header
        let mut header = self.tables_header.clone();
        header.heap_sizes = heap_sizes;

        // Update row counts for all tables
        header.set_row_count(TableId::Module, self.modules.len() as u32);
        header.set_row_count(TableId::TypeRef, self.type_refs.len() as u32);
        header.set_row_count(TableId::TypeDef, self.type_defs.len() as u32);
        header.set_row_count(TableId::FieldPtr, self.field_ptrs.len() as u32);
        header.set_row_count(TableId::Field, self.fields.len() as u32);
        header.set_row_count(TableId::MethodPtr, self.method_ptrs.len() as u32);
        header.set_row_count(TableId::MethodDef, self.method_defs.len() as u32);
        header.set_row_count(TableId::ParamPtr, self.param_ptrs.len() as u32);
        header.set_row_count(TableId::Param, self.params.len() as u32);
        header.set_row_count(TableId::InterfaceImpl, self.interface_impls.len() as u32);
        header.set_row_count(TableId::MemberRef, self.member_refs.len() as u32);
        header.set_row_count(TableId::Constant, self.constants.len() as u32);
        header.set_row_count(
            TableId::CustomAttribute,
            self.custom_attributes.len() as u32,
        );
        header.set_row_count(TableId::FieldMarshal, self.field_marshals.len() as u32);
        header.set_row_count(TableId::DeclSecurity, self.decl_securities.len() as u32);
        header.set_row_count(TableId::ClassLayout, self.class_layouts.len() as u32);
        header.set_row_count(TableId::FieldLayout, self.field_layouts.len() as u32);
        header.set_row_count(TableId::StandAloneSig, self.stand_alone_sigs.len() as u32);
        header.set_row_count(TableId::EventMap, self.event_maps.len() as u32);
        header.set_row_count(TableId::EventPtr, self.event_ptrs.len() as u32);
        header.set_row_count(TableId::Event, self.events.len() as u32);
        header.set_row_count(TableId::PropertyMap, self.property_maps.len() as u32);
        header.set_row_count(TableId::PropertyPtr, self.property_ptrs.len() as u32);
        header.set_row_count(TableId::Property, self.properties.len() as u32);
        header.set_row_count(TableId::MethodSemantics, self.method_semantics.len() as u32);
        header.set_row_count(TableId::MethodImpl, self.method_impls.len() as u32);
        header.set_row_count(TableId::ModuleRef, self.module_refs.len() as u32);
        header.set_row_count(TableId::TypeSpec, self.type_specs.len() as u32);
        header.set_row_count(TableId::ImplMap, self.impl_maps.len() as u32);
        header.set_row_count(TableId::FieldRva, self.field_rvas.len() as u32);
        header.set_row_count(TableId::EncLog, self.enc_logs.len() as u32);
        header.set_row_count(TableId::EncMap, self.enc_maps.len() as u32);
        header.set_row_count(TableId::Assembly, self.assemblies.len() as u32);
        header.set_row_count(
            TableId::AssemblyProcessor,
            self.assembly_processors.len() as u32,
        );
        header.set_row_count(TableId::AssemblyOs, self.assembly_oses.len() as u32);
        header.set_row_count(TableId::AssemblyRef, self.assembly_refs.len() as u32);
        header.set_row_count(
            TableId::AssemblyRefProcessor,
            self.assembly_ref_processors.len() as u32,
        );
        header.set_row_count(TableId::AssemblyRefOs, self.assembly_ref_oses.len() as u32);
        header.set_row_count(TableId::File, self.files.len() as u32);
        header.set_row_count(TableId::ExportedType, self.exported_types.len() as u32);
        header.set_row_count(
            TableId::ManifestResource,
            self.manifest_resources.len() as u32,
        );
        header.set_row_count(TableId::NestedClass, self.nested_classes.len() as u32);
        header.set_row_count(TableId::GenericParam, self.generic_params.len() as u32);
        header.set_row_count(TableId::MethodSpec, self.method_specs.len() as u32);
        header.set_row_count(
            TableId::GenericParamConstraint,
            self.generic_param_constraints.len() as u32,
        );

        header.write_to(writer);

        let ctx = header.context();

        // Write all table rows in order by TableId
        // 0x00 Module
        for row in &self.modules {
            row.write(writer, &ctx);
        }
        // 0x01 TypeRef
        for row in &self.type_refs {
            row.write(writer, &ctx);
        }
        // 0x02 TypeDef
        for row in &self.type_defs {
            row.write(writer, &ctx);
        }
        // 0x03 FieldPtr
        for row in &self.field_ptrs {
            row.write(writer, &ctx);
        }
        // 0x04 Field
        for row in &self.fields {
            row.write(writer, &ctx);
        }
        // 0x05 MethodPtr
        for row in &self.method_ptrs {
            row.write(writer, &ctx);
        }
        // 0x06 MethodDef
        for row in &self.method_defs {
            row.write(writer, &ctx);
        }
        // 0x07 ParamPtr
        for row in &self.param_ptrs {
            row.write(writer, &ctx);
        }
        // 0x08 Param
        for row in &self.params {
            row.write(writer, &ctx);
        }
        // 0x09 InterfaceImpl
        for row in &self.interface_impls {
            row.write(writer, &ctx);
        }
        // 0x0A MemberRef
        for row in &self.member_refs {
            row.write(writer, &ctx);
        }
        // 0x0B Constant
        for row in &self.constants {
            row.write(writer, &ctx);
        }
        // 0x0C CustomAttribute
        for row in &self.custom_attributes {
            row.write(writer, &ctx);
        }
        // 0x0D FieldMarshal
        for row in &self.field_marshals {
            row.write(writer, &ctx);
        }
        // 0x0E DeclSecurity
        for row in &self.decl_securities {
            row.write(writer, &ctx);
        }
        // 0x0F ClassLayout
        for row in &self.class_layouts {
            row.write(writer, &ctx);
        }
        // 0x10 FieldLayout
        for row in &self.field_layouts {
            row.write(writer, &ctx);
        }
        // 0x11 StandAloneSig
        for row in &self.stand_alone_sigs {
            row.write(writer, &ctx);
        }
        // 0x12 EventMap
        for row in &self.event_maps {
            row.write(writer, &ctx);
        }
        // 0x13 EventPtr
        for row in &self.event_ptrs {
            row.write(writer, &ctx);
        }
        // 0x14 Event
        for row in &self.events {
            row.write(writer, &ctx);
        }
        // 0x15 PropertyMap
        for row in &self.property_maps {
            row.write(writer, &ctx);
        }
        // 0x16 PropertyPtr
        for row in &self.property_ptrs {
            row.write(writer, &ctx);
        }
        // 0x17 Property
        for row in &self.properties {
            row.write(writer, &ctx);
        }
        // 0x18 MethodSemantics
        for row in &self.method_semantics {
            row.write(writer, &ctx);
        }
        // 0x19 MethodImpl
        for row in &self.method_impls {
            row.write(writer, &ctx);
        }
        // 0x1A ModuleRef
        for row in &self.module_refs {
            row.write(writer, &ctx);
        }
        // 0x1B TypeSpec
        for row in &self.type_specs {
            row.write(writer, &ctx);
        }
        // 0x1C ImplMap
        for row in &self.impl_maps {
            row.write(writer, &ctx);
        }
        // 0x1D FieldRva
        for row in &self.field_rvas {
            row.write(writer, &ctx);
        }
        // 0x1E EncLog
        for row in &self.enc_logs {
            row.write(writer, &ctx);
        }
        // 0x1F EncMap
        for row in &self.enc_maps {
            row.write(writer, &ctx);
        }
        // 0x20 Assembly
        for row in &self.assemblies {
            row.write(writer, &ctx);
        }
        // 0x21 AssemblyProcessor
        for row in &self.assembly_processors {
            row.write(writer, &ctx);
        }
        // 0x22 AssemblyOs
        for row in &self.assembly_oses {
            row.write(writer, &ctx);
        }
        // 0x23 AssemblyRef
        for row in &self.assembly_refs {
            row.write(writer, &ctx);
        }
        // 0x24 AssemblyRefProcessor
        for row in &self.assembly_ref_processors {
            row.write(writer, &ctx);
        }
        // 0x25 AssemblyRefOs
        for row in &self.assembly_ref_oses {
            row.write(writer, &ctx);
        }
        // 0x26 File
        for row in &self.files {
            row.write(writer, &ctx);
        }
        // 0x27 ExportedType
        for row in &self.exported_types {
            row.write(writer, &ctx);
        }
        // 0x28 ManifestResource
        for row in &self.manifest_resources {
            row.write(writer, &ctx);
        }
        // 0x29 NestedClass
        for row in &self.nested_classes {
            row.write(writer, &ctx);
        }
        // 0x2A GenericParam
        for row in &self.generic_params {
            row.write(writer, &ctx);
        }
        // 0x2B MethodSpec
        for row in &self.method_specs {
            row.write(writer, &ctx);
        }
        // 0x2C GenericParamConstraint
        for row in &self.generic_param_constraints {
            row.write(writer, &ctx);
        }
    }
}