Archive for the ‘Windows internals’ Category

Object Tracking and WinDBG

Wednesday, August 25th, 2010

The Object Manager (Ob) in Windows provides and excellent feature called object tracking, which causes the Ob to maintain a list of every active object in the system. When activated, it allows you to find every driver object, event object, file object, mutex object, etc. at any point in time via the !object command. While the overhead of this is likely to be unacceptable for everyday use, in certain debugging situations it can be immensely helpful. For example, I recently debugged an issue where autochk would not run when our file system filter was installed on the system. I suspected that  a rogue file object was preventing NTFS from dismounting, so I turned on object tracking in order to quickly find the file object causing the problem (turned out to be multiple file objects).

Unfortunately things have changed in Windows 7 and the debugging tools haven’t caught up so this no longer works, but I’ll provide a solution to that once I get there…

Enabling Object Tracking

Object tracking is enabled via the FLG_MAINTAIN_OBJECT_TYPELIST GFlags option. You can enable this via the GFlags utility on the target machine, but I prefer to do it via the debugger on a per-boot basis so that I don’t have to remember to shut it off:

1: kd> !gflag + otl
Current NtGlobalFlag contents: 0x00004000
    otl - Maintain a list of objects for each type

Important note: This must be done very early in the boot process before the Ob initializes. I recommend setting an initial break in the debugger by using the WinDBG command CTRL+ALT+K and using the !gflag command at the initial break.

Once you’ve enabled the command, just hit Go and proceed to run whatever tests or do whatever you like. Once you’re ready to start inspecting objects, the path you will take will differ on Vista (and earlier) and Windows 7.

Dumping Objects Prior To Win7

Prior to Win7, life is fairly straightforward as the !object command supports walking the object list. The syntax for the command is:

!object 0 Name

Where Name is documented to be:

Name
If the first argument is zero, the second argument is interpreted as the name of a class of system objects for which to display all instances.

So, for example:

!object 0 File
!object 0 Event
!object 0 Semaphore
!object 0 Device
!object 0 Driver

Any of these will dump out all of the objects of that particular type and you can then pick through and do whatever it is you do with that information.

Dumping Objects on Win7

Now for the fun part. If you attempt to run any of the above !object  commands on a Win7 target, you’ll get the following error:

1: kd> !object 0 File
Scanning 723 objects of type 'File'
WARNING: Object header 83d8bb48 flag (42) does not have
OB_FLAG_CREATOR_INFO (4) set

The problem is that starting with Win7, that flag no longer exists. Instead, the object header tracks whether or not this feature is enabled via another field in the header. So, unfortunately, the Ob changed but the !object command wasn’t updated to reflect the changes.

We can get this back though from a gratuitously complicated debugger command that walks the list starting at an entry. Finding the starting entry could be simplified, but I’ll make you find it manually because that’s how I did it when I wrote the script and I don’t want to make it too easy on you :)

Also, I’ll apologize in advance for the script being on a single line and thus guaranteeing that it will require some sort of WinDBG Rosetta Stone in order to decipher (again, because that’s how I did it when I wrote it…Job security!).

First, you’ll need to dump the global type variable for the type of objects you want to see. Examples of these are IoFileObjectType, ExEventObjectType, IoDriverObjectType, etc. (if you’re having trouble finding the name of the one you want just let me know). I’ll pick the file object type:

1: kd> x nt!iofileobjecttype
82775a54 nt!IoFileObjectType = 0x83d656e0
1: kd> dt nt!_object_type 0x83d656e0
   +0x000 TypeList         : _LIST_ENTRY [ 0x83d8bb38 - 0x846022d0 ]
   +0x008 Name             : _UNICODE_STRING "File"
   +0x010 DefaultObject    : 0x0000005c Void
   +0x014 Index            : 0x1c ''
   +0x018 TotalNumberOfObjects : 0x2d3
   +0x01c TotalNumberOfHandles : 0xaa
   +0x020 HighWaterNumberOfObjects : 0x691
   +0x024 HighWaterNumberOfHandles : 0xb6
   +0x028 TypeInfo         : _OBJECT_TYPE_INITIALIZER
   +0x078 TypeLock         : _EX_PUSH_LOCK
   +0x07c Key              : 0x656c6946
   +0x080 CallbackList     : _LIST_ENTRY [ 0x83d65760 - 0x83d65760 ] 

Note the TypeList field. That’s the list of currently valid objects for that type in the system in the form of OBJECT_HEADER_CREATOR_INFO structures, which currently exist directly before the object header. So, TypeList entry address + sizeof(OBJECT_HEADER_CREATOR_INFO) + FIELD_OFFSET(OBJECT_HEADER, Body) is where the actual object address is. I’ll put that all together into the following command (I’m going to break it up C style with “\” characters so you can see it, please remove before actually using and make into a single line):

r @$t0 = @@(sizeof(nt!_object_header_creator_info) \
+ #FIELD_OFFSET(nt!_object_header, Body)); \
!list "-x \".block {as /x Res @$extret+@$t0} ;\
.block{.echo ${Res}; !object ${Res}} ; \
ad /q Res\" 0x83d8bb38" 

Note that the address used at the end of the command is from the dt output above in bold. Also remember that it’s written to occupy a single line, so it needs to get pasted into the KD prompt with no newlines and those backslashes removed. Running the command should provide you with relatively the same output at the old !object command on previous O/S releases.

If you’d like to clean up the script or, even better, turn it into a debugger extension that takes a name like !object, please let me know or send along the results. Right now it’s on my ever increases prioritized list of things to do and I’d like to take it off :)

Checked out The NT Insider digital edition yet?

Wednesday, August 18th, 2010

We’ve finally gone digital with The NT Insider! You can grab the PDF here and read about all sorts of interesting topics (writing file system filter drivers, debugger extensions, and virtual storage miniports, to name a few).

DPCs execute on their own call stack (x86 Edition)

Thursday, April 29th, 2010

Deferred Procedure Call (DPCs) are callbacks to an arbitrary thread context at IRQL DISPATCH_LEVEL. There is a DPC queue per processor, and queueing a DPC performs two steps:

1) Inserts the DPC onto the DPC queue of the current processor.

2) Requests a DISPATCH_LEVEL software interrupt on the current processor.

Note that there are exceptions to both of those, though I’m not interested in talking about them at this moment

When the operating system is about to return to an IRQL < DISPATCH_LEVEL, the DISPATCH_LEVEL software interrupt is delivered to the processor. On XP, the ISR for this interrupt is hal!HalpDispatchInterrupt, which does some interrupt management work and calls nt!KiDispatchInterrupt. You can get a feel for how this works by setting a breakpoint on KiDispatchInterrupt and checking out a few call stacks, which should look like the following:

kidispatch

While KiInterruptDispatch serves a few different purposes, for our discussion all we care about is the beginning of the function shown here:

kidispatch_asm

Note the call near the end of the listing to nt!KiRetireDpcList. This is the function that will sit in a loop dequeing DPCs from the current processor’s DPC queue and calling the callbacks. There’s some interesting code leading up to that call though, so let’s go line by line and figure out exactly what this code is doing.

nt!KiDispatchInterrupt:
mov     ebx,dword ptr fs:[1Ch]

This line is moving the contents of offset 0x1c from the far segment into EBX. In kernel mode, the base of the far segment is the base address of what is called the PCR for the current processor:

fs_pcr

Thus, this code is grabbing whatever field is at offset 0x1c from the base of the PCR structure. Luckily we have the type information for the PCR, which is nt!_KPCR so we can easily see what is at that offset in the structure:

pcr_1c

That is the SelfPcr field, which is just the flat address of the PCR (in this case that would be 0xffdff000). Let’s move on to the next fragment:

nt!KiDispatchInterrupt+0x7:
lea  eax,[ebx+980h]
cli
cmp  eax,dword ptr [eax]
je   nt!KiDispatchInterrupt+0x2f (805459df)

Here, we add 0×980 to the base address of the PCR and store the result in EAX. We then disable interrupts on the current processor and check to see if the contents of the pointer match the pointer address.

