[英]How to call C function printf for an integer from assembly code
我無法從匯編代碼調用printf。 我的函數end_power用於從power打印結果,但是每當我調用printf時,都會遇到分段錯誤。 (我正在64位Linux上運行該程序)唯一不起作用的部分是end_power函數,更具體地說,是調用printf涉及的行
# 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:
#
# %rbx - holds the base number
# %rcx - holds the power
#
# -8(%rbp) - holds the current result
#
# %rax is used for temporary storage
#
.type power, @function
power:
pushq %rbp # save old base pointer
movq %rsp, %rbp # make stack pointer the base pointer
subq $8, %rsp # get room for our local storage
movq 16(%rbp), %rbx # put first argument in %rax
movq 24(%rbp), %rcx # put second argument in %rcx
movq %rbx, -8(%rbp) # store current result
power_loop_start:
cmpq $1, %rcx # if the power is 1, we are done
je end_power
movq -8(%rbp), %rax # move the current result into %rax
imulq %rbx, %rax # multiply the current result by
# the base number
movq %rax, -8(%rbp) # store the current result
decq %rcx # decrease the power
jmp power_loop_start # run for the next power
end_power:
movq -8(%rbp), %rdi # return value goes in %rdi
pushq -8(%rbp)
pushq $fmtdec
call printf
add $16, %rsp
movq %rbp, %rsp # restore the stack pointer
popq %rbp # restore the base pointer
ret
64位Linux的調用約定與32位Linux的調用約定有很大不同。 看一下: http : //en.wikipedia.org/wiki/X86_calling_conventions#System_V_AMD64_ABI
更改
pushq -8(%rbp)
pushq $fmtdec
call printf
add $16, %rsp
至
mov $fmtdec,%rdi
mov -8(%rbp),%rsi
xor %eax, %eax
call printf
並認為這會覆蓋您以前在RDI中的“返回值”。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.