Passing parameters from C to GNU Assembly function in 64bit

坚强是说给别人听的谎言 提交于 2021-02-11 07:09:02

问题


I have main function in C that runs code in assembly. I just want to make simple sum:

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

But i got mess in my sum. It looks like i badly pass arguments, beause if I do this:

movq $123, %rax

return value is 123. I 've tried many ways, but cannot find how to make this properly to sum.


回答1:


Thanks 'Jester' for so much effort and time to get me this explained!

To sum up. Passing parameters from C to As ( and as well from As to C) has its own ABI convention. As you can see there, params are send on order: 1) rdi 2) rsi 3) rdx ... and so on...

In case you have more parameters than in convention, it will be pushed to stack.

So in my case:

.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


来源:https://stackoverflow.com/questions/36610530/passing-parameters-from-c-to-gnu-assembly-function-in-64bit

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!