TExcelTAD

System Calls

A system call (syscall) is the single, controlled doorway from a user program into the kernel. Opening a file, reading from the network, starting a process, allocating memory, asking the time: anything that needs hardware or another process ends in a system call. Programs rarely make them directly; they call a library function such as fopen() in C, open() in Python or File.ReadAllText() in .NET, which makes the system call for them.

What happens during a system call

text
  user mode                                   kernel mode
  ---------                                   -----------
  app: read(fd, buf, 100)
    |
  libc wrapper:
    rax = 0 (read)   rdi = fd
    rsi = buf        rdx = 100
    syscall  -------------------------------> entry: save registers, switch to kernel stack
                                              look up table[rax] -> ksys_read()
                                              check fd, copy data into buf
    <--------------------------------------- sysret: rax = bytes read (or -errno)
  libc: if rax < 0 -> errno = -rax, return -1
    |
  app continues
  1. The library puts the system call number and the arguments in registers (on x86-64 Linux: number in rax, arguments in rdi, rsi, rdx, r10, r8, r9).
  2. The syscall instruction switches the CPU to kernel mode and jumps to the kernel's entry point.
  3. The kernel uses the number as an index into its system call table, checks every argument (pointers must point into the caller's memory, file descriptors must be open, permissions must allow it) and does the work.
  4. It returns a result in rax. On Linux a negative value in the range -1 to -4095 means an error code; the C library stores it in errno and returns -1.

Making system calls without any library

Assembly can call the kernel directly. This program uses raw Linux system calls only: write (number 1), a call number that does not exist (999) and exit (60). The invalid call returns -ENOSYS (-38) in rax; the program turns that number into text and prints it with another write:

nasm · try it yourself
section .data
msg:    db "hello straight from the kernel", 10
len     equ $ - msg
res:    db "syscall 999 returned -00", 10
rlen    equ $ - res

section .text
global _start
_start:
        mov rax, 1          ; syscall 1 = write
        mov rdi, 1          ; fd 1 = standard output
        mov rsi, msg        ; buffer
        mov rdx, len        ; byte count
        syscall             ; rax = bytes written

        mov rax, 999        ; no such system call
        syscall             ; rax = -38 (-ENOSYS)

        neg rax             ; 38
        mov rbx, 10
        xor rdx, rdx
        div rbx             ; rax = 3, rdx = 8
        add al, '0'
        add dl, '0'
        mov [res + rlen - 3], al
        mov [res + rlen - 2], dl

        mov rax, 1          ; write the result line
        mov rdi, 1
        mov rsi, res
        mov rdx, rlen
        syscall

        mov rax, 60         ; syscall 60 = exit
        xor rdi, rdi        ; status 0
        syscall
hello straight from the kernel
syscall 999 returned -38

Watching system calls on Linux

The usual tool is strace, which prints every system call a program makes (sample output, trimmed; yours will differ):

bash
ada@ubuntu:~$ strace -e trace=openat,read,write,close cat hello.txt
openat(AT_FDCWD, "hello.txt", O_RDONLY) = 3
read(3, "hi there\n", 131072)           = 9
write(1, "hi there\n", 9)               = 9
hi there
read(3, "", 131072)                     = 0
close(3)                                = 0
+++ exited with 0 +++
ada@ubuntu:~$ strace -c ls > /dev/null      # -c: count calls instead of listing them

Even without strace, /proc shows a little of the machinery. /proc/self/syscall holds the number of the system call a process is currently blocked in; when cut reads the file, it is in the middle of read, number 0. And /proc/self/fd lists the open file descriptors, the small integers that system calls such as read and write take:

bash · try it yourself
cut -d' ' -f1 /proc/self/syscall          # 0 = read on x86-64
exec 3> notes.txt                         # the shell opens a file as fd 3
ls /proc/self/fd                          # 0 1 2 = standard in/out/err, 3 = notes.txt, 4 = the directory ls is reading
readlink /proc/self/fd/3
cat /no/such/file
echo "exit status $? (the kernel returned -ENOENT)"
0
0
1
2
3
4
/home/learner/notes.txt
cat: /no/such/file: No such file or directory
exit status 1 (the kernel returned -ENOENT)

The message No such file or directory is just the text for error number ENOENT (2) that the kernel returned from openat.

Common Linux system calls

Area System calls
Files openat, read, write, close, lseek, stat, mkdir, unlink, rename
Processes fork/clone, execve, exit_group, wait4, getpid, kill
Memory mmap, munmap, brk, mprotect
Network socket, connect, bind, listen, accept, sendto, recvfrom
Waiting poll, epoll_wait, futex, nanosleep, io_uring_enter

Linux has roughly 450 system calls on x86-64. Their numbers never change: a program compiled in 2005 still runs.

System calls on Windows

Windows has the same mechanism, different conventions:

  • Programs call Win32 functions (CreateFileW, ReadFile, VirtualAlloc) in kernel32.dll/kernelbase.dll.
  • These call the native API in ntdll.dll (NtCreateFile, NtReadFile, NtAllocateVirtualMemory), whose stubs put the service number in eax and execute syscall.
  • The kernel's system service dispatcher looks the number up in the System Service Descriptor Table and calls the routine in ntoskrnl.exe. GUI calls (windows, drawing) go to a second table in win32k.sys.
  • Results come back as an NTSTATUS code (STATUS_SUCCESS = 0, STATUS_OBJECT_NAME_NOT_FOUND = 0xC0000034), which kernel32 translates into a Win32 error (ERROR_FILE_NOT_FOUND = 2) for GetLastError().
  • The service numbers are undocumented and change between Windows builds, so only ntdll.dll may use them directly; that is the stable boundary on Windows.

A disassembled ntdll stub looks like this (sample from one Windows 11 build; the number differs on yours):

text
ntdll!NtReadFile:
    mov  r10, rcx
    mov  eax, 6          ; service number for this build
    test byte ptr [SharedUserData+0x308], 1
    jne  use_int2e
    syscall
    ret

Sysinternals Process Monitor shows file, registry and process activity (at the Win32/driver level rather than raw system calls), and wpr/WPA can record them in detail. A quick look at the error-code translation (sample output):

cmd
C:\Users\ada>type nosuchfile.txt
The system cannot find the file specified.

C:\Users\ada>certutil -error 2
0x2 (WIN32: 2 ERROR_FILE_NOT_FOUND) -- 2 (2)
Error message text: The system cannot find the file specified.
CertUtil: -error command completed successfully.

Linux and Windows side by side

Task C library / Linux syscall Win32 function Native API (ntdll)
Open a file open() / openat CreateFileW NtCreateFile
Read read() / read ReadFile NtReadFile
Allocate memory mmap() / mmap VirtualAlloc NtAllocateVirtualMemory
New process fork() + execve() CreateProcessW NtCreateUserProcess
Wait for a child waitpid() / wait4 WaitForSingleObject NtWaitForSingleObject
Error value errno (e.g. ENOENT = 2) GetLastError() (e.g. ERROR_FILE_NOT_FOUND = 2) NTSTATUS

A system call table, simulated

The kernel's dispatcher is essentially an array of function pointers with argument checks in front. A toy version:

python · try it yourself
ENOENT, EBADF, ENOSYS = 2, 9, 38
files = {"/etc/hostname": b"tad\n"}
fd_table = {0: "/dev/tty", 1: "/dev/tty", 2: "/dev/tty"}   # standard in/out/err

def sys_openat(path):
    if path not in files:
        return -ENOENT
    fd = min(set(range(len(fd_table) + 1)) - set(fd_table))   # lowest free number
    fd_table[fd] = path
    return fd

def sys_read(fd, count):
    if fd not in fd_table:
        return -EBADF
    return files[fd_table[fd]][:count]

def sys_close(fd):
    return 0 if fd_table.pop(fd, None) else -EBADF

TABLE = {0: sys_read, 3: sys_close, 257: sys_openat}           # real x86-64 numbers
NAMES = {0: "read", 3: "close", 257: "openat", 999: "?"}

def syscall(nr, *args):
    handler = TABLE.get(nr)
    result = handler(*args) if handler else -ENOSYS
    shown = ", ".join(repr(a) for a in args)
    print(f"{NAMES[nr]}({shown}) = {result!r}")
    return result

fd = syscall(257, "/etc/hostname")
syscall(0, fd, 100)
syscall(3, fd)
syscall(0, fd, 100)            # already closed
syscall(257, "/etc/nope")
syscall(999)
openat('/etc/hostname') = 3
read(3, 100) = b'tad\n'
close(3) = 0
read(3, 100) = -9
openat('/etc/nope') = -2
?() = -38

Learn more: User Mode & Kernel Mode · Processes · Windows NT Architecture

Go further: Processes, Privileges and System Calls watches the kernel's access decision with strace and uses system calls as evidence.

Test yourself

On Linux, how does the C library report that a system call failed?

  1. It throws an exception
  2. It returns -1 and sets errno
  3. It prints to stderr
  4. It returns 0

Why should Windows programs not issue syscall instructions with hard-coded numbers?

  1. Windows has no system calls
  2. The service numbers change between Windows builds
  3. Only drivers may use syscall
  4. It needs administrator rights

Which Windows function corresponds to Linux's mmap for allocating memory?

  1. HeapFree
  2. VirtualAlloc
  3. CreateFileW
  4. GetLastError