1---
 2title: "Calling assembly functions from C"
 3url: calling-assembly-functions-from-c.html
 4date: 2024-06-17T16:12:13+02:00
 5type: note
 6draft: false
 7tags: [c]
 8---
 9
10This is using the portable GNU assembler and TinyCC compiler but GCC or Clang
11can be used as well.
12
13First lets define a simple function in assembly.
14
15```asm
16# sum.s
17.intel_syntax noprefix
18
19.global sum
20
21.text
22
23sum:
24    add rdi, rsi
25    mov rax, rdi
26    ret
27```
28
29Lets compile this with GNU assembler `as sum.s -o sum.o`.
30
31Now we need a C program that calls this function.
32
33```c
34// main.c
35#include <stdio.h>
36
37// We need to define the signature of the function.
38int sum(int a, int b);
39
40int main() {
41    for(int i=0; i<10; ++i) {
42        printf("SUM of 5+%d is %d\n", i, sum(5, i));
43    }
44    return 0;
45}
46```
47
48Now lets compile and link into final program with `tcc main.c sum.o -o main`.
49
50Use this table to see what each register is being used for.
51
52| Register | Conventional use                | Low 32-bits | Low 16-bits | Low 8-bits |
53|----------|---------------------------------|-------------|-------------|------------|
54| %rax     | Return value, caller-saved      | %eax        | %ax         | %al        |
55| %rdi     | 1st argument, caller-saved      | %edi        | %di         | %dil       |
56| %rsi     | 2nd argument, caller-saved      | %esi        | %si         | %sil       |
57| %rdx     | 3rd argument, caller-saved      | %edx        | %dx         | %dl        |
58| %rcx     | 4th argument, caller-saved      | %ecx        | %cx         | %cl        |
59| %r8      | 5th argument, caller-saved      | %r8d        | %r8w        | %r8b       |
60| %r9      | 6th argument, caller-saved      | %r9d        | %r9w        | %r9b       |
61| %r10     | Scratch/temporary, caller-saved | %r10d       | %r10w       | %r10b      |
62| %r11     | Scratch/temporary, caller-saved | %r11d       | %r11w       | %r11b      |
63| %rsp     | Stack pointer, callee-saved     | %esp        | %sp         | %spl       |
64| %rbx     | Local variable, callee-saved    | %ebx        | %bx         | %bl        |
65| %rbp     | Local variable, callee-saved    | %ebp        | %bp         | %bpl       |
66| %r12     | Local variable, callee-saved    | %r12d       | %r12w       | %r12b      |
67| %r13     | Local variable, callee-saved    | %r13d       | %r13w       | %r13b      |
68| %r14     | Local variable, callee-saved    | %r14d       | %r14w       | %r14b      |
69| %r15     | Local variable, callee-saved    | %r15d       | %r15w       | %r15b      |
70| %rip     | Instruction pointer             |             |             |            |
71| %rflags  | Status/condition code bits      |             |             |            |
72
73You can read more about [x86-64 Machine-Level Programming](/assets/notes/asm64-handout.pdf).
74