summaryrefslogtreecommitdiffstats
path: root/src/lib/kStuff/kLdr/kLdrModPE.c
blob: 1a9bbc24c341f75e992fabeb57e9d4f22b2a8b9d (plain)
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
/* $Id: kLdrModPE.c 117 2020-03-15 15:23:36Z bird $ */
/** @file
 * kLdr - The Module Interpreter for the Portable Executable (PE) Format.
 */

/*
 * Copyright (c) 2006-2007 Knut St. Osmundsen <bird-kStuff-spamix@anduin.net>
 *
 * Permission is hereby granted, free of charge, to any person
 * obtaining a copy of this software and associated documentation
 * files (the "Software"), to deal in the Software without
 * restriction, including without limitation the rights to use,
 * copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the
 * Software is furnished to do so, subject to the following
 * conditions:
 *
 * The above copyright notice and this permission notice shall be
 * included in all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
 * OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
 * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
 * WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
 * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
 * OTHER DEALINGS IN THE SOFTWARE.
 */

/*******************************************************************************
*   Header Files                                                               *
*******************************************************************************/
#include <k/kLdr.h>
#include "kLdrInternal.h"
#include <k/kLdrFmts/pe.h>


/*******************************************************************************
*   Defined Constants And Macros                                               *
*******************************************************************************/
/** @def KLDRMODPE_STRICT
 * Define KLDRMODPE_STRICT to enabled strict checks in KLDRMODPE. */
#define KLDRMODPE_STRICT 1

/** @def KLDRMODPE_ASSERT
 * Assert that an expression is true when KLDR_STRICT is defined.
 */
#ifdef KLDRMODPE_STRICT
# define KLDRMODPE_ASSERT(expr)  kHlpAssert(expr)
#else
# define KLDRMODPE_ASSERT(expr)  do {} while (0)
#endif

/** @def KLDRMODPE_RVA2TYPE
 * Converts a RVA to a pointer of the specified type.
 * @param   pvBits      The bits (image base).
 * @param   uRVA        The image relative virtual address.
 * @param   type        The type to cast to.
 */
#define KLDRMODPE_RVA2TYPE(pvBits, uRVA, type) \
        ( (type) ((KUPTR)(pvBits) + (KUPTR)(uRVA)) )

/** @def KLDRMODPE_VALID_RVA
 * Checks that the specified RVA value is non-zero and within the bounds of the image.
 * @returns true/false.
 * @param   pModPE      The PE module interpreter instance.
 * @param   uRVA        The RVA to validate.
 */
#define KLDRMODPE_VALID_RVA(pModPE, uRVA) \
        ( (uRVA) && (uRVA) < (pModPE)->Hdrs.OptionalHeader.SizeOfImage )



/*******************************************************************************
*   Structures and Typedefs                                                    *
*******************************************************************************/
/**
 * Instance data for the PE module interpreter.
 */
typedef struct KLDRMODPE
{
    /** Pointer to the module. (Follows the section table.) */
    PKLDRMOD                pMod;
    /** Pointer to the RDR mapping of the raw file bits. NULL if not mapped. */
    const void             *pvBits;
    /** Pointer to the user mapping. */
    const void             *pvMapping;
    /** Reserved flags. */
    KU32                    f32Reserved;
    /** The number of imported modules.
     * If ~(KU32)0 this hasn't been determined yet. */
    KU32                    cImportModules;
    /** The offset of the NT headers. */
    KLDRFOFF                offHdrs;
    /** Copy of the NT headers. */
    IMAGE_NT_HEADERS64      Hdrs;
    /** The section header table . */
    IMAGE_SECTION_HEADER    aShdrs[1];
} KLDRMODPE, *PKLDRMODPE;


/*******************************************************************************
*   Internal Functions                                                         *
*******************************************************************************/
static KI32 kldrModPENumberOfImports(PKLDRMOD pMod, const void *pvBits);
static int  kldrModPERelocateBits(PKLDRMOD pMod, void *pvBits, KLDRADDR NewBaseAddress, KLDRADDR OldBaseAddress,
                                  PFNKLDRMODGETIMPORT pfnGetImport, void *pvUser);

static int  kldrModPEDoCreate(PKRDR pRdr, KLDRFOFF offNewHdr, PKLDRMODPE *ppMod);
/*static void kldrModPEDoLoadConfigConversion(PIMAGE_LOAD_CONFIG_DIRECTORY64 pLoadCfg); */
static int  kLdrModPEDoOptionalHeaderValidation(PKLDRMODPE pModPE);
static int  kLdrModPEDoSectionHeadersValidation(PKLDRMODPE pModPE);
static void kldrModPEDoOptionalHeaderConversion(PIMAGE_OPTIONAL_HEADER64 pOptionalHeader);
static int  kldrModPEDoForwarderQuery(PKLDRMODPE pModPE, const void *pvBits, const char *pszForwarder,
                                     PFNKLDRMODGETIMPORT pfnGetImport, void *pvUser, PKLDRADDR puValue, KU32 *pfKind);
static int  kldrModPEDoFixups(PKLDRMODPE pModPE, void *pvMapping, KLDRADDR NewBaseAddress, KLDRADDR OldBaseAddress);
static int  kldrModPEDoImports32Bit(PKLDRMODPE pModPE, void *pvMapping, const IMAGE_IMPORT_DESCRIPTOR *pImpDesc,
                                    PFNKLDRMODGETIMPORT pfnGetImport, void *pvUser);
static int  kldrModPEDoImports64Bit(PKLDRMODPE pModPE, void *pvMapping, const IMAGE_IMPORT_DESCRIPTOR *pImpDesc,
                                    PFNKLDRMODGETIMPORT pfnGetImport, void *pvUser);
static int  kldrModPEDoImports(PKLDRMODPE pModPE, void *pvMapping, PFNKLDRMODGETIMPORT pfnGetImport, void *pvUser);
static int  kldrModPEDoCallDLL(PKLDRMODPE pModPE, void *pvMapping, unsigned uOp, KUPTR uHandle);
static int  kldrModPEDoCallTLS(PKLDRMODPE pModPE, void *pvMapping, unsigned uOp, KUPTR uHandle);


/**
 * Create a loader module instance interpreting the executable image found
 * in the specified file provider instance.
 *
 * @returns 0 on success and *ppMod pointing to a module instance.
 *          On failure, a non-zero OS specific error code is returned.
 * @param   pOps            Pointer to the registered method table.
 * @param   pRdr            The file provider instance to use.
 * @param   fFlags          Flags, MBZ.
 * @param   enmCpuArch      The desired CPU architecture. KCPUARCH_UNKNOWN means
 *                          anything goes, but with a preference for the current
 *                          host architecture.
 * @param   offNewHdr       The offset of the new header in MZ files. -1 if not found.
 * @param   ppMod           Where to store the module instance pointer.
 */
static int kldrModPECreate(PCKLDRMODOPS pOps, PKRDR pRdr, KU32 fFlags, KCPUARCH enmCpuArch, KLDRFOFF offNewHdr, PPKLDRMOD ppMod)
{
    PKLDRMODPE pModPE;
    int rc;
    K_NOREF(fFlags);

    /*
     * Create the instance data and do a minimal header validation.
     */
    rc = kldrModPEDoCreate(pRdr, offNewHdr, &pModPE);
    if (!rc)
    {
        /*
         * Match up against the requested CPU architecture.
         */
        if (    enmCpuArch == KCPUARCH_UNKNOWN
            ||  pModPE->pMod->enmArch == enmCpuArch)
        {
            pModPE->pMod->pOps = pOps;
            pModPE->pMod->u32Magic = KLDRMOD_MAGIC;
            *ppMod = pModPE->pMod;
            return 0;
        }
        rc = KLDR_ERR_CPU_ARCH_MISMATCH;
    }
    kHlpFree(pModPE);
    return rc;
}


/**
 * Separate function for reading creating the PE module instance to
 * simplify cleanup on failure.
 */
