dotscope 0.6.0

A high-performance, cross-platform framework for analyzing and reverse engineering .NET PE executables
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
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
//! High-level .NET assembly abstraction and metadata access.
//!
//! This module provides the main entry point for analyzing .NET assemblies through the
//! [`crate::CilObject`] struct. It offers comprehensive access to all ECMA-335 metadata
//! tables, streams, type system, resources, and assembly information with efficient
//! memory management and thread-safe access patterns.
//!
//! # Architecture
//!
//! The module is built around a self-referencing pattern that ensures parsed metadata
//! structures maintain valid references to the underlying file data without expensive
//! copying. Key architectural components include:
//!
//! - **File Layer**: Memory-mapped file access for efficient I/O
//! - **Metadata Layer**: Structured access to ECMA-335 metadata tables and streams
//! - **Validation Layer**: Configurable validation during loading
//! - **Caching Layer**: Thread-safe caching of parsed structures
//! - **Analysis Layer**: High-level access to types, methods, fields, and metadata
//!
//! # Key Components
//!
//! ## Core Types
//! - [`crate::CilObject`] - Main entry point for .NET assembly analysis
//! - Internal data structure holding parsed metadata and type registry
//!
//! ## Loading Methods
//! - [`crate::CilObject::from_path`] - Load assembly from disk with default validation
//! - [`crate::CilObject::from_path_with_validation`] - Load from path with custom validation settings
//! - [`crate::CilObject::from_mem`] - Load assembly from memory buffer
//! - [`crate::CilObject::from_mem_with_validation`] - Load from memory with custom validation
//! - [`crate::CilObject::from_dotscope_file`] - Load from a dotscope File instance
//! - [`crate::CilObject::from_dotscope_file_with_validation`] - Load from File with custom validation
//! - [`crate::CilObject::from_std_file`] - Load from a std::fs::File handle
//! - [`crate::CilObject::from_std_file_with_validation`] - Load from std::fs::File with custom validation
//! - [`crate::CilObject::from_reader`] - Load from any Read implementation
//! - [`crate::CilObject::from_reader_with_validation`] - Load from Read with custom validation
//! - [`crate::CilObject::from_view`] - Load from a CilAssemblyView instance
//! - [`crate::CilObject::from_view_with_validation`] - Load from CilAssemblyView with custom validation
//!
//! ## Metadata Access Methods
//! - [`crate::CilObject::module`] - Get module information
//! - [`crate::CilObject::assembly`] - Get assembly metadata
//! - [`crate::CilObject::strings`] - Access strings heap
//! - [`crate::CilObject::userstrings`] - Access user strings heap
//! - [`crate::CilObject::guids`] - Access GUID heap
//! - [`crate::CilObject::blob`] - Access blob heap
//! - [`crate::CilObject::tables`] - Access raw metadata tables
//!
//! ## High-level Analysis Methods
//! - [`crate::CilObject::types`] - Get all type definitions
//! - [`crate::CilObject::methods`] - Get all method definitions
//! - [`crate::CilObject::imports`] - Get imported types and methods
//! - [`crate::CilObject::exports`] - Get exported types and methods
//! - [`crate::CilObject::resources`] - Get embedded resources
//!
//! # Usage Examples
//!
//! ## Basic Assembly Loading and Analysis
//!
//! ```rust,no_run
//! use dotscope::CilObject;
//! use std::path::Path;
//!
//! // Load an assembly from file
//! let assembly = CilObject::from_path(Path::new("tests/samples/mono_4.8/mscorlib.dll"))?;
//!
//! // Access basic assembly information
//! if let Some(module) = assembly.module() {
//!     println!("Module: {}", module.name);
//! }
//!
//! if let Some(assembly_info) = assembly.assembly() {
//!     println!("Assembly: {}", assembly_info.name);
//! }
//!
//! // Analyze types and methods
//! let types = assembly.types();
//! let methods = assembly.methods();
//! println!("Found {} types and {} methods", types.len(), methods.len());
//! # Ok::<(), dotscope::Error>(())
//! ```
//!
//! ## Memory-based Analysis
//!
//! ```rust,no_run
//! use dotscope::CilObject;
//!
//! // Load from memory buffer (e.g., downloaded or embedded)
//! let file_data = std::fs::read("assembly.dll")?;
//! let assembly = CilObject::from_mem(file_data)?;
//!
//! // Access metadata streams with iteration
//! if let Some(strings) = assembly.strings() {
//!     // Indexed access
//!     if let Ok(name) = strings.get(1) {
//!         println!("String at index 1: {}", name);
//!     }
//!     
//!     // Iterate through all strings
//!     for (offset, string) in strings.iter() {
//!         println!("String at {}: '{}'", offset, string);
//!     }
//! }
//! # Ok::<(), Box<dyn std::error::Error>>(())
//! ```
//!
//! ## Custom Validation Settings
//!
//! ```rust,no_run
//! use dotscope::{CilObject, ValidationConfig};
//! use std::path::Path;
//!
//! // Use minimal validation for best performance
//! let assembly = CilObject::from_path_with_validation(
//!     Path::new("tests/samples/mono_4.8/mscorlib.dll"),
//!     ValidationConfig::minimal()
//! )?;
//!
//! // Use strict validation for maximum verification
//! let assembly = CilObject::from_path_with_validation(
//!     Path::new("tests/samples/mono_4.8/mscorlib.dll"),
//!     ValidationConfig::strict()
//! )?;
//! # Ok::<(), dotscope::Error>(())
//! ```
//!
//! ## Comprehensive Metadata Analysis
//!
//! ```rust,no_run
//! use dotscope::CilObject;
//! use std::path::Path;
//!
//! let assembly = CilObject::from_path(Path::new("tests/samples/mono_4.8/mscorlib.dll"))?;
//!
//! // Analyze imports and exports
//! let imports = assembly.imports();
//! let exports = assembly.exports();
//! println!("Imports: {} items", imports.total_count());
//! println!("Exports: {} items", exports.total_count());
//!
//! // Access embedded resources
//! let resources = assembly.resources();
//! println!("Resources: {} items", resources.len());
//!
//! // Access raw metadata tables for low-level analysis
//! if let Some(tables) = assembly.tables() {
//!     println!("Metadata schema version: {}.{}",
//!              tables.major_version, tables.minor_version);
//! }
//! # Ok::<(), dotscope::Error>(())
//! ```
//!
//! # Error Handling
//!
//! All operations return [`crate::Result<T>`] with comprehensive error information:
//! - **File I/O errors**: When files cannot be read or accessed
//! - **Format errors**: When PE or metadata format is invalid
//! - **Validation errors**: When validation checks fail during loading
//! - **Memory errors**: When insufficient memory is available
//!
//! # Thread Safety
//!
//! [`crate::CilObject`] is designed for thread-safe concurrent read access. Internal
//! caching and lazy loading use appropriate synchronization primitives to ensure
//! correctness in multi-threaded scenarios. All public APIs are [`std::marker::Send`] and [`std::marker::Sync`].
//!
use std::{path::Path, sync::Arc};

use log::debug;

use crate::{
    analysis::CallGraph,
    cilassembly::CilAssembly,
    file::File,
    metadata::{
        cilassemblyview::CilAssemblyView,
        cor20header::Cor20Header,
        diagnostics::Diagnostics,
        exports::UnifiedExportContainer,
        identity::AssemblyIdentity,
        imports::UnifiedImportContainer,
        loader::CilObjectData,
        method::{method_name_by_token, MethodMap, MethodRc},
        query::{MethodQuery, TypeQuery},
        resources::Resources,
        root::Root,
        streams::{Blob, Guid, Strings, TablesHeader, UserStrings},
        tables::{
            member_ref_name_by_token, method_spec_name_by_token, AssemblyOsRc, AssemblyProcessorRc,
            AssemblyRc, AssemblyRefMap, DeclSecurityMap, MemberRefMap, MemberRefRc, MethodSpecMap,
            MethodSpecRc, ModuleRc, ModuleRefMap,
        },
        token::Token,
        typesystem::TypeRegistry,
        validation::{ValidationConfig, ValidationEngine},
    },
    project::ProjectContext,
    Error, Result,
};

/// A fully parsed and loaded .NET assembly representation.
///
/// `CilObject` is the main entry point for analyzing .NET PE files, providing
/// access to all metadata tables, streams, and assembly information. It uses
/// efficient memory access techniques to handle large assemblies while
/// maintaining memory safety through self-referencing data structures.
///
/// The object automatically handles the complex .NET metadata format including:
/// - CLI header parsing and validation
/// - Metadata root and stream directory processing  
/// - All metadata tables (Type, Method, Field, Assembly, etc.)
/// - String heaps, user string heaps, GUID heaps, and blob heaps
/// - Cross-references between assemblies and modules
/// - Type system construction and method disassembly integration
///
/// # Architecture
///
/// The implementation uses a self-referencing pattern to ensure that parsed
/// metadata structures maintain valid references to the underlying file data
/// without requiring expensive data copying. This enables efficient analysis
/// of large assemblies while maintaining Rust's memory safety guarantees.
///
/// # Usage Examples
///
/// ```rust,no_run
/// use dotscope::CilObject;
/// use std::path::Path;
///
/// // Load an assembly from file
/// let assembly = CilObject::from_path(Path::new("tests/samples/mono_4.8/mscorlib.dll"))?;
///
/// // Access assembly metadata
/// if let Some(assembly_info) = assembly.assembly() {
///     println!("Assembly name: {}", assembly_info.name);
/// }
/// println!("Number of types: {}", assembly.types().len());
///
/// // Examine methods
/// for entry in assembly.methods().iter() {
///     let method = entry.value();
///     println!("Method: {} (RVA: {:X})", method.name, method.rva.unwrap_or(0));
/// }
///
/// // Load from memory buffer
/// let file_data = std::fs::read("tests/samples/mono_4.8/mscorlib.dll")?;
/// let assembly = CilObject::from_mem(file_data)?;
/// # Ok::<(), Box<dyn std::error::Error>>(())
/// ```
///
/// # Thread Safety
///
/// [`CilObject`] is [`std::marker::Send`] and [`std::marker::Sync`] for thread-safe concurrent read access.
/// Internal caching and lazy loading use appropriate synchronization primitives
/// to ensure correctness in multi-threaded scenarios. All accessor methods can be
/// safely called concurrently from multiple threads.
pub struct CilObject {
    /// Handles file lifetime management and provides raw metadata access
    assembly_view: CilAssemblyView,
    /// Contains resolved metadata structures (types, methods, etc.)
    data: CilObjectData,
}

impl CilObject {
    /// Creates a new `CilObject` by loading and parsing a .NET assembly from a path.
    ///
    /// This method handles the complete loading process including file I/O,
    /// PE header validation, and metadata parsing. The file is memory-mapped
    /// for efficient access to large assemblies.
    ///
    /// # Arguments
    ///
    /// * `path` - Path to the .NET assembly file (.dll, .exe, or .netmodule).
    ///   Accepts `&Path`, `&str`, `String`, or `PathBuf`.
    ///
    /// # Returns
    ///
    /// Returns a fully parsed `CilObject` or an error if:
    /// - The file cannot be opened or read
    /// - The file is not a valid PE format
    /// - The PE file is not a valid .NET assembly
    /// - Metadata streams are corrupted or invalid
    ///
    /// # Usage Examples
    ///
    /// ```rust,no_run
    /// use dotscope::CilObject;
    /// use std::path::Path;
    ///
    /// // With Path
    /// let assembly = CilObject::from_path(Path::new("tests/samples/mono_4.8/mscorlib.dll"))?;
    ///
    /// // With string slice
    /// let assembly = CilObject::from_path("tests/samples/mono_4.8/mscorlib.dll")?;
    ///
    /// if let Some(assembly_info) = assembly.assembly() {
    ///     println!("Loaded assembly: {}", assembly_info.name);
    /// }
    /// # Ok::<(), dotscope::Error>(())
    /// ```
    ///
    /// # Errors
    ///
    /// Returns [`crate::Error`] if the file cannot be read or parsed as a valid .NET assembly.
    ///
    /// # Thread Safety
    ///
    /// This method is thread-safe and can be called concurrently from multiple threads.
    pub fn from_path(path: impl AsRef<Path>) -> Result<Self> {
        Self::from_path_with_validation(path, ValidationConfig::production())
    }

    /// Creates a new `CilObject` by parsing a .NET assembly from a path with custom validation configuration.
    ///
    /// This method allows you to control which validation checks are performed during loading.
    /// Use this when you need to balance security requirements vs. loading speed.
    ///
    /// # Arguments
    ///
    /// * `path` - Path to the .NET assembly file. Accepts `&Path`, `&str`, `String`, or `PathBuf`.
    /// * `validation_config` - Configuration specifying which validation checks to perform
    ///
    /// # Usage Examples
    ///
    /// ```rust,no_run
    /// use dotscope::{CilObject, ValidationConfig};
    /// use std::path::Path;
    ///
    /// // Load with minimal validation for maximum speed
    /// let assembly = CilObject::from_path_with_validation(
    ///     "tests/samples/mono_4.8/mscorlib.dll",
    ///     ValidationConfig::minimal()
    /// )?;
    ///
    /// // Load with production validation for balance of safety and speed
    /// let assembly = CilObject::from_path_with_validation(
    ///     Path::new("tests/samples/mono_4.8/mscorlib.dll"),
    ///     ValidationConfig::production()
    /// )?;
    /// # Ok::<(), dotscope::Error>(())
    /// ```
    ///
    /// # Errors
    ///
    /// Returns [`crate::Error`] if the file cannot be read, parsed as a valid .NET assembly,
    /// or if validation checks fail.
    ///
    /// # Thread Safety
    ///
    /// This method is thread-safe and can be called concurrently from multiple threads.
    pub fn from_path_with_validation(
        path: impl AsRef<Path>,
        validation_config: ValidationConfig,
    ) -> Result<Self> {
        debug!("Loading assembly: {}", path.as_ref().display());
        let assembly_view = CilAssemblyView::from_path(path)?;
        let lenient = validation_config.lenient;
        let data = CilObjectData::from_assembly_view(&assembly_view, None, lenient)?;

        let object = CilObject {
            assembly_view,
            data,
        };

        object.validate(validation_config)?;
        debug!(
            "Assembly loaded: {} types, {} methods",
            object.types().len(),
            object.methods().len()
        );
        Ok(object)
    }

    /// Creates a new `CilObject` by parsing a .NET assembly from a memory buffer.
    ///
    /// This method is useful for analyzing assemblies that are already loaded
    /// in memory, downloaded from network sources, or embedded as resources.
    /// The data is copied internally to ensure proper lifetime management.
    ///
    /// # Arguments
    ///
    /// * `data` - Raw bytes of the .NET assembly in PE format
    ///
    /// # Returns
    ///
    /// Returns a fully parsed `CilObject` or an error if:
    /// - The data is not a valid PE format
    /// - The PE data is not a valid .NET assembly  
    /// - Metadata streams are corrupted or invalid
    /// - Memory allocation fails during processing
    ///
    /// # Usage Examples
    ///
    /// ```rust,no_run
    /// use dotscope::CilObject;
    ///
    /// // Load assembly from file into memory then parse
    /// let file_data = std::fs::read("tests/samples/mono_4.8/mscorlib.dll")?;
    /// let assembly = CilObject::from_mem(file_data)?;
    ///
    /// // Access the loaded assembly
    /// if let Some(module) = assembly.module() {
    ///     println!("Module name: {}", module.name);
    /// }
    /// # Ok::<(), Box<dyn std::error::Error>>(())
    /// ```
    ///
    /// # Errors
    ///
    /// Returns [`crate::Error`] if the memory buffer cannot be parsed as a valid .NET assembly.
    ///
    /// # Thread Safety
    ///
    /// This method is thread-safe and can be called concurrently from multiple threads.
    pub fn from_mem(data: Vec<u8>) -> Result<Self> {
        Self::from_mem_with_validation(data, ValidationConfig::production())
    }

