There is no API (that I know of) to do this. But If you have a DLL in the process, then you will get DLL_PROCESS_ATTACH/DLL_THREAD_ATTACH notifications in DllMain when each thread is created. You can record the thread ID and the address of a stack object for that thread when you get these notifications, because you will get called on the new thread. So store the thread id and stack address in some table that you create at that time. Don t try to do a lot of work in DllMain, just record the stack location and return.
You can then use VirtualQuery to get turn the address of a variable on each thread stack into a virtual allocation range, that should give you the base address of the stack (remember that stacks grow from high addresses to low addresses). The default allocation size for a stack is 1Mb, but that can be overridden by a linker switch or by the thread creator, but a stack must be contiguous. So what you get back from VirtualQuery
will be the full stack at that point in time
As for the heap location - there can be multiple locations for the heap, but in general if you want to assume a single contigous heap location then use HeapAlloc to get the address of a heap object and then VirtualQuery
to determine the range of pages for that section of the heap.
Alternatively You can use VirtualQuery
on the hModule for the EXE and for each DLL. and then you can assume that anything that is read-write and isn t a stack or a module is part of the heap. Note that this will be true in most processes, but may not be true in some because an application can call VirtualAlloc
or CreateFileMapping
directly, resulting in valid data pointers that are not from either stack or heap.
Use EnumProcessModules to get the the list of modules loaded into a process.
VirtualQuery basically takes a random address, and returns the base address of the collection of pages that that address belongs to, as well as the page protections. So it s good for going from a specific pointer which type of allocation.