汇编代码的退出状态不一致

时间:2015-03-01 01:05:05

标签: assembly x86

我正在执行#34;从头开始编程"书,我不断得到奇怪的输出。

这一个例如输出:13而不是12.如果我改变参数我继续得到错误的输出。如果我输入2-3和2-3输出应该是16但它是18 ...只有当我使用2的倍数时似乎是正确的。喜欢,2-4和2-4工作正常,输出是32谁知道什么事了?谢谢!

#PURPOSE: Program to illustrate how functions work
# This program will compute the value of
# 2^3 + 5^2
#
#Everything in the main program is stored in registers,
#so the data section doesn’t have anything.
.section .data
.section .text
.globl _start
_start:
pushl $2 #push second argument
pushl $2 #push first argument
call power #call the function
addl $8, %esp #move the stack pointer back

pushl %eax #save the first answer before
#calling the next function
pushl $2 #push second argument
pushl $3 #push first argument
call power #call the function
addl $8, %esp #move the stack pointer back
popl %ebx #The second answer is already
#in %eax. We saved the
#first answer onto the stack,
#so now we can just pop it
#out into %ebx
addl %eax, %ebx #add them together
#the result is in %ebx
movl $1, %eax #exit (%ebx is returned)
int $0x80
#PURPOSE: This function is used to compute
# the value of a number raised to
# a power.
#
#INPUT: First argument - the base number
# Second argument - the power to
# raise it to
#
#OUTPUT: Will give the result as a return value
#
#NOTES: The power must be 1 or greater
#VARIABLES:
# %ebx - holds the base number
# %ecx - holds the power
#
# -4(%ebp) - holds the current result
#
# %eax is used for temporary storage
#
.type power, @function
power:
pushl %ebp #save old base pointer
movl %esp, %ebp #make stack pointer the base pointer
subl $4, %esp #get room for our local storage
movl 8(%ebp), %ebx #put first argument in %eax
movl 12(%ebp), %ecx #put second argument in %ecx
movl %ebx, -4(%ebp) #store current result
power_loop_start:
cmpl $1, %ecx #if the power is 1, we are done
je end_power
movl -4(%ebp), %eax #move the current result into %eax
imull %ebx, %eax #multiply the current result by
#the base number
movl %eax, -4(%ebp) #store the current result
decl %ecx #decrease the power
jmp power_loop_start #run for the next power
end_power:
movl -4(%ebp), %eax #return value goes in %eax
movl %ebp, %esp #restore the stack pointer
popl %ebp #restore the base pointer
ret

1 个答案:

答案 0 :(得分:2)

答案是正确的,你正在解释错误的代码。

power函数将第一个参数引发到第二个参数,但由于push它们在代码中以相反的顺序出现。按照评论,这一切都在那里解释:

pushl $2 #push second argument
pushl $3 #push first argument
call power #call the function

因此,该函数将计算3^2 9。向2^2=4添加13确实会提供{{1}}。