-4

I am learning x86 assembly and have some problems with understanding some of the instructions. What does sub $0x10,%rsp mean, and why GCC copied this mov $0x0,%eax line two times?

0x0000000000001135 <+0>:    push   %rbp   
0x0000000000001136 <+1>:    mov    %rsp,%rbp
0x0000000000001139 <+4>:    sub    $0x10,%rsp
0x000000000000113d <+8>:    movl   $0xa,-0x4(%rbp)  
0x0000000000001144 <+15>:   mov    -0x4(%rbp),%eax
0x0000000000001147 <+18>:   mov    %eax,%esi
0x0000000000001149 <+20>:   lea    0xeb4(%rip),%rdi        # 0x2004
0x0000000000001150 <+27>:   mov    $0x0,%eax
0x0000000000001155 <+32>:   callq  0x1030 <printf@plt>
0x000000000000115a <+37>:   mov    $0x0,%eax
0x000000000000115f <+42>:   leaveq 
0x0000000000001160 <+43>:   retq
1201ProgramAlarm
  • 32,384
  • 7
  • 42
  • 56
Nazar
  • 3
  • 3
  • Have you looked up what those instructions mean in the reference manual? Also, why wouldn't the compiler happen to use `mov $0x0,%eax` twice? Do you know what that instruction does? – Thomas Jager May 21 '19 at 13:57
  • 1
    The first `mov $0, %eax` is there because _"printf uses a variable number of arguments and %rax specifies how many SSE registers are used for the arguments "_. The second one is there because presumably this function is supposed to return 0. If you didn't zero out `eax` again you'd be returning what `printf` returned, i.e. the number of characters written by `printf`. – Michael May 21 '19 at 14:13
  • @Michael oh thx man, where i can read about it, and can give more information – Nazar May 21 '19 at 14:21
  • 1
    You can google e.g. _"x86_64 calling convention"_ and _"x86_64 vararg eax"_. – Michael May 21 '19 at 14:27
  • This looks like unoptimized machine code. If the compiler is not allowed to optimize the code, random pointless instructions may appear. – fuz May 21 '19 at 15:03

1 Answers1

0

sub $0x10,%rsp allocates space on the stack, it's the same as doing pushq 0 twice except that the value in the allocated stack space will not necessarily be zero, but this is ok since the mov instructions used later replace the garbage with real data.

As Michael rightly stated the mov $0x0,%eax is because printf (as well as any other varargs function) takes the number of arguments in rax.

0x777C
  • 993
  • 7
  • 21