Segfault when dereferencing %rax after -static compiling

Amittai Aviram amittai.aviram@yale.edu
Wed Nov 24 22:16:00 GMT 2010


My program has a function to find the approximate location of the top (highest address) of the stack, by using a loop similar to what you would use for a backtrace:



       uint64_t rbp = 0;
        uint64_t raw_stack_start = 0;

        asm volatile ("movq %%rbp, %0" : "=m"(rbp));
	while (rbp) {
                raw_stack_start = rbp;
                rbp = *(uint64_t *)rbp;
        }
   
GCC compiles the loop as follows (from objdump -D):

400700:       48 c7 45 f8 00 00 00 00	movq   $0x0,-0x8(%rbp)
400708:       48 c7 45 f0 00 00 00 00	movq   $0x0,-0x10(%rbp)
400710:       48 89 6d f8            	mov    %rbp,-0x8(%rbp)
400714:       eb 13                  	jmp    400729 <find_stack_start+0x2d>
400716:       48 8b 45 f8            	mov    -0x8(%rbp),%rax
40071a:       48 89 45 f0            	mov    %rax,-0x10(%rbp)
40071e:       48 8b 45 f8            	mov    -0x8(%rbp),%rax
400722:       48 8b 00               	mov    (%rax),%rax
400725:       48 89 45 f8            	mov    %rax,-0x8(%rbp)
400729:       48 8b 45 f8            	mov    -0x8(%rbp),%rax
40072d:       48 85 c0               	test   %rax,%rax
400730:       75 e4                  	jne    400716 <find_stack_start+0x1a>

When I compile this code without the -static flag, it runs fine and gives me a plausible address.  When I compile it with the -static flag, I get a segmentation fault, which GDB traces to instruction 0x400722 above, where I dereference %rax and store the value in %rax.  Why would this cause a segmentation fault—with the -static flag but not without it?

Thanks!

Amittai

Amittai Aviram
PhD Student in Computer Science
Yale University
646 483 2639
amittai.aviram@yale.edu
http://www.amittai.com



More information about the Gcc-help mailing list