static int kldrModPEDoCreate(PKRDR pRdr, KLDRFOFF offNewHdr, PKLDRMODPE *ppModPE)
{
    struct
    {
        KU32                Signature;
        IMAGE_FILE_HEADER   FileHdr;
    } s;
    PKLDRMODPE pModPE;
    PKLDRMOD pMod;
    KSIZE cb;
    KSIZE cchFilename;
    KLDRFOFF off;
    KU32 i;
    int rc;
    *ppModPE = NULL;

    /*
     * Read the signature and file header.
     */
    rc = kRdrRead(pRdr, &s, sizeof(s), offNewHdr > 0 ? offNewHdr : 0);
    if (rc)
        return rc;
    if (s.Signature != IMAGE_NT_SIGNATURE)
        return KLDR_ERR_UNKNOWN_FORMAT;

    /* sanity checks. */
    if (    s.FileHdr.NumberOfSections > 4096
        ||  (   s.FileHdr.SizeOfOptionalHeader != sizeof(IMAGE_OPTIONAL_HEADER32)
             && s.FileHdr.SizeOfOptionalHeader != sizeof(IMAGE_OPTIONAL_HEADER64))
        ||  !(s.FileHdr.Characteristics & IMAGE_FILE_EXECUTABLE_IMAGE)
       )
        return KLDR_ERR_PE_BAD_FILE_HEADER;
    if (    s.FileHdr.Machine != IMAGE_FILE_MACHINE_I386
        &&  s.FileHdr.Machine != IMAGE_FILE_MACHINE_AMD64
       )
        return KLDR_ERR_PE_UNSUPPORTED_MACHINE;

    /*
     * Calc the instance size, allocate and initialize it.
     */
    cchFilename = kHlpStrLen(kRdrName(pRdr));
    cb = K_ALIGN_Z(K_OFFSETOF(KLDRMODPE, aShdrs[s.FileHdr.NumberOfSections]), 16)
       + K_OFFSETOF(KLDRMOD, aSegments[s.FileHdr.NumberOfSections + 1])
       + cchFilename + 1;
    pModPE = (PKLDRMODPE)kHlpAlloc(cb);
    if (!pModPE)
        return KERR_NO_MEMORY;
    *ppModPE = pModPE;

    /* KLDRMOD */
    pMod = (PKLDRMOD)((KU8 *)pModPE + K_ALIGN_Z(K_OFFSETOF(KLDRMODPE, aShdrs[s.FileHdr.NumberOfSections]), 16));
    pMod->pvData = pModPE;
    pMod->pRdr = pRdr;
    pMod->pOps = NULL;      /* set upon success. */
    pMod->cSegments = s.FileHdr.NumberOfSections + 1;
    pMod->cchFilename = (KU32)cchFilename;
    pMod->pszFilename = (char *)&pMod->aSegments[pMod->cSegments];
    kHlpMemCopy((char *)pMod->pszFilename, kRdrName(pRdr), cchFilename + 1);
    pMod->pszName = kHlpGetFilename(pMod->pszFilename);
    pMod->cchName = (KU32)(cchFilename - (pMod->pszName - pMod->pszFilename));
    pMod->fFlags = 0;
    switch (s.FileHdr.Machine)
    {
        case IMAGE_FILE_MACHINE_I386:
            pMod->enmCpu = KCPU_I386;
            pMod->enmArch = KCPUARCH_X86_32;
            pMod->enmEndian = KLDRENDIAN_LITTLE;
            break;

        case IMAGE_FILE_MACHINE_AMD64:
            pMod->enmCpu = KCPU_K8;
            pMod->enmArch = KCPUARCH_AMD64;
            pMod->enmEndian = KLDRENDIAN_LITTLE;
            break;
        default:
            kHlpAssert(0);
            break;
    }
    pMod->enmFmt = KLDRFMT_PE;
    if (s.FileHdr.Characteristics & IMAGE_FILE_DLL)
        pMod->enmType = !(s.FileHdr.Characteristics & IMAGE_FILE_RELOCS_STRIPPED)
            ? KLDRTYPE_SHARED_LIBRARY_RELOCATABLE
            : KLDRTYPE_SHARED_LIBRARY_FIXED;
    else
        pMod->enmType = !(s.FileHdr.Characteristics & IMAGE_FILE_RELOCS_STRIPPED)
            ? KLDRTYPE_EXECUTABLE_RELOCATABLE
            : KLDRTYPE_EXECUTABLE_FIXED;
    pMod->u32Magic = 0;     /* set upon success. */

    /* KLDRMODPE */
    pModPE->pMod = pMod;
    pModPE->pvBits = NULL;
    pModPE->pvMapping = NULL;
    pModPE->f32Reserved = 0;
    pModPE->cImportModules = ~(KU32)0;
    pModPE->offHdrs = offNewHdr >= 0 ? offNewHdr : 0;
    pModPE->Hdrs.Signature = s.Signature;
    pModPE->Hdrs.FileHeader = s.FileHdr;

    /*
     * Read the optional header and the section table.
     */
    off = pModPE->offHdrs + sizeof(pModPE->Hdrs.Signature) + sizeof(pModPE->Hdrs.FileHeader);
    rc = kRdrRead(pRdr, &pModPE->Hdrs.OptionalHeader, pModPE->Hdrs.FileHeader.SizeOfOptionalHeader, off);
    if (rc)
        return rc;
    if (pModPE->Hdrs.FileHeader.SizeOfOptionalHeader != sizeof(pModPE->Hdrs.OptionalHeader))
        kldrModPEDoOptionalHeaderConversion(&pModPE->Hdrs.OptionalHeader);
    off += pModPE->Hdrs.FileHeader.SizeOfOptionalHeader;
    rc = kRdrRead(pRdr, &pModPE->aShdrs[0], sizeof(IMAGE_SECTION_HEADER) * pModPE->Hdrs.FileHeader.NumberOfSections, off);
    if (rc)
        return rc;

    /*
     * Validate the two.
     */
    rc = kLdrModPEDoOptionalHeaderValidation(pModPE);
    if (rc)
        return rc;
    for (i = 0; i < pModPE->Hdrs.FileHeader.NumberOfSections; i++)
    {
        rc = kLdrModPEDoSectionHeadersValidation(pModPE);
        if (rc)
            return rc;
    }

    /*
     * Setup the KLDRMOD segment array.
     */
    /* The implied headers section. */
    pMod->aSegments[0].pvUser = NULL;
    pMod->aSegments[0].pchName = "TheHeaders";
    pMod->aSegments[0].cchName = sizeof("TheHeaders") - 1;
    pMod->aSegments[0].enmProt = KPROT_READONLY;
    pMod->aSegments[0].cb = pModPE->Hdrs.OptionalHeader.SizeOfHeaders;
    pMod->aSegments[0].Alignment = pModPE->Hdrs.OptionalHeader.SectionAlignment;
    pMod->aSegments[0].LinkAddress = pModPE->Hdrs.OptionalHeader.ImageBase;
    pMod->aSegments[0].offFile = 0;
    pMod->aSegments[0].cbFile = pModPE->Hdrs.OptionalHeader.SizeOfHeaders;
    pMod->aSegments[0].RVA = 0;
    if (pMod->cSegments > 1)
        pMod->aSegments[0].cbMapped = pModPE->aShdrs[0].VirtualAddress;
    else
        pMod->aSegments[0].cbMapped = pModPE->Hdrs.OptionalHeader.SizeOfHeaders;
    pMod->aSegments[0].MapAddress = 0;

    /* The section headers. */
    for (i = 0; i < pModPE->Hdrs.FileHeader.NumberOfSections; i++)
    {
        const char *pch;
        KU32        cb2;

        /* unused */
        pMod->aSegments[i + 1].pvUser = NULL;
        pMod->aSegments[i + 1].MapAddress = 0;
        pMod->aSegments[i + 1].SelFlat = 0;
        pMod->aSegments[i + 1].Sel16bit = 0;
        pMod->aSegments[i + 1].fFlags = 0;

        /* name */
        pMod->aSegments[i + 1].pchName = pch = (const char *)&pModPE->aShdrs[i].Name[0];
        cb2 = IMAGE_SIZEOF_SHORT_NAME;
        while (   cb2 > 0
               && (pch[cb2 - 1] == ' ' || pch[cb2 - 1] == '\0'))
            cb2--;
        pMod->aSegments[i + 1].cchName = cb2;

        /* size and addresses */
        if (!(pModPE->aShdrs[i].Characteristics & IMAGE_SCN_TYPE_NOLOAD))
        {
            /* Kluge to deal with wlink ".reloc" sections that has a VirtualSize of 0 bytes. */
            cb2 = pModPE->aShdrs[i].Misc.VirtualSize;
            if (!cb2)
                cb2 = K_ALIGN_Z(pModPE->aShdrs[i].SizeOfRawData, pModPE->Hdrs.OptionalHeader.SectionAlignment);
            pMod->aSegments[i + 1].cb          = pModPE->aShdrs[i].Misc.VirtualSize;
            pMod->aSegments[i + 1].LinkAddress = pModPE->aShdrs[i].VirtualAddress
                                               + pModPE->Hdrs.OptionalHeader.ImageBase;
            pMod->aSegments[i + 1].RVA         = pModPE->aShdrs[i].VirtualAddress;
            pMod->aSegments[i + 1].cbMapped    = cb2;
            if (i + 2 < pMod->cSegments)
                pMod->aSegments[i + 1].cbMapped= pModPE->aShdrs[i + 1].VirtualAddress
                                               - pModPE->aShdrs[i].VirtualAddress;
        }
        else
        {
            pMod->aSegments[i + 1].cb          = 0;
            pMod->aSegments[i + 1].cbMapped    = 0;
            pMod->aSegments[i + 1].LinkAddress = NIL_KLDRADDR;
            pMod->aSegments[i + 1].RVA         = 0;
        }

        /* file location */
        pMod->aSegments[i + 1].offFile = pModPE->aShdrs[i].PointerToRawData;
        pMod->aSegments[i + 1].cbFile  = pModPE->aShdrs[i].SizeOfRawData;
        if (    pMod->aSegments[i + 1].cbMapped > 0 /* if mapped */
            &&  (KLDRSIZE)pMod->aSegments[i + 1].cbFile > pMod->aSegments[i + 1].cbMapped)
            pMod->aSegments[i + 1].cbFile = (KLDRFOFF)(pMod->aSegments[i + 1].cbMapped);

        /* protection */
        switch (  pModPE->aShdrs[i].Characteristics
                & (IMAGE_SCN_MEM_SHARED | IMAGE_SCN_MEM_EXECUTE | IMAGE_SCN_MEM_READ | IMAGE_SCN_MEM_WRITE))
        {
            case 0:
            case IMAGE_SCN_MEM_SHARED:
                pMod->aSegments[i + 1].enmProt = KPROT_NOACCESS;
                break;
            case IMAGE_SCN_MEM_READ:
            case IMAGE_SCN_MEM_READ | IMAGE_SCN_MEM_SHARED:
                pMod->aSegments[i + 1].enmProt = KPROT_READONLY;
                break;
            case IMAGE_SCN_MEM_WRITE:
            case IMAGE_SCN_MEM_WRITE | IMAGE_SCN_MEM_READ:
                pMod->aSegments[i + 1].enmProt = KPROT_WRITECOPY;
                break;
            case IMAGE_SCN_MEM_WRITE | IMAGE_SCN_MEM_SHARED:
            case IMAGE_SCN_MEM_WRITE | IMAGE_SCN_MEM_SHARED | IMAGE_SCN_MEM_READ:
                pMod->aSegments[i + 1].enmProt = KPROT_READWRITE;
                break;
            case IMAGE_SCN_MEM_EXECUTE:
            case IMAGE_SCN_MEM_EXECUTE | IMAGE_SCN_MEM_SHARED:
                pMod->aSegments[i + 1].enmProt = KPROT_EXECUTE;
                break;
            case IMAGE_SCN_MEM_EXECUTE | IMAGE_SCN_MEM_READ:
            case IMAGE_SCN_MEM_EXECUTE | IMAGE_SCN_MEM_READ | IMAGE_SCN_MEM_SHARED:
                pMod->aSegments[i + 1].enmProt = KPROT_EXECUTE_READ;
                break;
            case IMAGE_SCN_MEM_EXECUTE | IMAGE_SCN_MEM_WRITE:
            case IMAGE_SCN_MEM_EXECUTE | IMAGE_SCN_MEM_WRITE | IMAGE_SCN_MEM_READ:
                pMod->aSegments[i + 1].enmProt = KPROT_EXECUTE_WRITECOPY;
                break;
            case IMAGE_SCN_MEM_EXECUTE | IMAGE_SCN_MEM_WRITE | IMAGE_SCN_MEM_SHARED:
            case IMAGE_SCN_MEM_EXECUTE | IMAGE_SCN_MEM_WRITE | IMAGE_SCN_MEM_SHARED | IMAGE_SCN_MEM_READ:
                pMod->aSegments[i + 1].enmProt = KPROT_EXECUTE_READWRITE;
                break;
        }

        /* alignment. */
        switch (pModPE->aShdrs[i].Characteristics & IMAGE_SCN_ALIGN_MASK)
        {
            case 0: /* hope this is right... */
                pMod->aSegments[i + 1].Alignment = pModPE->Hdrs.OptionalHeader.SectionAlignment;
                break;
            case IMAGE_SCN_ALIGN_1BYTES:        pMod->aSegments[i + 1].Alignment = 1; break;
            case IMAGE_SCN_ALIGN_2BYTES:        pMod->aSegments[i + 1].Alignment = 2; break;
            case IMAGE_SCN_ALIGN_4BYTES:        pMod->aSegments[i + 1].Alignment = 4; break;
            case IMAGE_SCN_ALIGN_8BYTES:        pMod->aSegments[i + 1].Alignment = 8; break;
            case IMAGE_SCN_ALIGN_16BYTES:       pMod->aSegments[i + 1].Alignment = 16; break;
            case IMAGE_SCN_ALIGN_32BYTES:       pMod->aSegments[i + 1].Alignment = 32; break;
            case IMAGE_SCN_ALIGN_64BYTES:       pMod->aSegments[i + 1].Alignment = 64; break;
            case IMAGE_SCN_ALIGN_128BYTES:      pMod->aSegments[i + 1].Alignment = 128; break;
            case IMAGE_SCN_ALIGN_256BYTES:      pMod->aSegments[i + 1].Alignment = 256; break;
            case IMAGE_SCN_ALIGN_512BYTES:      pMod->aSegments[i + 1].Alignment = 512; break;
            case IMAGE_SCN_ALIGN_1024BYTES:     pMod->aSegments[i + 1].Alignment = 1024; break;
            case IMAGE_SCN_ALIGN_2048BYTES:     pMod->aSegments[i + 1].Alignment = 2048; break;
            case IMAGE_SCN_ALIGN_4096BYTES:     pMod->aSegments[i + 1].Alignment = 4096; break;
            case IMAGE_SCN_ALIGN_8192BYTES:     pMod->aSegments[i + 1].Alignment = 8192; break;
            default: kHlpAssert(0);          pMod->aSegments[i + 1].Alignment = 0; break;
        }
    }

    /*
     * We're done.
     */
    *ppModPE = pModPE;
    return 0;
}


