editpe 0.2.4

Resource Editor for parsing and modification of Windows Portable Executables and their resources
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
//! Data types for parsing and building the resource section.
//! The resource section contains the resource directory and the resource data.
//! See <https://learn.microsoft.com/en-us/windows/win32/debug/pe-format#the-rsrc-section> for more information.

use alloc::{
    format,
    string::{String, ToString},
    vec::Vec,
};
use core::{borrow::Borrow, cmp::Ordering, iter, mem::size_of};

use debug_ignore::DebugIgnore;
use foldhash::fast::RandomState;
use indexmap::{IndexMap, IndexSet};
use log::{error, trace, warn};
use zerocopy::IntoBytes;

#[cfg(feature = "images")]
pub use image::DynamicImage;

use crate::util::u16_string_len;

/// Trait for data types that can be converted to icon data.
///
/// This trait is implemented for `&[u8]`, `Vec<u8>`, and for `DynamicImage` when the `images` feature is enabled.
pub trait ToIcon {
    fn icons(&self) -> Result<Vec<Vec<u8>>, ResourceError>;
}
impl ToIcon for &[u8] {
    fn icons(&self) -> Result<Vec<Vec<u8>>, ResourceError> {
        if self.len() < 22 {
            return Err(ResourceError::InvalidBytes("icon data is too small".into()));
        }
        let directory = read::<IconDirectory>(&self[0..6])?;
        if directory.type_ != 1 {
            return Err(ResourceError::InvalidBytes("icon data is not an icon".into()));
        }
        if directory.count < 1 {
            return Err(ResourceError::InvalidBytes("icon data has no images".into()));
        }
        let mut icons = Vec::with_capacity(directory.count as usize);
        for i in 0..directory.count as usize {
            if self.len() < 6 + i * 16 + 16 {
                return Err(ResourceError::InvalidBytes("icon data is too small".into()));
            }
            let size = read::<u32>(&self[6..][i * 16 + 8..])? as usize;
            let offset = read::<u32>(&self[6..][i * 16 + 12..])? as usize;
            let end = match offset.checked_add(size) {
                Some(end) if end <= self.len() => end,
                _ => return Err(ResourceError::InvalidBytes("icon data is truncated".into())),
            };
            let mut data = Vec::with_capacity(14 + size);
            // prepend 12 bytes of ICO directory entry metadata + 2-byte dummy id
            data.extend_from_slice(&self[6..][i * 16..i * 16 + 12]);
            data.extend_from_slice(&[0u8; 2]);
            data.extend_from_slice(&self[offset..end]);
            icons.push(data);
        }
        Ok(icons)
    }
}
impl ToIcon for Vec<u8> {
    fn icons(&self) -> Result<Vec<Vec<u8>>, ResourceError> { self.as_slice().icons() }
}
#[cfg(feature = "images")]
impl ToIcon for &DynamicImage {
    fn icons(&self) -> Result<Vec<Vec<u8>>, ResourceError> {
        use image::{ImageFormat, imageops::FilterType::Lanczos3};
        use std::io::Cursor;
        const RESOLUTIONS: &[u32] = &[256, 128, 48, 32, 24, 16];
        RESOLUTIONS
            .iter()
            .map(|&size| {
                let mut data = Vec::new();
                self.resize_exact(size, size, Lanczos3)
                    .to_rgba8()
                    .write_to(&mut Cursor::new(&mut data), ImageFormat::Ico)?;
                // prepend 12 bytes of ICO directory entry metadata + 2-byte dummy id
                let mut result = Vec::with_capacity(14 + data.len() - 22);
                result.extend_from_slice(&data[6..18]);
                result.extend_from_slice(&[0u8; 2]);
                result.extend_from_slice(&data[22..]);
                Ok(result)
            })
            .collect::<Result<Vec<Vec<u8>>, ResourceError>>()
    }
}
#[cfg(feature = "images")]
impl ToIcon for DynamicImage {
    fn icons(&self) -> Result<Vec<Vec<u8>>, ResourceError> { (&self).icons() }
}

use crate::{constants::*, errors::*, types::*, util::*};

/// Portable executable resource directory.
///
/// The resource directory contains the resource table and the resource data entries.
///
/// See [`Image::resource_directory`](crate::Image::resource_directory) for retrieving the resource directory from an image.
#[derive(Debug, Clone, Eq, PartialEq, Default)]
pub struct ResourceDirectory {
    pub(crate) virtual_address: u32,
    pub(crate) root:            ResourceTable,
}
impl ResourceDirectory {
    /// Parse the resource directory from the given image at the given base address.
    /// The virtual address is used to resolve the resource data offsets and has to correspond to the virtual address in the section table header of the source image.
    ///
    /// # Returns
    /// Returns an error if the resource directory at the given address is invalid.
    pub fn parse(
        image: &[u8], base_address: u32, virtual_address: u32,
    ) -> Result<Self, ImageReadError> {
        let root =
            ResourceTable::parse(image, base_address, virtual_address, 0, 0, &mut Vec::new())?;
        Ok(Self {
            virtual_address,
            root,
        })
    }

    /// Get the main icon of the executable.
    /// The icon will be the first icon in the `MAINICON` group icon directory if it exists.
    /// Otherwise, the first icon in the first group icon directory will be returned.
    ///
    /// # Returns
    /// Returns `None` if no icon exists.
    /// Returns an error if the resource table structure is not well-formed.
    pub fn get_main_icon(&self) -> Result<Option<&[u8]>, ResourceError> {
        if self.root.entries.is_empty() {
            return Ok(None);
        }

        // find the group icon table
        let group_table = self.root.get(ResourceEntryName::ID(RT_GROUP_ICON as u32));
        let group_table = match group_table {
            Some(ResourceEntry::Table(t)) => t,
            Some(_) => {
                return Err(ResourceError::InvalidTable(
                    "group icon table is not a table".to_string(),
                ));
            }
            _ => return Ok(None),
        };
        if group_table.entries.is_empty() {
            return Ok(None);
        }

        // find the main icon directory table
        let icon_directory_table = group_table
            .entries
            .get(&ResourceEntryName::from_string("MAINICON"))
            .or_else(|| group_table.entries.first().map(|(_, v)| v));
        let icon_directory_table = match icon_directory_table {
            Some(ResourceEntry::Table(t)) => t,
            Some(_) => {
                return Err(ResourceError::InvalidTable(
                    "inner group icon table is not a table".to_string(),
                ));
            }
            None => return Ok(None),
        };
        if icon_directory_table.entries.is_empty() {
            return Ok(None);
        }

        // find the main icon directory
        let icon_directory_entry = match icon_directory_table.entries.first().map(|(_, v)| v) {
            Some(ResourceEntry::Data(data)) => data,
            Some(ResourceEntry::Table(_)) => {
                return Err(ResourceError::InvalidTable(
                    "group icon table entry is not data".to_string(),
                ));
            }
            None => return Ok(None),
        };
        let icon_directory = read::<IconDirectory>(&icon_directory_entry.data)?;

        // get the first icon in the main icon directory
        if icon_directory.count == 0 {
            return Ok(None);
        }
        let icon_directory_entry = read::<IconDirectoryEntry>(&icon_directory_entry.data[6..])?;
        let icon_id = icon_directory_entry.id as u32;

        // find the main icon table
        let icon_table = match self.root.get(ResourceEntryName::ID(RT_ICON as u32)) {
            Some(ResourceEntry::Table(table)) => table,
            Some(ResourceEntry::Data(_)) => {
                return Err(ResourceError::InvalidTable("icon table is not a table".to_string()));
            }
            None => return Ok(None),
        };

        let inner_table = icon_table.get(ResourceEntryName::ID(icon_id));
        let inner_table = match inner_table {
            Some(ResourceEntry::Table(t)) => t,
            Some(_) => {
                return Err(ResourceError::InvalidTable(
                    "inner icon table is not a table".to_string(),
                ));
            }
            None => return Ok(None),
        };
        if inner_table.entries.is_empty() {
            return Ok(None);
        }

        // get the main icon from the icon table
        let icon = match inner_table.entries.first().map(|(_, v)| v) {
            Some(ResourceEntry::Table(_)) => {
                return Err(ResourceError::InvalidTable(
                    "icon table entry is not data".to_string(),
                ));
            }
            Some(ResourceEntry::Data(data)) => data,
            None => return Ok(None),
        };

        Ok(Some(icon.data()))
    }

