Geeks With Blogs
Kate Moss' Open Space

So you want to know the current stack size. The very first idea is probably to find it out from PE Header which is a good for main thread and other working thread that using default stack size. But what if you need to write a code that can find out the Stack Size pragmatically or what if the working thread is not using default stack size? (CreateThread with specific stack size in cbStack and applied the STACK_SIZE_PARAM_IS_A_RESERVATION  flag)

Just before reveal the answer, as stack is a thread dependent object (compare with heap which is a global object for all thread in the same process), if you are the kernel what will you store the stack relative information that can be accessed by user mode program? Yes, the TLS(Thread Local Storage); TLS is just like a global variable but is only accessible by the owner thread (of the TLS).

To prove our idea so let's dig into the kernel code. In private\winceos\coreos\nk\kernel\vm.c, there is a function, VMCreateStack, which is used by NKCreateThread and CreateNewProcHelper (one of the helper function for NKCreateProcess) to create stack for threads. And now looks closer to the VMCreateStack, we can find the following code

            } else {
                tlsKrn[PRETLS_STACKBOUND] = (DWORD) tlsUsr & ~VM_PAGE_OFST_MASK;
            tlsKrn[PRETLS_STACKBASE]  = (DWORD) pUsrStk;
            tlsKrn[PRETLS_STACKSIZE]  = cbSize;

 And also take a look at PUBLIC\COMMON\OAK\INC\pkfuncs.h

// macros for accessing PRETLS data
#define UStkBase()               (UTlsPtr()[PRETLS_STACKBASE])
#define UStkBound()              (UTlsPtr()[PRETLS_STACKBOUND])
#define UCurFiber()              (UTlsPtr()[PRETLS_CURFIBER])
#define UStkSize()               (UTlsPtr()[PRETLS_STACKSIZE])

It is now clear that we can use UStkSize and other UStkXXX to obtain the Stack size and other Stack info for Current Thread From TLS.



Posted on Monday, October 12, 2009 10:22 AM | Back to top

Comments on this post: Find out the Stack Size in CE 6.0

# re: Find out the Stack Size in CE 6.0
Requesting Gravatar...
Interesting information. Thanks.
Left by Vinoth on May 21, 2013 6:15 PM

Your comment:
 (will show your gravatar)

Copyright © Kate Moss' Open Space | Powered by: