title: Difference in behaviour between code executed by a pthread and the main thread in x64-assembly
body: <p>When writing some x64 assembly, I stumbled upon something weird. A function call works fine when executed on a main thread, but causes a segmentation fault when executed as a pthread. At first I thought I was invalidating the stack, as it only segfaults on the second call, but this does not match with the fact that it works properly on the main thread yet crashes on a newly-spawned thread. </p>
  
  <p>From gdb:</p>
  
  <pre><code>[Thread debugging using libthread_db enabled]
  Using host libthread_db library "/lib/x86_64-linux-gnu/libthread_db.so.1".
  Value: 1337
  Value: 1337
  [New Thread 0x7ffff77f6700 (LWP 8717)]
  Return value: 0
  Value: 1337
  
  Program received signal SIGSEGV, Segmentation fault.
  [Switching to Thread 0x7ffff77f6700 (LWP 8717)]
  __printf (format=0x600570 &lt;fmt&gt; "Value: %d\n") at printf.c:28
  28  printf.c: No such file or directory.
  </code></pre>
  
  <p>Does anyone have an idea about what could be going on here?</p>
  
  <pre><code>extern printf
  
  extern pthread_create
  extern pthread_join
  extern pthread_exit
  
  
  section .data
    align     4
    fmt       db    "Value: %d", 0x0A, 0
    fmt_rval  db    "Return value: %d", 0x0A, 0
    tID         dw    0
  
  section .text
    global _start
  
  _start:
    mov   rdi, 1337
    call  show_value
    call  show_value        ; &lt;- this call works fine
  
    ; CREATE THREAD
    mov     ecx, 0                ; function argument
    mov   edx, thread_1       ; function pointer
    mov     esi, 0                ; attributes
    mov   rdi, tID              ; pointer to threadID
    call  pthread_create
  
    mov   rdi, rax
    call  show_rval
  
    mov   rsi, 0              ; return value
    mov     rdi, [tID]          ; id to wait on
    call  pthread_join
  
    mov   rdi, rax
    call  show_rval
  
    call exit
  
  thread_1:
    mov   rdi, 1337
    call  show_value
    call  show_value     ; &lt;- this additional call causes a segfault
    ret
  
  
  show_value:
    push    rdi
  
    mov     rsi, rdi
    mov     rdi, fmt
    call    printf
  
    pop       rdi
    ret
  
  show_rval:
    push    rdi
  
    mov     rsi, rdi
    mov     rdi, fmt_rval
    call    printf
  
    pop       rdi
    ret
  
  exit:
    mov     rax, 60
    mov     rdi, 0
    syscall
  </code></pre>
  
  <p>The binary was generated on Ubuntu 14.04 (64-bit of course), with:</p>
  
  <pre><code>nasm -felf64 -g -o $1.o $1.asm
  ld  -I/lib64/ld-linux-x86-64.so.2 -o $1.out $1.o -lc -lpthread
  </code></pre>