summaryrefslogtreecommitdiff
path: root/src/VBox/VMM/PDMLdr.cpp
blob: df0734fbe902c8d2821baabdbdd00bda0d7d4b12 (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
/* $Id: PDMLdr.cpp 28800 2010-04-27 08:22:32Z vboxsync $ */
/** @file
 * PDM - Pluggable Device Manager, module loader.
 */

/*
 * Copyright (C) 2006-2007 Oracle Corporation
 *
 * This file is part of VirtualBox Open Source Edition (OSE), as
 * available from http://www.virtualbox.org. This file is free software;
 * you can redistribute it and/or modify it under the terms of the GNU
 * General Public License (GPL) as published by the Free Software
 * Foundation, in version 2 as it comes in the "COPYING" file of the
 * VirtualBox OSE distribution. VirtualBox OSE is distributed in the
 * hope that it will be useful, but WITHOUT ANY WARRANTY of any kind.
 */

//#define PDMLDR_FAKE_MODE

/*******************************************************************************
*   Header Files                                                               *
*******************************************************************************/
#define LOG_GROUP LOG_GROUP_PDM_LDR
#include "PDMInternal.h"
#include <VBox/pdm.h>
#include <VBox/mm.h>
#include <VBox/vmm.h>
#include <VBox/vm.h>
#include <VBox/uvm.h>
#include <VBox/sup.h>
#include <VBox/param.h>
#include <VBox/err.h>
#include <VBox/hwaccm.h>

#include <VBox/log.h>
#include <iprt/assert.h>
#include <iprt/alloc.h>
#include <iprt/ldr.h>
#include <iprt/path.h>
#include <iprt/string.h>

#include <limits.h>


/*******************************************************************************
*   Structures and Typedefs                                                    *
*******************************************************************************/
/**
 * Structure which the user argument of the RTLdrGetBits() callback points to.
 * @internal
 */
typedef struct PDMGETIMPORTARGS
{
    PVM         pVM;
    PPDMMOD     pModule;
} PDMGETIMPORTARGS, *PPDMGETIMPORTARGS;


/*******************************************************************************
*   Internal Functions                                                         *
*******************************************************************************/
static DECLCALLBACK(int) pdmR3GetImportRC(RTLDRMOD hLdrMod, const char *pszModule, const char *pszSymbol, unsigned uSymbol, RTUINTPTR *pValue, void *pvUser);
static int      pdmR3LoadR0U(PUVM pUVM, const char *pszFilename, const char *pszName);
static char *   pdmR3FileRC(const char *pszFile);
static char *   pdmR3FileR0(const char *pszFile);
static char *   pdmR3File(const char *pszFile, const char *pszDefaultExt, bool fShared);
static DECLCALLBACK(int) pdmR3QueryModFromEIPEnumSymbols(RTLDRMOD hLdrMod, const char *pszSymbol, unsigned uSymbol, RTUINTPTR Value, void *pvUser);



/**
 * Loads the VMMR0.r0 module early in the init process.
 *
 * @returns VBox status code.
 * @param   pUVM            Pointer to the user mode VM structure.
 */
VMMR3DECL(int) PDMR3LdrLoadVMMR0U(PUVM pUVM)
{
    return pdmR3LoadR0U(pUVM, NULL, VMMR0_MAIN_MODULE_NAME);
}


/**
 * Init the module loader part of PDM.
 *
 * This routine will load the Host Context Ring-0 and Guest
 * Context VMM modules.
 *
 * @returns VBox stutus code.
 * @param   pUVM        Pointer to the user mode VM structure.
 * @param   pvVMMR0Mod  The opqaue returned by PDMR3LdrLoadVMMR0.
 */
int pdmR3LdrInitU(PUVM pUVM)
{
#if defined(PDMLDR_FAKE_MODE) || !defined(VBOX_WITH_RAW_MODE)
    return VINF_SUCCESS;

#else

    /*
     * Load the mandatory GC module, the VMMR0.r0 is loaded before VM creation.
     */
    return PDMR3LdrLoadRC(pUVM->pVM, NULL, VMMGC_MAIN_MODULE_NAME);
#endif
}


/**
 * Terminate the module loader part of PDM.
 *
 * This will unload and free all modules.
 *
 * @param   pVM         The VM handle.
 *
 * @remarks This is normally called twice during termination.
 */
void pdmR3LdrTermU(PUVM pUVM)
{
    /*
     * Free the modules.
     */
    RTCritSectEnter(&pUVM->pdm.s.ListCritSect);
    PPDMMOD pModule = pUVM->pdm.s.pModules;
    pUVM->pdm.s.pModules = NULL;
    while (pModule)
    {
        /* free loader item. */
        if (pModule->hLdrMod != NIL_RTLDRMOD)
        {
            int rc2 = RTLdrClose(pModule->hLdrMod);
            AssertRC(rc2);
            pModule->hLdrMod = NIL_RTLDRMOD;
        }

        /* free bits. */
        switch (pModule->eType)
        {
            case PDMMOD_TYPE_R0:
            {
                Assert(pModule->ImageBase);
                int rc2 = SUPR3FreeModule((void *)(uintptr_t)pModule->ImageBase);
                AssertRC(rc2);
                pModule->ImageBase = 0;
                break;
            }

#ifdef VBOX_WITH_RAW_MODE
            case PDMMOD_TYPE_RC:
#endif
            case PDMMOD_TYPE_R3:
                /* MM will free this memory for us - it's alloc only memory. :-) */
                break;

            default:
                AssertMsgFailed(("eType=%d\n", pModule->eType));
                break;
        }
        pModule->pvBits = NULL;

        void    *pvFree = pModule;
        pModule = pModule->pNext;
        RTMemFree(pvFree);
    }
    RTCritSectLeave(&pUVM->pdm.s.ListCritSect);
}


/**
 * Applies relocations to GC modules.
 *
 * This must be done very early in the relocation
 * process so that components can resolve GC symbols during relocation.
 *
 * @param   pUVM        Pointer to the user mode VM structure.
 * @param   offDelta    Relocation delta relative to old location.
 */
VMMR3DECL(void) PDMR3LdrRelocateU(PUVM pUVM, RTGCINTPTR offDelta)
{
#ifdef VBOX_WITH_RAW_MODE
    LogFlow(("PDMR3LdrRelocate: offDelta=%RGv\n", offDelta));

    /*
     * GC Modules.
     */
    RTCritSectEnter(&pUVM->pdm.s.ListCritSect);
    if (pUVM->pdm.s.pModules)
    {
        /*
         * The relocation have to be done in two passes so imports
         * can be correctely resolved. The first pass will update
         * the ImageBase saving the current value in OldImageBase.
         * The second pass will do the actual relocation.
         */
        /* pass 1 */
        PPDMMOD pCur;
        for (pCur = pUVM->pdm.s.pModules; pCur; pCur = pCur->pNext)
        {
            if (pCur->eType == PDMMOD_TYPE_RC)
            {
                pCur->OldImageBase = pCur->ImageBase;
                pCur->ImageBase = MMHyperR3ToRC(pUVM->pVM, pCur->pvBits);
            }
        }

        /* pass 2 */
        for (pCur = pUVM->pdm.s.pModules; pCur; pCur = pCur->pNext)
        {
            if (pCur->eType == PDMMOD_TYPE_RC)
            {
                PDMGETIMPORTARGS Args;
                Args.pVM = pUVM->pVM;
                Args.pModule = pCur;
                int rc = RTLdrRelocate(pCur->hLdrMod, pCur->pvBits, pCur->ImageBase, pCur->OldImageBase,
                                       pdmR3GetImportRC, &Args);
                AssertFatalMsgRC(rc, ("RTLdrRelocate failed, rc=%d\n", rc));
                DBGFR3ModuleRelocate(pUVM->pVM, pCur->OldImageBase, pCur->ImageBase, RTLdrSize(pCur->hLdrMod),
                                     pCur->szFilename, pCur->szName);
            }
        }
    }
    RTCritSectLeave(&pUVM->pdm.s.ListCritSect);
#endif
}


/**
 * Loads a module into the host context ring-3.
 *
 * This is used by the driver and device init functions to load modules
 * containing the drivers and devices. The function can be extended to
 * load modules which are not native to the environment we're running in,
 * but at the moment this is not required.
 *
 * No reference counting is kept, since we don't implement any facilities
 * for unloading the module. But the module will naturally be released
 * when the VM terminates.
 *
 * @returns VBox status code.
 * @param   pUVM            Pointer to the user mode VM structure.
 * @param   pszFilename     Filename of the module binary.
 * @param   pszName         Module name. Case sensitive and the length is limited!
 */
int pdmR3LoadR3U(PUVM pUVM, const char *pszFilename, const char *pszName)
{
    /*
     * Validate input.
     */
    AssertMsg(pUVM->pVM->pdm.s.offVM, ("bad init order!\n"));
    Assert(pszFilename);
    size_t cchFilename = strlen(pszFilename);
    Assert(pszName);
    size_t cchName = strlen(pszName);
    PPDMMOD  pCur;
    if (cchName >= sizeof(pCur->szName))
    {
        AssertMsgFailed(("Name is too long, cchName=%d pszName='%s'\n", cchName, pszName));
        return VERR_INVALID_PARAMETER;
    }

    /*
     * Try lookup the name and see if the module exists.
     */
    int rc;
    RTCritSectEnter(&pUVM->pdm.s.ListCritSect);
    for (pCur = pUVM->pdm.s.pModules; pCur; pCur = pCur->pNext)
    {
        if (!strcmp(pCur->szName, pszName))
        {
            if (pCur->eType == PDMMOD_TYPE_R3)
                rc = VINF_PDM_ALREADY_LOADED;
            else
                rc = VERR_PDM_MODULE_NAME_CLASH;
            RTCritSectLeave(&pUVM->pdm.s.ListCritSect);

            AssertMsgRC(rc, ("We've already got a module '%s' loaded!\n", pszName));
            return rc;
        }
    }

    /*
     * Allocate the module list node and initialize it.
     */
    const char *pszSuff = RTLdrGetSuff();
    size_t      cchSuff = RTPathHaveExt(pszFilename) ? 0 : strlen(pszSuff);
    PPDMMOD     pModule = (PPDMMOD)RTMemAllocZ(RT_OFFSETOF(PDMMOD, szFilename[cchFilename + cchSuff + 1]));
    if (pModule)
    {
        pModule->eType = PDMMOD_TYPE_R3;
        memcpy(pModule->szName, pszName, cchName); /* memory is zero'ed, no need to copy terminator :-) */
        memcpy(pModule->szFilename, pszFilename, cchFilename);
        memcpy(&pModule->szFilename[cchFilename], pszSuff, cchSuff);

        /*
         * Load the loader item.
         */
        rc = SUPR3HardenedVerifyFile(pModule->szFilename, "pdmR3LoadR3U", NULL);
        if (RT_SUCCESS(rc))
            rc = RTLdrLoad(pModule->szFilename, &pModule->hLdrMod);
        if (RT_SUCCESS(rc))
        {
            pModule->pNext = pUVM->pdm.s.pModules;
            pUVM->pdm.s.pModules = pModule;
        }
        else
        {
            /* Something went wrong, most likely module not found. Don't consider other unlikely errors */
            rc = VMSetError(pUVM->pVM, rc, RT_SRC_POS, N_("Unable to load R3 module %s (%s)"), pModule->szFilename, pszName);
            RTMemFree(pModule);
        }
    }
    else
        rc = VERR_NO_MEMORY;

    RTCritSectLeave(&pUVM->pdm.s.ListCritSect);
    return rc;
}


#ifdef VBOX_WITH_RAW_MODE
/**
 * Resolve an external symbol during RTLdrGetBits() of a RC module.
 *
 * @returns VBox status code.
 * @param   hLdrMod         The loader module handle.
 * @param   pszModule       Module name.
 * @param   pszSymbol       Symbol name, NULL if uSymbol should be used.
 * @param   uSymbol         Symbol ordinal, ~0 if pszSymbol should be used.
 * @param   pValue          Where to store the symbol value (address).
 * @param   pvUser          User argument.
 */
static DECLCALLBACK(int) pdmR3GetImportRC(RTLDRMOD hLdrMod, const char *pszModule, const char *pszSymbol, unsigned uSymbol, RTUINTPTR *pValue, void *pvUser)
{
    PVM         pVM     = ((PPDMGETIMPORTARGS)pvUser)->pVM;
    PPDMMOD     pModule = ((PPDMGETIMPORTARGS)pvUser)->pModule;

    /*
     * Adjust input.
     */
    if (pszModule && !*pszModule)
        pszModule = NULL;

    /*
     * Builtin module.
     */
    if (!pszModule || !strcmp(pszModule, "VMMGCBuiltin.gc"))
    {
        int rc = VINF_SUCCESS;
        if (!strcmp(pszSymbol, "g_VM"))
            *pValue = pVM->pVMRC;
        else if (!strcmp(pszSymbol, "g_CPUM"))
            *pValue = VM_RC_ADDR(pVM, &pVM->cpum);
        else if (!strcmp(pszSymbol, "g_TRPM"))
            *pValue = VM_RC_ADDR(pVM, &pVM->trpm);
        else if (!strcmp(pszSymbol, "g_TRPMCPU"))
            *pValue = VM_RC_ADDR(pVM, &pVM->aCpus[0].trpm);
        else if (   !strncmp(pszSymbol, "VMM", 3)
                 || !strcmp(pszSymbol, "g_Logger")
                 || !strcmp(pszSymbol, "g_RelLogger"))
        {
            RTRCPTR RCPtr = 0;
            rc = VMMR3GetImportRC(pVM, pszSymbol, &RCPtr);
            if (RT_SUCCESS(rc))
                *pValue = RCPtr;
        }
        else if (   !strncmp(pszSymbol, "TM", 2)
                 || !strcmp(pszSymbol, "g_pSUPGlobalInfoPage"))
        {
            RTRCPTR RCPtr = 0;
            rc = TMR3GetImportRC(pVM, pszSymbol, &RCPtr);
            if (RT_SUCCESS(rc))
                *pValue = RCPtr;
        }
        else
        {
            AssertMsg(!pszModule, ("Unknown builtin symbol '%s' for module '%s'!\n", pszSymbol, pModule->szName)); NOREF(pModule);
            rc = VERR_SYMBOL_NOT_FOUND;
        }
        if (RT_SUCCESS(rc) || pszModule)
            return rc;
    }

    /*
     * Search for module.
     */
    PUVM     pUVM = pVM->pUVM;
    RTCritSectEnter(&pUVM->pdm.s.ListCritSect);
    PPDMMOD  pCur = pUVM->pdm.s.pModules;
    while (pCur)
    {
        if (    pCur->eType == PDMMOD_TYPE_RC
            &&  (   !pszModule
                 || !strcmp(pCur->szName, pszModule))
           )
        {
            /* Search for the symbol. */
            int rc = RTLdrGetSymbolEx(pCur->hLdrMod, pCur->pvBits, pCur->ImageBase, pszSymbol, pValue);
            if (RT_SUCCESS(rc))
            {
                AssertMsg(*pValue - pCur->ImageBase < RTLdrSize(pCur->hLdrMod),
                          ("%RRv-%RRv %s %RRv\n", (RTRCPTR)pCur->ImageBase,
                           (RTRCPTR)(pCur->ImageBase + RTLdrSize(pCur->hLdrMod) - 1),
                           pszSymbol, (RTRCPTR)*pValue));
                RTCritSectLeave(&pUVM->pdm.s.ListCritSect);
                return rc;
            }
            if (pszModule)
            {
                RTCritSectLeave(&pUVM->pdm.s.ListCritSect);
                AssertMsgFailed(("Couldn't find symbol '%s' in module '%s'!\n", pszSymbol, pszModule));
                LogRel(("PDMLdr: Couldn't find symbol '%s' in module '%s'!\n", pszSymbol, pszModule));
                return VERR_SYMBOL_NOT_FOUND;
            }
        }

        /* next */
        pCur = pCur->pNext;
    }

    RTCritSectLeave(&pUVM->pdm.s.ListCritSect);
    AssertMsgFailed(("Couldn't find module '%s' for resolving symbol '%s'!\n", pszModule, pszSymbol));
    return VERR_SYMBOL_NOT_FOUND;
}


/**
 * Loads a module into the guest context (i.e. into the Hypervisor memory region).
 *
 * @returns VBox status code.
 * @param   pVM             The VM to load it into.
 * @param   pszFilename     Filename of the module binary.
 * @param   pszName         Module name. Case sensitive and the length is limited!
 */
VMMR3DECL(int) PDMR3LdrLoadRC(PVM pVM, const char *pszFilename, const char *pszName)
{
    /*
     * Validate input.
     */
    AssertMsg(pVM->pdm.s.offVM, ("bad init order!\n"));
    PUVM     pUVM = pVM->pUVM;
    RTCritSectEnter(&pUVM->pdm.s.ListCritSect);
    PPDMMOD  pCur = pUVM->pdm.s.pModules;
    while (pCur)
    {
        if (!strcmp(pCur->szName, pszName))
        {
            RTCritSectLeave(&pUVM->pdm.s.ListCritSect);
            AssertMsgFailed(("We've already got a module '%s' loaded!\n", pszName));
            return VERR_PDM_MODULE_NAME_CLASH;
        }
        /* next */
        pCur = pCur->pNext;
    }

    /*
     * Find the file if not specified.
     */
    char *pszFile = NULL;
    if (!pszFilename)
        pszFilename = pszFile = pdmR3FileRC(pszName);

    /*
     * Allocate the module list node.
     */
    PPDMMOD     pModule = (PPDMMOD)RTMemAllocZ(sizeof(*pModule) + strlen(pszFilename));
    if (!pModule)
    {
        RTCritSectLeave(&pUVM->pdm.s.ListCritSect);
        RTMemTmpFree(pszFile);
        return VERR_NO_MEMORY;
    }
    AssertMsg(strlen(pszName) + 1 < sizeof(pModule->szName),
              ("pazName is too long (%d chars) max is %d chars.\n", strlen(pszName), sizeof(pModule->szName) - 1));
    strcpy(pModule->szName, pszName);
    pModule->eType = PDMMOD_TYPE_RC;
    strcpy(pModule->szFilename, pszFilename);


    /*
     * Open the loader item.
     */
    int rc = SUPR3HardenedVerifyFile(pszFilename, "PDMR3LdrLoadRC", NULL);
    if (RT_SUCCESS(rc))
        rc = RTLdrOpen(pszFilename, 0, RTLDRARCH_X86_32, &pModule->hLdrMod);
    if (RT_SUCCESS(rc))
    {
        /*
         * Allocate space in the hypervisor.
         */
        size_t          cb = RTLdrSize(pModule->hLdrMod);
        cb = RT_ALIGN_Z(cb, PAGE_SIZE);
        uint32_t        cPages = (uint32_t)(cb >> PAGE_SHIFT);
        if (((size_t)cPages << PAGE_SHIFT) == cb)
        {
            PSUPPAGE    paPages = (PSUPPAGE)RTMemTmpAlloc(cPages * sizeof(paPages[0]));
            if (paPages)
            {
                rc = SUPR3PageAllocEx(cPages, 0 /*fFlags*/, &pModule->pvBits, NULL /*pR0Ptr*/, paPages);
                if (RT_SUCCESS(rc))
                {
                    RTGCPTR GCPtr;
                    rc = MMR3HyperMapPages(pVM, pModule->pvBits, NIL_RTR0PTR,
                                           cPages, paPages, pModule->szName, &GCPtr);
                    if (RT_SUCCESS(rc))
                    {
                        MMR3HyperReserve(pVM, PAGE_SIZE, "fence", NULL);

                        /*
                         * Get relocated image bits.
                         */
                        Assert(MMHyperR3ToRC(pVM, pModule->pvBits) == GCPtr);
                        pModule->ImageBase = GCPtr;
                        PDMGETIMPORTARGS Args;
                        Args.pVM = pVM;
                        Args.pModule = pModule;
                        rc = RTLdrGetBits(pModule->hLdrMod, pModule->pvBits, pModule->ImageBase, pdmR3GetImportRC, &Args);
                        if (RT_SUCCESS(rc))
                        {
                            /*
                             * Insert the module.
                             */
                            if (pUVM->pdm.s.pModules)
                            {
                                /* we don't expect this list to be very long, so rather save the tail pointer. */
                                pCur = pUVM->pdm.s.pModules;
                                while (pCur->pNext)
                                    pCur = pCur->pNext;
                                pCur->pNext = pModule;
                            }
                            else
                                pUVM->pdm.s.pModules = pModule; /* (pNext is zeroed by alloc) */
                            Log(("PDM: RC Module at %RRv %s (%s)\n", (RTRCPTR)pModule->ImageBase, pszName, pszFilename));
                            RTCritSectLeave(&pUVM->pdm.s.ListCritSect);
                            RTMemTmpFree(pszFile);
                            RTMemTmpFree(paPages);
                            return VINF_SUCCESS;
                        }
                    }
                    else
                    {
                        AssertRC(rc);
                        SUPR3PageFreeEx(pModule->pvBits, cPages);
                    }
                }
                else
                    AssertMsgFailed(("SUPR3PageAlloc(%d,) -> %Rrc\n", cPages, rc));
                RTMemTmpFree(paPages);
            }
            else
                rc = VERR_NO_TMP_MEMORY;
        }
        else
            rc = VERR_OUT_OF_RANGE;
        int rc2 = RTLdrClose(pModule->hLdrMod);
        AssertRC(rc2);
    }
    RTCritSectLeave(&pUVM->pdm.s.ListCritSect);

    /* Don't consider VERR_PDM_MODULE_NAME_CLASH and VERR_NO_MEMORY above as these are very unlikely. */
    if (RT_FAILURE(rc))
        rc = VMSetError(pVM, rc, RT_SRC_POS, N_("Cannot load GC module %s"), pszFilename);

    RTMemFree(pModule);
    RTMemTmpFree(pszFile);
    return rc;
}
#endif /* VBOX_WITH_RAW_MODE */


/**
 * Loads a module into the ring-0 context.
 *
 * @returns VBox status code.
 * @param   pUVM            Pointer to the user mode VM structure.
 * @param   pszFilename     Filename of the module binary.
 * @param   pszName         Module name. Case sensitive and the length is limited!
 */
static int pdmR3LoadR0U(PUVM pUVM, const char *pszFilename, const char *pszName)
{
    /*
     * Validate input.
     */
    RTCritSectEnter(&pUVM->pdm.s.ListCritSect);
    PPDMMOD pCur = pUVM->pdm.s.pModules;
    while (pCur)
    {
        if (!strcmp(pCur->szName, pszName))
        {
            RTCritSectLeave(&pUVM->pdm.s.ListCritSect);
            AssertMsgFailed(("We've already got a module '%s' loaded!\n", pszName));
            return VERR_PDM_MODULE_NAME_CLASH;
        }
        /* next */
        pCur = pCur->pNext;
    }

    /*
     * Find the file if not specified.
     */
    char *pszFile = NULL;
    if (!pszFilename)
        pszFilename = pszFile = pdmR3FileR0(pszName);

    /*
     * Allocate the module list node.
     */
    PPDMMOD     pModule = (PPDMMOD)RTMemAllocZ(sizeof(*pModule) + strlen(pszFilename));
    if (!pModule)
    {
        RTCritSectLeave(&pUVM->pdm.s.ListCritSect);
        RTMemTmpFree(pszFile);
        return VERR_NO_MEMORY;
    }
    AssertMsg(strlen(pszName) + 1 < sizeof(pModule->szName),
              ("pazName is too long (%d chars) max is %d chars.\n", strlen(pszName), sizeof(pModule->szName) - 1));
    strcpy(pModule->szName, pszName);
    pModule->eType = PDMMOD_TYPE_R0;
    strcpy(pModule->szFilename, pszFilename);

    /*
     * Ask the support library to load it.
     */
    void *pvImageBase;
    int rc = SUPR3LoadModule(pszFilename, pszName, &pvImageBase);
    if (RT_SUCCESS(rc))
    {
        pModule->hLdrMod = NIL_RTLDRMOD;
        pModule->ImageBase = (uintptr_t)pvImageBase;

        /*
         * Insert the module.
         */
        if (pUVM->pdm.s.pModules)
        {
            /* we don't expect this list to be very long, so rather save the tail pointer. */
            pCur = pUVM->pdm.s.pModules;
            while (pCur->pNext)
                pCur = pCur->pNext;
            pCur->pNext = pModule;
        }
        else
            pUVM->pdm.s.pModules = pModule; /* (pNext is zeroed by alloc) */
        Log(("PDM: R0 Module at %RHv %s (%s)\n", (RTR0PTR)pModule->ImageBase, pszName, pszFilename));
        RTCritSectLeave(&pUVM->pdm.s.ListCritSect);
        RTMemTmpFree(pszFile);
        return VINF_SUCCESS;
    }

    RTCritSectLeave(&pUVM->pdm.s.ListCritSect);
    RTMemFree(pModule);
    LogRel(("pdmR3LoadR0U: pszName=\"%s\" rc=%Rrc\n", pszName, rc));

    /* Don't consider VERR_PDM_MODULE_NAME_CLASH and VERR_NO_MEMORY above as these are very unlikely. */
    if (RT_FAILURE(rc) && pUVM->pVM) /** @todo VMR3SetErrorU. */
        rc = VMSetError(pUVM->pVM, rc, RT_SRC_POS, N_("Cannot load R0 module %s"), pszFilename);

    RTMemTmpFree(pszFile); /* might be reference thru pszFilename in the above VMSetError call. */
    return rc;
}



/**
 * Get the address of a symbol in a given HC ring 3 module.
 *
 * @returns VBox status code.
 * @param   pVM             VM handle.
 * @param   pszModule       Module name.
 * @param   pszSymbol       Symbol name. If it's value is less than 64k it's treated like a
 *                          ordinal value rather than a string pointer.
 * @param   ppvValue        Where to store the symbol value.
 */
VMMR3DECL(int) PDMR3LdrGetSymbolR3(PVM pVM, const char *pszModule, const char *pszSymbol, void **ppvValue)
{
    /*
     * Validate input.
     */
    AssertMsg(pVM->pdm.s.offVM, ("bad init order!\n"));

    /*
     * Find the module.
     */
    PUVM pUVM = pVM->pUVM;
    RTCritSectEnter(&pUVM->pdm.s.ListCritSect);
    for (PPDMMOD pModule = pUVM->pdm.s.pModules; pModule; pModule = pModule->pNext)
    {
        if (    pModule->eType == PDMMOD_TYPE_R3
            &&  !strcmp(pModule->szName, pszModule))
        {
            RTUINTPTR Value = 0;
            int rc = RTLdrGetSymbolEx(pModule->hLdrMod, pModule->pvBits, pModule->ImageBase, pszSymbol, &Value);
            RTCritSectLeave(&pUVM->pdm.s.ListCritSect);
            if (RT_SUCCESS(rc))
            {
                *ppvValue = (void *)(uintptr_t)Value;
                Assert((uintptr_t)*ppvValue == Value);
            }
            else
            {
                if ((uintptr_t)pszSymbol < 0x10000)
                    AssertMsg(rc, ("Couldn't symbol '%u' in module '%s'\n", (unsigned)(uintptr_t)pszSymbol, pszModule));
                else
                    AssertMsg(rc, ("Couldn't symbol '%s' in module '%s'\n", pszSymbol, pszModule));
            }
            return rc;
        }
    }
    RTCritSectLeave(&pUVM->pdm.s.ListCritSect);
    AssertMsgFailed(("Couldn't locate module '%s'\n", pszModule));
    return VERR_SYMBOL_NOT_FOUND;
}


/**
 * Get the address of a symbol in a given HC ring 0 module.
 *
 * @returns VBox status code.
 * @param   pVM             VM handle.
 * @param   pszModule       Module name. If NULL the main R0 module (VMMR0.r0) is assumes.
 * @param   pszSymbol       Symbol name. If it's value is less than 64k it's treated like a
 *                          ordinal value rather than a string pointer.
 * @param   ppvValue        Where to store the symbol value.
 */
VMMR3DECL(int) PDMR3LdrGetSymbolR0(PVM pVM, const char *pszModule, const char *pszSymbol, PRTR0PTR ppvValue)
{
#ifdef PDMLDR_FAKE_MODE
    *ppvValue = 0xdeadbeef;
    return VINF_SUCCESS;

#else
    /*
     * Validate input.
     */
    AssertMsg(pVM->pdm.s.offVM, ("bad init order!\n"));
    if (!pszModule)
        pszModule = "VMMR0.r0";

    /*
     * Find the module.
     */
    PUVM pUVM = pVM->pUVM;
    RTCritSectEnter(&pUVM->pdm.s.ListCritSect);
    for (PPDMMOD pModule = pUVM->pdm.s.pModules; pModule; pModule = pModule->pNext)
    {
        if (    pModule->eType == PDMMOD_TYPE_R0
            &&  !strcmp(pModule->szName, pszModule))
        {
            int rc = SUPR3GetSymbolR0((void *)(uintptr_t)pModule->ImageBase, pszSymbol, (void **)ppvValue);
            RTCritSectLeave(&pUVM->pdm.s.ListCritSect);
            if (RT_FAILURE(rc))
            {
                AssertMsgRC(rc, ("Couldn't find symbol '%s' in module '%s'\n", pszSymbol, pszModule));
                LogRel(("PDMGetSymbol: Couldn't find symbol '%s' in module '%s'\n", pszSymbol, pszModule));
            }
            return rc;
        }
    }
    RTCritSectLeave(&pUVM->pdm.s.ListCritSect);
    AssertMsgFailed(("Couldn't locate module '%s'\n", pszModule));
    return VERR_SYMBOL_NOT_FOUND;
#endif
}


/**
 * Same as PDMR3LdrGetSymbolR0 except that the module will be attempted loaded if not found.
 *
 * @returns VBox status code.
 * @param   pVM             VM handle.
 * @param   pszModule       Module name. If NULL the main R0 module (VMMR0.r0) is assumed.
 * @param   pszSymbol       Symbol name. If it's value is less than 64k it's treated like a
 *                          ordinal value rather than a string pointer.
 * @param   ppvValue        Where to store the symbol value.
 */
VMMR3DECL(int) PDMR3LdrGetSymbolR0Lazy(PVM pVM, const char *pszModule, const char *pszSymbol, PRTR0PTR ppvValue)
{
#ifdef PDMLDR_FAKE_MODE
    *ppvValue = 0xdeadbeef;
    return VINF_SUCCESS;

#else
    /*
     * Since we're lazy, we'll only check if the module is present
     * and hand it over to PDMR3LdrGetSymbolR0 when that's done.
     */
    AssertMsg(pVM->pdm.s.offVM, ("bad init order!\n"));
    if (pszModule)
    {
        AssertMsgReturn(!strpbrk(pszModule, "/\\:\n\r\t"), ("pszModule=%s\n", pszModule), VERR_INVALID_PARAMETER);
        PUVM    pUVM = pVM->pUVM;
        PPDMMOD pModule;
        RTCritSectEnter(&pUVM->pdm.s.ListCritSect);
        for (pModule = pUVM->pdm.s.pModules; pModule; pModule = pModule->pNext)
            if (    pModule->eType == PDMMOD_TYPE_R0
                &&  !strcmp(pModule->szName, pszModule))
                break;
        RTCritSectLeave(&pUVM->pdm.s.ListCritSect);
        if (!pModule)
        {
            int rc = pdmR3LoadR0U(pUVM, NULL, pszModule);
            AssertMsgRCReturn(rc, ("pszModule=%s rc=%Rrc\n", pszModule, rc), VERR_MODULE_NOT_FOUND);
        }
    }
    return PDMR3LdrGetSymbolR0(pVM, pszModule, pszSymbol, ppvValue);
#endif
}


/**
 * Get the address of a symbol in a given RC module.
 *
 * @returns VBox status code.
 * @param   pVM             VM handle.
 * @param   pszModule       Module name. If NULL the main R0 module (VMMGC.gc) is assumes.
 * @param   pszSymbol       Symbol name. If it's value is less than 64k it's treated like a
 *                          ordinal value rather than a string pointer.
 * @param   pRCPtrValue     Where to store the symbol value.
 */
VMMR3DECL(int) PDMR3LdrGetSymbolRC(PVM pVM, const char *pszModule, const char *pszSymbol, PRTRCPTR pRCPtrValue)
{
#if defined(PDMLDR_FAKE_MODE) || !defined(VBOX_WITH_RAW_MODE)
    *pRCPtrValue = 0xfeedf00d;
    return VINF_SUCCESS;

#else
    /*
     * Validate input.
     */
    AssertMsg(pVM->pdm.s.offVM, ("bad init order!\n"));
    if (!pszModule)
        pszModule = "VMMGC.gc";

    /*
     * Find the module.
     */
    PUVM pUVM = pVM->pUVM;
    RTCritSectEnter(&pUVM->pdm.s.ListCritSect);
    for (PPDMMOD pModule = pUVM->pdm.s.pModules; pModule; pModule = pModule->pNext)
    {
        if (    pModule->eType == PDMMOD_TYPE_RC
            &&  !strcmp(pModule->szName, pszModule))
        {
            RTUINTPTR Value;
            int rc = RTLdrGetSymbolEx(pModule->hLdrMod, pModule->pvBits, pModule->ImageBase, pszSymbol, &Value);
            RTCritSectLeave(&pUVM->pdm.s.ListCritSect);
            if (RT_SUCCESS(rc))
            {
                *pRCPtrValue = (RTGCPTR)Value;
                Assert(*pRCPtrValue == Value);
            }
            else
            {
                if ((uintptr_t)pszSymbol < 0x10000)
                    AssertMsg(rc, ("Couldn't symbol '%u' in module '%s'\n", (unsigned)(uintptr_t)pszSymbol, pszModule));
                else
                    AssertMsg(rc, ("Couldn't symbol '%s' in module '%s'\n", pszSymbol, pszModule));
            }
            return rc;
        }
    }
    RTCritSectLeave(&pUVM->pdm.s.ListCritSect);
    AssertMsgFailed(("Couldn't locate module '%s'\n", pszModule));
    return VERR_SYMBOL_NOT_FOUND;
#endif
}


/**
 * Same as PDMR3LdrGetSymbolRC except that the module will be attempted loaded if not found.
 *
 * @returns VBox status code.
 * @param   pVM             VM handle.
 * @param   pszModule       Module name. If NULL the main R0 module (VMMGC.gc) is assumes.
 * @param   pszSymbol       Symbol name. If it's value is less than 64k it's treated like a
 *                          ordinal value rather than a string pointer.
 * @param   pRCPtrValue     Where to store the symbol value.
 */
VMMR3DECL(int) PDMR3LdrGetSymbolRCLazy(PVM pVM, const char *pszModule, const char *pszSymbol, PRTRCPTR pRCPtrValue)
{
#if defined(PDMLDR_FAKE_MODE) || !defined(VBOX_WITH_RAW_MODE)
    *pRCPtrValue = 0xfeedf00d;
    return VINF_SUCCESS;

#else
    /*
     * Since we're lazy, we'll only check if the module is present
     * and hand it over to PDMR3LdrGetSymbolRC when that's done.
     */
    AssertMsg(pVM->pdm.s.offVM, ("bad init order!\n"));
    if (pszModule)
    {
        AssertMsgReturn(!strpbrk(pszModule, "/\\:\n\r\t"), ("pszModule=%s\n", pszModule), VERR_INVALID_PARAMETER);
        PUVM    pUVM = pVM->pUVM;
        PPDMMOD pModule;
        RTCritSectEnter(&pUVM->pdm.s.ListCritSect);
        for (pModule = pUVM->pdm.s.pModules; pModule; pModule = pModule->pNext)
            if (    pModule->eType == PDMMOD_TYPE_RC
                &&  !strcmp(pModule->szName, pszModule))
                break;
        RTCritSectLeave(&pUVM->pdm.s.ListCritSect);
        if (!pModule)
        {
            char *pszFilename = pdmR3FileRC(pszModule);
            AssertMsgReturn(pszFilename, ("pszModule=%s\n", pszModule), VERR_MODULE_NOT_FOUND);
            int rc = PDMR3LdrLoadRC(pVM, pszFilename, pszModule);
            RTMemTmpFree(pszFilename);
            AssertMsgRCReturn(rc, ("pszModule=%s rc=%Rrc\n", pszModule, rc), VERR_MODULE_NOT_FOUND);
        }
    }
    return PDMR3LdrGetSymbolRC(pVM, pszModule, pszSymbol, pRCPtrValue);
#endif
}


/**
 * Constructs the full filename for a R3 image file.
 *
 * @returns Pointer to temporary memory containing the filename.
 *          Caller must free this using RTMemTmpFree().
 * @returns NULL on failure.
 *
 * @param   pszFile     File name (no path).
 */
char *pdmR3FileR3(const char *pszFile, bool fShared)
{
    return pdmR3File(pszFile, NULL, fShared);
}


/**
 * Constructs the full filename for a R0 image file.
 *
 * @returns Pointer to temporary memory containing the filename.
 *          Caller must free this using RTMemTmpFree().
 * @returns NULL on failure.
 *
 * @param   pszFile     File name (no path).
 */
char *pdmR3FileR0(const char *pszFile)
{
    return pdmR3File(pszFile, NULL, /*fShared=*/false);
}


/**
 * Constructs the full filename for a RC image file.
 *
 * @returns Pointer to temporary memory containing the filename.
 *          Caller must free this using RTMemTmpFree().
 * @returns NULL on failure.
 *
 * @param   pszFile     File name (no path).
 */
char *pdmR3FileRC(const char *pszFile)
{
    return pdmR3File(pszFile, NULL, /*fShared=*/false);
}


/**
 * Worker for pdmR3File().
 *
 * @returns Pointer to temporary memory containing the filename.
 *          Caller must free this using RTMemTmpFree().
 * @returns NULL on failure.
 *
 * @param   pszDir        Directory part
 * @param   pszFile       File name part
 * @param   pszDefaultExt Extension part
 */
static char *pdmR3FileConstruct(const char *pszDir, const char *pszFile, const char *pszDefaultExt)
{
    /*
     * Allocate temp memory for return buffer.
     */
    size_t cchDir  = strlen(pszDir);
    size_t cchFile = strlen(pszFile);
    size_t cchDefaultExt;

    /*
     * Default extention?
     */
    if (!pszDefaultExt || strchr(pszFile, '.'))
        cchDefaultExt = 0;
    else
        cchDefaultExt = strlen(pszDefaultExt);

    size_t cchPath = cchDir + 1 + cchFile + cchDefaultExt + 1;
    AssertMsgReturn(cchPath <= RTPATH_MAX, ("Path too long!\n"), NULL);

    char *pszRet = (char *)RTMemTmpAlloc(cchDir + 1 + cchFile + cchDefaultExt + 1);
    AssertMsgReturn(pszRet, ("Out of temporary memory!\n"), NULL);

    /*
     * Construct the filename.
     */
    memcpy(pszRet, pszDir, cchDir);
    pszRet[cchDir++] = '/';            /* this works everywhere */
    memcpy(pszRet + cchDir, pszFile, cchFile + 1);
    if (cchDefaultExt)
        memcpy(pszRet + cchDir + cchFile, pszDefaultExt, cchDefaultExt + 1);

    return pszRet;
}


/**
 * Worker for pdmR3FileRC(), pdmR3FileR0() and pdmR3FileR3().
 *
 * @returns Pointer to temporary memory containing the filename.
 *          Caller must free this using RTMemTmpFree().
 * @returns NULL on failure.
 * @param   pszFile         File name (no path).
 * @param   pszDefaultExt   The default extention, NULL if none.
 * @param   fShared         If true, search in the shared directory (/usr/lib on Unix), else
 *                          search in the private directory (/usr/lib/virtualbox on Unix).
 *                          Ignored if VBOX_PATH_SHARED_LIBS is not defined.
 * @todo    We'll have this elsewhere than in the root later!
 * @todo    Remove the fShared hack again once we don't need to link against VBoxDD anymore!
 */
static char *pdmR3File(const char *pszFile, const char *pszDefaultExt, bool fShared)
{
    char szPath[RTPATH_MAX];
    int  rc;

    rc = fShared ? RTPathSharedLibs(szPath, sizeof(szPath))
                 : RTPathAppPrivateArch(szPath, sizeof(szPath));
    if (!RT_SUCCESS(rc))
    {
        AssertMsgFailed(("RTPath[SharedLibs|AppPrivateArch](,%d) failed rc=%d!\n", sizeof(szPath), rc));
        return NULL;
    }

    return pdmR3FileConstruct(szPath, pszFile, pszDefaultExt);
}


/** @internal */
typedef struct QMFEIPARG
{
    RTRCUINTPTR uPC;

    char       *pszNearSym1;
    size_t     cchNearSym1;
    RTRCINTPTR  offNearSym1;

    char       *pszNearSym2;
    size_t      cchNearSym2;
    RTRCINTPTR  offNearSym2;
} QMFEIPARG, *PQMFEIPARG;

/**
 * Queries module information from an PC (eip/rip).
 *
 * This is typically used to locate a crash address.
 *
 * @returns VBox status code.
 *
 * @param   pVM         VM handle
 * @param   uPC         The program counter (eip/rip) to locate the module for.
 * @param   pszModName  Where to store the module name.
 * @param   cchModName  Size of the module name buffer.
 * @param   pMod        Base address of the module.
 * @param   pszNearSym1 Name of the closes symbol from below.
 * @param   cchNearSym1 Size of the buffer pointed to by pszNearSym1.
 * @param   pNearSym1   The address of pszNearSym1.
 * @param   pszNearSym2 Name of the closes symbol from below.
 * @param   cchNearSym2 Size of the buffer pointed to by pszNearSym2.
 * @param   pNearSym2   The address of pszNearSym2.
 */
VMMR3DECL(int) PDMR3LdrQueryRCModFromPC(PVM pVM, RTRCPTR uPC,
                                        char *pszModName,  size_t cchModName,  PRTRCPTR pMod,
                                        char *pszNearSym1, size_t cchNearSym1, PRTRCPTR pNearSym1,
                                        char *pszNearSym2, size_t cchNearSym2, PRTRCPTR pNearSym2)
{
    PUVM    pUVM = pVM->pUVM;
    int     rc   = VERR_MODULE_NOT_FOUND;
    RTCritSectEnter(&pUVM->pdm.s.ListCritSect);
    for (PPDMMOD pCur= pUVM->pdm.s.pModules; pCur; pCur = pCur->pNext)
    {
        /* Skip anything which isn't in GC. */
        if (pCur->eType != PDMMOD_TYPE_RC)
            continue;
        if (uPC - pCur->ImageBase < RTLdrSize(pCur->hLdrMod))
        {
            if (pMod)
                *pMod = pCur->ImageBase;
            if (pszModName && cchModName)
            {
                *pszModName = '\0';
                strncat(pszModName, pCur->szName, cchModName);
            }
            if (pNearSym1)   *pNearSym1   = 0;
            if (pNearSym2)   *pNearSym2   = 0;
            if (pszNearSym1) *pszNearSym1 = '\0';
            if (pszNearSym2) *pszNearSym2 = '\0';

            /*
             * Locate the nearest symbols.
             */
            QMFEIPARG   Args;
            Args.uPC         = uPC;
            Args.pszNearSym1 = pszNearSym1;
            Args.cchNearSym1 = cchNearSym1;
            Args.offNearSym1 = RTRCINTPTR_MIN;
            Args.pszNearSym2 = pszNearSym2;
            Args.cchNearSym2 = cchNearSym2;
            Args.offNearSym2 = RTRCINTPTR_MAX;

            rc = RTLdrEnumSymbols(pCur->hLdrMod, RTLDR_ENUM_SYMBOL_FLAGS_ALL, pCur->pvBits, pCur->ImageBase,
                                  pdmR3QueryModFromEIPEnumSymbols, &Args);
            if (pNearSym1 && Args.offNearSym1 != INT_MIN)
                *pNearSym1 = Args.offNearSym1 + uPC;
            if (pNearSym2 && Args.offNearSym2 != INT_MAX)
                *pNearSym2 = Args.offNearSym2 + uPC;

            rc = VINF_SUCCESS;
            if (pCur->eType == PDMMOD_TYPE_RC)
                break;
        }

    }
    RTCritSectLeave(&pUVM->pdm.s.ListCritSect);
    return rc;
}


/**
 * Enumeration callback function used by RTLdrEnumSymbols().
 *
 * @returns VBox status code. Failure will stop the enumeration.
 * @param   hLdrMod         The loader module handle.
 * @param   pszSymbol       Symbol name. NULL if ordinal only.
 * @param   uSymbol         Symbol ordinal, ~0 if not used.
 * @param   Value           Symbol value.
 * @param   pvUser          The user argument specified to RTLdrEnumSymbols().
 */
static DECLCALLBACK(int) pdmR3QueryModFromEIPEnumSymbols(RTLDRMOD hLdrMod, const char *pszSymbol, unsigned uSymbol, RTUINTPTR Value, void *pvUser)
{
    PQMFEIPARG pArgs = (PQMFEIPARG)pvUser;

    RTINTPTR off = Value - pArgs->uPC;
    if (off <= 0)   /* near1 is before or at same location. */
    {
        if (off > pArgs->offNearSym1)
        {
            pArgs->offNearSym1 = off;
            if (pArgs->pszNearSym1 && pArgs->cchNearSym1)
            {
                *pArgs->pszNearSym1 = '\0';
                if (pszSymbol)
                    strncat(pArgs->pszNearSym1, pszSymbol, pArgs->cchNearSym1);
                else
                {
                    char szOrd[32];
                    RTStrPrintf(szOrd, sizeof(szOrd), "#%#x", uSymbol);
                    strncat(pArgs->pszNearSym1, szOrd, pArgs->cchNearSym1);
                }
            }
        }
    }
    else            /* near2 is after */
    {
        if (off < pArgs->offNearSym2)
        {
            pArgs->offNearSym2 = off;
            if (pArgs->pszNearSym2 && pArgs->cchNearSym2)
            {
                *pArgs->pszNearSym2 = '\0';
                if (pszSymbol)
                    strncat(pArgs->pszNearSym2, pszSymbol, pArgs->cchNearSym2);
                else
                {
                    char szOrd[32];
                    RTStrPrintf(szOrd, sizeof(szOrd), "#%#x", uSymbol);
                    strncat(pArgs->pszNearSym2, szOrd, pArgs->cchNearSym2);
                }
            }
        }
    }

    return VINF_SUCCESS;
}


/**
 * Enumerate all PDM modules.
 *
 * @returns VBox status.
 * @param   pVM             VM Handle.
 * @param   pfnCallback     Function to call back for each of the modules.
 * @param   pvArg           User argument.
 */
VMMR3DECL(int)  PDMR3LdrEnumModules(PVM pVM, PFNPDMR3ENUM pfnCallback, void *pvArg)
{
    PUVM pUVM = pVM->pUVM;
    int  rc   = VINF_SUCCESS;
    RTCritSectEnter(&pUVM->pdm.s.ListCritSect);
    for (PPDMMOD pCur = pUVM->pdm.s.pModules; pCur; pCur = pCur->pNext)
    {
        rc = pfnCallback(pVM,
                         pCur->szFilename,
                         pCur->szName,
                         pCur->ImageBase,
                         pCur->eType == PDMMOD_TYPE_RC ? RTLdrSize(pCur->hLdrMod) : 0,
                         pCur->eType == PDMMOD_TYPE_RC,
                         pvArg);
        if (RT_FAILURE(rc))
            break;
    }
    RTCritSectLeave(&pUVM->pdm.s.ListCritSect);
    return rc;
}


/**
 * Locates a module.
 *
 * @returns Pointer to the module if found.
 * @param   pUVM            Pointer to the user mode VM structure.
 * @param   pszModule       The module name.
 * @param   enmType         The module type.
 * @param   fLazy           Lazy loading the module if set.
 */
static PPDMMOD pdmR3LdrFindModule(PUVM pUVM, const char *pszModule, PDMMODTYPE enmType, bool fLazy)
{
    RTCritSectEnter(&pUVM->pdm.s.ListCritSect);
    for (PPDMMOD pModule = pUVM->pdm.s.pModules; pModule; pModule = pModule->pNext)
        if (    pModule->eType == enmType
            &&  !strcmp(pModule->szName, pszModule))
        {
            RTCritSectLeave(&pUVM->pdm.s.ListCritSect);
            return pModule;
        }
    RTCritSectLeave(&pUVM->pdm.s.ListCritSect);
    if (fLazy)
    {
        switch (enmType)
        {
#ifdef VBOX_WITH_RAW_MODE
            case PDMMOD_TYPE_RC:
            {
                char *pszFilename = pdmR3FileRC(pszModule);
                if (pszFilename)
                {
                    int rc = PDMR3LdrLoadRC(pUVM->pVM, pszFilename, pszModule);
                    RTMemTmpFree(pszFilename);
                    if (RT_SUCCESS(rc))
                        return pdmR3LdrFindModule(pUVM, pszModule, enmType, false);
                }
                break;
            }
#endif

            case PDMMOD_TYPE_R0:
            {
                int rc = pdmR3LoadR0U(pUVM, NULL, pszModule);
                if (RT_SUCCESS(rc))
                    return pdmR3LdrFindModule(pUVM, pszModule, enmType, false);
                break;
            }

            default:
                AssertFailed();
        }
    }
    return NULL;
}


/**
 * Resolves a ring-0 or raw-mode context interface.
 *
 * @returns VBox status code.
 * @param   pVM             The VM handle.
 * @param   pvInterface     Pointer to the interface structure.  The symbol list
 *                          describes the layout.
 * @param   cbInterface     The size of the structure pvInterface is pointing
 *                          to.  For bounds checking.
 * @param   pszModule       The module name.  If NULL we assume it's the default
 *                          R0 or RC module (@a fRing0OrRC).  We'll attempt to
 *                          load the module if it isn't found in the module
 *                          list.
 * @param   pszSymPrefix    What to prefix the symbols in the list with.  The
 *                          idea is that you define a list that goes with an
 *                          interface (INTERFACE_SYM_LIST) and reuse it with
 *                          each implementation.
 * @param   pszSymList      The symbol list for the interface.  This is a
 *                          semi-colon separated list of symbol base names.  As
 *                          mentioned above, each is prefixed with @a
 *                          pszSymPrefix before resolving.  There are a couple
 *                          of special symbol names that will cause us to skip
 *                          ahead a little bit:
 *                              - U8:whatever,
 *                              - U16:whatever,
 *                              - U32:whatever,
 *                              - U64:whatever,
 *                              - RCPTR:whatever,
 *                              - R3PTR:whatever,
 *                              - R0PTR:whatever,
 *                              - GCPHYS:whatever,
 *                              - HCPHYS:whatever.
 * @param   fRing0          Set if it's a ring-0 context interface, clear if
 *                          it's raw-mode context interface.
 */
VMMR3DECL(int) PDMR3LdrGetInterfaceSymbols(PVM pVM, void *pvInterface, size_t cbInterface,
                                           const char *pszModule, const char *pszSymPrefix,
                                           const char *pszSymList, bool fRing0)
{
    /*
     * Find the module.
     */
    int     rc      = VINF_SUCCESS;
    PPDMMOD pModule = pdmR3LdrFindModule(pVM->pUVM,
                                         pszModule ? pszModule : fRing0 ? "VMMR0.r0" : "VMMGC.gc",
                                         fRing0 ? PDMMOD_TYPE_R0 : PDMMOD_TYPE_RC,
                                         true /*fLazy*/);
    if (pModule)
    {
        /* Prep the symbol name. */
        char            szSymbol[256];
        size_t const    cchSymPrefix = strlen(pszSymPrefix);
        AssertReturn(cchSymPrefix + 5 < sizeof(szSymbol), VERR_SYMBOL_NOT_FOUND);
        memcpy(szSymbol, pszSymPrefix, cchSymPrefix);

        /*
         * Iterate the symbol list.
         */
        uint32_t        offInterface = 0;
        const char     *pszCur       = pszSymList;
        while (pszCur)
        {
            /*
             * Find the end of the current symbol name.
             */
            size_t      cchSym;
            const char *pszNext = strchr(pszCur, ';');
            if (pszNext)
            {
                cchSym = pszNext - pszCur;
                pszNext++;
            }
            else
                cchSym = strlen(pszCur);
            AssertBreakStmt(cchSym > 0, rc = VERR_INVALID_PARAMETER);

            /* Is it a skip instruction? */
            const char *pszColon = (const char *)memchr(pszCur, ':', cchSym);
            if (pszColon)
            {
                /*
                 * String switch on the instruction and execute it, checking
                 * that we didn't overshoot the interface structure.
                 */
#define IS_SKIP_INSTR(szInstr) \
                (   cchSkip == sizeof(szInstr) - 1 \
                 && !memcmp(pszCur, szInstr, sizeof(szInstr) - 1) )

                size_t const cchSkip = pszColon - pszCur;
                if (IS_SKIP_INSTR("U8"))
                    offInterface += sizeof(uint8_t);
                else if (IS_SKIP_INSTR("U16"))
                    offInterface += sizeof(uint16_t);
                else if (IS_SKIP_INSTR("U32"))
                    offInterface += sizeof(uint32_t);
                else if (IS_SKIP_INSTR("U64"))
                    offInterface += sizeof(uint64_t);
                else if (IS_SKIP_INSTR("RCPTR"))
                    offInterface += sizeof(RTRCPTR);
                else if (IS_SKIP_INSTR("R3PTR"))
                    offInterface += sizeof(RTR3PTR);
                else if (IS_SKIP_INSTR("R0PTR"))
                    offInterface += sizeof(RTR0PTR);
                else if (IS_SKIP_INSTR("HCPHYS"))
                    offInterface += sizeof(RTHCPHYS);
                else if (IS_SKIP_INSTR("GCPHYS"))
                    offInterface += sizeof(RTGCPHYS);
                else
                    AssertMsgFailedBreakStmt(("Invalid skip instruction %.*s (prefix=%s)\n", cchSym, pszCur, pszSymPrefix),
                                             rc = VERR_INVALID_PARAMETER);
                AssertMsgBreakStmt(offInterface <= cbInterface,
                                   ("off=%#x cb=%#x (sym=%.*s prefix=%s)\n", offInterface, cbInterface, cchSym, pszCur, pszSymPrefix),
                                   rc = VERR_BUFFER_OVERFLOW);
#undef IS_SKIP_INSTR
            }
            else
            {
                /*
                 * Construct the symbol name, get its value, store it and
                 * advance the interface cursor.
                 */
                AssertReturn(cchSymPrefix + cchSym < sizeof(szSymbol), VERR_SYMBOL_NOT_FOUND);
                memcpy(&szSymbol[cchSymPrefix], pszCur, cchSym);
                szSymbol[cchSymPrefix + cchSym] = '\0';

                if (fRing0)
                {
                    void *pvValue;
                    rc = SUPR3GetSymbolR0((void *)(RTR0PTR)pModule->ImageBase, szSymbol, &pvValue);
                    AssertMsgRCBreak(rc, ("Couldn't find symbol '%s' in module '%s'\n", szSymbol, pModule->szName));

                    PRTR0PTR pValue = (PRTR0PTR)((uintptr_t)pvInterface + offInterface);
                    AssertMsgBreakStmt(offInterface + sizeof(*pValue) <= cbInterface,
                                       ("off=%#x cb=%#x sym=%s\n", offInterface, cbInterface, szSymbol),
                                       rc = VERR_BUFFER_OVERFLOW);
                    *pValue = (RTR0PTR)pvValue;
                    Assert((void *)*pValue == pvValue);
                    offInterface += sizeof(*pValue);
                }
                else
                {
                    RTUINTPTR Value;
                    rc = RTLdrGetSymbolEx(pModule->hLdrMod, pModule->pvBits, pModule->ImageBase, szSymbol, &Value);
                    AssertMsgRCBreak(rc, ("Couldn't find symbol '%s' in module '%s'\n", szSymbol, pModule->szName));

                    PRTRCPTR pValue = (PRTRCPTR)((uintptr_t)pvInterface + offInterface);
                    AssertMsgBreakStmt(offInterface + sizeof(*pValue) <= cbInterface,
                                       ("off=%#x cb=%#x sym=%s\n", offInterface, cbInterface, szSymbol),
                                       rc = VERR_BUFFER_OVERFLOW);
                    *pValue = (RTRCPTR)Value;
                    Assert(*pValue == Value);
                    offInterface += sizeof(*pValue);
                }
            }

            /* advance */
            pszCur = pszNext;
        }

    }
    else
        rc = VERR_MODULE_NOT_FOUND;
    return rc;
}