linux - x86-64 asm 中的函数参数

标签 linux assembly command-line x86-64 calling-convention

所以我必须为学校做这个项目,包括用 brainfuck 读取文件并将其解释为程序集。如果我将文件路径保存为 .data 部分中的字符串,则代码有效,但我想要它,以便在终端中启动代码时将文件路径作为参数获取。

我尝试弹出 3 次(因为堆栈应该是参数的数量/程序的地址/第一个参数),然后将 %rdi 设置为第三个弹出项的地址处的值,但它返回“./解释器”而不是文件路径

这是有效的代码:

.data
filePath: .asciz "brainF.b"
fileRead: .asicz "r"

.text
.global main
main:
    call fileReader #moves filePath to %rdi, fileRead to %rsi, calls fopen and reads the file
    #code that grabs the read string and interprets it

但我想要的是:

.data
fileRead: .asciz "r"

.text
.global main
main:
    #get 1st argument from terminal(file path) and store it in %rdi
    call fileReader #moves fileRead to %rsi, calls fopen and reads the file

下面是我必须如何编译和链接(这部分不能更改,这是我的老师要我做的):

gcc -o interpreter interpreter.s
./interpreter brainF.b

最佳答案

64 位调用约定在寄存器中传递前 6 个函数参数,因此 argcrdi 中,而 argvrsi 。第一个命令行参数是 argv[1] 所以要访问它你需要加载 8(%rsi):

.globl main
main:
    subq $8, %rsp           # align stack
    movq 8(%rsi), %rsi      # fetch argv[1]
    leaq fmt(%rip), %rdi    # format string
    xorl %eax, %eax         # no xmm used
    call printf             # print
    xorl %eax, %eax         # zero return value
    addq $8, %rsp           # restore stack
    ret                     # done

.data
fmt: .string "First argument is %s\n"

$ ./a.out foo bar
First argument is foo

当然你应该检查 argc 看看你是否收到了足够的参数。

关于linux - x86-64 asm 中的函数参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32885373/

相关文章:

Java Selenium Firefox 驱动程序 - 文本框 Onchange 问题

linux - 无法在 docker 文件中使用 Chown 更改文件夹所有权

linux - 如何在 Linux 上读取 RTS/CTS 引脚的值?

linux - 绕行和 GCC 内联汇编 (Linux)

c - 如何使用 Turbo C 2.01 编写内联汇编?

java - 从命令行运行在intellij中创建的java程序

linux - 如何设置 flatpak 应用程序在启动时运行?

c - 这种没有推送寄存器的交换有多安全?

linux - 修改之前在linux上执行的命令

linux - 如何永久更改vim编辑器的默认选项?