The CMP instruction will do a logical subtract of the two values and set the Z-Flag to one if the result is zero, which would mean that the two values are the same. The JE instruction will, “Jump if the Z-Flag Equals one”, so if the contents of the pointer match the address of the pointer then this code will jump over the code segment that calls KiRetireDpcList.

If you’ve never looked at much assembly that might seem a bit weird, so let’s see what’s add offset 0×980 from the PCR and see if we can figure out what this code is doing.

If you go to a full listing of the PCR structure, you’ll notice that the last offset given is 0×120 and that is the PrcbData field:

pcr_prcb

Thus, in order to figure out what’s at offset 0×980 from the base of the PCR we’ll need to go to offset 0×860 into the PRCB. We’ll find this by doing a dt nt!_kprcb and scanning the output:

prcb_queue

Aha! That field is labeled as the DpcListHead (a.k.a. the DPC queue) and the type is a LIST_ENTRY, which is the standard type for a doubly linked list in the kernel.

LIST_ENTRY structures have two fields, a Flink field that points to the next entry and a Blink field that points to the previous entry. When a list is empty, the Flink field points back to the address of the head of the list. So our previous check above is testing the value of the Flink field against the address of the list head, in other words it is checking to see if the list is empty. If it is, the code avoids draining the DPC queue (which makes sense).

If the list is not empty, then the code sets up to call KiRetireDpcList:

nt!KiDispatchInterrupt+0x12:
push    ebp
push    dword ptr [ebx]
mov     dword ptr [ebx],0FFFFFFFFh
mov     edx,esp
mov     esp,dword ptr [ebx+988h]
push    edx
mov     ebp,eax
call    nt!KiRetireDpcList (80545e0e)

I’m going to save the first three instructions for another time if I ever get to talk about Structured Exception Handling (SEH). Right now it’s sufficient to set that the code there prevents kernel mode exceptions from being raised to user mode exception handlers.

The next two instructions are interesting though:

mov     edx,esp
mov     esp,dword ptr [ebx+988h]

Note that the code saves the current stack pointer and then overwrites ESP with a different pointer value from the PCR. We saw previously that the last offset in the PCR is 0×120, which is the beginning of the PRCB. So, whatever value is at offset 0×868 from the PRCB is what we put into the stack pointer register. If you scroll up to the previous graphic, you’ll see that field labeled as DpcStack:

   +0x868 DpcStack         : Ptr32 Void

Thus, each processor has its own DPC stack that is used when DPCs are executed. Shortly this is going to lead to an unexpected problem that this post will hopefully help you solve.

Lastly, the old stack pointer is pushed onto the stack and finally the call to KiRetireDpcList occurs. When it completes, the old stack is restored and all is right in the World.

However, there’s an interesting issue that can arise in your crash analysis. What if the system crashes inside a DPC? Due to the stack swap that occurs in KiRetireDpcList you’ll get this when you try to dump the call stack:

stackswapped

In other words, you’ll get a listing for the DPC stack and you won’t necessarily be able to see the actual kernel stack of the current thread. While in 99% of the cases the DPC stack will be the only stack that you care about, there’s that 1% where knowing the current thread stack will provide the insight necessary to solve the crash (in almost 10 years I’ve seen two). Luckily, it’s going to be relatively straightforward to get the stack back. Even more luckily, it’s mostly formulaic so even if you’re not sure why you can get it back you’ll still be able to :)

First thing you need is the old stack pointer, which is the first thing on the stack before the return address in the call to nt!KiRetireDpcList:

oldesp

Then we’re going to dump this out with the dps command and find the return address to hal!HalpDispatchInterrupt that the nt!KiDispatchInterrupt will return to. We’ll also want the first thing on the stack after the return address:

prevebp_halp

In my case, I have 0xf715da0c and hal!HalpDispatchInterrupt+0xbb. Now all that’s left is to feed those two values into the special k syntax that allows you to specify your own EBP, ESP, and EIP overrides:

origstack

Note that there’s a cheater shortcut, I could have just done k = f715da00 f715da00 @eip in this case and gotten a slightly busted but still legible stack. The technique above gives a more attractive and correct stack in the end

Possibly we can cover why this command works in the future, but for now hopefully that’s enough of a guide for you to go experiment yourselves. Don’t forget that you can always play with this on a live system where you can verify your results by simply stepping out of nt!KiRetireDpcList.