    /// Creates a new `CilObject` by parsing a .NET assembly from a memory buffer with custom validation configuration.
    ///
    /// This method allows you to control which validation checks are performed during loading.
    /// Use this when you need to balance security requirements vs. loading speed.
    ///
    /// # Arguments
    ///
    /// * `data` - Raw bytes of the .NET assembly in PE format
    /// * `validation_config` - Configuration specifying which validation checks to perform
    ///
    /// # Usage Examples
    ///
    /// ```rust,no_run
    /// use dotscope::{CilObject, ValidationConfig};
    ///
    /// let file_data = std::fs::read("tests/samples/mono_4.8/mscorlib.dll")?;
    ///
    /// // Load with production validation settings
    /// let assembly = CilObject::from_mem_with_validation(
    ///     file_data.clone(),
    ///     ValidationConfig::production()
    /// )?;
    /// # Ok::<(), Box<dyn std::error::Error>>(())
    /// ```
    ///
    /// # Errors
    ///
    /// Returns [`crate::Error`] if the memory buffer cannot be parsed as a valid .NET assembly
    /// or if validation checks fail.
    ///
    /// # Thread Safety
    ///
    /// This method is thread-safe and can be called concurrently from multiple threads.
    pub fn from_mem_with_validation(
        data: Vec<u8>,
        validation_config: ValidationConfig,
    ) -> Result<Self> {
        debug!("Loading assembly from memory buffer ({} bytes)", data.len());
        let assembly_view = CilAssemblyView::from_mem(data)?;
        let lenient = validation_config.lenient;
        let object_data = CilObjectData::from_assembly_view(&assembly_view, None, lenient)?;

        let object = CilObject {
            assembly_view,
            data: object_data,
        };

        object.validate(validation_config)?;
        debug!(
            "Assembly loaded: {} types, {} methods",
            object.types().len(),
            object.methods().len()
        );
        Ok(object)
    }

    /// Creates a CilObject from a dotscope::file::File.
    ///
    /// This allows you to inspect the PE file before parsing .NET metadata,
    /// or to reuse an existing File instance.
    ///
    /// # Arguments
    /// * `file` - A File instance containing a .NET assembly
    ///
    /// # Errors
    /// Returns an error if:
    /// - The File doesn't contain a CLR runtime header
    /// - The .NET metadata is corrupted or invalid
    ///
    /// # Examples
    ///
    /// ```rust,no_run
    /// use dotscope::{File, CilObject};
    /// use std::path::Path;
    ///
    /// let file = File::from_path(Path::new("assembly.dll"))?;
    /// if file.is_clr() {
    ///     let cil_obj = CilObject::from_dotscope_file(file)?;
    ///     println!("Loaded {} methods", cil_obj.methods().len());
    /// }
    /// # Ok::<(), dotscope::Error>(())
    /// ```
    pub fn from_dotscope_file(file: File) -> Result<Self> {
        Self::from_dotscope_file_with_validation(file, ValidationConfig::production())
    }

    /// Creates a CilObject from a dotscope::file::File with validation.
    ///
    /// # Arguments
    /// * `file` - A File instance containing a .NET assembly
    /// * `validation_config` - Configuration specifying which validation checks to perform
    ///
    /// # Errors
    /// Returns an error if:
    /// - The File doesn't contain a CLR runtime header
    /// - The .NET metadata is corrupted or invalid
    /// - Validation checks fail
    ///
    /// # Examples
    ///
    /// ```rust,no_run
    /// use dotscope::{File, CilObject, ValidationConfig};
    /// use std::path::Path;
    ///
    /// let file = File::from_path(Path::new("assembly.dll"))?;
    /// let cil_obj = CilObject::from_dotscope_file_with_validation(
    ///     file,
    ///     ValidationConfig::production()
    /// )?;
    /// # Ok::<(), dotscope::Error>(())
    /// ```
    pub fn from_dotscope_file_with_validation(
        file: File,
        validation_config: ValidationConfig,
    ) -> Result<Self> {
        // Validate CLR header presence
        if !file.is_clr() {
            return Err(Error::NotSupported);
        }

        // Extract data and use existing from_mem path
        let data = file.into_data();
        Self::from_mem_with_validation(data, validation_config)
    }

    /// Creates a CilObject from an opened std::fs::File.
    ///
    /// The file is memory-mapped for efficient access.
    ///
    /// # Arguments
    /// * `file` - An opened file handle to a .NET assembly
    ///
    /// # Errors
    /// Returns an error if the file is not a valid .NET assembly.
    ///
    /// # Examples
    ///
    /// ```rust,no_run
    /// use dotscope::CilObject;
    /// use std::fs::File;
    ///
    /// let std_file = File::open("assembly.dll")?;
    /// let cil_obj = CilObject::from_std_file(std_file)?;
    /// # Ok::<(), Box<dyn std::error::Error>>(())
    /// ```
    pub fn from_std_file(file: std::fs::File) -> Result<Self> {
        Self::from_std_file_with_validation(file, ValidationConfig::production())
    }

    /// Creates a CilObject from an opened std::fs::File with validation.
    ///
    /// The file is memory-mapped for efficient access.
    ///
    /// # Arguments
    /// * `file` - An opened file handle to a .NET assembly
    /// * `validation_config` - Configuration specifying which validation checks to perform
    ///
    /// # Errors
    /// Returns an error if the file is not a valid .NET assembly or if validation checks fail.
    ///
    /// # Examples
    ///
    /// ```rust,no_run
    /// use dotscope::{CilObject, ValidationConfig};
    /// use std::fs::File;
    ///
    /// let std_file = File::open("assembly.dll")?;
    /// let cil_obj = CilObject::from_std_file_with_validation(
    ///     std_file,
    ///     ValidationConfig::production()
    /// )?;
    /// # Ok::<(), Box<dyn std::error::Error>>(())
    /// ```
    pub fn from_std_file_with_validation(
        file: std::fs::File,
        validation_config: ValidationConfig,
    ) -> Result<Self> {
        let pe_file = File::from_std_file(file)?;
        Self::from_dotscope_file_with_validation(pe_file, validation_config)
    }

    /// Creates a CilObject from any reader.
    ///
    /// # Arguments
    /// * `reader` - Any type implementing Read
    ///
    /// # Errors
    /// Returns an error if the data is not a valid .NET assembly.
    ///
    /// # Examples
    ///
    /// ```rust,no_run
    /// use dotscope::CilObject;
    /// use std::io::Cursor;
    ///
    /// let data = vec![/* PE bytes */];
    /// let cursor = Cursor::new(data);
    /// let cil_obj = CilObject::from_reader(cursor)?;
    /// # Ok::<(), dotscope::Error>(())
    /// ```
    pub fn from_reader<R: std::io::Read>(reader: R) -> Result<Self> {
        Self::from_reader_with_validation(reader, ValidationConfig::production())
    }

    /// Creates a CilObject from any reader with validation.
    ///
    /// # Arguments
    /// * `reader` - Any type implementing Read
    /// * `validation_config` - Configuration specifying which validation checks to perform
    ///
    /// # Errors
    /// Returns an error if the data is not a valid .NET assembly or if validation checks fail.
    ///
    /// # Examples
    ///
    /// ```rust,no_run
    /// use dotscope::{CilObject, ValidationConfig};
    /// use std::io::Cursor;
    ///
    /// let data = vec![/* PE bytes */];
    /// let cursor = Cursor::new(data);
    /// let cil_obj = CilObject::from_reader_with_validation(
    ///     cursor,
    ///     ValidationConfig::production()
    /// )?;
    /// # Ok::<(), dotscope::Error>(())
    /// ```
    pub fn from_reader_with_validation<R: std::io::Read>(
        reader: R,
        validation_config: ValidationConfig,
    ) -> Result<Self> {
        let pe_file = File::from_reader(reader)?;
        Self::from_dotscope_file_with_validation(pe_file, validation_config)
    }

    /// Creates a new `CilObject` from an existing `CilAssemblyView`.
    ///
    /// This method is designed for the CilProject workflow where CilAssemblyView instances
    /// are used for lightweight dependency discovery before being converted to full CilObjects.
    /// It bypasses file I/O since the CilAssemblyView already contains the parsed metadata.
    ///
    /// # Arguments
    ///
    /// * `assembly_view` - Pre-loaded CilAssemblyView with parsed metadata
    ///
    /// # Returns
    ///
    /// Returns a fully parsed `CilObject` or an error if:
    /// - Metadata processing fails during CilObjectData creation
    /// - Memory allocation fails during processing
    /// - Cross-references cannot be resolved
    ///
    /// # Usage Examples
    ///
    /// ```rust,no_run
    /// use dotscope::{CilObject, CilAssemblyView};
    /// use std::path::Path;
    ///
    /// // Load assembly view for dependency discovery
    /// let view = CilAssemblyView::from_path(Path::new("assembly.dll"))?;
    ///
    /// // Convert to full CilObject (single assembly mode)
    /// let assembly = CilObject::from_view(view)?;
    ///
    /// # Ok::<(), dotscope::Error>(())
    /// ```
    ///
    /// # Integration with CilProject
    ///
    /// For multi-assembly projects with circular dependencies, use `from_project` instead
    /// which provides proper barrier synchronization for parallel loading.
    ///
    /// # Thread Safety
    ///
    /// This method is thread-safe and can be called concurrently from multiple threads.
    ///
    /// # Errors
    ///
    /// Returns an error if the assembly cannot be processed or validated.
    pub fn from_view(assembly_view: CilAssemblyView) -> Result<Self> {
        Self::from_view_with_validation(assembly_view, ValidationConfig::production())
    }

