Index: /trunk/include/VBox/vmm/dbgf.h
===================================================================
--- /trunk/include/VBox/vmm/dbgf.h	(revision 73149)
+++ /trunk/include/VBox/vmm/dbgf.h	(revision 73150)
@@ -1181,4 +1181,18 @@
                                             PRTGCINTPTR poffDisp, PRTDBGMOD phMod);
 
+/** @name DBGFMOD_PE_F_XXX - flags for
+ * @{  */
+/** NT 3.1 images were a little different, so make allowances for that. */
+#define DBGFMODINMEM_F_PE_NT31                  RT_BIT_32(0)
+/** No container fallback. */
+#define DBGFMODINMEM_F_NO_CONTAINER_FALLBACK    RT_BIT_32(1)
+/** No in-memory reader fallback. */
+#define DBGFMODINMEM_F_NO_READER_FALLBACK       RT_BIT_32(2)
+/** Valid flags. */
+#define DBGFMODINMEM_F_VALID_MASK               UINT32_C(0x00000007)
+/** @} */
+VMMR3DECL(int)          DBGFR3ModInMem(PUVM pUVM, PCDBGFADDRESS pImageAddr, uint32_t fFlags, const char *pszName,
+                                       RTLDRARCH enmArch, uint32_t cbImage, PRTDBGMOD phDbgMod, PRTERRINFO pErrInfo);
+
 #endif /* IN_RING3 */
 
Index: /trunk/include/iprt/dbg.h
===================================================================
--- /trunk/include/iprt/dbg.h	(revision 73149)
+++ /trunk/include/iprt/dbg.h	(revision 73150)
@@ -960,6 +960,6 @@
 RTDECL(int)         RTDbgModCreateFromMap(PRTDBGMOD phDbgMod, const char *pszFilename, const char *pszName, RTUINTPTR uSubtrahend,
                                           RTDBGCFG hDbgCfg);
-RTDECL(int)         RTDbgModCreateFromPeImage(PRTDBGMOD phDbgMod, const char *pszFilename, const char *pszName, RTLDRMOD hLdrMod,
-                                              uint32_t cbImage, uint32_t uTimeDateStamp, RTDBGCFG hDbgCfg);
+RTDECL(int)         RTDbgModCreateFromPeImage(PRTDBGMOD phDbgMod, const char *pszFilename, const char *pszName,
+                                              PRTLDRMOD phLdrMod, uint32_t cbImage, uint32_t uTimeDateStamp, RTDBGCFG hDbgCfg);
 RTDECL(int)         RTDbgModCreateFromDbg(PRTDBGMOD phDbgMod, const char *pszFilename, const char *pszName, uint32_t cbImage,
                                           uint32_t uTimeDateStamp, RTDBGCFG hDbgCfg);
Index: /trunk/include/iprt/ldr.h
===================================================================
--- /trunk/include/iprt/ldr.h	(revision 73149)
+++ /trunk/include/iprt/ldr.h	(revision 73150)
@@ -352,4 +352,8 @@
     /** AMD64 (64-bit x86 if you like). */
     RTLDRARCH_AMD64,
+    /** 32-bit ARM. */
+    RTLDRARCH_ARM32,
+    /** 64-bit ARM. */
+    RTLDRARCH_ARM64,
     /** End of the valid values. */
     RTLDRARCH_END,
@@ -359,4 +363,20 @@
 /** Pointer to a RTLDRARCH. */
 typedef RTLDRARCH *PRTLDRARCH;
+
+/**
+ * Translates a RTLDRARCH value to a string.
+ *
+ * @returns Name corresponding to @a enmArch
+ * @param   enmArch             The value to name.
+ */
+RTDECL(const char *) RTLdrArchName(RTLDRARCH enmArch);
+
+/**
+ * Returns the host architecture.
+ *
+ * @returns Host architecture or RTLDRARCH_WHATEVER if no match.
+ */
+RTDECL(RTLDRARCH) RTLdrGetHostArch(void);
+
 
 /** @name RTLDR_O_XXX - RTLdrOpen flags.
@@ -498,4 +518,5 @@
  *                      a pointer to a memory block.
  * @param   phLdrMod    Where to return the module handle.
+ * @param   pErrInfo    Pointer to an error info buffer, optional.
  *
  * @remarks With the exception of invalid @a pfnDtor and/or @a pvUser
@@ -506,5 +527,5 @@
 RTDECL(int) RTLdrOpenInMemory(const char *pszName, uint32_t fFlags, RTLDRARCH enmArch, size_t cbImage,
                               PFNRTLDRRDRMEMREAD pfnRead, PFNRTLDRRDRMEMDTOR pfnDtor, void *pvUser,
-                              PRTLDRMOD phLdrMod);
+                              PRTLDRMOD phLdrMod, PRTERRINFO pErrInfo);
 
 /**
Index: /trunk/include/iprt/mangling.h
===================================================================
--- /trunk/include/iprt/mangling.h	(revision 73149)
+++ /trunk/include/iprt/mangling.h	(revision 73150)
@@ -1132,4 +1132,5 @@
 # define RTLatin1ToUtf8ExTag                            RT_MANGLER(RTLatin1ToUtf8ExTag)
 # define RTLatin1ToUtf8Tag                              RT_MANGLER(RTLatin1ToUtf8Tag)
+# define RTLdrArchName                                  RT_MANGLER(RTLdrArchName)
 # define RTLdrClose                                     RT_MANGLER(RTLdrClose)
 # define RTLdrEnumDbgInfo                               RT_MANGLER(RTLdrEnumDbgInfo)
@@ -1141,4 +1142,5 @@
 # define RTLdrGetFormat                                 RT_MANGLER(RTLdrGetFormat)
 # define RTLdrGetFunction                               RT_MANGLER(RTLdrGetFunction)
+# define RTLdrGetHostArch                               RT_MANGLER(RTLdrGetHostArch)
 # define RTLdrGetNativeHandle                           RT_MANGLER(RTLdrGetNativeHandle)
 # define RTLdrGetSuff                                   RT_MANGLER(RTLdrGetSuff)
Index: /trunk/src/VBox/Debugger/DBGCCommands.cpp
===================================================================
--- /trunk/src/VBox/Debugger/DBGCCommands.cpp	(revision 73149)
+++ /trunk/src/VBox/Debugger/DBGCCommands.cpp	(revision 73150)
@@ -62,4 +62,5 @@
 static FNDBGCCMD dbgcCmdFormat;
 static FNDBGCCMD dbgcCmdLoadImage;
+static FNDBGCCMD dbgcCmdLoadInMem;
 static FNDBGCCMD dbgcCmdLoadMap;
 static FNDBGCCMD dbgcCmdLoadSeg;
@@ -162,4 +163,13 @@
     {  0,           1,          DBGCVAR_CAT_NUMBER,     DBGCVD_FLAGS_DEP_PREV,          "subtrahend",   "Value to subtract from the addresses in the map file to rebase it correctly to address. (optional)" },
     {  0,           1,          DBGCVAR_CAT_NUMBER,     DBGCVD_FLAGS_DEP_PREV,          "seg",          "The module segment number (0-based). (optional)" },
+};
+
+
+/** loadinmem arguments. */
+static const DBGCVARDESC    g_aArgLoadInMem[] =
+{
+    /* cTimesMin,   cTimesMax,  enmCategory,            fFlags,                         pszName,        pszDescription */
+    {  0,           1,          DBGCVAR_CAT_POINTER,    0,                              "address",      "The module address." },
+    {  0,           1,          DBGCVAR_CAT_STRING,     0,                              "name",         "The module name. (optional)" },
 };
 
@@ -259,4 +269,5 @@
     { "loadimage32",2,        3,        &g_aArgLoadImage[0], RT_ELEMENTS(g_aArgLoadImage), 0, dbgcCmdLoadImage, "<filename> <address> [name]", "loadimage variant for selecting 32-bit images (mach-o)." },
     { "loadimage64",2,        3,        &g_aArgLoadImage[0], RT_ELEMENTS(g_aArgLoadImage), 0, dbgcCmdLoadImage, "<filename> <address> [name]", "loadimage variant for selecting 64-bit images (mach-o)." },
+    { "loadinmem",  1,        2,        &g_aArgLoadInMem[0], RT_ELEMENTS(g_aArgLoadInMem), 0, dbgcCmdLoadInMem, "<address> [name]",    "Tries to load a image mapped at the given address." },
     { "loadmap",    2,        5,        &g_aArgLoadMap[0],   RT_ELEMENTS(g_aArgLoadMap),   0, dbgcCmdLoadMap,   "<filename> <address> [name] [subtrahend] [seg]",
                                                                                                                                        "Loads the symbols from a map file, usually at a specified address. "
@@ -1359,4 +1370,52 @@
 
 /**
+ * @callback_method_impl{FNDBGCCMD, The 'loadinmem' command.}
+ */
+static DECLCALLBACK(int) dbgcCmdLoadInMem(PCDBGCCMD pCmd, PDBGCCMDHLP pCmdHlp, PUVM pUVM, PCDBGCVAR paArgs, unsigned cArgs)
+{
+    /*
+     * Validate the parsing and make sense of the input.
+     * This is a mess as usual because we don't trust the parser yet.
+     */
+    AssertReturn(    cArgs >= 1
+                 &&  cArgs <= 2
+                 &&  DBGCVAR_ISPOINTER(paArgs[0].enmType)
+                 &&  (cArgs < 2 || paArgs[1].enmType == DBGCVAR_TYPE_STRING),
+                 VERR_DBGC_PARSE_INCORRECT_ARG_TYPE);
+
+    RTLDRARCH       enmArch    = RTLDRARCH_WHATEVER;
+    const char     *pszModName = cArgs >= 2 ? paArgs[1].u.pszString : NULL;
+    DBGFADDRESS     ModAddress;
+    int rc = pCmdHlp->pfnVarToDbgfAddr(pCmdHlp, &paArgs[0], &ModAddress);
+    if (RT_FAILURE(rc))
+        return DBGCCmdHlpVBoxError(pCmdHlp, rc, "pfnVarToDbgfAddr: %Dv\n", &paArgs[1]);
+
+    /*
+     * Try create a module for it.
+     */
+    uint32_t fFlags = DBGFMODINMEM_F_NO_CONTAINER_FALLBACK | DBGFMODINMEM_F_NO_READER_FALLBACK;
+    RTDBGMOD hDbgMod;
+    RTERRINFOSTATIC ErrInfo;
+    rc = DBGFR3ModInMem(pUVM, &ModAddress, fFlags, pszModName, enmArch, 0 /*cbImage*/, &hDbgMod, RTErrInfoInitStatic(&ErrInfo));
+    if (RT_FAILURE(rc))
+    {
+        if (RTErrInfoIsSet(&ErrInfo.Core))
+            return DBGCCmdHlpFail(pCmdHlp, pCmd, "DBGFR3ModInMem failed for %Dv: %s",  &ModAddress, ErrInfo.Core.pszMsg);
+        return DBGCCmdHlpFailRc(pCmdHlp, pCmd, rc, "DBGFR3ModInMem failed for %Dv", &ModAddress);
+    }
+
+    /*
+     * Link the module into the appropriate address space.
+     */
+    PDBGC pDbgc = DBGC_CMDHLP2DBGC(pCmdHlp);
+    rc = DBGFR3AsLinkModule(pUVM, pDbgc->hDbgAs, hDbgMod, &ModAddress, NIL_RTDBGSEGIDX, RTDBGASLINK_FLAGS_REPLACE);
+    RTDbgModRelease(hDbgMod);
+    if (RT_FAILURE(rc))
+        return DBGCCmdHlpFailRc(pCmdHlp, pCmd, rc, "DBGFR3AsLinkModule failed for %Dv", &ModAddress);
+    return VINF_SUCCESS;
+}
+
+
+/**
  * @callback_method_impl{FNDBGCCMD, The 'loadmap' command.}
  */
Index: /trunk/src/VBox/Debugger/DBGPlugInWinNt.cpp
===================================================================
--- /trunk/src/VBox/Debugger/DBGPlugInWinNt.cpp	(revision 73149)
+++ /trunk/src/VBox/Debugger/DBGPlugInWinNt.cpp	(revision 73150)
@@ -595,5 +595,5 @@
     int rc = RTLdrOpenInMemory(pszName, RTLDR_O_FOR_DEBUG, RTLDRARCH_WHATEVER, pRdr->cbImage,
                                dbgDiggerWinNtRdr_Read, dbgDiggerWinNtRdr_Dtor, pRdr,
-                               &hLdrMod);
+                               &hLdrMod, NULL);
     if (RT_SUCCESS(rc))
         *phLdrMod = hLdrMod;
@@ -723,5 +723,5 @@
 
     RTDBGMOD hMod;
-    rc = RTDbgModCreateFromPeImage(&hMod, pszName, NULL, hLdrMod,
+    rc = RTDbgModCreateFromPeImage(&hMod, pszName, NULL, &hLdrMod,
                                    cbImageFromHdr, TimeDateStamp, DBGFR3AsGetConfig(pUVM));
     if (RT_FAILURE(rc))
@@ -752,4 +752,6 @@
     RTDbgModRelease(hMod);
     RTDbgAsRelease(hAs);
+    if (hLdrMod != NIL_RTLDRMOD)
+        RTLdrClose(hLdrMod);
 }
 
Index: /trunk/src/VBox/Debugger/testcase/tstDBGCStubs.cpp
===================================================================
--- /trunk/src/VBox/Debugger/testcase/tstDBGCStubs.cpp	(revision 73149)
+++ /trunk/src/VBox/Debugger/testcase/tstDBGCStubs.cpp	(revision 73150)
@@ -186,4 +186,13 @@
 }
 VMMR3DECL(int) DBGFR3AsSymbolByName(PUVM pUVM, RTDBGAS hDbgAs, const char *pszSymbol, PRTDBGSYMBOL pSymbol, PRTDBGMOD phMod)
