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
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
//! Owned PE file structures and serialization support.
//!
//! This module provides owned versions of PE (Portable Executable) structures that don't
//! require borrowing from the original file data. These structures support both parsing
//! from goblin PE objects and serialization back to binary format for the write pipeline.
//!
//! # Architecture
//!
//! The module provides owned alternatives to goblin's borrowed structures:
//! - [`Pe`] - Main PE file representation
//! - [`DosHeader`] - DOS header with signature and PE offset
//! - [`CoffHeader`] - COFF header with machine type and characteristics
//! - [`OptionalHeader`] - Optional header with data directories and Windows fields
//! - [`SectionTable`] - Section table entries with names and addresses
//! - [`DataDirectories`] - Data directory entries as owned map
//! - [`Import`]/[`Export`] - Owned import/export table entries
//!
//! Each structure implements:
//! - Conversion from corresponding goblin types
//! - Binary serialization methods for the write pipeline
//! - Accessor methods matching the original File API
//!
//! # Usage Examples
//!
//! ## Parsing from Goblin PE
//! ```rust,ignore
//! use goblin::pe::PE;
//! use dotscope::Pe;
//!
//! let goblin_pe = PE::parse(data)?;
//! let owned_pe = Pe::from_goblin_pe(&goblin_pe)?;
//! ```
//!
//! ## Serialization for Write Pipeline
//! ```rust,ignore
//! let mut buffer = Vec::new();
//! owned_pe.write_headers(&mut buffer)?;
//! owned_pe.write_section_table(&mut buffer)?;
//! ```

use crate::{Error, Result};
use std::collections::HashMap;
use std::fmt;
use std::io::Write;

/// PE machine type wrapper with human-readable Display.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct Machine(pub u16);

impl fmt::Display for Machine {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self.0 {
            0x014C => write!(f, "i386"),
            0x8664 => write!(f, "AMD64"),
            0x01C0 => write!(f, "ARM"),
            0xAA64 => write!(f, "ARM64"),
            0x01C4 => write!(f, "ARMv7"),
            other => write!(f, "0x{other:04X}"),
        }
    }
}

impl From<u16> for Machine {
    fn from(v: u16) -> Self {
        Self(v)
    }
}

/// PE subsystem wrapper with human-readable Display.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct Subsystem(pub u16);

impl fmt::Display for Subsystem {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self.0 {
            1 => write!(f, "Native"),
            2 => write!(f, "Windows GUI"),
            3 => write!(f, "Windows CUI"),
            9 => write!(f, "Windows CE GUI"),
            other => write!(f, "0x{other:04X}"),
        }
    }
}

impl From<u16> for Subsystem {
    fn from(v: u16) -> Self {
        Self(v)
    }
}

/// PE COFF characteristics bitfield wrapper with Display.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct PeCharacteristics(pub u16);

impl fmt::Display for PeCharacteristics {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        let mut parts = Vec::new();
        if self.0 & 0x0002 != 0 {
            parts.push("Executable");
        }
        if self.0 & 0x0020 != 0 {
            parts.push("LargeAddressAware");
        }
        if self.0 & 0x0100 != 0 {
            parts.push("32Bit");
        }
        if self.0 & 0x2000 != 0 {
            parts.push("DLL");
        }
        if parts.is_empty() {
            write!(f, "0x{:04X}", self.0)
        } else {
            write!(f, "{}", parts.join(", "))
        }
    }
}

impl From<u16> for PeCharacteristics {
    fn from(v: u16) -> Self {
        Self(v)
    }
}

newtype_ops!(Machine, u16);
newtype_ops!(Subsystem, u16);
newtype_ops!(PeCharacteristics, u16);

/// PE file format constants
pub mod constants {
    /// Size of the COR20 (.NET CLR) header in bytes per ECMA-335 §II.25.3.3.
    ///
    /// The COR20 header (also known as CLI header or CLR runtime header) is a fixed-size
    /// 72-byte structure that describes the .NET assembly's metadata location, entry point,
    /// and runtime requirements. This size has remained constant across all .NET versions.
    ///
    /// Key fields within the 72-byte header:
    /// - Bytes 0-3: Header size (always 72)
    /// - Bytes 4-5: Major runtime version
    /// - Bytes 6-7: Minor runtime version
    /// - Bytes 8-15: Metadata RVA and size
    /// - Bytes 16-19: Flags
    /// - Bytes 20-23: Entry point token
    /// - Remaining bytes: Resources, strong name, code manager, etc.
    pub const COR20_HEADER_SIZE: u32 = 72;

    /// Section characteristic: IMAGE_SCN_MEM_EXECUTE
    pub const IMAGE_SCN_MEM_EXECUTE: u32 = 0x2000_0000;

    /// Section characteristic: IMAGE_SCN_CNT_INITIALIZED_DATA | IMAGE_SCN_MEM_READ
    pub const IMAGE_SCN_METADATA: u32 = 0x4000_0040;

    /// Maximum reasonable RVA value for validation
    pub const MAX_REASONABLE_RVA: u32 = 0x1000_0000;

    /// Size of the `ImageResourceDirectory` structure in bytes.
    pub const IMAGE_RESOURCE_DIRECTORY_SIZE: usize = 16;

    /// Size of a `ResourceEntry` structure in bytes.
    pub const RESOURCE_ENTRY_SIZE: usize = 8;

    /// Size of a `ResourceDataEntry` structure in bytes.
    pub const RESOURCE_DATA_ENTRY_SIZE: usize = 16;

    /// Indicates that the resource entry's offset points to a subdirectory.
    /// Used in `ResourceEntry::offset_to_data_or_directory`.
    pub const IMAGE_RESOURCE_DATA_IS_DIRECTORY: u32 = 0x8000_0000;

    /// Indicates that the resource entry's name is a string offset.
    /// Used in `ResourceEntry::name_or_id`.
    pub const IMAGE_RESOURCE_NAME_IS_STRING: u32 = 0x8000_0000;

    /// Mask to extract the offset/ID value from resource entry fields.
    pub const IMAGE_RESOURCE_MASK: u32 = 0x7FFF_FFFF;
}

use constants::{IMAGE_RESOURCE_DIRECTORY_SIZE, RESOURCE_DATA_ENTRY_SIZE, RESOURCE_ENTRY_SIZE};

/// Owned PE file representation that doesn't require borrowing from source data.
///
/// This struct contains all the essential PE file information needed for both
/// analysis and generation operations. Unlike goblin's PE struct which borrows
/// from the source data, this structure owns all its data, eliminating lifetime
/// dependencies and enabling flexible usage patterns.
///
/// The structure is designed to support the write pipeline by providing binary
/// serialization methods for all PE components.
#[derive(Debug, Clone)]
pub struct Pe {
    /// DOS header information
    pub dos_header: DosHeader,

    /// COFF header with machine type and characteristics
    pub coff_header: CoffHeader,

    /// Optional header with Windows-specific fields and data directories
    pub optional_header: Option<OptionalHeader>,

    /// Section table entries
    pub sections: Vec<SectionTable>,

    /// Computed image base address
    pub image_base: u64,

    /// Whether this is a 64-bit PE file
    pub is_64bit: bool,

    /// Imported symbols and DLLs
    pub imports: Vec<Import>,

    /// Exported symbols
    pub exports: Vec<Export>,

    /// List of imported library names
    pub libraries: Vec<String>,

    /// Data directories as owned map for easy lookup
    pub data_directories: HashMap<DataDirectoryType, DataDirectory>,
}

/// Owned DOS header structure.
#[derive(Debug, Clone)]
pub struct DosHeader {
    /// DOS signature (usually "MZ")
    pub signature: u16,
    /// Number of bytes on last page of file
    pub bytes_on_last_page: u16,
    /// Number of pages in file
    pub pages_in_file: u16,
    /// Number of relocation entries
    pub relocations: u16,
    /// Size of header in paragraphs
    pub size_of_header_paragraphs: u16,
    /// Minimum extra paragraphs needed
    pub minimum_extra_paragraphs: u16,
    /// Maximum extra paragraphs needed
    pub maximum_extra_paragraphs: u16,
    /// Initial relative SS value
    pub initial_relative_ss: u16,
    /// Initial SP value
    pub initial_sp: u16,
    /// Checksum
    pub checksum: u16,
    /// Initial IP value
    pub initial_ip: u16,
    /// Initial relative CS value
    pub initial_relative_cs: u16,
    /// Address of relocation table
    pub address_of_relocation_table: u16,
    /// Overlay number
    pub overlay_number: u16,
    /// PE header offset
    pub pe_header_offset: u32,
}

/// Owned COFF header structure.
#[derive(Debug, Clone)]
pub struct CoffHeader {
    /// Machine type (e.g., IMAGE_FILE_MACHINE_I386, IMAGE_FILE_MACHINE_AMD64)
    pub machine: Machine,
    /// Number of sections
    pub number_of_sections: u16,
    /// Time and date stamp
    pub time_date_stamp: u32,
    /// File pointer to symbol table
    pub pointer_to_symbol_table: u32,
    /// Number of symbols
    pub number_of_symbols: u32,
    /// Size of optional header
    pub size_of_optional_header: u16,
    /// Characteristics flags
    pub characteristics: PeCharacteristics,
}