/**
 * Converts a 32-bit optional header to a 64-bit one
 *
 * @param   pOptHdr     The optional header to convert.
 */
static void kldrModPEDoOptionalHeaderConversion(PIMAGE_OPTIONAL_HEADER64 pOptHdr)
{
    /* volatile everywhere! */
    IMAGE_OPTIONAL_HEADER32 volatile *pOptHdr32 = (IMAGE_OPTIONAL_HEADER32 volatile *)pOptHdr;
    IMAGE_OPTIONAL_HEADER64 volatile *pOptHdr64 = pOptHdr;
    KU32 volatile                    *pu32Dst;
    KU32 volatile                    *pu32Src;
    KU32 volatile                    *pu32SrcLast;
    KU32                              u32;

    /* From LoaderFlags and out the difference is 4 * 32-bits. */
    pu32Dst     = (KU32 *)&pOptHdr64->DataDirectory[IMAGE_NUMBEROF_DIRECTORY_ENTRIES] - 1;
    pu32Src     = (KU32 *)&pOptHdr32->DataDirectory[IMAGE_NUMBEROF_DIRECTORY_ENTRIES] - 1;
    pu32SrcLast = (KU32 *)&pOptHdr32->LoaderFlags;
    while (pu32Src >= pu32SrcLast)
        *pu32Dst-- = *pu32Src--;

    /* The previous 4 fields are 32/64 and needs special attention. */
    pOptHdr64->SizeOfHeapCommit   = pOptHdr32->SizeOfHeapCommit;
    pOptHdr64->SizeOfHeapReserve  = pOptHdr32->SizeOfHeapReserve;
    pOptHdr64->SizeOfStackCommit  = pOptHdr32->SizeOfStackCommit;
    u32 = pOptHdr32->SizeOfStackReserve;
    pOptHdr64->SizeOfStackReserve = u32;

    /*
     * The rest matches except for BaseOfData which has been merged into ImageBase in the 64-bit version.
     * Thus, ImageBase needs some special treatement. It will probably work fine assigning one to the
     * other since this is all declared volatile, but taking now chances, we'll use a temp variable.
     */
    u32 = pOptHdr32->ImageBase;
    pOptHdr64->ImageBase = u32;
}


#if 0
/**
 * Converts a 32-bit load config directory to a 64 bit one.
 *
 * @param   pOptHdr     The load config to convert.
 */
static void kldrModPEDoLoadConfigConversion(PIMAGE_LOAD_CONFIG_DIRECTORY64 pLoadCfg)
{
    /* volatile everywhere! */
    IMAGE_LOAD_CONFIG_DIRECTORY32 volatile *pLoadCfg32 = (IMAGE_LOAD_CONFIG_DIRECTORY32 volatile *)pLoadCfg;
    IMAGE_LOAD_CONFIG_DIRECTORY64 volatile *pLoadCfg64 = pLoadCfg;
    KU32                                    u32;

    pLoadCfg64->SEHandlerCount             = pLoadCfg32->SEHandlerCount;
    pLoadCfg64->SEHandlerTable             = pLoadCfg32->SEHandlerTable;
    pLoadCfg64->SecurityCookie             = pLoadCfg32->SecurityCookie;
    pLoadCfg64->EditList                   = pLoadCfg32->EditList;
    pLoadCfg64->Reserved1                  = pLoadCfg32->Reserved1;
    pLoadCfg64->CSDVersion                 = pLoadCfg32->CSDVersion;
    /* (ProcessHeapFlags switched place with ProcessAffinityMask, but we're
     * more than 16 byte off by now so it doesn't matter.) */
    pLoadCfg64->ProcessHeapFlags           = pLoadCfg32->ProcessHeapFlags;
    pLoadCfg64->ProcessAffinityMask        = pLoadCfg32->ProcessAffinityMask;
    pLoadCfg64->VirtualMemoryThreshold     = pLoadCfg32->VirtualMemoryThreshold;
    pLoadCfg64->MaximumAllocationSize      = pLoadCfg32->MaximumAllocationSize;
    pLoadCfg64->LockPrefixTable            = pLoadCfg32->LockPrefixTable;
    pLoadCfg64->DeCommitTotalFreeThreshold = pLoadCfg32->DeCommitTotalFreeThreshold;
    u32 = pLoadCfg32->DeCommitFreeBlockThreshold;
    pLoadCfg64->DeCommitFreeBlockThreshold = u32;
    /* the remainder matches. */
}
#endif


/**
 * Internal worker which validates the section headers.
 */
static int kLdrModPEDoOptionalHeaderValidation(PKLDRMODPE pModPE)
{
    const unsigned fIs32Bit = pModPE->Hdrs.FileHeader.SizeOfOptionalHeader == sizeof(IMAGE_OPTIONAL_HEADER32);

    /* the magic */
    if (    pModPE->Hdrs.OptionalHeader.Magic
        !=  (fIs32Bit ? IMAGE_NT_OPTIONAL_HDR32_MAGIC : IMAGE_NT_OPTIONAL_HDR64_MAGIC))
        return KLDR_ERR_PE_BAD_OPTIONAL_HEADER;

    /** @todo validate more */
    return 0;
}


/**
 * Internal worker which validates the section headers.
 */
static int kLdrModPEDoSectionHeadersValidation(PKLDRMODPE pModPE)
{
    /** @todo validate shdrs */
    K_NOREF(pModPE);
    return 0;
}


/** @copydoc KLDRMODOPS::pfnDestroy */
static int kldrModPEDestroy(PKLDRMOD pMod)
{
    PKLDRMODPE pModPE = (PKLDRMODPE)pMod->pvData;
    int rc = 0;
    KLDRMODPE_ASSERT(!pModPE->pvMapping);

    if (pMod->pRdr)
    {
        rc = kRdrClose(pMod->pRdr);
        pMod->pRdr = NULL;
    }
    pMod->u32Magic = 0;
    pMod->pOps = NULL;
    kHlpFree(pModPE);
    return rc;
}


/**
 * Performs the mapping of the image.
 *
 * This can be used to do the internal mapping as well as the
 * user requested mapping. fForReal indicates which is desired.
 *
 * @returns 0 on success, non-zero OS or kLdr status code on failure.
 * @param   pModPE          The interpreter module instance
 * @param   fForReal        If set, do the user mapping. if clear, do the internal mapping.
 */
static int kldrModPEDoMap(PKLDRMODPE pModPE, unsigned fForReal)
{
    PKLDRMOD    pMod = pModPE->pMod;
    KBOOL       fFixed;
    void       *pvBase;
    int         rc;
    KU32        i;

    /*
     * Map it.
     */
    /* fixed image? */
    fFixed = fForReal
          && (   pMod->enmType == KLDRTYPE_EXECUTABLE_FIXED
              || pMod->enmType == KLDRTYPE_SHARED_LIBRARY_FIXED);
    if (!fFixed)
        pvBase = NULL;
    else
    {
        pvBase = (void *)(KUPTR)pMod->aSegments[0].LinkAddress;
        if ((KUPTR)pvBase != pMod->aSegments[0].LinkAddress)
            return KLDR_ERR_ADDRESS_OVERFLOW;
    }

    /* try do the prepare */
    rc = kRdrMap(pMod->pRdr, &pvBase, pMod->cSegments, pMod->aSegments, fFixed);
    if (rc)
        return rc;

    /*
     * Update the segments with their map addresses.
     */
    if (fForReal)
    {
        for (i = 0; i < pMod->cSegments; i++)
        {
            if (pMod->aSegments[i].RVA != NIL_KLDRADDR)
                pMod->aSegments[i].MapAddress = (KUPTR)pvBase + (KUPTR)pMod->aSegments[i].RVA;
        }
        pModPE->pvMapping = pvBase;
    }
    else
        pModPE->pvBits = pvBase;
    return 0;
}


/**
 * Unmaps a image mapping.
 *
 * This can be used to do the internal mapping as well as the
 * user requested mapping. fForReal indicates which is desired.
 *
 * @returns 0 on success, non-zero OS or kLdr status code on failure.
 * @param   pModPE          The interpreter module instance
 * @param   pvMapping       The mapping to unmap.
 */
static int kldrModPEDoUnmap(PKLDRMODPE pModPE, const void *pvMapping)
{
    PKLDRMOD    pMod = pModPE->pMod;
    int         rc;
    KU32        i;

    /*
     * Try unmap the image.
     */
    rc = kRdrUnmap(pMod->pRdr, (void *)pvMapping, pMod->cSegments, pMod->aSegments);
    if (rc)
        return rc;

    /*
     * Update the segments to reflect that they aren't mapped any longer.
     */
    if (pModPE->pvMapping == pvMapping)
    {
        pModPE->pvMapping = NULL;
        for (i = 0; i < pMod->cSegments; i++)
            pMod->aSegments[i].MapAddress = 0;
    }
    if (pModPE->pvBits == pvMapping)
        pModPE->pvBits = NULL;

    return 0;
}