    /// Set the main icon of the executable.
    /// The icon must be the byte slice of a valid icon, or a [`image::DynamicImage`] when the `images` feature is enabled.
    ///
    /// When `icon` is a [`image::DynamicImage`], the image is resized to the different icon resolutions.
    ///
    /// This will overwrite the group icon directory with the `MAINICON` name if it exists and keep all other group icon directories intact.
    /// This will not remove any existing icons.
    /// To remove the existing main icon directory and the icons referenced by, call [`remove_main_icon`](ResourceDirectory::remove_main_icon) before setting a new one.
    ///
    /// # Returns
    /// Returns an error if the new icon not a valid image or the resource table structure is not well-formed.
    pub fn set_main_icon<T: ToIcon>(&mut self, icon: T) -> Result<(), ResourceError> {
        // read and validate all icon entries
        let icons = icon.icons()?;
        let icon_count = u16::try_from(icons.len()).map_err(|_| {
            ResourceError::InvalidBytes(ReadError("icon count exceeds 65535".into()))
        })?;
        if icon_count == 0 {
            return Err(ResourceError::InvalidBytes(ReadError("icon has no images".into())));
        }
        for icon in &icons {
            if icon.len() < 14 {
                return Err(ResourceError::InvalidBytes(ReadError(
                    "icon directory entry is too small".into(),
                )));
            }
            u32::try_from(icon.len() - 14).map_err(|_| {
                ResourceError::InvalidBytes(ReadError("icon image exceeds 4GiB".into()))
            })?;
        }

        // find the main icon table
        let icon_table_name = ResourceEntryName::ID(RT_ICON as u32);
        let mut icon_table = self
            .root
            .cloned_table_or_default(&icon_table_name, "icon table is not a table")?;
        let group_table_name = ResourceEntryName::ID(RT_GROUP_ICON as u32);
        let mut group_table = self
            .root
            .cloned_table_or_default(&group_table_name, "group icon table is not a table")?;
        let first_free_icon_id = icon_table
            .entries
            .keys()
            .filter_map(|key| match key {
                ResourceEntryName::ID(id) => Some(*id),
                ResourceEntryName::Name(_) => None,
            })
            .max()
            .unwrap_or(0)
            .checked_add(1)
            .ok_or_else(|| {
                ResourceError::InvalidBytes(ReadError("icon identifier overflows".into()))
            })?;
        let last_icon_id =
            first_free_icon_id.checked_add(u32::from(icon_count) - 1).ok_or_else(|| {
                ResourceError::InvalidBytes(ReadError("icon identifier overflows".into()))
            })?;
        if last_icon_id > u16::MAX as u32 {
            return Err(ResourceError::InvalidBytes(ReadError(
                "icon identifier exceeds 65535".into(),
            )));
        }

        // add the icons to the icon table
        let mut icon_directory_entries = Vec::new();
        for (i, icon) in icons.iter().enumerate() {
            let id = first_free_icon_id
                .checked_add(u32::try_from(i).map_err(|_| {
                    ResourceError::InvalidBytes(ReadError("icon index exceeds u32".into()))
                })?)
                .ok_or_else(|| {
                    ResourceError::InvalidBytes(ReadError("icon identifier overflows".into()))
                })?;
            let mut inner_table = ResourceTable::default();
            inner_table.insert(
                ResourceEntryName::ID(LANGUAGE_ID_EN_US as u32),
                ResourceEntry::Data(ResourceData {
                    data:     {
                        let mut entry = read::<IconDirectoryEntry>(&icon[..14])?;
                        entry.id = u16::try_from(id).map_err(|_| {
                            ResourceError::InvalidBytes(ReadError(
                                "icon identifier exceeds 65535".into(),
                            ))
                        })?;
                        entry.bytes = u32::try_from(icon.len() - 14).map_err(|_| {
                            ResourceError::InvalidBytes(ReadError("icon image exceeds 4GiB".into()))
                        })?;
                        icon_directory_entries.push(entry);
                        icon[14..].to_vec().into()
                    },
                    codepage: CODE_PAGE_ID_EN_US as u32,
                    reserved: 0,
                }),
            );
            icon_table.insert(ResourceEntryName::ID(id), ResourceEntry::Table(inner_table));
        }

        // insert the main icon directory table
        let mut inner_table = ResourceTable::default();
        inner_table.insert(
            ResourceEntryName::ID(LANGUAGE_ID_EN_US as u32),
            ResourceEntry::Data(ResourceData {
                data:     {
                    let mut data = Vec::new();
                    let icon_directory = IconDirectory {
                        reserved: 0,
                        type_:    1,
                        count:    icon_count,
                    };
                    data.extend(icon_directory.as_bytes());
                    for entry in icon_directory_entries {
                        data.extend(&entry.as_bytes()[..14]);
                    }
                    data.into()
                },
                codepage: CODE_PAGE_ID_EN_US as u32,
                reserved: 0,
            }),
        );
        group_table.insert_at(
            ResourceEntryName::from_string("MAINICON"),
            ResourceEntry::Table(inner_table),
            0,
        );
        self.root.insert(icon_table_name, ResourceEntry::Table(icon_table));
        self.root.insert(group_table_name, ResourceEntry::Table(group_table));

        Ok(())
    }

    #[cfg(feature = "std")]
    /// Set the main icon of the executable from a file.
    /// The file must contain a valid image.
    /// The image is resized to the different icon resolutions when the `images` feature is enabled.
    ///
    /// See [`set_main_icon`](ResourceDirectory::set_main_icon) for more information.
    ///
    /// # Returns
    /// Returns an error if the file is not a valid image or the resource table structure is not well-formed.
    pub fn set_main_icon_file(&mut self, path: &str) -> Result<(), ResourceError> {
        #[cfg(feature = "images")]
        let icon = image::ImageReader::open(path)?.decode()?;
        #[cfg(not(feature = "images"))]
        let icon = std::fs::read(path)?;
        self.set_main_icon(icon)
    }

    #[cfg(feature = "std")]
    /// Set the main icon of the executable from a reader.
    /// The reader must contain a valid image.
    /// The image is resized to the different icon resolutions when the `images` feature is enabled.
    ///
    /// See [`set_main_icon`](ResourceDirectory::set_main_icon) for more information.
    ///
    /// # Returns
    /// Returns an error if the reader does not contain a valid image or the resource table structure is not well-formed.
    pub fn set_main_icon_reader<R: std::io::Read>(
        &mut self, reader: &mut R,
    ) -> Result<(), ResourceError> {
        let mut icon = Vec::new();
        reader.read_to_end(&mut icon)?;
        #[cfg(feature = "images")]
        let icon = image::load_from_memory(&icon)?;
        self.set_main_icon(icon)
    }

