How to list threads in WinDbg (kernel debugging) - windows

Does anyone know how I can list all threads in WinDbg while kernel debugging. I have found older references that say '~' but that does not work.
Specifically I am looking to the find the ID of a thread that caused an event, namely a breakpoint.
Thanks.

~ only works in user mode. To list all threads on the system, it's !process 0 1 as I recall (it's been awhile).
"Specifically I am looking to the find the ID of a thread that caused an event, namely a breakpoint."
This statement doesn't make much sense to do from kernel mode. Can you descrive more about what your scenario is?
Edit: Ah, now I get it. You want to know which thread you're currently in right now. Give !thread a go.

You can always use the #$thread pseudo register to reference the current thread object:
0: kd> r #$thread
$thread=fffff80002c02cc0
If you want the ID of the thread, you'll need to dig it out of the ETHREAD. Luckily, the #$thread is typed as a pointer to an ETHREAD if you're using the C++ evaluator:
0: kd> ?? #$thread->Cid
struct _CLIENT_ID
+0x000 UniqueProcess : 0x00000000`00001408 Void
+0x008 UniqueThread : 0x00000000`0000144c Void
-scott

Related

Where is a usermode thread context stored, and is it possible to modify?

i was wondering if anyone knows where the context of a thread running in usermode is stored in kernel ? and if there are any API's for dealing with getting and setting a usermode thread context ? i know that you should not be doing this for any reason, so please do not sidetrack into that. This is solely for the sake of research and will not be used by anything else than local projects of my own.
In usermode we have GetThreadContext and SetThreadContext, but i need to do this from a device driver in the kernel, i wish i had more to write but i can't find any information on this topic at all so i wish someone more educated than me can enlighten me on some of the windows internals at hand here.
Regards Paze.
when thread enter in kernel mode it context stored in it kernel stack, in struct _KTRAP_FRAME - it declared in ntdkk.h. in ntoskrnl.exe (all versions from win2000 up to win10) exist exported api
NTKERNELAPI
NTSTATUS
NTAPI
PsGetContextThread(
__in PETHREAD Thread,
__inout PCONTEXT ThreadContext,
__in KPROCESSOR_MODE Mode
);
you can use it for get thread context (and PsSetContextThread for set thread context).
about how this work - look in wrk - when you try get/set context from another thread special kernel mode APC is inserted to this thread with pointer to internal GETSETCONTEXT structure, after this requestor begin wait on event (OperationComplete) from this structure. when thread (for which we query context) next time begin execute in kernel - APC routine (PspGetSetContextSpecialApc) is executed - it fill context from _KTRAP_FRAME and set event (OperationComplete)

!clrstack never reports anything

I know I am dealing with a managed thread but I have never managed to get !clrstack to work. I always get:
0:000> !clrstack
OS Thread Id: 0xaabb (0)
Child SP IP Call Site
GetFrameContext failed: 1
00000000 00000000
Admittedly I could use !dumpstack but I can't figure out how to make it show the arguments. It only shows ChildEBP, Return Address and the function name. Besides it mixes managed and unmanaged calls and I'd like to focus only on the managed portions.
UPDATE
As requested by Thomas, !clrstack -i returns:
0:000> !clrstack -i
Loaded c:\cache\mscordbi.dll\53489464110000\mscordbi.dll
Loaded c:\cache\mscordacwks_x86_x86_4.0.30319.34209.dll\5348961E69d000\mscordacwks_x86_x86_4.0.30319.34209.dll
Dumping managed stack and managed variables using ICorDebug.
=================================================================
Child SP IP Call Site
003ad0bc 77d1f8e1 [NativeStackFrame]
Stack walk complete.
Its progress :-)
Please post the output from !dumpstack or k to double check the callstack, you know the !clrstack only display the managed code call stack, however sometimes , if the managed thread finished this work, it would be waited in the CLR code(semaphore) if you use the thread pool, and the remain call stack become totally unmanaged call stack.so !clrstack display nothing for it.

How to know if any IO Thread is available in windbg?

I have a legacy application that I am trying to debug which schedules a background task like this:
err = QueueUserWorkItem(
Foo,
NULL,
WT_EXECUTEINIOTHREAD);
I can see that my function Foo is never executed (i put a breakpoint on the function and it is never hit). So i thought lets see if we have any IO thread avaialble for the function ever or not. But sadly i dont know how to list such threads in windbg. Can anyone help me here please. I am doing this debugging in user mode.
Load sos: .loadby sos clr or .loadby sos mscorwks
Dump the threads: !Threads
Pick an interesting thread: ~<thread number>s (eg: ~13s) Then show the stack: !DumpStack
You could also try !EEStack to show all the threads (can be information overload).

Retrieving command line argument of process at driver level

Hello I am writing a minifilter driver for intercepting all the irp packets from a certain process say a.exe .
So , in the driver code it can be done by applying a check on the command line arguments that started the process.
Does anyone know how can i retrieve the command line argument ??
Thanks in advance .
There's no supported way to do this from within kernel-mode. In fact, trying to access user-mode process information from the kernel is a pain in general. I would suggest firing up a request to a user-mode service, which can then find that information and pass it back down to your kernel component.
However, there an undocumented method to do it. If you can get a handle to an EPROCESS struct for the target process, you can get at a pointer to the PEB (process environment block) struct within it, which then has a pointer to an RTL_USER_PROCESS_PARAMETERS structure, which has a member called CommandLine.
Example:
UNICODE_STRING* commandLine = epProcess->Peb->ProcessParameters->CommandLine;
The downside to this is that EPROCESS is almost entirely opaque and PEB is semi-opaque too, meaning that it may change in future versions of Windows. I certainly wouldn't advocate trying this in production code.
Try using the NtQueryInformationProcess or ZwQueryInformationProcess function with the PROCESSINFOCLASS parameter as ProcessBasicInformation. The output parameter, ProcessInformation, will be a struct of type PROCESS_BASIC_INFORMATION. As Polynomial mentioned, this struct has a pointer to the process's PEB struct, which contains the information you are looking for in its ProcessParameters field.

How to set name to a Win32 Thread?

How do I set a name to a Win32 thread. I did'nt find any Win32 API to achieve the same. Basically I want to add the Thread Name in the Log file. Is TLS (Thread Local Storage) the only way to do it?
Does this help ?
How to: Set a Thread Name in Native Code
In managed code, it is as easy as setting the Name property of the corresponding Thread object.
http://msdn.microsoft.com/en-us/library/xcb2z8hs(VS.90).aspx
//
// Usage: SetThreadName (-1, "MainThread");
//
#include <windows.h>
const DWORD MS_VC_EXCEPTION=0x406D1388;
#pragma pack(push,8)
typedef struct tagTHREADNAME_INFO
{
DWORD dwType; // Must be 0x1000.
LPCSTR szName; // Pointer to name (in user addr space).
DWORD dwThreadID; // Thread ID (-1=caller thread).
DWORD dwFlags; // Reserved for future use, must be zero.
} THREADNAME_INFO;
#pragma pack(pop)
void SetThreadName( DWORD dwThreadID, char* threadName)
{
THREADNAME_INFO info;
info.dwType = 0x1000;
info.szName = threadName;
info.dwThreadID = dwThreadID;
info.dwFlags = 0;
__try
{
RaiseException( MS_VC_EXCEPTION, 0, sizeof(info)/sizeof(ULONG_PTR), (ULONG_PTR*)&info );
}
__except(EXCEPTION_EXECUTE_HANDLER)
{
}
}
According to discussion with the Microsoft debugging team leads (see link below for details) the SetThreadDescription API is the API that will be used going forward by Microsoft to support thread naming officially in native code. By "officially" I mean an MS-supported API for naming threads, as opposed to the current exception-throwing hack that currently only works while a process is running in Visual Studio.
This API became available starting in Windows 10, version 1607.
Currently, however, there is very little tooling support, so the names you set won't be visible in the Visual Studio or WinDbg debuggers. As of April 2017, however, the Microsoft xperf/WPA tools do support it (threads named via this API will have their names show up properly in those tools).
If you would like to see this gain better support, such as in WinDbg, Visual Studio, and crash dump files, please vote for it using this link:
https://visualstudio.uservoice.com/forums/121579-visual-studio-ide/suggestions/17608120-properly-support-native-thread-naming-via-the-sett
Win32 threads do not have names. There is a Microsoft convention whereby applications raise special SEH exceptions containing a thread name. These exceptions can be intercepted by debuggers and used to indicate the thread name. A couple of the answers cover that.
However, that is all handled by the debugger. Threads themselves are nameless objects. So, if you want to associate names with your threads, you'll have to develop your own mechanism. Whilst you could use thread local storage that will only allow you to obtain the name from code executing in that thread. So a global map between thread ID and the name would seem like the most natural and useful approach.
You can use a thread-local storage object to store the name. For example,
__declspec( thread ) char threadName[32];
Then you can write and read this from a thread. This might be useful in a logger application, where you want to print out the name of the thread for every message. You probably want to write this variable as soon as the thread starts, and also throw the Microsoft exception (https://stackoverflow.com/a/10364541/364818) so that the debugger also knows the thread name.
If your application runs on Windows version 1607+, you can use SetThreadDescription()
If you want to see the name of your thread in the debugger (windbg or visual studio):
http://blogs.msdn.com/stevejs/archive/2005/12/19/505815.aspx
I'm not actually sure if there's a reverse method to get the thread name. But TLS sounds like the way to go.
Another way to do this is to store a pointer to the name in the ArbitraryUserPointer field of the TEB of the thread. This can be written to and read from at runtime.
There's a CodeProject article titled "Debugging With The Thread Information Block" that shows you how to do this.
You can always store this information for yourself in a suitable data structure. Use a hash or a map to map GetThreadId() to this name. Since GetThreadId() is always a unique identifier, this works just fine.
Cheers !
Of course, if he's creating many
threads, that hashmap will slowly fill
up and use more and more memory, so
some cleanup procedure is probably a
good thing as well.
You're absolutely right. When a thread dies, it's corresponding entry in the map should naturally be removed.

Resources