writing windbg extensions andre vachon software development lead windows product feedback microsoft...

28
Writing WinDbg Writing WinDbg Extensions Extensions Andre Vachon Andre Vachon Software Development Lead Software Development Lead Windows Product Feedback Windows Product Feedback Microsoft Corporation Microsoft Corporation

Upload: anis-richardson

Post on 31-Dec-2015

224 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: Writing WinDbg Extensions Andre Vachon Software Development Lead Windows Product Feedback Microsoft Corporation

Writing WinDbg ExtensionsWriting WinDbg Extensions

Andre VachonAndre VachonSoftware Development LeadSoftware Development LeadWindows Product FeedbackWindows Product FeedbackMicrosoft CorporationMicrosoft Corporation

Page 2: Writing WinDbg Extensions Andre Vachon Software Development Lead Windows Product Feedback Microsoft Corporation

22

AgendaAgenda

What are Debugger ExtensionsWhat are Debugger Extensions How do they workHow do they work Extension APIsExtension APIs

Legacy debugger extension APIsLegacy debugger extension APIs New DbgEng extension APIsNew DbgEng extension APIs

64-bit64-bit Sample codeSample code

Page 3: Writing WinDbg Extensions Andre Vachon Software Development Lead Windows Product Feedback Microsoft Corporation

33

What Are Debugger ExtensionsWhat Are Debugger Extensions

Lets you write your own debugger commandsLets you write your own debugger commands Great for automationGreat for automation Helps you streamline common debugging operationsHelps you streamline common debugging operations Can help analyze complex structuresCan help analyze complex structures

Simple structures can be dumped and analyzed using the dt Simple structures can be dumped and analyzed using the dt debugger command; No need to write extensions for thisdebugger command; No need to write extensions for this

Complex trees and lists can be displayed, searched, and parsed Complex trees and lists can be displayed, searched, and parsed to show the most commonly used informationto show the most commonly used information

Windows DEV team could not debug the OS without Windows DEV team could not debug the OS without debugger extensionsdebugger extensions Lots of complex structures to look atLots of complex structures to look at Important to help find corruption in structuresImportant to help find corruption in structures We have written hundreds of these: !process, !thread, !handle, !We have written hundreds of these: !process, !thread, !handle, !

teb, !peb, !vadteb, !peb, !vad

Page 4: Writing WinDbg Extensions Andre Vachon Software Development Lead Windows Product Feedback Microsoft Corporation

44

Debugger Extension Debugger Extension Programming ModelProgramming Model Debugger extensions are DLLs loaded by the debugger using LoadLibraryDebugger extensions are DLLs loaded by the debugger using LoadLibrary

Debugger extensions run in the context of the debugger process (WinDbg)Debugger extensions run in the context of the debugger process (WinDbg) Debugger extensions are trusted by the debuggerDebugger extensions are trusted by the debugger

A simple try – except is placed around execution of extensions to recover from AVsA simple try – except is placed around execution of extensions to recover from AVs Heap corruption in an extension will cause the debugger to crashHeap corruption in an extension will cause the debugger to crash

A debugger extension can make calls to A debugger extension can make calls to Debugger interfaces (dbgeng.dll)Debugger interfaces (dbgeng.dll) Calls to any other DLL are risky and should be avoided if possibleCalls to any other DLL are risky and should be avoided if possible Must be careful of interactions between Win32 APIs and dbgeng\dbghelp APIsMust be careful of interactions between Win32 APIs and dbgeng\dbghelp APIs

Calling dbghelp APIs directly can change internal state DbgEng relies onCalling dbghelp APIs directly can change internal state DbgEng relies on Any Win32 API can be called – APIs run in the context of the WinDbg processAny Win32 API can be called – APIs run in the context of the WinDbg process ReadProcessMemory could return different data than calling the debugger to read memory ReadProcessMemory could return different data than calling the debugger to read memory

from the target processfrom the target process

Debugger extensions run on the host debuggerDebugger extensions run on the host debugger In remote debugging scenarios, input\output is sent over the wireIn remote debugging scenarios, input\output is sent over the wire

Page 5: Writing WinDbg Extensions Andre Vachon Software Development Lead Windows Product Feedback Microsoft Corporation

55

