Search code examples
cassemblyx86-64att

What are the four execution steps before entering main?


Take the following 5-line file I have:

#include <stdio.h>
int main() {
    printf("Hello");
    return 0;
}

It corresponds to the following assembly:

`main:
    0x100000f60 <+0>:  pushq  %rbp
    0x100000f61 <+1>:  movq   %rsp, %rbp
    0x100000f64 <+4>:  subq   $0x10, %rsp
    0x100000f68 <+8>:  movl   $0x0, -0x4(%rbp)
->  0x100000f6f <+15>: leaq   0x34(%rip), %rdi          ; "Hello"

We can notice the first line in main which prints "Hello" corresponds to the fifth instruction. What are the four preceding instructions: what do they do?


Solution

  • 0x100000f60 <+0>:  pushq  %rbp
    

    Push the caller's base pointer.

    0x100000f61 <+1>:  movq   %rsp, %rbp
    

    Copy the stack pointer into the base pointer (set up this function's stack frame)

    0x100000f64 <+4>:  subq   $0x10, %rsp
    

    Reserve stack space (presumably for the return value - you probably didn't compile this program with any optimizations enabled)

    0x100000f68 <+8>:  movl   $0x0, -0x4(%rbp)
    

    Put the return value (zero) on the stack.

    ->  0x100000f6f <+15>: leaq   0x34(%rip), %rdi          ; "Hello"
    

    Load a pointer to the "Hello" string literal into rdi register.