问题
How a stack backtrace can be implemented when the compiler is explicitly told not to use ebp as stack frame pointer?
回答1:
The answer to this was only ever in comments on the accepted answer on What is the purpose of the EBP frame pointer register?.
Modern debuggers can do stack backtraces even in code compiled with -fomit-frame-pointer. That setting is the default in recent gcc.
gcc puts the necessary stack-unwind info into a .eh_frame_hdr
section. See this blog post for more details. It's used for runtime exceptions, too. You'll find it (with objdump -h
) in most binaries on a Linux system. It's about 16k for /bin/bash
, vs. 572B for GNU /bin/true
, 108k for ffmpeg
.
There is a gcc option to disable generating it, but it's a "normal" data section, not a debug section that strip
removes by default. Otherwise you couldn't backtrace through a library function that didn't have debug symbols. That section may be bigger than the push/mov/pop
instructions it replaces, but it has near zero runtime cost (e.g. uop cache).
I think the info stored in that section is a mapping from return-address to size of stack frame. Since every call
instruction pushes the address of the following instruction onto the stack, you can identify the parent caller from that address. Instead of pushing ebp
to make a linked list of stack frames on the stack, the offset to the next return address is stored in the .eh_frame_hdr
section, so it can be used if needed by code that needs to backtrace.
来源:https://stackoverflow.com/questions/34055891/implementing-stack-backtrace-without-using-ebp