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
//! PE file abstraction and .NET binary parsing.
//!
//! This module provides comprehensive support for parsing and analyzing Portable Executable (PE)
//! files containing .NET assemblies. It abstracts over different data sources (files, memory)
//! and provides ergonomic access to PE structures, .NET metadata, and binary data.
//!
//! # Architecture
//!
//! The module is built around several key components that work together to provide
//! comprehensive PE file analysis capabilities:
//!
//! - **File abstraction layer** - Unified interface for PE file access
//! - **Backend system** - Pluggable data sources (disk files, memory buffers)
//! - **PE format parsing** - Complete PE/COFF structure analysis
//! - **Address translation** - RVA to file offset conversion
//! - **Data directory access** - Direct access to PE data directories
//!
//! # Key Components
//!
//! ## Core Types
//! - [`crate::file::File`] - Main PE file abstraction with .NET-specific functionality
//! - [`crate::file::Backend`] - Trait for different data sources (disk files, memory buffers)
//!
//! ## Parsing Infrastructure  
//! - [`crate::file::parser::Parser`] - High-level parsing interface for metadata extraction
//! - [`crate::file::io`] - Low-level I/O utilities for reading PE structures
//!
//! ## Backend Implementations
//! - [`crate::file::physical::Physical`] - Memory-mapped file backend for disk access
//! - [`crate::file::memory::Memory`] - In-memory buffer backend for dynamic analysis
//!
//! # Data Sources
//!
//! The module supports multiple data sources through the [`crate::file::Backend`] trait:
//! - **Physical files** - Memory-mapped files for efficient disk access
//! - **Memory buffers** - In-memory PE data for dynamic analysis
//!
//! # PE Format Support
//!
//! Supports both PE32 and PE32+ formats with:
//! - DOS header and PE signature parsing
//! - COFF header and optional header extraction
//! - Section table parsing and virtual address resolution
//! - Data directory access (Import, Export, .NET metadata, etc.)
//! - RVA to file offset translation
//!
//! # Examples
//!
//! ## Loading from File
//!
//! ```rust,no_run
//! use dotscope::File;
//! use std::path::Path;
//!
//! // Load a .NET assembly from disk
//! let file = File::from_path(Path::new("tests/samples/WindowsBase.dll"))?;
//! println!("Loaded PE file with {} bytes", file.len());
//!
//! // Access PE headers
//! println!("Image base: 0x{:x}", file.imagebase());
//! println!("Number of sections: {}", file.sections().len());
//!
//! // Access .NET metadata location
//! let Some((clr_rva, clr_size)) = file.clr() else {
//!     panic!("No CLR header found");
//! };
//! println!("CLR header at RVA 0x{:x}, size: {} bytes", clr_rva, clr_size);
//! # Ok::<(), dotscope::Error>(())
//! ```
//!
//! ## Loading from Memory
//!
//! ```rust,no_run
//! use dotscope::File;
//! use std::fs;
//!
//! // Load assembly data into memory
//! let data = fs::read("tests/samples/WindowsBase.dll")?;
//! let file = File::from_mem(data)?;
//!
//! // Same API as file-based loading
//! println!("Assembly size: {} bytes", file.len());
//!
//! // Find specific sections
//! for section in file.sections() {
//!     let name = section.name.trim_end_matches('\0');
//!     if name == ".text" {
//!         println!("Code section at RVA 0x{:x}", section.virtual_address);
//!         break;
//!     }
//! }
//! # Ok::<(), dotscope::Error>(())
//! ```
//!
//! ## Address Translation
//!
//! ```rust,no_run
//! use dotscope::File;
//! use std::path::Path;
//!
//! let file = File::from_path(Path::new("tests/samples/WindowsBase.dll"))?;
//!
//! // Convert CLR header RVA to file offset
//! let Some((clr_rva, _)) = file.clr() else {
//!     panic!("No CLR header found");
//! };
//! let clr_offset = file.rva_to_offset(clr_rva)?;
//!
//! // Read CLR header data
//! let clr_data = file.data_slice(clr_offset, 72)?; // CLR header is 72 bytes
//! println!("CLR header starts with: {:02x?}", &clr_data[0..8]);
//! # Ok::<(), dotscope::Error>(())
//! ```
//!
//!
//! # Thread Safety
//!
//! All components are designed to be thread-safe and can be shared across threads
//! for concurrent analysis of the same PE file.
//!
//! # References
//!
//! - Microsoft PE/COFF Specification
//! - ECMA-335 6th Edition, Partition II - PE File Format

pub mod parser;
pub mod pe;

mod memory;
mod physical;

use std::path::Path;

use crate::{
    utils::align_to,
    Error::{self, Goblin, LayoutFailed, Other},
    Result,
};
use goblin::pe::PE;
use memory::Memory;
use pe::{constants::COR20_HEADER_SIZE, DataDirectory, DataDirectoryType, Pe};
use physical::Physical;

/// Backend trait for file data sources.
///
/// This trait abstracts over the source of PE data, allowing for both in-memory and on-disk
/// representations. All implementations must be thread-safe.
///
/// The trait provides a common interface for accessing PE file data regardless of whether
/// it's loaded from a file on disk or from a memory buffer. This enables flexible handling
/// of different data sources while maintaining performance.
pub trait Backend: Send + Sync {
    /// Returns a slice of the data at the given offset and length.
    ///
    /// This method provides bounds-checked access to the underlying data.
    /// It's used internally by the `File` struct to safely read portions
    /// of the PE file data.
    ///
    /// # Arguments
    ///
    /// * `offset` - The starting offset within the data.
    /// * `len` - The length of the slice in bytes.
    ///
    /// # Errors
    ///
    /// Returns an error if the requested range is out of bounds.
    fn data_slice(&self, offset: usize, len: usize) -> Result<&[u8]>;

    /// Returns the entire data buffer.
    ///
    /// This provides access to the complete PE file data as a single slice.
    /// For file-based backends, this typically maps the entire file into memory.
    /// For memory-based backends, this returns the underlying buffer.
    fn data(&self) -> &[u8];

    /// Returns the total length of the data buffer.
    ///
    /// This is equivalent to `self.data().len()` but may be more efficient
    /// for some backend implementations.
    fn len(&self) -> usize;

    /// Consumes the backend and returns the underlying data as an owned Vec<u8>.
    ///
    /// For memory-backed backends, this transfers ownership without copying.
    /// For file-backed backends (mmap), this makes a complete copy of the data.
    ///
    /// # Examples
    ///
    /// ```rust,ignore
    /// // Memory backend - no copy, ownership transfer
    /// let backend = Memory::new(vec![1, 2, 3]);
    /// let data = backend.into_data(); // Moves the Vec, no allocation
    ///
    /// // Physical backend - copies the mmap'd data
    /// let backend = Physical::new(Path::new("file.dll"))?;
    /// let data = backend.into_data(); // Allocates and copies
    /// ```
    fn into_data(self: Box<Self>) -> Vec<u8>;
}

/// Represents a loaded PE file.
///
/// This struct can load both .NET assemblies and native PE files. Use [`File::is_clr()`]
/// to check if the file contains .NET metadata.
///
/// This struct contains the parsed PE information and provides methods for accessing headers,
/// sections, data directories, and for converting between address spaces. It supports loading
/// from both files and memory buffers.
///
/// The `File` struct is the main entry point for working with PE files. It can load both
/// .NET assemblies and native PE executables/DLLs. Use [`File::is_clr()`] or [`File::clr()`]
/// to determine if the loaded file contains .NET metadata.
///
/// # Examples
///
/// ## Loading and checking for .NET metadata
///
/// ```rust,no_run
/// use dotscope::File;
/// use std::path::Path;
///
/// let file = File::from_path(Path::new("example.exe"))?;
/// println!("Loaded PE with {} sections", file.sections().len());
///
/// // Check if it's a .NET assembly
/// if file.is_clr() {
///     let (clr_rva, clr_size) = file.clr().unwrap();
///     println!(".NET assembly - CLR at RVA 0x{:x}, size={}", clr_rva, clr_size);
/// } else {
///     println!("Native PE executable (no .NET metadata)");
/// }
/// # Ok::<(), dotscope::Error>(())
/// ```
///
/// ## Loading from memory
///
/// ```rust,no_run
/// use dotscope::File;
/// use std::fs;
///
/// let data = fs::read("assembly.dll")?;
/// let file = File::from_mem(data)?;
///
/// // Access CLR metadata if present
/// if let Some((clr_rva, clr_size)) = file.clr() {
///     println!("CLR header at RVA 0x{:x}, {} bytes", clr_rva, clr_size);
/// }
/// # Ok::<(), dotscope::Error>(())
/// ```
///
/// ## Working with addresses
///
/// ```rust,no_run
/// use dotscope::File;
/// use std::path::Path;
///
/// let file = File::from_path(Path::new("tests/samples/WindowsBase.dll"))?;
///
/// // Convert between address spaces
/// let entry_rva = file.header_optional().as_ref().unwrap()
///     .standard_fields.address_of_entry_point as usize;
/// let entry_offset = file.rva_to_offset(entry_rva)?;
///
/// // Read entry point code
/// let entry_code = file.data_slice(entry_offset, 16)?;
/// println!("Entry point bytes: {:02x?}", entry_code);
/// # Ok::<(), dotscope::Error>(())
/// ```
pub struct File {
    /// The underlying data source (memory or file).
    data: Box<dyn Backend>,
    /// The parsed PE structure as owned data.
    pe: Pe,
}

impl File {
    /// Loads a PE file from the given path.
    ///
    /// This method opens a file from disk and parses it as a PE file.
    /// The file is memory-mapped for efficient access. Works with both .NET assemblies
    /// and native PE executables/DLLs.
    ///
    /// # Arguments
    ///
    /// * `path` - Path to the PE file on disk. Accepts `&Path`, `&str`, `String`, or `PathBuf`.
    ///
    /// # Errors
    ///
    /// Returns an error if:
    /// - The file cannot be read or opened
    /// - The file is not a valid PE format
    /// - The file is empty
    ///
    /// # Examples
    ///
    /// ```rust,no_run
    /// use dotscope::File;
    /// use std::path::Path;
    ///
    /// // With Path
    /// let file = File::from_path(Path::new("tests/samples/WindowsBase.dll"))?;
    ///
    /// // With string slice
    /// let file = File::from_path("tests/samples/WindowsBase.dll")?;
    ///
    /// println!("Loaded {} bytes with {} sections",
    ///          file.len(), file.sections().len());
    ///
    /// // Check if it's a .NET assembly
    /// if let Some((clr_rva, clr_size)) = file.clr() {
    ///     println!("CLR runtime header: RVA=0x{:x}, size={}", clr_rva, clr_size);
    /// }
    /// # Ok::<(), dotscope::Error>(())
    /// ```
    pub fn from_path(path: impl AsRef<Path>) -> Result<File> {
        let input = Physical::new(path.as_ref())?;

        Self::load(input)
    }

    /// Loads a PE file from a memory buffer.
    ///
    /// This method parses a PE file that's already loaded into memory.
    /// Useful when working with embedded resources or downloaded files.
    /// Works with both .NET assemblies and native PE executables/DLLs.
    ///
    /// # Arguments
    ///
    /// * `data` - The bytes of the PE file.
    ///
    /// # Errors
    ///
    /// Returns an error if:
    /// - The buffer is empty
    /// - The data is not a valid PE format
    ///
    /// # Examples
    ///
    /// ```rust,no_run
    /// use dotscope::File;
    /// use std::fs;
    ///
    /// // Load from downloaded or embedded data
    /// let data = fs::read("tests/samples/WindowsBase.dll")?;
    /// let file = File::from_mem(data)?;
    ///
    /// // Inspect the assembly
    /// println!("Assembly size: {} bytes", file.len());
    /// println!("Image base: 0x{:x}", file.imagebase());
    ///
    /// // Find specific sections
    /// for section in file.sections() {
    ///     let name = section.name.trim_end_matches('\0');
    ///     if name == ".text" {
    ///         println!("Code section at RVA 0x{:x}", section.virtual_address);
    ///         break;
    ///     }
    /// }
    /// # Ok::<(), dotscope::Error>(())
    /// ```
    pub fn from_mem(data: Vec<u8>) -> Result<File> {
        let input = Memory::new(data);

        Self::load(input)
    }