/// Owned optional header structure.
#[derive(Debug, Clone)]
pub struct OptionalHeader {
    /// Standard fields (PE32/PE32+ common)
    pub standard_fields: StandardFields,
    /// Windows-specific fields
    pub windows_fields: WindowsFields,
    /// Data directories
    pub data_directories: DataDirectories,
}

/// Standard fields common to PE32 and PE32+.
#[derive(Debug, Clone)]
pub struct StandardFields {
    /// Magic number (0x10b for PE32, 0x20b for PE32+)
    pub magic: u16,
    /// Major linker version
    pub major_linker_version: u8,
    /// Minor linker version  
    pub minor_linker_version: u8,
    /// Size of code section
    pub size_of_code: u32,
    /// Size of initialized data
    pub size_of_initialized_data: u32,
    /// Size of uninitialized data
    pub size_of_uninitialized_data: u32,
    /// Address of entry point
    pub address_of_entry_point: u32,
    /// Base of code section
    pub base_of_code: u32,
    /// Base of data section (PE32 only)
    pub base_of_data: Option<u32>,
}

/// Windows-specific fields.
#[derive(Debug, Clone)]
pub struct WindowsFields {
    /// Image base address
    pub image_base: u64,
    /// Section alignment in memory
    pub section_alignment: u32,
    /// File alignment
    pub file_alignment: u32,
    /// Major OS version
    pub major_operating_system_version: u16,
    /// Minor OS version
    pub minor_operating_system_version: u16,
    /// Major image version
    pub major_image_version: u16,
    /// Minor image version
    pub minor_image_version: u16,
    /// Major subsystem version
    pub major_subsystem_version: u16,
    /// Minor subsystem version
    pub minor_subsystem_version: u16,
    /// Win32 version value
    pub win32_version_value: u32,
    /// Size of image
    pub size_of_image: u32,
    /// Size of headers
    pub size_of_headers: u32,
    /// Checksum
    pub checksum: u32,
    /// Subsystem
    pub subsystem: Subsystem,
    /// DLL characteristics
    pub dll_characteristics: u16,
    /// Size of stack reserve
    pub size_of_stack_reserve: u64,
    /// Size of stack commit
    pub size_of_stack_commit: u64,
    /// Size of heap reserve
    pub size_of_heap_reserve: u64,
    /// Size of heap commit
    pub size_of_heap_commit: u64,
    /// Loader flags
    pub loader_flags: u32,
    /// Number of RVA and sizes
    pub number_of_rva_and_sizes: u32,
}

/// Data directories as an owned map for easy lookup.
#[derive(Debug, Clone)]
pub struct DataDirectories {
    directories: HashMap<DataDirectoryType, DataDirectory>,
}

/// Data directory entry.
#[derive(Debug, Clone, Copy)]
pub struct DataDirectory {
    /// Virtual address of the data
    pub virtual_address: u32,
    /// Size of the data
    pub size: u32,
}

/// Data directory types.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum DataDirectoryType {
    /// Export table directory.
    ExportTable = 0,
    /// Import table directory.
    ImportTable = 1,
    /// Resource table directory.
    ResourceTable = 2,
    /// Exception table directory.
    ExceptionTable = 3,
    /// Certificate table directory.
    CertificateTable = 4,
    /// Base relocation table directory.
    BaseRelocationTable = 5,
    /// Debug directory.
    Debug = 6,
    /// Architecture-specific data directory.
    Architecture = 7,
    /// Global pointer directory.
    GlobalPtr = 8,
    /// Thread local storage table directory.
    TlsTable = 9,
    /// Load configuration table directory.
    LoadConfigTable = 10,
    /// Bound import table directory.
    BoundImport = 11,
    /// Import address table directory.
    ImportAddressTable = 12,
    /// Delay import descriptor directory.
    DelayImportDescriptor = 13,
    /// CLR runtime header directory.
    ClrRuntimeHeader = 14,
    /// Reserved directory entry.
    Reserved = 15,
}

/// Owned section table entry.
#[derive(Debug, Clone)]
pub struct SectionTable {
    /// Section name (up to 8 bytes)
    pub name: String,
    /// Virtual size
    pub virtual_size: u32,
    /// Virtual address (RVA)
    pub virtual_address: u32,
    /// Size of raw data
    pub size_of_raw_data: u32,
    /// Pointer to raw data
    pub pointer_to_raw_data: u32,
    /// Pointer to relocations
    pub pointer_to_relocations: u32,
    /// Pointer to line numbers
    pub pointer_to_line_numbers: u32,
    /// Number of relocations
    pub number_of_relocations: u16,
    /// Number of line numbers
    pub number_of_line_numbers: u16,
    /// Section characteristics
    pub characteristics: u32,
}

/// Import entry representing a function imported from an external DLL.
///
/// This structure serves as the single source of truth for both PE parsing and metadata
/// processing, eliminating the need for type conversion between different layers of the
/// system. It captures all information needed to resolve and call imported functions
/// at runtime through the Windows PE loader.
///
/// # Import Resolution Mechanism
///
/// Windows PE imports use a two-table system:
/// - **Import Lookup Table (ILT)**: Template containing original import information
/// - **Import Address Table (IAT)**: Runtime-patched table with actual function addresses
///
/// The loader patches the IAT at runtime, replacing import descriptors with actual
/// function addresses from the target DLL.
///
/// # Import Types
///
/// Functions can be imported in two ways:
/// - **By Name**: Using function name and optional hint for optimization
/// - **By Ordinal**: Using only ordinal number (more efficient but less portable)
///
/// # Field Relationships
///
/// - `name` and `ordinal` are mutually exclusive (one will be None)
/// - `rva` points to the slot in the Import Address Table
/// - `hint` optimizes name lookups in the target DLL's export table
/// - `ilt_value` preserves the original Import Lookup Table entry value
#[derive(Debug, Clone)]
pub struct Import {
    /// Name of the DLL containing the imported function (e.g., "kernel32.dll")
    pub dll: String,
    /// Function name if imported by name (None for ordinal-only imports)
    pub name: Option<String>,
    /// Ordinal number if imported by ordinal (None for name-only imports)
    pub ordinal: Option<u16>,
    /// Relative Virtual Address of the Import Address Table slot for this import
    pub rva: u32,
    /// Hint value for optimizing name lookups in the target DLL's export table (0 if unavailable)
    pub hint: u16,
    /// Original Import Lookup Table entry value preserving import metadata (0 if unavailable)
    pub ilt_value: u64,
}

/// Owned export entry.
#[derive(Debug, Clone)]
pub struct Export {
    /// Function name (None for ordinal-only exports)
    pub name: Option<String>,
    /// Export RVA
    pub rva: u32,
    /// Ordinal offset for ordinal calculation
    pub offset: Option<u32>,
}

impl Pe {
    /// Create Pe from goblin PE structure.
    ///
    /// # Errors
    ///
    /// Returns an error if the PE structure contains invalid data or if conversion fails.
    /// Validation includes:
    /// - Presence of optional header
    /// - Image base is non-zero
    pub fn from_goblin_pe(goblin_pe: &goblin::pe::PE) -> Result<Self> {
        let dos_header = DosHeader::from_goblin(&goblin_pe.header.dos_header);
        let coff_header = CoffHeader::from_goblin(&goblin_pe.header.coff_header);
        let optional_header = goblin_pe
            .header
            .optional_header
            .as_ref()
            .map(OptionalHeader::from_goblin)
            .transpose()?;

        if optional_header.is_none() {
            return Err(malformed_error!("File does not have an OptionalHeader"));
        }

        if goblin_pe.image_base == 0 {
            return Err(malformed_error!("PE has invalid zero image base"));
        }

        let sections = goblin_pe
            .sections
            .iter()
            .map(SectionTable::from_goblin)
            .collect::<Result<Vec<_>>>()?;

        let imports = goblin_pe
            .imports
            .iter()
            .map(Import::from_goblin)
            .collect::<Result<Vec<_>>>()?;

        let exports = goblin_pe
            .exports
            .iter()
            .map(Export::from_goblin)
            .collect::<Result<Vec<_>>>()?;

        let libraries = goblin_pe.libraries.iter().map(|&s| s.to_string()).collect();

        let data_directories = optional_header
            .as_ref()
            .map_or_else(DataDirectories::new, |oh| oh.data_directories.clone());

        Ok(Pe {
            dos_header,
            coff_header,
            optional_header,
            sections,
            image_base: goblin_pe.image_base,
            is_64bit: goblin_pe.is_64,
            imports,
            exports,
            libraries,
            data_directories: data_directories.directories,
        })
    }

    /// Write DOS header to buffer.
    ///
    /// # Errors
    ///
    /// Returns an error if writing to the buffer fails.
    pub fn write_dos_header<W: Write>(&self, writer: &mut W) -> Result<()> {
        self.dos_header.write_to(writer)
    }

    /// Write PE signature and COFF header to buffer.
    ///
    /// # Errors
    ///
    /// Returns an error if writing to the buffer fails.
    pub fn write_pe_headers<W: Write>(&self, writer: &mut W) -> Result<()> {
        // PE signature
        writer.write_all(b"PE\x00\x00")?;

        // COFF header
        self.coff_header.write_to(writer)?;

        // Optional header
        if let Some(ref oh) = self.optional_header {
            oh.write_to(writer)?;
        }

        Ok(())
    }

