.file "calc.c"
.text
.globl calc
.type calc, @function
calc:
pushl %ebp
movl %esp, %ebp
movl 8(%ebp), %edx
movl 16(%ebp), %ecx
leal (%edx,%edx,2), %edx
movl 12(%ebp), %eax
leal (%edx,%eax,2), %eax
movl %ecx, %edx
sall $4, %edx
subl %ecx, %edx
addl %edx, %eax
popl %ebp
ret
.size calc, .-calc
.ident "GCC: (Ubuntu 4.3.3-5ubuntu4) 4.3.3"
.section .note.GNU-stack,"",@progbits
I'm trying to understand what's going on with this assembly code. I created it by typing gcc -O1 -S calc.c
which generated a calc.s
assembly file.
Can someone explain (in terms of the addition and multiplication in calc.c
) what is going on, line by line?
The original C code is:
int calc(int x, int y, int z)
{
return 3*x + 2*y + 15*z;
}
In assembly language, the call instruction handles passing the return address for you, and ret handles using that address to return back to where you called the function from. The return value is the main method of transferring data back to the main program.
Calling C from Assembly You can call C functions from Assembly as well. This example calls printf(). In the main function, we push and pop the stack and put our operations in between. We move all the parameters in to the appropriate registers, and then we call the function.
A function call is an important part of the C programming language. It is called inside a program whenever it is required to call a function. It is only called by its name in the main() function of a program. We can pass the parameters to a function calling in the main() function.
The steps you must follow to create an example are outlined below: Write a simple function in C that passes parameters and returns values the way you want your assembly routine to. Use the SRC directive (#PRAGMA SRC at the top of the file) so that the C compiler generates a . SRC file instead of a . OBJ file.
Ok, now it does something, I'll annotate it for you
calc:
pushl %ebp ; \
movl %esp, %ebp ; / set up basic stack frame
movl 8(%ebp), %edx ; load x
movl 16(%ebp), %ecx ; load z
leal (%edx,%edx,2), %edx ; calculate x + 2 * x
movl 12(%ebp), %eax ; load y
leal (%edx,%eax,2), %eax ; calculate (x + 2 * x) + (2 * y)
movl %ecx, %edx ; make a temp copy of z
sall $4, %edx ; calculate z * 16
subl %ecx, %edx ; calculate (z * 16) - z
addl %edx, %eax ; calculate final sum
popl %ebp
ret
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With