    /// Creates a File from an opened std::fs::File.
    ///
    /// The file is memory-mapped for efficient access. This is useful when you already have
    /// a file handle open with specific permissions or from a special location.
    ///
    /// # Arguments
    /// * `file` - An opened file handle
    ///
    /// # Errors
    /// Returns an error if:
    /// - The file cannot be memory-mapped
    /// - The data is not a valid PE format
    ///
    /// # Examples
    ///
    /// ```rust,no_run
    /// use dotscope::File;
    /// use std::fs::File as StdFile;
    ///
    /// let std_file = StdFile::open("assembly.dll")?;
    /// let pe_file = File::from_std_file(std_file)?;
    /// # Ok::<(), Box<dyn std::error::Error>>(())
    /// ```
    pub fn from_std_file(file: std::fs::File) -> Result<File> {
        let input = Physical::from_std_file(file)?;

        Self::load(input)
    }

    /// Creates a File from any type implementing Read.
    ///
    /// This is the most flexible constructor, allowing Files to be created from
    /// network streams, archives, cursors, or any custom reader.
    ///
    /// # Arguments
    /// * `reader` - Any type implementing Read
    ///
    /// # Errors
    /// Returns an error if:
    /// - The reader cannot be read
    /// - The data is not a valid PE format
    ///
    /// # Examples
    ///
    /// ```rust,no_run
    /// use dotscope::File;
    /// use std::io::Cursor;
    ///
    /// let data = vec![/* PE bytes */];
    /// let cursor = Cursor::new(data);
    /// let file = File::from_reader(cursor)?;
    /// # Ok::<(), dotscope::Error>(())
    /// ```
    pub fn from_reader<R: std::io::Read>(mut reader: R) -> Result<File> {
        let mut data = Vec::new();
        reader
            .read_to_end(&mut data)
            .map_err(|e| Other(format!("Failed to read from reader: {e}")))?;
        Self::from_mem(data)
    }

    /// Internal loader for any backend.
    ///
    /// # Arguments
    ///
    /// * `data` - The backend providing the PE data.
    ///
    /// # Errors
    ///
    /// Returns an error if the data is empty or not a valid PE format.
    fn load<T: Backend + 'static>(data: T) -> Result<File> {
        if data.len() == 0 {
            return Err(Error::NotSupported);
        }

        // ToDo: For MONO, the .NET CIL part is embedded into an ELF as an actual valid PE file.
        //       To support MONO, we'll need to parse the ELF file here, and extract the PE structure that this `File`
        //       is then pointing to

        let goblin_pe = match PE::parse(data.data()) {
            Ok(pe) => pe,
            Err(error) => return Err(Goblin(error)),
        };

        let owned_pe = Pe::from_goblin_pe(&goblin_pe)?;