    /// Write section table to buffer.
    ///
    /// # Errors
    ///
    /// Returns an error if writing to the buffer fails.
    pub fn write_section_table<W: Write>(&self, writer: &mut W) -> Result<()> {
        for section in &self.sections {
            section.write_to(writer)?;
        }
        Ok(())
    }

    /// Get data directory by type.
    #[must_use]
    pub fn get_data_directory(&self, dir_type: DataDirectoryType) -> Option<DataDirectory> {
        self.data_directories.get(&dir_type).copied()
    }

    /// Get CLR runtime header directory.
    #[must_use]
    pub fn get_clr_runtime_header(&self) -> Option<DataDirectory> {
        self.get_data_directory(DataDirectoryType::ClrRuntimeHeader)
    }

    /// Calculates the total size of PE headers (PE signature + COFF header + Optional header).
    ///
    /// This method computes the complete size needed for all PE headers based on
    /// the actual header contents, which is useful for layout planning during write operations.
    ///
    /// # Returns
    /// Total size in bytes of all PE headers
    #[must_use]
    pub fn calculate_headers_size(&self) -> u64 {
        // PE signature (4 bytes) + COFF header (20 bytes) + optional header size
        let optional_header_size = self
            .optional_header
            .as_ref()
            .map_or(0, |_| u64::from(self.coff_header.size_of_optional_header));

        4 + CoffHeader::SIZE as u64 + optional_header_size
    }

    /// Calculates the total size of all file headers (DOS header + PE headers).
    ///
    /// This method computes the complete size needed for DOS header plus all PE headers,
    /// which is useful for file layout calculations where the total header space is needed.
    ///
    /// # Returns
    /// Total size in bytes of DOS header + PE headers
    #[must_use]
    pub fn calculate_total_file_headers_size(&self) -> u64 {
        DosHeader::SIZE as u64 + self.calculate_headers_size()
    }

    /// Calculates the total size of all current sections' raw data.
    ///
    /// This method sums the `size_of_raw_data` field from all sections, which represents
    /// the total space occupied by section content in the file.
    ///
    /// # Returns
    /// Total size in bytes of all section raw data
    #[must_use]
    pub fn get_sections_total_raw_data_size(&self) -> u64 {
        self.sections
            .iter()
            .map(|section| u64::from(section.size_of_raw_data))
            .sum()
    }

    /// Gets the PE headers offset from the DOS header.
    ///
    /// # Returns
    /// Offset where PE headers start in the file
    #[must_use]
    pub fn get_pe_headers_offset(&self) -> u64 {
        u64::from(self.dos_header.pe_header_offset)
    }

    /// Gets the file alignment from the original PE headers.
    ///
    /// # Returns
    /// File alignment in bytes from the original PE headers
    #[must_use]
    pub fn get_file_alignment(&self) -> u64 {
        self.optional_header
            .as_ref()
            .map_or(0x200, |oh| u64::from(oh.windows_fields.file_alignment)) // Fallback to common default
    }

    /// Gets the section alignment from the original PE headers.
    ///
    /// # Returns
    /// Section alignment in bytes from the original PE headers
    #[must_use]
    pub fn get_section_alignment(&self) -> u64 {
        self.optional_header
            .as_ref()
            .map_or(0x1000, |oh| u64::from(oh.windows_fields.section_alignment))
        // Fallback to common default
    }

    /// Adds a new section to the PE file.
    ///
    /// This method adds a new section entry and automatically updates the section count
    /// in the COFF header to maintain consistency.
    ///
    /// # Arguments
    /// * `section` - The section to add
    pub fn add_section(&mut self, section: SectionTable) {
        self.sections.push(section);
        if let Ok(section_count) = u16::try_from(self.sections.len()) {
            self.coff_header.update_section_count(section_count);
        }
    }

    /// Removes a section by name from the PE file.
    ///
    /// This method removes the first section with the given name and automatically
    /// updates the section count in the COFF header.
    ///
    /// # Arguments
    /// * `name` - The name of the section to remove
    ///
    /// # Returns
    /// Returns `true` if a section was removed, `false` if no section with the given name was found
    pub fn remove_section(&mut self, name: &str) -> bool {
        if let Some(index) = self.sections.iter().position(|s| s.name == name) {
            self.sections.remove(index);
            if let Ok(section_count) = u16::try_from(self.sections.len()) {
                self.coff_header.update_section_count(section_count);
            }
            true
        } else {
            false
        }
    }

    /// Finds a mutable reference to a section by name.
    ///
    /// This allows direct modification of section properties while maintaining
    /// the section within the PE structure.
    ///
    /// # Arguments
    /// * `name` - The name of the section to find
    ///
    /// # Returns
    /// Returns a mutable reference to the section if found, None otherwise
    pub fn get_section_mut(&mut self, name: &str) -> Option<&mut SectionTable> {
        self.sections.iter_mut().find(|s| s.name == name)
    }

    /// Finds a reference to a section by name.
    ///
    /// # Arguments
    /// * `name` - The name of the section to find
    ///
    /// # Returns
    /// Returns a reference to the section if found, None otherwise
    #[must_use]
    pub fn get_section(&self, name: &str) -> Option<&SectionTable> {
        self.sections.iter().find(|s| s.name == name)
    }

    /// Updates the CLR runtime header data directory.
    ///
    /// This method updates the CLR data directory entry to point to a new location,
    /// maintaining consistency between the optional header and main data directories map.
    ///
    /// # Arguments
    /// * `rva` - The new RVA for the CLR runtime header
    /// * `size` - The new size of the CLR runtime header
    ///
    /// # Errors
    /// Returns an error if the PE has no optional header
    pub fn update_clr_data_directory(&mut self, rva: u32, size: u32) -> Result<()> {
        if let Some(ref mut optional_header) = self.optional_header {
            optional_header.data_directories.update_clr_entry(rva, size);
            // Also update the main data_directories map
            self.data_directories.insert(
                DataDirectoryType::ClrRuntimeHeader,
                DataDirectory {
                    virtual_address: rva,
                    size,
                },
            );
            Ok(())
        } else {
            Err(malformed_error!(
                "Cannot update CLR data directory: PE has no optional header"
            ))
        }
    }

    /// Updates a specific data directory entry.
    ///
    /// This method updates any data directory entry while maintaining consistency
    /// between the optional header and main data directories map.
    ///
    /// # Arguments
    /// * `dir_type` - The type of data directory to update
    /// * `rva` - The new RVA for the directory
    /// * `size` - The new size of the directory
    ///
    /// # Errors
    /// Returns an error if the PE has no optional header
    pub fn update_data_directory(
        &mut self,
        dir_type: DataDirectoryType,
        rva: u32,
        size: u32,
    ) -> Result<()> {
        if let Some(ref mut optional_header) = self.optional_header {
            optional_header
                .data_directories
                .update_entry(dir_type, rva, size);
            // Also update the main data_directories map
            self.data_directories.insert(
                dir_type,
                DataDirectory {
                    virtual_address: rva,
                    size,
                },
            );
            Ok(())
        } else {
            Err(malformed_error!(
                "Cannot update data directory: PE has no optional header"
            ))
        }
    }

    /// Updates the SizeOfImage field in the PE optional header.
    ///
    /// SizeOfImage must be updated when sections are added or modified to ensure
    /// the PE image size encompasses all sections. This value represents the total
    /// size of the image when loaded in memory, including all sections aligned to
    /// the section alignment boundary.
    ///
    /// # Arguments
    /// * `new_size` - The new SizeOfImage value
    ///
    /// # Errors
    /// Returns an error if the PE has no optional header
    pub fn update_size_of_image(&mut self, new_size: u32) -> Result<()> {
        if let Some(ref mut optional_header) = self.optional_header {
            optional_header.windows_fields.size_of_image = new_size;
            Ok(())
        } else {
            Err(malformed_error!(
                "Cannot update SizeOfImage: PE has no optional header"
            ))
        }
    }

    /// Updates the SizeOfHeaders field in the PE optional header.
    ///
    /// SizeOfHeaders must be updated when sections are added to ensure the value
    /// encompasses all headers including the expanded section table. This value
    /// represents the combined size of DOS header, PE headers, and section table,
    /// rounded up to FileAlignment.
    ///
    /// # Arguments
    /// * `new_size` - The new SizeOfHeaders value (must be aligned to FileAlignment)
    ///
    /// # Errors
    /// Returns an error if the PE has no optional header
    pub fn update_size_of_headers(&mut self, new_size: u32) -> Result<()> {
        if let Some(ref mut optional_header) = self.optional_header {
            optional_header.windows_fields.size_of_headers = new_size;
            Ok(())
        } else {
            Err(malformed_error!(
                "Cannot update SizeOfHeaders: PE has no optional header"
            ))
        }
    }

    /// Writes the complete PE headers in their current state.
    ///
    /// This method serializes the PE signature, COFF header, and optional header
    /// using their current values. No modifications are made during the write operation.
    ///
    /// # Arguments
    /// * `writer` - Writer to output the headers to
    ///
    /// # Errors
    /// Returns an error if writing fails
    pub fn write_headers<W: Write>(&self, writer: &mut W) -> Result<()> {
        // Write PE signature
        writer.write_all(b"PE\x00\x00")?;

        // Write COFF header in current state
        self.coff_header.write_to(writer)?;

        // Write optional header in current state
        if let Some(ref optional_header) = self.optional_header {
            optional_header.write_to(writer)?;
        }

        Ok(())
    }