/**
 * Gets usable bits and the right base address.
 *
 * @returns 0 on success.
 * @returns A non-zero status code if the BaseAddress isn't right or some problem is encountered
 *          featch in a temp mapping the bits.
 * @param   pModPE          The interpreter module instance
 * @param   ppvBits         The bits address, IN & OUT.
 * @param   pBaseAddress    The base address, IN & OUT. Optional.
 */
static int kldrModPEBitsAndBaseAddress(PKLDRMODPE pModPE, const void **ppvBits, PKLDRADDR pBaseAddress)
{
    int rc = 0;

    /*
     * Correct the base address.
     *
     * We don't use the base address for interpreting the bits in this
     * interpreter, which makes things relativly simple.
     */
    if (pBaseAddress)
    {
        if (*pBaseAddress == KLDRMOD_BASEADDRESS_MAP)
            *pBaseAddress = pModPE->pMod->aSegments[0].MapAddress;
        else if (*pBaseAddress == KLDRMOD_BASEADDRESS_LINK)
            *pBaseAddress = pModPE->Hdrs.OptionalHeader.ImageBase;
    }

    /*
     * Get bits.
     */
    if (ppvBits && !*ppvBits)
    {
        if (pModPE->pvMapping)
            *ppvBits = pModPE->pvMapping;
        else if (pModPE->pvBits)
            *ppvBits = pModPE->pvBits;
        else
        {
            /* create an internal mapping. */
            rc = kldrModPEDoMap(pModPE, 0 /* not for real */);
            if (rc)
                return rc;
            KLDRMODPE_ASSERT(pModPE->pvBits);
            *ppvBits = pModPE->pvBits;
        }
    }

    return 0;
}


/** @copydoc kLdrModQuerySymbol */
static int kldrModPEQuerySymbol(PKLDRMOD pMod, const void *pvBits, KLDRADDR BaseAddress, KU32 iSymbol,
                                const char *pchSymbol, KSIZE cchSymbol, const char *pszVersion,
                                PFNKLDRMODGETIMPORT pfnGetForwarder, void *pvUser, PKLDRADDR puValue, KU32 *pfKind)

{
    PKLDRMODPE                      pModPE = (PKLDRMODPE)pMod->pvData;
    const KU32                     *paExportRVAs;
    const IMAGE_EXPORT_DIRECTORY   *pExpDir;
    KU32                            iExpOrd;
    KU32                            uRVA;
    int                             rc;

    /*
     * Make sure we've got mapped bits and resolve any base address aliases.
     */
    rc = kldrModPEBitsAndBaseAddress(pModPE, &pvBits, &BaseAddress);
    if (rc)
        return rc;
    if (    pModPE->Hdrs.OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_EXPORT].Size
        <   sizeof(IMAGE_EXPORT_DIRECTORY))
        return KLDR_ERR_SYMBOL_NOT_FOUND;
    if (pszVersion && *pszVersion)
        return KLDR_ERR_SYMBOL_NOT_FOUND;

    pExpDir = KLDRMODPE_RVA2TYPE(pvBits,
                                 pModPE->Hdrs.OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_EXPORT].VirtualAddress,
                                 PIMAGE_EXPORT_DIRECTORY);
    if (!pchSymbol)
    {
        /*
         * Simple, calculate the unbased ordinal and bounds check it.
         */
        iExpOrd = iSymbol - pExpDir->Base;
        if (iExpOrd >= K_MAX(pExpDir->NumberOfNames, pExpDir->NumberOfFunctions))
            return KLDR_ERR_SYMBOL_NOT_FOUND;
    }
    else
    {
        /*
         * Do a binary search for the name.
         * (The name table is sorted in ascending ordered by the linker.)
         */
        const KU32 *paRVANames = KLDRMODPE_RVA2TYPE(pvBits, pExpDir->AddressOfNames, const KU32 *);
        const KU16 *paOrdinals = KLDRMODPE_RVA2TYPE(pvBits, pExpDir->AddressOfNameOrdinals, const KU16 *);
        KI32        iStart = 1; /* one based binary searching is simpler. */
        KI32        iEnd = pExpDir->NumberOfNames;

        for (;;)
        {
            KI32        i;
            int         diff;
            const char *pszName;

            /* done? */
            if (iStart > iEnd)
            {
#ifdef KLDRMODPE_STRICT /* Make sure the linker and we both did our job right. */
                for (i = 0; i < (KI32)pExpDir->NumberOfNames; i++)

                {
                    pszName = KLDRMODPE_RVA2TYPE(pvBits, paRVANames[i], const char *);
                    KLDRMODPE_ASSERT(kHlpStrNComp(pszName, pchSymbol, cchSymbol) || pszName[cchSymbol]);
                    KLDRMODPE_ASSERT(i == 0 || kHlpStrComp(pszName, KLDRMODPE_RVA2TYPE(pvBits, paRVANames[i - 1], const char *)));
                }
#endif
                return KLDR_ERR_SYMBOL_NOT_FOUND;
            }

            i = (iEnd - iStart) / 2 + iStart;
            pszName = KLDRMODPE_RVA2TYPE(pvBits, paRVANames[i - 1], const char *);
            diff = kHlpStrNComp(pszName, pchSymbol, cchSymbol);
            if (!diff)
                diff = pszName[cchSymbol] - 0;
            if (diff < 0)
                iStart = i + 1;     /* The symbol must be after the current name. */
            else if (diff)
                iEnd = i - 1;       /* The symbol must be before the current name. */
            else
            {
                iExpOrd = paOrdinals[i - 1];    /* match! */
                break;
            }
        }
    }

    /*
     * Lookup the address in the 'symbol' table.
     */
    paExportRVAs = KLDRMODPE_RVA2TYPE(pvBits, pExpDir->AddressOfFunctions, const KU32 *);
    uRVA = paExportRVAs[iExpOrd];
    if (    uRVA - pModPE->Hdrs.OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_EXPORT].VirtualAddress
        <   pModPE->Hdrs.OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_EXPORT].Size)
        return kldrModPEDoForwarderQuery(pModPE, pvBits, KLDRMODPE_RVA2TYPE(pvBits, uRVA, const char *),
                                         pfnGetForwarder, pvUser, puValue, pfKind);

    /*
     * Set the return value.
     */
    if (puValue)
        *puValue = BaseAddress + uRVA;
    if (pfKind)
        *pfKind = (pModPE->Hdrs.FileHeader.SizeOfOptionalHeader == sizeof(IMAGE_OPTIONAL_HEADER32)
                   ? KLDRSYMKIND_32BIT : KLDRSYMKIND_64BIT)
                | KLDRSYMKIND_NO_TYPE;
    return 0;
}


/**
 * Deal with a forwarder entry.
 *
 * We do this seprately from kldrModPEQuerySymbol because the code is clumsy (as is all PE code
 * thanks to the descriptive field names), and because it uses quite a bit more stack and we're
 * trying to avoid allocating stack unless we have to.
 *
 * @returns See kLdrModQuerySymbol.
 * @param   pModPE          The PE module interpreter instance.
 * @param   pvBits          Where to read the image from.
 * @param   pszForwarder    The forwarder entry name.
 * @param   pfnGetForwarder The callback for resolving forwarder symbols. (optional)
 * @param   pvUser          The user argument for the callback.
 * @param   puValue         Where to put the value. (optional)
 * @param   pfKind          Where to put the symbol kind. (optional)
 */
static int kldrModPEDoForwarderQuery(PKLDRMODPE pModPE, const void *pvBits, const char *pszForwarder,
                                     PFNKLDRMODGETIMPORT pfnGetForwarder, void *pvUser, PKLDRADDR puValue, KU32 *pfKind)
{
    const IMAGE_IMPORT_DESCRIPTOR *paImpDir;
    KU32            iImpModule;
    KU32            cchImpModule;
    const char     *pszSymbol;
    KU32            iSymbol;
    int             rc;

    if (!pfnGetForwarder)
        return KLDR_ERR_FORWARDER_SYMBOL;

    /*
     * Separate the name into a module name and a symbol name or ordinal.
     *
     * The module name ends at the first dot ('.').
     * After the dot follows either a symbol name or a hash ('#') + ordinal.
     */
    pszSymbol = pszForwarder;
    while (*pszSymbol != '.')
        pszSymbol++;
    if (!*pszSymbol)
        return KLDR_ERR_PE_BAD_FORWARDER;
    cchImpModule = (KU32)(pszSymbol - pszForwarder);

    pszSymbol++;                        /* skip the dot */
    if (!*pszSymbol)
        return KLDR_ERR_PE_BAD_FORWARDER;
    if (*pszSymbol == '#')
    {
        unsigned uBase;
        pszSymbol++;                    /* skip the hash */

        /* base detection */
        uBase = 10;
        if (pszSymbol[0] == '0' &&  (pszSymbol[1] == 'x' || pszSymbol[1] == 'X'))
        {
            uBase = 16;
            pszSymbol += 2;
        }

        /* ascii to integer */
        iSymbol = 0;
        for (;;)
        {
            /* convert char to digit. */
            unsigned uDigit = *pszSymbol++;
            if (uDigit >= '0' && uDigit <= '9')
                uDigit -= '0';
            else if (uDigit >= 'a' && uDigit <= 'z')
                uDigit -= 'a' + 10;
            else if (uDigit >= 'A' && uDigit <= 'Z')
                uDigit -= 'A' + 10;
            else if (!uDigit)
                break;
            else
                return KLDR_ERR_PE_BAD_FORWARDER;
            if (uDigit >= uBase)
                return KLDR_ERR_PE_BAD_FORWARDER;

            /* insert the digit */
            iSymbol *= uBase;
            iSymbol += uDigit;
        }

        pszSymbol = NULL;               /* no symbol name. */
    }
    else
        iSymbol = NIL_KLDRMOD_SYM_ORDINAL; /* no ordinal number. */


    /*
     * Find the import module name.
     *
     * We ASSUME the linker will make sure there is an import
     * entry for the module... not sure if this is right though.
     */
    if (    !pModPE->Hdrs.OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_IMPORT].Size
        ||  !pModPE->Hdrs.OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_IMPORT].VirtualAddress)
        return KLDR_ERR_PE_FORWARDER_IMPORT_NOT_FOUND;
    paImpDir = KLDRMODPE_RVA2TYPE(pvBits,
                                  pModPE->Hdrs.OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_IMPORT].VirtualAddress,
                                  const IMAGE_IMPORT_DESCRIPTOR *);

    kldrModPENumberOfImports(pModPE->pMod, pvBits);
    for (iImpModule = 0; iImpModule < pModPE->cImportModules; iImpModule++)
    {
        const char *pszName = KLDRMODPE_RVA2TYPE(pvBits, paImpDir[iImpModule].Name, const char *);
        KSIZE       cchName = kHlpStrLen(pszName);
        if (    (   cchName == cchImpModule
                 || (   cchName > cchImpModule
                     && pszName[cchImpModule] == '.'
                     && (pszName[cchImpModule + 1] == 'd' || pszName[cchImpModule + 1] == 'D')
                     && (pszName[cchImpModule + 2] == 'l' || pszName[cchImpModule + 2] == 'L')
                     && (pszName[cchImpModule + 3] == 'l' || pszName[cchImpModule + 3] == 'L'))
                )
            &&  kHlpMemICompAscii(pszName, pszForwarder, cchImpModule)
           )
        {
            /*
             * Now the rest is up to the callback (almost).
             */
            rc = pfnGetForwarder(pModPE->pMod, iImpModule, iSymbol, pszSymbol,
                                 pszSymbol ? kHlpStrLen(pszSymbol) : 0, NULL, puValue, pfKind, pvUser);
            if (!rc && pfKind)
                *pfKind |= KLDRSYMKIND_FORWARDER;
            return rc;
        }
    }
    return KLDR_ERR_PE_FORWARDER_IMPORT_NOT_FOUND;
}