Debugger Extension Debugger Extension Execution ModelExecution Model

Host: Debugger ProcessHost: Debugger Process

My Dll 1My Dll 1

My Dll 2My Dll 2

Target/Debuggee ProcessTarget/Debuggee Process

My AppMy App

WinDbgWinDbg

Debugger ExtensionDebugger Extension

UserMode : I . P. C.UserMode : I . P. C.Kernel Mode: Debug PortKernel Mode: Debug Port

No!

ExtensionInterfaces

Page 6: Writing WinDbg Extensions Andre Vachon Software Development Lead Windows Product Feedback Microsoft Corporation

66

Debugger Extension And Debugger Extension And Remote DebuggingRemote Debugging

Remote DebuggerRemote Debugger

WinDbgWinDbg

Host: Debugger ProcessHost: Debugger Process

WinDbgWinDbg

Debugger ExtensionDebugger Extension

ExtensionExtensionInterfacesInterfaces

User InputUser Input

Remote Debugging ProtocolRemote Debugging ProtocolNamed Pipes, TCPNamed Pipes, TCP

Page 7: Writing WinDbg Extensions Andre Vachon Software Development Lead Windows Product Feedback Microsoft Corporation

77

User Mode, Kernel Mode, User Mode, Kernel Mode, Dump FilesDump Files Debugger extension can work with any type or version of targetDebugger extension can work with any type or version of target

The debugger API abstracts the “target” as much as possibleThe debugger API abstracts the “target” as much as possible All basic extension APIs work on live sessions or dump files, user mode or All basic extension APIs work on live sessions or dump files, user mode or

kernel mode targets, and any version of the OSkernel mode targets, and any version of the OS Certain specific operations or data may not make sense on all targetsCertain specific operations or data may not make sense on all targets

ExamplesExamples Breakpoints won’t work on dump filesBreakpoints won’t work on dump files ReadPhysicalMemory is not supported for user mode targetsReadPhysicalMemory is not supported for user mode targets

Debugger extensions must gracefully handle errorsDebugger extensions must gracefully handle errors The debugger package organizes its extensions based on what targets The debugger package organizes its extensions based on what targets

they supportthey support Ext.dll – extensions that work for both user mode and kernel mode (!analyze, !Ext.dll – extensions that work for both user mode and kernel mode (!analyze, !

error, !list)error, !list) Uext.dll – user-mode only extensions (!runaway, !evlog)Uext.dll – user-mode only extensions (!runaway, !evlog) Kext.dll – kernel-mode only extensions (!pci, !process)Kext.dll – kernel-mode only extensions (!pci, !process)

Page 8: Writing WinDbg Extensions Andre Vachon Software Development Lead Windows Product Feedback Microsoft Corporation

88

Legacy (Old) Debugger Legacy (Old) Debugger Extension InterfacesExtension Interfaces Often referred to as Often referred to as Old StyleOld Style or or WDbgExtsWDbgExts extensions extensions Continued to be fully supported by dbgeng.dllContinued to be fully supported by dbgeng.dll Definitions can be found in wdbgexts.hDefinitions can be found in wdbgexts.h Exposes limited functionality that enabled most common featuresExposes limited functionality that enabled most common features

Read and write memoryRead and write memory Current process \ Thread informationCurrent process \ Thread information Expression evaluationExpression evaluation Basic symbol lookupBasic symbol lookup Basic type lookupBasic type lookup Crtl-C/Ctrl-BreakCrtl-C/Ctrl-Break

Extensions functions are called by Extensions functions are called by Asking the debugger engine for a table containing debugger extension Asking the debugger engine for a table containing debugger extension

function pointersfunction pointers Making calls through these function pointersMaking calls through these function pointers

Page 9: Writing WinDbg Extensions Andre Vachon Software Development Lead Windows Product Feedback Microsoft Corporation

99

New Debugger InterfacesNew Debugger Interfaces Often referred to as Often referred to as DbgEngDbgEng style extensions style extensions Debugger engine exposes a new, complete set of interfacesDebugger engine exposes a new, complete set of interfaces

Everything that can be performed by a debugger is exposed by the interfaceEverything that can be performed by a debugger is exposed by the interface Referred to as the Referred to as the DbgEngDbgEng API API WinDbg is built on top of this APIWinDbg is built on top of this API