    /// Writes all section headers in their current state.
    ///
    /// This method serializes all sections in the sections vector using their
    /// current values. The section count in the COFF header should already reflect
    /// the correct number of sections.
    ///
    /// # Arguments
    /// * `writer` - Writer to output the section table to
    ///
    /// # Errors
    /// Returns an error if writing fails
    pub fn write_section_headers<W: Write>(&self, writer: &mut W) -> Result<()> {
        for section in &self.sections {
            section.write_to(writer)?;
        }
        Ok(())
    }
}

impl DosHeader {
    /// Size of DOS header in bytes.
    pub const SIZE: usize = 64;

    /// Size of standard DOS header with stub (128 bytes per ECMA-335 §II.25.2.1).
    pub const STANDARD_SIZE: usize = 128;

    /// Standard DOS header with stub from ECMA-335 Partition II §25.2.1.
    ///
    /// This 128-byte block contains the DOS MZ header and a minimal DOS stub that
    /// prints "This program cannot be run in DOS mode." and exits. The e_lfanew
    /// field at offset 0x3C points to offset 0x80 (128) where the PE header begins.
    ///
    /// This is the canonical DOS header used by all .NET assemblies and matches
    /// what the CLR runtime expects. Using this standard header ensures maximum
    /// compatibility with all .NET runtime implementations.
    #[rustfmt::skip]
    pub const STANDARD_DOS_HEADER: [u8; 128] = [
        // DOS Header (64 bytes)
        0x4D, 0x5A, 0x90, 0x00, 0x03, 0x00, 0x00, 0x00, // MZ signature + header fields
        0x04, 0x00, 0x00, 0x00, 0xFF, 0xFF, 0x00, 0x00, // More header fields
        0xB8, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // Stack pointer, etc.
        0x40, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // Relocation table address
        0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // Reserved
        0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // Reserved
        0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // Reserved
        0x00, 0x00, 0x00, 0x00, 0x80, 0x00, 0x00, 0x00, // e_lfanew = 0x80 (offset 0x3C)
        // DOS Stub (64 bytes) - prints "This program cannot be run in DOS mode."
        0x0E, 0x1F, 0xBA, 0x0E, 0x00, 0xB4, 0x09, 0xCD, // PUSH CS; POP DS; MOV DX, 0x0E; MOV AH, 9; INT 21h
        0x21, 0xB8, 0x01, 0x4C, 0xCD, 0x21, 0x54, 0x68, // INT 21h; MOV AX, 0x4C01; INT 21h; "Th"
        0x69, 0x73, 0x20, 0x70, 0x72, 0x6F, 0x67, 0x72, // "is progr"
        0x61, 0x6D, 0x20, 0x63, 0x61, 0x6E, 0x6E, 0x6F, // "am canno"
        0x74, 0x20, 0x62, 0x65, 0x20, 0x72, 0x75, 0x6E, // "t be run"
        0x20, 0x69, 0x6E, 0x20, 0x44, 0x4F, 0x53, 0x20, // " in DOS "
        0x6D, 0x6F, 0x64, 0x65, 0x2E, 0x0D, 0x0D, 0x0A, // "mode.\r\r\n"
        0x24, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // "$" + padding
    ];

    fn from_goblin(goblin_dos: &goblin::pe::header::DosHeader) -> Self {
        Self {
            signature: goblin_dos.signature,
            bytes_on_last_page: goblin_dos.bytes_on_last_page,
            pages_in_file: goblin_dos.pages_in_file,
            relocations: goblin_dos.relocations,
            size_of_header_paragraphs: goblin_dos.size_of_header_in_paragraphs,
            minimum_extra_paragraphs: goblin_dos.minimum_extra_paragraphs_needed,
            maximum_extra_paragraphs: goblin_dos.maximum_extra_paragraphs_needed,
            initial_relative_ss: goblin_dos.initial_relative_ss,
            initial_sp: goblin_dos.initial_sp,
            checksum: goblin_dos.checksum,
            initial_ip: goblin_dos.initial_ip,
            initial_relative_cs: goblin_dos.initial_relative_cs,
            address_of_relocation_table: goblin_dos.file_address_of_relocation_table,
            overlay_number: goblin_dos.overlay_number,
            pe_header_offset: goblin_dos.pe_pointer,
        }
    }

    /// Writes this DOS header's fields to the writer.
    ///
    /// This writes just the 64-byte DOS header fields without the DOS stub.
    /// For most use cases, prefer [`Self::write_standard`] or [`Self::write_with_stub`]
    /// which include the required DOS stub.
    ///
    /// # Arguments
    ///
    /// * `writer` - The writer to output the DOS header fields to
    ///
    /// # Errors
    ///
    /// Returns an error if writing fails.
    pub fn write_to<W: Write>(&self, writer: &mut W) -> Result<()> {
        writer.write_all(&self.signature.to_le_bytes())?;
        writer.write_all(&self.bytes_on_last_page.to_le_bytes())?;
        writer.write_all(&self.pages_in_file.to_le_bytes())?;
        writer.write_all(&self.relocations.to_le_bytes())?;
        writer.write_all(&self.size_of_header_paragraphs.to_le_bytes())?;
        writer.write_all(&self.minimum_extra_paragraphs.to_le_bytes())?;
        writer.write_all(&self.maximum_extra_paragraphs.to_le_bytes())?;
        writer.write_all(&self.initial_relative_ss.to_le_bytes())?;
        writer.write_all(&self.initial_sp.to_le_bytes())?;
        writer.write_all(&self.checksum.to_le_bytes())?;
        writer.write_all(&self.initial_ip.to_le_bytes())?;
        writer.write_all(&self.initial_relative_cs.to_le_bytes())?;
        writer.write_all(&self.address_of_relocation_table.to_le_bytes())?;
        writer.write_all(&self.overlay_number.to_le_bytes())?;
        // Reserved fields (4 words)
        for _ in 0..4 {
            writer.write_all(&0u16.to_le_bytes())?;
        }
        // OEM fields
        writer.write_all(&0u16.to_le_bytes())?; // OEM identifier
        writer.write_all(&0u16.to_le_bytes())?; // OEM information
                                                // Reserved2 fields (10 words)
        for _ in 0..10 {
            writer.write_all(&0u16.to_le_bytes())?;
        }
        writer.write_all(&self.pe_header_offset.to_le_bytes())?;

        Ok(())
    }

    /// Writes the standard DOS header with stub.
    ///
    /// This writes the canonical 128-byte DOS header from ECMA-335 Partition II §25.2.1,
    /// which includes the DOS MZ header and a stub that prints "This program cannot be
    /// run in DOS mode." This is the standard header used by all .NET assemblies.
    ///
    /// # Arguments
    ///
    /// * `writer` - The writer to output the DOS header to
    ///
    /// # Errors
    ///
    /// Returns an error if writing fails.
    ///
    /// # Example
    ///
    /// ```rust,no_run
    /// use dotscope::DosHeader;
    ///
    /// let mut writer = Vec::new();
    /// DosHeader::write_standard(&mut writer)?;
    /// # Ok::<(), dotscope::Error>(())
    /// ```
    pub fn write_standard<W: Write>(writer: &mut W) -> Result<()> {
        writer.write_all(&Self::STANDARD_DOS_HEADER)?;
        Ok(())
    }

    /// Writes this DOS header instance followed by the standard DOS stub.
    ///
    /// Unlike [`Self::write_standard`], this method writes the current header's field values
    /// followed by the DOS stub. This is useful when preserving an existing header's
    /// specific field values while regenerating the file.
    ///
    /// The total size written is 128 bytes (64-byte header + 64-byte stub).
    ///
    /// # Arguments
    ///
    /// * `writer` - The writer to output the DOS header to
    ///
    /// # Errors
    ///
    /// Returns an error if writing fails.
    pub fn write_with_stub<W: Write>(&self, writer: &mut W) -> Result<()> {
        // Write the DOS header fields
        self.write_to(writer)?;

        // Write DOS stub (64 bytes starting at offset 64)
        writer.write_all(&Self::STANDARD_DOS_HEADER[64..128])?;

        Ok(())
    }
}

impl CoffHeader {
    /// Size of COFF header in bytes (20 bytes).
    pub const SIZE: usize = 20;

    fn from_goblin(goblin_coff: &goblin::pe::header::CoffHeader) -> Self {
        Self {
            machine: Machine(goblin_coff.machine),
            number_of_sections: goblin_coff.number_of_sections,
            time_date_stamp: goblin_coff.time_date_stamp,
            pointer_to_symbol_table: goblin_coff.pointer_to_symbol_table,
            number_of_symbols: goblin_coff.number_of_symbol_table,
            size_of_optional_header: goblin_coff.size_of_optional_header,
            characteristics: PeCharacteristics(goblin_coff.characteristics),
        }
    }

    /// Updates the number of sections in the COFF header.
    ///
    /// This method is used during write operations when adding new sections
    /// (like the .meta section) to ensure the COFF header reflects the
    /// correct section count.
    ///
    /// # Arguments
    /// * `new_count` - The new number of sections
    pub fn update_section_count(&mut self, new_count: u16) {
        self.number_of_sections = new_count;
    }

    /// Updates the size of optional header field in the COFF header.
    ///
    /// This method is used during write operations when the optional header
    /// size changes to ensure the COFF header reflects the correct size.
    ///
    /// # Arguments
    /// * `new_size` - The new size of the optional header in bytes
    pub fn update_optional_header_size(&mut self, new_size: u16) {
        self.size_of_optional_header = new_size;
    }

