I have this homework assignment where I am supposed to write a c program that displays arguments passed to previous functions in the call stack to the console. I have this piece of code:
struct stack_frame
{
struct stack_frame* next;
};
typedef struct stack_frame stack_frame;
void recover()
{
register stack_frame* sfptr __asm__("ebp");
stack_frame * frame = sfptr;
traverse_stack(frame, show_bytes);
}
Several recursive calls to a function foo(int, short, char) occur before the call to recover(), which initiates a traversal of the stack, resulting in the output of the arguments to all previous calls to foo.
When I compile this with gcc 4.8.2 without optimization, it runs perfectly. With -O1 it breaks because frame gets assigned an unreachable address. 0xffffffd9. I believe this is because the asm is getting optimized out.
I have tried many other ways of getting the value of the ebp register, including
stack_frame frame;
asm volatile("movl %%ebp, %0\n" : "=r"(frame->next));
and many others. I have tried adding clobbers. I have also tried designating frame as volatile. I have already reviewed many SO posts on this subject, including [question]: gcc removes inline assembler code and others. No matter what I have tried, I am the king of SegFault City.
The segfault occurs here:
void traverse_stack(stack_frame* frame, byte_processor show_bytes)
{
if (frame->next != NULL) // segfault here!!!!!!!
traverse_stack(frame, show_bytes);
show_args(frame, show_bytes);
}
show_bytes is just a function pointer to one of two functions that will display the bytes in hex for either big or little endian systems.
Anyway, I have to compile with -m32. I do not have the option of supplying any additional arguments.
Any help is greatly appreciated. Also, I am a bit of a newb, so if at all possible, please be gentle with your responses. Thanks in advance.