This is the mail archive of the
gcc-help@gcc.gnu.org
mailing list for the GCC project.
Re: Segfault when dereferencing %rax after -static compiling
- From: Ian Lance Taylor <iant at google dot com>
- To: Amittai Aviram <amittai dot aviram at yale dot edu>
- Cc: gcc-help at gcc dot gnu dot org
- Date: Tue, 30 Nov 2010 10:37:29 -0800
- Subject: Re: Segfault when dereferencing %rax after -static compiling
- References: <C3E85FD4-017A-4F7D-A6AF-61E6D67F7CA1@yale.edu>
Amittai Aviram <amittai.aviram@yale.edu> writes:
> 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?
There are many possible reasons. The most likely is simply that the
memory map looks different when the program is statically linked. You
might get more information if you look at the value of %rax which traps.
On GNU/Linux, you will also get more information by looking at
/proc/PID/maps.
Ian