    /// Creates a new `CilObject` from an existing `CilAssemblyView` with custom validation configuration.
    ///
    /// This method allows you to control which validation checks are performed during processing.
    /// Use this when you need to balance security requirements vs. loading speed.
    ///
    /// For multi-assembly projects with cross-references, use `from_project` instead which
    /// provides proper registry coordination.
    ///
    /// # Arguments
    ///
    /// * `assembly_view` - Pre-loaded CilAssemblyView with parsed metadata
    /// * `validation_config` - Configuration specifying which validation checks to perform
    ///
    /// # Returns
    ///
    /// Returns a fully parsed `CilObject` or an error if validation checks fail.
    ///
    /// # Errors
    ///
    /// Returns an error if the assembly cannot be processed or if validation checks fail.
    ///
    /// # Thread Safety
    ///
    /// This method is thread-safe and can be called concurrently from multiple threads.
    pub fn from_view_with_validation(
        assembly_view: CilAssemblyView,
        validation_config: ValidationConfig,
    ) -> Result<Self> {
        let lenient = validation_config.lenient;
        let object_data = CilObjectData::from_assembly_view(&assembly_view, None, lenient)?;

        let object = CilObject {
            assembly_view,
            data: object_data,
        };

        object.validate(validation_config)?;
        Ok(object)
    }

    /// Creates a new `CilObject` from an existing `CilAssemblyView` with project coordination.
    ///
    /// This method is designed for multi-assembly project loading where circular dependencies
    /// require barrier synchronization. The `ProjectContext` coordinates the parallel loading
    /// of multiple assemblies, ensuring proper TypeRegistry linking at the right stages.
    ///
    /// # Loading Pipeline
    ///
    /// The loading process is split into two phases to handle cross-assembly dependencies:
    ///
    /// 1. **Loading Phase**: All metadata loaders execute with barrier synchronization
    ///    - Stage 1-4 barriers ensure proper ordering of cross-assembly operations
    ///    - All assemblies must complete loading before any proceeds to validation
    ///
    /// 2. **Validation Phase**: After stage 4 barrier, validation runs on fully loaded data
    ///    - Nested type relationships are fully populated across all assemblies
    ///    - Cross-assembly type references can be safely traversed
    ///
    /// # Arguments
    ///
    /// * `assembly_view` - Pre-loaded CilAssemblyView with parsed metadata
    /// * `project_context` - Coordination context for multi-assembly parallel loading
    /// * `validation_config` - Configuration specifying which validation checks to perform
    ///
    /// # Returns
    ///
    /// Returns a fully parsed `CilObject` or an error if loading or validation fails.
    ///
    /// # Thread Safety
    ///
    /// This method is thread-safe and designed to be called concurrently from multiple threads
    /// with the same `ProjectContext`. The `ProjectContext` handles barrier synchronization.
    pub(crate) fn from_project(
        assembly_view: CilAssemblyView,
        project_context: &ProjectContext,
        validation_config: ValidationConfig,
    ) -> Result<Self> {
        // Phase 1: Load all metadata with barrier synchronization.
        // The stage 4 barrier inside from_assembly_view ensures all assemblies complete
        // their metadata loaders before any assembly proceeds past this point.
        let lenient = validation_config.lenient;
        let object_data =
            CilObjectData::from_assembly_view(&assembly_view, Some(project_context), lenient)?;

        let object = CilObject {
            assembly_view,
            data: object_data,
        };

        // Phase 2: Validate after all assemblies have completed loading.
        // This ensures cross-assembly nested type references are fully populated
        // before validation attempts to traverse them.
        object.validate(validation_config)?;
        Ok(object)
    }

    /// Returns the COR20 header containing .NET-specific PE information.
    ///
    /// The COR20 header (also known as CLI header) contains essential information
    /// about the .NET assembly including metadata directory location, entry point,
    /// and runtime flags. This header is always present in valid .NET assemblies.
    ///
    /// # Returns
    ///
    /// Reference to the parsed [`crate::metadata::cor20header::Cor20Header`] structure containing:
    /// - Metadata directory RVA and size
    /// - Entry point token (for executables)
    /// - Runtime flags (`IL_ONLY`, `32BIT_REQUIRED`, etc.)
    /// - Resources and strong name signature locations
    ///
    /// # Usage Examples
    ///
    /// ```rust,no_run
    /// use dotscope::CilObject;
    ///
    /// let assembly = CilObject::from_path("tests/samples/mono_4.8/mscorlib.dll")?;
    /// let header = assembly.cor20header();
    ///
    /// println!("Metadata RVA: 0x{:X}", header.meta_data_rva);
    /// println!("Runtime flags: {:?}", header.flags);
    /// # Ok::<(), dotscope::Error>(())
    /// ```
    pub fn cor20header(&self) -> &Cor20Header {
        self.assembly_view.cor20header()
    }

    /// Returns the metadata root header containing stream directory information.
    ///
    /// The metadata root is the entry point to the .NET metadata system, containing
    /// the version signature, stream count, and directory of all metadata streams
    /// (#~, #Strings, #US, #GUID, #Blob). This structure is always present and
    /// provides the foundation for accessing all assembly metadata.
    ///
    /// # Returns
    ///
    /// Reference to the parsed [`crate::metadata::root::Root`] structure containing:
    /// - Metadata format version and signature  
    /// - Stream directory with names, offsets, and sizes
    /// - Framework version string
    ///
    /// # Usage Examples
    ///
    /// ```rust,no_run
    /// use dotscope::CilObject;
    ///
    /// let assembly = CilObject::from_path("tests/samples/mono_4.8/mscorlib.dll")?;
    /// let root = assembly.metadata_root();
    ///
    /// println!("Metadata version: {}", root.version);
    /// println!("Number of streams: {}", root.stream_headers.len());
    /// for stream in &root.stream_headers {
    ///     println!("Stream: {} at offset 0x{:X}", stream.name, stream.offset);
    /// }
    /// # Ok::<(), dotscope::Error>(())
    /// ```
    pub fn metadata_root(&self) -> &Root {
        self.assembly_view.metadata_root()
    }