Random Other Points

1) The DISPATCH_LEVEL software interrupt isn’t always requested, so the DPC isn’t always drained when returning to an IRQL < DISPATCH_LEVEL.

2) The Idle thread also checks the DPC queue and, if it isn’t empty, drains the queue by dequeueing entries and calling the callbacks. In this case, the DPCs execute on the Idle thread’s stack

3) It is possible to target a DPC to a processor other than the current processor

Undocumented !verifier flags value (!verifier 0×200)

Wednesday, April 14th, 2010

Starting with Windows Vista, Driver Verifier has been updated to include circular trace buffers for interesting events. My favorite up until this point has been the pool allocate and free log, which records the call stack, calling thread, and address of pool allocations and frees. If the system then crashes due to a double free or access to a freed pool block, the debugger’s !verifier 0×80 command can be used to dump the alloc/free log. Even better, the command takes an optional address value that will show only the allocations and frees of the pool block containing that address.

You can see the results in this example from the WinDBG docs:

0: kd> !verifier 80 a2b1cf20
Parsing 00004000 array entries, searching for address a2b1cf20.
=======================================
Pool block a2b1ce98, Size 00000168, Thread a2b1ce98
808f1be6 ndis!ndisFreeToNPagedPool+0x39
808f11c1 ndis!ndisPplFree+0x47
808f100f ndis!NdisFreeNetBufferList+0x3b
8088db41 NETIO!NetioFreeNetBufferAndNetBufferList+0xe
8c588d68 tcpip!UdpEndSendMessages+0xdf
8c588cb5 tcpip!UdpSendMessagesDatagramsComplete+0x22
8088d622 NETIO!NetioDereferenceNetBufferListChain+0xcf
8c5954ea tcpip!FlSendNetBufferListChainComplete+0x1c
809b2370 ndis!ndisMSendCompleteNetBufferListsInternal+0x67
808f1781 ndis!NdisFSendNetBufferListsComplete+0x1a
8c04c68e pacer!PcFilterSendNetBufferListsComplete+0xb2
809b230c ndis!NdisMSendNetBufferListsComplete+0x70
8ac4a8ba test1!HandleCompletedTxPacket+0xea
=======================================
Pool block a2b1ce98, Size 00000164, Thread a2b1ce98
822af87f nt!VerifierExAllocatePoolWithTagPriority+0x5d
808f1c88 ndis!ndisAllocateFromNPagedPool+0x1d
808f11f3 ndis!ndisPplAllocate+0x60
808f1257 ndis!NdisAllocateNetBufferList+0x26
80890933 NETIO!NetioAllocateAndReferenceNetBufferListNetBufferMdlAndData+0x14
8c5889c2 tcpip!UdpSendMessages+0x503
8c05c565 afd!AfdTLSendMessages+0x27
8c07a087 afd!AfdTLFastDgramSend+0x7d
8c079f82 afd!AfdFastDatagramSend+0x5ae
8c06f3ea afd!AfdFastIoDeviceControl+0x3c1
8217474f nt!IopXxxControlFile+0x268
821797a1 nt!NtDeviceIoControlFile+0x2a
8204d16a nt!KiFastCallEntry+0x127

In the output, the most recent event is at the top. Thus, here you can see that the buffer was allocated with ndisAllocateFromNPagedPool and freed with ndisAllocateFromNPagedPool.

In addition to the pool allocation log, !verifier 0×100 shows the IRP log, which logs all IoCallDriver, IoCompleteRequest, and IoCancelIrp calls.

Based on the docs you’d think that’s all there is, but there’s an undocumented log that can be accessed with !verifier 0×200 and that is the critical region log.

This is not to be confused with the user mode concept of critical regions. In a driver, one can call KeEnterCriticalRegion and KeExitCriticalRegion in order to disable and re-enable APC delivery. Without getting too much in to why a driver needs to disable APC delivery, what’s important to note is that every call to KeEnterCriticalRegion must be matched with a call to KeExitCriticalRegion. If a driver gets this wrong, then the system will crash with an APC_INDEX_MISMATCH bugcheck when it notices that the enter/exit count is off.

