我正在尝试理解这段汇编代码与上面的C代码的关系。我不确定自己是否正确,希望有人能帮助我更好地理解。
int silly(int n, int *p)
{
int val, val2;
if (n > 0)
val2 = silly(n << 1, &val);
else
val = val2 = 0;
*p = val + val2 + n;
return val + val2;
}
这将产生以下机器代码:
silly:
pushl %ebp // Here I am making space for the function on the stack
movl %esp,%ebp // Moving the stack pointer where the base pointer is
subl $20,%esp // Subtracting 20 from the stack pointer to allocate more space
pushl %ebx // Pushing the %ebx register on top of the stack
movl 8(%ebp),%ebx // Getting the first argument(which is n) and store it in register %ebx
testl %ebx,%ebx // The first if-statement which compares if n > 0
jle .L3 // Jump if less or equal - meaning if n < 0 then jump to .L3
addl $-8,%esp // Add -8 to %esp to allocate more space
leal -4(%ebp),%eax // Storing the first local variable (which is val) in %eax
pushl %eax // Pushing the register %eax on top of the stack
leal (%ebx,%ebx),%eax // n + n and stores it as 2n in %eax
pushl %eax // Pushing register %eax on top of the stack (Which I find strange
// considering that I've just pushed %eax onto the stack above
call silly // Call the function silly
jmp .L4 // Jump to .L4 (Unconditionally)
.p2align 4,,7 // Don't know what this means.
.L3: // .L3 is the else-statement
xorl %eax,%eax // Basically making %eax = 0
movl %eax,-4(%ebp) // Moving the value in %eax which is 0 to the first local variable
// meaning val = 0
.L4: // .L4 is the section after the else-statement
movl -4(%ebp),%edx // Getting val again and now storing it in %edx
addl %eax,%edx // Adding what is in %eax (which is 0) to %edx
movl 12(%ebp),%eax // Getting the second parameter (*p) and storing it in %eax
addl %edx,%ebx // Adding value from %edx to %ebx - meaning val + n
movl %ebx,(%eax) // Moving what is in %ebx and storing it in memory location of %eax
movl -24(%ebp),%ebx // Getting the second local variable (val2) and moving it to %ebx
movl %edx,%eax // Move val to %eax - and the return value will be in %eax
movl %ebp,%esp
popl %ebp
ret
我正在努力理解它,刚开始学习汇编语言,所以关于这个主题的指针将非常有用。我有几个问题需要询问这个汇编代码,这可能有助于我理解堆栈:
(a) 变量 `val` 是否存储在堆栈中?
(b) 如果是,相对于 %ebp,它存储在什么字节偏移量上?
(c) 为什么需要将其存储在堆栈中?
(a) 变量 `val2` 是否存储在堆栈中?
(b) 如果是,相对于 %ebp,它存储在什么字节偏移量上?
(c) 为什么需要将其存储在堆栈中?
(a) -24(%ebp) 存储了什么(如果有)?
(b) 如果在此处存储了某些东西,为什么需要将其存储?
(a) -8(%ebp) 存储了什么(如果有)?
(b) 如果在此处存储了某些东西,为什么需要将其存储?
提前感谢您的帮助 :)
val2
未初始化。有时候,val
也是未初始化的。 - wildplasser