extremeaxe5
extremeaxe5

Reputation: 815

Movement of `main` function after running in gdb?

I have the following C code in ret0.c.

int main(){
  return 0;
}

Compiling and running through gdb, I have the following output:

(gdb) disas main
Dump of assembler code for function main:
   0x0000000000001119 <+0>: push   %rbp
   0x000000000000111a <+1>: mov    %rsp,%rbp
   0x000000000000111d <+4>: mov    $0x0,%eax
   0x0000000000001122 <+9>: pop    %rbp
   0x0000000000001123 <+10>:    retq   
End of assembler dump.
(gdb) run
Starting program: /home/michael/core/mind/ob/thm/cs/lang/other/c/ret0 
[Inferior 1 (process 14766) exited normally]
(gdb) disas main
Dump of assembler code for function main:
   0x0000555555555119 <+0>: push   %rbp
   0x000055555555511a <+1>: mov    %rsp,%rbp
   0x000055555555511d <+4>: mov    $0x0,%eax
   0x0000555555555122 <+9>: pop    %rbp
   0x0000555555555123 <+10>:    retq   
End of assembler dump.

So after executing once, the location of main in memory has changed? What's going on here?

Upvotes: 0

Views: 86

Answers (2)

Employed Russian
Employed Russian

Reputation: 213646

What's going on here?

You have a position-independent executable (which is really a special form of a shared library), which is relocated to random address at runtime.

You can verify this by running file ret0, which will say something like ELF 64-bit LSB pie executable, x86-64, version 1 ...

To build a non-PIE executable, use gcc -no-pie .... Non-position-independent executables must be loaded at the address at which they were linked, main will stay in place.

Upvotes: 0

Yosef Arbiv
Yosef Arbiv

Reputation: 400

The first output was printed before the process was started. In this case gdb prints the offset in the binary file.

The second output is after the process was terminated, and you see the actual address in the memory space of the process.

Upvotes: 2

Related Questions