    /// Remove the main icon directory and all icons uniquely referenced by it.
    ///
    /// # Returns
    /// Returns an error if the icon resource directory is invalid.
    pub fn remove_main_icon(&mut self) -> Result<(), ResourceError> {
        if self.root.entries.is_empty() {
            return Ok(());
        }

        // find the group table
        let group_table = self.root.get_mut(ResourceEntryName::ID(RT_GROUP_ICON as u32));
        let group_table = match group_table {
            Some(ResourceEntry::Table(t)) => t,
            Some(_) => {
                return Err(ResourceError::InvalidTable(
                    "group icon table is not a table".to_string(),
                ));
            }
            _ => return Ok(()),
        };
        if group_table.entries.is_empty() {
            return Ok(());
        }

        // find the main icon directory table
        let mut icon_directory_name = ResourceEntryName::from_string("MAINICON");
        let mut icon_directory_table = group_table.get(&icon_directory_name);
        if icon_directory_table.is_none() {
            icon_directory_table = group_table.entries.first().map(|(name, v)| {
                icon_directory_name = name.clone();
                v
            });
        }
        let icon_directory_table = match icon_directory_table {
            Some(ResourceEntry::Table(t)) => t,
            Some(_) => {
                return Err(ResourceError::InvalidTable(
                    "inner group icon table is not a table".to_string(),
                ));
            }
            _ => return Ok(()),
        };
        if icon_directory_table.entries.is_empty() {
            return Ok(());
        }

        // find the main icon directory
        let icon_directory_entry = match icon_directory_table.entries.first().map(|(_, v)| v) {
            Some(ResourceEntry::Data(data)) => data,
            Some(ResourceEntry::Table(_)) => {
                return Err(ResourceError::InvalidTable(
                    "group icon table entry is not data".to_string(),
                ));
            }
            None => return Ok(()),
        };
        let icon_directory = read::<IconDirectory>(&icon_directory_entry.data)?;

        // get a list of all icons in the main icon directory for removal
        let mut icons_to_remove = IndexSet::with_hasher(RandomState::default());
        for i in 0..icon_directory.count {
            let icon_directory_entry = read_at::<IconDirectoryEntry>(
                &icon_directory_entry.data,
                6 + i as usize * size_of::<IconDirectoryEntry>(),
            )?;
            let icon_id = icon_directory_entry.id;
            icons_to_remove.insert(icon_id);
        }

        // get a list of icons in other icon directories and remove them from the list
        for (other_icon_directory_name, other_icon_directory_table) in group_table.entries.iter() {
            if other_icon_directory_name == &icon_directory_name {
                continue;
            }
            let other_icon_directory_table = match other_icon_directory_table {
                ResourceEntry::Table(table) => table,
                ResourceEntry::Data(_) => continue,
            };
            if other_icon_directory_table.entries.is_empty() {
                continue;
            }
            let other_icon_directory_entry =
                match other_icon_directory_table.entries.first().map(|(_, v)| v) {
                    Some(ResourceEntry::Data(data)) => data,
                    Some(ResourceEntry::Table(_)) | None => continue,
                };
            let other_icon_directory = read::<IconDirectory>(&other_icon_directory_entry.data)?;
            for i in 0..other_icon_directory.count {
                let icon_directory_entry = read_at::<IconDirectoryEntry>(
                    &other_icon_directory_entry.data,
                    6 + i as usize * size_of::<IconDirectoryEntry>(),
                )?;
                let icon_id = icon_directory_entry.id;
                icons_to_remove.swap_remove(&icon_id);
            }
        }

        // remove the main icon directory table
        group_table.remove(&icon_directory_name);
        if group_table.entries.is_empty() {
            self.root.remove(ResourceEntryName::ID(RT_GROUP_ICON as u32));
        }

        // find the main icon table
        let icon_table = match self.root.get_mut(ResourceEntryName::ID(RT_ICON as u32)) {
            Some(ResourceEntry::Table(table)) => table,
            Some(ResourceEntry::Data(_)) | None => return Ok(()),
        };

        // remove the icons from the icon table
        for icon_id in icons_to_remove {
            icon_table.remove(ResourceEntryName::ID(icon_id as u32));
        }

        Ok(())
    }

    /// Get the version information of the executable.
    ///
    /// # Returns
    /// Returns `None` if no version information exists.
    /// Returns an error if the version resource directory is invalid.
    pub fn get_version_info(&self) -> Result<Option<VersionInfo>, ResourceError> {
        if self.root.entries.is_empty() {
            return Ok(None);
        }

        // find the group table
        let version_table = self.root.get(ResourceEntryName::ID(RT_VERSION as u32));
        let version_table = match version_table {
            Some(ResourceEntry::Table(t)) => t,
            Some(_) => {
                return Err(ResourceError::InvalidTable(
                    "version table is not a table".to_string(),
                ));
            }
            _ => return Ok(None),
        };
        if version_table.entries.is_empty() {
            return Ok(None);
        }

        // find the main version directory table
        let inner_table = version_table.entries.first().map(|(_, v)| v);
        let inner_table = match inner_table {
            Some(ResourceEntry::Table(t)) => t,
            Some(_) => {
                return Err(ResourceError::InvalidTable(
                    "inner version table is not a table".to_string(),
                ));
            }
            None => return Ok(None),
        };
        if inner_table.entries.is_empty() {
            return Ok(None);
        }

        // find the main version directory
        let version_directory_entry = inner_table
            .entries
            .iter()
            .find(|(name, _)| **name == ResourceEntryName::ID(LANGUAGE_ID_EN_US as u32))
            .or_else(|| inner_table.entries.first())
            .map(|(_, v)| v)
            .unwrap();
        let version_directory_entry = match version_directory_entry {
            ResourceEntry::Data(data) => data,
            ResourceEntry::Table(_) => {
                return Err(ResourceError::InvalidTable(
                    "version table entry is not data".to_string(),
                ));
            }
        };

        Ok(Some(VersionInfo::parse(&version_directory_entry.data)?))
    }

    /// Set the version information of the executable.
    ///
    /// This will overwrite the existing version information.
    ///
    /// # Returns
    /// Returns an error if the resource table structure is not well-formed.
    pub fn set_version_info(&mut self, version_info: &VersionInfo) -> Result<(), ResourceError> {
        let data = version_info.try_build()?;
        let version_table_name = ResourceEntryName::ID(RT_VERSION as u32);
        let mut version_table = self
            .root
            .cloned_table_or_default(&version_table_name, "version table is not a table")?;

        // find the main version directory table
        let inner_table = version_table.entries.first().map(|(_, v)| v);
        let mut inner_table = match inner_table {
            Some(ResourceEntry::Table(t)) => t.clone(),
            Some(_) => {
                return Err(ResourceError::InvalidTable(
                    "inner version table is not a table".to_string(),
                ));
            }
            None => ResourceTable::default(),
        };

        inner_table.insert_at(
            ResourceEntryName::ID(LANGUAGE_ID_EN_US as u32),
            ResourceEntry::Data(ResourceData {
                data:     data.into(),
                codepage: CODE_PAGE_ID_EN_US as u32,
                reserved: 0,
            }),
            0,
        );
        version_table.insert_at(ResourceEntryName::ID(1), ResourceEntry::Table(inner_table), 0);
        self.root.insert(version_table_name, ResourceEntry::Table(version_table));

        Ok(())
    }

    /// Remove the version information of the executable.
    ///
    /// # Returns
    /// Returns an error if the resource table structure is not well-formed.
    pub fn remove_version_info(&mut self) -> Result<(), ResourceError> {
        if self.root.entries.is_empty() {
            return Ok(());
        }

        // find the version table
        let version_table = self.root.get_mut(ResourceEntryName::ID(RT_VERSION as u32));
        let version_table = match version_table {
            Some(ResourceEntry::Table(t)) => t,
            Some(_) => {
                return Err(ResourceError::InvalidTable(
                    "version table is not a table".to_string(),
                ));
            }
            _ => return Ok(()),
        };
        if version_table.entries.is_empty() {
            return Ok(());
        }

        // find the main version directory table
        let inner_table = version_table.entries.first_mut().map(|(_, v)| v);
        let inner_table = match inner_table {
            Some(ResourceEntry::Table(t)) => t,
            Some(_) => {
                return Err(ResourceError::InvalidTable(
                    "inner version table is not a table".to_string(),
                ));
            }
            None => return Ok(()),
        };
        if inner_table.entries.is_empty() {
            return Ok(());
        }

        // remove the main version directory
        inner_table.remove(inner_table.entries.keys().next().unwrap().clone());
        if inner_table.entries.is_empty() {
            version_table.remove(version_table.entries.keys().next().unwrap().clone());
        }
        if version_table.entries.is_empty() {
            self.root.remove(ResourceEntryName::ID(RT_VERSION as u32));
        }

        Ok(())
    }