    /// Writes this COFF header to the writer.
    ///
    /// The COFF header is 20 bytes and immediately follows the PE signature ("PE\0\0").
    /// It describes the target machine architecture, number of sections, and file characteristics.
    ///
    /// # Arguments
    ///
    /// * `writer` - The writer to output the COFF header to
    ///
    /// # Errors
    ///
    /// Returns an error if writing fails.
    pub fn write_to<W: Write>(&self, writer: &mut W) -> Result<()> {
        writer.write_all(&self.machine.to_le_bytes())?;
        writer.write_all(&self.number_of_sections.to_le_bytes())?;
        writer.write_all(&self.time_date_stamp.to_le_bytes())?;
        writer.write_all(&self.pointer_to_symbol_table.to_le_bytes())?;
        writer.write_all(&self.number_of_symbols.to_le_bytes())?;
        writer.write_all(&self.size_of_optional_header.to_le_bytes())?;
        writer.write_all(&self.characteristics.to_le_bytes())?;

        Ok(())
    }
}

impl OptionalHeader {
    fn from_goblin(goblin_oh: &goblin::pe::optional_header::OptionalHeader) -> Result<Self> {
        let standard_fields = StandardFields::from_goblin(&goblin_oh.standard_fields)?;
        let windows_fields = WindowsFields::from_goblin(&goblin_oh.windows_fields);
        let data_directories = DataDirectories::from_goblin(&goblin_oh.data_directories);

        Ok(Self {
            standard_fields,
            windows_fields,
            data_directories,
        })
    }

    /// Writes this optional header to the writer.
    ///
    /// The optional header contains the PE format magic, linker version, code/data sizes,
    /// entry point, image base, alignments, subsystem info, and all 16 data directories.
    ///
    /// # Arguments
    ///
    /// * `writer` - The writer to output the optional header to
    ///
    /// # Errors
    ///
    /// Returns an error if:
    /// - The magic value is invalid (not 0x10b or 0x20b)
    /// - Writing fails
    pub fn write_to<W: Write>(&self, writer: &mut W) -> Result<()> {
        let is_pe32_plus = match self.standard_fields.magic {
            0x10b => false, // PE32
            0x20b => true,  // PE32+
            magic => {
                return Err(malformed_error!(
                    "Invalid PE optional header magic: 0x{:x} (expected 0x10b or 0x20b)",
                    magic
                ))
            }
        };

        self.standard_fields.write_to(writer)?;
        self.windows_fields.write_to(writer, is_pe32_plus)?;
        self.data_directories.write_to(writer)?;

        Ok(())
    }

    /// Returns the serialized size of this optional header in bytes.
    ///
    /// The size varies based on PE format:
    /// - PE32 (magic 0x10b): 224 bytes (28 standard + 68 windows + 128 data dirs)
    /// - PE32+ (magic 0x20b): 240 bytes (24 standard + 88 windows + 128 data dirs)
    #[must_use]
    pub fn size(&self) -> usize {
        Self::size_for_format(self.standard_fields.magic == 0x20b)
    }

    /// Returns the serialized size of an optional header for the given PE format.
    ///
    /// # Arguments
    ///
    /// * `is_pe32_plus` - `true` for PE32+ (64-bit), `false` for PE32 (32-bit)
    #[must_use]
    pub const fn size_for_format(is_pe32_plus: bool) -> usize {
        StandardFields::SIZE_FOR_FORMAT[is_pe32_plus as usize]
            + WindowsFields::SIZE_FOR_FORMAT[is_pe32_plus as usize]
            + DataDirectories::SIZE
    }
}

impl StandardFields {
    /// Size of standard fields: [PE32, PE32+]
    /// - PE32: 28 bytes (includes base_of_data)
    /// - PE32+: 24 bytes (no base_of_data)
    pub const SIZE_FOR_FORMAT: [usize; 2] = [28, 24];

    fn from_goblin(goblin_sf: &goblin::pe::optional_header::StandardFields) -> Result<Self> {
        Ok(Self {
            magic: goblin_sf.magic,
            major_linker_version: goblin_sf.major_linker_version,
            minor_linker_version: goblin_sf.minor_linker_version,
            size_of_code: u32::try_from(goblin_sf.size_of_code)
                .map_err(|_| malformed_error!("PE size_of_code value too large"))?,
            size_of_initialized_data: u32::try_from(goblin_sf.size_of_initialized_data)
                .map_err(|_| malformed_error!("PE size_of_initialized_data value too large"))?,
            size_of_uninitialized_data: u32::try_from(goblin_sf.size_of_uninitialized_data)
                .map_err(|_| malformed_error!("PE size_of_uninitialized_data value too large"))?,
            address_of_entry_point: goblin_sf.address_of_entry_point,
            base_of_code: u32::try_from(goblin_sf.base_of_code)
                .map_err(|_| malformed_error!("PE base_of_code value too large"))?,
            base_of_data: if goblin_sf.magic == 0x10b {
                Some(goblin_sf.base_of_data)
            } else {
                None
            },
        })
    }

    /// Writes this standard fields structure to the writer.
    ///
    /// # Arguments
    ///
    /// * `writer` - The writer to output the standard fields to
    ///
    /// # Errors
    ///
    /// Returns an error if writing fails or if PE32 format is missing `base_of_data`.
    pub fn write_to<W: Write>(&self, writer: &mut W) -> Result<()> {
        writer.write_all(&self.magic.to_le_bytes())?;
        writer.write_all(&self.major_linker_version.to_le_bytes())?;
        writer.write_all(&self.minor_linker_version.to_le_bytes())?;
        writer.write_all(&self.size_of_code.to_le_bytes())?;
        writer.write_all(&self.size_of_initialized_data.to_le_bytes())?;
        writer.write_all(&self.size_of_uninitialized_data.to_le_bytes())?;
        writer.write_all(&self.address_of_entry_point.to_le_bytes())?;
        writer.write_all(&self.base_of_code.to_le_bytes())?;

        // base_of_data only exists in PE32 (magic == 0x10b)
        if self.magic == 0x10b {
            if let Some(base_of_data) = self.base_of_data {
                writer.write_all(&base_of_data.to_le_bytes())?;
            } else {
                return Err(Error::Malformed {
                    message: "PE32 file missing base_of_data field".to_string(),
                    file: file!(),
                    line: line!(),
                });
            }
        }

        Ok(())
    }
}

impl WindowsFields {
    /// Size of Windows-specific fields: [PE32, PE32+]
    /// - PE32: 68 bytes (4-byte image_base and stack/heap sizes)
    /// - PE32+: 88 bytes (8-byte image_base and stack/heap sizes)
    pub const SIZE_FOR_FORMAT: [usize; 2] = [68, 88];

    fn from_goblin(goblin_wf: &goblin::pe::optional_header::WindowsFields) -> Self {
        Self {
            image_base: goblin_wf.image_base,
            section_alignment: goblin_wf.section_alignment,
            file_alignment: goblin_wf.file_alignment,
            major_operating_system_version: goblin_wf.major_operating_system_version,
            minor_operating_system_version: goblin_wf.minor_operating_system_version,
            major_image_version: goblin_wf.major_image_version,
            minor_image_version: goblin_wf.minor_image_version,
            major_subsystem_version: goblin_wf.major_subsystem_version,
            minor_subsystem_version: goblin_wf.minor_subsystem_version,
            win32_version_value: goblin_wf.win32_version_value,
            size_of_image: goblin_wf.size_of_image,
            size_of_headers: goblin_wf.size_of_headers,
            checksum: goblin_wf.check_sum,
            subsystem: Subsystem(goblin_wf.subsystem),
            dll_characteristics: goblin_wf.dll_characteristics,
            size_of_stack_reserve: goblin_wf.size_of_stack_reserve,
            size_of_stack_commit: goblin_wf.size_of_stack_commit,
            size_of_heap_reserve: goblin_wf.size_of_heap_reserve,
            size_of_heap_commit: goblin_wf.size_of_heap_commit,
            loader_flags: goblin_wf.loader_flags,
            number_of_rva_and_sizes: goblin_wf.number_of_rva_and_sizes,
        }
    }

