user2678074
user2678074

Reputation: 825

Passing parameters from C to GNU Assembly function in 64bit

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.

Upvotes: 1

Views: 1646

Answers (1)

user2678074
user2678074

Reputation: 825

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

Upvotes: 1

Related Questions