The way this works is that entering a critical region decrements a field of the KTHREAD structure and exiting a critical region increments the field of the structure. At various points in the O/S, the field of the KTHREAD is checked to make sure that it is zero. If it isn’t, then the system crashes with the previously mentioned APC_INDEX_MISMATCH bugcheck code. One such place that this is checked is in the system service dispatcher before returning back to the caller, which is why you’ll see these bugchecks come from KiSystemServiceExit.

What makes these crashes particularly difficult to track down is that the crash is a secondary failure, by the time the system notices that the count field is incorrect the code that caused the bad state is gone. Enter the critical region log, which will trace every call to KeEnterCriticalRegion and KeLeaveCriticalRegion for the Verified drivers. Now, when the system crashes you can just type !verifier 0×200 in the debugger and find the mismatched call.

Note that this only works with Driver Verifier enabled, just another reason to make sure that you’re always testing with Verifier!

Why does my target machine sometimes become unresponsive after I set a breakpoint?

Wednesday, February 10th, 2010

Ever had this happen to you? You set a seemingly normal breakpoint in your target machine from WinDBG and resume the system:

bpset

You then go back over to your target system and it is completely unresponsive. The mouse won’t move, keyboard doesn’t work, etc. So, you go back over to your debugger system, break into the target, clear the breakpoint, and all is fine again. Disassembling the routine just to make sure all is well doesn’t show anything of interest that might explain this:

coderesident

So what’s up with that?

The problem is actually a variation of the issue that was described by Bryce Jonasson and Jen-Leng Chiu of the Debugging Tools for Windows team in a recent issue of The NT Insider, available here. The issue is that, even though the u command indicates otherwise, the offending code in question is actually paged out at the moment. Not entirely paged out to disk mind you, but currently in transition. We can see this by examining the state of the PTE with the !pte command:

notvalidintrans1

If the page is not currently valid, then why are we seeing valid data contents when we unassemble the virtual address? The reason is that, by default, the debugger will automatically decode and display the contents of pages that are in transition. They are still in memory and the PTE contains the information necessary to find the actual memory, so why not show the data? This behavior can be changed with the nodecodeptes parameter to the .cache command:

autodecodeoff

If we now try to disassemble the address we’ll see that the virtual address is in fact current invalid:

nolongermapped

We can restore the default behavior by specifying the decodeptes option:

decodeenabled

But why does the system go into a tailspin when we set a breakpoint on this address?  The reason is that the debugger cannot set a breakpoint on an invalid PTE. Thus, setting a breakpoint on this address sets what is called an, “owed” breakpoint. When we resume the target system, the target system will try like heck to set a breakpoint on this address every chance it gets, which might result in the system not doing much but trying to set this breakpoint.

The best workaround for this issue is to set a hardware access breakpoint on the address instead of a software breakpoint. This will utilize the support of the processor to break when someone finally executes this address instead of trying to set the breakpoint by replacing a byte of memory with an int 3 instruction: 

boabp

An alternative would be to use the .pagein command to force the memory to be paged in on the target, though paging in kernel memory requires support from the operating system that is only in Windows Vista and later. There is also the .allow_bp_ba_convert command, which enabled an option that would have automatically converted our bp breakpoint into a ba breakpoint in this situation.

Sometimes session context is important too

Saturday, February 6th, 2010

I go on and on about thread and process context in this blog and in my courses, but every once in a rare while session context becomes an important topic.

Historically we’ve thought of sessions as being a Terminal Services only concept, where each user logged on to the Terminal Server is provided their own session. This allows the user to have their own desktop, mapped drive letters, processes, etc. Windows XP brought the idea of sessions to the desktop with the introduction of Fast User Switching, which provides each logged on user their own session. Windows Vista took advantage of the built in support of sessions to provide isolation from background services with interactive user tasks. This so called, “Session Zero Isolation” means that every Vista and later Windows installation is always running at least two sessions, session 0 containing critical Windows processes and services and session 1 providing the default user desktop.