    /// Writes this Windows-specific fields structure to the writer.
    ///
    /// # Arguments
    ///
    /// * `writer` - The writer to output the fields to
    /// * `is_pe32_plus` - `true` for PE32+ (64-bit), `false` for PE32 (32-bit)
    ///
    /// # Errors
    ///
    /// Returns an error if writing fails or if PE32 format has values exceeding u32 range.
    pub fn write_to<W: Write>(&self, writer: &mut W, is_pe32_plus: bool) -> Result<()> {
        // Write image_base with appropriate size
        if is_pe32_plus {
            writer.write_all(&self.image_base.to_le_bytes())?;
        } else {
            writer.write_all(
                &u32::try_from(self.image_base)
                    .map_err(|_| malformed_error!("Image base exceeds u32 range"))?
                    .to_le_bytes(),
            )?;
        }

        writer.write_all(&self.section_alignment.to_le_bytes())?;
        writer.write_all(&self.file_alignment.to_le_bytes())?;
        writer.write_all(&self.major_operating_system_version.to_le_bytes())?;
        writer.write_all(&self.minor_operating_system_version.to_le_bytes())?;
        writer.write_all(&self.major_image_version.to_le_bytes())?;
        writer.write_all(&self.minor_image_version.to_le_bytes())?;
        writer.write_all(&self.major_subsystem_version.to_le_bytes())?;
        writer.write_all(&self.minor_subsystem_version.to_le_bytes())?;
        writer.write_all(&self.win32_version_value.to_le_bytes())?;
        writer.write_all(&self.size_of_image.to_le_bytes())?;
        writer.write_all(&self.size_of_headers.to_le_bytes())?;
        writer.write_all(&self.checksum.to_le_bytes())?;
        writer.write_all(&self.subsystem.to_le_bytes())?;
        writer.write_all(&self.dll_characteristics.to_le_bytes())?;

        // Write stack/heap size fields with appropriate size based on PE format
        if is_pe32_plus {
            // PE32+: 8-byte fields
            writer.write_all(&self.size_of_stack_reserve.to_le_bytes())?;
            writer.write_all(&self.size_of_stack_commit.to_le_bytes())?;
            writer.write_all(&self.size_of_heap_reserve.to_le_bytes())?;
            writer.write_all(&self.size_of_heap_commit.to_le_bytes())?;
        } else {
            // PE32: 4-byte fields
            writer.write_all(
                &u32::try_from(self.size_of_stack_reserve)
                    .map_err(|_| malformed_error!("Stack reserve size exceeds u32 range"))?
                    .to_le_bytes(),
            )?;
            writer.write_all(
                &u32::try_from(self.size_of_stack_commit)
                    .map_err(|_| malformed_error!("Stack commit size exceeds u32 range"))?
                    .to_le_bytes(),
            )?;
            writer.write_all(
                &u32::try_from(self.size_of_heap_reserve)
                    .map_err(|_| malformed_error!("Heap reserve size exceeds u32 range"))?
                    .to_le_bytes(),
            )?;
            writer.write_all(
                &u32::try_from(self.size_of_heap_commit)
                    .map_err(|_| malformed_error!("Heap commit size exceeds u32 range"))?
                    .to_le_bytes(),
            )?;
        }

        writer.write_all(&self.loader_flags.to_le_bytes())?;

        writer.write_all(&self.number_of_rva_and_sizes.to_le_bytes())?;

        Ok(())
    }
}

impl Default for DataDirectories {
    fn default() -> Self {
        Self::new()
    }
}

impl DataDirectories {
    /// Number of data directory entries (16 per PE specification).
    pub const COUNT: usize = 16;

    /// Size of data directories in bytes (128 bytes = 16 entries × 8 bytes each).
    pub const SIZE: usize = Self::COUNT * 8;

    /// Creates a new empty `DataDirectories` structure.
    ///
    /// Use [`Self::update_entry`] to populate individual directory entries.
    #[must_use]
    pub fn new() -> Self {
        Self {
            directories: HashMap::new(),
        }
    }

    /// Get CLR runtime header directory.
    #[must_use]
    pub fn get_clr_runtime_header(&self) -> Option<&DataDirectory> {
        self.directories.get(&DataDirectoryType::ClrRuntimeHeader)
    }

    /// Updates a data directory entry.
    ///
    /// This method allows updating specific data directory entries during write
    /// operations, such as updating the CLR runtime header when adding new metadata.
    ///
    /// # Arguments
    /// * `dir_type` - The type of data directory to update
    /// * `rva` - The new RVA (Relative Virtual Address) for the directory
    /// * `size` - The new size in bytes for the directory
    ///
    /// # Examples
    /// ```rust,no_run
    /// use dotscope::{DataDirectories, DataDirectoryType};
    ///
    /// # let mut data_directories = DataDirectories::new();
    /// // Update CLR runtime header location
    /// data_directories.update_entry(
    ///     DataDirectoryType::ClrRuntimeHeader,
    ///     0x2000, // new RVA
    ///     72      // CLR header size
    /// );
    /// ```
    pub fn update_entry(&mut self, dir_type: DataDirectoryType, rva: u32, size: u32) {
        self.directories.insert(
            dir_type,
            DataDirectory {
                virtual_address: rva,
                size,
            },
        );
    }

    /// Updates the CLR runtime header data directory entry.
    ///
    /// This is a convenience method specifically for updating the CLR runtime header
    /// directory entry, which is commonly done during .NET assembly write operations.
    ///
    /// # Arguments
    /// * `rva` - The new RVA for the CLR runtime header
    /// * `size` - The new size of the CLR runtime header (typically 72 bytes)
    ///
    /// # Examples
    /// ```rust,no_run
    /// use dotscope::DataDirectories;
    ///
    /// # let mut data_directories = DataDirectories::new();
    /// // Update CLR header to point to new location
    /// data_directories.update_clr_entry(0x2000, 72);
    /// ```
    pub fn update_clr_entry(&mut self, rva: u32, size: u32) {
        self.update_entry(DataDirectoryType::ClrRuntimeHeader, rva, size);
    }

    fn from_goblin(goblin_dd: &goblin::pe::data_directories::DataDirectories) -> Self {
        let mut directories = HashMap::new();

        // Convert goblin data directories to our owned format
        // Note: We avoid using goblin_dd.dirs() because it can panic on malformed files
        // with invalid data directory indices. Instead, we manually iterate through
        // the valid range and handle errors gracefully.
        for (i, opt_entry) in goblin_dd.data_directories.iter().enumerate() {
            if let Some((_, dir_entry)) = opt_entry {
                let dir_type = match i {
                    0 => DataDirectoryType::ExportTable,
                    1 => DataDirectoryType::ImportTable,
                    2 => DataDirectoryType::ResourceTable,
                    3 => DataDirectoryType::ExceptionTable,
                    4 => DataDirectoryType::CertificateTable,
                    5 => DataDirectoryType::BaseRelocationTable,
                    6 => DataDirectoryType::Debug,
                    7 => DataDirectoryType::Architecture,
                    8 => DataDirectoryType::GlobalPtr,
                    9 => DataDirectoryType::TlsTable,
                    10 => DataDirectoryType::LoadConfigTable,
                    11 => DataDirectoryType::BoundImport,
                    12 => DataDirectoryType::ImportAddressTable,
                    13 => DataDirectoryType::DelayImportDescriptor,
                    14 => DataDirectoryType::ClrRuntimeHeader,
                    15 => DataDirectoryType::Reserved,
                    _ => {
                        continue;
                    }
                };

                if dir_entry.virtual_address != 0 || dir_entry.size != 0 {
                    directories.insert(
                        dir_type,
                        DataDirectory {
                            virtual_address: dir_entry.virtual_address,
                            size: dir_entry.size,
                        },
                    );
                }
            }
        }

        Self { directories }
    }

    fn write_to<W: Write>(&self, writer: &mut W) -> Result<()> {
        // Write all 16 data directory entries in order
        for i in 0..16 {
            let dir_type = match i {
                0 => DataDirectoryType::ExportTable,
                1 => DataDirectoryType::ImportTable,
                2 => DataDirectoryType::ResourceTable,
                3 => DataDirectoryType::ExceptionTable,
                4 => DataDirectoryType::CertificateTable,
                5 => DataDirectoryType::BaseRelocationTable,
                6 => DataDirectoryType::Debug,
                7 => DataDirectoryType::Architecture,
                8 => DataDirectoryType::GlobalPtr,
                9 => DataDirectoryType::TlsTable,
                10 => DataDirectoryType::LoadConfigTable,
                11 => DataDirectoryType::BoundImport,
                12 => DataDirectoryType::ImportAddressTable,
                13 => DataDirectoryType::DelayImportDescriptor,
                14 => DataDirectoryType::ClrRuntimeHeader,
                15 => DataDirectoryType::Reserved,
                _ => unreachable!(),
            };

            if let Some(entry) = self.directories.get(&dir_type) {
                writer.write_all(&entry.virtual_address.to_le_bytes())?;
                writer.write_all(&entry.size.to_le_bytes())?;
            } else {
                // Empty entry
                writer.write_all(&0u32.to_le_bytes())?; // virtual_address
                writer.write_all(&0u32.to_le_bytes())?; // size
            }
        }

        Ok(())
    }
}

impl SectionTable {
    /// Size of a section table entry in bytes (40 bytes per section).
    pub const SIZE: usize = 40;

    fn from_goblin(goblin_section: &goblin::pe::section_table::SectionTable) -> Result<Self> {
        let name = std::str::from_utf8(&goblin_section.name)
            .map_err(|_| Error::Malformed {
                message: "Invalid section name".to_string(),
                file: file!(),
                line: line!(),
            })?
            .trim_end_matches('\0')
            .to_string();

        Ok(Self {
            name,
            virtual_size: goblin_section.virtual_size,
            virtual_address: goblin_section.virtual_address,
            size_of_raw_data: goblin_section.size_of_raw_data,
            pointer_to_raw_data: goblin_section.pointer_to_raw_data,
            pointer_to_relocations: goblin_section.pointer_to_relocations,
            pointer_to_line_numbers: goblin_section.pointer_to_linenumbers,
            number_of_relocations: goblin_section.number_of_relocations,
            number_of_line_numbers: goblin_section.number_of_linenumbers,
            characteristics: goblin_section.characteristics,
        })
    }

