gpt4 book ai didi

assembly - 将 scanf 与 x86-64 GAS 组件结合使用

转载 作者:行者123 更新时间:2023-12-02 15:42:57 25 4
gpt4 key购买 nike

我在尝试调用系统函数 scanf 以在我的 x86 汇编程序中工作时遇到了很多问题。目前我已经让它从标准中读取,但是它只会读取没有段错误的字符(我不知道为什么,指定字符串是%d)。我在网上看到的 x86 中的 scanf 示例使用 quarky 或使用 NASM 语法编写,因此我尝试将它们改编为我的程序。

f:
.string "%d"

_main:
movq $0, %rax #Clean rax
movq $f, %rdi #Load string format
movq %rcx, %rsi #Set storage to rcx (Not sure if this is valid)
call scanf
ret

在输入字符或字符串后,使用 printf 检查 rcx 和 rax 分别返回 1 和 0(这是程序不会出现段错误的唯一方法)。

任何有关如何在 x86 气体组装中正确使用 scanf 的见解将非常感激!

最佳答案

正如您担心的那样,movq %rcx, %rsi 不正确。您需要传递一个指向内存的指针。寄存器不是内存地址空间的一部分,因此不能有指向它们的指针。您需要全局或本地分配存储。顺便说一句,您不应将数据(尤其是可写数据)放入默认的 .text 部分,因为该部分用于代码并且通常是只读的。另外,调用约定通常要求 16 字节堆栈指针对齐,因此您也应该注意这一点。

.globl main

main:
push %rbp # keep stack aligned
mov $0, %eax # clear AL (zero FP args in XMM registers)
leaq f(%rip), %rdi # load format string
leaq x(%rip), %rsi # set storage to address of x
call scanf
pop %rbp
ret

.data

f: .string "%d" # could be in .rodata instead
x: .long 0

(如果您的环境需要符号上有前导下划线,则使用 _main,也可能使用 _scanf。)

<小时/>

将符号/标签的地址放入寄存器实际上有 3 种选择。与 RIP 相关的 LEA 是 x86-64 上的标准方式。 How to load address of function or label into register in GNU Assembler

作为一种优化,如果您的变量位于地址空间的较低 4GiB 中,例如在 Linux 非 PIE(位置依赖)可执行文件中,您可以使用 32 位绝对立即数:

    mov  $f, %edi       # load format string
mov $x, %esi # set storage to address of x

movq $f, %rdi 将使用 32 位符号扩展立即数(而不是通过写入 EDI 隐式零扩展到 RDI),但具有与 RIP 相同的代码大小-相对LEA。

您还可以使用助记符 movabsq 加载完整的 64 位绝对地址。但不要这样做,因为 10 字节指令不利于代码大小,并且仍然需要运行时修复,因为它与位置无关。

    movabsq $f, %rdi # load format string
movabsq $x, %rsi # set storage to address of x
<小时/>

根据要求:使用局部变量进行输出可能如下所示:

    subq  $8, %rsp       # allocate 8 bytes from stack
xor %eax, %eax # clear AL (and RAX)
leaq f(%rip), %rdi # load format string
movq %rsp, %rsi # set storage to local variable
call scanf
addq $8, %rsp # restore stack
ret

关于assembly - 将 scanf 与 x86-64 GAS 组件结合使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27095286/

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