user146297
user146297

Reputation: 79

Disassembly of a C function

I was trying to understand disassembled code of the following function.

void func(char *string) {
    printf("the string is %s\n",string);
}

The disassembled code is given below.

1) 0x080483e4 <+0>:     push   %ebp  
2) 0x080483e5 <+1>:     mov    %esp,%ebp  
3) 0x080483e7 <+3>:     sub    $0x18,%esp  
4) 0x080483ea <+6>:     mov    $0x80484f0,%eax  
5) 0x080483ef <+11>:    mov    0x8(%ebp),%edx  
6) 0x080483f2 <+14>:    mov    %edx,0x4(%esp)  
7) 0x080483f6 <+18>:    mov    %eax,(%esp)  
8) 0x080483f9 <+21>:    call   0x8048300 <printf@plt>

Could anyone tell me what lines 4-7 means (not the literal explanation). Also why 24 bytes are allocated on stack on line 3?

Upvotes: 1

Views: 2351

Answers (2)

user1129665
user1129665

Reputation:

Basically what happens here:

4) 0x080483ea <+6> : mov $0x80484f0,%eax

Load the address of "the string is %s\n" into eax.

5) 0x080483ef <+11>: mov 0x8(%ebp),%edx

Move the argument string into edx.

6) 0x080483f2 <+14>: mov %edx,0x4(%esp)

Push the value of edx or string into the stack, second argument of printf

7) 0x080483f6 <+18>: mov %eax,(%esp)

Push the value of eax or "the string is %s\n" into the stack, first argument of printf, and then it will call printf.

sub $0x18,%esp is not necessary since the function has no local variables, gcc seems to like making extra space but honestly I don't know why.

Upvotes: 5

Guilherme Bernal
Guilherme Bernal

Reputation: 8293

The stack is a continuous region of memory that starts at a higher address and ends at esp. Whenever you need your stack to grow, you subtract from esp. Every function can have a frame on the stack. It is the part of the stack that the function owns and is responsible for cleaning after it is done. It means, when the function starts it decreases esp to create its frame. When it ends it increases it back. ebp usually points to the beginning of your frame.

Initially this function pushs ebp to tha stack so that it can be stored when the function ends, sets esp = ebp to mark the begin of its frame and allocate 28 bytes. Why 28? For alignment. It already allocated 4 bytes for the ebp. 4 + 28 = 32.

The lines 4-7 will prepare the call to printf. It expects its arguments to be on the frame of the caller. When we read mov 0x8(%ebp), %edx, we are taking our argument char* string from the caller's frame. printf will do the same.

Note that your assembly is missing a leave and a ret instructions to clear the stack and return to the caller.

Upvotes: 1

Related Questions