title: main and stack alignment
body: <p>I have a function which prints text and a floating point number. Here is a version which does not use main</p>
  
  <pre><code>extern printf
  extern _exit
  
  section .data
      hello:     db 'Hello world! %f',10,0
      pi:        dq  3.14159
  section .text
      global _start
  _start:
      xor eax, eax
      lea rdi, [rel hello]
      movsd xmm0, [rel pi]
      mov eax, 1
      call printf
      mov rax, 0
      jmp _exit
  </code></pre>
  
  <p>I assemble and link this like this</p>
  
  <pre><code>nasm -felf64 hello.asm
  ld hello.o -dynamic-linker /lib64/ld-linux-x86-64.so.2 -lc -melf_x86_64
  </code></pre>
  
  <p>This runs fine. However, now I want to do this using <code>main</code>.</p>
  
  <pre><code>global main
  extern printf
  
  section .data
      hello:     db 'Hello world! %f',10,0
      pi:        dq  3.14159
  section .text
      main:
      sub rsp, 8
      xor eax, eax
      lea rdi, [rel hello]
      movsd xmm0, [rel pi]
      mov eax, 1
      call printf
      mov rax, 0
      add rsp, 8
      ret
  </code></pre>
  
  <p>I assembly and link like this</p>
  
  <pre><code>nasm -felf64 hello_main.asm
  gcc hello_main.o
  </code></pre>
  
  <p>This runs fine as well. However, I had to subtract eight bytes from the stack pointer before calling <code>printf</code> and then add eight bytes to the stack pointer after otherwise I get a segmentation fault. </p>
  
  <p>Looking at the stack pointer I see that without using <code>main</code> it's 16-byte aligned but with <code>main</code> it's only eight byte aligned. The fact that eight bytes has to be subtracted and added says that it's always 8-byte aligned and never 16-byte aligned (unless I misunderstand something). Why is this? I thought with x86_64 code we could assume that the stack is 16-byte aligned (at least for standard library function calls which I would think includes <code>main</code>).</p>