Mar 15, 2012

Get stack limits on windows

Internet is full of all kinds of explanations on how you can get TIB via fs register, but it's over-complicated and obviously does not work for x64. Here is a much cleaner alternative, works for both x32 and x64.

#include "stdafx.h"
#include <stdio.h>
#include <windows.h>
#include <winnt.h>
#include <tchar.h>

#define INSTACKRANGE(x, pTib)  ( ((x) > (pTib->StackBase)) ? (0) : (((x) < (pTib->StackLimit)) ? (0) : (1)) )

int _tmain(int argc, _TCHAR* argv[])
{
    volatile int var1 = 123;
    static volatile int var2 = 456;
    NT_TIB * pTib = (NT_TIB *)NtCurrentTeb();
    printf("Base %p Limit %p var1 %p (%s) var2 %p (%s)\n",
        pTib->StackBase,pTib->StackLimit,
        &var1,INSTACKRANGE(&var1,pTib) ? "in":"out",
        &var2,INSTACKRANGE(&var2,pTib) ? "in":"out");

    return 0;
}

No comments: