VirtualBox

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

Last change on this file since 91703 was 86164, checked in by vboxsync, 4 years ago

Debugger/DBGPlugInWinNt: Add KPCR/KPCRB extraction for 32bit Windows [build fix]

  • Property svn:eol-style set to native
  • Property svn:keywords set to Author Date Id Revision
File size: 59.1 KB
Line 
1/* $Id: DBGPlugInWinNt.cpp 86164 2020-09-18 07:25:03Z vboxsync $ */
2/** @file
3 * DBGPlugInWindows - Debugger and Guest OS Digger Plugin For Windows NT.
4 */
5
6/*
7 * Copyright (C) 2009-2020 Oracle Corporation
8 *
9 * This file is part of VirtualBox Open Source Edition (OSE), as
10 * available from http://www.virtualbox.org. This file is free software;
11 * you can redistribute it and/or modify it under the terms of the GNU
12 * General Public License (GPL) as published by the Free Software
13 * Foundation, in version 2 as it comes in the "COPYING" file of the
14 * VirtualBox OSE distribution. VirtualBox OSE is distributed in the
15 * hope that it will be useful, but WITHOUT ANY WARRANTY of any kind.
16 */
17
18
19/*********************************************************************************************************************************
20* Header Files *
21*********************************************************************************************************************************/
22#define LOG_GROUP LOG_GROUP_DBGF /// @todo add new log group.
23#include "DBGPlugIns.h"
24#include <VBox/vmm/dbgf.h>
25#include <VBox/vmm/cpumctx.h>
26#include <VBox/vmm/mm.h>
27#include <VBox/err.h>
28#include <VBox/param.h>
29#include <iprt/ctype.h>
30#include <iprt/ldr.h>
31#include <iprt/mem.h>
32#include <iprt/path.h>
33#include <iprt/stream.h>
34#include <iprt/string.h>
35#include <iprt/utf16.h>
36#include <iprt/formats/pecoff.h>
37#include <iprt/formats/mz.h>
38#include <iprt/nt/nt-structures.h>
39
40
41/*********************************************************************************************************************************
42* Structures and Typedefs *
43*********************************************************************************************************************************/
44
45/** @name Internal WinNT structures
46 * @{ */
47/**
48 * PsLoadedModuleList entry for 32-bit NT aka LDR_DATA_TABLE_ENTRY.
49 * Tested with XP.
50 */
51typedef struct NTMTE32
52{
53 struct
54 {
55 uint32_t Flink;
56 uint32_t Blink;
57 } InLoadOrderLinks,
58 InMemoryOrderModuleList,
59 InInitializationOrderModuleList;
60 uint32_t DllBase;
61 uint32_t EntryPoint;
62 /** @note This field is not a size in NT 3.1. It's NULL for images loaded by the
63 * boot loader, for other images it looks like some kind of pointer. */
64 uint32_t SizeOfImage;
65 struct
66 {
67 uint16_t Length;
68 uint16_t MaximumLength;
69 uint32_t Buffer;
70 } FullDllName,
71 BaseDllName;
72 uint32_t Flags;
73 uint16_t LoadCount;
74 uint16_t TlsIndex;
75 /* ... there is more ... */
76} NTMTE32;
77typedef NTMTE32 *PNTMTE32;
78
79/**
80 * PsLoadedModuleList entry for 64-bit NT aka LDR_DATA_TABLE_ENTRY.
81 */
82typedef struct NTMTE64
83{
84 struct
85 {
86 uint64_t Flink;
87 uint64_t Blink;
88 } InLoadOrderLinks, /**< 0x00 */
89 InMemoryOrderModuleList, /**< 0x10 */
90 InInitializationOrderModuleList; /**< 0x20 */
91 uint64_t DllBase; /**< 0x30 */
92 uint64_t EntryPoint; /**< 0x38 */
93 uint32_t SizeOfImage; /**< 0x40 */
94 uint32_t Alignment; /**< 0x44 */
95 struct
96 {
97 uint16_t Length; /**< 0x48,0x58 */
98 uint16_t MaximumLength; /**< 0x4a,0x5a */
99 uint32_t Alignment; /**< 0x4c,0x5c */
100 uint64_t Buffer; /**< 0x50,0x60 */
101 } FullDllName, /**< 0x48 */
102 BaseDllName; /**< 0x58 */
103 uint32_t Flags; /**< 0x68 */
104 uint16_t LoadCount; /**< 0x6c */
105 uint16_t TlsIndex; /**< 0x6e */
106 /* ... there is more ... */
107} NTMTE64;
108typedef NTMTE64 *PNTMTE64;
109
110/** MTE union. */
111typedef union NTMTE
112{
113 NTMTE32 vX_32;
114 NTMTE64 vX_64;
115} NTMTE;
116typedef NTMTE *PNTMTE;
117
118
119/**
120 * The essential bits of the KUSER_SHARED_DATA structure.
121 */
122typedef struct NTKUSERSHAREDDATA
123{
124 uint32_t TickCountLowDeprecated;
125 uint32_t TickCountMultiplier;
126 struct
127 {
128 uint32_t LowPart;
129 int32_t High1Time;
130 int32_t High2Time;
131
132 } InterruptTime,
133 SystemTime,
134 TimeZoneBias;
135 uint16_t ImageNumberLow;
136 uint16_t ImageNumberHigh;
137 RTUTF16 NtSystemRoot[260];
138 uint32_t MaxStackTraceDepth;
139 uint32_t CryptoExponent;
140 uint32_t TimeZoneId;
141 uint32_t LargePageMinimum;
142 uint32_t Reserved2[6];
143 uint32_t NtBuildNumber;
144 uint32_t NtProductType;
145 uint8_t ProductTypeIsValid;
146 uint8_t abPadding[3];
147 uint32_t NtMajorVersion;
148 uint32_t NtMinorVersion;
149 /* uint8_t ProcessorFeatures[64];
150 ...
151 */
152} NTKUSERSHAREDDATA;
153typedef NTKUSERSHAREDDATA *PNTKUSERSHAREDDATA;
154
155/** KI_USER_SHARED_DATA for i386 */
156#define NTKUSERSHAREDDATA_WINNT32 UINT32_C(0xffdf0000)
157/** KI_USER_SHARED_DATA for AMD64 */
158#define NTKUSERSHAREDDATA_WINNT64 UINT64_C(0xfffff78000000000)
159
160/** NTKUSERSHAREDDATA::NtProductType */
161typedef enum NTPRODUCTTYPE
162{
163 kNtProductType_Invalid = 0,
164 kNtProductType_WinNt = 1,
165 kNtProductType_LanManNt,
166 kNtProductType_Server
167} NTPRODUCTTYPE;
168
169
170/** NT image header union. */
171typedef union NTHDRSU
172{
173 IMAGE_NT_HEADERS32 vX_32;
174 IMAGE_NT_HEADERS64 vX_64;
175} NTHDRS;
176/** Pointer to NT image header union. */
177typedef NTHDRS *PNTHDRS;
178/** Pointer to const NT image header union. */
179typedef NTHDRS const *PCNTHDRS;
180
181
182/**
183 * NT KD version block.
184 */
185typedef struct NTKDVERSIONBLOCK
186{
187 uint16_t MajorVersion;
188 uint16_t MinorVersion;
189 uint8_t ProtocolVersion;
190 uint8_t KdSecondaryVersion;
191 uint16_t Flags;
192 uint16_t MachineType;
193 uint8_t MaxPacketType;
194 uint8_t MaxStateChange;
195 uint8_t MaxManipulate;
196 uint8_t Simulation;
197 uint16_t Unused;
198 uint64_t KernBase;
199 uint64_t PsLoadedModuleList;
200 uint64_t DebuggerDataList;
201} NTKDVERSIONBLOCK;
202/** Pointer to an NT KD version block. */
203typedef NTKDVERSIONBLOCK *PNTKDVERSIONBLOCK;
204/** Pointer to a const NT KD version block. */
205typedef const NTKDVERSIONBLOCK *PCNTKDVERSIONBLOCK;
206
207/** @} */
208
209
210
211typedef enum DBGDIGGERWINNTVER
212{
213 DBGDIGGERWINNTVER_UNKNOWN,
214 DBGDIGGERWINNTVER_3_1,
215 DBGDIGGERWINNTVER_3_5,
216 DBGDIGGERWINNTVER_4_0,
217 DBGDIGGERWINNTVER_5_0,
218 DBGDIGGERWINNTVER_5_1,
219 DBGDIGGERWINNTVER_6_0
220} DBGDIGGERWINNTVER;
221
222/**
223 * WinNT guest OS digger instance data.
224 */
225typedef struct DBGDIGGERWINNT
226{
227 /** Whether the information is valid or not.
228 * (For fending off illegal interface method calls.) */
229 bool fValid;
230 /** 32-bit (true) or 64-bit (false) */
231 bool f32Bit;
232 /** Set if NT 3.1 was detected.
233 * This implies both Misc.VirtualSize and NTMTE32::SizeOfImage are zero. */
234 bool fNt31;
235
236 /** The NT version. */
237 DBGDIGGERWINNTVER enmVer;
238 /** NTKUSERSHAREDDATA::NtProductType */
239 NTPRODUCTTYPE NtProductType;
240 /** NTKUSERSHAREDDATA::NtMajorVersion */
241 uint32_t NtMajorVersion;
242 /** NTKUSERSHAREDDATA::NtMinorVersion */
243 uint32_t NtMinorVersion;
244 /** NTKUSERSHAREDDATA::NtBuildNumber */
245 uint32_t NtBuildNumber;
246
247 /** The address of the ntoskrnl.exe image. */
248 DBGFADDRESS KernelAddr;
249 /** The address of the ntoskrnl.exe module table entry. */
250 DBGFADDRESS KernelMteAddr;
251 /** The address of PsLoadedModuleList. */
252 DBGFADDRESS PsLoadedModuleListAddr;
253
254 /** Array of detected KPCR addresses for each vCPU. */
255 PDBGFADDRESS paKpcrAddr;
256 /** Array of detected KPCRB addresses for each vCPU. */
257 PDBGFADDRESS paKpcrbAddr;
258
259 /** The Windows NT specifics interface. */
260 DBGFOSIWINNT IWinNt;
261} DBGDIGGERWINNT;
262/** Pointer to the linux guest OS digger instance data. */
263typedef DBGDIGGERWINNT *PDBGDIGGERWINNT;
264
265
266/**
267 * The WinNT digger's loader reader instance data.
268 */
269typedef struct DBGDIGGERWINNTRDR
270{
271 /** The VM handle (referenced). */
272 PUVM pUVM;
273 /** The image base. */
274 DBGFADDRESS ImageAddr;
275 /** The image size. */
276 uint32_t cbImage;
277 /** The file offset of the SizeOfImage field in the optional header if it
278 * needs patching, otherwise set to UINT32_MAX. */
279 uint32_t offSizeOfImage;
280 /** The correct image size. */
281 uint32_t cbCorrectImageSize;
282 /** Number of entries in the aMappings table. */
283 uint32_t cMappings;
284 /** Mapping hint. */
285 uint32_t iHint;
286 /** Mapping file offset to memory offsets, ordered by file offset. */
287 struct
288 {
289 /** The file offset. */
290 uint32_t offFile;
291 /** The size of this mapping. */
292 uint32_t cbMem;
293 /** The offset to the memory from the start of the image. */
294 uint32_t offMem;
295 } aMappings[1];
296} DBGDIGGERWINNTRDR;
297/** Pointer a WinNT loader reader instance data. */
298typedef DBGDIGGERWINNTRDR *PDBGDIGGERWINNTRDR;
299
300
301/*********************************************************************************************************************************
302* Defined Constants And Macros *
303*********************************************************************************************************************************/
304/** Validates a 32-bit Windows NT kernel address */
305#define WINNT32_VALID_ADDRESS(Addr) ((Addr) > UINT32_C(0x80000000) && (Addr) < UINT32_C(0xfffff000))
306/** Validates a 64-bit Windows NT kernel address */
307#define WINNT64_VALID_ADDRESS(Addr) ((Addr) > UINT64_C(0xffff800000000000) && (Addr) < UINT64_C(0xfffffffffffff000))
308/** Validates a kernel address. */
309#define WINNT_VALID_ADDRESS(pThis, Addr) ((pThis)->f32Bit ? WINNT32_VALID_ADDRESS(Addr) : WINNT64_VALID_ADDRESS(Addr))
310/** Versioned and bitness wrapper. */
311#define WINNT_UNION(pThis, pUnion, Member) ((pThis)->f32Bit ? (pUnion)->vX_32. Member : (pUnion)->vX_64. Member )
312
313/** The length (in chars) of the kernel file name (no path). */
314#define WINNT_KERNEL_BASE_NAME_LEN 12
315
316/** WindowsNT on little endian ASCII systems. */
317#define DIG_WINNT_MOD_TAG UINT64_C(0x54696e646f774e54)
318
319
320/*********************************************************************************************************************************
321* Internal Functions *
322*********************************************************************************************************************************/
323static DECLCALLBACK(int) dbgDiggerWinNtInit(PUVM pUVM, void *pvData);
324
325
326/*********************************************************************************************************************************
327* Global Variables *
328*********************************************************************************************************************************/
329/** Kernel names. */
330static const RTUTF16 g_wszKernelNames[][WINNT_KERNEL_BASE_NAME_LEN + 1] =
331{
332 { 'n', 't', 'o', 's', 'k', 'r', 'n', 'l', '.', 'e', 'x', 'e' }
333};
334
335
336
337/**
338 * Tries to resolve the KPCR and KPCRB addresses for each vCPU.
339 *
340 * @returns nothing.
341 * @param pThis The instance data.
342 * @param pUVM The user mode VM handle.
343 */
344static void dbgDiggerWinNtResolveKpcr(PDBGDIGGERWINNT pThis, PUVM pUVM)
345{
346 /*
347 * Getting at the KPCR and KPCRB is explained here:
348 * https://www.geoffchappell.com/studies/windows/km/ntoskrnl/structs/kpcr.htm
349 * Together with the available offsets from:
350 * https://github.com/tpn/winsdk-10/blob/master/Include/10.0.16299.0/shared/ksamd64.inc#L883
351 * we can verify that the found addresses are valid by cross checking that the GDTR and self reference
352 * match what we expect.
353 */
354 VMCPUID cCpus = DBGFR3CpuGetCount(pUVM);
355 pThis->paKpcrAddr = (PDBGFADDRESS)RTMemAllocZ(cCpus * 2 * sizeof(DBGFADDRESS));
356 if (RT_LIKELY(pThis->paKpcrAddr))
357 {
358 pThis->paKpcrbAddr = &pThis->paKpcrAddr[cCpus];
359
360 /* Work each CPU, unexpected values in each CPU make the whole thing fail to play safe. */
361 int rc = VINF_SUCCESS;
362 for (VMCPUID idCpu = 0; (idCpu < cCpus) && RT_SUCCESS(rc); idCpu++)
363 {
364 PDBGFADDRESS pKpcrAddr = &pThis->paKpcrAddr[idCpu];
365 PDBGFADDRESS pKpcrbAddr = &pThis->paKpcrbAddr[idCpu];
366
367 if (pThis->f32Bit)
368 {
369 /* Read FS base */
370 uint32_t GCPtrKpcrBase = 0;
371
372 rc = DBGFR3RegCpuQueryU32(pUVM, idCpu, DBGFREG_FS_BASE, &GCPtrKpcrBase);
373 if ( RT_SUCCESS(rc)
374 && WINNT32_VALID_ADDRESS(GCPtrKpcrBase))
375 {
376 /*
377 * Read the start of the KPCR (@todo Probably move this to a global header)
378 * and verify its content.
379 */
380 struct
381 {
382 uint8_t abOoi[28]; /* Out of interest */
383 uint32_t GCPtrSelf;
384 uint32_t GCPtrCurrentPrcb;
385 uint32_t u32Irql;
386 uint32_t u32Iir;
387 uint32_t u32IirActive;
388 uint32_t u32Idr;
389 uint32_t GCPtrKdVersionBlock;
390 uint32_t GCPtrIdt;
391 uint32_t GCPtrGdt;
392 uint32_t GCPtrTss;
393 } Kpcr;
394
395 LogFlow(("DigWinNt/KPCR[%u]: GS Base %RGv\n", idCpu, GCPtrKpcrBase));
396 DBGFR3AddrFromFlat(pUVM, pKpcrAddr, GCPtrKpcrBase);
397
398 rc = DBGFR3MemRead(pUVM, idCpu, pKpcrAddr, &Kpcr, sizeof(Kpcr));
399 if (RT_SUCCESS(rc))
400 {
401 uint32_t GCPtrGdt = 0;
402 uint32_t GCPtrIdt = 0;
403
404 rc = DBGFR3RegCpuQueryU32(pUVM, idCpu, DBGFREG_GDTR_BASE, &GCPtrGdt);
405 if (RT_SUCCESS(rc))
406 rc = DBGFR3RegCpuQueryU32(pUVM, idCpu, DBGFREG_IDTR_BASE, &GCPtrIdt);
407 if (RT_SUCCESS(rc))
408 {
409 if ( Kpcr.GCPtrGdt == GCPtrGdt
410 && Kpcr.GCPtrIdt == GCPtrIdt
411 && Kpcr.GCPtrSelf == pKpcrAddr->FlatPtr)
412 {
413 DBGFR3AddrFromFlat(pUVM, pKpcrbAddr, Kpcr.GCPtrCurrentPrcb);
414 LogRel(("DigWinNt/KPCR[%u]: KPCR=%RGv KPCRB=%RGv\n", idCpu, pKpcrAddr->FlatPtr, pKpcrbAddr->FlatPtr));
415
416 /*
417 * Try to extract the NT build number from the KD version block if it exists,
418 * the shared user data might have set it to 0.
419 *
420 * @todo We can use this method to get at the kern base and loaded module list if the other detection
421 * method fails (seen with Windows 10 x86).
422 * @todo On 32bit Windows the debugger data list is also always accessible this way contrary to
423 * the amd64 version where it is only available with "/debug on" set.
424 */
425 if (!pThis->NtBuildNumber)
426 {
427 NTKDVERSIONBLOCK KdVersBlock;
428 DBGFADDRESS AddrKdVersBlock;
429
430 DBGFR3AddrFromFlat(pUVM, &AddrKdVersBlock, Kpcr.GCPtrKdVersionBlock);
431 rc = DBGFR3MemRead(pUVM, idCpu, &AddrKdVersBlock, &KdVersBlock, sizeof(KdVersBlock));
432 if (RT_SUCCESS(rc))
433 pThis->NtBuildNumber = KdVersBlock.MinorVersion;
434 }
435 }
436 else
437 LogRel(("DigWinNt/KPCR[%u]: KPCR validation error GDT=(%RGv vs %RGv) KPCR=(%RGv vs %RGv)\n", idCpu,
438 Kpcr.GCPtrGdt, GCPtrGdt, Kpcr.GCPtrSelf, pKpcrAddr->FlatPtr));
439 }
440 else
441 LogRel(("DigWinNt/KPCR[%u]: Getting GDT or IDT base register failed with %Rrc\n", idCpu, rc));
442 }
443 }
444 else
445 LogRel(("DigWinNt/KPCR[%u]: Getting FS base register failed with %Rrc (%RGv)\n", idCpu, rc, GCPtrKpcrBase));
446 }
447 else
448 {
449 /* Read GS base which points to the base of the KPCR for each CPU. */
450 RTGCUINTPTR GCPtrTmp = 0;
451 rc = DBGFR3RegCpuQueryU64(pUVM, idCpu, DBGFREG_GS_BASE, &GCPtrTmp);
452 if ( RT_SUCCESS(rc)
453 && !WINNT64_VALID_ADDRESS(GCPtrTmp))
454 {
455 /*
456 * Could be a user address when we stopped the VM right in usermode,
457 * read the GS kernel base MSR instead.
458 */
459 rc = DBGFR3RegCpuQueryU64(pUVM, idCpu, DBGFREG_MSR_K8_KERNEL_GS_BASE, &GCPtrTmp);
460 }
461
462 if ( RT_SUCCESS(rc)
463 && WINNT64_VALID_ADDRESS(GCPtrTmp))
464 {
465 LogFlow(("DigWinNt/KPCR[%u]: GS Base %RGv\n", idCpu, GCPtrTmp));
466 DBGFR3AddrFromFlat(pUVM, pKpcrAddr, GCPtrTmp);
467
468 rc = DBGFR3RegCpuQueryU64(pUVM, idCpu, DBGFREG_GDTR_BASE, &GCPtrTmp);
469 if (RT_SUCCESS(rc))
470 {
471 /*
472 * Read the start of the KPCR (@todo Probably move this to a global header)
473 * and verify its content.
474 */
475 struct
476 {
477 RTGCUINTPTR GCPtrGdt;
478 RTGCUINTPTR GCPtrTss;
479 RTGCUINTPTR GCPtrUserRsp;
480 RTGCUINTPTR GCPtrSelf;
481 RTGCUINTPTR GCPtrCurrentPrcb;
482 } Kpcr;
483
484 rc = DBGFR3MemRead(pUVM, idCpu, pKpcrAddr, &Kpcr, sizeof(Kpcr));
485 if (RT_SUCCESS(rc))
486 {
487 if ( Kpcr.GCPtrGdt == GCPtrTmp
488 && Kpcr.GCPtrSelf == pKpcrAddr->FlatPtr
489 /** @todo && TSS */ )
490 {
491 DBGFR3AddrFromFlat(pUVM, pKpcrbAddr, Kpcr.GCPtrCurrentPrcb);
492 LogRel(("DigWinNt/KPCR[%u]: KPCR=%RGv KPCRB=%RGv\n", idCpu, pKpcrAddr->FlatPtr, pKpcrbAddr->FlatPtr));
493 }
494 else
495 LogRel(("DigWinNt/KPCR[%u]: KPCR validation error GDT=(%RGv vs %RGv) KPCR=(%RGv vs %RGv)\n", idCpu,
496 Kpcr.GCPtrGdt, GCPtrTmp, Kpcr.GCPtrSelf, pKpcrAddr->FlatPtr));
497 }
498 else
499 LogRel(("DigWinNt/KPCR[%u]: Reading KPCR start at %RGv failed with %Rrc\n", idCpu, pKpcrAddr->FlatPtr, rc));
500 }
501 else
502 LogRel(("DigWinNt/KPCR[%u]: Getting GDT base register failed with %Rrc\n", idCpu, rc));
503 }
504 else
505 LogRel(("DigWinNt/KPCR[%u]: Getting GS base register failed with %Rrc\n", idCpu, rc));
506 }
507 }
508
509 if (RT_FAILURE(rc))
510 {
511 LogRel(("DigWinNt/KPCR: Failed to detmine KPCR and KPCRB rc=%Rrc\n", rc));
512 RTMemFree(pThis->paKpcrAddr);
513 pThis->paKpcrAddr = NULL;
514 pThis->paKpcrbAddr = NULL;
515 }
516 }
517 else
518 LogRel(("DigWinNt/KPCR: Failed to allocate %u entries for the KPCR/KPCRB addresses\n", cCpus * 2));
519}
520
521
522/**
523 * Process a PE image found in guest memory.
524 *
525 * @param pThis The instance data.
526 * @param pUVM The user mode VM handle.
527 * @param pszName The module name.
528 * @param pszFilename The image filename.
529 * @param pImageAddr The image address.
530 * @param cbImage The size of the image.
531 */
532static void dbgDiggerWinNtProcessImage(PDBGDIGGERWINNT pThis, PUVM pUVM, const char *pszName, const char *pszFilename,
533 PCDBGFADDRESS pImageAddr, uint32_t cbImage)
534{
535 LogFlow(("DigWinNt: %RGp %#x %s\n", pImageAddr->FlatPtr, cbImage, pszName));
536
537 /*
538 * Do some basic validation first.
539 */
540 if ( (cbImage < sizeof(IMAGE_NT_HEADERS64) && !pThis->fNt31)
541 || cbImage >= _1M * 256)
542 {
543 Log(("DigWinNt: %s: Bad image size: %#x\n", pszName, cbImage));
544 return;
545 }
546
547 /*
548 * Use the common in-memory module reader to create a debug module.
549 */
550 RTERRINFOSTATIC ErrInfo;
551 RTDBGMOD hDbgMod = NIL_RTDBGMOD;
552 int rc = DBGFR3ModInMem(pUVM, pImageAddr, pThis->fNt31 ? DBGFMODINMEM_F_PE_NT31 : 0, pszName, pszFilename,
553 pThis->f32Bit ? RTLDRARCH_X86_32 : RTLDRARCH_AMD64, cbImage,
554 &hDbgMod, RTErrInfoInitStatic(&ErrInfo));
555 if (RT_SUCCESS(rc))
556 {
557 /*
558 * Tag the module.
559 */
560 rc = RTDbgModSetTag(hDbgMod, DIG_WINNT_MOD_TAG);
561 AssertRC(rc);
562
563 /*
564 * Link the module.
565 */
566 RTDBGAS hAs = DBGFR3AsResolveAndRetain(pUVM, DBGF_AS_KERNEL);
567 if (hAs != NIL_RTDBGAS)
568 rc = RTDbgAsModuleLink(hAs, hDbgMod, pImageAddr->FlatPtr, RTDBGASLINK_FLAGS_REPLACE /*fFlags*/);
569 else
570 rc = VERR_INTERNAL_ERROR;
571 RTDbgModRelease(hDbgMod);
572 RTDbgAsRelease(hAs);
573 }
574 else if (RTErrInfoIsSet(&ErrInfo.Core))
575 Log(("DigWinNt: %s: DBGFR3ModInMem failed: %Rrc - %s\n", pszName, rc, ErrInfo.Core.pszMsg));
576 else
577 Log(("DigWinNt: %s: DBGFR3ModInMem failed: %Rrc\n", pszName, rc));
578}
579
580
581/**
582 * Generate a debugger compatible module name from a filename.
583 *
584 * @returns Pointer to module name (doesn't need to be pszName).
585 * @param pszFilename The source filename.
586 * @param pszName Buffer to put the module name in.
587 * @param cbName Buffer size.
588 */
589static const char *dbgDiggerWintNtFilenameToModuleName(const char *pszFilename, char *pszName, size_t cbName)
590{
591 /* Skip to the filename part of the filename. :-) */
592 pszFilename = RTPathFilenameEx(pszFilename, RTPATH_STR_F_STYLE_DOS);
593
594 /* We try use 'nt' for the kernel. */
595 if ( RTStrICmpAscii(pszFilename, "ntoskrnl.exe") == 0
596 || RTStrICmpAscii(pszFilename, "ntkrnlmp.exe") == 0)
597 return "nt";
598
599
600 /* Drop the extension if .dll or .sys. */
601 size_t cchFilename = strlen(pszFilename);
602 if ( cchFilename > 4
603 && pszFilename[cchFilename - 4] == '.')
604 {
605 if ( RTStrICmpAscii(&pszFilename[cchFilename - 4], ".sys") == 0
606 || RTStrICmpAscii(&pszFilename[cchFilename - 4], ".dll") == 0)
607 cchFilename -= 4;
608 }
609
610 /* Copy and do replacements. */
611 if (cchFilename >= cbName)
612 cchFilename = cbName - 1;
613 size_t off;
614 for (off = 0; off < cchFilename; off++)
615 {
616 char ch = pszFilename[off];
617 if (!RT_C_IS_ALNUM(ch))
618 ch = '_';
619 pszName[off] = ch;
620 }
621 pszName[off] = '\0';
622 return pszName;
623}
624
625
626/**
627 * @interface_method_impl{DBGFOSIWINNT,pfnQueryVersion}
628 */
629static DECLCALLBACK(int) dbgDiggerWinNtIWinNt_QueryVersion(struct DBGFOSIWINNT *pThis, PUVM pUVM,
630 uint32_t *puVersMajor, uint32_t *puVersMinor,
631 uint32_t *puBuildNumber, bool *pf32Bit)
632{
633 RT_NOREF(pUVM);
634 PDBGDIGGERWINNT pData = RT_FROM_MEMBER(pThis, DBGDIGGERWINNT, IWinNt);
635
636 if (puVersMajor)
637 *puVersMajor = pData->NtMajorVersion;
638 if (puVersMinor)
639 *puVersMinor = pData->NtMinorVersion;
640 if (puBuildNumber)
641 *puBuildNumber = pData->NtBuildNumber;
642 if (pf32Bit)
643 *pf32Bit = pData->f32Bit;
644 return VINF_SUCCESS;
645}
646
647
648/**
649 * @interface_method_impl{DBGFOSIWINNT,pfnQueryKernelPtrs}
650 */
651static DECLCALLBACK(int) dbgDiggerWinNtIWinNt_QueryKernelPtrs(struct DBGFOSIWINNT *pThis, PUVM pUVM,
652 PRTGCUINTPTR pGCPtrKernBase, PRTGCUINTPTR pGCPtrPsLoadedModuleList)
653{
654 RT_NOREF(pUVM);
655 PDBGDIGGERWINNT pData = RT_FROM_MEMBER(pThis, DBGDIGGERWINNT, IWinNt);
656
657 *pGCPtrKernBase = pData->KernelAddr.FlatPtr;
658 *pGCPtrPsLoadedModuleList = pData->PsLoadedModuleListAddr.FlatPtr;
659 return VINF_SUCCESS;
660}
661
662
663/**
664 * @interface_method_impl{DBGFOSIWINNT,pfnQueryKpcrForVCpu}
665 */
666static DECLCALLBACK(int) dbgDiggerWinNtIWinNt_QueryKpcrForVCpu(struct DBGFOSIWINNT *pThis, PUVM pUVM, VMCPUID idCpu,
667 PRTGCUINTPTR pKpcr, PRTGCUINTPTR pKpcrb)
668{
669 PDBGDIGGERWINNT pData = RT_FROM_MEMBER(pThis, DBGDIGGERWINNT, IWinNt);
670
671 if (!pData->paKpcrAddr)
672 return VERR_NOT_SUPPORTED;
673
674 AssertReturn(idCpu < DBGFR3CpuGetCount(pUVM), VERR_INVALID_PARAMETER);
675
676 if (pKpcr)
677 *pKpcr = pData->paKpcrAddr[idCpu].FlatPtr;
678 if (pKpcrb)
679 *pKpcrb = pData->paKpcrbAddr[idCpu].FlatPtr;
680 return VINF_SUCCESS;
681}
682
683
684/**
685 * @interface_method_impl{DBGFOSIWINNT,pfnQueryCurThrdForVCpu}
686 */
687static DECLCALLBACK(int) dbgDiggerWinNtIWinNt_QueryCurThrdForVCpu(struct DBGFOSIWINNT *pThis, PUVM pUVM, VMCPUID idCpu,
688 PRTGCUINTPTR pCurThrd)
689{
690 PDBGDIGGERWINNT pData = RT_FROM_MEMBER(pThis, DBGDIGGERWINNT, IWinNt);
691
692 if (!pData->paKpcrAddr)
693 return VERR_NOT_SUPPORTED;
694
695 AssertReturn(idCpu < DBGFR3CpuGetCount(pUVM), VERR_INVALID_PARAMETER);
696
697 DBGFADDRESS AddrCurThrdPtr = pData->paKpcrbAddr[idCpu];
698 DBGFR3AddrAdd(&AddrCurThrdPtr, 0x08); /** @todo Make this prettier. */
699 return DBGFR3MemRead(pUVM, idCpu, &AddrCurThrdPtr, pCurThrd, sizeof(*pCurThrd));
700}
701
702
703/**
704 * @copydoc DBGFOSREG::pfnStackUnwindAssist
705 */
706static DECLCALLBACK(int) dbgDiggerWinNtStackUnwindAssist(PUVM pUVM, void *pvData, VMCPUID idCpu, PDBGFSTACKFRAME pFrame,
707 PRTDBGUNWINDSTATE pState, PCCPUMCTX pInitialCtx, RTDBGAS hAs,
708 uint64_t *puScratch)
709{
710 Assert(pInitialCtx);
711
712 /*
713 * We want to locate trap frames here. The trap frame structure contains
714 * the 64-bit IRET frame, so given unwind information it's easy to identify
715 * using the return type and frame address.
716 */
717 if (pFrame->fFlags & DBGFSTACKFRAME_FLAGS_64BIT)
718 {
719 /*
720 * Is this a trap frame? If so, try read the trap frame.
721 */
722 if ( pFrame->enmReturnType == RTDBGRETURNTYPE_IRET64
723 && !(pFrame->AddrFrame.FlatPtr & 0x7)
724 && WINNT64_VALID_ADDRESS(pFrame->AddrFrame.FlatPtr) )
725 {
726 KTRAP_FRAME_AMD64 TrapFrame;
727 RT_ZERO(TrapFrame);
728 uint64_t const uTrapFrameAddr = pFrame->AddrFrame.FlatPtr
729 - RT_UOFFSETOF(KTRAP_FRAME_AMD64, ErrCdOrXcptFrameOrS);
730 int rc = pState->pfnReadStack(pState, uTrapFrameAddr, sizeof(TrapFrame), &TrapFrame);
731 if (RT_SUCCESS(rc))
732 {
733 /* Valid? Not too much else we can check here (EFlags isn't
734 reliable in manually construct frames). */
735 if (TrapFrame.ExceptionActive <= 2)
736 {
737 pFrame->fFlags |= DBGFSTACKFRAME_FLAGS_TRAP_FRAME;
738
739 /*
740 * Add sure 'register' information from the frame to the frame.
741 *
742 * To avoid code duplication, we do this in two steps in a loop.
743 * The first iteration only figures out how many registers we're
744 * going to save and allocates room for them. The second iteration
745 * does the actual adding.
746 */
747 uint32_t cRegs = pFrame->cSureRegs;
748 PDBGFREGVALEX paSureRegs = NULL;
749#define ADD_REG_NAMED(a_Type, a_ValMemb, a_Value, a_pszName) do { \
750 if (paSureRegs) \
751 { \
752 paSureRegs[iReg].pszName = a_pszName;\
753 paSureRegs[iReg].enmReg = DBGFREG_END; \
754 paSureRegs[iReg].enmType = a_Type; \
755 paSureRegs[iReg].Value.a_ValMemb = (a_Value); \
756 } \
757 iReg++; \
758 } while (0)
759#define MAYBE_ADD_GREG(a_Value, a_enmReg, a_idxReg) do { \
760 if (!(pState->u.x86.Loaded.s.fRegs & RT_BIT(a_idxReg))) \
761 { \
762 if (paSureRegs) \
763 { \
764 pState->u.x86.Loaded.s.fRegs |= RT_BIT(a_idxReg); \
765 pState->u.x86.auRegs[a_idxReg] = (a_Value); \
766 paSureRegs[iReg].Value.u64 = (a_Value); \
767 paSureRegs[iReg].enmReg = a_enmReg; \
768 paSureRegs[iReg].enmType = DBGFREGVALTYPE_U64; \
769 paSureRegs[iReg].pszName = NULL; \
770 } \
771 iReg++; \
772 } \
773 } while (0)
774 for (unsigned iLoop = 0; iLoop < 2; iLoop++)
775 {
776 uint32_t iReg = pFrame->cSureRegs;
777 ADD_REG_NAMED(DBGFREGVALTYPE_U64, u64, uTrapFrameAddr, "TrapFrame");
778 ADD_REG_NAMED(DBGFREGVALTYPE_U8, u8, TrapFrame.ExceptionActive, "ExceptionActive");
779 if (TrapFrame.ExceptionActive == 0)
780 {
781 ADD_REG_NAMED(DBGFREGVALTYPE_U8, u8, TrapFrame.PreviousIrql, "PrevIrql");
782 ADD_REG_NAMED(DBGFREGVALTYPE_U8, u8, (uint8_t)TrapFrame.ErrCdOrXcptFrameOrS, "IntNo");
783 }
784 else if ( TrapFrame.ExceptionActive == 1
785 && TrapFrame.FaultIndicator == ((TrapFrame.ErrCdOrXcptFrameOrS >> 1) & 0x9))
786 ADD_REG_NAMED(DBGFREGVALTYPE_U64, u64, TrapFrame.FaultAddrOrCtxRecOrTS, "cr2-probably");
787 if (TrapFrame.SegCs & X86_SEL_RPL)
788 ADD_REG_NAMED(DBGFREGVALTYPE_U8, u8, 1, "UserMode");
789 else
790 ADD_REG_NAMED(DBGFREGVALTYPE_U8, u8, 1, "KernelMode");
791 if (TrapFrame.ExceptionActive <= 1)
792 {
793 MAYBE_ADD_GREG(TrapFrame.Rax, DBGFREG_RAX, X86_GREG_xAX);
794 MAYBE_ADD_GREG(TrapFrame.Rcx, DBGFREG_RCX, X86_GREG_xCX);
795 MAYBE_ADD_GREG(TrapFrame.Rdx, DBGFREG_RDX, X86_GREG_xDX);
796 MAYBE_ADD_GREG(TrapFrame.R8, DBGFREG_R8, X86_GREG_x8);
797 MAYBE_ADD_GREG(TrapFrame.R9, DBGFREG_R9, X86_GREG_x9);
798 MAYBE_ADD_GREG(TrapFrame.R10, DBGFREG_R10, X86_GREG_x10);
799 MAYBE_ADD_GREG(TrapFrame.R11, DBGFREG_R11, X86_GREG_x11);
800 }
801 else if (TrapFrame.ExceptionActive == 2)
802 {
803 MAYBE_ADD_GREG(TrapFrame.Rbx, DBGFREG_RBX, X86_GREG_xBX);
804 MAYBE_ADD_GREG(TrapFrame.Rsi, DBGFREG_RSI, X86_GREG_xSI);
805 MAYBE_ADD_GREG(TrapFrame.Rdi, DBGFREG_RDI, X86_GREG_xDI);
806 }
807 // MAYBE_ADD_GREG(TrapFrame.Rbp, DBGFREG_RBP, X86_GREG_xBP); - KiInterrupt[Sub]Dispatch* may leave this invalid.
808
809 /* Done? */
810 if (iLoop > 0)
811 {
812 Assert(cRegs == iReg);
813 break;
814 }
815
816 /* Resize the array, zeroing the extension. */
817 if (pFrame->cSureRegs)
818 paSureRegs = (PDBGFREGVALEX)MMR3HeapRealloc(pFrame->paSureRegs, iReg * sizeof(paSureRegs[0]));
819 else
820 paSureRegs = (PDBGFREGVALEX)MMR3HeapAllocU(pUVM, MM_TAG_DBGF_STACK, iReg * sizeof(paSureRegs[0]));
821 AssertReturn(paSureRegs, VERR_NO_MEMORY);
822
823 pFrame->paSureRegs = paSureRegs;
824 RT_BZERO(&paSureRegs[pFrame->cSureRegs], (iReg - pFrame->cSureRegs) * sizeof(paSureRegs[0]));
825 cRegs = iReg;
826 }
827#undef ADD_REG_NAMED
828#undef MAYBE_ADD_GREG
829
830 /* Commit the register update. */
831 pFrame->cSureRegs = cRegs;
832 }
833 }
834 }
835 }
836
837 RT_NOREF(pUVM, pvData, idCpu, hAs, pInitialCtx, puScratch);
838 return VINF_SUCCESS;
839}
840
841
842/**
843 * @copydoc DBGFOSREG::pfnQueryInterface
844 */
845static DECLCALLBACK(void *) dbgDiggerWinNtQueryInterface(PUVM pUVM, void *pvData, DBGFOSINTERFACE enmIf)
846{
847 RT_NOREF(pUVM);
848 PDBGDIGGERWINNT pThis = (PDBGDIGGERWINNT)pvData;
849
850 switch (enmIf)
851 {
852 case DBGFOSINTERFACE_WINNT:
853 return &pThis->IWinNt;
854 default:
855 return NULL;
856 }
857}
858
859
860/**
861 * @copydoc DBGFOSREG::pfnQueryVersion
862 */
863static DECLCALLBACK(int) dbgDiggerWinNtQueryVersion(PUVM pUVM, void *pvData, char *pszVersion, size_t cchVersion)
864{
865 RT_NOREF1(pUVM);
866 PDBGDIGGERWINNT pThis = (PDBGDIGGERWINNT)pvData;
867 Assert(pThis->fValid);
868 const char *pszNtProductType;
869 switch (pThis->NtProductType)
870 {
871 case kNtProductType_WinNt: pszNtProductType = "-WinNT"; break;
872 case kNtProductType_LanManNt: pszNtProductType = "-LanManNT"; break;
873 case kNtProductType_Server: pszNtProductType = "-Server"; break;
874 default: pszNtProductType = ""; break;
875 }
876 RTStrPrintf(pszVersion, cchVersion, "%u.%u-%s%s (BuildNumber %u)", pThis->NtMajorVersion, pThis->NtMinorVersion,
877 pThis->f32Bit ? "x86" : "AMD64", pszNtProductType, pThis->NtBuildNumber);
878 return VINF_SUCCESS;
879}
880
881
882/**
883 * @copydoc DBGFOSREG::pfnTerm
884 */
885static DECLCALLBACK(void) dbgDiggerWinNtTerm(PUVM pUVM, void *pvData)
886{
887 RT_NOREF1(pUVM);
888 PDBGDIGGERWINNT pThis = (PDBGDIGGERWINNT)pvData;
889 Assert(pThis->fValid);
890
891 /*
892 * As long as we're using our private LDR reader implementation,
893 * we must unlink and ditch the modules we created.
894 */
895 RTDBGAS hDbgAs = DBGFR3AsResolveAndRetain(pUVM, DBGF_AS_KERNEL);
896 if (hDbgAs != NIL_RTDBGAS)
897 {
898 uint32_t iMod = RTDbgAsModuleCount(hDbgAs);
899 while (iMod-- > 0)
900 {
901 RTDBGMOD hMod = RTDbgAsModuleByIndex(hDbgAs, iMod);
902 if (hMod != NIL_RTDBGMOD)
903 {
904 if (RTDbgModGetTag(hMod) == DIG_WINNT_MOD_TAG)
905 {
906 int rc = RTDbgAsModuleUnlink(hDbgAs, hMod);
907 AssertRC(rc);
908 }
909 RTDbgModRelease(hMod);
910 }
911 }
912 RTDbgAsRelease(hDbgAs);
913 }
914
915 if (pThis->paKpcrAddr)
916 RTMemFree(pThis->paKpcrAddr);
917 /* pThis->paKpcrbAddr comes from the same allocation as pThis->paKpcrAddr. */
918
919 pThis->paKpcrAddr = NULL;
920 pThis->paKpcrbAddr = NULL;
921
922 pThis->fValid = false;
923}
924
925
926/**
927 * @copydoc DBGFOSREG::pfnRefresh
928 */
929static DECLCALLBACK(int) dbgDiggerWinNtRefresh(PUVM pUVM, void *pvData)
930{
931 PDBGDIGGERWINNT pThis = (PDBGDIGGERWINNT)pvData;
932 NOREF(pThis);
933 Assert(pThis->fValid);
934
935 /*
936 * For now we'll flush and reload everything.
937 */
938 dbgDiggerWinNtTerm(pUVM, pvData);
939
940 return dbgDiggerWinNtInit(pUVM, pvData);
941}
942
943
944/**
945 * @copydoc DBGFOSREG::pfnInit
946 */
947static DECLCALLBACK(int) dbgDiggerWinNtInit(PUVM pUVM, void *pvData)
948{
949 PDBGDIGGERWINNT pThis = (PDBGDIGGERWINNT)pvData;
950 Assert(!pThis->fValid);
951
952 union
953 {
954 uint8_t au8[0x2000];
955 RTUTF16 wsz[0x2000/2];
956 NTKUSERSHAREDDATA UserSharedData;
957 } u;
958 DBGFADDRESS Addr;
959 int rc;
960
961 /*
962 * Figure the NT version.
963 */
964 DBGFR3AddrFromFlat(pUVM, &Addr, pThis->f32Bit ? NTKUSERSHAREDDATA_WINNT32 : NTKUSERSHAREDDATA_WINNT64);
965 rc = DBGFR3MemRead(pUVM, 0 /*idCpu*/, &Addr, &u, PAGE_SIZE);
966 if (RT_SUCCESS(rc))
967 {
968 pThis->NtProductType = u.UserSharedData.ProductTypeIsValid && u.UserSharedData.NtProductType <= kNtProductType_Server
969 ? (NTPRODUCTTYPE)u.UserSharedData.NtProductType
970 : kNtProductType_Invalid;
971 pThis->NtMajorVersion = u.UserSharedData.NtMajorVersion;
972 pThis->NtMinorVersion = u.UserSharedData.NtMinorVersion;
973 pThis->NtBuildNumber = u.UserSharedData.NtBuildNumber;
974 }
975 else if (pThis->fNt31)
976 {
977 pThis->NtProductType = kNtProductType_WinNt;
978 pThis->NtMajorVersion = 3;
979 pThis->NtMinorVersion = 1;
980 pThis->NtBuildNumber = 0;
981 }
982 else
983 {
984 Log(("DigWinNt: Error reading KUSER_SHARED_DATA: %Rrc\n", rc));
985 return rc;
986 }
987
988 /*
989 * Dig out the module chain.
990 */
991 DBGFADDRESS AddrPrev = pThis->PsLoadedModuleListAddr;
992 Addr = pThis->KernelMteAddr;
993 do
994 {
995 /* Read the validate the MTE. */
996 NTMTE Mte;
997 rc = DBGFR3MemRead(pUVM, 0 /*idCpu*/, &Addr, &Mte, pThis->f32Bit ? sizeof(Mte.vX_32) : sizeof(Mte.vX_64));
998 if (RT_FAILURE(rc))
999 break;
1000 if (WINNT_UNION(pThis, &Mte, InLoadOrderLinks.Blink) != AddrPrev.FlatPtr)
1001 {
1002 Log(("DigWinNt: Bad Mte At %RGv - backpointer\n", Addr.FlatPtr));
1003 break;
1004 }
1005 if (!WINNT_VALID_ADDRESS(pThis, WINNT_UNION(pThis, &Mte, InLoadOrderLinks.Flink)) )
1006 {
1007 Log(("DigWinNt: Bad Mte at %RGv - forward pointer\n", Addr.FlatPtr));
1008 break;
1009 }
1010 if (!WINNT_VALID_ADDRESS(pThis, WINNT_UNION(pThis, &Mte, BaseDllName.Buffer)))
1011 {
1012 Log(("DigWinNt: Bad Mte at %RGv - BaseDllName=%llx\n", Addr.FlatPtr, WINNT_UNION(pThis, &Mte, BaseDllName.Buffer)));
1013 break;
1014 }
1015 if (!WINNT_VALID_ADDRESS(pThis, WINNT_UNION(pThis, &Mte, FullDllName.Buffer)))
1016 {
1017 Log(("DigWinNt: Bad Mte at %RGv - FullDllName=%llx\n", Addr.FlatPtr, WINNT_UNION(pThis, &Mte, FullDllName.Buffer)));
1018 break;
1019 }
1020 if (!WINNT_VALID_ADDRESS(pThis, WINNT_UNION(pThis, &Mte, DllBase)))
1021 {
1022 Log(("DigWinNt: Bad Mte at %RGv - DllBase=%llx\n", Addr.FlatPtr, WINNT_UNION(pThis, &Mte, DllBase) ));
1023 break;
1024 }
1025
1026 uint32_t const cbImageMte = !pThis->fNt31 ? WINNT_UNION(pThis, &Mte, SizeOfImage) : 0;
1027 if ( !pThis->fNt31
1028 && ( cbImageMte > _256M
1029 || WINNT_UNION(pThis, &Mte, EntryPoint) - WINNT_UNION(pThis, &Mte, DllBase) > cbImageMte) )
1030 {
1031 Log(("DigWinNt: Bad Mte at %RGv - EntryPoint=%llx SizeOfImage=%x DllBase=%llx\n",
1032 Addr.FlatPtr, WINNT_UNION(pThis, &Mte, EntryPoint), cbImageMte, WINNT_UNION(pThis, &Mte, DllBase)));
1033 break;
1034 }
1035
1036 /* Read the full name. */
1037 DBGFADDRESS AddrName;
1038 DBGFR3AddrFromFlat(pUVM, &AddrName, WINNT_UNION(pThis, &Mte, FullDllName.Buffer));
1039 uint16_t cbName = WINNT_UNION(pThis, &Mte, FullDllName.Length);
1040 if (cbName < sizeof(u))
1041 rc = DBGFR3MemRead(pUVM, 0 /*idCpu*/, &AddrName, &u, cbName);
1042 else
1043 rc = VERR_OUT_OF_RANGE;
1044 if (RT_FAILURE(rc))
1045 {
1046 DBGFR3AddrFromFlat(pUVM, &AddrName, WINNT_UNION(pThis, &Mte, BaseDllName.Buffer));
1047 cbName = WINNT_UNION(pThis, &Mte, BaseDllName.Length);
1048 if (cbName < sizeof(u))
1049 rc = DBGFR3MemRead(pUVM, 0 /*idCpu*/, &AddrName, &u, cbName);
1050 else
1051 rc = VERR_OUT_OF_RANGE;
1052 }
1053 if (RT_SUCCESS(rc))
1054 {
1055 u.wsz[cbName / 2] = '\0';
1056
1057 char *pszFilename;
1058 rc = RTUtf16ToUtf8(u.wsz, &pszFilename);
1059 if (RT_SUCCESS(rc))
1060 {
1061 char szModName[128];
1062 const char *pszModName = dbgDiggerWintNtFilenameToModuleName(pszFilename, szModName, sizeof(szModName));
1063
1064 /* Read the start of the PE image and pass it along to a worker. */
1065 DBGFADDRESS ImageAddr;
1066 DBGFR3AddrFromFlat(pUVM, &ImageAddr, WINNT_UNION(pThis, &Mte, DllBase));
1067 dbgDiggerWinNtProcessImage(pThis, pUVM, pszModName, pszFilename, &ImageAddr, cbImageMte);
1068 RTStrFree(pszFilename);
1069 }
1070 }
1071
1072 /* next */
1073 AddrPrev = Addr;
1074 DBGFR3AddrFromFlat(pUVM, &Addr, WINNT_UNION(pThis, &Mte, InLoadOrderLinks.Flink));
1075 } while ( Addr.FlatPtr != pThis->KernelMteAddr.FlatPtr
1076 && Addr.FlatPtr != pThis->PsLoadedModuleListAddr.FlatPtr);
1077
1078 /* Try resolving the KPCR and KPCRB addresses for each vCPU. */
1079 dbgDiggerWinNtResolveKpcr(pThis, pUVM);
1080
1081 pThis->fValid = true;
1082 return VINF_SUCCESS;
1083}
1084
1085
1086/**
1087 * @copydoc DBGFOSREG::pfnProbe
1088 */
1089static DECLCALLBACK(bool) dbgDiggerWinNtProbe(PUVM pUVM, void *pvData)
1090{
1091 PDBGDIGGERWINNT pThis = (PDBGDIGGERWINNT)pvData;
1092 DBGFADDRESS Addr;
1093 union
1094 {
1095 uint8_t au8[8192];
1096 uint16_t au16[8192/2];
1097 uint32_t au32[8192/4];
1098 IMAGE_DOS_HEADER MzHdr;
1099 RTUTF16 wsz[8192/2];
1100 X86DESCGATE a32Gates[X86_XCPT_PF + 1];
1101 X86DESC64GATE a64Gates[X86_XCPT_PF + 1];
1102 } u;
1103
1104 union
1105 {
1106 NTMTE32 v32;
1107 NTMTE64 v64;
1108 } uMte, uMte2, uMte3;
1109
1110 /*
1111 * NT only runs in protected or long mode.
1112 */
1113 CPUMMODE const enmMode = DBGFR3CpuGetMode(pUVM, 0 /*idCpu*/);
1114 if (enmMode != CPUMMODE_PROTECTED && enmMode != CPUMMODE_LONG)
1115 return false;
1116 bool const f64Bit = enmMode == CPUMMODE_LONG;
1117 uint64_t const uStart = f64Bit ? UINT64_C(0xffff080000000000) : UINT32_C(0x80001000);
1118 uint64_t const uEnd = f64Bit ? UINT64_C(0xffffffffffff0000) : UINT32_C(0xffff0000);
1119
1120 /*
1121 * To approximately locate the kernel we examine the IDTR handlers.
1122 *
1123 * The exception/trap/fault handlers are all in NT kernel image, we pick
1124 * KiPageFault here.
1125 */
1126 uint64_t uIdtrBase = 0;
1127 uint16_t uIdtrLimit = 0;
1128 int rc = DBGFR3RegCpuQueryXdtr(pUVM, 0, DBGFREG_IDTR, &uIdtrBase, &uIdtrLimit);
1129 AssertRCReturn(rc, false);
1130
1131 const uint16_t cbMinIdtr = (X86_XCPT_PF + 1) * (f64Bit ? sizeof(X86DESC64GATE) : sizeof(X86DESCGATE));
1132 if (uIdtrLimit < cbMinIdtr)
1133 return false;
1134
1135 rc = DBGFR3MemRead(pUVM, 0 /*idCpu*/, DBGFR3AddrFromFlat(pUVM, &Addr, uIdtrBase), &u, cbMinIdtr);
1136 if (RT_FAILURE(rc))
1137 return false;
1138
1139 uint64_t uKrnlStart = uStart;
1140 uint64_t uKrnlEnd = uEnd;
1141 if (f64Bit)
1142 {
1143 uint64_t uHandler = u.a64Gates[X86_XCPT_PF].u16OffsetLow
1144 | ((uint32_t)u.a64Gates[X86_XCPT_PF].u16OffsetHigh << 16)
1145 | ((uint64_t)u.a64Gates[X86_XCPT_PF].u32OffsetTop << 32);
1146 if (uHandler < uStart || uHandler > uEnd)
1147 return false;
1148 uKrnlStart = (uHandler & ~(uint64_t)_4M) - _512M;
1149 uKrnlEnd = (uHandler + (uint64_t)_4M) & ~(uint64_t)_4M;
1150 }
1151 else
1152 {
1153 uint32_t uHandler = RT_MAKE_U32(u.a32Gates[X86_XCPT_PF].u16OffsetLow, u.a32Gates[X86_XCPT_PF].u16OffsetHigh);
1154 if (uHandler < uStart || uHandler > uEnd)
1155 return false;
1156 uKrnlStart = (uHandler & ~(uint64_t)_4M) - _64M;
1157 uKrnlEnd = (uHandler + (uint64_t)_4M) & ~(uint64_t)_4M;
1158 }
1159
1160 /*
1161 * Look for the PAGELK section name that seems to be a part of all kernels.
1162 * Then try find the module table entry for it. Since it's the first entry
1163 * in the PsLoadedModuleList we can easily validate the list head and report
1164 * success.
1165 *
1166 * Note! We ASSUME the section name is 8 byte aligned.
1167 */
1168 DBGFADDRESS KernelAddr;
1169 for (DBGFR3AddrFromFlat(pUVM, &KernelAddr, uKrnlStart);
1170 KernelAddr.FlatPtr < uKrnlEnd;
1171 KernelAddr.FlatPtr += PAGE_SIZE)
1172 {
1173 bool fNt31 = false;
1174 DBGFADDRESS const RetryAddress = KernelAddr;
1175 rc = DBGFR3MemScan(pUVM, 0 /*idCpu*/, &KernelAddr, uEnd - KernelAddr.FlatPtr,
1176 8, "PAGELK\0", sizeof("PAGELK\0"), &KernelAddr);
1177 if ( rc == VERR_DBGF_MEM_NOT_FOUND
1178 && enmMode != CPUMMODE_LONG)
1179 {
1180 /* NT3.1 didn't have a PAGELK section, so look for _TEXT instead. The
1181 following VirtualSize is zero, so check for that too. */
1182 rc = DBGFR3MemScan(pUVM, 0 /*idCpu*/, &RetryAddress, uEnd - RetryAddress.FlatPtr,
1183 8, "_TEXT\0\0\0\0\0\0", sizeof("_TEXT\0\0\0\0\0\0"), &KernelAddr);
1184 fNt31 = true;
1185 }
1186 if (RT_FAILURE(rc))
1187 break;
1188 DBGFR3AddrSub(&KernelAddr, KernelAddr.FlatPtr & PAGE_OFFSET_MASK);
1189
1190 /* MZ + PE header. */
1191 rc = DBGFR3MemRead(pUVM, 0 /*idCpu*/, &KernelAddr, &u, sizeof(u));
1192 if ( RT_SUCCESS(rc)
1193 && u.MzHdr.e_magic == IMAGE_DOS_SIGNATURE
1194 && !(u.MzHdr.e_lfanew & 0x7)
1195 && u.MzHdr.e_lfanew >= 0x080
1196 && u.MzHdr.e_lfanew <= 0x400) /* W8 is at 0x288*/
1197 {
1198 if (enmMode != CPUMMODE_LONG)
1199 {
1200 IMAGE_NT_HEADERS32 const *pHdrs = (IMAGE_NT_HEADERS32 const *)&u.au8[u.MzHdr.e_lfanew];
1201 if ( pHdrs->Signature == IMAGE_NT_SIGNATURE
1202 && pHdrs->FileHeader.Machine == IMAGE_FILE_MACHINE_I386
1203 && pHdrs->FileHeader.SizeOfOptionalHeader == sizeof(pHdrs->OptionalHeader)
1204 && pHdrs->FileHeader.NumberOfSections >= 10 /* the kernel has lots */
1205 && (pHdrs->FileHeader.Characteristics & (IMAGE_FILE_EXECUTABLE_IMAGE | IMAGE_FILE_DLL)) == IMAGE_FILE_EXECUTABLE_IMAGE
1206 && pHdrs->OptionalHeader.Magic == IMAGE_NT_OPTIONAL_HDR32_MAGIC
1207 && pHdrs->OptionalHeader.NumberOfRvaAndSizes == IMAGE_NUMBEROF_DIRECTORY_ENTRIES
1208 )
1209 {
1210 /* Find the MTE. */
1211 RT_ZERO(uMte);
1212 uMte.v32.DllBase = KernelAddr.FlatPtr;
1213 uMte.v32.EntryPoint = KernelAddr.FlatPtr + pHdrs->OptionalHeader.AddressOfEntryPoint;
1214 uMte.v32.SizeOfImage = !fNt31 ? pHdrs->OptionalHeader.SizeOfImage : 0; /* NT 3.1 didn't set the size. */
1215 DBGFADDRESS HitAddr;
1216 rc = DBGFR3MemScan(pUVM, 0 /*idCpu*/, &KernelAddr, uEnd - KernelAddr.FlatPtr,
1217 4 /*align*/, &uMte.v32.DllBase, 3 * sizeof(uint32_t), &HitAddr);
1218 while (RT_SUCCESS(rc))
1219 {
1220 /* check the name. */
1221 DBGFADDRESS MteAddr = HitAddr;
1222 rc = DBGFR3MemRead(pUVM, 0 /*idCpu*/, DBGFR3AddrSub(&MteAddr, RT_OFFSETOF(NTMTE32, DllBase)),
1223 &uMte2.v32, sizeof(uMte2.v32));
1224 if ( RT_SUCCESS(rc)
1225 && uMte2.v32.DllBase == uMte.v32.DllBase
1226 && uMte2.v32.EntryPoint == uMte.v32.EntryPoint
1227 && uMte2.v32.SizeOfImage == uMte.v32.SizeOfImage
1228 && WINNT32_VALID_ADDRESS(uMte2.v32.InLoadOrderLinks.Flink)
1229 && WINNT32_VALID_ADDRESS(uMte2.v32.BaseDllName.Buffer)
1230 && WINNT32_VALID_ADDRESS(uMte2.v32.FullDllName.Buffer)
1231 && uMte2.v32.BaseDllName.Length <= 128
1232 && uMte2.v32.FullDllName.Length <= 260
1233 )
1234 {
1235 rc = DBGFR3MemRead(pUVM, 0 /*idCpu*/, DBGFR3AddrFromFlat(pUVM, &Addr, uMte2.v32.BaseDllName.Buffer),
1236 u.wsz, uMte2.v32.BaseDllName.Length);
1237 u.wsz[uMte2.v32.BaseDllName.Length / 2] = '\0';
1238 if ( RT_SUCCESS(rc)
1239 && ( !RTUtf16ICmp(u.wsz, g_wszKernelNames[0])
1240 /* || !RTUtf16ICmp(u.wsz, g_wszKernelNames[1]) */
1241 )
1242 )
1243 {
1244 rc = DBGFR3MemRead(pUVM, 0 /*idCpu*/,
1245 DBGFR3AddrFromFlat(pUVM, &Addr, uMte2.v32.InLoadOrderLinks.Blink),
1246 &uMte3.v32, RT_SIZEOFMEMB(NTMTE32, InLoadOrderLinks));
1247 if ( RT_SUCCESS(rc)
1248 && uMte3.v32.InLoadOrderLinks.Flink == MteAddr.FlatPtr
1249 && WINNT32_VALID_ADDRESS(uMte3.v32.InLoadOrderLinks.Blink) )
1250 {
1251 Log(("DigWinNt: MteAddr=%RGv KernelAddr=%RGv SizeOfImage=%x &PsLoadedModuleList=%RGv (32-bit)\n",
1252 MteAddr.FlatPtr, KernelAddr.FlatPtr, uMte2.v32.SizeOfImage, Addr.FlatPtr));
1253 pThis->KernelAddr = KernelAddr;
1254 pThis->KernelMteAddr = MteAddr;
1255 pThis->PsLoadedModuleListAddr = Addr;
1256 pThis->f32Bit = true;
1257 pThis->fNt31 = fNt31;
1258 return true;
1259 }
1260 }
1261 else if (RT_SUCCESS(rc))
1262 {
1263 Log2(("DigWinNt: Wrong module: MteAddr=%RGv ImageAddr=%RGv SizeOfImage=%#x '%ls'\n",
1264 MteAddr.FlatPtr, KernelAddr.FlatPtr, uMte2.v32.SizeOfImage, u.wsz));
1265 break; /* Not NT kernel */
1266 }
1267 }
1268
1269 /* next */
1270 DBGFR3AddrAdd(&HitAddr, 4);
1271 if (HitAddr.FlatPtr < uEnd)
1272 rc = DBGFR3MemScan(pUVM, 0 /*idCpu*/, &HitAddr, uEnd - HitAddr.FlatPtr,
1273 4 /*align*/, &uMte.v32.DllBase, 3 * sizeof(uint32_t), &HitAddr);
1274 else
1275 rc = VERR_DBGF_MEM_NOT_FOUND;
1276 }
1277 }
1278 }
1279 else
1280 {
1281 IMAGE_NT_HEADERS64 const *pHdrs = (IMAGE_NT_HEADERS64 const *)&u.au8[u.MzHdr.e_lfanew];
1282 if ( pHdrs->Signature == IMAGE_NT_SIGNATURE
1283 && pHdrs->FileHeader.Machine == IMAGE_FILE_MACHINE_AMD64
1284 && pHdrs->FileHeader.SizeOfOptionalHeader == sizeof(pHdrs->OptionalHeader)
1285 && pHdrs->FileHeader.NumberOfSections >= 10 /* the kernel has lots */
1286 && (pHdrs->FileHeader.Characteristics & (IMAGE_FILE_EXECUTABLE_IMAGE | IMAGE_FILE_DLL))
1287 == IMAGE_FILE_EXECUTABLE_IMAGE
1288 && pHdrs->OptionalHeader.Magic == IMAGE_NT_OPTIONAL_HDR64_MAGIC
1289 && pHdrs->OptionalHeader.NumberOfRvaAndSizes == IMAGE_NUMBEROF_DIRECTORY_ENTRIES
1290 )
1291 {
1292 /* Find the MTE. */
1293 RT_ZERO(uMte.v64);
1294 uMte.v64.DllBase = KernelAddr.FlatPtr;
1295 uMte.v64.EntryPoint = KernelAddr.FlatPtr + pHdrs->OptionalHeader.AddressOfEntryPoint;
1296 uMte.v64.SizeOfImage = pHdrs->OptionalHeader.SizeOfImage;
1297 DBGFADDRESS ScanAddr;
1298 DBGFADDRESS HitAddr;
1299 rc = DBGFR3MemScan(pUVM, 0 /*idCpu*/, DBGFR3AddrFromFlat(pUVM, &ScanAddr, uStart),
1300 uEnd - uStart, 8 /*align*/, &uMte.v64.DllBase, 5 * sizeof(uint32_t), &HitAddr);
1301 while (RT_SUCCESS(rc))
1302 {
1303 /* Read the start of the MTE and check some basic members. */
1304 DBGFADDRESS MteAddr = HitAddr;
1305 rc = DBGFR3MemRead(pUVM, 0 /*idCpu*/, DBGFR3AddrSub(&MteAddr, RT_OFFSETOF(NTMTE64, DllBase)),
1306 &uMte2.v64, sizeof(uMte2.v64));
1307 if ( RT_SUCCESS(rc)
1308 && uMte2.v64.DllBase == uMte.v64.DllBase
1309 && uMte2.v64.EntryPoint == uMte.v64.EntryPoint
1310 && uMte2.v64.SizeOfImage == uMte.v64.SizeOfImage
1311 && WINNT64_VALID_ADDRESS(uMte2.v64.InLoadOrderLinks.Flink)
1312 && WINNT64_VALID_ADDRESS(uMte2.v64.BaseDllName.Buffer)
1313 && WINNT64_VALID_ADDRESS(uMte2.v64.FullDllName.Buffer)
1314 && uMte2.v64.BaseDllName.Length <= 128
1315 && uMte2.v64.FullDllName.Length <= 260
1316 )
1317 {
1318 /* Try read the base name and compare with known NT kernel names. */
1319 rc = DBGFR3MemRead(pUVM, 0 /*idCpu*/, DBGFR3AddrFromFlat(pUVM, &Addr, uMte2.v64.BaseDllName.Buffer),
1320 u.wsz, uMte2.v64.BaseDllName.Length);
1321 u.wsz[uMte2.v64.BaseDllName.Length / 2] = '\0';
1322 if ( RT_SUCCESS(rc)
1323 && ( !RTUtf16ICmp(u.wsz, g_wszKernelNames[0])
1324 /* || !RTUtf16ICmp(u.wsz, g_wszKernelNames[1]) */
1325 )
1326 )
1327 {
1328 /* Read the link entry of the previous entry in the list and check that its
1329 forward pointer points at the MTE we've found. */
1330 rc = DBGFR3MemRead(pUVM, 0 /*idCpu*/,
1331 DBGFR3AddrFromFlat(pUVM, &Addr, uMte2.v64.InLoadOrderLinks.Blink),
1332 &uMte3.v64, RT_SIZEOFMEMB(NTMTE64, InLoadOrderLinks));
1333 if ( RT_SUCCESS(rc)
1334 && uMte3.v64.InLoadOrderLinks.Flink == MteAddr.FlatPtr
1335 && WINNT64_VALID_ADDRESS(uMte3.v64.InLoadOrderLinks.Blink) )
1336 {
1337 Log(("DigWinNt: MteAddr=%RGv KernelAddr=%RGv SizeOfImage=%x &PsLoadedModuleList=%RGv (32-bit)\n",
1338 MteAddr.FlatPtr, KernelAddr.FlatPtr, uMte2.v64.SizeOfImage, Addr.FlatPtr));
1339 pThis->KernelAddr = KernelAddr;
1340 pThis->KernelMteAddr = MteAddr;
1341 pThis->PsLoadedModuleListAddr = Addr;
1342 pThis->f32Bit = false;
1343 pThis->fNt31 = false;
1344 return true;
1345 }
1346 }
1347 else if (RT_SUCCESS(rc))
1348 {
1349 Log2(("DigWinNt: Wrong module: MteAddr=%RGv ImageAddr=%RGv SizeOfImage=%#x '%ls'\n",
1350 MteAddr.FlatPtr, KernelAddr.FlatPtr, uMte2.v64.SizeOfImage, u.wsz));
1351 break; /* Not NT kernel */
1352 }
1353 }
1354
1355 /* next */
1356 DBGFR3AddrAdd(&HitAddr, 8);
1357 if (HitAddr.FlatPtr < uEnd)
1358 rc = DBGFR3MemScan(pUVM, 0 /*idCpu*/, &HitAddr, uEnd - HitAddr.FlatPtr,
1359 8 /*align*/, &uMte.v64.DllBase, 3 * sizeof(uint32_t), &HitAddr);
1360 else
1361 rc = VERR_DBGF_MEM_NOT_FOUND;
1362 }
1363 }
1364 }
1365 }
1366 }
1367 return false;
1368}
1369
1370
1371/**
1372 * @copydoc DBGFOSREG::pfnDestruct
1373 */
1374static DECLCALLBACK(void) dbgDiggerWinNtDestruct(PUVM pUVM, void *pvData)
1375{
1376 RT_NOREF2(pUVM, pvData);
1377}
1378
1379
1380/**
1381 * @copydoc DBGFOSREG::pfnConstruct
1382 */
1383static DECLCALLBACK(int) dbgDiggerWinNtConstruct(PUVM pUVM, void *pvData)
1384{
1385 RT_NOREF1(pUVM);
1386 PDBGDIGGERWINNT pThis = (PDBGDIGGERWINNT)pvData;
1387 pThis->fValid = false;
1388 pThis->f32Bit = false;
1389 pThis->enmVer = DBGDIGGERWINNTVER_UNKNOWN;
1390
1391 pThis->IWinNt.u32Magic = DBGFOSIWINNT_MAGIC;
1392 pThis->IWinNt.pfnQueryVersion = dbgDiggerWinNtIWinNt_QueryVersion;
1393 pThis->IWinNt.pfnQueryKernelPtrs = dbgDiggerWinNtIWinNt_QueryKernelPtrs;
1394 pThis->IWinNt.pfnQueryKpcrForVCpu = dbgDiggerWinNtIWinNt_QueryKpcrForVCpu;
1395 pThis->IWinNt.pfnQueryCurThrdForVCpu = dbgDiggerWinNtIWinNt_QueryCurThrdForVCpu;
1396 pThis->IWinNt.u32EndMagic = DBGFOSIWINNT_MAGIC;
1397
1398 return VINF_SUCCESS;
1399}
1400
1401
1402const DBGFOSREG g_DBGDiggerWinNt =
1403{
1404 /* .u32Magic = */ DBGFOSREG_MAGIC,
1405 /* .fFlags = */ 0,
1406 /* .cbData = */ sizeof(DBGDIGGERWINNT),
1407 /* .szName = */ "WinNT",
1408 /* .pfnConstruct = */ dbgDiggerWinNtConstruct,
1409 /* .pfnDestruct = */ dbgDiggerWinNtDestruct,
1410 /* .pfnProbe = */ dbgDiggerWinNtProbe,
1411 /* .pfnInit = */ dbgDiggerWinNtInit,
1412 /* .pfnRefresh = */ dbgDiggerWinNtRefresh,
1413 /* .pfnTerm = */ dbgDiggerWinNtTerm,
1414 /* .pfnQueryVersion = */ dbgDiggerWinNtQueryVersion,
1415 /* .pfnQueryInterface = */ dbgDiggerWinNtQueryInterface,
1416 /* .pfnStackUnwindAssist = */ dbgDiggerWinNtStackUnwindAssist,
1417 /* .u32EndMagic = */ DBGFOSREG_MAGIC
1418};
1419
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