views:

342

answers:

3

Hi,

Are there Visual C++ versions of the following (in GCC)?

  1. __builtin_return_address
  2. __builtin_frame_address

Reference - http://gcc.gnu.org/onlinedocs/gcc/Return-Address.html

If not, is there a way to emulate them?

Thanks.

+1  A: 

For functions declared __cdecl, the frame address is the top of the function's stack (pointed to by esp, and adjusted by the sizeof the function's parameters). I believe GCC typically stores that pointer for the current function in ebp (not sure about VS). That memory location is a pointer, and holds the return address.

For functions declared __fastcall, the adjustment to esp is much smaller, as some of the function's arguments may have been passed in registers.

I'm not sure about __stdcall, but I think it's the same as __cdecl.

greyfade
How would __builtin_frame_address(n) work then when n > 0?
jameszhao00
Deduction. The run-time solution is to trace back and simulate popping the stack to locate the old stack locations.
greyfade
+5  A: 

Here is a full list of the available Visual Studio 2008 Compiler Intrinsics. One of the ones you are specifically looking for here is _ReturnAddress... still looking for the other.

For walking the stack (and getting frame pointers), read the details on the Visual Leak Detector stack walking mechanism, which uses StackWalk64 internally.

280Z28
Yea just saw that too. __builtin_frame_address is no where to be found though...
jameszhao00
@james: now it is ^^
280Z28
Awesome. Thanks.
jameszhao00
+1  A: 

The corresponding function to __builtin_frame_address, if it exists, would likely not work in optimized code, since VC does an optimization called Frame Pointer Omission. However, you can turn that optimization off, as described here: http://msdn.microsoft.com/en-us/library/2kxx5t2c%28VS.71%29.aspx

Note that, for x86 you can write inline assembly code http://msdn.microsoft.com/en-us/library/4ks26t93%28VS.71%29.aspx unfortunately, it doesn't work for 64-bit architectures so that probably isn't helpful to you.

Drew Hoskins