/** @copydoc kLdrModEnumSymbols */
static int kldrModPEEnumSymbols(PKLDRMOD pMod, const void *pvBits, KLDRADDR BaseAddress,
                                KU32 fFlags, PFNKLDRMODENUMSYMS pfnCallback, void *pvUser)
{
    PKLDRMODPE                      pModPE = (PKLDRMODPE)pMod->pvData;
    const KU32                     *paFunctions;
    const IMAGE_EXPORT_DIRECTORY   *pExpDir;
    const KU32                     *paRVANames;
    const KU16                     *paOrdinals;
    KU32                            iFunction;
    KU32                            cFunctions;
    KU32                            cNames;
    int                             rc;
    K_NOREF(fFlags);

    /*
     * Make sure we've got mapped bits and resolve any base address aliases.
     */
    rc = kldrModPEBitsAndBaseAddress(pModPE, &pvBits, &BaseAddress);
    if (rc)
        return rc;

    if (    pModPE->Hdrs.OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_EXPORT].Size
        <   sizeof(IMAGE_EXPORT_DIRECTORY))
        return 0; /* no exports to enumerate, return success. */

    pExpDir = KLDRMODPE_RVA2TYPE(pvBits,
                                 pModPE->Hdrs.OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_EXPORT].VirtualAddress,
                                 PIMAGE_EXPORT_DIRECTORY);

    /*
     * Enumerate the ordinal exports.
     */
    paRVANames = KLDRMODPE_RVA2TYPE(pvBits, pExpDir->AddressOfNames, const KU32 *);
    paOrdinals = KLDRMODPE_RVA2TYPE(pvBits, pExpDir->AddressOfNameOrdinals, const KU16 *);
    paFunctions = KLDRMODPE_RVA2TYPE(pvBits, pExpDir->AddressOfFunctions, const KU32 *);
    cFunctions = pExpDir->NumberOfFunctions;
    cNames = pExpDir->NumberOfNames;
    for (iFunction = 0; iFunction < cFunctions; iFunction++)
    {
        unsigned        fFoundName;
        KU32            iName;
        const KU32      uRVA = paFunctions[iFunction];
        const KLDRADDR  uValue = BaseAddress + uRVA;
        KU32            fKind = (pModPE->Hdrs.FileHeader.SizeOfOptionalHeader == sizeof(IMAGE_OPTIONAL_HEADER32)
                              ? KLDRSYMKIND_32BIT : KLDRSYMKIND_64BIT)
                              | KLDRSYMKIND_NO_TYPE;
        if (    uRVA - pModPE->Hdrs.OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_EXPORT].VirtualAddress
            <   pModPE->Hdrs.OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_EXPORT].Size)
            fKind |= KLDRSYMKIND_FORWARDER;

        /*
         * Any symbol names?
         */
        fFoundName = 0;
        for (iName = 0; iName < cNames; iName++)
        {
            const char *pszName;
            if (paOrdinals[iName] != iFunction)
                continue;
            fFoundName = 1;
            pszName = KLDRMODPE_RVA2TYPE(pvBits, paRVANames[iName], const char *);
            rc = pfnCallback(pMod, iFunction + pExpDir->Base, pszName, kHlpStrLen(pszName), NULL,
                             uValue, fKind, pvUser);
            if (rc)
                return rc;
        }

        /*
         * If no names, call once with the ordinal only.
         */
        if (!fFoundName)
        {
            rc = pfnCallback(pMod, iFunction + pExpDir->Base, NULL, 0, NULL, uValue, fKind, pvUser);
            if (rc)
                return rc;
        }
    }

    return 0;
}


/** @copydoc kLdrModGetImport */
static int kldrModPEGetImport(PKLDRMOD pMod, const void *pvBits, KU32 iImport, char *pszName, KSIZE cchName)
{
    PKLDRMODPE                      pModPE = (PKLDRMODPE)pMod->pvData;
    const IMAGE_IMPORT_DESCRIPTOR  *pImpDesc;
    const char                     *pszImportName;
    KSIZE                           cchImportName;
    int                             rc;

    /*
     * Make sure we've got mapped bits and resolve any base address aliases.
     */
    rc = kldrModPEBitsAndBaseAddress(pModPE, &pvBits, NULL);
    if (rc)
        return rc;

    /*
     * Simple bounds check.
     */
    if (iImport >= (KU32)kldrModPENumberOfImports(pMod, pvBits))
        return KLDR_ERR_IMPORT_ORDINAL_OUT_OF_BOUNDS;

    /*
     * Get the name.
     */
    pImpDesc = KLDRMODPE_RVA2TYPE(pvBits,
                                  pModPE->Hdrs.OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_IMPORT].VirtualAddress
                                  + sizeof(IMAGE_IMPORT_DESCRIPTOR) * iImport,
                                  const IMAGE_IMPORT_DESCRIPTOR *);
    pszImportName = KLDRMODPE_RVA2TYPE(pvBits, pImpDesc->Name, const char *);
    cchImportName = kHlpStrLen(pszImportName);
    if (cchImportName < cchName)
    {
        kHlpMemCopy(pszName, pszImportName, cchImportName + 1);
        rc = 0;
    }
    else
    {
        kHlpMemCopy(pszName, pszImportName, cchName);
        if (cchName)
            pszName[cchName - 1] = '\0';
        rc = KERR_BUFFER_OVERFLOW;
    }

    return rc;
}


/** @copydoc kLdrModNumberOfImports */
static KI32 kldrModPENumberOfImports(PKLDRMOD pMod, const void *pvBits)
{
    PKLDRMODPE pModPE = (PKLDRMODPE)pMod->pvData;
    if (pModPE->cImportModules == ~(KU32)0)
    {
        /*
         * We'll have to walk the import descriptors to figure out their number.
         * First, make sure we've got mapped bits.
         */
        if (kldrModPEBitsAndBaseAddress(pModPE, &pvBits, NULL))
            return -1;
        pModPE->cImportModules = 0;
        if (    pModPE->Hdrs.OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_IMPORT].Size
            &&  pModPE->Hdrs.OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_IMPORT].VirtualAddress)
        {
            const IMAGE_IMPORT_DESCRIPTOR  *pImpDesc;

            pImpDesc = KLDRMODPE_RVA2TYPE(pvBits,
                                          pModPE->Hdrs.OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_IMPORT].VirtualAddress,
                                          const IMAGE_IMPORT_DESCRIPTOR *);
            while (pImpDesc->Name && pImpDesc->FirstThunk)
            {
                pModPE->cImportModules++;
                pImpDesc++;
            }
        }
    }
    return pModPE->cImportModules;
}


/** @copydoc kLdrModGetStackInfo */
static int kldrModPEGetStackInfo(PKLDRMOD pMod, const void *pvBits, KLDRADDR BaseAddress, PKLDRSTACKINFO pStackInfo)
{
    PKLDRMODPE pModPE = (PKLDRMODPE)pMod->pvData;
    K_NOREF(pvBits);
    K_NOREF(BaseAddress);

    pStackInfo->Address = NIL_KLDRADDR;
    pStackInfo->LinkAddress = NIL_KLDRADDR;
    pStackInfo->cbStack = pStackInfo->cbStackThread = pModPE->Hdrs.OptionalHeader.SizeOfStackReserve;

    return 0;
}


/** @copydoc kLdrModQueryMainEntrypoint */
static int kldrModPEQueryMainEntrypoint(PKLDRMOD pMod, const void *pvBits, KLDRADDR BaseAddress, PKLDRADDR pMainEPAddress)
{
    PKLDRMODPE pModPE = (PKLDRMODPE)pMod->pvData;
    int rc;
    K_NOREF(pvBits);

    /*
     * Resolve base address alias if any.
     */
    rc = kldrModPEBitsAndBaseAddress(pModPE, NULL, &BaseAddress);
    if (rc)
        return rc;

    /*
     * Convert the address from the header.
     */
    *pMainEPAddress = pModPE->Hdrs.OptionalHeader.AddressOfEntryPoint
        ? BaseAddress + pModPE->Hdrs.OptionalHeader.AddressOfEntryPoint
        : NIL_KLDRADDR;
    return 0;
}


/** @copydoc kLdrModEnumDbgInfo */
static int kldrModPEEnumDbgInfo(PKLDRMOD pMod, const void *pvBits, PFNKLDRENUMDBG pfnCallback, void *pvUser)
{
    PKLDRMODPE                      pModPE = (PKLDRMODPE)pMod->pvData;
    const IMAGE_DEBUG_DIRECTORY    *pDbgDir;
    KU32                            iDbgInfo;
    KU32                            cb;
    int                             rc;

    /*
     * Check that there is a debug directory first.
     */
    cb = pModPE->Hdrs.OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_DEBUG].Size;
    if (    cb < sizeof(IMAGE_DEBUG_DIRECTORY) /* screw borland linkers */
        ||  !pModPE->Hdrs.OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_DEBUG].VirtualAddress)
        return 0;

    /*
     * Make sure we've got mapped bits.
     */
    rc = kldrModPEBitsAndBaseAddress(pModPE, &pvBits, NULL);
    if (rc)
        return rc;

    /*
     * Enumerate the debug directory.
     */
    pDbgDir = KLDRMODPE_RVA2TYPE(pvBits,
                                 pModPE->Hdrs.OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_DEBUG].VirtualAddress,
                                 const IMAGE_DEBUG_DIRECTORY *);
    for (iDbgInfo = 0;; iDbgInfo++, pDbgDir++, cb -= sizeof(IMAGE_DEBUG_DIRECTORY))
    {
        KLDRDBGINFOTYPE     enmDbgInfoType;

        /* convert the type. */
        switch (pDbgDir->Type)
        {
            case IMAGE_DEBUG_TYPE_UNKNOWN:
            case IMAGE_DEBUG_TYPE_FPO:
            case IMAGE_DEBUG_TYPE_COFF: /*stabs dialect??*/
            case IMAGE_DEBUG_TYPE_MISC:
            case IMAGE_DEBUG_TYPE_EXCEPTION:
            case IMAGE_DEBUG_TYPE_FIXUP:
            case IMAGE_DEBUG_TYPE_BORLAND:
            default:
                enmDbgInfoType = KLDRDBGINFOTYPE_UNKNOWN;
                break;
            case IMAGE_DEBUG_TYPE_CODEVIEW:
                enmDbgInfoType = KLDRDBGINFOTYPE_CODEVIEW;
                break;
        }

        rc = pfnCallback(pMod, iDbgInfo,
                         enmDbgInfoType, pDbgDir->MajorVersion, pDbgDir->MinorVersion, NULL,
                         pDbgDir->PointerToRawData ? (KLDRFOFF)pDbgDir->PointerToRawData : -1,
                         pDbgDir->AddressOfRawData ? pDbgDir->AddressOfRawData : NIL_KLDRADDR,
                         pDbgDir->SizeOfData,
                         NULL,
                         pvUser);
        if (rc)
            break;

        /* next */
        if (cb <= sizeof(IMAGE_DEBUG_DIRECTORY))
            break;
    }

    return rc;
}


/** @copydoc kLdrModHasDbgInfo */
static int kldrModPEHasDbgInfo(PKLDRMOD pMod, const void *pvBits)
{
    PKLDRMODPE pModPE = (PKLDRMODPE)pMod->pvData;
    K_NOREF(pvBits);

    /*
     * Base this entirely on the presence of a debug directory.
     */
    if (    pModPE->Hdrs.OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_DEBUG].Size
            < sizeof(IMAGE_DEBUG_DIRECTORY) /* screw borland linkers */
        ||  !pModPE->Hdrs.OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_DEBUG].VirtualAddress)
        return KLDR_ERR_NO_DEBUG_INFO;
    return 0;
}


/** @copydoc kLdrModMap */
static int kldrModPEMap(PKLDRMOD pMod)
{
    PKLDRMODPE  pModPE = (PKLDRMODPE)pMod->pvData;
    int         rc;

    /*
     * Already mapped?
     */
    if (pModPE->pvMapping)
        return KLDR_ERR_ALREADY_MAPPED;

    /*
     * We've got a common worker which does this.
     */
    rc = kldrModPEDoMap(pModPE, 1 /* the real thing */);
    if (rc)
        return rc;
    KLDRMODPE_ASSERT(pModPE->pvMapping);
    return 0;
}


/** @copydoc kLdrModUnmap */
static int kldrModPEUnmap(PKLDRMOD pMod)
{
    PKLDRMODPE  pModPE = (PKLDRMODPE)pMod->pvData;
    int         rc;

    /*
     * Mapped?
     */
    if (!pModPE->pvMapping)
        return KLDR_ERR_NOT_MAPPED;

    /*
     * We've got a common worker which does this.
     */
    rc = kldrModPEDoUnmap(pModPE, pModPE->pvMapping);
    if (rc)
        return rc;
    KLDRMODPE_ASSERT(!pModPE->pvMapping);
    return 0;

}


/** @copydoc kLdrModAllocTLS */
static int kldrModPEAllocTLS(PKLDRMOD pMod, void *pvMapping)
{
    PKLDRMODPE  pModPE = (PKLDRMODPE)pMod->pvData;

    /*
     * Mapped?
     */
    if (pvMapping == KLDRMOD_INT_MAP)
    {
        pvMapping = (void *)pModPE->pvMapping;
        if (!pvMapping)
            return KLDR_ERR_NOT_MAPPED;
    }

    /*
     * If no TLS directory then there is nothing to do.
     */
    if (    !pModPE->Hdrs.OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_TLS].Size
        ||  !pModPE->Hdrs.OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_TLS].VirtualAddress)
        return 0;
    /** @todo implement TLS. */
    return -1;
}


/** @copydoc kLdrModFreeTLS */
static void kldrModPEFreeTLS(PKLDRMOD pMod, void *pvMapping)
{
    PKLDRMODPE  pModPE = (PKLDRMODPE)pMod->pvData;

    /*
     * Mapped?
     */
    if (pvMapping == KLDRMOD_INT_MAP)
    {
        pvMapping = (void *)pModPE->pvMapping;
        if (!pvMapping)
            return;
    }

    /*
     * If no TLS directory then there is nothing to do.
     */
    if (    !pModPE->Hdrs.OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_TLS].Size
        ||  !pModPE->Hdrs.OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_TLS].VirtualAddress)
        return;
    /** @todo implement TLS. */
    return;
}


/** @copydoc kLdrModReload */
static int kldrModPEReload(PKLDRMOD pMod)
{
    PKLDRMODPE pModPE = (PKLDRMODPE)pMod->pvData;

    /*
     * Mapped?
     */
    if (!pModPE->pvMapping)
        return KLDR_ERR_NOT_MAPPED;

    /* the file provider does it all */
    return kRdrRefresh(pMod->pRdr, (void *)pModPE->pvMapping, pMod->cSegments, pMod->aSegments);
}


/** @copydoc kLdrModFixupMapping */
static int kldrModPEFixupMapping(PKLDRMOD pMod, PFNKLDRMODGETIMPORT pfnGetImport, void *pvUser)
{
    PKLDRMODPE pModPE = (PKLDRMODPE)pMod->pvData;
    int rc, rc2;

    /*
     * Mapped?
     */
    if (!pModPE->pvMapping)
        return KLDR_ERR_NOT_MAPPED;

    /*
     * Before doing anything we'll have to make all pages writable.
     */
    rc = kRdrProtect(pMod->pRdr, (void *)pModPE->pvMapping, pMod->cSegments, pMod->aSegments, 1 /* unprotect */);
    if (rc)
        return rc;

    /*
     * Apply base relocations.
     */
    rc = kldrModPEDoFixups(pModPE, (void *)pModPE->pvMapping, (KUPTR)pModPE->pvMapping,
                           pModPE->Hdrs.OptionalHeader.ImageBase);

    /*
     * Resolve imports.
     */
    if (!rc)
        rc = kldrModPEDoImports(pModPE, (void *)pModPE->pvMapping, pfnGetImport, pvUser);

    /*
     * Restore protection.
     */
    rc2 = kRdrProtect(pMod->pRdr, (void *)pModPE->pvMapping, pMod->cSegments, pMod->aSegments, 0 /* protect */);
    if (!rc && rc2)
        rc = rc2;
    return rc;
}


/**
 * Applies base relocations to a (unprotected) image mapping.
 *
 * @returns 0 on success, non-zero kLdr status code on failure.
 * @param   pModPE          The PE module interpreter instance.
 * @param   pvMapping       The mapping to fixup.
 * @param   NewBaseAddress  The address to fixup the mapping to.
 * @param   OldBaseAddress  The address the mapping is currently fixed up to.
 */
static int  kldrModPEDoFixups(PKLDRMODPE pModPE, void *pvMapping, KLDRADDR NewBaseAddress, KLDRADDR OldBaseAddress)
{
    const KLDRADDR                  Delta = NewBaseAddress - OldBaseAddress;
    KU32                            cbLeft = pModPE->Hdrs.OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_BASERELOC].Size;
    const IMAGE_BASE_RELOCATION    *pBR, *pFirstBR;

    /*
     * Don't don anything if the delta is 0 or there aren't any relocations.
     */
    if (    !Delta
        ||  !cbLeft
        ||  !pModPE->Hdrs.OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_BASERELOC].VirtualAddress)
        return 0;

    /*
     * Process the fixups block by block.
     * (These blocks appears to be 4KB on all archs despite the native page size.)
     */
    pBR = pFirstBR = KLDRMODPE_RVA2TYPE(pvMapping,
                                        pModPE->Hdrs.OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_BASERELOC].VirtualAddress,
                                        const IMAGE_BASE_RELOCATION *);
    while (     cbLeft > sizeof(IMAGE_BASE_RELOCATION)
           &&   pBR->SizeOfBlock >= sizeof(IMAGE_BASE_RELOCATION) /* paranoia */)
    {
        union
        {
            KU8        *pu8;
            KU16       *pu16;
            KU32       *pu32;
            KU64       *pu64;
        }               uChunk,
                        u;
        const KU16 *poffFixup = (const KU16 *)(pBR + 1);
        const KU32  cbBlock = K_MIN(cbLeft, pBR->SizeOfBlock) - sizeof(IMAGE_BASE_RELOCATION); /* more caution... */
        KU32        cFixups = cbBlock / sizeof(poffFixup[0]);
        uChunk.pu8 = KLDRMODPE_RVA2TYPE(pvMapping, pBR->VirtualAddress, KU8 *);

        /*
         * Loop thru the fixups in this chunk.
         */
        while (cFixups > 0)
        {
            u.pu8 = uChunk.pu8 + (*poffFixup & 0xfff);
            switch (*poffFixup >> 12) /* ordered by value. */
            {
                /* 0 - Alignment placeholder. */
                case IMAGE_REL_BASED_ABSOLUTE:
                    break;

                /* 1 - 16-bit, add 2nd 16-bit part of the delta. (rare) */
                case IMAGE_REL_BASED_HIGH:
                    *u.pu16 += (KU16)(Delta >> 16);
                    break;

                /* 2 - 16-bit, add 1st 16-bit part of the delta. (rare) */
                case IMAGE_REL_BASED_LOW:
                    *u.pu16 += (KU16)Delta;
                    break;

                /* 3 - 32-bit, add delta. (frequent in 32-bit images) */
                case IMAGE_REL_BASED_HIGHLOW:
                    *u.pu32 += (KU32)Delta;
                    break;

                /* 4 - 16-bit, add 2nd 16-bit of the delta, sign adjust for the lower 16-bit. one arg. (rare)  */
                case IMAGE_REL_BASED_HIGHADJ:
                {
                    KI32 i32;
                    if (cFixups <= 1)
                        return KLDR_ERR_PE_BAD_FIXUP;

                    i32 = (KU32)*u.pu16 << 16;
                    i32 |= *++poffFixup; cFixups--; /* the addend argument */
                    i32 += (KU32)Delta;
                    i32 += 0x8000;
                    *u.pu16 = (KU16)(i32 >> 16);
                    break;
                }

                /* 5 - 32-bit MIPS JMPADDR, no implemented. */
                case IMAGE_REL_BASED_MIPS_JMPADDR:
                    *u.pu32 = (*u.pu32 & 0xc0000000)
                            | ((KU32)((*u.pu32 << 2) + (KU32)Delta) >> 2);
                    break;

                /* 6 - Intra section? Reserved value in later specs. Not implemented. */
                case IMAGE_REL_BASED_SECTION:
                    KLDRMODPE_ASSERT(!"SECTION");
                    return KLDR_ERR_PE_BAD_FIXUP;

                /* 7 - Relative intra section? Reserved value in later specs. Not implemented. */
                case IMAGE_REL_BASED_REL32:
                    KLDRMODPE_ASSERT(!"SECTION");
                    return KLDR_ERR_PE_BAD_FIXUP;

                /* 8 - reserved according to binutils... */
                case 8:
                    KLDRMODPE_ASSERT(!"RESERVERED8");
                    return KLDR_ERR_PE_BAD_FIXUP;

                /* 9 - IA64_IMM64 (/ MIPS_JMPADDR16), no specs nor need to support the platform yet.
                 * Bet this requires more code than all the other fixups put together in good IA64 spirit :-) */
                case IMAGE_REL_BASED_IA64_IMM64:
                    KLDRMODPE_ASSERT(!"IA64_IMM64 / MIPS_JMPADDR16");
                    return KLDR_ERR_PE_BAD_FIXUP;

                /* 10 - 64-bit, add delta. (frequently in 64-bit images) */
                case IMAGE_REL_BASED_DIR64:
                    *u.pu64 += (KU64)Delta;
                    break;

                /* 11 - 16-bit, add 3rd 16-bit of the delta, sign adjust for the lower 32-bit. two args. (rare) */
                case IMAGE_REL_BASED_HIGH3ADJ:
                {
                    KI64 i64;
                    if (cFixups <= 2)
                        return KLDR_ERR_PE_BAD_FIXUP;

                    i64 = (KU64)*u.pu16 << 32
                        | ((KU32)poffFixup[2] << 16)
                        | poffFixup[1];
                    i64 += Delta;
                    i64 += 0x80008000UL;
                    *u.pu16 = (KU16)(i64 >> 32);
                    /* skip the addends arguments */
                    poffFixup += 2;
                    cFixups -= 2;
                    break;
                }

                /* the rest are yet to be defined.*/
                default:
                    return KLDR_ERR_PE_BAD_FIXUP;
            }

            /*
             * Next relocation.
             */
            poffFixup++;
            cFixups--;
        }


        /*
         * Next block.
         */
        cbLeft -= pBR->SizeOfBlock;
        pBR = (PIMAGE_BASE_RELOCATION)((KUPTR)pBR + pBR->SizeOfBlock);
    }

    return 0;
}



