VirtualBox

source: vbox/trunk/src/VBox/Debugger/DBGPlugInWinNt.cpp@ 101665

Last change on this file since 101665 was 99739, checked in by vboxsync, 18 months ago

*: doxygen corrections (mostly about removing @returns from functions returning void).

  • Property svn:eol-style set to native
  • Property svn:keywords set to Author Date Id Revision
File size: 74.0 KB
Line 
1/* $Id: DBGPlugInWinNt.cpp 99739 2023-05-11 01:01:08Z vboxsync $ */
2/** @file
3 * DBGPlugInWindows - Debugger and Guest OS Digger Plugin For Windows NT.
4 */
5
6/*
7 * Copyright (C) 2009-2023 Oracle and/or its affiliates.
8 *
9 * This file is part of VirtualBox base platform packages, as
10 * available from https://www.virtualbox.org.
11 *
12 * This program is free software; you can redistribute it and/or
13 * modify it under the terms of the GNU General Public License
14 * as published by the Free Software Foundation, in version 3 of the
15 * License.
16 *
17 * This program is distributed in the hope that it will be useful, but
18 * WITHOUT ANY WARRANTY; without even the implied warranty of
19 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
20 * General Public License for more details.
21 *
22 * You should have received a copy of the GNU General Public License
23 * along with this program; if not, see <https://www.gnu.org/licenses>.
24 *
25 * SPDX-License-Identifier: GPL-3.0-only
26 */
27
28
29/*********************************************************************************************************************************
30* Header Files *
31*********************************************************************************************************************************/
32#define LOG_GROUP LOG_GROUP_DBGF /// @todo add new log group.
33#include "DBGPlugIns.h"
34#include <VBox/vmm/dbgf.h>
35#include <VBox/vmm/cpumctx.h>
36#include <VBox/vmm/mm.h>
37#ifdef VBOX_DEBUGGER_WITH_WIN_DBG_PRINT_HOOKING
38# include <VBox/vmm/vmapi.h>
39# include <VBox/dis.h>
40#endif
41#include <VBox/vmm/vmmr3vtable.h>
42#include <VBox/err.h>
43#include <VBox/param.h>
44#include <iprt/ctype.h>
45#include <iprt/ldr.h>
46#include <iprt/mem.h>
47#include <iprt/path.h>
48#include <iprt/stream.h>
49#include <iprt/string.h>
50#include <iprt/utf16.h>
51#include <iprt/formats/pecoff.h>
52#include <iprt/formats/mz.h>
53#include <iprt/nt/nt-structures.h>
54
55
56/*********************************************************************************************************************************
57* Structures and Typedefs *
58*********************************************************************************************************************************/
59
60/** @name Internal WinNT structures
61 * @{ */
62/**
63 * PsLoadedModuleList entry for 32-bit NT aka LDR_DATA_TABLE_ENTRY.
64 * Tested with XP.
65 */
66typedef struct NTMTE32
67{
68 struct
69 {
70 uint32_t Flink;
71 uint32_t Blink;
72 } InLoadOrderLinks,
73 InMemoryOrderModuleList,
74 InInitializationOrderModuleList;
75 uint32_t DllBase;
76 uint32_t EntryPoint;
77 /** @note This field is not a size in NT 3.1. It's NULL for images loaded by the
78 * boot loader, for other images it looks like some kind of pointer. */
79 uint32_t SizeOfImage;
80 struct
81 {
82 uint16_t Length;
83 uint16_t MaximumLength;
84 uint32_t Buffer;
85 } FullDllName,
86 BaseDllName;
87 uint32_t Flags;
88 uint16_t LoadCount;
89 uint16_t TlsIndex;
90 /* ... there is more ... */
91} NTMTE32;
92typedef NTMTE32 *PNTMTE32;
93
94/**
95 * PsLoadedModuleList entry for 64-bit NT aka LDR_DATA_TABLE_ENTRY.
96 */
97typedef struct NTMTE64
98{
99 struct
100 {
101 uint64_t Flink;
102 uint64_t Blink;
103 } InLoadOrderLinks, /**< 0x00 */
104 InMemoryOrderModuleList, /**< 0x10 */
105 InInitializationOrderModuleList; /**< 0x20 */
106 uint64_t DllBase; /**< 0x30 */
107 uint64_t EntryPoint; /**< 0x38 */
108 uint32_t SizeOfImage; /**< 0x40 */
109 uint32_t Alignment; /**< 0x44 */
110 struct
111 {
112 uint16_t Length; /**< 0x48,0x58 */
113 uint16_t MaximumLength; /**< 0x4a,0x5a */
114 uint32_t Alignment; /**< 0x4c,0x5c */
115 uint64_t Buffer; /**< 0x50,0x60 */
116 } FullDllName, /**< 0x48 */
117 BaseDllName; /**< 0x58 */
118 uint32_t Flags; /**< 0x68 */
119 uint16_t LoadCount; /**< 0x6c */
120 uint16_t TlsIndex; /**< 0x6e */
121 /* ... there is more ... */
122} NTMTE64;
123typedef NTMTE64 *PNTMTE64;
124
125/** MTE union. */
126typedef union NTMTE
127{
128 NTMTE32 vX_32;
129 NTMTE64 vX_64;
130} NTMTE;
131typedef NTMTE *PNTMTE;
132
133
134/**
135 * The essential bits of the KUSER_SHARED_DATA structure.
136 */
137typedef struct NTKUSERSHAREDDATA
138{
139 uint32_t TickCountLowDeprecated;
140 uint32_t TickCountMultiplier;
141 struct
142 {
143 uint32_t LowPart;
144 int32_t High1Time;
145 int32_t High2Time;
146
147 } InterruptTime,
148 SystemTime,
149 TimeZoneBias;
150 uint16_t ImageNumberLow;
151 uint16_t ImageNumberHigh;
152 RTUTF16 NtSystemRoot[260];
153 uint32_t MaxStackTraceDepth;
154 uint32_t CryptoExponent;
155 uint32_t TimeZoneId;
156 uint32_t LargePageMinimum;
157 uint32_t Reserved2[6];
158 uint32_t NtBuildNumber;
159 uint32_t NtProductType;
160 uint8_t ProductTypeIsValid;
161 uint8_t abPadding[3];
162 uint32_t NtMajorVersion;
163 uint32_t NtMinorVersion;
164 /* uint8_t ProcessorFeatures[64];
165 ...
166 */
167} NTKUSERSHAREDDATA;
168typedef NTKUSERSHAREDDATA *PNTKUSERSHAREDDATA;
169
170/** KI_USER_SHARED_DATA for i386 */
171#define NTKUSERSHAREDDATA_WINNT32 UINT32_C(0xffdf0000)
172/** KI_USER_SHARED_DATA for AMD64 */
173#define NTKUSERSHAREDDATA_WINNT64 UINT64_C(0xfffff78000000000)
174
175/** NTKUSERSHAREDDATA::NtProductType */
176typedef enum NTPRODUCTTYPE
177{
178 kNtProductType_Invalid = 0,
179 kNtProductType_WinNt = 1,
180 kNtProductType_LanManNt,
181 kNtProductType_Server
182} NTPRODUCTTYPE;
183
184
185/** NT image header union. */
186typedef union NTHDRSU
187{
188 IMAGE_NT_HEADERS32 vX_32;
189 IMAGE_NT_HEADERS64 vX_64;
190} NTHDRS;
191/** Pointer to NT image header union. */
192typedef NTHDRS *PNTHDRS;
193/** Pointer to const NT image header union. */
194typedef NTHDRS const *PCNTHDRS;
195
196
197/**
198 * NT KD version block.
199 */
200typedef struct NTKDVERSIONBLOCK
201{
202 uint16_t MajorVersion;
203 uint16_t MinorVersion;
204 uint8_t ProtocolVersion;
205 uint8_t KdSecondaryVersion;
206 uint16_t Flags;
207 uint16_t MachineType;
208 uint8_t MaxPacketType;
209 uint8_t MaxStateChange;
210 uint8_t MaxManipulate;
211 uint8_t Simulation;
212 uint16_t Unused;
213 uint64_t KernBase;
214 uint64_t PsLoadedModuleList;
215 uint64_t DebuggerDataList;
216} NTKDVERSIONBLOCK;
217/** Pointer to an NT KD version block. */
218typedef NTKDVERSIONBLOCK *PNTKDVERSIONBLOCK;
219/** Pointer to a const NT KD version block. */
220typedef const NTKDVERSIONBLOCK *PCNTKDVERSIONBLOCK;
221
222/** @} */
223
224
225
226typedef enum DBGDIGGERWINNTVER
227{
228 DBGDIGGERWINNTVER_UNKNOWN,
229 DBGDIGGERWINNTVER_3_1,
230 DBGDIGGERWINNTVER_3_5,
231 DBGDIGGERWINNTVER_4_0,
232 DBGDIGGERWINNTVER_5_0,
233 DBGDIGGERWINNTVER_5_1,
234 DBGDIGGERWINNTVER_6_0
235} DBGDIGGERWINNTVER;
236
237/**
238 * WinNT guest OS digger instance data.
239 */
240typedef struct DBGDIGGERWINNT
241{
242 /** Whether the information is valid or not.
243 * (For fending off illegal interface method calls.) */
244 bool fValid;
245 /** 32-bit (true) or 64-bit (false) */
246 bool f32Bit;
247 /** Set if NT 3.1 was detected.
248 * This implies both Misc.VirtualSize and NTMTE32::SizeOfImage are zero. */
249 bool fNt31;
250
251 /** The NT version. */
252 DBGDIGGERWINNTVER enmVer;
253 /** NTKUSERSHAREDDATA::NtProductType */
254 NTPRODUCTTYPE NtProductType;
255 /** NTKUSERSHAREDDATA::NtMajorVersion */
256 uint32_t NtMajorVersion;
257 /** NTKUSERSHAREDDATA::NtMinorVersion */
258 uint32_t NtMinorVersion;
259 /** NTKUSERSHAREDDATA::NtBuildNumber */
260 uint32_t NtBuildNumber;
261
262 /** The address of the ntoskrnl.exe image. */
263 DBGFADDRESS KernelAddr;
264 /** The address of the ntoskrnl.exe module table entry. */
265 DBGFADDRESS KernelMteAddr;
266 /** The address of PsLoadedModuleList. */
267 DBGFADDRESS PsLoadedModuleListAddr;
268
269 /** Array of detected KPCR addresses for each vCPU. */
270 PDBGFADDRESS paKpcrAddr;
271 /** Array of detected KPCRB addresses for each vCPU. */
272 PDBGFADDRESS paKpcrbAddr;
273
274 /** The Windows NT specifics interface. */
275 DBGFOSIWINNT IWinNt;
276
277#ifdef VBOX_DEBUGGER_WITH_WIN_DBG_PRINT_HOOKING
278 /** Breakpoint owner handle for the DbgPrint/vDbgPrint{,Ex}... interception. */
279 DBGFBPOWNER hBpOwnerDbgPrint;
280 /** Breakpoint handle for the DbgPrint/vDbgPrint{,Ex}... interception. */
281 DBGFBP hBpDbgPrint;
282#endif
283} DBGDIGGERWINNT;
284/** Pointer to the linux guest OS digger instance data. */
285typedef DBGDIGGERWINNT *PDBGDIGGERWINNT;
286
287
288/**
289 * The WinNT digger's loader reader instance data.
290 */
291typedef struct DBGDIGGERWINNTRDR
292{
293 /** The VM handle (referenced). */
294 PUVM pUVM;
295 /** The image base. */
296 DBGFADDRESS ImageAddr;
297 /** The image size. */
298 uint32_t cbImage;
299 /** The file offset of the SizeOfImage field in the optional header if it
300 * needs patching, otherwise set to UINT32_MAX. */
301 uint32_t offSizeOfImage;
302 /** The correct image size. */
303 uint32_t cbCorrectImageSize;
304 /** Number of entries in the aMappings table. */
305 uint32_t cMappings;
306 /** Mapping hint. */
307 uint32_t iHint;
308 /** Mapping file offset to memory offsets, ordered by file offset. */
309 struct
310 {
311 /** The file offset. */
312 uint32_t offFile;
313 /** The size of this mapping. */
314 uint32_t cbMem;
315 /** The offset to the memory from the start of the image. */
316 uint32_t offMem;
317 } aMappings[1];
318} DBGDIGGERWINNTRDR;
319/** Pointer a WinNT loader reader instance data. */
320typedef DBGDIGGERWINNTRDR *PDBGDIGGERWINNTRDR;
321
322
323/*********************************************************************************************************************************
324* Defined Constants And Macros *
325*********************************************************************************************************************************/
326/** Validates a 32-bit Windows NT kernel address */
327#define WINNT32_VALID_ADDRESS(Addr) ((Addr) > UINT32_C(0x80000000) && (Addr) < UINT32_C(0xfffff000))
328/** Validates a 64-bit Windows NT kernel address */
329#define WINNT64_VALID_ADDRESS(Addr) ((Addr) > UINT64_C(0xffff800000000000) && (Addr) < UINT64_C(0xfffffffffffff000))
330/** Validates a kernel address. */
331#define WINNT_VALID_ADDRESS(pThis, Addr) ((pThis)->f32Bit ? WINNT32_VALID_ADDRESS(Addr) : WINNT64_VALID_ADDRESS(Addr))
332/** Versioned and bitness wrapper. */
333#define WINNT_UNION(pThis, pUnion, Member) ((pThis)->f32Bit ? (pUnion)->vX_32. Member : (pUnion)->vX_64. Member )
334
335/** The length (in chars) of the kernel file name (no path). */
336#define WINNT_KERNEL_BASE_NAME_LEN 12
337
338/** WindowsNT on little endian ASCII systems. */
339#define DIG_WINNT_MOD_TAG UINT64_C(0x54696e646f774e54)
340
341
342/*********************************************************************************************************************************
343* Internal Functions *
344*********************************************************************************************************************************/
345static DECLCALLBACK(int) dbgDiggerWinNtInit(PUVM pUVM, PCVMMR3VTABLE pVMM, void *pvData);
346
347
348/*********************************************************************************************************************************
349* Global Variables *
350*********************************************************************************************************************************/
351/** Kernel names. */
352static const RTUTF16 g_wszKernelNames[][WINNT_KERNEL_BASE_NAME_LEN + 1] =
353{
354 { 'n', 't', 'o', 's', 'k', 'r', 'n', 'l', '.', 'e', 'x', 'e' }
355};
356
357
358#ifdef VBOX_DEBUGGER_WITH_WIN_DBG_PRINT_HOOKING
359/**
360 * Queries the string from guest memory with the pointer in the given register, sanitizing it.
361 *
362 * @returns VBox status code.
363 * @param pUVM The user mode VM handle.
364 * @param idCpu The CPU ID.
365 * @param enmReg The register to query the string pointer from.
366 * @param pszBuf Where to store the sanitized string.
367 * @param cbBuf Size of the buffer in number of bytes.
368 */
369static int dbgDiggerWinNtDbgPrintQueryStringFromReg(PUVM pUVM, VMCPUID idCpu, DBGFREG enmReg, char *pszBuf, size_t cbBuf)
370{
371 uint64_t u64RegPtr = 0;
372 int rc = DBGFR3RegCpuQueryU64(pUVM, idCpu, enmReg, &u64RegPtr);
373 if ( rc == VINF_SUCCESS
374 || rc == VINF_DBGF_ZERO_EXTENDED_REGISTER) /* Being strict about what we expect here. */
375 {
376 DBGFADDRESS AddrStr;
377 DBGFR3AddrFromFlat(pUVM, &AddrStr, u64RegPtr);
378 rc = DBGFR3MemRead(pUVM, idCpu, &AddrStr, pszBuf, cbBuf);
379 if (RT_SUCCESS(rc))
380 {
381 /* Check that there is a zero terminator and purge invalid encoding (expecting UTF-8 here). */
382 size_t idx = 0;
383 for (idx = 0; idx < cbBuf; idx++)
384 if (pszBuf[idx] == '\0')
385 break;
386
387 if (idx == cbBuf)
388 pszBuf[cbBuf - 1] = '\0'; /* Force terminator, truncating the string. */
389 else
390 memset(&pszBuf[idx], 0, cbBuf - idx); /* Clear everything afterwards. */
391
392 /* Purge the string encoding. */
393 RTStrPurgeEncoding(pszBuf);
394 }
395 }
396 else if (RT_SUCCESS(rc))
397 rc = VERR_INVALID_STATE;
398
399 return rc;
400}
401
402
403/**
404 * @copydoc{FNDBGFBPHIT, Breakpoint callback for the DbgPrint interception.}
405 */
406static DECLCALLBACK(VBOXSTRICTRC) dbgDiggerWinNtDbgPrintHit(PVM pVM, VMCPUID idCpu, void *pvUserBp, DBGFBP hBp, PCDBGFBPPUB pBpPub, uint16_t fFlags)
407{
408 RT_NOREF(hBp, pBpPub, fFlags);
409 PDBGDIGGERWINNT pThis = (PDBGDIGGERWINNT)pvUserBp;
410 PUVM pUVM = VMR3GetUVM(pVM);
411
412 /*
413 * The worker prototype looks like the following:
414 * vDbgPrintExWorker(PCCH Prefix, ULONG ComponentId, ULONG Level, PCCH Format, va_list arglist, BOOL fUnknown)
415 *
416 * Depending on the bitness the parameters are grabbed from the appropriate registers and stack locations.
417 * For amd64 reading the following is recommended:
418 * https://docs.microsoft.com/en-us/cpp/build/x64-calling-convention?view=vs-2019
419 * https://docs.microsoft.com/en-us/cpp/build/prolog-and-epilog?view=vs-2019
420 * https://docs.microsoft.com/en-us/cpp/build/stack-usage?view=vs-2019
421 *
422 * @todo 32bit
423 */
424 int rc = VINF_SUCCESS;
425 uint32_t idComponent = 0;
426 uint32_t iLevel = 0;
427 char aszPrefixStr[128]; /* Restricted size. */
428 char aszFmtStr[_1K]; /* Restricted size. */
429 DBGFADDRESS AddrVaList;
430 if (!pThis->f32Bit)
431 {
432 /*
433 * Grab the prefix, component, level, format string pointer from the registers and the argument list from the
434 * stack (mind the home area for the register arguments).
435 */
436 rc = dbgDiggerWinNtDbgPrintQueryStringFromReg(pUVM, idCpu, DBGFREG_RCX, &aszPrefixStr[0], sizeof(aszPrefixStr));
437 if (RT_SUCCESS(rc))
438 rc = DBGFR3RegCpuQueryU32(pUVM, idCpu, DBGFREG_RDX, &idComponent);
439 if (RT_SUCCESS(rc))
440 rc = DBGFR3RegCpuQueryU32(pUVM, idCpu, DBGFREG_R8, &iLevel);
441 if (RT_SUCCESS(rc))
442 rc = dbgDiggerWinNtDbgPrintQueryStringFromReg(pUVM, idCpu, DBGFREG_R9, &aszFmtStr[0], sizeof(aszFmtStr));
443 if (RT_SUCCESS(rc))
444 {
445 /* Grabbing the pointer to the va list. The stack layout when we are here looks like (each entry is 64bit):
446 * +-------------+
447 * | ... |
448 * | VA list ptr |
449 * | (arg3/r9) |
450 * | (arg2/r8) |
451 * | (arg1/rdx) |
452 * | (arg0/rcx) |
453 * | return RIP |
454 * +-------------+ <- RSP
455 */
456 uint64_t uRegRsp = 0;
457 rc = DBGFR3RegCpuQueryU64(pUVM, idCpu, DBGFREG_RSP, &uRegRsp);
458 if (rc == VINF_SUCCESS)
459 {
460 DBGFADDRESS AddrVaListPtr;
461 RTGCUINTPTR GCPtrVaList = 0;
462
463 DBGFR3AddrFromFlat(pUVM, &AddrVaListPtr, uRegRsp + 5 * sizeof(RTGCUINTPTR));
464 rc = DBGFR3MemRead(pUVM, idCpu, &AddrVaListPtr, &GCPtrVaList, sizeof(GCPtrVaList));
465 if (RT_SUCCESS(rc))
466 DBGFR3AddrFromFlat(pUVM, &AddrVaList, GCPtrVaList);
467 }
468 else
469 rc = VERR_INVALID_STATE;
470 }
471 }
472 else
473 rc = VERR_NOT_IMPLEMENTED; /** @todo */
474
475 if (RT_SUCCESS(rc))
476 {
477 LogRel(("DigWinNt/DbgPrint: Queried arguments %s %#x %u %s %RGv\n", &aszPrefixStr[0], idComponent, iLevel, &aszFmtStr[0], AddrVaList.FlatPtr));
478 /** @todo Continue here. */
479 }
480 else
481 LogRel(("DigWinNt/DbgPrint: Failed to query all arguments with rc=%Rrc\n", rc));
482
483 return VINF_SUCCESS;
484}
485
486
487/**
488 * Disassembles the given instruction and checks whether it is a call with a fixed address.
489 *
490 * @returns Flag whether the insturction at the given address is a call.
491 * @param pThis The instance data.
492 * @param pUVM The user mode VM handle.
493 * @param pAddrInsn Guest address of the instruction.
494 * @param pAddrCall Where to store the destination if the instruction is a call.
495 */
496static bool dbgDiggerWinNtDbgPrintWrapperInsnIsCall(PDBGDIGGERWINNT pThis, PUVM pUVM, PCDBGFADDRESS pAddrInsn, PDBGFADDRESS pAddrCall)
497{
498 DISSTATE DisState;
499 RT_ZERO(DisState);
500
501 /* Prefetch the instruction. */
502 uint8_t abInstr[32];
503 int rc = DBGFR3MemRead(pUVM, 0 /*idCpu*/, pAddrInsn, &abInstr[0], sizeof(abInstr));
504 if (RT_SUCCESS(rc))
505 {
506 uint32_t cbInsn = 0;
507 rc = DISInstr(&abInstr[0], pThis->f32Bit ? DISCPUMODE_32BIT : DISCPUMODE_64BIT, &DisState, &cbInsn);
508 if ( RT_SUCCESS(rc)
509 && DisState.pCurInstr->uOpcode == OP_CALL
510 && DisState.Param1.fUse & DISUSE_IMMEDIATE)
511 {
512 if (DisState.Param1.fUse & (DISUSE_IMMEDIATE32 | DISUSE_IMMEDIATE64))
513 DBGFR3AddrFromFlat(pUVM, pAddrCall, DisState.Param1.uValue);
514 else if (DisState.Param1.fUse & (DISUSE_IMMEDIATE32_REL | DISUSE_IMMEDIATE64_REL))
515 {
516 *pAddrCall = *pAddrInsn;
517 DBGFR3AddrAdd(pAddrCall, DisState.Param1.uValue + cbInsn);
518 }
519
520 return true;
521 }
522 }
523
524 return false;
525}
526
527
528/**
529 * Tries to find the single call instruction of the DbgPrint/etc. worker in the given control flow graph
530 * (single basic block assumed).
531 *
532 * @returns VBox status code.
533 * @param pThis The instance data.
534 * @param pUVM The user mode VM handle.
535 * @param hFlow The control flow graph handle.
536 * @param pAddr Where to store the worker address on success.
537 */
538static int dbgDiggerWinNtDbgPrintResolveWorker(PDBGDIGGERWINNT pThis, PUVM pUVM, DBGFFLOW hFlow, PDBGFADDRESS pAddr)
539{
540 DBGFFLOWBB hBb;
541 int rc = DBGFR3FlowQueryStartBb(hFlow, &hBb);
542 if (RT_SUCCESS(rc))
543 {
544 bool fCallFound = false;
545
546 for (uint32_t i = 0; i < DBGFR3FlowBbGetInstrCount(hBb) && RT_SUCCESS(rc); i++)
547 {
548 DBGFADDRESS AddrInsn;
549 uint32_t cbInsn;
550 rc = DBGFR3FlowBbQueryInstr(hBb, i, &AddrInsn, &cbInsn, NULL);
551 if (RT_SUCCESS(rc))
552 {
553 DBGFADDRESS AddrCall;
554 if (dbgDiggerWinNtDbgPrintWrapperInsnIsCall(pThis, pUVM, &AddrInsn, &AddrCall))
555 {
556 if (!fCallFound)
557 {
558 *pAddr = AddrCall;
559 fCallFound = true;
560 }
561 else
562 {
563 LogRel(("DigWinNt/DbgPrint: nt!vDbgPrintEx contains multiple call instructions!\n"));
564 rc = VERR_ALREADY_EXISTS;
565 }
566 }
567 }
568 }
569
570 DBGFR3FlowBbRelease(hBb);
571 }
572
573 return rc;
574}
575
576
577/**
578 * Tries to resolve and hook into the worker for all the DbgPrint like wrappers to be able
579 * to gather debug information from the system.
580 *
581 * @param pThis The instance data.
582 * @param pUVM The user mode VM handle.
583 */
584static void dbgDiggerWinNtDbgPrintHook(PDBGDIGGERWINNT pThis, PUVM pUVM)
585{
586 /*
587 * This is a multi step process:
588 * 1. Try to resolve the address of vDbgPrint() (available since XP).
589 * 2. Create a control flow graph from the code and verify the following assumptions:
590 * 1. Only a single basic block.
591 * 2. Just one call instruction.
592 * @todo More?
593 * 3. Get the address from the called worker
594 * 4. Set a hardware breakpoint with our callback.
595 */
596 RTDBGAS hAs = DBGFR3AsResolveAndRetain(pUVM, DBGF_AS_KERNEL);
597 if (hAs != NIL_RTDBGAS)
598 {
599 RTDBGSYMBOL SymInfo;
600 int rc = RTDbgAsSymbolByName(hAs, "nt!vDbgPrintEx", &SymInfo, NULL /*phMod*/);
601 if (RT_SUCCESS(rc))
602 {
603 DBGFADDRESS Addr;
604 DBGFR3AddrFromFlat(pUVM, &Addr, (RTGCPTR)SymInfo.Value);
605
606 LogRel(("DigWinNt/DbgPrint: nt!vDbgPrintEx resolved to %RGv\n", SymInfo.Value));
607
608 DBGFFLOW hCfg;
609 rc = DBGFR3FlowCreate(pUVM, 0 /*idCpu*/, &Addr, 512 /*cbDisasmMax*/,
610 0 /*fFlagsFlow*/, DBGF_DISAS_FLAGS_UNPATCHED_BYTES | DBGF_DISAS_FLAGS_ANNOTATE_PATCHED | DBGF_DISAS_FLAGS_DEFAULT_MODE,
611 &hCfg);
612 if (RT_SUCCESS(rc))
613 {
614 /* Verify assumptions. */
615 if (DBGFR3FlowGetBbCount(hCfg) == 1)
616 {
617 rc = dbgDiggerWinNtDbgPrintResolveWorker(pThis, pUVM, hCfg, &Addr);
618 if (RT_SUCCESS(rc))
619 {
620 /* Try to hook the worker. */
621 LogRel(("DigWinNt/DbgPrint: Worker for nt!vDbgPrintEx resolved to %RGv\n", Addr.FlatPtr));
622 rc = DBGFR3BpOwnerCreate(pUVM, dbgDiggerWinNtDbgPrintHit, NULL /*pfnBpIoHit*/, &pThis->hBpOwnerDbgPrint);
623 if (RT_SUCCESS(rc))
624 {
625 rc = DBGFR3BpSetInt3Ex(pUVM, pThis->hBpOwnerDbgPrint, pThis, 0 /*idCpu*/, &Addr, DBGF_BP_F_DEFAULT,
626 0 /*iHitTrigger*/, 0 /*iHitDisable*/, &pThis->hBpDbgPrint);
627 if (RT_SUCCESS(rc))
628 LogRel(("DigWinNt/DbgPrint: Hooked nt!vDbgPrintEx worker hBp=%#x\n", pThis->hBpDbgPrint));
629 else
630 {
631 LogRel(("DigWinNt/DbgPrint: Setting hardware breakpoint for nt!vDbgPrintEx worker failed with rc=%Rrc\n", rc));
632 int rc2 = DBGFR3BpOwnerDestroy(pUVM, pThis->hBpOwnerDbgPrint);
633 pThis->hBpOwnerDbgPrint = NIL_DBGFBPOWNER;
634 AssertRC(rc2);
635 }
636 }
637 }
638 /* else LogRel() already done */
639 }
640 else
641 LogRel(("DigWinNt/DbgPrint: Control flow graph for nt!vDbgPrintEx has more than one basic block (%u)\n",
642 DBGFR3FlowGetBbCount(hCfg)));
643
644 DBGFR3FlowRelease(hCfg);
645 }
646 else
647 LogRel(("DigWinNt/DbgPrint: Failed to create control flow graph from nt!vDbgPrintEx rc=%Rrc\n", rc));
648 }
649 else
650 LogRel(("DigWinNt/DbgPrint: Failed to resolve nt!vDbgPrintEx -> rc=%Rrc\n", rc));
651 RTDbgAsRelease(hAs);
652 }
653 else
654 LogRel(("DigWinNt/DbgPrint: Failed to resolve kernel address space handle\n"));
655}
656#endif
657
658/**
659 * Tries to resolve the KPCR and KPCRB addresses for each vCPU.
660 *
661 * @param pThis The instance data.
662 * @param pUVM The user mode VM handle.
663 * @param pVMM The VMM function table.
664 */
665static void dbgDiggerWinNtResolveKpcr(PDBGDIGGERWINNT pThis, PUVM pUVM, PCVMMR3VTABLE pVMM)
666{
667 /*
668 * Getting at the KPCR and KPCRB is explained here:
669 * https://www.geoffchappell.com/studies/windows/km/ntoskrnl/structs/kpcr.htm
670 * Together with the available offsets from:
671 * https://github.com/tpn/winsdk-10/blob/master/Include/10.0.16299.0/shared/ksamd64.inc#L883
672 * we can verify that the found addresses are valid by cross checking that the GDTR and self reference
673 * match what we expect.
674 */
675 VMCPUID cCpus = pVMM->pfnDBGFR3CpuGetCount(pUVM);
676 pThis->paKpcrAddr = (PDBGFADDRESS)RTMemAllocZ(cCpus * 2 * sizeof(DBGFADDRESS));
677 if (RT_LIKELY(pThis->paKpcrAddr))
678 {
679 pThis->paKpcrbAddr = &pThis->paKpcrAddr[cCpus];
680
681 /* Work each CPU, unexpected values in each CPU make the whole thing fail to play safe. */
682 int rc = VINF_SUCCESS;
683 for (VMCPUID idCpu = 0; (idCpu < cCpus) && RT_SUCCESS(rc); idCpu++)
684 {
685 PDBGFADDRESS pKpcrAddr = &pThis->paKpcrAddr[idCpu];
686 PDBGFADDRESS pKpcrbAddr = &pThis->paKpcrbAddr[idCpu];
687
688 if (pThis->f32Bit)
689 {
690 /* Read FS base */
691 uint32_t GCPtrKpcrBase = 0;
692
693 rc = pVMM->pfnDBGFR3RegCpuQueryU32(pUVM, idCpu, DBGFREG_FS_BASE, &GCPtrKpcrBase);
694 if ( RT_SUCCESS(rc)
695 && WINNT32_VALID_ADDRESS(GCPtrKpcrBase))
696 {
697 /*
698 * Read the start of the KPCR (@todo Probably move this to a global header)
699 * and verify its content.
700 */
701 struct
702 {
703 uint8_t abOoi[28]; /* Out of interest */
704 uint32_t GCPtrSelf;
705 uint32_t GCPtrCurrentPrcb;
706 uint32_t u32Irql;
707 uint32_t u32Iir;
708 uint32_t u32IirActive;
709 uint32_t u32Idr;
710 uint32_t GCPtrKdVersionBlock;
711 uint32_t GCPtrIdt;
712 uint32_t GCPtrGdt;
713 uint32_t GCPtrTss;
714 } Kpcr;
715
716 LogFlow(("DigWinNt/KPCR[%u]: GS Base %RGv\n", idCpu, GCPtrKpcrBase));
717 pVMM->pfnDBGFR3AddrFromFlat(pUVM, pKpcrAddr, GCPtrKpcrBase);
718
719 rc = pVMM->pfnDBGFR3MemRead(pUVM, idCpu, pKpcrAddr, &Kpcr, sizeof(Kpcr));
720 if (RT_SUCCESS(rc))
721 {
722 uint32_t GCPtrGdt = 0;
723 uint32_t GCPtrIdt = 0;
724
725 rc = pVMM->pfnDBGFR3RegCpuQueryU32(pUVM, idCpu, DBGFREG_GDTR_BASE, &GCPtrGdt);
726 if (RT_SUCCESS(rc))
727 rc = pVMM->pfnDBGFR3RegCpuQueryU32(pUVM, idCpu, DBGFREG_IDTR_BASE, &GCPtrIdt);
728 if (RT_SUCCESS(rc))
729 {
730 if ( Kpcr.GCPtrGdt == GCPtrGdt
731 && Kpcr.GCPtrIdt == GCPtrIdt
732 && Kpcr.GCPtrSelf == pKpcrAddr->FlatPtr)
733 {
734 pVMM->pfnDBGFR3AddrFromFlat(pUVM, pKpcrbAddr, Kpcr.GCPtrCurrentPrcb);
735 LogRel(("DigWinNt/KPCR[%u]: KPCR=%RGv KPCRB=%RGv\n", idCpu, pKpcrAddr->FlatPtr, pKpcrbAddr->FlatPtr));
736
737 /*
738 * Try to extract the NT build number from the KD version block if it exists,
739 * the shared user data might have set it to 0.
740 *
741 * @todo We can use this method to get at the kern base and loaded module list if the other detection
742 * method fails (seen with Windows 10 x86).
743 * @todo On 32bit Windows the debugger data list is also always accessible this way contrary to
744 * the amd64 version where it is only available with "/debug on" set.
745 */
746 if (!pThis->NtBuildNumber)
747 {
748 NTKDVERSIONBLOCK KdVersBlock;
749 DBGFADDRESS AddrKdVersBlock;
750
751 pVMM->pfnDBGFR3AddrFromFlat(pUVM, &AddrKdVersBlock, Kpcr.GCPtrKdVersionBlock);
752 rc = pVMM->pfnDBGFR3MemRead(pUVM, idCpu, &AddrKdVersBlock, &KdVersBlock, sizeof(KdVersBlock));
753 if (RT_SUCCESS(rc))
754 pThis->NtBuildNumber = KdVersBlock.MinorVersion;
755 }
756 }
757 else
758 LogRel(("DigWinNt/KPCR[%u]: KPCR validation error GDT=(%RGv vs %RGv) KPCR=(%RGv vs %RGv)\n", idCpu,
759 Kpcr.GCPtrGdt, GCPtrGdt, Kpcr.GCPtrSelf, pKpcrAddr->FlatPtr));
760 }
761 else
762 LogRel(("DigWinNt/KPCR[%u]: Getting GDT or IDT base register failed with %Rrc\n", idCpu, rc));
763 }
764 }
765 else
766 LogRel(("DigWinNt/KPCR[%u]: Getting FS base register failed with %Rrc (%RGv)\n", idCpu, rc, GCPtrKpcrBase));
767 }
768 else
769 {
770 /* Read GS base which points to the base of the KPCR for each CPU. */
771 RTGCUINTPTR GCPtrTmp = 0;
772 rc = pVMM->pfnDBGFR3RegCpuQueryU64(pUVM, idCpu, DBGFREG_GS_BASE, &GCPtrTmp);
773 if ( RT_SUCCESS(rc)
774 && !WINNT64_VALID_ADDRESS(GCPtrTmp))
775 {
776 /*
777 * Could be a user address when we stopped the VM right in usermode,
778 * read the GS kernel base MSR instead.
779 */
780 rc = pVMM->pfnDBGFR3RegCpuQueryU64(pUVM, idCpu, DBGFREG_MSR_K8_KERNEL_GS_BASE, &GCPtrTmp);
781 }
782
783 if ( RT_SUCCESS(rc)
784 && WINNT64_VALID_ADDRESS(GCPtrTmp))
785 {
786 LogFlow(("DigWinNt/KPCR[%u]: GS Base %RGv\n", idCpu, GCPtrTmp));
787 pVMM->pfnDBGFR3AddrFromFlat(pUVM, pKpcrAddr, GCPtrTmp);
788
789 rc = pVMM->pfnDBGFR3RegCpuQueryU64(pUVM, idCpu, DBGFREG_GDTR_BASE, &GCPtrTmp);
790 if (RT_SUCCESS(rc))
791 {
792 /*
793 * Read the start of the KPCR (@todo Probably move this to a global header)
794 * and verify its content.
795 */
796 struct
797 {
798 RTGCUINTPTR GCPtrGdt;
799 RTGCUINTPTR GCPtrTss;
800 RTGCUINTPTR GCPtrUserRsp;
801 RTGCUINTPTR GCPtrSelf;
802 RTGCUINTPTR GCPtrCurrentPrcb;
803 } Kpcr;
804
805 rc = pVMM->pfnDBGFR3MemRead(pUVM, idCpu, pKpcrAddr, &Kpcr, sizeof(Kpcr));
806 if (RT_SUCCESS(rc))
807 {
808 if ( Kpcr.GCPtrGdt == GCPtrTmp
809 && Kpcr.GCPtrSelf == pKpcrAddr->FlatPtr
810 /** @todo && TSS */ )
811 {
812 pVMM->pfnDBGFR3AddrFromFlat(pUVM, pKpcrbAddr, Kpcr.GCPtrCurrentPrcb);
813 LogRel(("DigWinNt/KPCR[%u]: KPCR=%RGv KPCRB=%RGv\n", idCpu, pKpcrAddr->FlatPtr, pKpcrbAddr->FlatPtr));
814 }
815 else
816 LogRel(("DigWinNt/KPCR[%u]: KPCR validation error GDT=(%RGv vs %RGv) KPCR=(%RGv vs %RGv)\n", idCpu,
817 Kpcr.GCPtrGdt, GCPtrTmp, Kpcr.GCPtrSelf, pKpcrAddr->FlatPtr));
818 }
819 else
820 LogRel(("DigWinNt/KPCR[%u]: Reading KPCR start at %RGv failed with %Rrc\n", idCpu, pKpcrAddr->FlatPtr, rc));
821 }
822 else
823 LogRel(("DigWinNt/KPCR[%u]: Getting GDT base register failed with %Rrc\n", idCpu, rc));
824 }
825 else
826 LogRel(("DigWinNt/KPCR[%u]: Getting GS base register failed with %Rrc\n", idCpu, rc));
827 }
828 }
829
830 if (RT_FAILURE(rc))
831 {
832 LogRel(("DigWinNt/KPCR: Failed to detmine KPCR and KPCRB rc=%Rrc\n", rc));
833 RTMemFree(pThis->paKpcrAddr);
834 pThis->paKpcrAddr = NULL;
835 pThis->paKpcrbAddr = NULL;
836 }
837 }
838 else
839 LogRel(("DigWinNt/KPCR: Failed to allocate %u entries for the KPCR/KPCRB addresses\n", cCpus * 2));
840}
841
842
843/**
844 * Process a PE image found in guest memory.
845 *
846 * @param pThis The instance data.
847 * @param pUVM The user mode VM handle.
848 * @param pVMM The VMM function table.
849 * @param pszName The module name.
850 * @param pszFilename The image filename.
851 * @param pImageAddr The image address.
852 * @param cbImage The size of the image.
853 */
854static void dbgDiggerWinNtProcessImage(PDBGDIGGERWINNT pThis, PUVM pUVM, PCVMMR3VTABLE pVMM, const char *pszName,
855 const char *pszFilename, PCDBGFADDRESS pImageAddr, uint32_t cbImage)
856{
857 LogFlow(("DigWinNt: %RGp %#x %s\n", pImageAddr->FlatPtr, cbImage, pszName));
858
859 /*
860 * Do some basic validation first.
861 */
862 if ( (cbImage < sizeof(IMAGE_NT_HEADERS64) && !pThis->fNt31)
863 || cbImage >= _1M * 256)
864 {
865 Log(("DigWinNt: %s: Bad image size: %#x\n", pszName, cbImage));
866 return;
867 }
868
869 /*
870 * Use the common in-memory module reader to create a debug module.
871 */
872 RTERRINFOSTATIC ErrInfo;
873 RTDBGMOD hDbgMod = NIL_RTDBGMOD;
874 int rc = pVMM->pfnDBGFR3ModInMem(pUVM, pImageAddr, pThis->fNt31 ? DBGFMODINMEM_F_PE_NT31 : 0, pszName, pszFilename,
875 pThis->f32Bit ? RTLDRARCH_X86_32 : RTLDRARCH_AMD64, cbImage,
876 &hDbgMod, RTErrInfoInitStatic(&ErrInfo));
877 if (RT_SUCCESS(rc))
878 {
879 /*
880 * Tag the module.
881 */
882 rc = RTDbgModSetTag(hDbgMod, DIG_WINNT_MOD_TAG);
883 AssertRC(rc);
884
885 /*
886 * Link the module.
887 */
888 RTDBGAS hAs = pVMM->pfnDBGFR3AsResolveAndRetain(pUVM, DBGF_AS_KERNEL);
889 if (hAs != NIL_RTDBGAS)
890 rc = RTDbgAsModuleLink(hAs, hDbgMod, pImageAddr->FlatPtr, RTDBGASLINK_FLAGS_REPLACE /*fFlags*/);
891 else
892 rc = VERR_INTERNAL_ERROR;
893 RTDbgModRelease(hDbgMod);
894 RTDbgAsRelease(hAs);
895 }
896 else if (RTErrInfoIsSet(&ErrInfo.Core))
897 Log(("DigWinNt: %s: DBGFR3ModInMem failed: %Rrc - %s\n", pszName, rc, ErrInfo.Core.pszMsg));
898 else
899 Log(("DigWinNt: %s: DBGFR3ModInMem failed: %Rrc\n", pszName, rc));
900}
901
902
903/**
904 * Generate a debugger compatible module name from a filename.
905 *
906 * @returns Pointer to module name (doesn't need to be pszName).
907 * @param pszFilename The source filename.
908 * @param pszName Buffer to put the module name in.
909 * @param cbName Buffer size.
910 */
911static const char *dbgDiggerWintNtFilenameToModuleName(const char *pszFilename, char *pszName, size_t cbName)
912{
913 /* Skip to the filename part of the filename. :-) */
914 pszFilename = RTPathFilenameEx(pszFilename, RTPATH_STR_F_STYLE_DOS);
915
916 /* We try use 'nt' for the kernel. */
917 if ( RTStrICmpAscii(pszFilename, "ntoskrnl.exe") == 0
918 || RTStrICmpAscii(pszFilename, "ntkrnlmp.exe") == 0)
919 return "nt";
920
921
922 /* Drop the extension if .dll or .sys. */
923 size_t cchFilename = strlen(pszFilename);
924 if ( cchFilename > 4
925 && pszFilename[cchFilename - 4] == '.')
926 {
927 if ( RTStrICmpAscii(&pszFilename[cchFilename - 4], ".sys") == 0
928 || RTStrICmpAscii(&pszFilename[cchFilename - 4], ".dll") == 0)
929 cchFilename -= 4;
930 }
931
932 /* Copy and do replacements. */
933 if (cchFilename >= cbName)
934 cchFilename = cbName - 1;
935 size_t off;
936 for (off = 0; off < cchFilename; off++)
937 {
938 char ch = pszFilename[off];
939 if (!RT_C_IS_ALNUM(ch))
940 ch = '_';
941 pszName[off] = ch;
942 }
943 pszName[off] = '\0';
944 return pszName;
945}
946
947
948/**
949 * @interface_method_impl{DBGFOSIWINNT,pfnQueryVersion}
950 */
951static DECLCALLBACK(int) dbgDiggerWinNtIWinNt_QueryVersion(struct DBGFOSIWINNT *pThis, PUVM pUVM, PCVMMR3VTABLE pVMM,
952 uint32_t *puVersMajor, uint32_t *puVersMinor,
953 uint32_t *puBuildNumber, bool *pf32Bit)
954{
955 PDBGDIGGERWINNT pData = RT_FROM_MEMBER(pThis, DBGDIGGERWINNT, IWinNt);
956 RT_NOREF(pUVM, pVMM);
957
958 if (puVersMajor)
959 *puVersMajor = pData->NtMajorVersion;
960 if (puVersMinor)
961 *puVersMinor = pData->NtMinorVersion;
962 if (puBuildNumber)
963 *puBuildNumber = pData->NtBuildNumber;
964 if (pf32Bit)
965 *pf32Bit = pData->f32Bit;
966 return VINF_SUCCESS;
967}
968
969
970/**
971 * @interface_method_impl{DBGFOSIWINNT,pfnQueryKernelPtrs}
972 */
973static DECLCALLBACK(int) dbgDiggerWinNtIWinNt_QueryKernelPtrs(struct DBGFOSIWINNT *pThis, PUVM pUVM, PCVMMR3VTABLE pVMM,
974 PRTGCUINTPTR pGCPtrKernBase, PRTGCUINTPTR pGCPtrPsLoadedModuleList)
975{
976 PDBGDIGGERWINNT pData = RT_FROM_MEMBER(pThis, DBGDIGGERWINNT, IWinNt);
977 RT_NOREF(pUVM, pVMM);
978
979 *pGCPtrKernBase = pData->KernelAddr.FlatPtr;
980 *pGCPtrPsLoadedModuleList = pData->PsLoadedModuleListAddr.FlatPtr;
981 return VINF_SUCCESS;
982}
983
984
985/**
986 * @interface_method_impl{DBGFOSIWINNT,pfnQueryKpcrForVCpu}
987 */
988static DECLCALLBACK(int) dbgDiggerWinNtIWinNt_QueryKpcrForVCpu(struct DBGFOSIWINNT *pThis, PUVM pUVM, PCVMMR3VTABLE pVMM,
989 VMCPUID idCpu, PRTGCUINTPTR pKpcr, PRTGCUINTPTR pKpcrb)
990{
991 PDBGDIGGERWINNT pData = RT_FROM_MEMBER(pThis, DBGDIGGERWINNT, IWinNt);
992
993 if (!pData->paKpcrAddr)
994 return VERR_NOT_SUPPORTED;
995
996 AssertReturn(idCpu < pVMM->pfnDBGFR3CpuGetCount(pUVM), VERR_INVALID_CPU_ID);
997
998 if (pKpcr)
999 *pKpcr = pData->paKpcrAddr[idCpu].FlatPtr;
1000 if (pKpcrb)
1001 *pKpcrb = pData->paKpcrbAddr[idCpu].FlatPtr;
1002 return VINF_SUCCESS;
1003}
1004
1005
1006/**
1007 * @interface_method_impl{DBGFOSIWINNT,pfnQueryCurThrdForVCpu}
1008 */
1009static DECLCALLBACK(int) dbgDiggerWinNtIWinNt_QueryCurThrdForVCpu(struct DBGFOSIWINNT *pThis, PUVM pUVM, PCVMMR3VTABLE pVMM,
1010 VMCPUID idCpu, PRTGCUINTPTR pCurThrd)
1011{
1012 PDBGDIGGERWINNT pData = RT_FROM_MEMBER(pThis, DBGDIGGERWINNT, IWinNt);
1013
1014 if (!pData->paKpcrAddr)
1015 return VERR_NOT_SUPPORTED;
1016
1017 AssertReturn(idCpu < pVMM->pfnDBGFR3CpuGetCount(pUVM), VERR_INVALID_CPU_ID);
1018
1019 DBGFADDRESS AddrCurThrdPtr = pData->paKpcrbAddr[idCpu];
1020 pVMM->pfnDBGFR3AddrAdd(&AddrCurThrdPtr, 0x08); /** @todo Make this prettier. */
1021 return pVMM->pfnDBGFR3MemRead(pUVM, idCpu, &AddrCurThrdPtr, pCurThrd, sizeof(*pCurThrd));
1022}
1023
1024
1025/**
1026 * @copydoc DBGFOSREG::pfnStackUnwindAssist
1027 */
1028static DECLCALLBACK(int) dbgDiggerWinNtStackUnwindAssist(PUVM pUVM, PCVMMR3VTABLE pVMM, void *pvData, VMCPUID idCpu,
1029 PDBGFSTACKFRAME pFrame, PRTDBGUNWINDSTATE pState, PCCPUMCTX pInitialCtx,
1030 RTDBGAS hAs, uint64_t *puScratch)
1031{
1032 Assert(pInitialCtx);
1033
1034 /*
1035 * We want to locate trap frames here. The trap frame structure contains
1036 * the 64-bit IRET frame, so given unwind information it's easy to identify
1037 * using the return type and frame address.
1038 */
1039 if (pFrame->fFlags & DBGFSTACKFRAME_FLAGS_64BIT)
1040 {
1041 /*
1042 * Is this a trap frame? If so, try read the trap frame.
1043 */
1044 if ( pFrame->enmReturnType == RTDBGRETURNTYPE_IRET64
1045 && !(pFrame->AddrFrame.FlatPtr & 0x7)
1046 && WINNT64_VALID_ADDRESS(pFrame->AddrFrame.FlatPtr) )
1047 {
1048 KTRAP_FRAME_AMD64 TrapFrame;
1049 RT_ZERO(TrapFrame);
1050 uint64_t const uTrapFrameAddr = pFrame->AddrFrame.FlatPtr
1051 - RT_UOFFSETOF(KTRAP_FRAME_AMD64, ErrCdOrXcptFrameOrS);
1052 int rc = pState->pfnReadStack(pState, uTrapFrameAddr, sizeof(TrapFrame), &TrapFrame);
1053 if (RT_SUCCESS(rc))
1054 {
1055 /* Valid? Not too much else we can check here (EFlags isn't
1056 reliable in manually construct frames). */
1057 if (TrapFrame.ExceptionActive <= 2)
1058 {
1059 pFrame->fFlags |= DBGFSTACKFRAME_FLAGS_TRAP_FRAME;
1060
1061 /*
1062 * Add sure 'register' information from the frame to the frame.
1063 *
1064 * To avoid code duplication, we do this in two steps in a loop.
1065 * The first iteration only figures out how many registers we're
1066 * going to save and allocates room for them. The second iteration
1067 * does the actual adding.
1068 */
1069 uint32_t cRegs = pFrame->cSureRegs;
1070 PDBGFREGVALEX paSureRegs = NULL;
1071#define ADD_REG_NAMED(a_Type, a_ValMemb, a_Value, a_pszName) do { \
1072 if (paSureRegs) \
1073 { \
1074 paSureRegs[iReg].pszName = a_pszName;\
1075 paSureRegs[iReg].enmReg = DBGFREG_END; \
1076 paSureRegs[iReg].enmType = a_Type; \
1077 paSureRegs[iReg].Value.a_ValMemb = (a_Value); \
1078 } \
1079 iReg++; \
1080 } while (0)
1081#define MAYBE_ADD_GREG(a_Value, a_enmReg, a_idxReg) do { \
1082 if (!(pState->u.x86.Loaded.s.fRegs & RT_BIT(a_idxReg))) \
1083 { \
1084 if (paSureRegs) \
1085 { \
1086 pState->u.x86.Loaded.s.fRegs |= RT_BIT(a_idxReg); \
1087 pState->u.x86.auRegs[a_idxReg] = (a_Value); \
1088 paSureRegs[iReg].Value.u64 = (a_Value); \
1089 paSureRegs[iReg].enmReg = a_enmReg; \
1090 paSureRegs[iReg].enmType = DBGFREGVALTYPE_U64; \
1091 paSureRegs[iReg].pszName = NULL; \
1092 } \
1093 iReg++; \
1094 } \
1095 } while (0)
1096 for (unsigned iLoop = 0; iLoop < 2; iLoop++)
1097 {
1098 uint32_t iReg = pFrame->cSureRegs;
1099 ADD_REG_NAMED(DBGFREGVALTYPE_U64, u64, uTrapFrameAddr, "TrapFrame");
1100 ADD_REG_NAMED(DBGFREGVALTYPE_U8, u8, TrapFrame.ExceptionActive, "ExceptionActive");
1101 if (TrapFrame.ExceptionActive == 0)
1102 {
1103 ADD_REG_NAMED(DBGFREGVALTYPE_U8, u8, TrapFrame.PreviousIrql, "PrevIrql");
1104 ADD_REG_NAMED(DBGFREGVALTYPE_U8, u8, (uint8_t)TrapFrame.ErrCdOrXcptFrameOrS, "IntNo");
1105 }
1106 else if ( TrapFrame.ExceptionActive == 1
1107 && TrapFrame.FaultIndicator == ((TrapFrame.ErrCdOrXcptFrameOrS >> 1) & 0x9))
1108 ADD_REG_NAMED(DBGFREGVALTYPE_U64, u64, TrapFrame.FaultAddrOrCtxRecOrTS, "cr2-probably");
1109 if (TrapFrame.SegCs & X86_SEL_RPL)
1110 ADD_REG_NAMED(DBGFREGVALTYPE_U8, u8, 1, "UserMode");
1111 else
1112 ADD_REG_NAMED(DBGFREGVALTYPE_U8, u8, 1, "KernelMode");
1113 if (TrapFrame.ExceptionActive <= 1)
1114 {
1115 MAYBE_ADD_GREG(TrapFrame.Rax, DBGFREG_RAX, X86_GREG_xAX);
1116 MAYBE_ADD_GREG(TrapFrame.Rcx, DBGFREG_RCX, X86_GREG_xCX);
1117 MAYBE_ADD_GREG(TrapFrame.Rdx, DBGFREG_RDX, X86_GREG_xDX);
1118 MAYBE_ADD_GREG(TrapFrame.R8, DBGFREG_R8, X86_GREG_x8);
1119 MAYBE_ADD_GREG(TrapFrame.R9, DBGFREG_R9, X86_GREG_x9);
1120 MAYBE_ADD_GREG(TrapFrame.R10, DBGFREG_R10, X86_GREG_x10);
1121 MAYBE_ADD_GREG(TrapFrame.R11, DBGFREG_R11, X86_GREG_x11);
1122 }
1123 else if (TrapFrame.ExceptionActive == 2)
1124 {
1125 MAYBE_ADD_GREG(TrapFrame.Rbx, DBGFREG_RBX, X86_GREG_xBX);
1126 MAYBE_ADD_GREG(TrapFrame.Rsi, DBGFREG_RSI, X86_GREG_xSI);
1127 MAYBE_ADD_GREG(TrapFrame.Rdi, DBGFREG_RDI, X86_GREG_xDI);
1128 }
1129 // MAYBE_ADD_GREG(TrapFrame.Rbp, DBGFREG_RBP, X86_GREG_xBP); - KiInterrupt[Sub]Dispatch* may leave this invalid.
1130
1131 /* Done? */
1132 if (iLoop > 0)
1133 {
1134 Assert(cRegs == iReg);
1135 break;
1136 }
1137
1138 /* Resize the array, zeroing the extension. */
1139 if (pFrame->cSureRegs)
1140 paSureRegs = (PDBGFREGVALEX)pVMM->pfnMMR3HeapRealloc(pFrame->paSureRegs, iReg * sizeof(paSureRegs[0]));
1141 else
1142 paSureRegs = (PDBGFREGVALEX)pVMM->pfnMMR3HeapAllocU(pUVM, MM_TAG_DBGF_STACK, iReg * sizeof(paSureRegs[0]));
1143 AssertReturn(paSureRegs, VERR_NO_MEMORY);
1144
1145 pFrame->paSureRegs = paSureRegs;
1146 RT_BZERO(&paSureRegs[pFrame->cSureRegs], (iReg - pFrame->cSureRegs) * sizeof(paSureRegs[0]));
1147 cRegs = iReg;
1148 }
1149#undef ADD_REG_NAMED
1150#undef MAYBE_ADD_GREG
1151
1152 /* Commit the register update. */
1153 pFrame->cSureRegs = cRegs;
1154 }
1155 }
1156 }
1157 }
1158
1159 RT_NOREF(pUVM, pVMM, pvData, idCpu, hAs, pInitialCtx, puScratch);
1160 return VINF_SUCCESS;
1161}
1162
1163
1164/**
1165 * @copydoc DBGFOSREG::pfnQueryInterface
1166 */
1167static DECLCALLBACK(void *) dbgDiggerWinNtQueryInterface(PUVM pUVM, PCVMMR3VTABLE pVMM, void *pvData, DBGFOSINTERFACE enmIf)
1168{
1169 RT_NOREF(pUVM, pVMM);
1170 PDBGDIGGERWINNT pThis = (PDBGDIGGERWINNT)pvData;
1171
1172 switch (enmIf)
1173 {
1174 case DBGFOSINTERFACE_WINNT:
1175 return &pThis->IWinNt;
1176 default:
1177 return NULL;
1178 }
1179}
1180
1181
1182/**
1183 * @copydoc DBGFOSREG::pfnQueryVersion
1184 */
1185static DECLCALLBACK(int) dbgDiggerWinNtQueryVersion(PUVM pUVM, PCVMMR3VTABLE pVMM, void *pvData,
1186 char *pszVersion, size_t cchVersion)
1187{
1188 RT_NOREF(pUVM, pVMM);
1189 PDBGDIGGERWINNT pThis = (PDBGDIGGERWINNT)pvData;
1190 Assert(pThis->fValid);
1191
1192 const char *pszNtProductType;
1193 switch (pThis->NtProductType)
1194 {
1195 case kNtProductType_WinNt: pszNtProductType = "-WinNT"; break;
1196 case kNtProductType_LanManNt: pszNtProductType = "-LanManNT"; break;
1197 case kNtProductType_Server: pszNtProductType = "-Server"; break;
1198 default: pszNtProductType = ""; break;
1199 }
1200
1201 RTStrPrintf(pszVersion, cchVersion, "%u.%u-%s%s (BuildNumber %u)", pThis->NtMajorVersion, pThis->NtMinorVersion,
1202 pThis->f32Bit ? "x86" : "AMD64", pszNtProductType, pThis->NtBuildNumber);
1203 return VINF_SUCCESS;
1204}
1205
1206
1207/**
1208 * @copydoc DBGFOSREG::pfnTerm
1209 */
1210static DECLCALLBACK(void) dbgDiggerWinNtTerm(PUVM pUVM, PCVMMR3VTABLE pVMM, void *pvData)
1211{
1212 RT_NOREF1(pUVM);
1213 PDBGDIGGERWINNT pThis = (PDBGDIGGERWINNT)pvData;
1214 Assert(pThis->fValid);
1215
1216#ifdef VBOX_DEBUGGER_WITH_WIN_DBG_PRINT_HOOKING
1217 if (pThis->hBpDbgPrint != NIL_DBGFBP)
1218 {
1219 int rc = DBGFR3BpClear(pUVM, pThis->hBpDbgPrint);
1220 AssertRC(rc);
1221 pThis->hBpDbgPrint = NIL_DBGFBP;
1222 }
1223
1224 if (pThis->hBpOwnerDbgPrint != NIL_DBGFBPOWNER)
1225 {
1226 int rc = DBGFR3BpOwnerDestroy(pUVM, pThis->hBpOwnerDbgPrint);
1227 AssertRC(rc);
1228 pThis->hBpOwnerDbgPrint = NIL_DBGFBPOWNER;
1229 }
1230#endif
1231
1232 /*
1233 * As long as we're using our private LDR reader implementation,
1234 * we must unlink and ditch the modules we created.
1235 */
1236 RTDBGAS hDbgAs = pVMM->pfnDBGFR3AsResolveAndRetain(pUVM, DBGF_AS_KERNEL);
1237 if (hDbgAs != NIL_RTDBGAS)
1238 {
1239 uint32_t iMod = RTDbgAsModuleCount(hDbgAs);
1240 while (iMod-- > 0)
1241 {
1242 RTDBGMOD hMod = RTDbgAsModuleByIndex(hDbgAs, iMod);
1243 if (hMod != NIL_RTDBGMOD)
1244 {
1245 if (RTDbgModGetTag(hMod) == DIG_WINNT_MOD_TAG)
1246 {
1247 int rc = RTDbgAsModuleUnlink(hDbgAs, hMod);
1248 AssertRC(rc);
1249 }
1250 RTDbgModRelease(hMod);
1251 }
1252 }
1253 RTDbgAsRelease(hDbgAs);
1254 }
1255
1256 if (pThis->paKpcrAddr)
1257 RTMemFree(pThis->paKpcrAddr);
1258 /* pThis->paKpcrbAddr comes from the same allocation as pThis->paKpcrAddr. */
1259
1260 pThis->paKpcrAddr = NULL;
1261 pThis->paKpcrbAddr = NULL;
1262
1263 pThis->fValid = false;
1264}
1265
1266
1267/**
1268 * @copydoc DBGFOSREG::pfnRefresh
1269 */
1270static DECLCALLBACK(int) dbgDiggerWinNtRefresh(PUVM pUVM, PCVMMR3VTABLE pVMM, void *pvData)
1271{
1272 PDBGDIGGERWINNT pThis = (PDBGDIGGERWINNT)pvData;
1273 NOREF(pThis);
1274 Assert(pThis->fValid);
1275
1276 /*
1277 * For now we'll flush and reload everything.
1278 */
1279 dbgDiggerWinNtTerm(pUVM, pVMM, pvData);
1280
1281 return dbgDiggerWinNtInit(pUVM, pVMM, pvData);
1282}
1283
1284
1285/**
1286 * @copydoc DBGFOSREG::pfnInit
1287 */
1288static DECLCALLBACK(int) dbgDiggerWinNtInit(PUVM pUVM, PCVMMR3VTABLE pVMM, void *pvData)
1289{
1290 PDBGDIGGERWINNT pThis = (PDBGDIGGERWINNT)pvData;
1291 Assert(!pThis->fValid);
1292
1293 union
1294 {
1295 uint8_t au8[0x2000];
1296 RTUTF16 wsz[0x2000/2];
1297 NTKUSERSHAREDDATA UserSharedData;
1298 } u;
1299 DBGFADDRESS Addr;
1300 int rc;
1301
1302 /*
1303 * Figure the NT version.
1304 */
1305 pVMM->pfnDBGFR3AddrFromFlat(pUVM, &Addr, pThis->f32Bit ? NTKUSERSHAREDDATA_WINNT32 : NTKUSERSHAREDDATA_WINNT64);
1306 rc = pVMM->pfnDBGFR3MemRead(pUVM, 0 /*idCpu*/, &Addr, &u, PAGE_SIZE);
1307 if (RT_SUCCESS(rc))
1308 {
1309 pThis->NtProductType = u.UserSharedData.ProductTypeIsValid && u.UserSharedData.NtProductType <= kNtProductType_Server
1310 ? (NTPRODUCTTYPE)u.UserSharedData.NtProductType
1311 : kNtProductType_Invalid;
1312 pThis->NtMajorVersion = u.UserSharedData.NtMajorVersion;
1313 pThis->NtMinorVersion = u.UserSharedData.NtMinorVersion;
1314 pThis->NtBuildNumber = u.UserSharedData.NtBuildNumber;
1315 }
1316 else if (pThis->fNt31)
1317 {
1318 pThis->NtProductType = kNtProductType_WinNt;
1319 pThis->NtMajorVersion = 3;
1320 pThis->NtMinorVersion = 1;
1321 pThis->NtBuildNumber = 0;
1322 }
1323 else
1324 {
1325 Log(("DigWinNt: Error reading KUSER_SHARED_DATA: %Rrc\n", rc));
1326 return rc;
1327 }
1328
1329 /*
1330 * Dig out the module chain.
1331 */
1332 DBGFADDRESS AddrPrev = pThis->PsLoadedModuleListAddr;
1333 Addr = pThis->KernelMteAddr;
1334 do
1335 {
1336 /* Read the validate the MTE. */
1337 NTMTE Mte;
1338 rc = pVMM->pfnDBGFR3MemRead(pUVM, 0 /*idCpu*/, &Addr, &Mte, pThis->f32Bit ? sizeof(Mte.vX_32) : sizeof(Mte.vX_64));
1339 if (RT_FAILURE(rc))
1340 break;
1341 if (WINNT_UNION(pThis, &Mte, InLoadOrderLinks.Blink) != AddrPrev.FlatPtr)
1342 {
1343 Log(("DigWinNt: Bad Mte At %RGv - backpointer\n", Addr.FlatPtr));
1344 break;
1345 }
1346 if (!WINNT_VALID_ADDRESS(pThis, WINNT_UNION(pThis, &Mte, InLoadOrderLinks.Flink)) )
1347 {
1348 Log(("DigWinNt: Bad Mte at %RGv - forward pointer\n", Addr.FlatPtr));
1349 break;
1350 }
1351 if (!WINNT_VALID_ADDRESS(pThis, WINNT_UNION(pThis, &Mte, BaseDllName.Buffer)))
1352 {
1353 Log(("DigWinNt: Bad Mte at %RGv - BaseDllName=%llx\n", Addr.FlatPtr, WINNT_UNION(pThis, &Mte, BaseDllName.Buffer)));
1354 break;
1355 }
1356 if (!WINNT_VALID_ADDRESS(pThis, WINNT_UNION(pThis, &Mte, FullDllName.Buffer)))
1357 {
1358 Log(("DigWinNt: Bad Mte at %RGv - FullDllName=%llx\n", Addr.FlatPtr, WINNT_UNION(pThis, &Mte, FullDllName.Buffer)));
1359 break;
1360 }
1361 if (!WINNT_VALID_ADDRESS(pThis, WINNT_UNION(pThis, &Mte, DllBase)))
1362 {
1363 Log(("DigWinNt: Bad Mte at %RGv - DllBase=%llx\n", Addr.FlatPtr, WINNT_UNION(pThis, &Mte, DllBase) ));
1364 break;
1365 }
1366
1367 uint32_t const cbImageMte = !pThis->fNt31 ? WINNT_UNION(pThis, &Mte, SizeOfImage) : 0;
1368 if ( !pThis->fNt31
1369 && ( cbImageMte > _256M
1370 || WINNT_UNION(pThis, &Mte, EntryPoint) - WINNT_UNION(pThis, &Mte, DllBase) > cbImageMte) )
1371 {
1372 Log(("DigWinNt: Bad Mte at %RGv - EntryPoint=%llx SizeOfImage=%x DllBase=%llx\n",
1373 Addr.FlatPtr, WINNT_UNION(pThis, &Mte, EntryPoint), cbImageMte, WINNT_UNION(pThis, &Mte, DllBase)));
1374 break;
1375 }
1376
1377 /* Read the full name. */
1378 DBGFADDRESS AddrName;
1379 pVMM->pfnDBGFR3AddrFromFlat(pUVM, &AddrName, WINNT_UNION(pThis, &Mte, FullDllName.Buffer));
1380 uint16_t cbName = WINNT_UNION(pThis, &Mte, FullDllName.Length);
1381 if (cbName < sizeof(u))
1382 rc = pVMM->pfnDBGFR3MemRead(pUVM, 0 /*idCpu*/, &AddrName, &u, cbName);
1383 else
1384 rc = VERR_OUT_OF_RANGE;
1385 if (RT_FAILURE(rc))
1386 {
1387 pVMM->pfnDBGFR3AddrFromFlat(pUVM, &AddrName, WINNT_UNION(pThis, &Mte, BaseDllName.Buffer));
1388 cbName = WINNT_UNION(pThis, &Mte, BaseDllName.Length);
1389 if (cbName < sizeof(u))
1390 rc = pVMM->pfnDBGFR3MemRead(pUVM, 0 /*idCpu*/, &AddrName, &u, cbName);
1391 else
1392 rc = VERR_OUT_OF_RANGE;
1393 }
1394 if (RT_SUCCESS(rc))
1395 {
1396 u.wsz[cbName / 2] = '\0';
1397
1398 char *pszFilename;
1399 rc = RTUtf16ToUtf8(u.wsz, &pszFilename);
1400 if (RT_SUCCESS(rc))
1401 {
1402 char szModName[128];
1403 const char *pszModName = dbgDiggerWintNtFilenameToModuleName(pszFilename, szModName, sizeof(szModName));
1404
1405 /* Read the start of the PE image and pass it along to a worker. */
1406 DBGFADDRESS ImageAddr;
1407 pVMM->pfnDBGFR3AddrFromFlat(pUVM, &ImageAddr, WINNT_UNION(pThis, &Mte, DllBase));
1408 dbgDiggerWinNtProcessImage(pThis, pUVM, pVMM, pszModName, pszFilename, &ImageAddr, cbImageMte);
1409 RTStrFree(pszFilename);
1410 }
1411 }
1412
1413 /* next */
1414 AddrPrev = Addr;
1415 pVMM->pfnDBGFR3AddrFromFlat(pUVM, &Addr, WINNT_UNION(pThis, &Mte, InLoadOrderLinks.Flink));
1416 } while ( Addr.FlatPtr != pThis->KernelMteAddr.FlatPtr
1417 && Addr.FlatPtr != pThis->PsLoadedModuleListAddr.FlatPtr);
1418
1419 /* Try resolving the KPCR and KPCRB addresses for each vCPU. */
1420 dbgDiggerWinNtResolveKpcr(pThis, pUVM, pVMM);
1421
1422#ifdef VBOX_DEBUGGER_WITH_WIN_DBG_PRINT_HOOKING
1423 /* Try to hook into the DbgPrint/vDbgPrint... code so we can gather information from the drivers. */
1424 dbgDiggerWinNtDbgPrintHook(pThis, pUVM);
1425#endif
1426
1427 pThis->fValid = true;
1428 return VINF_SUCCESS;
1429}
1430
1431
1432/**
1433 * @copydoc DBGFOSREG::pfnProbe
1434 */
1435static DECLCALLBACK(bool) dbgDiggerWinNtProbe(PUVM pUVM, PCVMMR3VTABLE pVMM, void *pvData)
1436{
1437 PDBGDIGGERWINNT pThis = (PDBGDIGGERWINNT)pvData;
1438 DBGFADDRESS Addr;
1439 union
1440 {
1441 uint8_t au8[8192];
1442 uint16_t au16[8192/2];
1443 uint32_t au32[8192/4];
1444 IMAGE_DOS_HEADER MzHdr;
1445 RTUTF16 wsz[8192/2];
1446 X86DESCGATE a32Gates[X86_XCPT_PF + 1];
1447 X86DESC64GATE a64Gates[X86_XCPT_PF + 1];
1448 } u;
1449
1450 union
1451 {
1452 NTMTE32 v32;
1453 NTMTE64 v64;
1454 } uMte, uMte2, uMte3;
1455
1456 /*
1457 * NT only runs in protected or long mode.
1458 */
1459 CPUMMODE const enmMode = pVMM->pfnDBGFR3CpuGetMode(pUVM, 0 /*idCpu*/);
1460 if (enmMode != CPUMMODE_PROTECTED && enmMode != CPUMMODE_LONG)
1461 return false;
1462 bool const f64Bit = enmMode == CPUMMODE_LONG;
1463 uint64_t const uStart = f64Bit ? UINT64_C(0xffff080000000000) : UINT32_C(0x80001000);
1464 uint64_t const uEnd = f64Bit ? UINT64_C(0xffffffffffff0000) : UINT32_C(0xffff0000);
1465
1466 /*
1467 * To approximately locate the kernel we examine the IDTR handlers.
1468 *
1469 * The exception/trap/fault handlers are all in NT kernel image, we pick
1470 * KiPageFault here.
1471 */
1472 uint64_t uIdtrBase = 0;
1473 uint16_t uIdtrLimit = 0;
1474 int rc = pVMM->pfnDBGFR3RegCpuQueryXdtr(pUVM, 0, DBGFREG_IDTR, &uIdtrBase, &uIdtrLimit);
1475 AssertRCReturn(rc, false);
1476
1477 const uint16_t cbMinIdtr = (X86_XCPT_PF + 1) * (f64Bit ? sizeof(X86DESC64GATE) : sizeof(X86DESCGATE));
1478 if (uIdtrLimit < cbMinIdtr)
1479 return false;
1480
1481 rc = pVMM->pfnDBGFR3MemRead(pUVM, 0 /*idCpu*/, pVMM->pfnDBGFR3AddrFromFlat(pUVM, &Addr, uIdtrBase), &u, cbMinIdtr);
1482 if (RT_FAILURE(rc))
1483 return false;
1484
1485 uint64_t uKrnlStart = uStart;
1486 uint64_t uKrnlEnd = uEnd;
1487 if (f64Bit)
1488 {
1489 uint64_t uHandler = u.a64Gates[X86_XCPT_PF].u16OffsetLow
1490 | ((uint32_t)u.a64Gates[X86_XCPT_PF].u16OffsetHigh << 16)
1491 | ((uint64_t)u.a64Gates[X86_XCPT_PF].u32OffsetTop << 32);
1492 if (uHandler < uStart || uHandler > uEnd)
1493 return false;
1494 uKrnlStart = (uHandler & ~(uint64_t)_4M) - _512M;
1495 uKrnlEnd = (uHandler + (uint64_t)_4M) & ~(uint64_t)_4M;
1496 }
1497 else
1498 {
1499 uint32_t uHandler = RT_MAKE_U32(u.a32Gates[X86_XCPT_PF].u16OffsetLow, u.a32Gates[X86_XCPT_PF].u16OffsetHigh);
1500 if (uHandler < uStart || uHandler > uEnd)
1501 return false;
1502 uKrnlStart = (uHandler & ~(uint64_t)_4M) - _64M;
1503 uKrnlEnd = (uHandler + (uint64_t)_4M) & ~(uint64_t)_4M;
1504 }
1505
1506 /*
1507 * Look for the PAGELK section name that seems to be a part of all kernels.
1508 * Then try find the module table entry for it. Since it's the first entry
1509 * in the PsLoadedModuleList we can easily validate the list head and report
1510 * success.
1511 *
1512 * Note! We ASSUME the section name is 8 byte aligned.
1513 */
1514 DBGFADDRESS KernelAddr;
1515 for (pVMM->pfnDBGFR3AddrFromFlat(pUVM, &KernelAddr, uKrnlStart);
1516 KernelAddr.FlatPtr < uKrnlEnd;
1517 KernelAddr.FlatPtr += PAGE_SIZE)
1518 {
1519 bool fNt31 = false;
1520 DBGFADDRESS const RetryAddress = KernelAddr;
1521 rc = pVMM->pfnDBGFR3MemScan(pUVM, 0 /*idCpu*/, &KernelAddr, uEnd - KernelAddr.FlatPtr,
1522 8, "PAGELK\0", sizeof("PAGELK\0"), &KernelAddr);
1523 if ( rc == VERR_DBGF_MEM_NOT_FOUND
1524 && enmMode != CPUMMODE_LONG)
1525 {
1526 /* NT3.1 didn't have a PAGELK section, so look for _TEXT instead. The
1527 following VirtualSize is zero, so check for that too. */
1528 rc = pVMM->pfnDBGFR3MemScan(pUVM, 0 /*idCpu*/, &RetryAddress, uEnd - RetryAddress.FlatPtr,
1529 8, "_TEXT\0\0\0\0\0\0", sizeof("_TEXT\0\0\0\0\0\0"), &KernelAddr);
1530 fNt31 = true;
1531 }
1532 if (RT_FAILURE(rc))
1533 break;
1534 pVMM->pfnDBGFR3AddrSub(&KernelAddr, KernelAddr.FlatPtr & PAGE_OFFSET_MASK);
1535
1536 /* MZ + PE header. */
1537 rc = pVMM->pfnDBGFR3MemRead(pUVM, 0 /*idCpu*/, &KernelAddr, &u, sizeof(u));
1538 if ( RT_SUCCESS(rc)
1539 && u.MzHdr.e_magic == IMAGE_DOS_SIGNATURE
1540 && !(u.MzHdr.e_lfanew & 0x7)
1541 && u.MzHdr.e_lfanew >= 0x080
1542 && u.MzHdr.e_lfanew <= 0x400) /* W8 is at 0x288*/
1543 {
1544 if (enmMode != CPUMMODE_LONG)
1545 {
1546 IMAGE_NT_HEADERS32 const *pHdrs = (IMAGE_NT_HEADERS32 const *)&u.au8[u.MzHdr.e_lfanew];
1547 if ( pHdrs->Signature == IMAGE_NT_SIGNATURE
1548 && pHdrs->FileHeader.Machine == IMAGE_FILE_MACHINE_I386
1549 && pHdrs->FileHeader.SizeOfOptionalHeader == sizeof(pHdrs->OptionalHeader)
1550 && pHdrs->FileHeader.NumberOfSections >= 10 /* the kernel has lots */
1551 && (pHdrs->FileHeader.Characteristics & (IMAGE_FILE_EXECUTABLE_IMAGE | IMAGE_FILE_DLL)) == IMAGE_FILE_EXECUTABLE_IMAGE
1552 && pHdrs->OptionalHeader.Magic == IMAGE_NT_OPTIONAL_HDR32_MAGIC
1553 && pHdrs->OptionalHeader.NumberOfRvaAndSizes == IMAGE_NUMBEROF_DIRECTORY_ENTRIES
1554 )
1555 {
1556 /* Find the MTE. */
1557 RT_ZERO(uMte);
1558 uMte.v32.DllBase = KernelAddr.FlatPtr;
1559 uMte.v32.EntryPoint = KernelAddr.FlatPtr + pHdrs->OptionalHeader.AddressOfEntryPoint;
1560 uMte.v32.SizeOfImage = !fNt31 ? pHdrs->OptionalHeader.SizeOfImage : 0; /* NT 3.1 didn't set the size. */
1561 DBGFADDRESS HitAddr;
1562 rc = pVMM->pfnDBGFR3MemScan(pUVM, 0 /*idCpu*/, &KernelAddr, uEnd - KernelAddr.FlatPtr,
1563 4 /*align*/, &uMte.v32.DllBase, 3 * sizeof(uint32_t), &HitAddr);
1564 while (RT_SUCCESS(rc))
1565 {
1566 /* check the name. */
1567 DBGFADDRESS MteAddr = HitAddr;
1568 rc = pVMM->pfnDBGFR3MemRead(pUVM, 0 /*idCpu*/,
1569 pVMM->pfnDBGFR3AddrSub(&MteAddr, RT_OFFSETOF(NTMTE32, DllBase)),
1570 &uMte2.v32, sizeof(uMte2.v32));
1571 if ( RT_SUCCESS(rc)
1572 && uMte2.v32.DllBase == uMte.v32.DllBase
1573 && uMte2.v32.EntryPoint == uMte.v32.EntryPoint
1574 && uMte2.v32.SizeOfImage == uMte.v32.SizeOfImage
1575 && WINNT32_VALID_ADDRESS(uMte2.v32.InLoadOrderLinks.Flink)
1576 && WINNT32_VALID_ADDRESS(uMte2.v32.BaseDllName.Buffer)
1577 && WINNT32_VALID_ADDRESS(uMte2.v32.FullDllName.Buffer)
1578 && uMte2.v32.BaseDllName.Length <= 128
1579 && uMte2.v32.FullDllName.Length <= 260
1580 )
1581 {
1582 rc = pVMM->pfnDBGFR3MemRead(pUVM, 0 /*idCpu*/,
1583 pVMM->pfnDBGFR3AddrFromFlat(pUVM, &Addr, uMte2.v32.BaseDllName.Buffer),
1584 u.wsz, uMte2.v32.BaseDllName.Length);
1585 u.wsz[uMte2.v32.BaseDllName.Length / 2] = '\0';
1586 if ( RT_SUCCESS(rc)
1587 && ( !RTUtf16ICmp(u.wsz, g_wszKernelNames[0])
1588 /* || !RTUtf16ICmp(u.wsz, g_wszKernelNames[1]) */
1589 )
1590 )
1591 {
1592 rc = pVMM->pfnDBGFR3MemRead(pUVM, 0 /*idCpu*/,
1593 pVMM->pfnDBGFR3AddrFromFlat(pUVM, &Addr,
1594 uMte2.v32.InLoadOrderLinks.Blink),
1595 &uMte3.v32, RT_SIZEOFMEMB(NTMTE32, InLoadOrderLinks));
1596 if ( RT_SUCCESS(rc)
1597 && uMte3.v32.InLoadOrderLinks.Flink == MteAddr.FlatPtr
1598 && WINNT32_VALID_ADDRESS(uMte3.v32.InLoadOrderLinks.Blink) )
1599 {
1600 Log(("DigWinNt: MteAddr=%RGv KernelAddr=%RGv SizeOfImage=%x &PsLoadedModuleList=%RGv (32-bit)\n",
1601 MteAddr.FlatPtr, KernelAddr.FlatPtr, uMte2.v32.SizeOfImage, Addr.FlatPtr));
1602 pThis->KernelAddr = KernelAddr;
1603 pThis->KernelMteAddr = MteAddr;
1604 pThis->PsLoadedModuleListAddr = Addr;
1605 pThis->f32Bit = true;
1606 pThis->fNt31 = fNt31;
1607 return true;
1608 }
1609 }
1610 else if (RT_SUCCESS(rc))
1611 {
1612 Log2(("DigWinNt: Wrong module: MteAddr=%RGv ImageAddr=%RGv SizeOfImage=%#x '%ls'\n",
1613 MteAddr.FlatPtr, KernelAddr.FlatPtr, uMte2.v32.SizeOfImage, u.wsz));
1614 break; /* Not NT kernel */
1615 }
1616 }
1617
1618 /* next */
1619 pVMM->pfnDBGFR3AddrAdd(&HitAddr, 4);
1620 if (HitAddr.FlatPtr < uEnd)
1621 rc = pVMM->pfnDBGFR3MemScan(pUVM, 0 /*idCpu*/, &HitAddr, uEnd - HitAddr.FlatPtr,
1622 4 /*align*/, &uMte.v32.DllBase, 3 * sizeof(uint32_t), &HitAddr);
1623 else
1624 rc = VERR_DBGF_MEM_NOT_FOUND;
1625 }
1626 }
1627 }
1628 else
1629 {
1630 IMAGE_NT_HEADERS64 const *pHdrs = (IMAGE_NT_HEADERS64 const *)&u.au8[u.MzHdr.e_lfanew];
1631 if ( pHdrs->Signature == IMAGE_NT_SIGNATURE
1632 && pHdrs->FileHeader.Machine == IMAGE_FILE_MACHINE_AMD64
1633 && pHdrs->FileHeader.SizeOfOptionalHeader == sizeof(pHdrs->OptionalHeader)
1634 && pHdrs->FileHeader.NumberOfSections >= 10 /* the kernel has lots */
1635 && (pHdrs->FileHeader.Characteristics & (IMAGE_FILE_EXECUTABLE_IMAGE | IMAGE_FILE_DLL))
1636 == IMAGE_FILE_EXECUTABLE_IMAGE
1637 && pHdrs->OptionalHeader.Magic == IMAGE_NT_OPTIONAL_HDR64_MAGIC
1638 && pHdrs->OptionalHeader.NumberOfRvaAndSizes == IMAGE_NUMBEROF_DIRECTORY_ENTRIES
1639 )
1640 {
1641 /* Find the MTE. */
1642 RT_ZERO(uMte.v64);
1643 uMte.v64.DllBase = KernelAddr.FlatPtr;
1644 uMte.v64.EntryPoint = KernelAddr.FlatPtr + pHdrs->OptionalHeader.AddressOfEntryPoint;
1645 uMte.v64.SizeOfImage = pHdrs->OptionalHeader.SizeOfImage;
1646 DBGFADDRESS ScanAddr;
1647 DBGFADDRESS HitAddr;
1648 rc = pVMM->pfnDBGFR3MemScan(pUVM, 0 /*idCpu*/, pVMM->pfnDBGFR3AddrFromFlat(pUVM, &ScanAddr, uStart),
1649 uEnd - uStart, 8 /*align*/, &uMte.v64.DllBase, 5 * sizeof(uint32_t), &HitAddr);
1650 while (RT_SUCCESS(rc))
1651 {
1652 /* Read the start of the MTE and check some basic members. */
1653 DBGFADDRESS MteAddr = HitAddr;
1654 rc = pVMM->pfnDBGFR3MemRead(pUVM, 0 /*idCpu*/,
1655 pVMM->pfnDBGFR3AddrSub(&MteAddr, RT_OFFSETOF(NTMTE64, DllBase)),
1656 &uMte2.v64, sizeof(uMte2.v64));
1657 if ( RT_SUCCESS(rc)
1658 && uMte2.v64.DllBase == uMte.v64.DllBase
1659 && uMte2.v64.EntryPoint == uMte.v64.EntryPoint
1660 && uMte2.v64.SizeOfImage == uMte.v64.SizeOfImage
1661 && WINNT64_VALID_ADDRESS(uMte2.v64.InLoadOrderLinks.Flink)
1662 && WINNT64_VALID_ADDRESS(uMte2.v64.BaseDllName.Buffer)
1663 && WINNT64_VALID_ADDRESS(uMte2.v64.FullDllName.Buffer)
1664 && uMte2.v64.BaseDllName.Length <= 128
1665 && uMte2.v64.FullDllName.Length <= 260
1666 )
1667 {
1668 /* Try read the base name and compare with known NT kernel names. */
1669 rc = pVMM->pfnDBGFR3MemRead(pUVM, 0 /*idCpu*/,
1670 pVMM->pfnDBGFR3AddrFromFlat(pUVM, &Addr, uMte2.v64.BaseDllName.Buffer),
1671 u.wsz, uMte2.v64.BaseDllName.Length);
1672 u.wsz[uMte2.v64.BaseDllName.Length / 2] = '\0';
1673 if ( RT_SUCCESS(rc)
1674 && ( !RTUtf16ICmp(u.wsz, g_wszKernelNames[0])
1675 /* || !RTUtf16ICmp(u.wsz, g_wszKernelNames[1]) */
1676 )
1677 )
1678 {
1679 /* Read the link entry of the previous entry in the list and check that its
1680 forward pointer points at the MTE we've found. */
1681 rc = pVMM->pfnDBGFR3MemRead(pUVM, 0 /*idCpu*/,
1682 pVMM->pfnDBGFR3AddrFromFlat(pUVM, &Addr,
1683 uMte2.v64.InLoadOrderLinks.Blink),
1684 &uMte3.v64, RT_SIZEOFMEMB(NTMTE64, InLoadOrderLinks));
1685 if ( RT_SUCCESS(rc)
1686 && uMte3.v64.InLoadOrderLinks.Flink == MteAddr.FlatPtr
1687 && WINNT64_VALID_ADDRESS(uMte3.v64.InLoadOrderLinks.Blink) )
1688 {
1689 Log(("DigWinNt: MteAddr=%RGv KernelAddr=%RGv SizeOfImage=%x &PsLoadedModuleList=%RGv (32-bit)\n",
1690 MteAddr.FlatPtr, KernelAddr.FlatPtr, uMte2.v64.SizeOfImage, Addr.FlatPtr));
1691 pThis->KernelAddr = KernelAddr;
1692 pThis->KernelMteAddr = MteAddr;
1693 pThis->PsLoadedModuleListAddr = Addr;
1694 pThis->f32Bit = false;
1695 pThis->fNt31 = false;
1696 return true;
1697 }
1698 }
1699 else if (RT_SUCCESS(rc))
1700 {
1701 Log2(("DigWinNt: Wrong module: MteAddr=%RGv ImageAddr=%RGv SizeOfImage=%#x '%ls'\n",
1702 MteAddr.FlatPtr, KernelAddr.FlatPtr, uMte2.v64.SizeOfImage, u.wsz));
1703 break; /* Not NT kernel */
1704 }
1705 }
1706
1707 /* next */
1708 pVMM->pfnDBGFR3AddrAdd(&HitAddr, 8);
1709 if (HitAddr.FlatPtr < uEnd)
1710 rc = pVMM->pfnDBGFR3MemScan(pUVM, 0 /*idCpu*/, &HitAddr, uEnd - HitAddr.FlatPtr,
1711 8 /*align*/, &uMte.v64.DllBase, 3 * sizeof(uint32_t), &HitAddr);
1712 else
1713 rc = VERR_DBGF_MEM_NOT_FOUND;
1714 }
1715 }
1716 }
1717 }
1718 }
1719 return false;
1720}
1721
1722
1723/**
1724 * @copydoc DBGFOSREG::pfnDestruct
1725 */
1726static DECLCALLBACK(void) dbgDiggerWinNtDestruct(PUVM pUVM, PCVMMR3VTABLE pVMM, void *pvData)
1727{
1728 RT_NOREF(pUVM, pVMM, pvData);
1729}
1730
1731
1732/**
1733 * @copydoc DBGFOSREG::pfnConstruct
1734 */
1735static DECLCALLBACK(int) dbgDiggerWinNtConstruct(PUVM pUVM, PCVMMR3VTABLE pVMM, void *pvData)
1736{
1737 RT_NOREF(pUVM, pVMM);
1738 PDBGDIGGERWINNT pThis = (PDBGDIGGERWINNT)pvData;
1739 pThis->fValid = false;
1740 pThis->f32Bit = false;
1741 pThis->enmVer = DBGDIGGERWINNTVER_UNKNOWN;
1742
1743 pThis->IWinNt.u32Magic = DBGFOSIWINNT_MAGIC;
1744 pThis->IWinNt.pfnQueryVersion = dbgDiggerWinNtIWinNt_QueryVersion;
1745 pThis->IWinNt.pfnQueryKernelPtrs = dbgDiggerWinNtIWinNt_QueryKernelPtrs;
1746 pThis->IWinNt.pfnQueryKpcrForVCpu = dbgDiggerWinNtIWinNt_QueryKpcrForVCpu;
1747 pThis->IWinNt.pfnQueryCurThrdForVCpu = dbgDiggerWinNtIWinNt_QueryCurThrdForVCpu;
1748 pThis->IWinNt.u32EndMagic = DBGFOSIWINNT_MAGIC;
1749
1750#ifdef VBOX_DEBUGGER_WITH_WIN_DBG_PRINT_HOOKING
1751 pThis->hBpDbgPrint = NIL_DBGFBP;
1752 pThis->hBpOwnerDbgPrint = NIL_DBGFBPOWNER;
1753#endif
1754
1755 return VINF_SUCCESS;
1756}
1757
1758
1759const DBGFOSREG g_DBGDiggerWinNt =
1760{
1761 /* .u32Magic = */ DBGFOSREG_MAGIC,
1762 /* .fFlags = */ 0,
1763 /* .cbData = */ sizeof(DBGDIGGERWINNT),
1764 /* .szName = */ "WinNT",
1765 /* .pfnConstruct = */ dbgDiggerWinNtConstruct,
1766 /* .pfnDestruct = */ dbgDiggerWinNtDestruct,
1767 /* .pfnProbe = */ dbgDiggerWinNtProbe,
1768 /* .pfnInit = */ dbgDiggerWinNtInit,
1769 /* .pfnRefresh = */ dbgDiggerWinNtRefresh,
1770 /* .pfnTerm = */ dbgDiggerWinNtTerm,
1771 /* .pfnQueryVersion = */ dbgDiggerWinNtQueryVersion,
1772 /* .pfnQueryInterface = */ dbgDiggerWinNtQueryInterface,
1773 /* .pfnStackUnwindAssist = */ dbgDiggerWinNtStackUnwindAssist,
1774 /* .u32EndMagic = */ DBGFOSREG_MAGIC
1775};
1776
Note: See TracBrowser for help on using the repository browser.

© 2024 Oracle Support Privacy / Do Not Sell My Info Terms of Use Trademark Policy Automated Access Etiquette