How to find thread that particular interface connected to

Imagine you have some field myIntf of type IMyInterface in some class and that interface is implemented in native code. In some cases, it is useful to know which thread was used to introduce this interface to .NET first time. It is useful, because this interface would be connected/attached to that thread and call of any function from that interface will attempt to marshal execution to that thread, unless it is free threaded. And this thread could be blocked, destroyed etc.

So, imagine you have following code:
myIntf.Func1();

If you add Debug.Break(); before this line code and run your application from WinDbg and wait until execution will stop. Next, press Shift+F11 three times to exit from Debug.Break. Now press Alt+7 to switch to disassembly view. You will see some CPU instructions and after few of them you will see call. Click on that line and press F7 to run until that instruction. Now register rcx will contain pointer to myIntf interface instance. Now execute this command to load .NET support Dll in WinDbg
.cordll -ve -u -l

And this command to display information about this object:
!DumpObj @rcx
or short version
!do @rcx

You see RCW info that looks like hyper link. Click on it. There you will see thread address that associated with this RCW. It is Thread object from .NET runtime that written on C++. Imagine Thread’s object address is 0x123457890. Unfortunately, there is no type information in publicly available PDB files, so it is hard to find thread handle in Thread object. But after some time I found clr!Thread::CreateNewOSThread. From source code it is clear that new thread is created and then SetThreadHandle called. SetThreadHandle is actually call to FastInterlockExchangePointer. Quick look at disassembly reveals this:
mov     rdi,rcx

call    qword ptr [clr!_imp_CreateThread (00007ffa`735af488)]
test    rax,rax
je      clr!Thread::CreateNewOSThread+0x11d (00007ffa`7310e219)

xchg    rax,qword ptr [rdi+210h]

It is clear that rdi is this pointer in Thread object and after handle is created it written to offset 0x210. To check thread handle type this:
dd 0x123457890+210 L1

This will print handle of that thread that connected to our interface. But how to find that thread in Threads view in WinDbg? WinDbg showing thread id instead thread handle. Use this command:
!handle <handle> f

This will print thread id of that thread

Comments

Post comment