gpt4 book ai didi

c - 如何从汇编代码中调用 C 函数 printf 获取整数

转载 作者:行者123 更新时间:2023-11-30 17:28:15 27 4
gpt4 key购买 nike

我在从汇编代码调用 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 中的“返回值”。

关于c - 如何从汇编代码中调用 C 函数 printf 获取整数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26086481/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com