System Calls in Depth
Without the C library, the syscall instruction is your program's only door to the outside world: files, memory, processes, time and the network all go through the Linux kernel. This lesson looks at the conventions in detail, at how errors are reported, and at a handful of useful calls.
The convention, once more
| Register | Role |
|---|---|
rax |
system call number in, result out |
rdi, rsi, rdx, r10, r8, r9 |
arguments 1–6 (note r10, not rcx, for the 4th) |
rcx, r11 |
overwritten (the CPU stores the return address and flags there) |
| everything else | preserved |
The 4th argument moves from rcx to r10 because the syscall instruction itself uses rcx. Some commonly used x86-64 Linux system calls:
rax |
Name | Arguments | Returns |
|---|---|---|---|
| 0 | read |
fd, buffer, count | bytes read (0 = end of file) |
| 1 | write |
fd, buffer, count | bytes written |
| 2 | open |
path, flags, mode | a new file descriptor |
| 3 | close |
fd | 0 |
| 9 | mmap |
addr, length, prot, flags, fd, offset | address of the new mapping |
| 11 | munmap |
addr, length | 0 |
| 12 | brk |
new end of the data segment | the current end |
| 39 | getpid |
— | process id |
| 60 | exit |
status | does not return |
| 231 | exit_group |
status | ends all threads |
The full list is in the kernel source (arch/x86/entry/syscalls/syscall_64.tbl) and man 2 syscalls.
Errors are negative return values
A failing system call does not set a flag or raise an exception: it returns −errno in rax, a value between −4095 and −1. (The C library turns that into -1 plus the global errno.) Writing to a file descriptor that isn't open returns -9, which is EBADF, "bad file descriptor":
section .data
msg: db "hello?", 10
missing_path: db "/no/such/file.txt", 0
section .text
global _start
_start:
mov eax, 1 ; write
mov edi, 99 ; a file descriptor that isn't open
mov rsi, msg
mov edx, 7
syscall
mov rdi, rax
call print_int ; -9 = -EBADF
mov eax, 2 ; open
mov rdi, missing_path
xor esi, esi ; O_RDONLY
syscall
mov rdi, rax
call print_int ; -2 = -ENOENT: no such file
mov eax, 60
xor edi, edi
syscall
; ---- print_int: print rdi as a signed decimal number and a newline ----
print_int:
test rdi, rdi
jns print_uint ; not negative: print it as it is
neg rdi ; make it positive
push rdi ; keep it (write and syscall clobber registers)
push '-' ; the minus sign, as a byte on the stack
mov eax, 1 ; write(1, rsp, 1)
mov edi, 1
mov rsi, rsp
mov edx, 1
syscall
pop rdi ; drop the '-'
pop rdi ; the positive value again
jmp print_uint ; print_uint's ret returns to our caller
; ---- print_uint: print rdi as an unsigned decimal number and a newline ----
print_uint:
mov rax, rdi ; rax = the number to convert
sub rsp, 32 ; room for up to 20 digits and a newline
lea rsi, [rsp + 31] ; fill the buffer from its end
mov byte [rsi], 10 ; the newline is the last character
mov ecx, 10
.next_digit:
xor edx, edx ; the dividend is rdx:rax, so clear rdx
div rcx ; rax = quotient, rdx = remainder (0..9)
add dl, '0' ; remainder -> ASCII digit
dec rsi
mov [rsi], dl ; store it in front of the previous one
test rax, rax
jnz .next_digit ; repeat until the quotient is 0
lea rdx, [rsp + 32]
sub rdx, rsi ; rdx = number of bytes to print
mov eax, 1 ; write(1, rsi, rdx)
mov edi, 1
syscall
add rsp, 32
ret-9
-2
| errno | Name | Meaning |
|---|---|---|
| 2 | ENOENT |
no such file or directory |
| 9 | EBADF |
bad file descriptor |
| 12 | ENOMEM |
out of memory |
| 13 | EACCES |
permission denied |
| 14 | EFAULT |
bad address (you passed an invalid pointer) |
| 22 | EINVAL |
invalid argument |
Check results with test rax, rax / js .error: every error is negative.
Standard error and exit codes
File descriptor 2 is standard error. Error messages go there so they don't mix with a program's real output when that output is redirected to a file. Combined with a non-zero exit status, this is how a well-behaved command-line tool reports failure:
section .data
result: db "partial result", 10
result_len equ $ - result
error: db "error: input file is empty", 10
error_len equ $ - error
section .text
global _start
_start:
mov eax, 1
mov edi, 1 ; standard output
mov rsi, result
mov edx, result_len
syscall
mov eax, 1
mov edi, 2 ; standard error
mov rsi, error
mov edx, error_len
syscall
mov eax, 60
mov edi, 3 ; exit status 3: "something went wrong"
syscallpartial result
error: input file is empty
In a terminal both lines appear on the screen. With ./tool > out.txt only the first one goes to the file, and echo $? prints 3. The playground shows standard output first and then standard error.
Reading input
read(fd, buffer, count) returns how many bytes it got, and 0 at end of file. The playgrounds run programs with empty input, so a read from file descriptor 0 immediately reports end of file:
section .bss
buffer: resb 64
section .text
global _start
_start:
xor eax, eax ; read
xor edi, edi ; fd 0 = standard input
mov rsi, buffer
mov edx, 64
syscall
mov rdi, rax
call print_int ; 0 bytes: end of input
mov eax, 60
xor edi, edi
syscall
; ---- print_int: print rdi as a signed decimal number and a newline ----
print_int:
test rdi, rdi
jns print_uint ; not negative: print it as it is
neg rdi ; make it positive
push rdi ; keep it (write and syscall clobber registers)
push '-' ; the minus sign, as a byte on the stack
mov eax, 1 ; write(1, rsp, 1)
mov edi, 1
mov rsi, rsp
mov edx, 1
syscall
pop rdi ; drop the '-'
pop rdi ; the positive value again
jmp print_uint ; print_uint's ret returns to our caller
; ---- print_uint: print rdi as an unsigned decimal number and a newline ----
print_uint:
mov rax, rdi ; rax = the number to convert
sub rsp, 32 ; room for up to 20 digits and a newline
lea rsi, [rsp + 31] ; fill the buffer from its end
mov byte [rsi], 10 ; the newline is the last character
mov ecx, 10
.next_digit:
xor edx, edx ; the dividend is rdx:rax, so clear rdx
div rcx ; rax = quotient, rdx = remainder (0..9)
add dl, '0' ; remainder -> ASCII digit
dec rsi
mov [rsi], dl ; store it in front of the previous one
test rax, rax
jnz .next_digit ; repeat until the quotient is 0
lea rdx, [rsp + 32]
sub rdx, rsi ; rdx = number of bytes to print
mov eax, 1 ; write(1, rsi, rdx)
mov edi, 1
syscall
add rsp, 32
ret0
Run locally, echo hi | ./prog would print 3 (the bytes h, i and a newline).
Getting memory with mmap
There is no malloc without libc, but the kernel hands out memory directly. mmap with MAP_PRIVATE | MAP_ANONYMOUS returns fresh, zero-filled pages:
PROT_READ equ 1
PROT_WRITE equ 2
MAP_PRIVATE equ 0x02
MAP_ANONYMOUS equ 0x20
section .text
global _start
_start:
mov eax, 9 ; mmap
xor edi, edi ; let the kernel choose the address
mov esi, 4096 ; one page
mov edx, PROT_READ | PROT_WRITE
mov r10d, MAP_PRIVATE | MAP_ANONYMOUS ; 4th argument in r10!
mov r8, -1 ; no file
xor r9d, r9d ; offset 0
syscall
test rax, rax
js .failed
mov rbx, rax ; rbx = our new memory
; use it: store the squares 0..9 as quadwords
xor ecx, ecx
.fill:
mov rax, rcx
imul rax, rcx
mov [rbx + rcx*8], rax
inc ecx
cmp ecx, 10
jb .fill
mov rdi, rbx
mov esi, 10
call print_array
mov eax, 11 ; munmap: give it back
mov rdi, rbx
mov esi, 4096
syscall
.failed:
mov eax, 60
xor edi, edi
syscall
; ---- print_array: print rsi unsigned quadwords starting at rdi on one line ----
print_array:
push rbx
push r12
mov rbx, rdi ; rbx = address of the next element
mov r12, rsi ; r12 = elements left
sub rsp, 32 ; digit buffer, as in print_uint
.element:
test r12, r12
jz .finish
mov rax, [rbx] ; the number to convert
lea rsi, [rsp + 31]
mov byte [rsi], ' ' ; a space after each number ...
cmp r12, 1
jne .convert
mov byte [rsi], 10 ; ... except the last one, which ends the line
.convert:
mov ecx, 10
.digit:
xor edx, edx
div rcx
add dl, '0'
dec rsi
mov [rsi], dl
test rax, rax
jnz .digit
lea rdx, [rsp + 32]
sub rdx, rsi ; length of digits + separator
mov eax, 1
mov edi, 1
syscall
add rbx, 8 ; next quadword
dec r12
jmp .element
.finish:
add rsp, 32
pop r12
pop rbx
ret0 1 4 9 16 25 36 49 64 81
We never print the address itself: with address-space layout randomization it differs on every run.
Watching system calls with strace
On your own machine, strace lists every system call a program makes, with decoded arguments and results — invaluable when a call fails:
$ strace ./errors
execve("./errors", ["./errors"], 0x7ffd... /* 20 vars */) = 0
write(99, "hello?\n", 7) = -1 EBADF (Bad file descriptor)
open("/no/such/file.txt", O_RDONLY) = -1 ENOENT (No such file or directory)
write(1, "-9\n", 3) = 3
write(1, "-2\n", 3) = 3
exit(0) = ?Test yourself
Which register holds the 4th system call argument?
- rcx
- r10
- rdx
- r8
How does a Linux system call report an error?
- It sets the carry flag
- It returns a negative errno value in rax
- It kills the program
- It writes to stderr
What does read return at end of file?
- -1
- 0
- The buffer size
- It blocks forever