tags:

views:

223

answers:

2

For a C++ debug application I want to be able to count the number of callstack frames easily. Is there an OS function to do this?

I need this for Windows and Posix, i.e. cross platform. Solutions to either or both platforms would be great.

I can walk the stack to find all of the frames but I wondered if there was an easy call to do this.

+2  A: 

No, because this is a compiler thing.

The compiler is free to define its own ABI. This defines how the callstack (if any) is defined. Unless you are using pure "C" this is non trivial and will be different for every compiler.

Also I have heard (but have not verified) that MS is using a new scheme were stack frames are placed randomly around memory so as to prevent (make harder) buffer overflow attacks that affect the return jump. Not exactly relevant but a fun fact.

Martin York
Last I heard, they were just placing random "cookies" on the stack frame that you'd have to overwrite before overwriting the return address. Then on function return the cookie is checked, and if it has changed, the app terminates.
Eclipse
Just to point out, Microsoft's stack cookies, while interesting have been defeated already, and thus should not be relied on for safety.Stack frames are indeed not placed randomly, because that would defeat the whole "stack" thing.
X-Istence
I was not referring to the cookies. I was referring to the actual placement of the frame. Which potentially could be anywhere in memory (with a bit of extra wiring from the compiler). A stack is just the simplest method of recording the information it does not technically need to be a stack.
Martin York
Ok, so I have to walk the stack in an implementation specific way. There is no call to get the stack size. Are there any cross platform libraries to do this?
Nick
A: 

If you use glibc (Linux) you can use the following functions to get the stack trace:

#include <execinfo.h> 
int backtrace(void **buffer, int size); 
char **backtrace_symbols(void *const *buffer, int size); 
void backtrace_symbols_fd(void *const *buffer, int size, int fd);

For more information see the man page for backtrace.

lothar