    /// Get the manifest of the executable.
    ///
    /// # Returns
    /// Returns `None` if no manifest exists.
    /// Returns an error if the manifest resource directory is invalid.
    pub fn get_manifest(&self) -> Result<Option<String>, ResourceError> {
        if self.root.entries.is_empty() {
            return Ok(None);
        }

        // find the manifest table
        let manifest_table = self.root.get(ResourceEntryName::ID(RT_MANIFEST as u32));
        let manifest_table = match manifest_table {
            Some(ResourceEntry::Table(t)) => t,
            Some(_) => {
                return Err(ResourceError::InvalidTable(
                    "manifest table is not a table".to_string(),
                ));
            }
            _ => return Ok(None),
        };
        if manifest_table.entries.is_empty() {
            return Ok(None);
        }

        // find the main manifest directory table
        let inner_table = manifest_table.entries.first().map(|(_, v)| v);
        let inner_table = match inner_table {
            Some(ResourceEntry::Table(t)) => t,
            Some(_) => {
                return Err(ResourceError::InvalidTable(
                    "inner manifest table is not a table".to_string(),
                ));
            }
            None => return Ok(None),
        };
        if inner_table.entries.is_empty() {
            return Ok(None);
        }

        // find the main manifest directory
        let manifest_directory_entry = inner_table
            .entries
            .iter()
            .find(|(name, _)| **name == ResourceEntryName::ID(LANGUAGE_ID_EN_US as u32))
            .or_else(|| inner_table.entries.first())
            .map(|(_, v)| v)
            .unwrap();
        let manifest_directory_entry = match manifest_directory_entry {
            ResourceEntry::Data(data) => data,
            ResourceEntry::Table(_) => {
                return Err(ResourceError::InvalidTable(
                    "manifest table entry is not data".to_string(),
                ));
            }
        };

        Ok(Some(String::from_utf8_lossy(&manifest_directory_entry.data).to_string()))
    }

    /// Set the manifest of the executable.
    ///
    /// This will overwrite the existing manifest.
    ///
    /// # Returns
    /// Returns an error if the resource table structure is not well-formed.
    pub fn set_manifest(&mut self, manifest: &str) -> Result<(), ResourceError> {
        let manifest_table_name = ResourceEntryName::ID(RT_MANIFEST as u32);
        let mut manifest_table = self
            .root
            .cloned_table_or_default(&manifest_table_name, "manifest table is not a table")?;

        // find the main manifest directory table
        let inner_table = manifest_table.entries.first().map(|(_, v)| v);
        let mut inner_table = match inner_table {
            Some(ResourceEntry::Table(t)) => t.clone(),
            Some(_) => {
                return Err(ResourceError::InvalidTable(
                    "inner manifest table is not a table".to_string(),
                ));
            }
            None => ResourceTable::default(),
        };

        inner_table.insert_at(
            ResourceEntryName::ID(LANGUAGE_ID_EN_US as u32),
            ResourceEntry::Data(ResourceData {
                data:     manifest.as_bytes().to_vec().into(),
                codepage: CODE_PAGE_ID_EN_US as u32,
                reserved: 0,
            }),
            0,
        );
        manifest_table.insert_at(ResourceEntryName::ID(1), ResourceEntry::Table(inner_table), 0);
        self.root.insert(manifest_table_name, ResourceEntry::Table(manifest_table));

        Ok(())
    }

    /// Remove the manifest of the executable.
    ///
    /// # Returns
    /// Returns an error if the resource table structure is not well-formed.
    pub fn remove_manifest(&mut self) -> Result<(), ResourceError> {
        if self.root.entries.is_empty() {
            return Ok(());
        }

        // find the version table
        let manifest_table = self.root.get_mut(ResourceEntryName::ID(RT_MANIFEST as u32));
        let manifest_table = match manifest_table {
            Some(ResourceEntry::Table(t)) => t,
            Some(_) => {
                return Err(ResourceError::InvalidTable(
                    "manifest table is not a table".to_string(),
                ));
            }
            _ => return Ok(()),
        };
        if manifest_table.entries.is_empty() {
            return Ok(());
        }

        // find the main manifest directory table
        let inner_table = manifest_table.entries.first_mut().map(|(_, v)| v);
        let inner_table = match inner_table {
            Some(ResourceEntry::Table(t)) => t,
            Some(_) => {
                return Err(ResourceError::InvalidTable(
                    "inner manifest table is not a table".to_string(),
                ));
            }
            None => return Ok(()),
        };
        if inner_table.entries.is_empty() {
            return Ok(());
        }

        // remove the main manifest directory
        inner_table.remove(inner_table.entries.keys().next().unwrap().clone());
        if inner_table.entries.is_empty() {
            manifest_table.remove(manifest_table.entries.keys().next().unwrap().clone());
        }
        if manifest_table.entries.is_empty() {
            self.root.remove(ResourceEntryName::ID(RT_MANIFEST as u32));
        }

        Ok(())
    }

    /// Returns the virtual address of the resource directory in the source image.
    pub fn virtual_address(&self) -> u32 { self.virtual_address }

    /// Returns the root resource table.
    /// The root resource table contains the top-level resource entries.
    pub fn root(&self) -> &ResourceTable { &self.root }

    /// Returns the mutable root resource table.
    /// The root resource table contains the top-level resource entries.
    pub fn root_mut(&mut self) -> &mut ResourceTable { &mut self.root }

    /// Returns the size of the resulting resource directory in bytes.
    pub fn size(&self) -> u32 { self.root.size() }

    /// Build the resource directory into raw bytes to be included in an image.
    /// The virtual address is used to compute the resource data offsets and has to correspond to the virtual address in the section table header of the target image.
    pub fn build(&self, virtual_address: u32) -> Vec<u8> { self.root.build(virtual_address) }
}

/// Portable executable resource table data.
enum TableData {
    Table(ResourceDirectoryTable),
    Entry(ResourceDirectoryEntry),
}

/// Portable executable resource table.
#[derive(Debug, Clone, Eq, PartialEq, Default)]
pub struct ResourceTable {
    pub(crate) data:    ResourceDirectoryTable,
    pub(crate) entries: IndexMap<ResourceEntryName, ResourceEntry, RandomState>,
}
impl ResourceTable {
    fn cloned_table_or_default<N: Borrow<ResourceEntryName>>(
        &self, name: N, error: &str,
    ) -> Result<Self, ResourceError> {
        match self.get(name) {
            Some(ResourceEntry::Table(table)) => Ok(table.clone()),
            Some(ResourceEntry::Data(_)) => Err(ResourceError::InvalidTable(error.to_string())),
            None => Ok(Self::default()),
        }
    }

