Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Analyzing the assembly code generated to manipulate command line arguments

Tags:

c

x86

assembly

#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. 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? On the stack?

like image 374
Bruce Avatar asked Dec 12 '25 22:12

Bruce


2 Answers

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).

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. movl 4(%ecx), %eax access argv from this pseudo-struct.

like image 78
Necrolis Avatar answered Dec 14 '25 18:12

Necrolis


argv is a parameter to "main()", so in many ABIs, it will indeed be passed on the stack.

like image 38
Perry Avatar answered Dec 14 '25 20:12

Perry



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!