On this page

A file descriptor is an index into a per-process table, and syscall isn’t a call—it’s a transition into ring 0.

In lesson 11, we computed element addresses via base + index*scale + disp. The next layer is the kernel boundary: how a program asks the OS to open a file, why rcx and r11 cannot be trusted across a syscall, where errno comes from, and what the number 3 returned by open actually represents.

Mental Model: An Index Instead of an Address

What it looks like in C99 What happens in hardware
fd holds a physical disk sector address fd is a small integer—an index into the process’s open-file table
syscall is an ordinary call The CPU switches privilege rings, saving the return address in rcx and flags in r11
An error is always -1 The kernel returns negative -errno; the libc wrapper turns it into -1 and sets errno
read always returns the requested byte count A regular file may return fewer bytes—for example, near EOF
O_RDONLY is a distinct non-zero flag O_RDONLY equals 0, so no bit is set in the flags argument

The syscall Instruction: Entering Ring 0

The syscall instruction doesn’t work like call: it never pushes a return address onto the stack. The instruction switches the CPU from user ring 3 to ring 0, reading the entry point address that the kernel pre-loaded into LSTAR. On entry, the hardware saves the next instruction’s address in rcx and RFLAGS in r11; on return, sysret reads the return address back from rcx. Both registers are therefore overwritten on every system call.

Ring 0 (kernel)Ring 3 (user space)Ring 0 (kernel)Ring 3 (user space)rip → rcx, rflags → r11, rip ← LSTARrip ← rcx, rflags ← r11syscall (rax = number, args in rdi, rsi, rdx, r10, r8, r9)1sysret (rax = result)2
Ring 0 (kernel)Ring 3 (user space)Ring 0 (kernel)Ring 3 (user space)rip → rcx, rflags → r11, rip ← LSTARrip ← rcx, rflags ← r11syscall (rax = number, args in rdi, rsi, rdx, r10, r8, r9)1sysret (rax = result)2
Fig. 1. Entering the kernel and returning via syscall/sysret

The rcx_clobber.asm testbed loads recognizable constants into rcx and r11, issues a write, and checks what remains in both registers:

rcx_clobber.asm
; SPDX-License-Identifier: PolyForm-Noncommercial-1.0.0

; rcx_clobber.asm — syscall clobbers rcx (return address) and r11 (RFLAGS).
; GDB inspects after_syscall: rcx == rip and r11 == eflags.

default rel

%define SYS_WRITE 1
%define SYS_OPEN 2
%define SYS_EXIT 60
%define STDOUT 1

section .rodata
    msg: db "syscall clobbers rcx and r11", 10
    msg_len: equ $ - msg
    missing: db "/proc/self/fd/999999", 0

section .text
    global _start

; ------------------------------------------------------------------------------
; _start — loads sentinels into rcx and r11, calls write, then opens a missing file.
; Input:     none
; Output:    does not return; exit code 12: 2 clobbered registers + 10 for -ENOENT
; Clobbers:  rax, rcx, rdx, rsi, rdi, r8, r11, flags
; ------------------------------------------------------------------------------
_start:
    mov rcx, 0x1111111111111111
    mov r11, 0x2222222222222222

    ; syscall: write(STDOUT, msg, msg_len)
    mov eax, SYS_WRITE
    mov edi, STDOUT
    lea rsi, [msg]
    mov edx, msg_len
    syscall

after_syscall:
    xor r8d, r8d
    mov rax, 0x1111111111111111
    cmp rcx, rax
    je .rcx_kept
    inc r8d

.rcx_kept:
    mov rax, 0x2222222222222222
    cmp r11, rax
    je .r11_kept
    inc r8d

.r11_kept:
    ; syscall: open("/proc/self/fd/999999", O_RDONLY)
    mov eax, SYS_OPEN
    lea rdi, [missing]
    xor esi, esi
    xor edx, edx
    syscall

raw_errno:
    cmp rax, -2
    jne .errno_done
    add r8d, 10