All debugging capabilities are exposed through dbgeng.dllAll debugging capabilities are exposed through dbgeng.dll

Can write new standalone tools that call the interfaceCan write new standalone tools that call the interface Debugger extension DLLs are generally more convenient in most scenariosDebugger extension DLLs are generally more convenient in most scenarios

Functionality supported by the DbgEng API Functionality supported by the DbgEng API Read and write memoryRead and write memory Current thread and process informationCurrent thread and process information Expression evaluationExpression evaluation Full symbol lookup and enumerationFull symbol lookup and enumeration Full type lookup and enumerationFull type lookup and enumeration General target informationGeneral target information

Extensions functions are called by Extensions functions are called by Creating debug interface objectsCreating debug interface objects Calling the engine interfaces exposed by these objectsCalling the engine interfaces exposed by these objects

BreakpointsBreakpoints Source code supportSource code support Rich output controlRich output control Initialization and instantiationInitialization and instantiation Module enumerationModule enumeration Version informationVersion information Execution controlExecution control

Page 10: Writing WinDbg Extensions Andre Vachon Software Development Lead Windows Product Feedback Microsoft Corporation

1010

Legacy Extension InitializationLegacy Extension Initialization Legacy extension DLLs need to export the following entry points from the DLLLegacy extension DLLs need to export the following entry points from the DLL

WinDbgExtensionDllInit – Required WinDbgExtensionDllInit – Required ExtensionApiVersion – RequiredExtensionApiVersion – Required CheckVersion – OptionalCheckVersion – Optional

The debugger finds entry points using GetProcAddress on the extension DLLThe debugger finds entry points using GetProcAddress on the extension DLL Entry Points are called all DLL initializationEntry Points are called all DLL initialization

No Uninitialize routine in the legacy extension modelNo Uninitialize routine in the legacy extension model

typedef VOIDtypedef VOID(WDBGAPI*PWINDBG_EXTENSION_DLL_INIT)((WDBGAPI*PWINDBG_EXTENSION_DLL_INIT)( PWINDBG_EXTENSION_APIS lpExtensionApis,PWINDBG_EXTENSION_APIS lpExtensionApis, USHORT MajorVersion,USHORT MajorVersion, USHORT MinorVersion);USHORT MinorVersion);

typedef LPEXT_API_VERSIONtypedef LPEXT_API_VERSION(WDBGAPI*PWINDBG_EXTENSION_API_VERSION)((WDBGAPI*PWINDBG_EXTENSION_API_VERSION)( VOID);VOID);

typedef ULONGtypedef ULONG(WDBGAPI*PWINDBG_CHECK_VERSION)((WDBGAPI*PWINDBG_CHECK_VERSION)( VOID);VOID);

Page 11: Writing WinDbg Extensions Andre Vachon Software Development Lead Windows Product Feedback Microsoft Corporation

1111

New Extension InitializationNew Extension Initialization New extension DLLs need to export the following entry points from the DLL New extension DLLs need to export the following entry points from the DLL

DebugExtensionInitializeDebugExtensionInitialize DebugExtensionNotifyDebugExtensionNotify DebugExtensionUninitializeDebugExtensionUninitialize

An extension cannot export both new and old entry points from its DLLAn extension cannot export both new and old entry points from its DLL The debugger finds entry points using GetProcAddress on the extension DLLThe debugger finds entry points using GetProcAddress on the extension DLL DebugExtensionNotify is called when the target is connected or disconnectedDebugExtensionNotify is called when the target is connected or disconnected

typedef HRESULTtypedef HRESULT(CALLBACK* PDEBUG_EXTENSION_INITIALIZE)(CALLBACK* PDEBUG_EXTENSION_INITIALIZE)(OUT PULONG Version, OUT PULONG Flags);(OUT PULONG Version, OUT PULONG Flags);

typedef void typedef void (CALLBACK* PDEBUG_EXTENSION_UNINITIALIZE)(CALLBACK* PDEBUG_EXTENSION_UNINITIALIZE)(void);(void);

typedef void typedef void (CALLBACK* PDEBUG_EXTENSION_NOTIFY)(CALLBACK* PDEBUG_EXTENSION_NOTIFY)(IN ULONG Notify, IN ULONG64 Argument);(IN ULONG Notify, IN ULONG64 Argument);

