can anyone help me understand this assembly code? I'm totally new to the assembly language and I just can't figure it out... The following assembly code should produce this function:
func(int a) { return a * 34 }
The comments // are my thoughts what it should mean, please correct me if I'm wrong
//esp = stack-pointer, ebp = callee saved, eax = return value
pushl %ebp // a is pushed on stack
movl %esp,%ebp // a = stackpointer
movl 8(%ebp),%eax // eax = M(8 + a).But what is in M(8 + a)?
sall $4,%eax // eax << 4
addl 8(%ebp),%eax // eax = M(8 + a)
addl %eax,%eax // eax = eax + eax
movl %ebp,%esp // eax = t
popl %ebp // pop a from stack
ret
Could someone please explain me how to figure this out? Thanks a lot!
pushl %ebp // a is pushed on stack
movl %esp,%ebp // a = stackpointer
As noted in a comment, ebp has nothing to do with a. ebp is the stack base pointer -- this code saves the old value of ebp to the stack, then saves the stack pointer in ebp.
movl 8(%ebp),%eax // eax = M(8 + a).But what is in M(8 + a)?
Correct. What's on the stack is the input value of eax.
sall $4,%eax // eax << 4
Correct. (And the result is assigned back to eax.)
addl 8(%ebp),%eax // eax = M(8 + a)
No, you've misunderstood this. This adds the value on the stack at 8(ebp) -- which is the original value of a -- to eax. The addition is applied to the values, not memory addresses.
addl %eax,%eax // eax = eax + eax
Correct. The value of eax is not modified beyond here, so this is the return value of the function.
movl %ebp,%esp // eax = t
popl %ebp // pop a from stack
ret
This code reverses the effects of the first two instructions. It's a standard cleanup sequence, and has nothing to do with a.
The important parts of this function can be glossed as:
a1 = a << 4; // = a * 16
a2 = a1 + a; // = a * 17
a3 = a2 + a2; // = a * 34
return a3;
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