简体   繁体   English

分析生成的汇编代码以操作命令行参数

[英]Analyzing the assembly code generated to manipulate command line arguments

#include <stdio.h>
int main(int argc, char * argv[])
{
 argv[1][2] = 'A';
 return 0;
}

Here is the corresponding assembly code from GCC for a 32-bit Intel architecture. 以下是GCC针对32位Intel架构的相应汇编代码。 I can't totally understand what is going on. 我无法完全理解发生了什么。

main:
        leal    4(%esp), %ecx  - Add 4 to esp and store the address in ecx
        andl    $-16, %esp  - Store first 28 bits from esp's address into esp??
        pushl   -4(%ecx)  - Push the old esp on stack
        pushl   %ebp         - Preamble
        movl    %esp, %ebp
        pushl   %ecx          - push old esp + 4 on stack
        movl    4(%ecx), %eax   - move ecx + 4 to eax. this is the address of argv. argc stored at (%ecx).
        addl    $4, %eax - argv[1]
        movl    (%eax), %eax - argv[1][0]
        addl    $2, %eax  - argv[1][2]
        movb    $65, (%eax) - move 'A'
        movl    $0, %eax - move return value (0)
        popl    %ecx - get old value of ecx
        leave
        leal    -4(%ecx), %esp  - restore esp
        ret

What is going on in the beginning of the code before the preamble? 在序言之前的代码开头发生了什么? Where is argv store according to the following code? 根据以下代码,argv存储在哪里? On the stack? 在堆栈上?

The funny code (the first two lines) that you are seeing is the alignment of the stack to 16 bytes ( -16 is the same as ~15 , and x & ~15 rounds x to a multiple of 16). 您看到的有趣代码(前两行)是堆栈对齐为16个字节( -16~15相同, x & ~15回合x到16的倍数)。

argv would be stored at ESP + 8 when entering the function, what leal 4(%esp), %ecx does is create a pointer to a pseudo-struct containing argc and argv , then it proceeds to access them from there. 当进入函数时, argv将存储在ESP + 8leal 4(%esp), %ecx所做的是创建一个指向包含argcargv的伪结构的指针,然后它继续从那里访问它们。 movl 4(%ecx), %eax access argv from this pseudo-struct. movl 4(%ecx), %eax来自此伪结构的movl 4(%ecx), %eax访问argv

argv是“main()”的参数,因此在许多ABI中,它确实会在堆栈上传递。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM