In this article I will describe the process of calling C functions from assembler.
Let’s try to call printf ( “Hello World \ n!”); and exit (0);
section .rodata
message: db "Hello, world!", 10, 0
section .text
extern printf
extern exit
global main
main:
xor rax, rax
mov rdi, message
call printf
xor rdi, rdi
call exit
Everything is much simpler than it seems, in the section .rodata we describe the static data, in this case the string “Hello, world!”, 10 it is a newline character, and will not forget it annihilate the.
The section of code declare outside of the printf function, exit libraries, stdio, stdlib, also declare main entry function:
section .text
extern printf
extern exit
global main
In the case of the return function rax pass 0, can be used mov rax, 0; but to accelerate the use xor rax, rax; Further, in the first argument is a pointer to a string:
rdi, message
Next call external C functions printf:
main:
xor rax, rax
mov rdi, message
call printf
xor rdi, rdi
call exit
By analogy, transfer case 0 in the first argument and calling exit:
xor rdi, rdi
call exit
As the Elves say:
Who does not listen
He eats plov @Alexander Pelevin
References
https://www.devdungeon.com/content/how-mix-c-and-assembly
https://nekosecurity.com/x86-64-assembly/part-3-nasm-anatomy-syscall-passing-argument
https://www.cs.uaf.edu/2017/fall/cs301/reference/x86_64.html
Source Code
https://gitlab.com/demensdeum/assembly-playground