我在 C 中有 main 函数,它在汇编中运行代码。我只想简单求和:
主.c
#include <stdio.h>
extern int addByAssembly(int first_number, int second_number);
int main (int argc, char **argv)
{
int sum=0;
sum = addByAssembly(5,4);
printf ("%d\n",sum);
return 0;
}
addByAssembly.s
.data
SYSREAD = 0
SYSWRITE = 1
SYSEXIT = 60
STDOUT = 1
STDIN = 0
EXIT_SUCCESS = 0
.text
#.global main
#main:
#call write
#movq $SYSEXIT, %rax
#movq $EXIT_SUCCESS, %rdi
#syscall
#********
.globl addByAssembly
addByAssembly:
pushq %rbp
movq %rsp, %rbp
movq 16(%rsp), %rax
addq 24(%rsp), %rax
movq %rbp, %rsp
popq %rbp
但是我的总和一团糟。看起来我传递参数很糟糕,因为如果我这样做:
movq $123, %rax
返回值为 123。我尝试了很多方法,但找不到如何正确求和。
最佳答案
感谢“Jester”付出如此多的努力和时间来让我解释这个!
总结一下。将参数从 C 传递给 As(以及从 As 传递给 C)有自己的 ABI convention . 如您所见,参数按顺序发送: 1) rdi 2) 强弱指数 3)RDX ...等等...
如果你有比约定更多的参数,它将被插入堆栈。
所以就我而言:
.globl addByAssembly
addByAssembly:
pushq %rbp
movq %rsp, %rbp
--movq 16(%rsp), %rax #this was wrong as my params are
--addq 24(%rsp), %rax # first in %rdi, second in %rsi
++lea (%rdi, %rsi), %rax # in my case this line will do
# %rdi+%rsi -> %rax (learn lea, usefull command)
# REMEMBER return value is always in %rax!
movq %rbp, %rsp
popq %rbp
关于c - 将参数从 C 传递到 64 位的 GNU 汇编函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36610530/