[This is for PC/Visual C++ specifically (although any other answers would be quite illuminating :))]
How can you tell if a pointer comes from an object in the stack? For example:
int g_n = 0; void F() { int *pA = &s_n; ASSERT_IS_POINTER_ON_STACK(pA); int i = 0; int *pB = &i; ASSERT_IS_POINTER_ON_STACK(pB); }
so only the second assert (pB) should trip. I’m thinking using some inline assembly to figure out if it’s within the SS segment register or something like that. Does anybody know if there’s any built in functions for this, or a simple way to do this?
Thanks! RC
Technically speaking, in portable C you can’t know. A stack for arguments is a hardware detail that is honored on many but not all compilers. Some compilers will use registers for arguments when they can (ie, fastcall).
If you are working specifically on windows NT, you want to grab the Thread Execution Block from calling NtCurrentTeb(). Joe Duffy’s blog has information on this and from it you can get the stack range. You check for pointer in range and you should be good to go.