        Ok(File {
            data: Box::new(data),
            pe: owned_pe,
        })
    }

    /// Returns the total size of the loaded file in bytes.
    ///
    /// # Examples
    ///
    /// ```rust,no_run
    /// use dotscope::File;
    /// use std::path::Path;
    ///
    /// let file = File::from_path(Path::new("tests/samples/WindowsBase.dll"))?;
    /// println!("File size: {} bytes", file.len());
    /// # Ok::<(), dotscope::Error>(())
    /// ```
    #[must_use]
    pub fn len(&self) -> usize {
        self.data.len()
    }

    /// Returns `true` if the file has a length of zero.
    ///
    /// # Examples
    ///
    /// ```rust,no_run
    /// use dotscope::File;
    /// use std::path::Path;
    ///
    /// let file = File::from_path(Path::new("tests/samples/WindowsBase.dll"))?;
    /// assert!(!file.is_empty()); // Valid PE files are never empty
    /// # Ok::<(), dotscope::Error>(())
    /// ```
    #[must_use]
    pub fn is_empty(&self) -> bool {
        self.len() == 0
    }

    /// Returns the image base address of the loaded PE file.
    ///
    /// The image base is the preferred virtual address where the PE file
    /// should be loaded in memory. This is used for calculating virtual addresses.
    ///
    /// # Examples
    ///
    /// ```rust,no_run
    /// use dotscope::File;
    /// use std::path::Path;
    ///
    /// let file = File::from_path(Path::new("tests/samples/WindowsBase.dll"))?;
    /// let base = file.imagebase();
    /// println!("Image base: 0x{:x}", base);
    /// # Ok::<(), dotscope::Error>(())
    /// ```
    #[must_use]
    pub fn imagebase(&self) -> u64 {
        self.pe.image_base
    }

    /// Returns a reference to the COFF header.
    ///
    /// The COFF header contains essential metadata about the executable,
    /// including the machine type, number of sections, and timestamp.
    ///
    /// # Examples
    ///
    /// ```rust,no_run
    /// use dotscope::File;
    /// use std::path::Path;
    ///
    /// let file = File::from_path(Path::new("tests/samples/WindowsBase.dll"))?;
    /// let header = file.header();
    /// println!("Machine type: 0x{:x}", header.machine);
    /// println!("Number of sections: {}", header.number_of_sections);
    /// # Ok::<(), dotscope::Error>(())
    /// ```
    #[must_use]
    pub fn header(&self) -> &pe::CoffHeader {
        &self.pe.coff_header
    }

    /// Returns a reference to the DOS header.
    ///
    /// The DOS header is the first part of a PE file and contains the DOS stub
    /// that displays the "This program cannot be run in DOS mode" message.
    ///
    /// # Examples
    ///
    /// ```rust,no_run
    /// use dotscope::File;
    /// use std::path::Path;
    ///
    /// let file = File::from_path(Path::new("tests/samples/WindowsBase.dll"))?;
    /// let dos_header = file.header_dos();
    /// println!("DOS signature: 0x{:x}", dos_header.signature);
    /// println!("Number of bytes on last page: {}", dos_header.bytes_on_last_page);
    /// # Ok::<(), dotscope::Error>(())
    /// ```
    #[must_use]
    pub fn header_dos(&self) -> &pe::DosHeader {
        &self.pe.dos_header
    }

    /// Returns a reference to the optional header, if present.
    ///
    /// This is always `Some` for valid .NET assemblies since they require
    /// an optional header to define data directories and other metadata.
    ///
    /// # Examples
    ///
    /// ```rust,no_run
    /// use dotscope::File;
    /// use std::path::Path;
    ///
    /// let file = File::from_path(Path::new("tests/samples/WindowsBase.dll"))?;
    /// let optional_header = file.header_optional().as_ref().unwrap();
    /// println!("Entry point: 0x{:x}", optional_header.standard_fields.address_of_entry_point);
    /// println!("Subsystem: {:?}", optional_header.windows_fields.subsystem);
    /// # Ok::<(), dotscope::Error>(())
    /// ```
    #[must_use]
    pub fn header_optional(&self) -> &Option<pe::OptionalHeader> {
        // We have verified the existence of the optional_header during the initial load.
        &self.pe.optional_header
    }

    /// Returns the RVA and size of the CLR runtime header, if present.
    ///
    /// The CLR runtime header contains metadata about the .NET runtime,
    /// including pointers to metadata tables and other runtime structures.
    ///
    /// # Returns
    ///
    /// - `Some((rva, size))` if this PE file contains a CLR runtime header (.NET assembly)
    /// - `None` if this is a native PE file without .NET metadata
    ///
    /// # Examples
    ///
    /// ```rust,no_run
    /// use dotscope::File;
    /// use std::path::Path;
    ///
    /// let file = File::from_path(Path::new("example.exe"))?;
    /// match file.clr() {
    ///     Some((rva, size)) => println!(".NET assembly: CLR at RVA 0x{:x}", rva),
    ///     None => println!("Native PE file (no .NET metadata)"),
    /// }
    /// # Ok::<(), dotscope::Error>(())
    /// ```
    #[must_use]
    pub fn clr(&self) -> Option<(usize, usize)> {
        self.pe
            .get_clr_runtime_header()
            .map(|clr_dir| (clr_dir.virtual_address as usize, clr_dir.size as usize))
    }

    /// Returns true if this PE file contains a CLR runtime header (.NET assembly).
    ///
    /// This is a convenience method equivalent to `file.clr().is_some()`.
    ///
    /// # Examples
    ///
    /// ```rust,no_run
    /// use dotscope::File;
    /// use std::path::Path;
    ///
    /// let file = File::from_path(Path::new("example.exe"))?;
    /// if file.is_clr() {
    ///     println!("This is a .NET assembly");
    /// } else {
    ///     println!("This is a native PE file");
    /// }
    /// # Ok::<(), dotscope::Error>(())
    /// ```
    #[must_use]
    pub fn is_clr(&self) -> bool {
        self.clr().is_some()
    }

    /// Returns a slice of the section headers of the PE file.
    ///
    /// Sections contain the actual code and data of the PE file, such as
    /// `.text` (executable code), `.data` (initialized data), and `.rsrc` (resources).
    ///
    /// # Examples
    ///
    /// ```rust,no_run
    /// use dotscope::File;
    /// use std::path::Path;
    ///
    /// let file = File::from_path(Path::new("tests/samples/WindowsBase.dll"))?;
    /// for section in file.sections() {
    ///     println!("Section: {} at RVA 0x{:x}, size: {} bytes",
    ///              section.name, section.virtual_address, section.virtual_size);
    /// }
    /// # Ok::<(), dotscope::Error>(())
    /// ```
    #[must_use]
    pub fn sections(&self) -> &[pe::SectionTable] {
        &self.pe.sections
    }

    /// Returns the data directories of the PE file.
    ///
    /// # Examples
    ///
    /// ```rust,no_run
    /// use dotscope::File;
    /// use std::path::Path;
    ///
    /// let file = File::from_path(Path::new("tests/samples/WindowsBase.dll"))?;
    /// for (dir_type, directory) in file.directories() {
    ///     println!("Directory: {:?}, RVA: 0x{:x}", dir_type, directory.virtual_address);
    /// }
    /// # Ok::<(), dotscope::Error>(())
    /// ```
    #[must_use]
    pub fn directories(&self) -> Vec<(DataDirectoryType, DataDirectory)> {
        // We have verified the existence of the optional_header during the initial load.
        self.pe
            .data_directories
            .iter()
            .map(|(&dir_type, &dir)| (dir_type, dir))
            .collect()
    }

    /// Returns the RVA and size of a specific data directory entry.
    ///
    /// This method provides unified access to PE data directory entries by type.
    /// It returns the virtual address and size if the directory exists and is valid,
    /// or `None` if the directory doesn't exist or has zero address/size.
    ///
    /// # Arguments
    /// * `dir_type` - The type of data directory to retrieve
    ///
    /// # Returns
    /// - `Some((rva, size))` if the directory exists with non-zero address and size
    /// - `None` if the directory doesn't exist or has zero address/size
    ///
    /// # Examples
    ///
    /// ```rust,no_run
    /// use dotscope::File;
    /// use dotscope::DataDirectoryType;
    /// use std::path::Path;
    ///
    /// let file = File::from_path(Path::new("example.dll"))?;
    ///
    /// // Check for import table
    /// if let Some((import_rva, import_size)) = file.get_data_directory(DataDirectoryType::ImportTable) {
    ///     println!("Import table at RVA 0x{:x}, size: {} bytes", import_rva, import_size);
    /// }
    ///
    /// // Check for export table
    /// if let Some((export_rva, export_size)) = file.get_data_directory(DataDirectoryType::ExportTable) {
    ///     println!("Export table at RVA 0x{:x}, size: {} bytes", export_rva, export_size);
    /// }
    /// # Ok::<(), dotscope::Error>(())
    /// ```
    #[must_use]
    pub fn get_data_directory(&self, dir_type: DataDirectoryType) -> Option<(u32, u32)> {
        self.pe
            .get_data_directory(dir_type)
            .filter(|directory| directory.virtual_address != 0 && directory.size != 0)
            .map(|directory| (directory.virtual_address, directory.size))
    }

    /// Returns the parsed import data from the PE file.
    ///
    /// Uses goblin's PE parsing to extract import table information including
    /// DLL dependencies and imported functions. Returns the parsed import data
    /// if an import directory exists.
    ///
    /// # Returns
    /// - `Some(imports)` if import directory exists and was successfully parsed
    /// - `None` if no import directory exists or parsing failed
    ///
    /// # Examples
    ///
    /// ```rust,no_run
    /// use dotscope::File;
    /// use std::path::Path;
    ///
    /// let file = File::from_path(Path::new("example.dll"))?;
    /// if let Some(imports) = file.imports() {
    ///     for import in imports {
    ///         println!("DLL: {}", import.dll);
    ///         if let Some(ref name) = import.name {
    ///             if !name.is_empty() {
    ///                 println!("  Function: {}", name);
    ///             }
    ///         } else if let Some(ordinal) = import.ordinal {
    ///             println!("  Ordinal: {}", ordinal);
    ///         }
    ///     }
    /// }
    /// # Ok::<(), dotscope::Error>(())
    /// ```
    #[must_use]
    pub fn imports(&self) -> Option<&Vec<pe::Import>> {
        if self.pe.imports.is_empty() {
            None
        } else {
            Some(&self.pe.imports)
        }
    }

    /// Returns the parsed export data from the PE file.
    ///
    /// Uses goblin's PE parsing to extract export table information including
    /// exported functions and their addresses. Returns the parsed export data
    /// if an export directory exists.
    ///
    /// # Returns
    /// - `Some(exports)` if export directory exists and was successfully parsed
    /// - `None` if no export directory exists or parsing failed
    ///
    /// # Examples
    ///
    /// ```rust,no_run
    /// use dotscope::File;
    /// use std::path::Path;
    ///
    /// let file = File::from_path(Path::new("example.dll"))?;
    /// if let Some(exports) = file.exports() {
    ///     for export in exports {
    ///         if let Some(name) = &export.name {
    ///             println!("Export: {} -> 0x{:X}", name, export.rva);
    ///         }
    ///     }
    /// }
    /// # Ok::<(), dotscope::Error>(())
    /// ```
    #[must_use]
    pub fn exports(&self) -> Option<&Vec<pe::Export>> {
        if self.pe.exports.is_empty() {
            None
        } else {
            Some(&self.pe.exports)
        }
    }

    /// Returns the raw data of the loaded file.
    ///
    /// This provides access to the entire PE file contents as a byte slice.
    /// Useful for reading specific offsets or when you need direct access
    /// to the binary data.
    ///
    /// # Examples
    ///
    /// ```rust,no_run
    /// use dotscope::File;
    /// use std::path::Path;
    ///
    /// let file = File::from_path(Path::new("tests/samples/WindowsBase.dll"))?;
    /// let data = file.data();
    ///
    /// // Check DOS signature (MZ)
    /// assert_eq!(&data[0..2], b"MZ");
    ///
    /// // Access PE signature offset
    /// let pe_offset = u32::from_le_bytes([data[60], data[61], data[62], data[63]]) as usize;
    /// assert_eq!(&data[pe_offset..pe_offset + 4], b"PE\0\0");
    /// # Ok::<(), dotscope::Error>(())
    /// ```
    #[must_use]
    pub fn data(&self) -> &[u8] {
        self.data.data()
    }

    /// Returns a slice of the file data at the given offset and length.
    ///
    /// This is a safe way to access specific portions of the PE file data
    /// with bounds checking to prevent buffer overflows.
    ///
    /// # Arguments
    ///
    /// * `offset` - The offset to start the slice from.
    /// * `len` - The length of the slice.
    ///
    /// # Errors
    ///
    /// Returns an error if the requested range is out of bounds.
    ///
    /// # Examples
    ///
    /// ```rust,no_run
    /// use dotscope::File;
    /// use std::path::Path;
    ///
    /// let file = File::from_path(Path::new("tests/samples/WindowsBase.dll"))?;
    ///
    /// // Read the DOS header (first 64 bytes)
    /// let dos_header = file.data_slice(0, 64)?;
    /// assert_eq!(&dos_header[0..2], b"MZ");
    ///
    /// // Read PE signature
    /// let pe_offset = u32::from_le_bytes([dos_header[60], dos_header[61],
    ///                                     dos_header[62], dos_header[63]]) as usize;
    /// let pe_sig = file.data_slice(pe_offset, 4)?;
    /// assert_eq!(pe_sig, b"PE\0\0");
    /// # Ok::<(), dotscope::Error>(())
    /// ```
    pub fn data_slice(&self, offset: usize, len: usize) -> Result<&[u8]> {
        self.data.data_slice(offset, len)
    }

    /// Converts a virtual address (VA) to a file offset.
    ///
    /// Virtual addresses are absolute addresses where the PE file would be
    /// loaded in memory. This method converts them to file offsets for
    /// reading data from the actual file.
    ///
    /// # Arguments
    ///
    /// * `va` - The virtual address to convert.
    ///
    /// # Errors
    ///
    /// Returns an error if the VA is out of bounds or cannot be mapped.
    ///
    /// # Examples
    ///
    /// ```rust,no_run
    /// use dotscope::File;
    /// use std::path::Path;
    ///
    /// let file = File::from_path(Path::new("tests/samples/WindowsBase.dll"))?;
    ///
    /// // Convert entry point VA to file offset
    /// let entry_point_va = file.header_optional().as_ref().unwrap().standard_fields.address_of_entry_point as usize;
    /// let image_base = file.imagebase() as usize;
    /// let full_va = image_base + entry_point_va;
    ///
    /// let offset = file.va_to_offset(full_va)?;
    /// println!("Entry point at file offset: 0x{:x}", offset);
    /// # Ok::<(), dotscope::Error>(())
    /// ```
    pub fn va_to_offset(&self, va: usize) -> Result<usize> {
        let ib = self.imagebase();
        if ib > va as u64 {
            return Err(out_of_bounds_error!());
        }

        let rva_u64 = va as u64 - ib;
        let rva = usize::try_from(rva_u64)
            .map_err(|_| malformed_error!("RVA too large to fit in usize: {}", rva_u64))?;
        self.rva_to_offset(rva)
    }

    /// Converts a relative virtual address (RVA) to a file offset.
    ///
    /// RVAs are addresses relative to the image base. This is the most common
    /// address format used within PE files for referencing data and code.
    ///
    /// # Arguments
    ///
    /// * `rva` - The RVA to convert.
    ///
    /// # Errors
    ///
    /// Returns an error if the RVA cannot be mapped to a file offset.
    ///
    /// # Examples
    ///
    /// ```rust,no_run
    /// use dotscope::File;
    /// use std::path::Path;
    ///
    /// let file = File::from_path(Path::new("tests/samples/WindowsBase.dll"))?;
    ///
    /// // Convert CLR header RVA to file offset
    /// let Some((clr_rva, _)) = file.clr() else {
    ///     panic!("No CLR header found");
    /// };
    /// let clr_offset = file.rva_to_offset(clr_rva)?;
    ///
    /// // Read CLR header data
    /// let clr_data = file.data_slice(clr_offset, 72)?; // CLR header is 72 bytes
    /// println!("CLR header starts with: {:02x?}", &clr_data[0..8]);
    /// # Ok::<(), dotscope::Error>(())
    /// ```
    pub fn rva_to_offset(&self, rva: usize) -> Result<usize> {
        for section in &self.pe.sections {
            let Some(section_max) = section.virtual_address.checked_add(section.virtual_size)
            else {
                return Err(malformed_error!(
                    "Section malformed, causing integer overflow - {} + {}",
                    section.virtual_address,
                    section.virtual_size
                ));
            };

            let rva_u32 = u32::try_from(rva)
                .map_err(|_| malformed_error!("RVA too large to fit in u32: {}", rva))?;
            if section.virtual_address <= rva_u32 && section_max > rva_u32 {
                return Ok(
                    (rva - section.virtual_address as usize) + section.pointer_to_raw_data as usize
                );
            }
        }

        Err(malformed_error!(
            "RVA could not be converted to offset - {}",
            rva
        ))
    }

    /// Converts a file offset to a relative virtual address (RVA).
    ///
    /// This is the inverse of `rva_to_offset()`. Given a file offset,
    /// it calculates what RVA that offset corresponds to when the
    /// PE file is loaded in memory.
    ///
    /// # Arguments
    ///
    /// * `offset` - The file offset to convert.
    ///
    /// # Errors
    ///
    /// Returns an error if the offset cannot be mapped to an RVA.
    ///
    /// # Examples
    ///
    /// ```rust,no_run
    /// use dotscope::File;
    /// use std::path::Path;
    ///
    /// let file = File::from_path(Path::new("tests/samples/WindowsBase.dll"))?;
    ///
    /// // Find what RVA corresponds to file offset 0x1000
    /// let rva = file.offset_to_rva(0x1000)?;
    /// println!("File offset 0x1000 maps to RVA 0x{:x}", rva);
    ///
    /// // Verify round-trip conversion
    /// let back_to_offset = file.rva_to_offset(rva)?;
    /// assert_eq!(back_to_offset, 0x1000);
    /// # Ok::<(), dotscope::Error>(())
    /// ```
    pub fn offset_to_rva(&self, offset: usize) -> Result<usize> {
        for section in &self.pe.sections {
            let Some(section_max) = section
                .pointer_to_raw_data
                .checked_add(section.size_of_raw_data)
            else {
                return Err(malformed_error!(
                    "Section malformed, causing integer overflow - {} + {}",
                    section.pointer_to_raw_data,
                    section.size_of_raw_data
                ));
            };

            let offset_u32 = u32::try_from(offset)
                .map_err(|_| malformed_error!("Offset too large to fit in u32: {}", offset))?;
            if section.pointer_to_raw_data <= offset_u32 && section_max > offset_u32 {
                return Ok((offset - section.pointer_to_raw_data as usize)
                    + section.virtual_address as usize);
            }
        }

        Err(malformed_error!(
            "Offset could not be converted to RVA - {}",
            offset
        ))
    }

    /// Determines if a section contains .NET metadata by checking the actual metadata RVA.
    ///
    /// This method reads the CLR runtime header to get the metadata RVA and checks
    /// if it falls within the specified section's address range. This is more accurate
    /// than name-based heuristics since metadata can technically be located in any section.
    ///
    /// # Arguments
    /// * `section_name` - The name of the section to check (e.g., ".text")
    ///
    /// # Returns
    /// Returns `true` if the section contains .NET metadata, `false` otherwise.
    ///
    /// # Examples
    ///
    /// ```rust,no_run
    /// use dotscope::File;
    /// use std::path::Path;
    ///
    /// let file = File::from_path(Path::new("example.dll"))?;
    ///
    /// if file.section_contains_metadata(".text") {
    ///     println!("The .text section contains .NET metadata");
    /// }
    /// # Ok::<(), dotscope::Error>(())
    /// ```
    #[must_use]
    pub fn section_contains_metadata(&self, section_name: &str) -> bool {
        let clr_rva = match self.clr() {
            Some((rva, size)) if rva > 0 && size >= COR20_HEADER_SIZE as usize => {
                let Ok(rva_u32) = u32::try_from(rva) else {
                    return false; // RVA too large for valid PE
                };
                rva_u32
            }
            _ => return false, // No CLR header means no .NET metadata
        };

        let Ok(clr_offset) = self.rva_to_offset(clr_rva as usize) else {
            return false;
        };

        let Ok(clr_data) = self.data_slice(clr_offset, COR20_HEADER_SIZE as usize) else {
            return false;
        };

        if clr_data.len() < 12 {
            return false;
        }

        let meta_data_rva =
            u32::from_le_bytes([clr_data[8], clr_data[9], clr_data[10], clr_data[11]]);

        if meta_data_rva == 0 {
            return false; // No metadata
        }

        for section in self.sections() {
            let current_section_name = section.name.as_str();

            if current_section_name == section_name {
                let section_start = section.virtual_address;
                let section_end = section.virtual_address + section.virtual_size;
                return meta_data_rva >= section_start && meta_data_rva < section_end;
            }
        }

        false // Section not found
    }

    /// Gets the file alignment value from the PE header.
    ///
    /// This method extracts the file alignment value from the PE optional header.
    /// This is typically 512 bytes for most .NET assemblies.
    ///
    /// # Returns
    /// Returns the file alignment value in bytes.
    ///
    /// # Errors
    /// Returns [`crate::Error::LayoutFailed`] if the PE header cannot be accessed.
    pub fn file_alignment(&self) -> Result<u32> {
        let optional_header = self.header_optional().as_ref().ok_or_else(|| {
            LayoutFailed("Missing optional header for file alignment".to_string())
        })?;

        Ok(optional_header.windows_fields.file_alignment)
    }

    /// Gets the section alignment value from the PE header.
    ///
    /// This method extracts the section alignment value from the PE optional header.
    /// This is typically 4096 bytes (page size) for most .NET assemblies.
    ///
    /// # Returns
    /// Returns the section alignment value in bytes.
    ///
    /// # Errors
    /// Returns [`crate::Error::LayoutFailed`] if the PE header cannot be accessed.
    pub fn section_alignment(&self) -> Result<u32> {
        let optional_header = self.header_optional().as_ref().ok_or_else(|| {
            LayoutFailed("Missing optional header for section alignment".to_string())
        })?;

        Ok(optional_header.windows_fields.section_alignment)
    }

    /// Determines if this is a PE32+ format file.
    ///
    /// Returns `true` for PE32+ (64-bit) format, `false` for PE32 (32-bit) format.
    /// This affects the size of ILT/IAT entries and ordinal import bit positions.
    ///
    /// # Returns
    /// Returns `true` if PE32+ format, `false` if PE32 format.
    ///
    /// # Errors
    /// Returns [`crate::Error::LayoutFailed`] if the PE format cannot be determined.
    pub fn is_pe32_plus_format(&self) -> Result<bool> {
        let optional_header = self.header_optional().as_ref().ok_or_else(|| {
            LayoutFailed("Missing optional header for PE format detection".to_string())
        })?;

        // PE32 magic is 0x10b, PE32+ magic is 0x20b
        Ok(optional_header.standard_fields.magic != 0x10b)
    }

    /// Finds the .text section in the PE file.
    ///
    /// Locates the .text section (or .text-prefixed section) which typically
    /// contains .NET metadata and executable code.
    ///
    /// # Returns
    /// Returns a reference to the .text section table entry.
    ///
    /// # Errors
    /// Returns [`crate::Error::LayoutFailed`] if no .text section is found.
    fn find_text_section(&self) -> Result<&pe::SectionTable> {
        self.sections()
            .iter()
            .find(|s| s.name.as_str() == ".text" || s.name.starts_with(".text"))
            .ok_or_else(|| LayoutFailed("Could not find .text section".to_string()))
    }

    /// Gets the RVA of the .text section.
    ///
    /// Locates the .text section (or .text-prefixed section) which typically
    /// contains .NET metadata and executable code.
    ///
    /// # Returns
    /// Returns the RVA (Relative Virtual Address) of the .text section.
    ///
    /// # Errors
    /// Returns [`crate::Error::LayoutFailed`] if no .text section is found.
    pub fn text_section_rva(&self) -> Result<u32> {
        Ok(self.find_text_section()?.virtual_address)
    }

    /// Gets the file offset of the .text section.
    ///
    /// This method finds the .text section in the PE file and returns its file offset.
    /// This is needed for calculating absolute file offsets for metadata components.
    ///
    /// # Returns
    /// Returns the file offset of the .text section.
    ///
    /// # Errors
    /// Returns [`crate::Error::LayoutFailed`] if no .text section is found.
    pub fn text_section_file_offset(&self) -> Result<u64> {
        Ok(u64::from(self.find_text_section()?.pointer_to_raw_data))
    }

    /// Gets the raw size of the .text section.
    ///
    /// This method finds the .text section and returns its raw data size.
    /// This is needed for calculating metadata expansion requirements.
    ///
    /// # Returns
    /// Returns the raw size of the .text section in bytes.
    ///
    /// # Errors
    /// Returns [`crate::Error::LayoutFailed`] if no .text section is found.
    pub fn text_section_raw_size(&self) -> Result<u32> {
        Ok(self.find_text_section()?.size_of_raw_data)
    }

    /// Gets the total size of the file.
    ///
    /// Returns the size of the underlying file data in bytes.
    ///
    /// # Returns
    /// Returns the file size in bytes.
    #[must_use]
    pub fn file_size(&self) -> u64 {
        u64::try_from(self.data().len()).unwrap_or(u64::MAX)
    }

    /// Gets the PE signature offset from the DOS header.
    ///
    /// Reads the PE offset from the DOS header at offset 0x3C to locate
    /// the PE signature ("PE\0\0") within the file.
    ///
    /// # Returns
    /// Returns the file offset where the PE signature is located.
    ///
    /// # Errors
    /// Returns [`crate::Error::LayoutFailed`] if the file is too small to contain
    /// a valid DOS header.
    pub fn pe_signature_offset(&self) -> Result<u64> {
        let data = self.data();

        if data.len() < 64 {
            return Err(LayoutFailed(
                "File too small to contain DOS header".to_string(),
            ));
        }

        // PE offset is at offset 0x3C in DOS header
        let pe_offset = u32::from_le_bytes([data[60], data[61], data[62], data[63]]);
        Ok(u64::from(pe_offset))
    }

    /// Calculates the size of PE headers (including optional header).
    ///
    /// Computes the total size of PE signature, COFF header, and optional header
    /// by reading the optional header size from the COFF header.
    ///
    /// # Returns
    /// Returns the total size in bytes of all PE headers.
    ///
    /// # Errors
    /// Returns [`crate::Error::LayoutFailed`] if the file is too small or
    /// headers are malformed.
    pub fn pe_headers_size(&self) -> Result<u64> {
        // PE signature (4) + COFF header (20) + Optional header size
        // We need to read the optional header size from the COFF header
        let pe_sig_offset = self.pe_signature_offset()?;
        let data = self.data();

        let coff_header_offset = pe_sig_offset + 4; // Skip PE signature

        #[allow(clippy::cast_possible_truncation)]
        if data.len() < (coff_header_offset + 20) as usize {
            return Err(LayoutFailed(
                "File too small to contain COFF header".to_string(),
            ));
        }

        // Optional header size is at offset 16 in COFF header
        let opt_header_size_offset = coff_header_offset + 16;
        #[allow(clippy::cast_possible_truncation)]
        let opt_header_size = u16::from_le_bytes([
            data[opt_header_size_offset as usize],
            data[opt_header_size_offset as usize + 1],
        ]);

        Ok(4 + 20 + u64::from(opt_header_size)) // PE sig + COFF + Optional header
    }

    /// Aligns an offset to this file's PE file alignment boundary.
    ///
    /// PE files require data to be aligned to specific boundaries for optimal loading.
    /// This method uses the actual file alignment value from the PE header rather than
    /// assuming a hardcoded value.
    ///
    /// # Arguments
    /// * `offset` - The offset to align
    ///
    /// # Returns
    /// Returns the offset rounded up to the next file alignment boundary.
    ///
    /// # Errors
    /// Returns [`crate::Error::LayoutFailed`] if the PE header cannot be accessed.
    pub fn align_to_file_alignment(&self, offset: u64) -> Result<u64> {
        let file_alignment = u64::from(self.file_alignment()?);
        Ok(align_to(offset, file_alignment))
    }

    /// Returns a reference to the internal Pe structure.
    ///
    /// This provides access to the owned PE data structures for operations
    /// that need to work directly with PE components, such as size calculations
    /// and header updates during write operations.
    ///
    /// # Returns
    /// Reference to the internal Pe structure
    #[must_use]
    pub fn pe(&self) -> &Pe {
        &self.pe
    }

    /// Returns a mutable reference to the internal Pe structure.
    ///
    /// This provides mutable access to the owned PE data structures, enabling
    /// direct modifications to PE headers, sections, and data directories.
    /// Use this when you need to modify the PE structure in-place rather than
    /// creating copies.
    ///
    /// # Returns
    /// Mutable reference to the internal Pe structure
    ///
    /// # Examples
    /// ```rust,no_run
    /// use dotscope::{File, SectionTable};
    ///
    /// // Add a new section to the PE file
    /// let mut file = File::from_path("assembly.dll")?;
    /// let new_section = SectionTable::from_layout_info(
    ///     ".meta".to_string(),
    ///     0x4000,
    ///     0x1000,
    ///     0x2000,
    ///     0x1000,
    ///     0x40000040,
    /// )?;
    /// file.pe_mut().add_section(new_section);
    ///
    /// // Update CLR data directory
    /// file.pe_mut().update_clr_data_directory(0x4000, 72)?;
    /// # Ok::<(), dotscope::Error>(())
    /// ```
    pub fn pe_mut(&mut self) -> &mut Pe {
        &mut self.pe
    }

    /// Consumes the File and returns the underlying data as an owned `Vec<u8>`.
    ///
    /// For files loaded via `from_mem()`, this transfers ownership without copying.
    /// For files loaded via `from_file()`, this makes a complete copy of the memory-mapped data.
    ///
    /// # Examples
    ///
    /// ```rust,no_run
    /// use dotscope::File;
    /// use std::path::Path;
    ///
    /// // From memory - no copy
    /// let original_data = vec![/* PE bytes */];
    /// let file = File::from_mem(original_data)?;
    /// let recovered_data = file.into_data();
    ///
    /// // From file - copies the data
    /// let file = File::from_path(Path::new("assembly.dll"))?;
    /// let data_copy = file.into_data();
    /// # Ok::<(), dotscope::Error>(())
    /// ```
    #[must_use]
    pub fn into_data(self) -> Vec<u8> {
        self.data.into_data()
    }
}

#[cfg(test)]
mod tests {
    use std::{env, fs, path::PathBuf};

    use super::*;
    use crate::test::factories::general::file::verify_file;

    /// Tests loading a PE file from disk.
    #[test]
    fn load_file() {
        let path = PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("tests/samples/WindowsBase.dll");
        let file = File::from_path(&path).unwrap();

        verify_file(&file);
    }

    /// Tests loading a PE file from a memory buffer.
    #[test]
    fn load_buffer() {
        let path = PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("tests/samples/WindowsBase.dll");
        let data = fs::read(&path).unwrap();
        let file = File::from_mem(data).unwrap();

        verify_file(&file);
    }

    /// Tests loading an invalid PE file.
    #[test]
    fn load_invalid() {
        let data = include_bytes!("../../tests/samples/WB_ROOT.bin");
        if File::from_mem(data.to_vec()).is_ok() {
            panic!("This should not load!")
        }
    }

    /// Tests the unified get_data_directory method.
    #[test]
    fn test_get_data_directory() {
        let path = PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("tests/samples/WindowsBase.dll");
        let file = File::from_path(&path).unwrap();

        // Test CLR runtime header (should exist for .NET assemblies)
        let clr_dir = file.get_data_directory(DataDirectoryType::ClrRuntimeHeader);
        assert!(clr_dir.is_some(), "CLR runtime header should exist");
        let (clr_rva, clr_size) = clr_dir.unwrap();
        assert!(clr_rva > 0, "CLR RVA should be non-zero");
        assert!(clr_size > 0, "CLR size should be non-zero");

        // Verify it matches the existing clr() method
        let (expected_rva, expected_size) = file.clr().expect("Should have CLR header");
        assert_eq!(
            clr_rva as usize, expected_rva,
            "CLR RVA should match clr() method"
        );
        assert_eq!(
            clr_size as usize, expected_size,
            "CLR size should match clr() method"
        );

        // Test non-existent directory (should return None)
        let _base_reloc_dir = file.get_data_directory(DataDirectoryType::BaseRelocationTable);
        // For a typical .NET assembly, base relocation table might not exist
        // We don't assert anything specific here as it depends on the assembly

        // The method should handle any directory type gracefully
        let tls_dir = file.get_data_directory(DataDirectoryType::TlsTable);
        // TLS table typically doesn't exist in .NET assemblies, but method should not panic
        if let Some((tls_rva, tls_size)) = tls_dir {
            assert!(
                tls_rva > 0 && tls_size > 0,
                "If TLS directory exists, it should have valid values"
            );
        }
    }