    fn parse(
        image: &[u8], base_address: u32, virtual_address: u32, directory_offset: u32, level: usize,
        ancestors: &mut Vec<u32>,
    ) -> Result<Self, ImageReadError> {
        let table_offset = base_address.checked_add(directory_offset).ok_or_else(|| {
            ReadError(format!(
                "resource table offset {base_address:#x} + {directory_offset:#x} overflows"
            ))
        })?;
        if ancestors.contains(&table_offset) {
            return Err(ReadError(format!(
                "resource table cycle detected at offset {table_offset:#x}"
            ))
            .into());
        }
        ancestors.push(table_offset);

        let result = (|| {
            let resource_table = read_at::<ResourceDirectoryTable>(image, table_offset as usize)?;
            trace!("{} {:#x?}", "--".repeat(level + 1), resource_table);

            let mut entries = IndexMap::default();

            let num_entries = resource_table.number_of_name_entries as u32
                + resource_table.number_of_id_entries as u32;
            let mut entry_offset = table_offset.checked_add(16).ok_or_else(|| {
                ReadError(format!("resource entry offset at {table_offset:#x} overflows"))
            })?;
            for _ in 0..num_entries {
                let entry = read_at::<ResourceDirectoryEntry>(image, entry_offset as usize)?;
                trace!("{} {:#x?}", "--".repeat(level + 1), entry);
                entry_offset = entry_offset
                    .checked_add(8)
                    .ok_or_else(|| ReadError("resource entry offset overflows".into()))?;

                let name = match ResourceEntryName::parse(
                    image,
                    base_address,
                    entry.name_offset_or_integer_id,
                ) {
                    Ok(name) => name,
                    Err(error) => {
                        warn!(
                            "{} skipping invalid resource name: {error:?}",
                            "--".repeat(level + 1)
                        );
                        continue;
                    }
                };

                if entry.data_entry_or_subdirectory_offset & 0x80000000 != 0 {
                    match ResourceTable::parse(
                        image,
                        base_address,
                        virtual_address,
                        entry.data_entry_or_subdirectory_offset ^ 0x80000000,
                        level + 1,
                        ancestors,
                    ) {
                        Ok(table) => {
                            entries.insert(name, ResourceEntry::Table(table));
                        }
                        Err(error) => warn!(
                            "{} skipping invalid resource subdirectory: {error:?}",
                            "--".repeat(level + 1)
                        ),
                    }
                } else {
                    let data_entry_offset =
                        match base_address.checked_add(entry.data_entry_or_subdirectory_offset) {
                            Some(offset) => offset,
                            None => {
                                warn!(
                                    "{} skipping resource data entry with overflowing offset",
                                    "--".repeat(level + 1)
                                );
                                continue;
                            }
                        };
                    trace!(
                        "reading {} bytes at {} (image size {})",
                        size_of::<ResourceDataEntry>(),
                        data_entry_offset,
                        image.len()
                    );
                    let data = match read_at::<ResourceDataEntry>(image, data_entry_offset as usize)
                    {
                        Ok(data) => data,
                        Err(error) => {
                            warn!(
                                "{} skipping invalid resource data entry: {error:?}",
                                "--".repeat(level + 1)
                            );
                            continue;
                        }
                    };
                    // calculate as i64 and convert to u64 first to check for padding
                    let address =
                        base_address as i64 + data.data_rva as i64 - virtual_address as i64;
                    let mut address = address as u64;
                    if address & 0xffffffffff000000 == 0xffffffffff000000 {
                        warn!(
                            "{} resource data entry address {:#x?} seems to be packed, ignoring padding",
                            "--".repeat(level + 1),
                            address
                        );
                        address ^= 0xffffffffff000000;
                    }
                    trace!("{} {:#x?} {:#x?}", "--".repeat(level + 1), address, data);
                    let resource_data = usize::try_from(address)
                        .ok()
                        .and_then(|address| checked_slice(image, address, data.size as usize).ok());
                    let Some(resource_data) = resource_data else {
                        warn!(
                            "{} skipping resource data outside the image",
                            "--".repeat(level + 1)
                        );
                        continue;
                    };
                    entries.insert(
                        name,
                        ResourceEntry::Data(ResourceData {
                            codepage: data.codepage,
                            reserved: data.reserved,
                            data:     resource_data.to_vec().into(),
                        }),
                    );
                }
            }
            let mut normalized_table = resource_table;
            normalized_table.number_of_name_entries =
                entries.keys().filter(|name| matches!(name, ResourceEntryName::Name(_))).count()
                    as u16;
            normalized_table.number_of_id_entries =
                entries.keys().filter(|name| matches!(name, ResourceEntryName::ID(_))).count()
                    as u16;
            Ok(Self {
                data: normalized_table,
                entries,
            })
        })();

        ancestors.pop();
        result
    }

    fn build(&self, virtual_address: u32) -> Vec<u8> {
        let mut tables_offset = 0;
        let mut strings_offset = 0;
        let mut descriptions_offset = 0;
        let mut data_offset = 0;
        let (mut tables_data, strings_data, mut descriptions_data, data_data) = self.build_table(
            virtual_address,
            &mut tables_offset,
            &mut strings_offset,
            &mut descriptions_offset,
            &mut data_offset,
        );

        let mut data = Vec::new();
        data.extend(tables_data.iter_mut().flat_map(|data| match data {
            TableData::Table(table) => table.as_bytes(),
            TableData::Entry(entry) => {
                if entry.data_entry_or_subdirectory_offset & 0x80000000 == 0 {
                    entry.data_entry_or_subdirectory_offset += tables_offset + strings_offset;
                }
                if entry.name_offset_or_integer_id & 0x80000000 != 0 {
                    entry.name_offset_or_integer_id += tables_offset;
                }
                entry.as_bytes()
            }
        }));
        data.extend(strings_data.iter());
        data.extend(descriptions_data.iter_mut().flat_map(|data| {
            data.data_rva += tables_offset + strings_offset + descriptions_offset;
            data.as_bytes()
        }));
        data.extend(data_data);

        data
    }

    fn build_table(
        &self, virtual_address: u32, tables_offset: &mut u32, strings_offset: &mut u32,
        descriptions_offset: &mut u32, data_offset: &mut u32,
    ) -> (Vec<TableData>, Vec<u8>, Vec<ResourceDataEntry>, Vec<u8>) {
        let mut tables_data = Vec::<TableData>::new();
        let mut strings_data = Vec::<u8>::new();
        let mut descriptions_data = Vec::<ResourceDataEntry>::new();
        let mut data_data = Vec::<u8>::new();

        tables_data.push(TableData::Table(self.data));
        *tables_offset += 16;

        // Sort entries as described in <https://learn.microsoft.com/en-us/windows/win32/debug/pe-format#resource-directory-entries>
        // named entries (case-insensitive) then ID entries (numerical)
        let mut sorted_keys: Vec<&ResourceEntryName> = self.entries.keys().collect();
        sorted_keys.sort_by(|a, b| match (a, b) {
            (ResourceEntryName::Name(_), ResourceEntryName::ID(_)) => Ordering::Less,
            (ResourceEntryName::ID(_), ResourceEntryName::Name(_)) => Ordering::Greater,
            (ResourceEntryName::Name(_), ResourceEntryName::Name(_)) => {
                match (a.to_string(), b.to_string()) {
                    (Some(a), Some(b)) => a.to_uppercase().cmp(&b.to_uppercase()),
                    _ => a.string_data().cmp(b.string_data()),
                }
            }
            (ResourceEntryName::ID(a), ResourceEntryName::ID(b)) => a.cmp(b),
        });

        let mut next_table_offset = 0u32;
        let mut next_table_sizes = 0u32;
        for name in &sorted_keys {
            let entry = &self.entries[*name];
            strings_data.extend(name.string_data());
            let name_offset_or_integer_id = if name.string_size() > 0 {
                *strings_offset | 0x80000000
            } else {
                name.id()
            };
            *strings_offset += name.string_size();

            match entry {
                ResourceEntry::Table(table) => {
                    let entry_data = ResourceDirectoryEntry {
                        name_offset_or_integer_id,
                        data_entry_or_subdirectory_offset: (*tables_offset
                            + self.entries.len() as u32 * 8
                            + next_table_sizes)
                            | 0x80000000,
                    };
                    tables_data.push(TableData::Entry(entry_data));
                    next_table_offset += 8;
                    next_table_sizes += table.tables_size();
                }
                ResourceEntry::Data(data) => {
                    let entry_data = ResourceDirectoryEntry {
                        name_offset_or_integer_id,
                        data_entry_or_subdirectory_offset: *descriptions_offset,
                    };
                    tables_data.push(TableData::Entry(entry_data));
                    next_table_offset += 8;

                    let mut data_len = data.data.len();
                    if data_len > u32::MAX as _ {
                        // TODO (semver): return result
                        error!(
                            "resource entry data is larger than {}B and will be truncated (is {}B)",
                            u32::MAX,
                            data_len
                        );
                        data_len = u32::MAX as _;
                    }
                    let data_len = data_len as u32;

                    data_data.extend(&data.data[..data_len as usize]);
                    let description_data = ResourceDataEntry {
                        data_rva: *data_offset + virtual_address,
                        size:     data_len,
                        codepage: data.codepage,
                        reserved: data.reserved,
                    };
                    descriptions_data.push(description_data);
                    *descriptions_offset += 16;
                    *data_offset += data_len;
                }
            }
        }
        *tables_offset += next_table_offset;

        for name in &sorted_keys {
            let entry = &self.entries[*name];
            match entry {
                ResourceEntry::Table(table) => {
                    let (t_tables_data, t_strings_data, t_descriptions_data, t_data_data) = table
                        .build_table(
                            virtual_address,
                            tables_offset,
                            strings_offset,
                            descriptions_offset,
                            data_offset,
                        );
                    tables_data.extend(t_tables_data);
                    strings_data.extend(t_strings_data);
                    descriptions_data.extend(t_descriptions_data);
                    data_data.extend(t_data_data);
                }
                ResourceEntry::Data(_) => {}
            }
        }

        (tables_data, strings_data, descriptions_data, data_data)
    }

