Error codes and logging
Error returns
Raw syscalls return errors as a negative number in RAX, between -4095 and -1. Check the sign of RAX after every call that can fail, and negate it to get the positive errno:
syscall
cmp rax, 0
jge ok ; no error
neg rax ; rax = errno
; handle the error
ok:
errno values
Common errnos: 2 ENOENT (no such file), 5 EIO, 9 EBADF (bad descriptor), 13 EACCES, 17 EEXIST, 22 EINVAL. The list is in errno.h. Your program maps them to a message table and prints the text.
Writing a log
A log is a file opened with O_APPEND (0x400), written with sys_write, and closed with sys_close. Write one line per event: timestamp, severity, message, newline. Opening and closing per line is slow but simple; keeping the descriptor open is the production version.
The code on this page was assembled with NASM 3.01 and linked with GNU ld 2.45.1, and the program was run on Alpine Linux 3.24.3 (x86_64) in a Docker container.
Article author: Arthur Isaev