    /// Calculates the total size required for a section table with the given number of sections.
    ///
    /// # Arguments
    /// * `section_count` - Number of sections in the table
    ///
    /// # Returns
    /// Total size in bytes for the section table
    #[must_use]
    pub fn calculate_table_size(section_count: usize) -> u64 {
        (section_count * Self::SIZE) as u64
    }

    /// Creates a SectionTable from layout information.
    ///
    /// This converts from the layout planning structures used during write operations
    /// back to the PE section table format.
    ///
    /// # Arguments
    /// * `name` - Section name
    /// * `virtual_address` - RVA where section is mapped
    /// * `virtual_size` - Virtual size of section in memory
    /// * `file_offset` - File offset where section data is stored
    /// * `file_size` - Size of section data in file
    /// * `characteristics` - Section characteristics flags
    ///
    /// # Returns
    /// A new SectionTable instance
    ///
    /// # Errors
    /// Returns an error if the file offset or size exceed u32 range
    pub fn from_layout_info(
        name: String,
        virtual_address: u32,
        virtual_size: u32,
        file_offset: u64,
        file_size: u64,
        characteristics: u32,
    ) -> Result<Self> {
        let size_of_raw_data = u32::try_from(file_size)
            .map_err(|_| malformed_error!("File size exceeds u32 range: {}", file_size))?;
        let pointer_to_raw_data = u32::try_from(file_offset)
            .map_err(|_| malformed_error!("File offset exceeds u32 range: {}", file_offset))?;

        Ok(Self {
            name,
            virtual_size,
            virtual_address,
            size_of_raw_data,
            pointer_to_raw_data,
            pointer_to_relocations: 0,  // 0 for .NET assemblies
            pointer_to_line_numbers: 0, // 0 for .NET assemblies
            number_of_relocations: 0,   // 0 for .NET assemblies
            number_of_line_numbers: 0,  // 0 for .NET assemblies
            characteristics,
        })
    }

    /// Updates the virtual address and size of this section.
    ///
    /// # Arguments
    /// * `virtual_address` - New RVA where section is mapped
    /// * `virtual_size` - New virtual size of section in memory
    pub fn update_virtual_location(&mut self, virtual_address: u32, virtual_size: u32) {
        self.virtual_address = virtual_address;
        self.virtual_size = virtual_size;
    }

    /// Updates the file location and size of this section.
    ///
    /// # Arguments
    /// * `file_offset` - New file offset where section data is stored
    /// * `file_size` - New size of section data in file
    ///
    /// # Errors
    /// Returns an error if the file offset or size exceed u32 range
    pub fn update_file_location(&mut self, file_offset: u64, file_size: u64) -> Result<()> {
        self.pointer_to_raw_data = u32::try_from(file_offset)
            .map_err(|_| malformed_error!("File offset exceeds u32 range: {}", file_offset))?;
        self.size_of_raw_data = u32::try_from(file_size)
            .map_err(|_| malformed_error!("File size exceeds u32 range: {}", file_size))?;
        Ok(())
    }

    /// Updates the section characteristics flags.
    ///
    /// # Arguments
    /// * `characteristics` - New section characteristics flags
    pub fn update_characteristics(&mut self, characteristics: u32) {
        self.characteristics = characteristics;
    }

    /// Sets the section name.
    ///
    /// PE section names are limited to 8 bytes per the PE specification.
    /// This method validates the name length before setting it.
    ///
    /// # Arguments
    /// * `name` - New section name (must be 8 bytes or less)
    ///
    /// # Errors
    /// Returns an error if the name exceeds 8 bytes.
    pub fn set_name(&mut self, name: String) -> Result<()> {
        if name.len() > 8 {
            return Err(malformed_error!(
                "Section name '{}' exceeds 8-byte PE limit ({} bytes)",
                name,
                name.len()
            ));
        }
        self.name = name;
        Ok(())
    }

    /// Writes this section header to the writer.
    ///
    /// Each section header is 40 bytes and describes a section's location in both
    /// the file and virtual memory, along with its characteristics (readable,
    /// writable, executable, etc.).
    ///
    /// # Arguments
    ///
    /// * `writer` - The writer to output the section header to
    ///
    /// # Errors
    ///
    /// Returns an error if writing fails.
    pub fn write_to<W: Write>(&self, writer: &mut W) -> Result<()> {
        // Write name (8 bytes, null-padded)
        let mut name_bytes = [0u8; 8];
        let name_str = self.name.as_bytes();
        let copy_len = std::cmp::min(name_str.len(), 8);
        name_bytes[..copy_len].copy_from_slice(&name_str[..copy_len]);
        writer.write_all(&name_bytes)?;

        writer.write_all(&self.virtual_size.to_le_bytes())?;
        writer.write_all(&self.virtual_address.to_le_bytes())?;
        writer.write_all(&self.size_of_raw_data.to_le_bytes())?;
        writer.write_all(&self.pointer_to_raw_data.to_le_bytes())?;
        writer.write_all(&self.pointer_to_relocations.to_le_bytes())?;
        writer.write_all(&self.pointer_to_line_numbers.to_le_bytes())?;
        writer.write_all(&self.number_of_relocations.to_le_bytes())?;
        writer.write_all(&self.number_of_line_numbers.to_le_bytes())?;
        writer.write_all(&self.characteristics.to_le_bytes())?;

        Ok(())
    }
}

impl Import {
    fn from_goblin(goblin_import: &goblin::pe::import::Import) -> Result<Self> {
        Ok(Self {
            dll: goblin_import.dll.to_string(),
            name: if goblin_import.name.is_empty() {
                None
            } else {
                Some(goblin_import.name.to_string())
            },
            ordinal: if goblin_import.ordinal != 0 {
                Some(goblin_import.ordinal)
            } else {
                None
            },
            rva: u32::try_from(goblin_import.rva)
                .map_err(|_| malformed_error!("PE import RVA value too large"))?,
            hint: 0, // Not available from goblin
            ilt_value: u64::try_from(goblin_import.offset)
                .map_err(|_| malformed_error!("PE import offset value too large"))?,
        })
    }

    /// Get the function identifier for this import (name or ordinal)
    #[must_use]
    pub fn function_identifier(&self) -> String {
        if let Some(ref name) = self.name {
            name.clone()
        } else if let Some(ordinal) = self.ordinal {
            format!("#{ordinal}")
        } else {
            "unknown".to_string()
        }
    }
}

impl Export {
    fn from_goblin(goblin_export: &goblin::pe::export::Export) -> Result<Self> {
        Ok(Self {
            name: goblin_export.name.map(ToString::to_string),
            rva: u32::try_from(goblin_export.rva)
                .map_err(|_| malformed_error!("PE export RVA value too large"))?,
            offset: goblin_export
                .offset
                .map(|o| {
                    u32::try_from(o)
                        .map_err(|_| malformed_error!("PE export offset value too large"))
                })
                .transpose()?,
        })
    }
}

/// Represents an image resource directory header in the PE format.
///
/// This is the header structure at each level of the resource directory tree.
/// The resource directory is organized as a tree with up to 3 levels:
/// Type -> Name -> Language.
///
/// # Structure (16 bytes)
///
/// | Offset | Size | Field                    |
/// |--------|------|--------------------------|
/// | 0      | 4    | characteristics          |
/// | 4      | 4    | time_date_stamp          |
/// | 8      | 2    | major_version            |
/// | 10     | 2    | minor_version            |
/// | 12     | 2    | number_of_named_entries  |
/// | 14     | 2    | number_of_id_entries     |
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
pub struct ImageResourceDirectory {
    /// Resource flags (reserved, typically 0).
    pub characteristics: u32,
    /// Time/date stamp of resource creation.
    pub time_date_stamp: u32,
    /// Major version number.
    pub major_version: u16,
    /// Minor version number.
    pub minor_version: u16,
    /// Number of entries that use string names.
    pub number_of_named_entries: u16,
    /// Number of entries that use integer IDs.
    pub number_of_id_entries: u16,
}

impl ImageResourceDirectory {
    /// Reads an `ImageResourceDirectory` from a byte slice at the given offset.
    pub fn read_from(data: &[u8], offset: usize) -> Result<Self> {
        if offset + IMAGE_RESOURCE_DIRECTORY_SIZE > data.len() {
            return Err(malformed_error!(
                "Resource directory at offset {:#x} exceeds bounds",
                offset
            ));
        }

        Ok(Self {
            characteristics: u32::from_le_bytes([
                data[offset],
                data[offset + 1],
                data[offset + 2],
                data[offset + 3],
            ]),
            time_date_stamp: u32::from_le_bytes([
                data[offset + 4],
                data[offset + 5],
                data[offset + 6],
                data[offset + 7],
            ]),
            major_version: u16::from_le_bytes([data[offset + 8], data[offset + 9]]),
            minor_version: u16::from_le_bytes([data[offset + 10], data[offset + 11]]),
            number_of_named_entries: u16::from_le_bytes([data[offset + 12], data[offset + 13]]),
            number_of_id_entries: u16::from_le_bytes([data[offset + 14], data[offset + 15]]),
        })
    }

    /// Returns the total number of entries (named + ID).
    #[inline]
    pub fn entry_count(&self) -> usize {
        self.number_of_named_entries as usize + self.number_of_id_entries as usize
    }