.errno_done:
    ; syscall: exit(r8d) — 12 when rcx/r11 are clobbered and raw -ENOENT is observed
    mov edi, r8d
    mov eax, SYS_EXIT
    syscall

section .note.GNU-stack noalloc noexec nowrite progbits

Disassembly shows both 64-bit constants and the syscall instruction itself:

  401000:	48 b9 11 11 11 11 11 	movabs rcx,0x1111111111111111
  401007:	11 11 11
  40100a:	49 bb 22 22 22 22 22 	movabs r11,0x2222222222222222
  401011:	22 22 22
  40102a:	0f 05                	syscall
  40102c:	45 31 c0             	xor    r8d,r8d
  • 48 b9 and 49 bb — opcodes moving 64-bit immediates into rcx and r11.
  • 0f 05 — two-byte syscall opcode; after_syscall begins right after it.
  • 45 31 c0 — xor r8d, r8d: r8 tracks how many registers were clobbered.

Stopping in GDB at after_syscall shows the aftermath of the transition:

(gdb) break after_syscall
Breakpoint 1 at 0x40102c: file rcx_clobber.asm, line 39.
(gdb) run
syscall clobbers rcx and r11

Breakpoint 1, after_syscall () at rcx_clobber.asm:39
39	    xor r8d, r8d
(gdb) print/x $rcx
$1 = 0x40102c
(gdb) print/x $rip
$2 = 0x40102c
(gdb) print/x $r11
$3 = 0x202
(gdb) print/x $eflags
$4 = 0x202
  • $1 = 0x40102c — rcx now holds the address of the next instruction, not 0x1111111111111111.
  • $2 = 0x40102c — rip is at the same instruction, confirming rcx was used as the saved return address.
  • $3 = 0x202 — r11 holds RFLAGS; 0x202 is IF (interrupts enabled) plus the hardwired bit 1.
  • $4 = 0x202 — $eflags confirms r11 holds the exact flags snapshot.

That is why the fourth argument to a syscall goes in r10 instead of rcx: rcx is already spoken for by the return address. The same rule explains why keeping a loop counter in rcx across a syscall breaks your loop.

Errors, errno, and Negative Return Values

A raw system call reports an error as a negative integer: rax = -2 means -ENOENT. The libc wrapper translates this into -1 and stores the positive code in errno. The GDB check below pauses right after the raw open:

(gdb) break raw_errno
Breakpoint 2 at 0x401065: file rcx_clobber.asm, line 60.
(gdb) continue

Breakpoint 2, raw_errno () at rcx_clobber.asm:60
60	    cmp rax, -2
(gdb) print/d $rax
$5 = -2
  • $5 = -2 — the kernel returned -ENOENT; the positive error code is 2.
  • cmp rax, -2 — the assembly code checks the raw negative return code directly, not -1.
  • In C99, the same failure surfaces as open(...) == -1 with errno == ENOENT.

Inside libc, the wrapper doesn’t test each error individually; it checks whether the return value falls in a narrow band of negative integers:

if ((uint64_t)rax >= (uint64_t)-4095) {
    errno = -(int)rax;

    return -1;
}

Casting to uint64_t maps -1 to 0xFFFFFFFFFFFFFFFF and -4095 to 0xFFFFFFFFFFFFF001, so a single unsigned comparison catches the entire −4095 … −1 error range while letting valid non-negative results pass through. The branch errno = -rax flips the kernel’s negative code to positive, and the caller sees only -1.

The testbed exits with 12: two clobbered registers plus ten for detecting -ENOENT.

VFS: From fd to inode

The number returned by open is a file descriptor, not a disk address. That mapping is managed by the VFS. The file itself on disk is described by an inode.

process fd table
0…2 — stdio
3 — opened file

struct file
offset = 6
flags = O_RDONLY

inode
0644, 8 bytes
blocks: VFS-LAB.

process fd table
0…2 — stdio
3 — opened file

struct file
offset = 6
flags = O_RDONLY

inode
0644, 8 bytes
blocks: VFS-LAB.

Fig. 2. Path from a file descriptor to an inode

The vfs_demo.c testbed exercises the full lifecycle: creates a file, writes eight bytes, reads the start, seeks with lseek, and reads the tail:

vfs_demo.c
/* SPDX-License-Identifier: PolyForm-Noncommercial-1.0.0 */

/* vfs_demo.c — fd -> struct file -> inode: open, write, read, lseek, close. */

#include <errno.h>
#include <fcntl.h>
#include <inttypes.h>
#include <stddef.h>
#include <stdint.h>
#include <stdio.h>
#include <string.h>
#include <unistd.h>

#define PAYLOAD "VFS-LAB."
#define PAYLOAD_LEN 8u
#define CHUNK 4u
#define TAIL_OFFSET 6
#define MISSING_PATH "build/vfs_demo.missing"

static int write_all(int fd, const char *buf, size_t len)
{
    size_t done = 0;

    while (done < len) {
        ssize_t n = write(fd, buf + done, len - done);

        if (n < 0) {
            if (errno == EINTR) {
                continue;
            }

            return -1;
        }

        if (n == 0) {
            return -1;
        }

        done += (size_t)n;
    }

    return 0;
}

int main(int argc, char **argv)
{
    const char *path = "build/vfs_demo.dat";
    char buf[16] = {0};
    int fd = -1;
    int saved = 0;
    ssize_t n = 0;
    off_t off = 0;

    if (argc > 1) {
        path = argv[1];
    }

    fd = open(path, O_CREAT | O_TRUNC | O_WRONLY, 0644);
    if (fd < 0) {
        perror("open O_WRONLY");

        return 1;
    }

    printf("open O_WRONLY fd = %d\n", fd);

    if (write_all(fd, PAYLOAD, PAYLOAD_LEN) != 0) {
        perror("write");
        close(fd);

        return 1;
    }

    printf("write = %u bytes\n", (unsigned)PAYLOAD_LEN);

    if (close(fd) != 0) {
        perror("close write");

        return 1;
    }

    fd = -1;

    fd = open(path, O_RDONLY);
    if (fd < 0) {
        perror("open O_RDONLY");

        return 1;
    }

    printf("open O_RDONLY fd = %d\n", fd);

    n = read(fd, buf, CHUNK);
    if (n < 0) {
        perror("read first");
        close(fd);

        return 1;
    }

    printf("read first %u = %zd bytes: %.*s\n", (unsigned)CHUNK, n, (int)n, buf);

    off = lseek(fd, TAIL_OFFSET, SEEK_SET);
    if (off < 0) {
        perror("lseek");
        close(fd);

        return 1;
    }

    printf("lseek SEEK_SET %d = %" PRIdMAX "\n", TAIL_OFFSET, (intmax_t)off);

    memset(buf, 0, sizeof buf);
    n = read(fd, buf, CHUNK);
    if (n < 0) {
        perror("read tail");
        close(fd);

        return 1;
    }

    printf("read tail %u = %zd bytes: %.*s\n", (unsigned)CHUNK, n, (int)n, buf);

    if (close(fd) != 0) {
        perror("close read");

        return 1;
    }

    fd = -1;

    if (unlink(path) != 0) {
        perror("unlink");

        return 1;
    }

    errno = 0;
    fd = open(MISSING_PATH, O_RDONLY);
    if (fd >= 0) {
        close(fd);
        fprintf(stderr, "unexpected open success\n");

        return 1;
    }

    saved = errno;
    printf("errno after missing open = %d (%s)\n", saved, strerror(saved));

    return 0;
}

Running it prints the descriptor numbers, byte counts, and error code:

open O_WRONLY fd = 3
write = 8 bytes
open O_RDONLY fd = 3
read first 4 = 4 bytes: VFS-
lseek SEEK_SET 6 = 6
read tail 4 = 2 bytes: B.
errno after missing open = 2 (No such file or directory)
  • fd = 3 — descriptors 0, 1, and 2 are already occupied by stdin, stdout, and stderr.
  • read first 4 = 4 — reads VFS- from the start of the file.
  • lseek SEEK_SET 6 = 6 — updates the current offset to 6; that offset lives in struct file, not in the inode.
  • read tail 4 = 2 — only B. remains near EOF, so read returns two bytes.
  • errno ... = 2 — the open wrapper returned -1 and stored the error code in errno.

strace reveals the exact syscall sequence (dynamic loader lines and final output omitted; modern glibc lowers open to openat syscall 257, though raw SYS_OPEN = 2 from rcx_clobber.asm is still supported by the kernel):

openat(AT_FDCWD, "build/vfs_demo.dat", O_WRONLY|O_CREAT|O_TRUNC, 0644) = 3
write(3, "VFS-LAB.", 8)                 = 8
close(3)                                = 0
openat(AT_FDCWD, "build/vfs_demo.dat", O_RDONLY) = 3
read(3, "VFS-", 4)                      = 4
lseek(3, 6, SEEK_SET)                   = 6
read(3, "B.", 4)                        = 2
close(3)                                = 0
unlink("build/vfs_demo.dat")            = 0
openat(AT_FDCWD, "build/vfs_demo.missing", O_RDONLY) = -1 ENOENT (No such file or directory)
  • openat — the syscall libc translates open into; AT_FDCWD means “current working directory.”
  • = 3 — the kernel allocated the lowest free descriptor, 3.
  • O_WRONLY|O_CREAT|O_TRUNC — write-only, create, and truncate flags; the next argument 0644 sets permissions in octal (the leading zero in C is mandatory): owner read/write (6), group and others read-only (4).
  • O_RDONLY — equals zero; strace prints it symbolically because no other access bits are set.
  • lseek(3, 6, SEEK_SET) = 6 — moves the offset to 6 without touching the file’s bytes.
  • read(...) = 2 — short read at EOF.
  • = -1 ENOENT — the kernel returned -ENOENT; libc turned it into -1 and errno = 2.

lseek, Short Reads, and EINTR

The lseek syscall neither reads nor writes data: it only updates the offset inside struct file. The next read begins at that new position.

A short read is normal behavior, not an error. A regular file returns fewer bytes near EOF, and a terminal or socket may return one byte out of a hundred requested. That’s why callers loop on read, checking against zero and the target byte count rather than assuming the first call delivered everything.

EINTR is handled explicitly in write_all: the loop retries write whenever errno equals EINTR.

Signal Frames: Crossing the Same Kernel Boundary

Signals belong here because signal delivery is another ring 3 ↔ ring 0 crossing orchestrated by the kernel. VFS shows how the kernel tracks file state behind fd; during a signal, it saves the process’s own execution state using the same boundary machinery as syscall. The kernel builds a signal frame on the user stack containing ucontext_t, freeing the handler from saving registers manually.

When constructing that frame, the kernel skips below the 128-byte user-space red zone (lesson 09) so it doesn’t clobber scratch data the interrupted function keeps beneath rsp. The kernel itself is compiled with -mno-red-zone for a related reason: a hardware interrupt in ring 0 could arrive before a handler moves rsp, pushing an interrupt frame straight onto the 128 bytes below the kernel stack pointer.

Ring 0 (kernel)Ring 3 (user space)Ring 0 (kernel)Ring 3 (user space)kernel builds ucontext_tbelow rsp − 128signal handler runssignal / exception1invoke signal handler2rt_sigreturn3restore context4
Ring 0 (kernel)Ring 3 (user space)Ring 0 (kernel)Ring 3 (user space)kernel builds ucontext_tbelow rsp − 128signal handler runssignal / exception1invoke signal handler2rt_sigreturn3restore context4
Fig. 3. Signal frame built on the user stack

Common Pitfalls

  1. “Keeping a loop counter in rcx across a syscall.”
    Fact: before the call rcx holds 0x1111111111111111; after write, it holds 0x40102c—the address of the next instruction.
    Cause: the CPU saves the return address in rcx and sysret reads it back from there; rcx is never preserved.
    Fix: keep live values in r8–r10, rbx, or on the stack, and treat rcx and r11 as clobbered across syscall.

  2. "open returned -1, so the kernel returned -1."
    Fact: in GDB at raw_errno, rax = -2, while errno in C99 is 2; strace prints = -1 ENOENT.
    Cause: a raw syscall returns -errno, and the libc wrapper converts it to -1 plus errno.
    Fix: in assembly, test rax for negative values; in C99, check -1 and inspect errno immediately after the call.

  3. "O_RDONLY is a non-zero flag you OR with other flags."
    Fact: openat(..., O_RDONLY) = 3 shows no non-zero bit in the access-mode field: O_RDONLY == 0.
    Cause: access mode is encoded in the lowest two bits, and 0 already means read-only.
    Fix: never test flags for non-zero to detect O_RDONLY, and don’t pass O_RDONLY where a write mask is expected.

  4. “A single read returning fewer bytes means data was lost.”
    Fact: read(3, "B.", 4) = 2 near EOF, yet the file is intact.
    Cause: read returns whatever bytes are immediately available; a short read isn’t an error.
    Fix: accumulate bytes in a loop until you reach the desired length or 0, just like write_all does for writes.

Lab

Goal. Build fd_probe.asm to open a file with raw syscalls and walk through open → read → lseek → read → close.

Contract and requirements.

  • Standalone binary: entry point _start, no libc and no C99 harness.
  • Keep the file path in .rodata; open the file read-only.
  • First read requests 4 bytes, lseek moves to offset 6, and a second read requests 4 more bytes.
  • Print both chunks via write separated by a newline.
  • If open returns a negative value, exit immediately with status 1 without attempting to read.
  • On success, exit with the sum of the lengths of the two chunks read.

Verification criteria.

  1. strace -e trace=open,openat,read,lseek,close ./build/fd_probe shows all five steps and their exact byte counts.
  2. In GDB at a label after open, rax prints 3.
  3. The second read returns 2 when the file is eight bytes long.
  4. After renaming the input file, the program exits with 1 and GDB shows rax = -2.
  5. echo $? on success equals the sum of the two read lengths, not the total file size.
Hints, expected output, and walkthrough

For a file containing VFS-LAB., the first read returns 4 and the second returns 2. Their sum is 6, which becomes the exit status.

  • Syscall numbers: open = 2, read = 0, lseek = 8, close = 3.
  • For lseek, pass offset 6 as the second argument and SEEK_SET (0) as the third.
  • After open, fd is 3 because 0, 1, and 2 are already open.
  • When the file is missing, open returns -2; check for negative values rather than -1.

If the second read returns 4, lseek failed or its result was ignored. If the program prints an empty slice, check the buffer pointer and byte count passed to write, not read.

Testbed sources, Makefile, and automated tests for this lesson: lessons/12-syscalls-and-vfs.

Summary

  1. syscall is a hardware ring-0 transition instruction, not an ordinary call.
  2. syscall saves the return address in rcx and RFLAGS in r11; both are clobbered.
  3. The fourth syscall argument goes in r10 because rcx is reserved for the return address.
  4. Raw syscalls return -errno; libc turns that into -1 and errno.
  5. A file descriptor is an index into the process table; VFS maps it to struct file and an inode.
  6. lseek updates the offset in struct file, and read can return fewer bytes than requested.
Bridge to the Next Lesson
Our programs can now open files and pass syscall arguments in registers, yet where do argc and argv come from before main is ever called? In lesson 13, I unpack the initial process stack: what the kernel pushes before jumping to _start, where envp lives, and why executing ret from _start crashes the program.