    /// Tests the pe_signature_offset method.
    #[test]
    fn test_pe_signature_offset() {
        let path = PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("tests/samples/crafted_2.exe");
        let file = File::from_path(&path).expect("Failed to load test assembly");

        let pe_offset = file
            .pe_signature_offset()
            .expect("Should get PE signature offset");
        assert!(pe_offset > 0, "PE signature offset should be positive");
        assert!(pe_offset < 1024, "PE signature offset should be reasonable");
    }

    /// Tests the pe_headers_size method.
    #[test]
    fn test_pe_headers_size() {
        let path = PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("tests/samples/crafted_2.exe");
        let file = File::from_path(&path).expect("Failed to load test assembly");

        let headers_size = file
            .pe_headers_size()
            .expect("Should calculate headers size");
        assert!(headers_size >= 24, "Headers should be at least 24 bytes");
        assert!(headers_size <= 1024, "Headers size should be reasonable");
    }

    /// Tests the align_to_file_alignment method.
    #[test]
    fn test_align_to_file_alignment() {
        let path = PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("tests/samples/crafted_2.exe");
        let file = File::from_path(&path).expect("Failed to load test assembly");

        // Test alignment with actual file alignment from PE header
        let alignment = file.file_alignment().expect("Should get file alignment");

        // Test various offsets
        assert_eq!(file.align_to_file_alignment(0).unwrap(), 0);
        assert_eq!(file.align_to_file_alignment(1).unwrap(), alignment as u64);
        assert_eq!(
            file.align_to_file_alignment(alignment as u64).unwrap(),
            alignment as u64
        );
        assert_eq!(
            file.align_to_file_alignment(alignment as u64 + 1).unwrap(),
            (alignment * 2) as u64
        );
    }
}