Linux syscalls
The interface
Linux system calls take the call number in RAX and up to six arguments in RDI, RSI, RDX, R10, R8, R9. The SYSCALL instruction enters the kernel, which returns the result in RAX:
mov rax, 1 ; sys_write mov rdi, 1 ; fd: stdout mov rsi, msg ; buffer mov rdx, len ; count syscall ; rax = bytes written
The common numbers
The calls you will use most: 0 read, 1 write, 2 open, 3 close, 60 exit, and 231 exit_group. On Debian and Ubuntu the full table lives in /usr/include/x86_64-linux-gnu/asm/unistd_64.h:
%define SYS_READ 0 %define SYS_WRITE 1 %define SYS_OPEN 2 %define SYS_CLOSE 3 %define SYS_EXIT 60
Error returns
A failed syscall returns a negative errno in RAX, between -4095 and -1. Test the sign of RAX, and negate it to get the errno value. Unlike libc, raw syscalls set no C library variables.
Questions
A new set of questions in a new order every time. Choose one answer for each, then check.
-
Which registers hold the arguments of a Linux system call?
Answer
RDI, RSI, RDX, R10, R8, R9
The call number is in RAX, and the six argument registers start at RDI.
-
Which register holds the system call number?
Answer
RAX
Linux selects the call by the number in RAX.
-
What is the call number of write on x86-64 Linux?
Answer
1
0 is read, 1 is write, 2 is open and 60 is exit.
-
What does a failed syscall return in RAX?
Answer
A negative errno between -4095 and -1
The kernel returns -errno, so the sign of RAX tells success from failure.
-
Which call ends the whole process, including every thread?
Answer
231 exit_group
exit ends the calling thread; exit_group ends every thread of the process.
-
How many arguments can a Linux system call take?
Answer
6
Six registers carry the arguments: RDI, RSI, RDX, R10, R8 and R9.
-
What does this program print?
default rel section .data msg db "OS", 10 section .text global _start _start: mov rax, 1 mov rdi, 1 mov rsi, msg mov rdx, 3 syscall mov rax, 60 xor rdi, rdi syscallAnswer
OS
write prints the two letters and the newline from the buffer.
-
What exit status does this program return?
section .text global _start _start: mov rax, 60 mov rdi, 1 syscallAnswer
1
The first argument of exit is the status, and rdi is 1.
-
What does
%define SYS_EXIT 60do?Answer
It names the constant 60 for the assembler
A %define is a preprocessor name, replaced by its value when the file is assembled.
-
Which call reads bytes from a file descriptor?
Answer
0 read
read takes the descriptor, the buffer and the count, and returns the bytes read.
The snippets on this page are fragments, not whole programs: they show the syscall interface. They were assembled with NASM 3.01 on Alpine Linux 3.24.3 (x86_64) in a Docker container.
Article author: Arthur Isaev