1

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?

Peter Cordes
  • 328,167
  • 45
  • 605
  • 847
  • It is called stack frame. Maintained with ebp in 32 bit and rbp in 64 bit Intel ASM. bp means "base pointer". You can search for usages of ebp/rbp and what is a stack frame. – unlut Oct 06 '19 at 03:29
  • In combination it is what is call a *Function Prolog* where control is passed from the calling process to your executable. Before control is transferred the caller must set up a stackframe for your process and save the address where control will return when your program exits. At the end of your program the *Function Epilogue* returns control back where it left off. – David C. Rankin Oct 06 '19 at 03:33
  • 1
    The *block* that `printf("Hello");` compiles to *starts* at the `lea` of the first (and only) arg. That instruction alone just puts the address of the string constant in a register. Nothing happens until `call printf`. – Peter Cordes Oct 06 '19 at 04:30
  • @PeterCordes what's `lea` ? –  Oct 07 '19 at 03:11
  • It's an instruction mnemonic you can look up in the manual. It calculates an addressing mode and puts the *address* in a register. – Peter Cordes Oct 07 '19 at 07:29

1 Answers1

1
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.

Carl Norum
  • 219,201
  • 40
  • 422
  • 469