Where is the "%d\n" format string stored and how does GCC pass it to printf on x86-64?

56 Views Asked by At

So i was debugging a simple c program as follows in gdb looking at the assembly

#include <stdio.h>
#include <stdlib.h>

int main() {
  int a = 12;
  printf("%d\n", a);
}

The assembly code is as follows

0x0000000000001139 <+0>:    push   rbp
   0x000000000000113a <+1>: mov    rbp,rsp
   0x000000000000113d <+4>: sub    rsp,0x10
   0x0000000000001141 <+8>: mov    DWORD PTR [rbp-0x4],0xc
   0x0000000000001148 <+15>:    mov    eax,DWORD PTR [rbp-0x4]
   0x000000000000114b <+18>:    mov    esi,eax
   0x000000000000114d <+20>:    lea    rax,[rip+0xeb0]        # 0x2004
   0x0000000000001154 <+27>:    mov    rdi,rax
   0x0000000000001157 <+30>:    mov    eax,0x0
   0x000000000000115c <+35>:    call   0x1030 <printf@plt>
   0x0000000000001161 <+40>:    mov    eax,0x0
   0x0000000000001166 <+45>:    leave
   0x0000000000001167 <+46>:    ret

The variable a is first in the stack and then in eax and then in esi(rsi), since printf takes one argument then we move the data finally into rsi which is the second paramater in the calling convention However the first parameter "%d\n" must be somehow stored in rdi again by the calling convention however examining rdi shows that it does not store this.

Is it stored somewhere in the stack or does rdi point to it please explain it to me, info about calling convention is from this source

http://6.s081.scripts.mit.edu/sp18/x86-64-architecture-guide.html

Tried converting the data into string or other things none of which worked

1

There are 1 best solutions below

2
fuz On BEST ANSWER

The string "%d\n" is stored in the read-only data segment. This sequence of instructions deals with it:

lea    rax,[rip+0xeb0]    ; retrieve string address
mov    rdi,rax            ; provide string address as first argument

You can examine the string with a gdb command like this, after having stepped past the LEA instruction:

printf (char *)$rax