Function Call Convention (System V AMD64)
Pass args in registers, preserve callee-saved regs, keep rsp 16-byte aligned.
Code
; sum3(a, b, c) -> a + b + c
; Args: rdi=a, rsi=b, rdx=c ; result in rax
section .text
global sum3
sum3:
mov rax, rdi
add rax, rsi
add rax, rdx
ret
; A non-leaf function that calls printf — must save rbx (callee-saved)
extern printf
fmt: db "n=%d", 10, 0
global show_n
show_n:
push rbx ; save callee-saved reg we will use
mov rbx, rdi ; keep arg across the printf call
sub rsp, 8 ; align rsp to 16 before 'call'
mov rdi, fmt
mov esi, ebx
xor eax, eax ; 0 vector args (variadic ABI)
call printf
add rsp, 8 ; restore rsp
mov rax, rbx ; return n
pop rbx ; restore rbx
retExplanation
The System V AMD64 ABI passes the first 6 integer args in rdi, rsi, rdx, rcx, r8, r9 and returns in rax. Caller-saved registers (rax, rcx, rdx, rsi, rdi, r8-r11) may be clobbered by any call; callee-saved ones (rbx, rbp, r12-r15) must be preserved. rsp must be 16-byte aligned at the moment of 'call' (the call then pushes 8 bytes of return address, leaving the callee with rsp 8 off).
More Assembly Snippets
Hello World via Linux syscall
A freestanding x86-64 program that prints and exits using only kernel syscalls.
Loop Summation (1..N)
Sum integers 1..N with a counted loop using dec/jnz.
strlen — Scan Until NUL
Compute C-string length by scanning memory until a zero byte.
memcpy — Copy with rep movsb
Use the rep movsb string instruction for a tight memory copy.
Bit Manipulation: popcount, ctz, abs
Use BMI/ABM instructions for branchless bit operations.
Read a File via syscalls
open/read/write/close a file using only Linux syscalls.