Page 12: Writing WinDbg Extensions Andre Vachon Software Development Lead Windows Product Feedback Microsoft Corporation

1212

Getting Debugger Extension Getting Debugger Extension APIsAPIs Legacy debugger extensions get legacy extension interfaces (function Legacy debugger extensions get legacy extension interfaces (function

pointers) during initialization as part of init call (param1)pointers) during initialization as part of init call (param1) Pointers must be cached in a global variable named Pointers must be cached in a global variable named ExtensionApisExtensionApis

New debugger extensions get new debugger interfaces by callingNew debugger extensions get new debugger interfaces by calling DebugCreate(__uuidof (IDebugClient), &DebugClient))DebugCreate(__uuidof (IDebugClient), &DebugClient)) DebugClient->QueryInterface(_uuidof(DebugClient->QueryInterface(_uuidof(Interface_you_want)Interface_you_want)

New debugger extensions can also query for the legacy New debugger extensions can also query for the legacy extension interfacesextension interfaces Legacy extension interfaces can not be remotedLegacy extension interfaces can not be remoted DebugClient->QueryInterface(_uuidof(IDebugControl), &DebugControl)DebugClient->QueryInterface(_uuidof(IDebugControl), &DebugControl) DebugControl->GetWindbgExtensionApis64(&ExtensionApis);DebugControl->GetWindbgExtensionApis64(&ExtensionApis);

Page 13: Writing WinDbg Extensions Andre Vachon Software Development Lead Windows Product Feedback Microsoft Corporation

1313

Input – Argument ParsingInput – Argument Parsing Debugger extensions receive arguments as one long Debugger extensions receive arguments as one long

text stringtext string Extensions can parse parameters any way they wantExtensions can parse parameters any way they want Extension will be given all output up to a ‘;’ character, Extension will be given all output up to a ‘;’ character,

unless quotedunless quoted ‘‘;’is a delimiter between multiple, independent debugger commands;’is a delimiter between multiple, independent debugger commands

Debugger provides routines to help parse argumentsDebugger provides routines to help parse arguments Legacy Interfaces: Legacy Interfaces: GetExpression(), GetExpressionEXGetExpression(), GetExpressionEX New interfaces: Evaluate()New interfaces: Evaluate() These interfaces do both argument parsing These interfaces do both argument parsing andand evaluation evaluation

of argumentsof arguments Strings will be treated as symbolStrings will be treated as symbol ‘‘-’ will be treated as minus-’ will be treated as minus

RecommendationsRecommendations Add /h to provide helpAdd /h to provide help

Page 14: Writing WinDbg Extensions Andre Vachon Software Development Lead Windows Product Feedback Microsoft Corporation

1414

OutputOutput

Standard debugger extension output is text-basedStandard debugger extension output is text-based Output control, Extension functions are common exceptionsOutput control, Extension functions are common exceptions Extensions can generate their own UI – not recommendedExtensions can generate their own UI – not recommended

Standard output format very similar to C-runtimeStandard output format very similar to C-runtime %s, %d, specifiers, etc%s, %d, specifiers, etc Special Special pointerpointer specifier %p specifier %p

Always consumes 64 bit input (always use ULONG64)Always consumes 64 bit input (always use ULONG64) Prints 32 or 64 bits based on the target OSPrints 32 or 64 bits based on the target OS

Legacy InterfaceLegacy Interface

New InterfaceNew Interface

#define dprintf (ExtensionApis.lpOutputRoutine);#define dprintf (ExtensionApis.lpOutputRoutine);Dprintf(“pointer =%p, string=%s”, (ULONG64) pointer, Dprintf(“pointer =%p, string=%s”, (ULONG64) pointer,

(LPSTR string);(LPSTR string);

g_ExtControl->Output(Mask, Format,...);g_ExtControl->Output(Mask, Format,...);

Page 15: Writing WinDbg Extensions Andre Vachon Software Development Lead Windows Product Feedback Microsoft Corporation

1515

Output ControlOutput Control The debugger interfaces have rich support for output control; The debugger interfaces have rich support for output control;

What is it ?What is it ? Allows the application to capture or modify output before it gets displayedAllows the application to capture or modify output before it gets displayed Allows for special formatting in windows, such as the stack windowAllows for special formatting in windows, such as the stack window Allows filtering to only display certain types of messages (errors, Allows filtering to only display certain types of messages (errors,

warnings)warnings) KD and WinDbg use output control. Can also be used by extensionsKD and WinDbg use output control. Can also be used by extensions

OutputControl is associated with a client (queried interfaces)OutputControl is associated with a client (queried interfaces) Extensions should respect output control setup by these applicationsExtensions should respect output control setup by these applications

If extensions don’t have specific output control needs, they should inherit If extensions don’t have specific output control needs, they should inherit them from the callerthem from the caller

A new style extension should query interfaces each time an extension API A new style extension should query interfaces each time an extension API is called (and then release them at the end of each call) to inherit the is called (and then release them at the end of each call) to inherit the OutputControl from the calling threadOutputControl from the calling thread

Page 16: Writing WinDbg Extensions Andre Vachon Software Development Lead Windows Product Feedback Microsoft Corporation

1616

Symbol LookupSymbol Lookup Use symbols to lookup data in your driverUse symbols to lookup data in your driver Always use a module qualifier when evaluating a symbolAlways use a module qualifier when evaluating a symbol

Example: Example: mydriver!datamydriver!data Without a module qualifier, the debugger will load all symbol files until it Without a module qualifier, the debugger will load all symbol files until it

finds a module with a symbol finds a module with a symbol datadata Avoid caching evaluated symbols (in global variables)Avoid caching evaluated symbols (in global variables)

Driver can load and unload, and extensions are Driver can load and unload, and extensions are notnot notified of such notified of such events; Once a PDB is loaded, a symbol lookup is not very expensiveevents; Once a PDB is loaded, a symbol lookup is not very expensive

Legacy interfacesLegacy interfaces Get an address from a name: Get an address from a name: GetExpression()GetExpression() Get a name from an address: Get a name from an address: GetSymbol()GetSymbol()

New InterfacesNew Interfaces Get an address from a name: Get an address from a name: Evaluate(), GetOffsetByName()Evaluate(), GetOffsetByName() Get a name from an address: Get a name from an address: GetNameByOffset()GetNameByOffset()

Page 17: Writing WinDbg Extensions Andre Vachon Software Development Lead Windows Product Feedback Microsoft Corporation

1717

Reading MemoryReading Memory Most code uses the built-in ReadMemory macro with legacy debugger Most code uses the built-in ReadMemory macro with legacy debugger

extension interfaces for memory readingextension interfaces for memory reading Reading raw memory should be a rare occurrence in a debugger extensionReading raw memory should be a rare occurrence in a debugger extension Use more structured memory reading operationsUse more structured memory reading operations

These APIs read memory on the target process \ machineThese APIs read memory on the target process \ machine

To read data that will be interpreted as pointers, useTo read data that will be interpreted as pointers, use

#define ReadMemory (ExtensionApis.lpReadProcessMemoryRoutine)#define ReadMemory (ExtensionApis.lpReadProcessMemoryRoutine)Typedef ULONG (WDBGAPI*PWINDBG_READ_PROCESS_MEMORY_ROUTINE64)(Typedef ULONG (WDBGAPI*PWINDBG_READ_PROCESS_MEMORY_ROUTINE64)( ULONG64 offset,ULONG64 offset, PVOID lpBuffer,PVOID lpBuffer, ULONG cb,ULONG cb, PULONG lpcbBytesRead);PULONG lpcbBytesRead);IDebugDataSpaces STDMETHOD(ReadVirtual)(IDebugDataSpaces STDMETHOD(ReadVirtual)( THIS_THIS_ IN ULONG64 Offset,IN ULONG64 Offset, OUT PVOID Buffer,OUT PVOID Buffer, IN ULONG BufferSize,IN ULONG BufferSize, OUT OPTIONAL PULONG BytesRead);OUT OPTIONAL PULONG BytesRead);

ReadPointer(ULONG64 Address, PULONG64 Pointer);ReadPointer(ULONG64 Address, PULONG64 Pointer);

Page 18: Writing WinDbg Extensions Andre Vachon Software Development Lead Windows Product Feedback Microsoft Corporation

1818

64-Bit Support64-Bit Support Everything in the debugger and debugger extension are designed Everything in the debugger and debugger extension are designed

around 64-bit supportaround 64-bit support All recent debugger APIs treat addresses as 64-bit valuesAll recent debugger APIs treat addresses as 64-bit values All pointers are passed as ULONG64All pointers are passed as ULONG64 Debugger manipulates all addresses as 64-bit valuesDebugger manipulates all addresses as 64-bit values

Debugger extensions should tooDebugger extensions should too 32-bit addresses read from a 32-bit target need to be SIGN-EXTENDED32-bit addresses read from a 32-bit target need to be SIGN-EXTENDED

Why ?Why ? We use 32 bit machines to debug 64 bit targetsWe use 32 bit machines to debug 64 bit targets

On 32 bits On 32 bits *anything*anything = 4 bytes = 4 bytes On 64 bits On 64 bits *anything*anything = 8 bytes = 8 bytes If we used Pointers to store addresses, we would always lose the top 4 bytes of If we used Pointers to store addresses, we would always lose the top 4 bytes of

addresses coming back from 64-bit targetsaddresses coming back from 64-bit targets

#define KDEXT_64BIT required before including wdbgexts.h#define KDEXT_64BIT required before including wdbgexts.h Set Version number to EXT_API_VERSION_NUMBER64Set Version number to EXT_API_VERSION_NUMBER64

Page 19: Writing WinDbg Extensions Andre Vachon Software Development Lead Windows Product Feedback Microsoft Corporation

1919

64 Bits And Structures64 Bits And Structures On a 32-bit machine (x86)On a 32-bit machine (x86)

PVOID is 32 bitsPVOID is 32 bits ULONG is 32 bitsULONG is 32 bits ULONG64 is 64 bitsULONG64 is 64 bits

On a 64-bit machine (amd64, IA64)On a 64-bit machine (amd64, IA64) PVOID is 64 bitsPVOID is 64 bits ULONG is 32 bitsULONG is 32 bits ULONG64 is 64 bitsULONG64 is 64 bits

Debugger extensions are compiled Debugger extensions are compiled executable code running on the executable code running on the HOSTHOST Host uses one size or the other Host uses one size or the other

To support 64-bit debugging, a 32 To support 64-bit debugging, a 32 bit host must be able to debug a bit host must be able to debug a 64-bit target64-bit target

How to deal with this problem?How to deal with this problem? TypeType InformationInformation

typedef struct {typedef struct { 32-bit struct 32-bit struct offsetoffset

64-bit struct 64-bit struct offsetoffset

DWORD size;DWORD size; 00 00

PVOID ptr1;PVOID ptr1; 44 88

PVOID ptr1;PVOID ptr1; 88 1616

ULONG u1;ULONG u1; 1212 2424

ULONG u2;ULONG u2; 1616 2828

PVOID ptr3;PVOID ptr3; 2020 3232

} FOO} FOO

Page 20: Writing WinDbg Extensions Andre Vachon Software Development Lead Windows Product Feedback Microsoft Corporation

2020

What Is Type InformationWhat Is Type Information Type information refers to the encoding of the structure definitions Type information refers to the encoding of the structure definitions

(structs, classes) by the compiler and linker(structs, classes) by the compiler and linker Only structured types are storedOnly structured types are stored Strings for constants (#define) are not saved in the PDB; They are thrown Strings for constants (#define) are not saved in the PDB; They are thrown

away by the preprocessoraway by the preprocessor EnumEnum are saved by the latest compiler and linker are saved by the latest compiler and linker Only data actually used by the code (Enum, structures) are stored in Only data actually used by the code (Enum, structures) are stored in

the PDBthe PDB Type information is data stored in the PDB fileType information is data stored in the PDB file

One of the data streams stored in the PDB fileOne of the data streams stored in the PDB file Always saved away by the compiler and linkerAlways saved away by the compiler and linker PDB is regenerated with every linking of an imagePDB is regenerated with every linking of an image PDBs released by Microsoft do not contain type information in the PDBs released by Microsoft do not contain type information in the

general casegeneral case PDBs are “stripped” before being releasedPDBs are “stripped” before being released

Type information is too largeType information is too large Type information contains lots of Intellectual propertyType information contains lots of Intellectual property

Some type information is re-added to certain binaries, like ntoskrnl.exe, to support Some type information is re-added to certain binaries, like ntoskrnl.exe, to support debugger extensionsdebugger extensions

Page 21: Writing WinDbg Extensions Andre Vachon Software Development Lead Windows Product Feedback Microsoft Corporation

2121

Using Type InformationUsing Type Information

Type information solves the 32/64-bit issue for debugger Type information solves the 32/64-bit issue for debugger extensionsextensions Dynamically use the type descriptions stored in the PDB to Dynamically use the type descriptions stored in the PDB to

analyze the data structures read from the targetanalyze the data structures read from the target

This works becauseThis works because The debugger treats all addresses as 64 bits and truncates The debugger treats all addresses as 64 bits and truncates

appropriately when reading from a 32-bit targetappropriately when reading from a 32-bit target Compiler and linker keep the same type names, whether Compiler and linker keep the same type names, whether

compiling compiling 32 or 64 bits32 or 64 bits

Symbol files are matched up to the target codeSymbol files are matched up to the target code

LimitationsLimitations Requires good symbols – few developers look at debugging Requires good symbols – few developers look at debugging

sessions without good symbols anywaysessions without good symbols anyway

Page 22: Writing WinDbg Extensions Andre Vachon Software Development Lead Windows Product Feedback Microsoft Corporation

2222

Using Type InformationUsing Type Information Legacy Legacy GetFieldValue()GetFieldValue() command command

Macro in wdbgexts.hMacro in wdbgexts.h

Legacy Legacy InitTypeRead()InitTypeRead() and and ReadField()ReadField() commands commands Used when large structures need to be read\analyzedUsed when large structures need to be read\analyzed Code simplification over Code simplification over GetFieldValue()GetFieldValue() InitTypeRead()InitTypeRead() sets some global state about the current data structure sets some global state about the current data structure ReadField()ReadField() reads a field of that structure from the target into a local reads a field of that structure from the target into a local

variablevariable New Interfaces have numerous APIs to enumerate types and New Interfaces have numerous APIs to enumerate types and

variablesvariables The The IDebugSymbolsIDebugSymbols class encapsulates these routines class encapsulates these routines

All TARGET addresses and pointers in a debugger extension must All TARGET addresses and pointers in a debugger extension must Be signed extended if coming from 32 bitBe signed extended if coming from 32 bit Be stored as ULONG64Be stored as ULONG64 Use Use ReadPointer()ReadPointer() and and GetFieldValue()GetFieldValue()

GetFieldValue(ULONG64 Address, LPSTR Type, LPSTR Field, ULONG64 Value);GetFieldValue(ULONG64 Address, LPSTR Type, LPSTR Field, ULONG64 Value);

Page 23: Writing WinDbg Extensions Andre Vachon Software Development Lead Windows Product Feedback Microsoft Corporation

2323

Control–CControl–C

Control-C handling is shared between the core debugger Control-C handling is shared between the core debugger code and the extensioncode and the extension Generate by Ctrl-C in command line debuggers, Ctrl-Break in Generate by Ctrl-C in command line debuggers, Ctrl-Break in

WinDbgWinDbg

Debugger engine willDebugger engine will The IO thread in the debugger will receive the Ctrl-CThe IO thread in the debugger will receive the Ctrl-C The engine stores the state of this event in a global variableThe engine stores the state of this event in a global variable

Debugger extension must check this stateDebugger extension must check this state Only one thread in the debugger processes command; Only one thread in the debugger processes command;

The debugger extension takes over this threadThe debugger extension takes over this thread Debugger can not kill the extension threadDebugger can not kill the extension thread

Debugger extension must call the engine to check the state and Debugger extension must call the engine to check the state and exit its processingexit its processing

Page 24: Writing WinDbg Extensions Andre Vachon Software Development Lead Windows Product Feedback Microsoft Corporation

2424

Extension FunctionsExtension Functions Most extensions commands run from the debugger generate Most extensions commands run from the debugger generate

text outputtext output Example: !pool, !process, !analyzeExample: !pool, !process, !analyze

The debugger also supports debugger extensions functionsThe debugger also supports debugger extensions functions Example: _EFN_GetPoolDataExample: _EFN_GetPoolData Output : ‘C’ data structure that can be consumed by the callerOutput : ‘C’ data structure that can be consumed by the caller Extension functions are defined in extsfns.hExtension functions are defined in extsfns.h Allows powerful extensions to be built using other debugger extensions, Allows powerful extensions to be built using other debugger extensions,

without text parsingwithout text parsing Exported from a DLL like other extension commandsExported from a DLL like other extension commands

_EFN_ is the convention for exporting these functions to distinguish them from _EFN_ is the convention for exporting these functions to distinguish them from normal debugger extension commandsnormal debugger extension commands

Debugger engine automatically appends this prefixDebugger engine automatically appends this prefix GetExtensionFunctionGetExtensionFunction equivalent to equivalent to GetProcAddressGetProcAddress

g_ExtControl->GetExtensionFunction(0, "GetPoolData",(FARPROC*)&pGetPoolData);g_ExtControl->GetExtensionFunction(0, "GetPoolData",(FARPROC*)&pGetPoolData);(*pGetPoolData)((PDEBUG_CLIENT)g_ExtClient, Pool, pPoolData);(*pGetPoolData)((PDEBUG_CLIENT)g_ExtClient, Pool, pPoolData);

Page 25: Writing WinDbg Extensions Andre Vachon Software Development Lead Windows Product Feedback Microsoft Corporation

2525

How To Get StartedHow To Get Started All documentation about existing debugger extensions (!pool, !All documentation about existing debugger extensions (!pool, !

thread, !process) is in the basic debugger documentationthread, !process) is in the basic debugger documentation Installed by default in the root of the debugger in Installed by default in the root of the debugger in debugger.chmdebugger.chm

All documentation about debugger extension APIs and all debugger All documentation about debugger extension APIs and all debugger extension code samples are part of the debuggerextension code samples are part of the debugger NotNot installed by default – you must select the “SDK” component when installed by default – you must select the “SDK” component when

doing the debugger installdoing the debugger install Docs are called Docs are called debugext.chm debugext.chm (only partially done at this time)(only partially done at this time) Samples are stored by default under the samples directorySamples are stored by default under the samples directory

Use the samples we provideUse the samples we provide SimpleextSimpleext

Uses legacy extension APIsUses legacy extension APIs Dumps basic data structuresDumps basic data structures

ExtsExts Uses new DbgEng APIUses new DbgEng API

Page 26: Writing WinDbg Extensions Andre Vachon Software Development Lead Windows Product Feedback Microsoft Corporation

2626

New Style Or Legacy Style New Style Or Legacy Style Extensions?Extensions? Legacy extensions work fine in the new debuggerLegacy extensions work fine in the new debugger

No extension DLL is required to switch to new style interfacesNo extension DLL is required to switch to new style interfaces

Legacy extensions require a little less code to writeLegacy extensions require a little less code to write More simple macros are availableMore simple macros are available Initialization is a little less complexInitialization is a little less complex Great for very simple codeGreat for very simple code

New extension APIs Provide more flexibility and featuresNew extension APIs Provide more flexibility and features Many more featuresMany more features Fine grain control over debugger behaviorFine grain control over debugger behavior Can still use legacy interfaces and macros for part of the codeCan still use legacy interfaces and macros for part of the code Recommend using C++ for new style extensionsRecommend using C++ for new style extensions

Page 27: Writing WinDbg Extensions Andre Vachon Software Development Lead Windows Product Feedback Microsoft Corporation

2727

ResourcesResources

Debugger URL and download siteDebugger URL and download site http://www.microsoft.com/whdc/ddk/debugginghttp://www.microsoft.com/whdc/ddk/debugging

Debugger e-mail – for debugger bug reports Debugger e-mail – for debugger bug reports and feature requestsand feature requests windbgfbwindbgfb @ microsoft.com @ microsoft.com We try to fix all the bugs people reportWe try to fix all the bugs people report We do not provide general debugging support on We do not provide general debugging support on

this aliasthis alias

Debugger newsgroupDebugger newsgroup Microsoft.public.windbgMicrosoft.public.windbg Good place for general debugging issuesGood place for general debugging issues

Page 28: Writing WinDbg Extensions Andre Vachon Software Development Lead Windows Product Feedback Microsoft Corporation