+{
+    return VERR_INTERNAL_ERROR;
+}
+VMMR3DECL(int) DBGFR3AsLinkModule(PUVM pUVM, RTDBGAS hDbgAs, RTDBGMOD hMod, PCDBGFADDRESS pModAddress, RTDBGSEGIDX iModSeg, uint32_t fFlags)
+{
+    return VERR_INTERNAL_ERROR;
+}
+VMMR3DECL(int) DBGFR3ModInMem(PUVM pUVM, PCDBGFADDRESS pImageAddr, uint32_t fFlags, const char *pszName,
+                              RTLDRARCH enmArch, uint32_t cbImage, PRTDBGMOD phDbgMod, PRTERRINFO pErrInfo)
 {
     return VERR_INTERNAL_ERROR;
Index: /trunk/src/VBox/Runtime/common/dbg/dbgmod.cpp
===================================================================
--- /trunk/src/VBox/Runtime/common/dbg/dbgmod.cpp	(revision 73149)
+++ /trunk/src/VBox/Runtime/common/dbg/dbgmod.cpp	(revision 73150)
@@ -1074,6 +1074,6 @@
 
 
-RTDECL(int) RTDbgModCreateFromPeImage(PRTDBGMOD phDbgMod, const char *pszFilename, const char *pszName, RTLDRMOD hLdrMod,
-                                      uint32_t cbImage, uint32_t uTimestamp, RTDBGCFG hDbgCfg)
+RTDECL(int) RTDbgModCreateFromPeImage(PRTDBGMOD phDbgMod, const char *pszFilename, const char *pszName,
+                                      PRTLDRMOD phLdrMod, uint32_t cbImage, uint32_t uTimestamp, RTDBGCFG hDbgCfg)
 {
     /*
@@ -1087,4 +1087,6 @@
         pszName = RTPathFilenameEx(pszFilename, RTPATH_STR_F_STYLE_DOS);
     AssertPtrReturn(pszName, VERR_INVALID_POINTER);
+    AssertPtrNullReturn(phLdrMod, VERR_INVALID_POINTER);
+    RTLDRMOD hLdrMod = phLdrMod ? *phLdrMod : NIL_RTLDRMOD;
     AssertReturn(hLdrMod == NIL_RTLDRMOD || RTLdrSize(hLdrMod) != ~(size_t)0, VERR_INVALID_HANDLE);
 
@@ -1134,4 +1136,8 @@
                 if (RT_SUCCESS(rc))
                 {
+                    /* We now own the loader handle, so clear the caller variable. */
+                    if (phLdrMod)
+                        *phLdrMod = NIL_RTLDRMOD;
+
                     /*
                      * Do it now or procrastinate?
Index: /trunk/src/VBox/Runtime/common/ldr/ldr.cpp
===================================================================
--- /trunk/src/VBox/Runtime/common/ldr/ldr.cpp	(revision 73149)
+++ /trunk/src/VBox/Runtime/common/ldr/ldr.cpp	(revision 73150)
@@ -157,2 +157,20 @@
 RT_EXPORT_SYMBOL(RTLdrClose);
 
+
+RTDECL(RTLDRARCH) RTLdrGetHostArch(void)
+{
+#if   defined(RT_ARCH_AMD64)
+    RTLDRARCH enmArch = RTLDRARCH_AMD64;
+#elif defined(RT_ARCH_X86)
+    RTLDRARCH enmArch = RTLDRARCH_X86_32;
+#elif defined(RT_ARCH_ARM) || defined(RT_ARCH_ARM32)
+    RTLDRARCH enmArch = RTLDRARCH_ARM32;
+#elif defined(RT_ARCH_ARM64)
+    RTLDRARCH enmArch = RTLDRARCH_ARM64;
+#else
+    RTLDRARCH enmArch = RTLDRARCH_WHATEVER;
+#endif
+    return enmArch;
+}
+RT_EXPORT_SYMBOL(RTLdrGetHostArch);
+
Index: /trunk/src/VBox/Runtime/common/ldr/ldrEx.cpp
===================================================================
--- /trunk/src/VBox/Runtime/common/ldr/ldrEx.cpp	(revision 73149)
+++ /trunk/src/VBox/Runtime/common/ldr/ldrEx.cpp	(revision 73150)
@@ -62,11 +62,5 @@
      */
     if (enmArch == RTLDRARCH_HOST)
-#if   defined(RT_ARCH_AMD64)
-        enmArch = RTLDRARCH_AMD64;
-#elif defined(RT_ARCH_X86)
-        enmArch = RTLDRARCH_X86_32;
-#else
-        enmArch = RTLDRARCH_WHATEVER;
-#endif
+        enmArch = RTLdrGetHostArch();
 
     /*
@@ -744,5 +738,5 @@
  * @param   enmArch             The value to name.
  */
-DECLHIDDEN(const char *) rtLdrArchName(RTLDRARCH enmArch)
+RTDECL(const char *) RTLdrArchName(RTLDRARCH enmArch)
 {
     switch (enmArch)
@@ -753,4 +747,6 @@
         case RTLDRARCH_AMD64:       return "AMD64";
         case RTLDRARCH_X86_32:      return "X86_32";
+        case RTLDRARCH_ARM32:       return "ARM32";
+        case RTLDRARCH_ARM64:       return "ARM64";
 
         case RTLDRARCH_END:
@@ -760,2 +756,4 @@
     return "UNKNOWN";
 }
+RT_EXPORT_SYMBOL(RTLdrArchName);
+
Index: /trunk/src/VBox/Runtime/common/ldr/ldrMemory.cpp
===================================================================
--- /trunk/src/VBox/Runtime/common/ldr/ldrMemory.cpp	(revision 73149)
+++ /trunk/src/VBox/Runtime/common/ldr/ldrMemory.cpp	(revision 73150)
@@ -265,8 +265,8 @@
 RTDECL(int) RTLdrOpenInMemory(const char *pszName, uint32_t fFlags, RTLDRARCH enmArch, size_t cbImage,
                               PFNRTLDRRDRMEMREAD pfnRead, PFNRTLDRRDRMEMDTOR pfnDtor, void *pvUser,
-                              PRTLDRMOD phLdrMod)
-{
-    LogFlow(("RTLdrOpenInMemory: pszName=%p:{%s} fFlags=%#x enmArch=%d cbImage=%#zx pfnRead=%p pfnDtor=%p pvUser=%p phLdrMod=%p\n",
-             pszName, pszName, fFlags, enmArch, cbImage, pfnRead, pfnDtor, pvUser, phLdrMod));
+                              PRTLDRMOD phLdrMod, PRTERRINFO pErrInfo)
+{
+    LogFlow(("RTLdrOpenInMemory: pszName=%p:{%s} fFlags=%#x enmArch=%d cbImage=%#zx pfnRead=%p pfnDtor=%p pvUser=%p phLdrMod=%p pErrInfo=%p\n",
+             pszName, pszName, fFlags, enmArch, cbImage, pfnRead, pfnDtor, pvUser, phLdrMod, pErrInfo));
 
     if (!pfnRead || !pfnDtor)
@@ -292,11 +292,5 @@
      */
     if (enmArch == RTLDRARCH_HOST)
-#if   defined(RT_ARCH_AMD64)
-        enmArch = RTLDRARCH_AMD64;
-#elif defined(RT_ARCH_X86)
-        enmArch = RTLDRARCH_X86_32;
-#else
-        enmArch = RTLDRARCH_WHATEVER;
-#endif
+        enmArch = RTLdrGetHostArch();
 
     /*
@@ -307,5 +301,5 @@
     if (RT_SUCCESS(rc))
     {
-        rc = RTLdrOpenWithReader(pReader, fFlags, enmArch, phLdrMod, NULL);
+        rc = RTLdrOpenWithReader(pReader, fFlags, enmArch, phLdrMod, pErrInfo);
         if (RT_SUCCESS(rc))
         {
@@ -317,5 +311,8 @@
     }
     else
+    {
         pfnDtor(pvUser);
+        rc = RTErrInfoSetF(pErrInfo, rc, "rtldrRdrMem_Create failed: %Rrc", rc);
+    }
     *phLdrMod = NIL_RTLDRMOD;
 
Index: /trunk/src/VBox/Runtime/common/ldr/ldrPE.cpp
===================================================================
--- /trunk/src/VBox/Runtime/common/ldr/ldrPE.cpp	(revision 73149)
+++ /trunk/src/VBox/Runtime/common/ldr/ldrPE.cpp	(revision 73150)
@@ -3951,5 +3951,5 @@
         if (!(fFlags & RTLDR_O_IGNORE_ARCH_IF_NO_CODE))
             return RTERRINFO_LOG_SET_F(pErrInfo, VERR_LDR_ARCH_MISMATCH, "Image is for '%s', only accepting images for '%s'.",
-                                       rtldrPEGetArchName(FileHdr.Machine), rtLdrArchName(enmArch));
+                                       rtldrPEGetArchName(FileHdr.Machine), RTLdrArchName(enmArch));
         fArchNoCodeCheckPending = true;
     }
@@ -3970,5 +3970,5 @@
         return RTERRINFO_LOG_SET_F(pErrInfo, VERR_LDR_ARCH_MISMATCH,
                                    "Image is for '%s' and contains code (%#x), only accepting images for '%s' with code.",
-                                   rtldrPEGetArchName(FileHdr.Machine), OptHdr.SizeOfCode, rtLdrArchName(enmArch));
+                                   rtldrPEGetArchName(FileHdr.Machine), OptHdr.SizeOfCode, RTLdrArchName(enmArch));
 
     /*
Index: /trunk/src/VBox/Runtime/include/internal/ldr.h
===================================================================
--- /trunk/src/VBox/Runtime/include/internal/ldr.h	(revision 73149)
+++ /trunk/src/VBox/Runtime/include/internal/ldr.h	(revision 73150)
@@ -497,5 +497,4 @@
 
 DECLHIDDEN(int) rtLdrReadAt(RTLDRMOD hLdrMod, void *pvBuf, uint32_t iDbgInfo, RTFOFF off, size_t cb);
-DECLHIDDEN(const char *) rtLdrArchName(RTLDRARCH enmArch);
 
 RT_C_DECLS_END
Index: /trunk/src/VBox/Runtime/tools/RTLdrFlt.cpp
===================================================================
--- /trunk/src/VBox/Runtime/tools/RTLdrFlt.cpp	(revision 73149)
+++ /trunk/src/VBox/Runtime/tools/RTLdrFlt.cpp	(revision 73150)
@@ -257,5 +257,5 @@
                     rc = RTDbgModCreateFromImage(&hMod, pszModule, NULL, enmArch, hDbgCfg);
                 else
-                    rc = RTDbgModCreateFromPeImage(&hMod, pszModule, NULL, NIL_RTLDRMOD, cbImage, uTimestamp, hDbgCfg);
+                    rc = RTDbgModCreateFromPeImage(&hMod, pszModule, NULL, NULL, cbImage, uTimestamp, hDbgCfg);
                 if (RT_FAILURE(rc))
                     return RTMsgErrorExit(RTEXITCODE_FAILURE, "RTDbgModCreateFromImage(,%s,,) -> %Rrc", pszModule, rc);
Index: /trunk/src/VBox/VMM/Makefile.kmk
===================================================================
--- /trunk/src/VBox/VMM/Makefile.kmk	(revision 73149)
+++ /trunk/src/VBox/VMM/Makefile.kmk	(revision 73150)
@@ -99,4 +99,5 @@
 	VMMR3/DBGFLog.cpp \
 	VMMR3/DBGFMem.cpp \
+	VMMR3/DBGFR3ModInMem.cpp \
 	VMMR3/DBGFOS.cpp \
 	VMMR3/DBGFR3PlugIn.cpp \
Index: /trunk/src/VBox/VMM/VMMR3/DBGFR3ModInMem.cpp
===================================================================
--- /trunk/src/VBox/VMM/VMMR3/DBGFR3ModInMem.cpp	(revision 73150)
+++ /trunk/src/VBox/VMM/VMMR3/DBGFR3ModInMem.cpp	(revision 73150)
@@ -0,0 +1,650 @@
+/* $Id$ */
+/** @file
+ * DBGFR3ModInMemPe - In memory PE module 'loader'.
+ */
+
+/*
+ * Copyright (C) 2009-2018 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.
+ */
+
+
+/*********************************************************************************************************************************
+*   Header Files                                                                                                                 *
+*********************************************************************************************************************************/
+#define LOG_GROUP LOG_GROUP_DBGF
+#include <VBox/vmm/dbgf.h>
+
+#include <VBox/err.h>
+#include <iprt/ldr.h>
+#include <iprt/mem.h>
+#include <iprt/string.h>
+#include <iprt/formats/pecoff.h>
+#include <iprt/formats/mz.h>
+#include <iprt/formats/elf.h>
+
+
+/*********************************************************************************************************************************
+*   Structures and Typedefs                                                                                                      *
+*********************************************************************************************************************************/
+/**
+ * The WinNT digger's loader reader instance data.
+ */
+typedef struct DBGFMODPERDR
+{
+    /** The VM handle (referenced). */
+    PUVM                pUVM;
+    /** The image base. */
+    DBGFADDRESS         ImageAddr;
+    /** The image size. */
+    uint32_t            cbImage;
+    /** The file offset of the SizeOfImage field in the optional header if it
+     *  needs patching, otherwise set to UINT32_MAX. */
+    uint32_t            offSizeOfImage;
+    /** The correct image size. */
+    uint32_t            cbCorrectImageSize;
+    /** Number of entries in the aMappings table. */
+    uint32_t            cMappings;
+    /** Mapping hint. */
+    uint32_t            iHint;
+    /** Mapping file offset to memory offsets, ordered by file offset. */
+    struct
+    {
+        /** The file offset. */
+        uint32_t        offFile;
+        /** The size of this mapping. */
+        uint32_t        cbMem;
+        /** The offset to the memory from the start of the image.  */
+        uint32_t        offMem;
+    } aMappings[1];
+} DBGFMODPERDR;
+/** Pointer a WinNT loader reader instance data. */
+typedef DBGFMODPERDR *PDBGFMODPERDR;
+
+/**
+ * Stack buffer.
+ */
+typedef union DBGFMODINMEMBUF
+{
+    uint8_t             ab[0x2000];
+    IMAGE_DOS_HEADER    DosHdr;
+    IMAGE_NT_HEADERS32  Nt32;
+    IMAGE_NT_HEADERS64  Nt64;
+} DBGFMODINMEMBUF;
+/** Pointer to stack buffer. */
+typedef DBGFMODINMEMBUF *PDBGFMODINMEMBUF;
+
+
+
+/**
+ * Handles in-memory ELF images.
+ *
+ * @returns VBox status code.
+ * @param   pUVM            The user mode VM handle.
+ * @param   pImageAddr      The image address.
+ * @param   fFlags          Flags, DBGFMODINMEM_F_XXX.
+ * @param   pszName         The image name, optional.
+ * @param   enmArch         The image arch if we force it, pass
+ *                          RTLDRARCH_WHATEVER if you don't care.
+ * @param   cbImage         Image size.  Pass 0 if not known.
+ * @param   puBuf           The header buffer.
+ * @param   phDbgMod        Where to return the resulting debug module on success.
+ * @param   pErrInfo        Where to return extended error info on failure.
+ */
+static int dbgfR3ModInMemElf(PUVM pUVM, PCDBGFADDRESS pImageAddr, uint32_t fFlags, const char *pszName,
+                             RTLDRARCH enmArch, uint32_t cbImage, PDBGFMODINMEMBUF puBuf,
+                             PRTDBGMOD phDbgMod, PRTERRINFO pErrInfo)
+{
+    RT_NOREF(pUVM, fFlags, pszName, enmArch, cbImage, puBuf, phDbgMod);
+    return RTERRINFO_LOG_SET_F(pErrInfo, VERR_INVALID_EXE_SIGNATURE, "Found ELF magic at %RGv", pImageAddr->FlatPtr);
+}
+
+
+/**
+ * @callback_method_impl{PFNRTLDRRDRMEMREAD}
+ */
+static DECLCALLBACK(int) dbgfModInMemPeRdr_Read(void *pvBuf, size_t cb, size_t off, void *pvUser)
+{
+    PDBGFMODPERDR pThis   = (PDBGFMODPERDR)pvUser;
+    uint32_t      offFile = (uint32_t)off;
+    AssertReturn(offFile == off, VERR_INVALID_PARAMETER);
+
+    uint32_t i = pThis->iHint;
+    if (pThis->aMappings[i].offFile > offFile)
+    {
+        i = pThis->cMappings;
+        while (i-- > 0)
+            if (offFile >= pThis->aMappings[i].offFile)
+                break;
+        pThis->iHint = i;
+    }
+
+    while (cb > 0)
+    {
+        uint32_t offNextMap =  i + 1 < pThis->cMappings ? pThis->aMappings[i + 1].offFile : pThis->cbImage;
+        uint32_t offMap     = offFile - pThis->aMappings[i].offFile;
+
+        /* Read file bits backed by memory. */
+        if (offMap < pThis->aMappings[i].cbMem)
+        {
+            uint32_t cbToRead = pThis->aMappings[i].cbMem - offMap;
+            if (cbToRead > cb)
+                cbToRead = (uint32_t)cb;
+
+            DBGFADDRESS Addr = pThis->ImageAddr;
+            DBGFR3AddrAdd(&Addr, pThis->aMappings[i].offMem + offMap);
+
+            int rc = DBGFR3MemRead(pThis->pUVM, 0 /*idCpu*/, &Addr, pvBuf, cbToRead);
+            if (RT_FAILURE(rc))
+                return rc;
+
+            /* Apply SizeOfImage patch? */
+            if (   pThis->offSizeOfImage != UINT32_MAX
+                && offFile            < pThis->offSizeOfImage + 4
+                && offFile + cbToRead > pThis->offSizeOfImage)
+            {
+                uint32_t SizeOfImage = pThis->cbCorrectImageSize;
+                uint32_t cbPatch     = sizeof(SizeOfImage);
+                int32_t  offPatch    = pThis->offSizeOfImage - offFile;
+                uint8_t *pbPatch     = (uint8_t *)pvBuf + offPatch;
+                if (offFile + cbToRead < pThis->offSizeOfImage + cbPatch)
+                    cbPatch = offFile + cbToRead - pThis->offSizeOfImage;
+                while (cbPatch-- > 0)
+                {
+                    if (offPatch >= 0)
+                        *pbPatch = (uint8_t)SizeOfImage;
+                    offPatch++;
+                    pbPatch++;
+                    SizeOfImage >>= 8;
+                }
+            }
+
+            /* Done? */
+            if (cbToRead == cb)
+                break;
+
+            offFile += cbToRead;
+            cb      -= cbToRead;
+            pvBuf    = (char *)pvBuf + cbToRead;
+        }
+
+        /* Mind the gap. */
+        if (offNextMap > offFile)
+        {
+            uint32_t cbZero = offNextMap - offFile;
+            if (cbZero > cb)
+            {
+                RT_BZERO(pvBuf, cb);
+                break;
+            }
+
+            RT_BZERO(pvBuf, cbZero);
+            offFile += cbZero;
+            cb      -= cbZero;
+            pvBuf   = (char *)pvBuf + cbZero;
+        }
+
+        pThis->iHint = ++i;
+    }
+
+    return VINF_SUCCESS;
+}
+
+
+/**
+ * @callback_method_impl{PFNRTLDRRDRMEMDTOR}
+ */
+static DECLCALLBACK(void) dbgfModInMemPeRdr_Dtor(void *pvUser)
+{
+    PDBGFMODPERDR pThis = (PDBGFMODPERDR)pvUser;
+
+    VMR3ReleaseUVM(pThis->pUVM);
+    pThis->pUVM = NULL;
+    RTMemFree(pvUser);
+}
+
+
+/**
+ * Checks if the section headers look okay.
+ *
+ * @returns VBox status code.
+ * @param   paShdrs             Pointer to the section headers.
+ * @param   cShdrs              Number of headers.
+ * @param   cbImage             The image size reported by NT.
+ * @param   cbImageFromHdr      The image size by the linker in the header.
+ * @param   uRvaRsrc            The RVA of the resource directory. UINT32_MAX if
+ *                              no resource directory.
+ * @param   cbSectAlign         The section alignment specified in the header.
+ * @param   fNt31               Set if NT 3.1.  Needed for chopped off HAL.
+ * @param   pcbImageCorrect     The corrected image size.  This is derived from
+ *                              cbImage and virtual range of the section tables.
+ *
+ *                              The problem is that NT may choose to drop the
+ *                              last pages in images it loads early, starting at
+ *                              the resource directory.  These images will have
+ *                              a page aligned cbImage.
+ *
+ * @param   pErrInfo            Where to return more error details.
+ */
+static int dbgfR3ModPeCheckSectHdrsAndImgSize(PCIMAGE_SECTION_HEADER paShdrs, uint32_t cShdrs, uint32_t cbImage,
+                                              uint32_t cbImageFromHdr, uint32_t uRvaRsrc, uint32_t cbSectAlign,
+                                              bool fNt31, uint32_t *pcbImageCorrect, PRTERRINFO pErrInfo)
+{
+    *pcbImageCorrect = cbImage;
+
+    for (uint32_t i = 0; i < cShdrs; i++)
+    {
+        if (!paShdrs[i].Name[0])
+            return RTERRINFO_LOG_SET_F(pErrInfo, VERR_BAD_EXE_FORMAT, "Section header #%u has no name", i);
+
+        if (paShdrs[i].Characteristics & IMAGE_SCN_TYPE_NOLOAD)
+            continue;
+
+        /* Tweak to determine the virtual size if the linker didn't set it (NT 3.1). */
+        /** @todo this isn't really perfect. cbImage is kind of wrong...   */
+        uint32_t cbVirtual = paShdrs[i].Misc.VirtualSize;
+        if (cbVirtual == 0)
+        {
+            for (uint32_t j = i + 1; j < cShdrs; j++)
+                if (   !(paShdrs[j].Characteristics & IMAGE_SCN_TYPE_NOLOAD)
+                    && paShdrs[j].VirtualAddress > paShdrs[i].VirtualAddress)
+                {
+                    cbVirtual = paShdrs[j].VirtualAddress - paShdrs[i].VirtualAddress;
+                    break;
+                }
+            if (!cbVirtual)
+            {
+                if (paShdrs[i].VirtualAddress < cbImageFromHdr)
+                    cbVirtual = cbImageFromHdr - paShdrs[i].VirtualAddress;
+                else if (paShdrs[i].SizeOfRawData > 0)
+                    cbVirtual = RT_ALIGN(paShdrs[i].SizeOfRawData, _4K);
+            }
+        }
+
+        /* Check that sizes are within the same range and that both sizes and
+           addresses are within reasonable limits. */
+        if (   RT_ALIGN(cbVirtual, _64K) < RT_ALIGN(paShdrs[i].SizeOfRawData, _64K)
+            || cbVirtual                >= _1G
+            || paShdrs[i].SizeOfRawData >= _1G)
+            return RTERRINFO_LOG_SET_F(pErrInfo, VERR_BAD_EXE_FORMAT,
+                                       "Section header #%u (%.8s) has a VirtualSize=%#x (%#x) and SizeOfRawData=%#x, that's too much data!",
+                                       i, paShdrs[i].Name, cbVirtual, paShdrs[i].Misc.VirtualSize, paShdrs[i].SizeOfRawData);
+        uint32_t uRvaEnd = paShdrs[i].VirtualAddress + cbVirtual;
+        if (uRvaEnd >= _1G || uRvaEnd < paShdrs[i].VirtualAddress)
+            return RTERRINFO_LOG_SET_F(pErrInfo, VERR_BAD_EXE_FORMAT,
+                                       "Section header #%u (%.8s) has a VirtualSize=%#x (%#x) and VirtualAddr=%#x, %#x in total, that's too much!",
+                                       i, paShdrs[i].Name, cbVirtual, paShdrs[i].Misc.VirtualSize, paShdrs[i].VirtualAddress, uRvaEnd);
+
+        /* Check for images chopped off around '.rsrc'. */
+        if (    cbImage < uRvaEnd
+            &&  uRvaEnd >= uRvaRsrc)
+            cbImage = RT_ALIGN(uRvaEnd, cbSectAlign);
+
+        /* Check that the section is within the image. */
+        if (uRvaEnd > cbImage && fNt31)
+            return RTERRINFO_LOG_SET_F(pErrInfo, VERR_BAD_EXE_FORMAT,
+                                       "Section header #%u has a virtual address range beyond the image: %#x TO %#x cbImage=%#x",
+                                       i, paShdrs[i].VirtualAddress, uRvaEnd, cbImage);
+    }
+
+    Assert(*pcbImageCorrect == cbImage || !(*pcbImageCorrect & 0xfff));
+    *pcbImageCorrect = cbImage;
+    return VINF_SUCCESS;
+}
+
+
+/**
+ * Create a loader module for the in-guest-memory PE module.
+ */
+static int dbgfR3ModInMemPeCreateLdrMod(PUVM pUVM, uint32_t fFlags, const char *pszName, PCDBGFADDRESS pImageAddr,
+                                        uint32_t cbImage, uint32_t cbImageFromHdr, bool f32Bit,
+                                        uint32_t cShdrs, PCIMAGE_SECTION_HEADER paShdrs, uint32_t cbSectAlign,
+                                        uint32_t cDataDir, PCIMAGE_DATA_DIRECTORY paDataDir, uint32_t offHdrs,
+                                        PRTLDRMOD phLdrMod, PRTERRINFO pErrInfo)
+{
+    /*
+     * Allocate and create a reader instance.
+     */
+    PDBGFMODPERDR pRdr = (PDBGFMODPERDR)RTMemAlloc(RT_UOFFSETOF_DYN(DBGFMODPERDR, aMappings[cShdrs + 2]));
+    if (!pRdr)
+        return VERR_NO_MEMORY;
+
+    VMR3RetainUVM(pUVM);
+    pRdr->pUVM               = pUVM;
+    pRdr->ImageAddr          = *pImageAddr;
+    pRdr->cbImage            = cbImage;
+    pRdr->cbCorrectImageSize = cbImage;
+    pRdr->offSizeOfImage     = UINT32_MAX;
+    pRdr->iHint              = 0;
+
+    /*
+     * Use the section table to construct a more accurate view of the file/image.
+     */
+    uint32_t uRvaRsrc = UINT32_MAX;
+    if (   cDataDir > IMAGE_DIRECTORY_ENTRY_RESOURCE
+        && paDataDir[IMAGE_DIRECTORY_ENTRY_RESOURCE].Size > 0)
+        uRvaRsrc = paDataDir[IMAGE_DIRECTORY_ENTRY_RESOURCE].VirtualAddress;
+
+    int rc = dbgfR3ModPeCheckSectHdrsAndImgSize(paShdrs, cShdrs, cbImage, cbImageFromHdr, uRvaRsrc, cbSectAlign,
+                                                RT_BOOL(fFlags & DBGFMODINMEM_F_PE_NT31), &pRdr->cbCorrectImageSize, pErrInfo);
+    if (RT_SUCCESS(rc))
+    {
+        pRdr->cMappings = 0;
+
+        for (uint32_t i = 0; i < cShdrs; i++)
+            if (   paShdrs[i].SizeOfRawData    > 0
+                && paShdrs[i].PointerToRawData > 0)
+            {
+                uint32_t j = 1;
+                if (!pRdr->cMappings)
+                    pRdr->cMappings++;
+                else
+                {
+                    while (j < pRdr->cMappings && pRdr->aMappings[j].offFile < paShdrs[i].PointerToRawData)
+                        j++;
+                    if (j < pRdr->cMappings)
+                        memmove(&pRdr->aMappings[j + 1], &pRdr->aMappings[j], (pRdr->cMappings - j) * sizeof(pRdr->aMappings));
+                }
+                pRdr->aMappings[j].offFile = paShdrs[i].PointerToRawData;
+                pRdr->aMappings[j].offMem  = paShdrs[i].VirtualAddress;
+                pRdr->aMappings[j].cbMem   = i + 1 < cShdrs
+                                           ? paShdrs[i + 1].VirtualAddress - paShdrs[i].VirtualAddress
+                                           : paShdrs[i].Misc.VirtualSize;
+                if (j == pRdr->cMappings)
+                    pRdr->cbImage = paShdrs[i].PointerToRawData + paShdrs[i].SizeOfRawData;
+                pRdr->cMappings++;
+            }
+
+        /* Insert the mapping of the headers that isn't covered by the section table. */
+        pRdr->aMappings[0].offFile = 0;
+        pRdr->aMappings[0].offMem  = 0;
+        pRdr->aMappings[0].cbMem   = pRdr->cMappings ? pRdr->aMappings[1].offFile : pRdr->cbImage;
+
+        int j = pRdr->cMappings - 1;
+        while (j-- > 0)
+        {
+            uint32_t cbFile = pRdr->aMappings[j + 1].offFile - pRdr->aMappings[j].offFile;
+            if (pRdr->aMappings[j].cbMem > cbFile)
+                pRdr->aMappings[j].cbMem = cbFile;
+        }
+    }
+    else if (fFlags & DBGFMODINMEM_F_NO_READER_FALLBACK)
+        return rc;
+    else
+    {
+        /*
+         * Fallback, fake identity mapped file data.
+         */
+        pRdr->cMappings = 1;
+        pRdr->aMappings[0].offFile = 0;
+        pRdr->aMappings[0].offMem  = 0;
+        pRdr->aMappings[0].cbMem   = pRdr->cbImage;
+    }
+
+    /* Enable the SizeOfImage patching if necessary. */
+    if (pRdr->cbCorrectImageSize != cbImage)
+    {
+        Log(("dbgfR3ModInMemPeCreateLdrMod: The image is really %#x bytes long, not %#x as mapped by NT!\n",
+             pRdr->cbCorrectImageSize, cbImage));
+        pRdr->offSizeOfImage = f32Bit
+                             ? offHdrs + RT_OFFSETOF(IMAGE_NT_HEADERS32, OptionalHeader.SizeOfImage)
+                             : offHdrs + RT_OFFSETOF(IMAGE_NT_HEADERS64, OptionalHeader.SizeOfImage);
+    }
+
+    /*
+     * Call the loader to open the PE image for debugging.
+     * Note! It always calls pfnDtor.
+     */
+    RTLDRMOD hLdrMod;
+    rc = RTLdrOpenInMemory(pszName, RTLDR_O_FOR_DEBUG, RTLDRARCH_WHATEVER, pRdr->cbImage,
+                           dbgfModInMemPeRdr_Read, dbgfModInMemPeRdr_Dtor, pRdr,
+                           &hLdrMod, pErrInfo);
+    if (RT_SUCCESS(rc))
+        *phLdrMod = hLdrMod;
+    else
+        *phLdrMod = NIL_RTLDRMOD;
+    return rc;
+}
+
+
+/**
+ * Handles in-memory PE images.
+ *
+ * @returns VBox status code.
+ * @param   pUVM            The user mode VM handle.
+ * @param   pImageAddr      The image address.
+ * @param   fFlags          Flags, DBGFMODINMEM_F_XXX.
+ * @param   pszName         The image name, optional.
+ * @param   enmArch         The image arch if we force it, pass
+ *                          RTLDRARCH_WHATEVER if you don't care.
+ * @param   cbImage         Image size.  Pass 0 if not known.
+ * @param   offPeHdrs       Offset of the PE header.
+ * @param   cbPeHdrsPart1   How read into uBuf at @a offPeHdrs.
+ * @param   puBuf           The header buffer.
+ * @param   phDbgMod        Where to return the resulting debug module on success.
+ * @param   pErrInfo        Where to return extended error info on failure.
+ */
+static int dbgfR3ModInMemPe(PUVM pUVM, PCDBGFADDRESS pImageAddr, uint32_t fFlags, const char *pszName, RTLDRARCH enmArch,
+                            uint32_t cbImage, uint32_t offPeHdrs, uint32_t cbPeHdrsPart1, PDBGFMODINMEMBUF puBuf,
+                            PRTDBGMOD phDbgMod, PRTERRINFO pErrInfo)
+{
+    /*
+     * Read the optional header and the section table after validating the
+     * info we need from the file header.
+     */
+    /* Check the opt hdr size and number of sections as these are used to determine how much to read next. */
+    if (   puBuf->Nt32.FileHeader.SizeOfOptionalHeader < sizeof(IMAGE_OPTIONAL_HEADER32)
+        || puBuf->Nt32.FileHeader.SizeOfOptionalHeader > sizeof(IMAGE_OPTIONAL_HEADER64) + 128)
+        return RTERRINFO_LOG_SET_F(pErrInfo, VERR_BAD_EXE_FORMAT, "Invalid SizeOfOptionalHeader value: %#RX32",
+                                   puBuf->Nt32.FileHeader.SizeOfOptionalHeader);
+
+    if (   puBuf->Nt32.FileHeader.NumberOfSections < 1
+        || puBuf->Nt32.FileHeader.NumberOfSections > 190 /* what fits in our 8K buffer */)
+        return RTERRINFO_LOG_SET_F(pErrInfo, VERR_BAD_EXE_FORMAT, "NumberOfSections is out of range: %#RX32 (1..190)",
+                                   puBuf->Nt32.FileHeader.NumberOfSections);
+
+    /* Read the optional header and section table. */
+    uint32_t const cbHdrs = RT_UOFFSETOF(IMAGE_NT_HEADERS32, OptionalHeader)
+                          + puBuf->Nt32.FileHeader.SizeOfOptionalHeader
+                          + puBuf->Nt32.FileHeader.NumberOfSections * sizeof(IMAGE_SECTION_HEADER);
+    AssertReturn(cbHdrs <= sizeof(*puBuf), RTERRINFO_LOG_SET_F(pErrInfo, VERR_INTERNAL_ERROR_2, "cbHdrs=%#x", cbHdrs));
+
+    DBGFADDRESS PeHdrPart2Addr = *pImageAddr;
+    DBGFR3AddrAdd(&PeHdrPart2Addr, offPeHdrs + cbPeHdrsPart1);
+    int rc = DBGFR3MemRead(pUVM, 0 /*idCpu*/, &PeHdrPart2Addr, &puBuf->ab[cbPeHdrsPart1], cbHdrs - cbPeHdrsPart1);
+    if (RT_FAILURE(rc))
+        return RTERRINFO_LOG_SET_F(pErrInfo, rc,
+                                   "Failed to read the second part of the PE headers at %RGv (off=%#RX32 + %#RX32): %Rrc",
+                                   PeHdrPart2Addr.FlatPtr, offPeHdrs, cbPeHdrsPart1, rc);
+
+    /*
+     * Check the image architecture and determine the bitness.
+     */
+    RTLDRARCH enmArchActual;
+    bool f32Bit;
+    switch (puBuf->Nt32.FileHeader.Machine)
+    {
+        case IMAGE_FILE_MACHINE_I386:
+            enmArchActual = RTLDRARCH_X86_32;
+            f32Bit = true;
+            break;
+        case IMAGE_FILE_MACHINE_AMD64:
+            enmArchActual = RTLDRARCH_AMD64;
+            f32Bit = false;
+            break;
+        case IMAGE_FILE_MACHINE_ARM:
+        case IMAGE_FILE_MACHINE_THUMB:
+        case IMAGE_FILE_MACHINE_ARMNT:
+            enmArchActual = RTLDRARCH_ARM32;
+            f32Bit = true;
+            break;
+        case IMAGE_FILE_MACHINE_ARM64:
+            enmArchActual = RTLDRARCH_ARM64;
+            f32Bit = false;
+            break;
+        default:
+            return RTERRINFO_LOG_SET_F(pErrInfo, VERR_LDR_ARCH_MISMATCH, "Unknown machine: %#x", puBuf->Nt32.FileHeader.Machine);
+    }
+    if (   enmArch != RTLDRARCH_WHATEVER
+        && enmArch != enmArchActual)
+        return RTERRINFO_LOG_SET_F(pErrInfo, VERR_LDR_ARCH_MISMATCH, "Found %s expected %s",
+                                   RTLdrArchName(enmArchActual), RTLdrArchName(enmArch));
+
+    /*
+     * Check optional header magic and size.
+     */
+    uint16_t const uOptMagic = f32Bit ? IMAGE_NT_OPTIONAL_HDR32_MAGIC : IMAGE_NT_OPTIONAL_HDR64_MAGIC;
+    if (puBuf->Nt32.OptionalHeader.Magic != uOptMagic)
+        return RTERRINFO_LOG_SET_F(pErrInfo, VERR_BAD_EXE_FORMAT, "Unexpected optional header magic: %#x (expected %#x)",
+                                   puBuf->Nt32.OptionalHeader.Magic, uOptMagic);
+
+    uint32_t const cDataDir = f32Bit ? puBuf->Nt32.OptionalHeader.NumberOfRvaAndSizes : puBuf->Nt64.OptionalHeader.NumberOfRvaAndSizes;
+    if (   cDataDir <= IMAGE_DIRECTORY_ENTRY_BASERELOC /* a bit random */
+        || cDataDir > 32 /* also random */)
+        return RTERRINFO_LOG_SET_F(pErrInfo, VERR_BAD_EXE_FORMAT, "Unexpected data directory size: %#x", cDataDir);
+
+    uint32_t cbOptHdr = f32Bit ? sizeof(IMAGE_OPTIONAL_HEADER32) : sizeof(IMAGE_OPTIONAL_HEADER64);
+    cbOptHdr -= sizeof(IMAGE_DATA_DIRECTORY) * IMAGE_NUMBEROF_DIRECTORY_ENTRIES;
+    cbOptHdr += sizeof(IMAGE_DATA_DIRECTORY) * cDataDir;
+    if (puBuf->Nt32.FileHeader.SizeOfOptionalHeader != cbOptHdr)
+        return RTERRINFO_LOG_SET_F(pErrInfo, VERR_BAD_EXE_FORMAT, "Unexpected optional header size: %#x (expected %#x)",
+                                   puBuf->Nt32.FileHeader.SizeOfOptionalHeader, cbOptHdr);
+
+    uint32_t const cbSectAlign = f32Bit ? puBuf->Nt32.OptionalHeader.SectionAlignment : puBuf->Nt64.OptionalHeader.SectionAlignment;
+    PCIMAGE_SECTION_HEADER pSHdrs    = (PCIMAGE_SECTION_HEADER)((uintptr_t)&puBuf->Nt32.OptionalHeader + cbOptHdr);
+    PCIMAGE_DATA_DIRECTORY paDataDir = (PCIMAGE_DATA_DIRECTORY)((uintptr_t)pSHdrs - cDataDir * sizeof(IMAGE_DATA_DIRECTORY));
+
+    /*
+     * Establish the image size.
+     */
+    uint32_t cbImageFromHdr = f32Bit ? puBuf->Nt32.OptionalHeader.SizeOfImage : puBuf->Nt64.OptionalHeader.SizeOfImage;
+    if (   !cbImage
+        || (fFlags & DBGFMODINMEM_F_PE_NT31))
+        cbImage = RT_ALIGN(cbImageFromHdr, _4K);
+    else if (RT_ALIGN(cbImageFromHdr, _4K) != RT_ALIGN(cbImage, _4K))
+        return RTERRINFO_LOG_SET_F(pErrInfo, VERR_MISMATCH, "Image size mismatch: input=%#x header=%#x", cbImage, cbImageFromHdr);
+
+    /*
+     * Guess the image name if not specified.
+     */
+    //char szImageName[64];
+    if (!pszName)
+    {
+        /** @todo */
+    }
+
+    /*
+     * Create the module using the in memory image first, falling back on cached image.
+     */
+    RTLDRMOD hLdrMod;
+    rc = dbgfR3ModInMemPeCreateLdrMod(pUVM, fFlags, pszName, pImageAddr, cbImage, cbImageFromHdr, f32Bit,
+                                      puBuf->Nt32.FileHeader.NumberOfSections, pSHdrs, cbSectAlign, cDataDir, paDataDir,
+                                      offPeHdrs, &hLdrMod, pErrInfo);
+    if (RT_FAILURE(rc))
+        hLdrMod = NIL_RTLDRMOD;
+
+    RTDBGMOD hMod;
+    rc = RTDbgModCreateFromPeImage(&hMod, pszName, NULL, &hLdrMod, cbImageFromHdr,
+                                   puBuf->Nt32.FileHeader.TimeDateStamp, DBGFR3AsGetConfig(pUVM));
+    if (RT_SUCCESS(rc))
+        *phDbgMod = hMod;
+    else if (!(fFlags & DBGFMODINMEM_F_NO_CONTAINER_FALLBACK))
+    {
+        /*
+         * Fallback is a container module.
+         */
+        rc = RTDbgModCreate(&hMod, pszName, cbImage, 0);
+        if (RT_SUCCESS(rc))
+        {
+            rc = RTDbgModSymbolAdd(hMod, "Headers", 0 /*iSeg*/, 0, cbImage, 0 /*fFlags*/, NULL);
+            AssertRC(rc);
+        }
+    }
+    return rc;
+}
+
+
+
+/**
+ * Process a PE image found in guest memory.
+ *
+ * @param   pUVM            The user mode VM handle.
+ * @param   pImageAddr      The image address.
+ * @param   fFlags          Flags, DBGFMODINMEM_F_XXX.
+ * @param   pszName         The image name, optional.
+ * @param   enmArch         The image arch if we force it, pass
+ *                          RTLDRARCH_WHATEVER if you don't care.
+ * @param   cbImage         Image size.  Pass 0 if not known.
+ * @param   phDbgMod        Where to return the resulting debug module on success.
+ * @param   pErrInfo        Where to return extended error info on failure.
+ */
+VMMR3DECL(int) DBGFR3ModInMem(PUVM pUVM, PCDBGFADDRESS pImageAddr, uint32_t fFlags, const char *pszName,
+                              RTLDRARCH enmArch, uint32_t cbImage, PRTDBGMOD phDbgMod, PRTERRINFO pErrInfo)
+{
+    /*
+     * Validate and adjust.
+     */
+    AssertPtrReturn(phDbgMod, VERR_INVALID_POINTER);
+    *phDbgMod = NIL_RTDBGMOD;
+    AssertPtrReturn(pImageAddr, VERR_INVALID_POINTER);
+    AssertMsgReturn(cbImage == 0 || cbImage >= sizeof(IMAGE_NT_HEADERS32) + sizeof(IMAGE_DOS_HEADER),
+                    ("cbImage=%#x\n", cbImage), VERR_INVALID_PARAMETER);
+    AssertMsgReturn(!(fFlags & ~DBGFMODINMEM_F_VALID_MASK), ("%#x\n", fFlags), VERR_INVALID_FLAGS);
+    if (enmArch == RTLDRARCH_HOST)
+        enmArch = RTLdrGetHostArch();
+
+    /*
+     * Look for an image header we can work with.
+     */
+    DBGFMODINMEMBUF uBuf;
+    RT_ZERO(uBuf);
+
+    int rc = DBGFR3MemRead(pUVM, 0 /*idCpu*/, pImageAddr, &uBuf, sizeof(uBuf.DosHdr));
+    if (RT_FAILURE(rc))
+        return RTERRINFO_LOG_SET_F(pErrInfo, rc, "Failed to read DOS header at %RGv: %Rrc", pImageAddr->FlatPtr, rc);
+
+    if (uBuf.ab[0] == ELFMAG0 && uBuf.ab[1] == ELFMAG1 && uBuf.ab[2] == ELFMAG2 && uBuf.ab[3] == ELFMAG3)
+        return dbgfR3ModInMemElf(pUVM, pImageAddr, fFlags, pszName, enmArch, cbImage, &uBuf, phDbgMod, pErrInfo);
+
+    uint32_t offNewHdrs;
+    if (uBuf.DosHdr.e_magic == IMAGE_DOS_SIGNATURE)
+    {
+        offNewHdrs = uBuf.DosHdr.e_lfanew;
+        if (   offNewHdrs < 16
+            || offNewHdrs > (cbImage ? _2M : cbImage - sizeof(IMAGE_NT_HEADERS32)))
+            return RTERRINFO_LOG_SET_F(pErrInfo, rc, "e_lfanew value is out of range: %RX32 (16..%u)",
+                                       offNewHdrs, (cbImage ? _2M : cbImage - sizeof(IMAGE_NT_HEADERS32)));
+    }
+    else if (uBuf.Nt32.Signature == IMAGE_NT_SIGNATURE)
+        offNewHdrs = 0;
+    else
+        return RTERRINFO_LOG_SET_F(pErrInfo, VERR_INVALID_EXE_SIGNATURE, "Unknown image magic at %RGv: %.8Rhxs",
+                                   pImageAddr->FlatPtr, uBuf.ab);
+
+    /*
+     * Read the next bit of header, assuming PE so stop at the end of
+     * the COFF file header.
+     */
+    DBGFADDRESS PeHdrAddr = *pImageAddr;
+    DBGFR3AddrAdd(&PeHdrAddr, offNewHdrs);
+    uint32_t const cbPeHdrsPart1 = RT_UOFFSETOF(IMAGE_NT_HEADERS32, OptionalHeader);
+    rc = DBGFR3MemRead(pUVM, 0 /*idCpu*/, &PeHdrAddr, &uBuf, cbPeHdrsPart1);
+    if (RT_FAILURE(rc))
+        return RTERRINFO_LOG_SET_F(pErrInfo, rc, "Failed to read PE/LX/NE headers at %RGv (off=%#RX32): %Rrc",
+                                   PeHdrAddr.FlatPtr, offNewHdrs, rc);
+
+    if (uBuf.Nt32.Signature == IMAGE_NT_SIGNATURE)
+        return dbgfR3ModInMemPe(pUVM, pImageAddr, fFlags, pszName, enmArch, cbImage, offNewHdrs, cbPeHdrsPart1, &uBuf,
+                                phDbgMod, pErrInfo);
+
+    return RTERRINFO_LOG_SET_F(pErrInfo, VERR_INVALID_EXE_SIGNATURE, "No PE/LX/NE header at %RGv (off=%#RX32): %.8Rhxs",
+                               PeHdrAddr.FlatPtr, offNewHdrs, uBuf.ab);
+}
+