    /// Get a resource entry from the table.
    /// # Returns
    /// The resource entry.
    pub fn get<N: Borrow<ResourceEntryName>>(&self, name: N) -> Option<&ResourceEntry> {
        self.entries.get(name.borrow())
    }

    /// Get a mutable resource entry from the table.
    /// # Returns
    /// The resource entry.
    pub fn get_mut<N: Borrow<ResourceEntryName>>(&mut self, name: N) -> Option<&mut ResourceEntry> {
        self.entries.get_mut(name.borrow())
    }

    /// Insert a resource entry into the table.
    /// If an entry with the given name already exists, it will be replaced.
    /// # Returns
    /// The replaced entry.
    pub fn insert<N: Borrow<ResourceEntryName>>(
        &mut self, name: N, entry: ResourceEntry,
    ) -> Option<ResourceEntry> {
        let name = name.borrow();
        let entry = self.entries.insert(name.clone(), entry);
        if entry.is_none() {
            if name.string_size() > 0 {
                self.data.number_of_name_entries += 1;
            } else {
                self.data.number_of_id_entries += 1;
            }
        }
        entry
    }

    /// Insert a resource entry into the table at the specified position.
    /// If an entry with the given name already exists, it will be replaced.
    /// # Returns
    /// The replaced entry.
    pub fn insert_at<N: Borrow<ResourceEntryName>>(
        &mut self, name: N, entry: ResourceEntry, position: usize,
    ) -> Option<ResourceEntry> {
        let name = name.borrow();
        let len = self.entries.len();
        let old_entry = self.entries.get(name).cloned();
        let new_entry = self
            .entries
            .entry(name.clone())
            .and_modify(|old_entry| *old_entry = entry.clone());
        let index = new_entry.index();
        new_entry.or_insert(entry);
        self.entries.move_index(index, position);
        if index >= len {
            if name.string_size() > 0 {
                self.data.number_of_name_entries += 1;
            } else {
                self.data.number_of_id_entries += 1;
            }
        }
        old_entry
    }

    /// Remove a resource entry from the table.
    /// # Returns
    /// The removed entry.
    pub fn remove<N: Borrow<ResourceEntryName>>(&mut self, name: N) -> Option<ResourceEntry> {
        let name = name.borrow();
        if let Some(entry) = self.entries.swap_remove(name) {
            if name.string_size() > 0 {
                self.data.number_of_name_entries -= 1;
            } else {
                self.data.number_of_id_entries -= 1;
            }
            Some(entry)
        } else {
            None
        }
    }

    /// Returns the entries in the table.
    pub fn entries(&self) -> Vec<&ResourceEntryName> { self.entries.keys().collect() }

    /// Returns the complete size of the table, its resources and its children in the resource table.
    pub fn size(&self) -> u32 {
        self.tables_size() + self.strings_size() + self.descriptions_size() + self.data_size()
    }

    /// Returns the size of the table and its children in the resource table.
    pub fn tables_size(&self) -> u32 {
        self.entries.iter().map(|(_, entry)| entry.table_size()).sum::<u32>() + 16
    }

    /// Returns the size of the strings in the entry and its children in the resource table.
    pub fn strings_size(&self) -> u32 {
        self.entries
            .iter()
            .map(|(name, entry)| name.string_size() + entry.strings_size())
            .sum::<u32>()
    }

    /// Returns the size of the descriptions in the tables children in the resource table.
    pub fn descriptions_size(&self) -> u32 {
        self.entries.iter().map(|(_, entry)| entry.description_size()).sum::<u32>()
    }

    /// Returns the size of the data in in the tables children in the resource table.
    pub fn data_size(&self) -> u32 {
        self.entries.iter().map(|(_, entry)| entry.data_size()).sum::<u32>()
    }
}

/// Raw resource data.
#[derive(Debug, Clone, Eq, PartialEq)]
pub struct ResourceData {
    data:     DebugIgnore<Vec<u8>>,
    codepage: u32,
    reserved: u32,
}
impl Default for ResourceData {
    fn default() -> Self {
        Self {
            data:     Vec::new().into(),
            codepage: CODE_PAGE_ID_EN_US as u32,
            reserved: 0,
        }
    }
}
impl ResourceData {
    /// Returns the raw data.
    pub fn data(&self) -> &[u8] { &self.data }

    /// Returns the codepage of the data.
    pub fn codepage(&self) -> u32 { self.codepage }

    /// Set the raw data.
    pub fn set_data(&mut self, data: Vec<u8>) { self.data = data.into(); }

    /// Set the codepage of the data.
    pub fn set_codepage(&mut self, codepage: u32) { self.codepage = codepage; }
}

/// Resource entry in a resource table.
/// This can be either a child table or raw data.
#[derive(Debug, Clone, Eq, PartialEq)]
pub enum ResourceEntry {
    Table(ResourceTable),
    Data(ResourceData),
}
impl Default for ResourceEntry {
    fn default() -> Self { Self::Data(ResourceData::default()) }
}
impl ResourceEntry {
    /// Returns if the data is a table.
    pub fn is_table(&self) -> bool {
        match self {
            ResourceEntry::Table(_) => true,
            ResourceEntry::Data(_) => false,
        }
    }

    /// Returns if the data is an entry.
    pub fn is_data(&self) -> bool {
        match self {
            ResourceEntry::Table(_) => false,
            ResourceEntry::Data(_) => true,
        }
    }

    /// Returns the sub-table if the data is an table.
    pub fn as_table(&self) -> Option<&ResourceTable> {
        match self {
            ResourceEntry::Table(table) => Some(table),
            ResourceEntry::Data(_) => None,
        }
    }

    /// Returns the mutable sub-table if the data is an table.
    pub fn as_table_mut(&mut self) -> Option<&mut ResourceTable> {
        match self {
            ResourceEntry::Table(table) => Some(table),
            ResourceEntry::Data(_) => None,
        }
    }

    /// Returns the table entry if the data is an entry.
    pub fn as_data(&self) -> Option<&ResourceData> {
        match self {
            ResourceEntry::Table(_) => None,
            ResourceEntry::Data(entry) => Some(entry),
        }
    }

    /// Returns the table entry if the data is an entry.
    pub fn as_data_mut(&mut self) -> Option<&mut ResourceData> {
        match self {
            ResourceEntry::Table(_) => None,
            ResourceEntry::Data(entry) => Some(entry),
        }
    }

    /// Returns the size of the table entry and its children in the resource table.
    pub fn table_size(&self) -> u32 {
        match self {
            // entry + sub-table
            ResourceEntry::Table(table) => table.tables_size() + 8,
            // entry
            ResourceEntry::Data(_) => 8,
        }
    }

    /// Returns the size of the strings in the entry and its children in the resource table.
    /// This is the size of the resouorce names of child tables.
    pub fn strings_size(&self) -> u32 {
        match self {
            ResourceEntry::Table(table) => table.strings_size(),
            ResourceEntry::Data(_) => 0,
        }
    }

    /// Returns the size of the descriptions in the entry and its children in the resource table.
    /// This is the size of the resource data description of the entry or child entries.
    pub fn description_size(&self) -> u32 {
        match self {
            ResourceEntry::Table(table) => table.descriptions_size(),
            ResourceEntry::Data(_) => 16,
        }
    }