/**
 * Resolves imports.
 *
 * @returns 0 on success, non-zero kLdr status code on failure.
 * @param   pModPE          The PE module interpreter instance.
 * @param   pvMapping       The mapping which imports should be resolved.
 * @param   pfnGetImport    The callback for resolving an imported symbol.
 * @param   pvUser          User argument to the callback.
 */
static int  kldrModPEDoImports(PKLDRMODPE pModPE, void *pvMapping, PFNKLDRMODGETIMPORT pfnGetImport, void *pvUser)
{
    const IMAGE_IMPORT_DESCRIPTOR *pImpDesc;

    /*
     * If no imports, there is nothing to do.
     */
    kldrModPENumberOfImports(pModPE->pMod, pvMapping);
    if (!pModPE->cImportModules)
        return 0;

    pImpDesc = KLDRMODPE_RVA2TYPE(pvMapping,
                                  pModPE->Hdrs.OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_IMPORT].VirtualAddress,
                                  const IMAGE_IMPORT_DESCRIPTOR *);
    if (pModPE->Hdrs.FileHeader.SizeOfOptionalHeader == sizeof(IMAGE_OPTIONAL_HEADER32))
        return kldrModPEDoImports32Bit(pModPE, pvMapping, pImpDesc, pfnGetImport, pvUser);
    return kldrModPEDoImports64Bit(pModPE, pvMapping, pImpDesc, pfnGetImport, pvUser);
}


/**
 * Resolves imports, 32-bit image.
 *
 * @returns 0 on success, non-zero kLdr status code on failure.
 * @param   pModPE          The PE module interpreter instance.
 * @param   pvMapping       The mapping which imports should be resolved.
 * @param   pImpDesc        Pointer to the first import descriptor.
 * @param   pfnGetImport    The callback for resolving an imported symbol.
 * @param   pvUser          User argument to the callback.
 */
static int  kldrModPEDoImports32Bit(PKLDRMODPE pModPE, void *pvMapping, const IMAGE_IMPORT_DESCRIPTOR *pImpDesc,
                                    PFNKLDRMODGETIMPORT pfnGetImport, void *pvUser)
{
    PKLDRMOD pMod = pModPE->pMod;
    KU32 iImp;

    /*
     * Iterate the import descriptors.
     */
    for (iImp = 0; iImp < pModPE->cImportModules; iImp++, pImpDesc++)
    {
        PIMAGE_THUNK_DATA32         pFirstThunk = KLDRMODPE_RVA2TYPE(pvMapping, pImpDesc->FirstThunk, PIMAGE_THUNK_DATA32);
        const IMAGE_THUNK_DATA32   *pThunk = pImpDesc->u.OriginalFirstThunk
            ? KLDRMODPE_RVA2TYPE(pvMapping, pImpDesc->u.OriginalFirstThunk, const IMAGE_THUNK_DATA32 *)
            : KLDRMODPE_RVA2TYPE(pvMapping, pImpDesc->FirstThunk, const IMAGE_THUNK_DATA32 *);

        /* Iterate the thunks. */
        while (pThunk->u1.Ordinal != 0)
        {
            KLDRADDR    Value;
            KU32        fKind = KLDRSYMKIND_REQ_FLAT;
            int         rc;

            /* Ordinal or name import? */
            if (IMAGE_SNAP_BY_ORDINAL32(pThunk->u1.Ordinal))
                rc = pfnGetImport(pMod, iImp, IMAGE_ORDINAL32(pThunk->u1.Ordinal), NULL, 0, NULL, &Value, &fKind, pvUser);
            else if (KLDRMODPE_VALID_RVA(pModPE, pThunk->u1.Ordinal))
            {
                const IMAGE_IMPORT_BY_NAME *pName = KLDRMODPE_RVA2TYPE(pvMapping, pThunk->u1.Ordinal, const IMAGE_IMPORT_BY_NAME *);
                rc = pfnGetImport(pMod, iImp, NIL_KLDRMOD_SYM_ORDINAL, (const char *)pName->Name,
                                  kHlpStrLen((const char *)pName->Name), NULL, &Value, &fKind, pvUser);
            }
            else
            {
                KLDRMODPE_ASSERT(!"bad 32-bit import");
                return KLDR_ERR_PE_BAD_IMPORT;
            }
            if (rc)
                return rc;

            /* Apply it. */
            pFirstThunk->u1.Function = (KU32)Value;
            if (pFirstThunk->u1.Function != Value)
            {
                KLDRMODPE_ASSERT(!"overflow");
                return KLDR_ERR_ADDRESS_OVERFLOW;
            }

            /* next */
            pThunk++;
            pFirstThunk++;
        }
    }

    return 0;
}


/**
 * Resolves imports, 64-bit image.
 *
 * @returns 0 on success, non-zero kLdr status code on failure.
 * @param   pModPE          The PE module interpreter instance.
 * @param   pvMapping       The mapping which imports should be resolved.
 * @param   pImpDesc        Pointer to the first import descriptor.
 * @param   pfnGetImport    The callback for resolving an imported symbol.
 * @param   pvUser          User argument to the callback.
 */
static int  kldrModPEDoImports64Bit(PKLDRMODPE pModPE, void *pvMapping, const IMAGE_IMPORT_DESCRIPTOR *pImpDesc,
                                    PFNKLDRMODGETIMPORT pfnGetImport, void *pvUser)
{
    PKLDRMOD pMod = pModPE->pMod;
    KU32 iImp;

    /*
     * Iterate the import descriptors.
     */
    for (iImp = 0; iImp < pModPE->cImportModules; iImp++, pImpDesc++)
    {
        PIMAGE_THUNK_DATA64         pFirstThunk = KLDRMODPE_RVA2TYPE(pvMapping, pImpDesc->FirstThunk, PIMAGE_THUNK_DATA64);
        const IMAGE_THUNK_DATA64   *pThunk = pImpDesc->u.OriginalFirstThunk
            ? KLDRMODPE_RVA2TYPE(pvMapping, pImpDesc->u.OriginalFirstThunk, const IMAGE_THUNK_DATA64 *)
            : KLDRMODPE_RVA2TYPE(pvMapping, pImpDesc->FirstThunk, const IMAGE_THUNK_DATA64 *);

        /* Iterate the thunks. */
        while (pThunk->u1.Ordinal != 0)
        {
            KLDRADDR    Value;
            KU32        fKind = KLDRSYMKIND_REQ_FLAT;
            int         rc;

            /* Ordinal or name import? */
            if (IMAGE_SNAP_BY_ORDINAL64(pThunk->u1.Ordinal))
                rc = pfnGetImport(pMod, iImp, (KU32)IMAGE_ORDINAL64(pThunk->u1.Ordinal), NULL, 0, NULL, &Value, &fKind, pvUser);
            else if (KLDRMODPE_VALID_RVA(pModPE, pThunk->u1.Ordinal))
            {
                const IMAGE_IMPORT_BY_NAME *pName = KLDRMODPE_RVA2TYPE(pvMapping, pThunk->u1.Ordinal, const IMAGE_IMPORT_BY_NAME *);
                rc = pfnGetImport(pMod, iImp, NIL_KLDRMOD_SYM_ORDINAL, (const char *)pName->Name,
                                  kHlpStrLen((const char *)pName->Name), NULL, &Value, &fKind, pvUser);
            }
            else
            {
                KLDRMODPE_ASSERT(!"bad 64-bit import");
                return KLDR_ERR_PE_BAD_IMPORT;
            }
            if (rc)
                return rc;

            /* Apply it. */
            pFirstThunk->u1.Function = Value;

            /* next */
            pThunk++;
            pFirstThunk++;
        }
    }

    return 0;
}