    /// Writes this `ImageResourceDirectory` to a byte slice at the given offset.
    pub fn write_to(&self, data: &mut [u8], offset: usize) -> Result<()> {
        if offset + IMAGE_RESOURCE_DIRECTORY_SIZE > data.len() {
            return Err(malformed_error!(
                "Resource directory at offset {:#x} exceeds bounds for write",
                offset
            ));
        }

        data[offset..offset + 4].copy_from_slice(&self.characteristics.to_le_bytes());
        data[offset + 4..offset + 8].copy_from_slice(&self.time_date_stamp.to_le_bytes());
        data[offset + 8..offset + 10].copy_from_slice(&self.major_version.to_le_bytes());
        data[offset + 10..offset + 12].copy_from_slice(&self.minor_version.to_le_bytes());
        data[offset + 12..offset + 14].copy_from_slice(&self.number_of_named_entries.to_le_bytes());
        data[offset + 14..offset + 16].copy_from_slice(&self.number_of_id_entries.to_le_bytes());

        Ok(())
    }
}

/// Represents a resource directory entry in the PE format.
///
/// Each entry can point to either a subdirectory or a data entry.
///
/// # Structure (8 bytes)
///
/// | Offset | Size | Field                        |
/// |--------|------|------------------------------|
/// | 0      | 4    | name_or_id                   |
/// | 4      | 4    | offset_to_data_or_directory  |
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
pub struct ResourceEntry {
    /// Either a string name offset (if high bit set) or an integer ID.
    pub name_or_id: u32,
    /// Offset to either a subdirectory (if high bit set) or a data entry.
    pub offset_to_data_or_directory: u32,
}

impl ResourceEntry {
    /// Reads a `ResourceEntry` from a byte slice at the given offset.
    pub fn read_from(data: &[u8], offset: usize) -> Result<Self> {
        if offset + RESOURCE_ENTRY_SIZE > data.len() {
            return Err(malformed_error!(
                "Resource entry at offset {:#x} exceeds bounds",
                offset
            ));
        }

        Ok(Self {
            name_or_id: u32::from_le_bytes([
                data[offset],
                data[offset + 1],
                data[offset + 2],
                data[offset + 3],
            ]),
            offset_to_data_or_directory: u32::from_le_bytes([
                data[offset + 4],
                data[offset + 5],
                data[offset + 6],
                data[offset + 7],
            ]),
        })
    }

    /// Returns true if this entry points to a subdirectory.
    #[inline]
    #[must_use]
    pub fn is_directory(self) -> bool {
        self.offset_to_data_or_directory & constants::IMAGE_RESOURCE_DATA_IS_DIRECTORY != 0
    }

    /// Returns the offset to the target (directory or data entry).
    #[inline]
    #[must_use]
    pub fn target_offset(self) -> usize {
        (self.offset_to_data_or_directory & constants::IMAGE_RESOURCE_MASK) as usize
    }

    /// Writes this `ResourceEntry` to a byte slice at the given offset.
    pub fn write_to(self, data: &mut [u8], offset: usize) -> Result<()> {
        if offset + RESOURCE_ENTRY_SIZE > data.len() {
            return Err(malformed_error!(
                "Resource entry at offset {:#x} exceeds bounds for write",
                offset
            ));
        }

        data[offset..offset + 4].copy_from_slice(&self.name_or_id.to_le_bytes());
        data[offset + 4..offset + 8]
            .copy_from_slice(&self.offset_to_data_or_directory.to_le_bytes());

        Ok(())
    }
}

/// Represents a resource data entry (leaf node) in the PE format.
///
/// This structure contains the RVA pointing to actual resource data.
///
/// # Structure (16 bytes)
///
/// | Offset | Size | Field          |
/// |--------|------|----------------|
/// | 0      | 4    | offset_to_data | (RVA - needs relocation!)
/// | 4      | 4    | size           |
/// | 8      | 4    | code_page      |
/// | 12     | 4    | reserved       |
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
pub struct ResourceDataEntry {
    /// RVA to the actual resource data. This field needs relocation when the section moves.
    pub offset_to_data: u32,
    /// Size of the resource data in bytes.
    pub size: u32,
    /// Code page for character encoding.
    pub code_page: u32,
    /// Reserved (must be 0).
    pub reserved: u32,
}

impl ResourceDataEntry {
    /// Reads a `ResourceDataEntry` from a byte slice at the given offset.
    pub fn read_from(data: &[u8], offset: usize) -> Result<Self> {
        if offset + RESOURCE_DATA_ENTRY_SIZE > data.len() {
            return Err(malformed_error!(
                "Resource data entry at offset {:#x} exceeds bounds",
                offset
            ));
        }

        Ok(Self {
            offset_to_data: u32::from_le_bytes([
                data[offset],
                data[offset + 1],
                data[offset + 2],
                data[offset + 3],
            ]),
            size: u32::from_le_bytes([
                data[offset + 4],
                data[offset + 5],
                data[offset + 6],
                data[offset + 7],
            ]),
            code_page: u32::from_le_bytes([
                data[offset + 8],
                data[offset + 9],
                data[offset + 10],
                data[offset + 11],
            ]),
            reserved: u32::from_le_bytes([
                data[offset + 12],
                data[offset + 13],
                data[offset + 14],
                data[offset + 15],
            ]),
        })
    }

    /// Writes this `ResourceDataEntry` to a byte slice at the given offset.
    pub fn write_to(&self, data: &mut [u8], offset: usize) -> Result<()> {
        if offset + RESOURCE_DATA_ENTRY_SIZE > data.len() {
            return Err(malformed_error!(
                "Resource data entry at offset {:#x} exceeds bounds",
                offset
            ));
        }

        let rva_bytes = self.offset_to_data.to_le_bytes();
        let size_bytes = self.size.to_le_bytes();
        let code_page_bytes = self.code_page.to_le_bytes();
        let reserved_bytes = self.reserved.to_le_bytes();

        data[offset..offset + 4].copy_from_slice(&rva_bytes);
        data[offset + 4..offset + 8].copy_from_slice(&size_bytes);
        data[offset + 8..offset + 12].copy_from_slice(&code_page_bytes);
        data[offset + 12..offset + 16].copy_from_slice(&reserved_bytes);

        Ok(())
    }
}

/// Relocates resource section data when the section moves to a new virtual address.
///
/// The PE resource directory contains a tree structure where leaf nodes (`ResourceDataEntry`)
/// contain RVAs pointing to the actual resource data. When the resource section is moved
/// to a new location, these RVAs must be adjusted by the delta between the old and new
/// section virtual addresses.
///
/// # Arguments
///
/// * `data` - Mutable slice containing the resource section data
/// * `old_rva` - The original virtual address of the resource section
/// * `new_rva` - The new virtual address where the section will be placed
///
/// # Returns
///
/// Returns `Ok(())` on success, or an error if the resource directory is malformed.
///
/// # Resource Directory Structure
///
/// The resource directory is a tree with up to 3 levels (Type -> Name -> Language).
/// Each level consists of:
/// - `ImageResourceDirectory` header (16 bytes)
/// - Array of `ResourceEntry` structures (8 bytes each)
///
/// `ResourceEntry` can point to either:
/// - Another `ImageResourceDirectory` (if high bit of offset is set)
/// - A `ResourceDataEntry` leaf node (if high bit is clear)
///
/// Only `ResourceDataEntry::offset_to_data` contains an absolute RVA that needs relocation.
/// All other offsets in the directory are relative to the start of the resource section.
pub fn relocate_resource_section(data: &mut [u8], old_rva: u32, new_rva: u32) -> Result<()> {
    if old_rva == new_rva || data.is_empty() {
        return Ok(()); // No relocation needed
    }

    let delta = i64::from(new_rva) - i64::from(old_rva);

    // Process the root directory at offset 0
    relocate_resource_directory(data, 0, delta)
}

/// Recursively processes a resource directory and its entries, adjusting RVAs as needed.
fn relocate_resource_directory(data: &mut [u8], offset: usize, delta: i64) -> Result<()> {
    // Read the directory header
    let dir = ImageResourceDirectory::read_from(data, offset)?;
    let entries_offset = offset + IMAGE_RESOURCE_DIRECTORY_SIZE;

    // Process each entry
    for i in 0..dir.entry_count() {
        let entry_offset = entries_offset + i * RESOURCE_ENTRY_SIZE;
        let entry = ResourceEntry::read_from(data, entry_offset)?;

        if entry.is_directory() {
            // Entry points to another directory - recurse
            relocate_resource_directory(data, entry.target_offset(), delta)?;
        } else {
            // Entry points to a ResourceDataEntry - adjust the RVA in-place
            // The RVA is the first 4 bytes of the ResourceDataEntry structure
            let data_entry_offset = entry.target_offset();
            if data_entry_offset + 4 > data.len() {
                return Err(malformed_error!(
                    "Resource data entry at offset {:#x} exceeds bounds",
                    data_entry_offset
                ));
            }
            let old_data_rva = u32::from_le_bytes([
                data[data_entry_offset],
                data[data_entry_offset + 1],
                data[data_entry_offset + 2],
                data[data_entry_offset + 3],
            ]);
            let new_data_rva = u32::try_from(i64::from(old_data_rva) + delta).map_err(|_| {
                malformed_error!(
                    "Resource RVA relocation overflow: old_rva={:#x}, delta={}",
                    old_data_rva,
                    delta
                )
            })?;
            data[data_entry_offset..data_entry_offset + 4]
                .copy_from_slice(&new_data_rva.to_le_bytes());
        }
    }

    Ok(())
}