    /// Returns the size of the data in the entry and its children in the resource table.
    /// This is the size of the resource data of the entry or child entries.
    pub fn data_size(&self) -> u32 {
        match self {
            ResourceEntry::Table(table) => table.data_size(),
            ResourceEntry::Data(data) => data.data.len() as u32,
        }
    }
}

/// Resource directory entry name.
/// This can either be a raw id or a name.
#[derive(Debug, Clone, Eq, PartialEq, Hash)]
pub enum ResourceEntryName {
    // raw id
    ID(u32),
    // 2 byte size + data
    Name(Vec<u8>),
}
impl Default for ResourceEntryName {
    fn default() -> Self { Self::ID(LANGUAGE_ID_EN_US as u32) }
}
impl ResourceEntryName {
    fn parse(image: &[u8], offset: u32, id: u32) -> Result<Self, ReadError> {
        if id & 0x80000000 != 0 {
            trace!("reading resource name {:#x?}", id);
            let address = offset
                .checked_add(id ^ 0x80000000)
                .ok_or_else(|| ReadError("resource name offset overflows".into()))?;
            let length = read_at::<u16>(image, address as usize)? as usize;
            trace!("resource name length: {}", length);
            // size is in 16 bit characters so it needs to be doubled
            let byte_length = length
                .checked_mul(2)
                .and_then(|length| length.checked_add(2))
                .ok_or_else(|| ReadError("resource name length overflows".into()))?;
            let data = checked_slice(image, address as usize, byte_length)?;
            trace!("resource name: {:x?}", data);
            Ok(Self::Name(data.to_vec()))
        } else {
            trace!("reading resource id {:#x?}", id);
            Ok(Self::ID(id))
        }
    }

    pub fn from_string<S: AsRef<str>>(string: S) -> Self {
        Self::try_from_string(string).expect("resource name exceeds 65535 UTF-16 units")
    }

    pub fn try_from_string<S: AsRef<str>>(string: S) -> Result<Self, ResourceError> {
        let string = string.as_ref();
        let string = string.encode_utf16().collect::<Vec<_>>();
        let length = u16::try_from(string.len()).map_err(|_| {
            ResourceError::InvalidBytes(ReadError(
                "resource name exceeds 65535 UTF-16 units".into(),
            ))
        })?;
        let mut data = Vec::with_capacity(string.len() * 2 + 2);
        data.extend_from_slice(&length.to_le_bytes());
        data.extend(string.into_iter().flat_map(|c| c.to_le_bytes()));
        Ok(Self::Name(data))
    }

    pub fn to_string(&self) -> Option<String> {
        match self {
            Self::ID(_) => None,
            Self::Name(data) => {
                let length = read_at::<u16>(data, 0).ok()? as usize;
                let data = checked_slice(data, 2, length.checked_mul(2)?).ok()?;
                let string = (0..length)
                    .map(|index| u16::from_le_bytes([data[index * 2], data[index * 2 + 1]]))
                    .collect::<Vec<_>>();
                Some(String::from_utf16_lossy(&string))
            }
        }
    }

    fn string_size(&self) -> u32 {
        match self {
            Self::ID(_) => 0,
            Self::Name(name) => name.len() as u32,
        }
    }

    fn id(&self) -> u32 {
        match self {
            Self::ID(id) => *id,
            Self::Name(_) => unreachable!(),
        }
    }

    fn string_data(&self) -> &[u8] {
        match self {
            Self::ID(_) => &[],
            Self::Name(data) => data.as_bytes(),
        }
    }
}

/// Version string table.
/// This is an entry in the version info resource.
#[derive(Debug, Clone, Eq, PartialEq, Default)]
pub struct VersionStringTable {
    pub key:     String,
    pub strings: IndexMap<String, String, RandomState>,
}

/// Version info resource.
/// This is a special resource that contains the version information of the executable.
#[derive(Debug, Clone, Eq, PartialEq, Default)]
pub struct VersionInfo {
    pub info:    FixedFileInfo,
    pub strings: Vec<VersionStringTable>,
    pub vars:    Vec<VersionU16>,
}

fn version_block_end(
    start: usize, length: u16, parent_end: usize, name: &str,
) -> Result<usize, ReadError> {
    if (length as usize) < size_of::<VersionHeader>() {
        return Err(ReadError(format!("{name} length is smaller than its header")));
    }
    let end = start
        .checked_add(length as usize)
        .ok_or_else(|| ReadError(format!("{name} length overflows")))?;
    if end > parent_end {
        return Err(ReadError(format!("{name} end {end:#x} exceeds parent end {parent_end:#x}")));
    }
    Ok(end)
}

fn version_length(value: usize, name: &str) -> Result<u16, ResourceError> {
    u16::try_from(value).map_err(|_| {
        ResourceError::InvalidBytes(ReadError(format!("{name} exceeds the 65535-byte limit")))
    })
}

