How to get thread stack information on Windows? How to get thread stack information on Windows? windows windows

How to get thread stack information on Windows?


(Definitions can be found here.)

To get stack boundaries:

THREAD_BASIC_INFORMATION basicInfo;NT_TIB tib;// Get TEB addressNtQueryInformationThread(YOUR_THREAD_HANDLE, ThreadBasicInformation, &basicInfo, sizeof(THREAD_BASIC_INFORMATION), NULL);// Read TIBNtReadVirtualMemory(YOUR_PROCESS_HANDLE, basicInfo.TebBaseAddress, &tib, sizeof(NT_TIB), NULL);// Check tib.StackBase and tib.StackLimit

To get the value of esp, simply use GetThreadContext.


An easier way without having to involve the Windows Driver Kit is as so:

NT_TIB* tib = (NT_TIB*)__readfsdword(0x18);size_t* stackBottom = (size_t*)tib->StackLimit;size_t* stackTop = (size_t*)tib->StackBase;


__readfsdword() works only for the current thread. So, the variant with NtQueryInformationThread() is more flexible.

Added some declarations which are missed in ntdll.h:

typedef enum _THREADINFOCLASS {    ThreadBasicInformation = 0,} THREADINFOCLASS;typedef LONG KPRIORITY;typedef struct _CLIENT_ID {    HANDLE UniqueProcess;    HANDLE UniqueThread;} CLIENT_ID;typedef CLIENT_ID *PCLIENT_ID;typedef struct _THREAD_BASIC_INFORMATION{  NTSTATUS                ExitStatus;  PVOID                   TebBaseAddress;  CLIENT_ID               ClientId;  KAFFINITY               AffinityMask;  KPRIORITY               Priority;  KPRIORITY               BasePriority;} THREAD_BASIC_INFORMATION, *PTHREAD_BASIC_INFORMATION;