/** @copydoc kLdrModCallInit */
static int kldrModPECallInit(PKLDRMOD pMod, void *pvMapping, KUPTR uHandle)
{
    PKLDRMODPE pModPE = (PKLDRMODPE)pMod->pvData;
    int rc;

    /*
     * Mapped?
     */
    if (pvMapping == KLDRMOD_INT_MAP)
    {
        pvMapping = (void *)pModPE->pvMapping;
        if (!pvMapping)
            return KLDR_ERR_NOT_MAPPED;
    }

    /*
     * Do TLS callbacks first and then call the init/term function if it's a DLL.
     */
    rc = kldrModPEDoCallTLS(pModPE, pvMapping, DLL_PROCESS_ATTACH, uHandle);
    if (    !rc
        &&  (pModPE->Hdrs.FileHeader.Characteristics & IMAGE_FILE_DLL))
    {
        rc = kldrModPEDoCallDLL(pModPE, pvMapping, DLL_PROCESS_ATTACH, uHandle);
        if (rc)
            kldrModPEDoCallTLS(pModPE, pvMapping, DLL_PROCESS_DETACH, uHandle);
    }

    return rc;
}


/**
 * Call the DLL entrypoint.
 *
 * @returns 0 on success.
 * @returns KLDR_ERR_MODULE_INIT_FAILED  or KLDR_ERR_THREAD_ATTACH_FAILED on failure.
 * @param   pModPE          The PE module interpreter instance.
 * @param   pvMapping       The module mapping to use (resolved).
 * @param   uOp             The operation (DLL_*).
 * @param   uHandle         The module handle to present.
 */
static int  kldrModPEDoCallDLL(PKLDRMODPE pModPE, void *pvMapping, unsigned uOp, KUPTR uHandle)
{
    int rc;

    /*
     * If no entrypoint there isn't anything to be done.
     */
    if (!pModPE->Hdrs.OptionalHeader.AddressOfEntryPoint)
        return 0;

    /*
     * Invoke the entrypoint and convert the boolean result to a kLdr status code.
     */
    rc = kldrModPEDoCall((KUPTR)pvMapping + pModPE->Hdrs.OptionalHeader.AddressOfEntryPoint, uHandle, uOp, NULL);
    if (rc)
        rc = 0;
    else if (uOp == DLL_PROCESS_ATTACH)
        rc = KLDR_ERR_MODULE_INIT_FAILED;
    else if (uOp == DLL_THREAD_ATTACH)
        rc = KLDR_ERR_THREAD_ATTACH_FAILED;
    else /* detach: ignore failures */
        rc = 0;
    return rc;
}


/**
 * Call the TLS entrypoints.
 *
 * @returns 0 on success.
 * @returns KLDR_ERR_THREAD_ATTACH_FAILED on failure.
 * @param   pModPE          The PE module interpreter instance.
 * @param   pvMapping       The module mapping to use (resolved).
 * @param   uOp             The operation (DLL_*).
 * @param   uHandle         The module handle to present.
 */
static int  kldrModPEDoCallTLS(PKLDRMODPE pModPE, void *pvMapping, unsigned uOp, KUPTR uHandle)
{
    /** @todo implement TLS support. */
    K_NOREF(pModPE);
    K_NOREF(pvMapping);
    K_NOREF(uOp);
    K_NOREF(uHandle);
    return 0;
}


/**
 * Do a 3 parameter callback.
 *
 * @returns 32-bit callback return.
 * @param   uEntrypoint     The address of the function to be called.
 * @param   uHandle         The first argument, the module handle.
 * @param   uOp             The second argumnet, the reason we're calling.
 * @param   pvReserved      The third argument, reserved argument. (figure this one out)
 */
KI32 kldrModPEDoCall(KUPTR uEntrypoint, KUPTR uHandle, KU32 uOp, void *pvReserved)
{
    KI32 rc;

/** @todo try/except */
#if defined(__X86__) || defined(__i386__) || defined(_M_IX86)
    /*
     * Be very careful.
     * Not everyone will have got the calling convention right.
     */
# ifdef __GNUC__
    __asm__ __volatile__(
        "pushl  %2\n\t"
        "pushl  %1\n\t"
        "pushl  %0\n\t"
        "lea   12(%%esp), %2\n\t"
        "call  *%3\n\t"
        "movl   %2, %%esp\n\t"
        : "=a" (rc)
        : "d" (uOp),
          "S" (0),
          "c" (uEntrypoint),
          "0" (uHandle));
# elif defined(_MSC_VER)
    __asm {
        mov     eax, [uHandle]
        mov     edx, [uOp]
        mov     ecx, 0
        mov     ebx, [uEntrypoint]
        push    edi
        mov     edi, esp
        push    ecx
        push    edx
        push    eax
        call    ebx
        mov     esp, edi
        pop     edi
        mov     [rc], eax
    }
# else
#  error "port me!"
# endif

#elif defined(__AMD64__) || defined(__x86_64__) || defined(_M_IX86)
    /*
     * For now, let's just get the work done...
     */
    /** @todo Deal with GCC / MSC differences in some sensible way. */
    int (*pfn)(KUPTR uHandle, KU32 uOp, void *pvReserved);
    pfn = (int (*)(KUPTR uHandle, KU32 uOp, void *pvReserved))uEntrypoint;
    rc = pfn(uHandle, uOp, NULL);

#else
# error "port me"
#endif
    K_NOREF(pvReserved);

    return rc;
}


/** @copydoc kLdrModCallTerm */
static int kldrModPECallTerm(PKLDRMOD pMod, void *pvMapping, KUPTR uHandle)
{
    PKLDRMODPE  pModPE = (PKLDRMODPE)pMod->pvData;

    /*
     * Mapped?
     */
    if (pvMapping == KLDRMOD_INT_MAP)
    {
        pvMapping = (void *)pModPE->pvMapping;
        if (!pvMapping)
            return KLDR_ERR_NOT_MAPPED;
    }

    /*
     * Do TLS callbacks first.
     */
    kldrModPEDoCallTLS(pModPE, pvMapping, DLL_PROCESS_DETACH, uHandle);
    if (pModPE->Hdrs.FileHeader.Characteristics & IMAGE_FILE_DLL)
        kldrModPEDoCallDLL(pModPE, pvMapping, DLL_PROCESS_DETACH, uHandle);

    return 0;
}


/** @copydoc kLdrModCallThread */
static int kldrModPECallThread(PKLDRMOD pMod, void *pvMapping, KUPTR uHandle, unsigned fAttachingOrDetaching)
{
    PKLDRMODPE  pModPE = (PKLDRMODPE)pMod->pvData;
    unsigned    uOp = fAttachingOrDetaching ? DLL_THREAD_ATTACH : DLL_THREAD_DETACH;
    int         rc;

    /*
     * Mapped?
     */
    if (pvMapping == KLDRMOD_INT_MAP)
    {
        pvMapping = (void *)pModPE->pvMapping;
        if (!pvMapping)
            return KLDR_ERR_NOT_MAPPED;
    }

    /*
     * Do TLS callbacks first and then call the init/term function if it's a DLL.
     */
    rc = kldrModPEDoCallTLS(pModPE, pvMapping, uOp, uHandle);
    if (!fAttachingOrDetaching)
        rc = 0;
    if (    !rc
        &&  (pModPE->Hdrs.FileHeader.Characteristics & IMAGE_FILE_DLL))
    {
        rc = kldrModPEDoCallDLL(pModPE, pvMapping, uOp, uHandle);
        if (!fAttachingOrDetaching)
            rc = 0;
        if (rc)
            kldrModPEDoCallTLS(pModPE, pvMapping, uOp, uHandle);
    }

    return rc;
}


/** @copydoc kLdrModSize */
static KLDRADDR kldrModPESize(PKLDRMOD pMod)
{
    PKLDRMODPE pModPE = (PKLDRMODPE)pMod->pvData;
    return pModPE->Hdrs.OptionalHeader.SizeOfImage;
}


/** @copydoc kLdrModGetBits */
static int kldrModPEGetBits(PKLDRMOD pMod, void *pvBits, KLDRADDR BaseAddress, PFNKLDRMODGETIMPORT pfnGetImport, void *pvUser)
{
    PKLDRMODPE  pModPE = (PKLDRMODPE)pMod->pvData;
    KU32        i;
    int         rc;

    /*
     * Zero the entire buffer first to simplify things.
     */
    kHlpMemSet(pvBits, 0, pModPE->Hdrs.OptionalHeader.SizeOfImage);

    /*
     * Iterate the segments and read the data within them.
     */
    for (i = 0; i < pMod->cSegments; i++)
    {
        /* skip it? */
        if (    pMod->aSegments[i].cbFile == -1
            ||  pMod->aSegments[i].offFile == -1
            ||  pMod->aSegments[i].LinkAddress == NIL_KLDRADDR
            ||  !pMod->aSegments[i].Alignment)
            continue;
        rc = kRdrRead(pMod->pRdr,
                         (KU8 *)pvBits + (pMod->aSegments[i].LinkAddress - pModPE->Hdrs.OptionalHeader.ImageBase),
                         pMod->aSegments[i].cbFile,
                         pMod->aSegments[i].offFile);
        if (rc)
            return rc;
    }

    /*
     * Perform relocations.
     */
    return kldrModPERelocateBits(pMod, pvBits, BaseAddress, pModPE->Hdrs.OptionalHeader.ImageBase, pfnGetImport, pvUser);

}


/** @copydoc kLdrModRelocateBits */
static int kldrModPERelocateBits(PKLDRMOD pMod, void *pvBits, KLDRADDR NewBaseAddress, KLDRADDR OldBaseAddress,
                                 PFNKLDRMODGETIMPORT pfnGetImport, void *pvUser)
{
    PKLDRMODPE pModPE = (PKLDRMODPE)pMod->pvData;
    int rc;

    /*
     * Call workers to do the jobs.
     */
    rc = kldrModPEDoFixups(pModPE, pvBits, NewBaseAddress, OldBaseAddress);
    if (!rc)
        rc = kldrModPEDoImports(pModPE, pvBits, pfnGetImport, pvUser);

    return rc;
}


/**
 * The PE module interpreter method table.
 */
KLDRMODOPS g_kLdrModPEOps =
{
    "PE",
    NULL,
    kldrModPECreate,
    kldrModPEDestroy,
    kldrModPEQuerySymbol,
    kldrModPEEnumSymbols,
    kldrModPEGetImport,
    kldrModPENumberOfImports,
    NULL /* can execute one is optional */,
    kldrModPEGetStackInfo,
    kldrModPEQueryMainEntrypoint,
    NULL /* pfnQueryImageUuid */,
    NULL, /** @todo resources */
    NULL, /** @todo resources */
    kldrModPEEnumDbgInfo,
    kldrModPEHasDbgInfo,
    kldrModPEMap,
    kldrModPEUnmap,
    kldrModPEAllocTLS,
    kldrModPEFreeTLS,
    kldrModPEReload,
    kldrModPEFixupMapping,
    kldrModPECallInit,
    kldrModPECallTerm,
    kldrModPECallThread,
    kldrModPESize,
    kldrModPEGetBits,
    kldrModPERelocateBits,
    NULL, /** @todo mostly done */
    42 /* the end */
};