impl VersionInfo {
    /// Parse the version info resource from a byte slice.
    ///
    /// # Returns
    /// Returns an error if the version info resource is not well-formed.
    pub fn parse(data: &[u8]) -> Result<Self, ReadError> {
        // read the version root header
        let header = read::<VersionHeader>(data)?;
        let root_end = version_block_end(0, header.length, data.len(), "version root")?;
        let data = checked_slice(data, 0, root_end)?;

        let version_root_key =
            read_u16_string(checked_slice(data, size_of::<VersionHeader>(), 32)?)?;
        if version_root_key != "VS_VERSION_INFO" {
            return Err(ReadError(format!("invalid version root key: {:?}", version_root_key)));
        }
        let value_offset =
            aligned_to(size_of::<VersionHeader>() + u16_string_len(&version_root_key) * 2 + 2, 4);

        // read the fixed file info
        if header.value_length != size_of::<FixedFileInfo>() as u16 {
            return Err(ReadError(format!(
                "invalid file info length: {:#x?}",
                header.value_length
            )));
        }
        let info = read_at::<FixedFileInfo>(data, value_offset)?;
        if info.signature != 0xfeef04bd {
            return Err(ReadError(format!(
                "invalid fixed file info signature: {:#x?}",
                info.signature
            )));
        }
        let file_info_header_offset = aligned_to(value_offset + size_of::<FixedFileInfo>(), 4);

        let mut child_offset = file_info_header_offset;
        let mut strings = Vec::new();
        let mut vars = Vec::new();

        while child_offset < data.len() {
            // read the file info header
            let file_info_header = read_at::<VersionHeader>(data, child_offset)?;
            let file_info_end = version_block_end(
                child_offset,
                file_info_header.length,
                data.len(),
                "version child",
            )?;
            let key_offset = child_offset + size_of::<VersionHeader>();
            let file_info_key =
                read_u16_string(checked_slice(data, key_offset, file_info_end - key_offset)?)?;
            let mut tables_offset = aligned_to(
                child_offset + size_of::<VersionHeader>() + u16_string_len(&file_info_key) * 2 + 2,
                4,
            );
            if tables_offset > file_info_end {
                return Err(ReadError("version child key exceeds its block".into()));
            }

            match file_info_key.as_str() {
                "VarFileInfo" => {
                    let var_header = read_at::<VersionHeader>(data, tables_offset)?;
                    let var_end = version_block_end(
                        tables_offset,
                        var_header.length,
                        file_info_end,
                        "translation table",
                    )?;
                    let key_offset = tables_offset + size_of::<VersionHeader>();
                    let table_key =
                        read_u16_string(checked_slice(data, key_offset, var_end - key_offset)?)?;
                    if &table_key != "Translation" {
                        return Err(ReadError(format!("invalid var table key: {:?}", table_key)));
                    }
                    let vars_offset = aligned_to(
                        tables_offset
                            + size_of::<VersionHeader>()
                            + u16_string_len(&table_key) * 2
                            + 2,
                        4,
                    );
                    let vars_end = vars_offset
                        .checked_add(var_header.value_length as usize)
                        .ok_or_else(|| ReadError("translation value length overflows".into()))?;
                    if vars_end > var_end
                        || var_header.value_length as usize % size_of::<u32>() != 0
                    {
                        return Err(ReadError("invalid translation value length".into()));
                    }
                    let mut var_offset = vars_offset;
                    while var_offset < vars_end {
                        vars.push(read_at::<VersionU16>(data, var_offset)?);
                        var_offset += size_of::<u32>();
                    }
                }
                "StringFileInfo" => {
                    while tables_offset < file_info_end {
                        let string_table_header = read_at::<VersionHeader>(data, tables_offset)?;
                        let string_table_end = version_block_end(
                            tables_offset,
                            string_table_header.length,
                            file_info_end,
                            "version string table",
                        )?;
                        let key_offset = tables_offset + size_of::<VersionHeader>();
                        let string_table_key = read_u16_string(checked_slice(
                            data,
                            key_offset,
                            string_table_end - key_offset,
                        )?)?;
                        let strings_offset = aligned_to(
                            tables_offset
                                + size_of::<VersionHeader>()
                                + u16_string_len(&string_table_key) * 2
                                + 2,
                            4,
                        );
                        if strings_offset > string_table_end {
                            return Err(ReadError(
                                "version string table key exceeds its block".into(),
                            ));
                        }

                        let mut string_offset = strings_offset;
                        let mut string_table = VersionStringTable {
                            key:     string_table_key,
                            strings: IndexMap::default(),
                        };

                        while string_offset < string_table_end {
                            let string_start = string_offset;
                            let string_header = read_at::<VersionHeader>(data, string_start)?;
                            let string_end = version_block_end(
                                string_start,
                                string_header.length,
                                string_table_end,
                                "version string",
                            )?;
                            let key_offset = string_start + size_of::<VersionHeader>();
                            let string_key = read_u16_string(checked_slice(
                                data,
                                key_offset,
                                string_end - key_offset,
                            )?)?;
                            let value_offset =
                                aligned_to(key_offset + u16_string_len(&string_key) * 2 + 2, 4);
                            let value_length =
                                (string_header.value_length as usize).checked_mul(2).ok_or_else(
                                    || ReadError("version string length overflows".into()),
                                )?;
                            let value_end = value_offset
                                .checked_add(value_length)
                                .ok_or_else(|| ReadError("version string end overflows".into()))?;
                            if value_end > string_end {
                                return Err(ReadError(
                                    "version string value exceeds its block".into(),
                                ));
                            }

                            if string_header.value_length > 0 && string_header.type_ == 1 {
                                let string_value = read_u16_string(checked_slice(
                                    data,
                                    value_offset,
                                    value_length,
                                )?)?;
                                string_table.strings.insert(string_key, string_value);
                            } else if string_header.value_length > 0 {
                                error!(
                                    "invalid string value type: {:#x?} (expected 0x1)",
                                    string_header.type_
                                );
                            };
                            string_offset = aligned_to(string_end, 4);
                        }
                        tables_offset = aligned_to(string_table_end, 4);
                        strings.push(string_table);
                    }
                }
                _ => {
                    return Err(ReadError(format!(
                        "invalid version string key: {:?}",
                        file_info_key
                    )));
                }
            }
            child_offset = aligned_to(file_info_end, 4);
        }

        Ok(Self {
            info,
            strings,
            vars,
        })
    }

    /// Build the version info into raw bytes to be included in a resource table.
    pub fn try_build(&self) -> Result<Vec<u8>, ResourceError> {
        let mut data = Vec::new();

        let mut string_tables = Vec::new();
        for string_table_data in &self.strings {
            let mut string_table_children = Vec::new();
            for (key, value) in &string_table_data.strings {
                let key_units = u16_string_len(key);
                let value_units = u16_string_len(value);
                let mut string = Vec::new();
                string.extend(
                    VersionHeader {
                        length:       version_length(
                            aligned_to(6 + key_units * 2 + 2, 4) + value_units * 2 + 2,
                            "version string",
                        )?,
                        value_length: version_length(value_units + 1, "version string value")?,
                        type_:        1,
                    }
                    .as_bytes(),
                );
                string.extend(string_to_u16(key));
                string.extend(iter::repeat(0).take(aligned_to(string.len(), 4) - string.len()));
                string.extend(string_to_u16(value));
                string.extend(iter::repeat(0).take(aligned_to(string.len(), 4) - string.len()));
                string_table_children.extend(string);
            }
            let mut string_table = Vec::new();
            let key_units = u16_string_len(&string_table_data.key);
            string_table.extend(
                VersionHeader {
                    length:       version_length(
                        aligned_to(6 + key_units * 2 + 2, 4) + string_table_children.len(),
                        "version string table",
                    )?,
                    value_length: 0,
                    type_:        1,
                }
                .as_bytes(),
            );
            string_table.extend(string_to_u16(&string_table_data.key));
            string_table.extend(
                iter::repeat(0).take(aligned_to(string_table.len(), 4) - string_table.len()),
            );
            string_table.extend(string_table_children);
            string_tables.extend(string_table);
        }

        let mut string_info = Vec::new();
        let string_info_key_units = u16_string_len("StringFileInfo");
        string_info.extend(
            VersionHeader {
                length:       version_length(
                    aligned_to(6 + string_info_key_units * 2 + 2, 4) + string_tables.len(),
                    "string file info",
                )?,
                value_length: 0,
                type_:        1,
            }
            .as_bytes(),
        );
        string_info.extend(string_to_u16("StringFileInfo"));
        string_info
            .extend(iter::repeat(0).take(aligned_to(string_info.len(), 4) - string_info.len()));
        string_info.extend(string_tables);

        let mut var = Vec::new();
        let var_data_length = self
            .vars
            .len()
            .checked_mul(size_of::<VersionU16>())
            .expect("translation data length overflows usize");
        let translation_key_units = u16_string_len("Translation");
        var.extend(
            VersionHeader {
                length:       version_length(
                    aligned_to(6 + translation_key_units * 2 + 2, 4) + var_data_length,
                    "translation table",
                )?,
                value_length: version_length(var_data_length, "translation data")?,
                type_:        0,
            }
            .as_bytes(),
        );
        var.extend(string_to_u16("Translation"));
        var.extend(iter::repeat(0).take(aligned_to(var.len(), 4) - var.len()));
        var.extend(self.vars.iter().flat_map(|var| var.as_bytes()));
        var.extend(iter::repeat(0).take(aligned_to(var.len(), 4) - var.len()));

        let mut var_info = Vec::new();
        let var_info_key_units = u16_string_len("VarFileInfo");
        var_info.extend(
            VersionHeader {
                length:       version_length(
                    aligned_to(6 + var_info_key_units * 2 + 2, 4) + var.len(),
                    "var file info",
                )?,
                value_length: 0,
                type_:        1,
            }
            .as_bytes(),
        );
        var_info.extend(string_to_u16("VarFileInfo"));
        var_info.extend(iter::repeat(0).take(aligned_to(var_info.len(), 4) - var_info.len()));
        var_info.extend(var);

        let root_key_units = u16_string_len("VS_VERSION_INFO");
        data.extend(
            VersionHeader {
                length:       version_length(
                    aligned_to(
                        aligned_to(6 + root_key_units * 2 + 2, 4) + size_of::<FixedFileInfo>(),
                        4,
                    ) + string_info.len()
                        + var_info.len(),
                    "version root",
                )?,
                value_length: version_length(size_of::<FixedFileInfo>(), "fixed file info")?,
                type_:        0,
            }
            .as_bytes(),
        );
        data.extend(string_to_u16("VS_VERSION_INFO"));
        data.extend(iter::repeat(0).take(aligned_to(data.len(), 4) - data.len()));
        data.extend(self.info.as_bytes());
        data.extend(iter::repeat(0).take(aligned_to(data.len(), 4) - data.len()));
        data.extend(string_info);
        data.extend(var_info);

        Ok(data)
    }

    /// Build the version info into raw bytes to be included in a resource table.
    pub fn build(&self) -> Vec<u8> {
        self.try_build().expect("version information exceeds format limits")
    }
}