Printf arguments not pushed on the stack

筅森魡賤 提交于 2021-02-10 13:11:26

问题


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


回答1:


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.




回答2:


Depending on your compiler, you will need to allocate space on the heap for your pointer 's'. Instead of char *s; use char s[300]; to allocate 300 bytes of room Otherwise 's' is simply pointing up the stack - which can be random

This could be partly why you are not seeing PUSH instructions.

Also, I don't see why there should be a PUSH instruction for the pointers required in printf? The assembler is simply copying (MOV) the value of the pointers



来源:https://stackoverflow.com/questions/19351451/printf-arguments-not-pushed-on-the-stack

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!