    /// Returns the metadata tables header from the #~ or #- stream.
    ///
    /// The tables header contains all metadata tables defined by ECMA-335,
    /// including Type definitions, Method definitions, Field definitions,
    /// Assembly references, and many others. This is the core of .NET metadata
    /// and provides structured access to all assembly information.
    ///
    /// # Returns
    ///
    /// - `Some(&`[`crate::metadata::streams::TablesHeader`]`)` if the #~ stream is present (compressed metadata)
    /// - `None` if no tables stream is found (invalid or malformed assembly)
    ///
    /// The [`crate::metadata::streams::TablesHeader`] provides access to:
    /// - All metadata table row counts and data
    /// - String, GUID, and Blob heap indices
    /// - Schema version and heap size information
    ///
    /// # Examples
    ///
    /// ```rust
    /// use dotscope::{CilObject, metadata::tables::{TypeDefRaw, TableId}};
    ///
    /// let assembly = CilObject::from_path("tests/samples/mono_4.8/mscorlib.dll")?;
    ///
    /// if let Some(tables) = assembly.tables() {
    ///     println!("Schema version: {}.{}", tables.major_version, tables.minor_version);
    ///
    ///     // Access individual tables
    ///     if let Some(typedef_table) = &tables.table::<TypeDefRaw>() {
    ///         println!("Number of types: {}", typedef_table.row_count);
    ///     }
    /// }
    /// # Ok::<(), dotscope::Error>(())
    /// ```
    pub fn tables(&self) -> Option<&TablesHeader<'_>> {
        self.assembly_view.tables()
    }

    /// Returns the strings heap from the #Strings stream.
    ///
    /// The strings heap contains null-terminated UTF-8 strings used throughout
    /// the metadata tables for names of types, members, parameters, and other
    /// identifiers. String references in tables are indices into this heap.
    ///
    /// # Returns
    ///
    /// - `Some(&`[`crate::metadata::streams::Strings`]`)` if the #Strings stream is present
    /// - `None` if the stream is missing (malformed assembly)
    ///
    /// # Examples
    ///
    /// ```rust
    /// use dotscope::CilObject;
    ///
    /// let assembly = CilObject::from_path("tests/samples/mono_4.8/mscorlib.dll")?;
    ///
    /// if let Some(strings) = assembly.strings() {
    ///     // Look up string by index (from metadata table)
    ///     if let Ok(name) = strings.get(0x123) {
    ///         println!("String at index 0x123: {}", name);
    ///     }
    /// }
    /// # Ok::<(), dotscope::Error>(())
    /// ```
    pub fn strings(&self) -> Option<&Strings<'_>> {
        self.assembly_view.strings()
    }

    /// Returns the user strings heap from the #US stream.
    ///
    /// The user strings heap contains length-prefixed Unicode strings that appear
    /// as string literals in CIL code (e.g., from C# string literals). These are
    /// accessed via the `ldstr` instruction and are distinct from metadata strings.
    ///
    /// # Returns
    ///
    /// - `Some(&`[`crate::metadata::streams::UserStrings`]`)` if the #US stream is present
    /// - `None` if the stream is missing (assembly has no string literals)
    ///
    /// # Examples
    ///
    /// ```rust
    /// use dotscope::CilObject;
    ///
    /// let assembly = CilObject::from_path("tests/samples/mono_4.8/mscorlib.dll")?;
    ///
    /// if let Some(user_strings) = assembly.userstrings() {
    ///     // Look up user string by token (from ldstr instruction)
    ///     if let Ok(literal) = user_strings.get(0x70000001) {
    ///         println!("String literal: {}", literal.to_string().unwrap());
    ///     }
    /// }
    /// # Ok::<(), dotscope::Error>(())
    /// ```
    pub fn userstrings(&self) -> Option<&UserStrings<'_>> {
        self.assembly_view.userstrings()
    }

    /// Returns the GUID heap from the #GUID stream.
    ///
    /// The GUID heap contains 16-byte GUIDs referenced by metadata tables,
    /// typically used for type library IDs, interface IDs, and other unique
    /// identifiers in COM interop scenarios.
    ///
    /// # Returns
    ///
    /// - `Some(&`[`crate::metadata::streams::Guid`]`)` if the #GUID stream is present
    /// - `None` if the stream is missing (assembly has no GUID references)
    ///
    /// # Examples
    ///
    /// ```rust
    /// use dotscope::CilObject;
    ///
    /// let assembly = CilObject::from_path("tests/samples/mono_4.8/mscorlib.dll")?;
    ///
    /// if let Some(guids) = assembly.guids() {
    ///     // Look up GUID by index (from metadata table)
    ///     if let Ok(guid) = guids.get(1) {
    ///         println!("GUID: {}", guid);
    ///     }
    /// }
    /// # Ok::<(), dotscope::Error>(())
    /// ```
    pub fn guids(&self) -> Option<&Guid<'_>> {
        self.assembly_view.guids()
    }

    /// Returns the blob heap from the #Blob stream.
    ///
    /// The blob heap contains variable-length binary data referenced by metadata
    /// tables, including type signatures, method signatures, field signatures,
    /// custom attribute values, and marshalling information.
    ///
    /// # Returns
    ///
    /// - `Some(&`[`crate::metadata::streams::Blob`]`)` if the #Blob stream is present
    /// - `None` if the stream is missing (malformed assembly)
    ///
    /// # Examples
    ///
    /// ```rust
    /// use dotscope::CilObject;
    ///
    /// let assembly = CilObject::from_path("tests/samples/mono_4.8/mscorlib.dll")?;
    ///
    /// if let Some(blob) = assembly.blob() {
    ///     // Look up blob by index (from metadata table)
    ///     if let Ok(signature) = blob.get(0x456) {
    ///         println!("Signature bytes: {:02X?}", signature);
    ///     }
    /// }
    /// # Ok::<(), dotscope::Error>(())
    /// ```
    pub fn blob(&self) -> Option<&Blob<'_>> {
        self.assembly_view.blobs()
    }

    /// Returns the diagnostics collected during loading.
    ///
    /// Diagnostics include warnings about structural issues, parsing failures,
    /// and other anomalies encountered during loading. These don't necessarily
    /// prevent loading but may indicate obfuscation or malformed metadata.
    ///
    /// # Returns
    ///
    /// Reference to the shared [`crate::metadata::diagnostics::Diagnostics`] container.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use dotscope::CilObject;
    ///
    /// let assembly = CilObject::from_path("tests/samples/mono_4.8/mscorlib.dll")?;
    ///
    /// if assembly.diagnostics().has_any() {
    ///     println!("Loading issues found:");
    ///     for diag in assembly.diagnostics().iter() {
    ///         println!("  {}", diag);
    ///     }
    /// }
    /// # Ok::<(), dotscope::Error>(())
    /// ```
    #[must_use]
    pub fn diagnostics(&self) -> &Arc<Diagnostics> {
        self.assembly_view.diagnostics()
    }

    /// Returns all assembly references used by this assembly.
    ///
    /// Assembly references represent external .NET assemblies that this assembly
    /// depends on, including version information, public key tokens, and culture
    /// settings. These correspond to entries in the `AssemblyRef` metadata table.
    ///
    /// # Returns
    ///
    /// Reference to the `AssemblyRefMap` containing all external assembly dependencies.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use dotscope::CilObject;
    ///
    /// let assembly = CilObject::from_path("tests/samples/mono_4.8/mscorlib.dll")?;
    /// let refs = assembly.refs_assembly();
    ///
    /// for entry in refs.iter() {
    ///     let (token, assembly_ref) = (entry.key(), entry.value());
    ///     println!("Dependency: {} v{}.{}.{}.{}",
    ///         assembly_ref.name,
    ///         assembly_ref.major_version,
    ///         assembly_ref.minor_version,
    ///         assembly_ref.build_number,
    ///         assembly_ref.revision_number
    ///     );
    /// }
    /// # Ok::<(), dotscope::Error>(())
    /// ```
    pub fn refs_assembly(&self) -> &AssemblyRefMap {
        &self.data.refs_assembly
    }

    /// Returns all module references used by this assembly.
    ///
    /// Module references represent external unmanaged modules (native DLLs)
    /// that this assembly imports functions from via P/Invoke declarations.
    /// These correspond to entries in the `ModuleRef` metadata table.
    ///
    /// # Returns
    ///
    /// Reference to the `ModuleRefMap` containing all external module dependencies.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use dotscope::CilObject;
    ///
    /// let assembly = CilObject::from_path("tests/samples/mono_4.8/mscorlib.dll")?;
    /// let refs = assembly.refs_module();
    ///
    /// for entry in refs.iter() {
    ///     let (token, module_ref) = (entry.key(), entry.value());
    ///     println!("Native module: {}", module_ref.name);
    /// }
    /// # Ok::<(), dotscope::Error>(())
    /// ```
    pub fn refs_module(&self) -> &ModuleRefMap {
        &self.data.refs_module
    }

    /// Returns all member references used by this assembly.
    ///
    /// Member references represent external type members (methods, fields, properties)
    /// from other assemblies that are referenced by this assembly's code.
    /// These correspond to entries in the `MemberRef` metadata table.
    ///
    /// # Returns
    ///
    /// Reference to the `MemberRefMap` containing all external member references.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use dotscope::CilObject;
    ///
    /// let assembly = CilObject::from_path("tests/samples/mono_4.8/mscorlib.dll")?;
    /// let refs = assembly.refs_members();
    ///
    /// for entry in refs.iter() {
    ///     let (token, member_ref) = (entry.key(), entry.value());
    ///     println!("External member: {}", member_ref.name);
    /// }
    /// # Ok::<(), dotscope::Error>(())
    /// ```
    pub fn refs_members(&self) -> &MemberRefMap {
        &self.data.refs_member
    }

    /// Returns all security declarations and permission sets defined in this assembly.
    ///
    /// Security declarations include Code Access Security (CAS) permissions, security
    /// transparency attributes, and other declarative security constraints. Each entry
    /// maps a token to its corresponding security declaration containing permission sets,
    /// security actions, and validation rules.
    ///
    /// # Returns
    ///
    /// A reference to the [`crate::metadata::tables::DeclSecurityMap`] containing all security declarations.
    /// The map uses tokens as keys and [`crate::metadata::tables::DeclSecurityRc`] (reference-counted security
    /// declarations) as values for efficient memory management.
    ///
    /// # Usage
    ///
    /// ```rust,no_run
    /// # use dotscope::CilObject;
    /// # fn security_example() -> dotscope::Result<()> {
    /// let assembly = CilObject::from_path("example.dll")?;
    /// let security_decls = assembly.security_declarations();
    ///
    /// for entry in security_decls.iter() {
    ///     let (token, decl) = (entry.key(), entry.value());
    ///     println!("Security declaration for token {}: {:?}",
    ///              token.value(), decl.action);
    /// }
    /// # Ok(())
    /// # }
    /// ```
    pub fn security_declarations(&self) -> &DeclSecurityMap {
        &self.data.decl_security
    }

    /// Returns the primary module information for this assembly.
    ///
    /// The module represents the main file of the assembly, containing the
    /// module's name, MVID (Module Version Identifier), and generation ID.
    /// Multi-file assemblies can have additional modules, but there's always
    /// one primary module.
    ///
    /// # Returns
    ///
    /// - `Some(&ModuleRc)` if module information is present
    /// - `None` if no module table entry exists (malformed assembly)
    ///
    /// # Examples
    ///
    /// ```rust
    /// use dotscope::CilObject;
    ///
    /// let assembly = CilObject::from_path("tests/samples/mono_4.8/mscorlib.dll")?;
    ///
    /// if let Some(module) = assembly.module() {
    ///     println!("Module name: {}", module.name);
    ///     println!("Module GUID: {}", module.mvid);
    /// }
    /// # Ok::<(), dotscope::Error>(())
    /// ```
    pub fn module(&self) -> Option<&ModuleRc> {
        self.data.module.get()
    }

    /// Returns the assembly metadata for this .NET assembly.
    ///
    /// The assembly metadata contains the assembly's identity including name,
    /// version, culture, public key information, and security attributes.
    /// This corresponds to the Assembly metadata table entry.
    ///
    /// # Returns
    ///
    /// - `Some(&AssemblyRc)` if assembly metadata is present
    /// - `None` if this is a module-only file (no Assembly table entry)
    ///
    /// # Examples
    ///
    /// ```rust
    /// use dotscope::CilObject;
    ///
    /// let assembly = CilObject::from_path("tests/samples/mono_4.8/mscorlib.dll")?;
    ///
    /// if let Some(assembly_info) = assembly.assembly() {
    ///     println!("Assembly: {}", assembly_info.name);
    ///     println!("Version: {}.{}.{}.{}",
    ///         assembly_info.major_version,
    ///         assembly_info.minor_version,
    ///         assembly_info.build_number,
    ///         assembly_info.revision_number
    ///     );
    /// }
    /// # Ok::<(), dotscope::Error>(())
    /// ```
    pub fn assembly(&self) -> Option<&AssemblyRc> {
        self.data.assembly.get()
    }

    /// Returns assembly OS information if present.
    ///
    /// The `AssemblyOS` table contains operating system identification information
    /// for the assembly. This table is rarely used in modern .NET assemblies
    /// and is primarily for legacy compatibility.
    ///
    /// # Returns
    ///
    /// - `Some(&AssemblyOsRc)` if OS information is present
    /// - `None` if no `AssemblyOS` table entry exists (typical for most assemblies)
    pub fn assembly_os(&self) -> Option<&AssemblyOsRc> {
        self.data.assembly_os.get()
    }

    /// Returns assembly processor information if present.
    ///
    /// The `AssemblyProcessor` table contains processor architecture identification
    /// information for the assembly. This table is rarely used in modern .NET
    /// assemblies and is primarily for legacy compatibility.
    ///
    /// # Returns
    ///
    /// - `Some(&AssemblyProcessorRc)` if processor information is present  
    /// - `None` if no `AssemblyProcessor` table entry exists (typical for most assemblies)
    pub fn assembly_processor(&self) -> Option<&AssemblyProcessorRc> {
        self.data.assembly_processor.get()
    }

    /// Returns the complete assembly identity for this loaded assembly.
    ///
    /// The assembly identity provides comprehensive identification information including
    /// name, version, culture, strong name, and processor architecture. This serves as
    /// the primary identifier for assemblies in multi-assembly analysis scenarios and
    /// cross-assembly resolution.
    ///
    /// # Returns
    ///
    /// - `Some(AssemblyIdentity)` if assembly metadata is present
    /// - `None` if no `Assembly` table entry exists (rare, but possible in malformed assemblies)
    ///
    /// # Examples
    ///
    /// ```rust,no_run
    /// use dotscope::CilObject;
    /// use std::path::Path;
    ///
    /// let assembly = CilObject::from_path(Path::new("example.dll"))?;
    ///
    /// if let Some(identity) = assembly.identity() {
    ///     println!("Assembly: {}", identity.display_name());
    ///     println!("Version: {}", identity.version);
    ///     println!("Strong named: {}", identity.is_strong_named());
    ///     println!("Culture neutral: {}", identity.is_culture_neutral());
    /// }
    /// # Ok::<(), dotscope::Error>(())
    /// ```
    ///
    /// # Multi-Assembly Usage
    ///
    /// ```rust,no_run
    /// use dotscope::CilObject;
    /// use std::collections::HashMap;
    /// use std::path::PathBuf;
    ///
    /// let mut assemblies = HashMap::new();
    /// let assembly_paths = vec![
    ///     PathBuf::from("tests/samples/mono_4.8/mscorlib.dll"),
    ///     PathBuf::from("tests/samples/mono_4.8/System.dll"),
    /// ];
    ///
    /// for path in assembly_paths {
    ///     let assembly = CilObject::from_path(&path)?;
    ///     if let Some(identity) = assembly.identity() {
    ///         assemblies.insert(identity, assembly);
    ///     }
    /// }
    /// # Ok::<(), dotscope::Error>(())
    /// ```
    pub fn identity(&self) -> Option<AssemblyIdentity> {
        self.assembly()
            .map(|asm| AssemblyIdentity::from_assembly(asm))
    }

    /// Checks if this is a netmodule (module without assembly manifest).
    ///
    /// A netmodule is a .NET module that lacks its own assembly identity.
    /// It contains types and code but is designed to be linked into a
    /// multi-file assembly. Netmodules have a Module table but no Assembly table.
    ///
    /// # Returns
    ///
    /// * `true` - This is a netmodule (no Assembly table)
    /// * `false` - This is a full assembly with its own identity
    ///
    /// # Examples
    ///
    /// ```rust,no_run
    /// use dotscope::CilObject;
    ///
    /// let module = CilObject::from_path("helper.netmodule")?;
    /// if module.is_netmodule() {
    ///     println!("This is a netmodule - part of a multi-file assembly");
    /// }
    /// # Ok::<(), dotscope::Error>(())
    /// ```
    #[must_use]
    pub fn is_netmodule(&self) -> bool {
        // A netmodule has a module but no assembly identity
        self.module().is_some() && self.assembly().is_none()
    }

    /// Returns the imports container with all P/Invoke and COM import information.
    ///
    /// The imports container provides access to all external function imports
    /// including P/Invoke declarations, COM method imports, and related
    /// marshalling information. This data comes from `ImplMap` and related tables.
    ///
    /// # Returns
    ///
    /// Reference to the `Imports` container with all import declarations.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use dotscope::CilObject;
    ///
    /// let assembly = CilObject::from_path("tests/samples/mono_4.8/mscorlib.dll")?;
    /// let imports = assembly.imports();
    ///
    /// for entry in imports.cil().iter() {
    ///     let (token, import) = (entry.key(), entry.value());
    ///     println!("Import: {}.{} from {:?}", import.namespace, import.name, import.source_id);
    /// }
    /// # Ok::<(), dotscope::Error>(())
    /// ```
    pub fn imports(&self) -> &UnifiedImportContainer {
        &self.data.import_container
    }

    /// Returns the exports container with all exported function information.
    ///
    /// The exports container provides access to all functions that this assembly
    /// exports for use by other assemblies or native code. This includes both
    /// managed exports and any native exports in mixed-mode assemblies.
    ///
    /// # Returns
    ///
    /// Reference to the `UnifiedExportContainer` with both CIL and native export declarations.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use dotscope::CilObject;
    ///
    /// let assembly = CilObject::from_path("tests/samples/mono_4.8/mscorlib.dll")?;
    /// let exports = assembly.exports();
    ///
    /// // Access CIL exports (existing functionality)
    /// for entry in exports.cil().iter() {
    ///     let (token, export) = (entry.key(), entry.value());
    ///     println!("CIL Export: {} at offset 0x{:X} - Token 0x{:X}", export.name, export.offset, token.value());
    /// }
    ///
    /// // Access native function exports
    /// let native_functions = exports.get_native_function_names();
    /// for function_name in native_functions {
    ///     println!("Native Export: {}", function_name);
    /// }
    /// # Ok::<(), dotscope::Error>(())
    /// ```
    pub fn exports(&self) -> &UnifiedExportContainer {
        &self.data.export_container
    }

    /// Returns the methods container with all method definitions and metadata.
    ///
    /// The methods container provides access to all methods defined in this assembly,
    /// including their signatures, IL code, exception handlers, and related metadata.
    /// This integrates data from `MethodDef`, `Param`, and other method-related tables.
    ///
    /// # Returns
    ///
    /// Reference to the `MethodMap` containing all method definitions.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use dotscope::CilObject;
    ///
    /// let assembly = CilObject::from_path("tests/samples/mono_4.8/mscorlib.dll")?;
    /// let methods = assembly.methods();
    ///
    /// for entry in methods.iter() {
    ///     let (token, method) = (entry.key(), entry.value());
    ///     println!("Method: {} (Token: 0x{:08X})", method.name, token.value());
    ///     if let Some(rva) = method.rva {
    ///         println!("  RVA: 0x{:X}", rva);
    ///     }
    /// }
    /// # Ok::<(), dotscope::Error>(())
    /// ```
    pub fn methods(&self) -> &MethodMap {
        &self.data.methods
    }

    /// Returns the method specifications container with all generic method instantiations.
    ///
    /// The method specifications container provides access to all generic method instantiations
    /// defined in this assembly. `MethodSpec` entries represent calls to generic methods with
    /// specific type arguments, enabling IL instructions to reference these instantiations.
    ///
    /// # Returns
    ///
    /// Reference to the `MethodSpecMap` containing all method specifications.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use dotscope::CilObject;
    ///
    /// let assembly = CilObject::from_path("tests/samples/mono_4.8/mscorlib.dll")?;
    /// let method_specs = assembly.method_specs();
    ///
    /// for entry in method_specs.iter() {
    ///     let (token, method_spec) = (entry.key(), entry.value());
    ///     println!("MethodSpec: Token 0x{:08X}", token.value());
    ///     println!("  Generic args count: {}", method_spec.generic_args.count());
    /// }
    /// # Ok::<(), dotscope::Error>(())
    /// ```
    pub fn method_specs(&self) -> &MethodSpecMap {
        &self.data.method_specs
    }

    /// Returns the method definition for the given token, if it exists.
    ///
    /// This is a convenience accessor that looks up a method by its metadata token
    /// and returns a cloned reference-counted pointer to the [`Method`] object. It
    /// eliminates the need to call [`methods()`](Self::methods), unwrap the `Entry`
    /// guard, and clone the value manually.
    ///
    /// # Arguments
    ///
    /// * `token` - The metadata token (table 0x06) identifying the method definition.
    ///
    /// # Returns
    ///
    /// A reference-counted [`Method`] if a method with the given token exists, `None` otherwise.
    ///
    /// # Examples
    ///
    /// ```rust,no_run
    /// use dotscope::CilObject;
    /// use dotscope::metadata::token::Token;
    ///
    /// let assembly = CilObject::from_path("tests/samples/WindowsBase.dll")?;
    /// let token = Token::new(0x06000001);
    ///
    /// if let Some(method) = assembly.method(&token) {
    ///     println!("Method: {} (static: {})", method.name, method.is_static());
    /// }
    /// # Ok::<(), dotscope::Error>(())
    /// ```
    pub fn method(&self, token: &Token) -> Option<MethodRc> {
        self.data.methods.get(token).map(|e| e.value().clone())
    }

    /// Returns the member reference for the given token, if it exists.
    ///
    /// This is a convenience accessor that looks up a member reference (external method
    /// or field reference) by its metadata token and returns a cloned reference-counted
    /// pointer to the [`MemberRef`](crate::metadata::tables::MemberRef) object.
    ///
    /// # Arguments
    ///
    /// * `token` - The metadata token (table 0x0A) identifying the member reference.
    ///
    /// # Returns
    ///
    /// A reference-counted [`MemberRef`](crate::metadata::tables::MemberRef) if a member
    /// reference with the given token exists, `None` otherwise.
    ///
    /// # Examples
    ///
    /// ```rust,no_run
    /// use dotscope::CilObject;
    /// use dotscope::metadata::token::Token;
    ///
    /// let assembly = CilObject::from_path("tests/samples/WindowsBase.dll")?;
    /// let token = Token::new(0x0A000001);
    ///
    /// if let Some(member_ref) = assembly.member_ref(&token) {
    ///     println!("Member: {} (declared by: {:?})", member_ref.name, member_ref.declaredby.token());
    /// }
    /// # Ok::<(), dotscope::Error>(())
    /// ```
    pub fn member_ref(&self, token: &Token) -> Option<MemberRefRc> {
        self.data.refs_member.get(token).map(|e| e.value().clone())
    }

    /// Returns the method specification for the given token, if it exists.
    ///
    /// A method specification represents a generic method instantiation with concrete
    /// type arguments. This is a convenience accessor that looks up a `MethodSpec` by
    /// its metadata token and returns a cloned reference-counted pointer.
    ///
    /// # Arguments
    ///
    /// * `token` - The metadata token (table 0x2B) identifying the method specification.
    ///
    /// # Returns
    ///
    /// A reference-counted [`MethodSpec`](crate::metadata::tables::MethodSpec) if a method
    /// specification with the given token exists, `None` otherwise.
    ///
    /// # Examples
    ///
    /// ```rust,no_run
    /// use dotscope::CilObject;
    /// use dotscope::metadata::token::Token;
    ///
    /// let assembly = CilObject::from_path("tests/samples/WindowsBase.dll")?;
    /// let token = Token::new(0x2B000001);
    ///
    /// if let Some(spec) = assembly.method_spec(&token) {
    ///     println!("MethodSpec: {:?} with {} generic args",
    ///              spec.method.token(), spec.generic_args.count());
    /// }
    /// # Ok::<(), dotscope::Error>(())
    /// ```
    pub fn method_spec(&self, token: &Token) -> Option<MethodSpecRc> {
        self.data.method_specs.get(token).map(|e| e.value().clone())
    }

    /// Resolves a method-like token to its simple method name.
    ///
    /// This method handles the three token types that can refer to a method:
    ///
    /// - **MethodDef** (table 0x06): Returns the method definition name.
    /// - **MemberRef** (table 0x0A): Returns the member reference name.
    /// - **MethodSpec** (table 0x2B): Follows the generic instantiation to the
    ///   underlying method and returns its name.
    ///
    /// This is useful for pattern matching on call targets where only the method
    /// name is needed (e.g., checking if a call targets `"get_IsAttached"` or
    /// `"Decompress"`), regardless of whether the call uses a direct definition,
    /// an external reference, or a generic instantiation.
    ///
    /// # Arguments
    ///
    /// * `token` - A metadata token from a call-like instruction operand.
    ///
    /// # Returns
    ///
    /// The method name as a `String` if the token refers to a known method, `None`
    /// if the token table is not one of the three supported types or if the entry
    /// does not exist.
    ///
    /// # Examples
    ///
    /// ```rust,no_run
    /// use dotscope::CilObject;
    /// use dotscope::metadata::token::Token;
    ///
    /// let assembly = CilObject::from_path("tests/samples/WindowsBase.dll")?;
    ///
    /// // Resolve a MethodDef token
    /// let token = Token::new(0x06000001);
    /// if let Some(name) = assembly.resolve_method_name(token) {
    ///     println!("Method name: {name}");
    /// }
    ///
    /// // Resolve a MemberRef token
    /// let token = Token::new(0x0A000001);
    /// if let Some(name) = assembly.resolve_method_name(token) {
    ///     println!("Member ref name: {name}");
    /// }
    /// # Ok::<(), dotscope::Error>(())
    /// ```
    pub fn resolve_method_name(&self, token: Token) -> Option<String> {
        match token.table() {
            0x06 => method_name_by_token(&self.data.methods, &token),
            0x0A => member_ref_name_by_token(&self.data.refs_member, &token),
            0x2B => method_spec_name_by_token(&self.data.method_specs, &token),
            _ => None,
        }
    }

    /// Returns the resources container with all embedded and linked resources.
    ///
    /// The resources container provides access to all resources associated with
    /// this assembly, including embedded resources, linked files, and resource
    /// metadata. This includes both .NET resources and Win32 resources.
    ///
    /// # Returns
    ///
    /// Reference to the `Resources` container with all resource information.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use dotscope::CilObject;
    ///
    /// let assembly = CilObject::from_path("tests/samples/mono_4.8/mscorlib.dll")?;
    /// let resources = assembly.resources();
    ///
    /// for entry in resources.iter() {
    ///     let (name, resource) = (entry.key(), entry.value());
    ///     println!("Resource: {} (Size: {}, Offset: 0x{:X})", name, resource.data_offset, resource.data_size);
    /// }
    /// # Ok::<(), dotscope::Error>(())
    /// ```
    pub fn resources(&self) -> &Resources {
        &self.data.resources
    }

    /// Returns the type registry containing all type definitions and references.
    ///
    /// The type registry provides centralized access to all types defined in and
    /// referenced by this assembly. This includes `TypeDef` entries (types defined
    /// in this assembly), `TypeRef` entries (types referenced from other assemblies),
    /// `TypeSpec` entries (instantiated generic types), and primitive types.
    ///
    /// # Returns
    ///
    /// Reference to the `TypeRegistry` containing all type information.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use dotscope::CilObject;
    ///
    /// let assembly = CilObject::from_path("tests/samples/mono_4.8/mscorlib.dll")?;
    /// let types = assembly.types();
    ///
    /// println!("Total types: {}", types.len());
    ///
    /// // Get all types
    /// for type_info in types.all_types() {
    ///     println!("Type: {}.{} (Token: 0x{:08X})",
    ///         type_info.namespace, type_info.name, type_info.token.value());
    /// }
    ///
    /// // Look up specific types
    /// let string_types = types.get_by_name("String");
    /// for string_type in string_types {
    ///     println!("Found String type in namespace: {}", string_type.namespace);
    /// }
    /// # Ok::<(), dotscope::Error>(())
    /// ```
    pub fn types(&self) -> Arc<TypeRegistry> {
        self.data.types.clone()
    }

    /// Returns a composable query over types in this assembly.
    ///
    /// # Examples
    ///
    /// ```rust,no_run
    /// use dotscope::CilObject;
    ///
    /// let assembly = CilObject::from_path("tests/samples/WindowsBase.dll")?;
    ///
    /// // Find all public, defined types
    /// let public_types = assembly.query_types()
    ///     .defined()
    ///     .public()
    ///     .find_all();
    /// # Ok::<(), dotscope::Error>(())
    /// ```
    pub fn query_types(&self) -> TypeQuery<'_> {
        TypeQuery::new(&self.data.types)
    }

    /// Returns a composable query over all methods in this assembly.
    ///
    /// # Examples
    ///
    /// ```rust,no_run
    /// use dotscope::CilObject;
    ///
    /// let assembly = CilObject::from_path("tests/samples/WindowsBase.dll")?;
    ///
    /// // Find all static constructors
    /// let cctors = assembly.query_methods()
    ///     .static_constructors()
    ///     .find_all();
    /// # Ok::<(), dotscope::Error>(())
    /// ```
    pub fn query_methods(&self) -> MethodQuery<'_> {
        MethodQuery::from_assembly(&self.data.methods)
    }

    /// Builds and returns the call graph for this assembly.
    ///
    /// The call graph represents the calling relationships between methods in the
    /// assembly, including direct calls, virtual dispatch, and interface calls.
    /// This is useful for understanding code structure, finding entry points,
    /// and performing inter-procedural analysis.
    ///
    /// Note: Building the call graph requires analyzing all methods in the assembly,
    /// which may be expensive for large assemblies. Consider caching the result if
    /// you need to access it multiple times.
    ///
    /// # Returns
    ///
    /// A [`CallGraph`] for this assembly, or an error if construction fails.
    ///
    /// # Errors
    ///
    /// Returns an error if call graph construction fails (e.g., due to corrupted
    /// method metadata).
    ///
    /// # Examples
    ///
    /// ```rust,no_run
    /// use dotscope::CilObject;
    ///
    /// let assembly = CilObject::from_path("tests/samples/mono_4.8/mscorlib.dll")?;
    /// let callgraph = assembly.callgraph()?;
    ///
    /// let stats = callgraph.stats();
    /// println!("Call graph: {} methods, {} edges", stats.method_count, stats.edge_count);
    ///
    /// // Export as DOT for visualization
    /// let dot = callgraph.to_dot(Some("MyAssembly"));
    /// std::fs::write("callgraph.dot", dot)?;
    /// # Ok::<(), Box<dyn std::error::Error>>(())
    /// ```
    pub fn callgraph(&self) -> Result<CallGraph> {
        CallGraph::build(self)
    }

    /// Returns the underlying file representation of this assembly.
    ///
    /// The file object provides access to the raw PE file data, headers, and
    /// file-level operations such as RVA-to-offset conversion, section access,
    /// and memory-mapped or buffered file I/O. This is useful for low-level
    /// analysis or when you need direct access to the PE file structure.
    ///
    /// # Returns
    ///
    /// Reference to the `Arc<File>` containing the PE file representation.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use dotscope::CilObject;
    ///
    /// let assembly = CilObject::from_path("tests/samples/mono_4.8/mscorlib.dll")?;
    /// let file = assembly.file();
    ///
    /// // Access file-level information
    /// println!("File size: {} bytes", file.data().len());
    ///
    /// // Access PE headers
    /// let dos_header = file.header_dos();
    /// let nt_headers = file.header();
    /// println!("Machine type: 0x{:X}", nt_headers.machine);
    ///
    /// // Convert RVA to file offset
    /// let Some((clr_rva, _)) = file.clr() else {
    ///     panic!("No CLR header found");
    /// };
    /// let offset = file.rva_to_offset(clr_rva)?;
    /// println!("CLR header at file offset: 0x{:X}", offset);
    /// # Ok::<(), dotscope::Error>(())
    /// ```
    pub fn file(&self) -> &Arc<File> {
        self.assembly_view.file()
    }

    /// Converts this `CilObject` into a [`CilAssembly`] for modification.
    ///
    /// This method efficiently transfers ownership of the internal assembly view
    /// to create a mutable assembly, avoiding unnecessary data copying. The resolved
    /// metadata (types, methods, etc.) is dropped since modifications work on the
    /// raw assembly view level.
    ///
    /// # Returns
    ///
    /// A [`CilAssembly`] ready for modification operations.
    ///
    /// # Usage Examples
    ///
    /// ```rust,no_run
    /// use dotscope::CilObject;
    ///
    /// let assembly = CilObject::from_path("input.dll")?;
    ///
    /// // Convert to mutable assembly for modifications
    /// let mut mutable = assembly.into_assembly();
    ///
    /// // Perform modifications
    /// mutable.string_add("NewString")?;
    ///
    /// // Write back and convert to CilObject
    /// let modified = mutable.into_cilobject()?;
    /// # Ok::<(), dotscope::Error>(())
    /// ```
    ///
    /// # Performance
    ///
    /// This operation is O(1) - it transfers ownership of the internal view
    /// without copying the underlying assembly data.
    #[must_use]
    pub fn into_assembly(self) -> CilAssembly {
        CilAssembly::new(self.assembly_view)
    }

    /// Validates the loaded assembly metadata using the specified configuration.
    ///
    /// This method runs comprehensive validation checks on the assembly metadata
    /// to ensure structural integrity, semantic correctness, and compliance with
    /// .NET metadata format requirements. This is separate from loading validation
    /// and can be used when you need to perform more comprehensive checks,
    /// additional validation after loading, or when you loaded with minimal
    /// validation initially.
    ///
    /// # Arguments
    ///
    /// * `config` - Validation configuration specifying which validations to perform
    ///
    /// # Returns
    ///
    /// Returns `Ok(())` if all validations pass, or an error describing
    /// any validation failures found.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use dotscope::{CilObject, ValidationConfig};
    /// use std::path::Path;
    ///
    /// # fn main() -> Result<(), Box<dyn std::error::Error>> {
    /// // Load assembly with minimal validation for speed
    /// let assembly = CilObject::from_path_with_validation(
    ///     Path::new("tests/samples/mono_4.8/mscorlib.dll"),
    ///     ValidationConfig::minimal()
    /// )?;
    ///
    /// // Later, perform comprehensive validation
    /// assembly.validate(ValidationConfig::comprehensive())?;
    /// # Ok(())
    /// # }
    /// ```
    ///
    /// # Errors
    ///
    /// Returns validation errors found during analysis, such as:
    /// - Circular type nesting
    /// - Field layout overlaps
    /// - Invalid generic constraints
    /// - Type system inconsistencies
    pub fn validate(&self, config: ValidationConfig) -> Result<()> {
        if config == ValidationConfig::disabled() {
            return Ok(());
        }

        let engine = ValidationEngine::new(&self.assembly_view, config)?;
        let result = engine.execute_two_stage_validation(&self.assembly_view, None, Some(self))?;

        result.into_result()
    }
}