In order to maintain global state for each session, Windows carves out a portion of the kernel virtual address space and stores and global data there. In order to scale appropriately across hundreds or even thousands of sessions, Windows cannot simply use an array of global session data with an entry for each session. Instead, Windows will use a single portion of the address space and simply map it differently based on the session that the current process runs in.

Why this is interesting is that we typically believe that all kernel virtual addresses are the same across all processes. However, we may find that different kernel virtual addresses are mapped differently depending on which session our process context maps to, just  like user space virtual addresses. An example of this was recently discovered on NTDEV and had to do with the tsddd.dll module. The OP couldn’t seem to figure out why he couldn’t read the image from either the debugger or his kernel driver. As it turns out, this image is only mapped in session zero on the target platform, which was Windows 7 (haven’t bothered to look anywhere else personally).

Let’s check it out with LiveKD. First, we can try to dump out the beginning of the image:

tsddds1

Nada. We can use the !pte command to determine what exactly is wrong with this address and we’ll see that there is simply no mapping for this address (as evidenced by the contents of the PTE being zero):

emptypte

Let’s use the !session command to look into which session we are in and what sessions are available:

session

According to this, we’re running in session one and there is another valid session, session zero. This matches what we understand about Vista and later where there are always at least two sessions running on the system. Let’s try switching to the other session and seeing if we can dump out the module header:

tsddds0

Jackpot! Thus, what we can determine from this is that this kernel module is currently only mapped into session zero on this machine.

Great description of IRQL by Jake Oshins

Thursday, February 4th, 2010

Doron Holan’s blog has a guest post by Jake Oshins on IRQL that provids a nice summary on the concept:

http://blogs.msdn.com/doronh/archive/2010/02/02/what-is-irql.aspx

For those who aren’t aware, Jake has done lots of development work on the HAL and ACPI (amongst other things) so he’s the one that you want to talk to when it comes to core Windows concepts such as IRQL, interrupt handling, power management, etc.

x64 Calling Convention

Saturday, December 19th, 2009

We’re working up to analyzing an interesting crash by learning more about working with the x64…

In order to work with x64 dumps we’re going to need to understand the calling convention used, that is going to allow us to do things such as identify the parameters passed to a particular function.

The basic rule here is that the first four parameters to a function are passed in registers, with the remaining parameters to the routine passed on the stack. The typical registers used here are:

Parameter 1 - RCX

Parameter2 - RDX

Parameter 3 - R8

Parameter 4 - R9

(NOTE: There are special rules when it comes to things such as floating point operations. Full details for those scenarios can be found here.)

For example, if a routine begins by accessing the contents of the RDX register, we can know that this routine is accessing the second parameter. We can also imply from that the fact that the caller must have loaded RDX with a meaningful value in a previous frame:

rdx

There is a major issue with this convention however. And that is the fact that all four of these parameters are treated as volatile by the compiler, meaning that their contents do not need to be saved across subroutine calls. Thus it is entirely possible and in fact quite likely that the compiler will overwrite the contents of these registers with unrelated values over the course of the subroutine. This makes reconstructing parameter values quite difficult on the x64.

The next x64 post will talk about the unique way that the x64 compiler utilizes the execution stack, which will then lead to a more detailed discussion on how we can utilize the stack to get parameter information back when we need it.

x64 Trap Frames

Thursday, December 17th, 2009

The first thing that anyone working with x64 dumps needs to know is that trap frames on the x64 do not contain non-volatile register state. What this means for you the analyst is that when you use the .trap command with an x64 target you cannot trust the register contents displayed for rbx, rbp, rdi, rsi, and r12-r15. If you need the contents of these registers at the time of the crash you will need to find the contents indirectly.

I highly recommend that you read my full treatment of this topic in the last issue of The NT Insider: http://www.osronline.com/article.cfm?id=542. In an upcoming post I’ll be showing another example of this as well.

Win7 Crash Dump Mysteries

Friday, December 11th, 2009

I’ve mentioned this here before, but more information on crash dumps and Windows 7 in the latest issue of The NT Insider:

http://www.osronline.com/article.cfm?article=545

Also, if you’re a subscriber the mailed issue has another article on common crash dump analysis/bug reporting mistakes that will hopefully be useful.