c - 将参数从 C 传递到 64 位的 GNU 汇编函数

标签 c assembly x86 x86-64

我在 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/

相关文章:

c - 了解stm8s反汇编中的功能?

performance - 组装一些与 nasm 宏不相符的代码

linux - 多个命令 grep

.net - 将 CLR 主机注入(inject)正在运行的进程 - 可能吗?

c++ - 为什么需要类型转换 (UINT)(void*)(DWORD)?

c - 如何在 C 中不缓冲地打开和读取文件?

objective-c - 指针和opengl绘图的问题

gcc - 为什么我不能使用 `section .data:` 和 `section .text:` 在 C 中创建长度超过 61 个字符的 char 数组?

c - C写的shell只执行一次

c - 尝试从 C 生成汇编代码