Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Printf arguments not pushed on the stack

I'm in the process of trying to understand the stack mechanisms.

From the theory I have seen, before a function is called, its arguments are pushed onto the stack.

However when calling printf in the code below, none of them are pushed:

#include<stdio.h>

int main(){

    char *s = " test string";
    printf("Print this: %s and this %s \n", s, s);
    return 1;
}

I've put a break in gdb to the printf instruction, and when displaying the stack, none of the 3 arguments are pushed onto the stack.

The only thing pushed to the stack is the string address s as can be seen in the disassembled code below:

   0x000000000040052c <+0>: push   %rbp
   0x000000000040052d <+1>: mov    %rsp,%rbp
   0x0000000000400530 <+4>: sub    $0x10,%rsp
   0x0000000000400534 <+8>: movq   $0x400604,-0x8(%rbp) // variable pushed on the stack
   0x000000000040053c <+16>:    mov    -0x8(%rbp),%rdx
   0x0000000000400540 <+20>:    mov    -0x8(%rbp),%rax
   0x0000000000400544 <+24>:    mov    %rax,%rsi
   0x0000000000400547 <+27>:    mov    $0x400611,%edi
   0x000000000040054c <+32>:    mov    $0x0,%eax
   0x0000000000400551 <+37>:    callq  0x400410 <printf@plt>
   0x0000000000400556 <+42>:    mov    $0x1,%eax
   0x000000000040055b <+47>:    leaveq 

Actually, the only argument appearing so far in the disassembled code is when "Print this: %s and this %s \n" is put in %edi...

   0x0000000000400547 <+27>:    mov    $0x400611,%edi

SO my question is: why am i not seeing 3 push instructions for each of my three arguments ?

uname -a: 3.8.0-31-generic #46-Ubuntu SMP Tue Sep 10 20:03:44 UTC 2013 x86_64 x86_64 x86_64 GNU/Linux

like image 893
Matt Avatar asked Jun 28 '26 00:06

Matt


1 Answers

On 64 bits Linux x86-64 systems, the x86-64 ABI (x86-64 Application Binary Interface) does not push arguments on stack, but uses some registers (this calling convention is slightly faster).

If you pass many arguments -e.g. a dozen- some of them gets pushed on the stack.

Perhaps read first the wikipage on x86 calling conventions before reading the x86-64 ABI specifications.

For variadic functions like printf details are a bit scary.

like image 53
Basile Starynkevitch Avatar answered Jun 30 '26 13:06

Basile Starynkevitch



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!