x86-64 asm 中的函数参数

Function arguments in x86-64 asm

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

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

这是有效的代码:

.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

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

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

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

.globl main
main:
    subq , %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 , %rsp           # restore stack
    ret                     # done

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

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

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