A file descriptor is an index into a per-process table, and
syscallisn’t acall—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.
The rcx_clobber.asm testbed loads recognizable constants into rcx and r11, issues a write, and checks what remains in both registers:
; 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 progbitsDisassembly 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,r8d48 b9and49 bb— opcodes moving 64-bit immediates intorcxandr11.0f 05— two-bytesyscallopcode;after_syscallbegins right after it.45 31 c0—xor r8d, r8d:r8tracks 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—rcxnow holds the address of the next instruction, not0x1111111111111111.$2 = 0x40102c—ripis at the same instruction, confirmingrcxwas used as the saved return address.$3 = 0x202—r11holdsRFLAGS;0x202isIF(interrupts enabled) plus the hardwired bit 1.$4 = 0x202—$eflagsconfirmsr11holds 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 is2.cmp rax, -2— the assembly code checks the raw negative return code directly, not-1.- In C99, the same failure surfaces as
open(...) == -1witherrno == 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.
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:
/* 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— descriptors0,1, and2are already occupied by stdin, stdout, and stderr.read first 4 = 4— readsVFS-from the start of the file.lseek SEEK_SET 6 = 6— updates the current offset to 6; that offset lives instruct file, not in the inode.read tail 4 = 2— onlyB.remains near EOF, soreadreturns two bytes.errno ... = 2— theopenwrapper returned-1and stored the error code inerrno.
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 translatesopeninto;AT_FDCWDmeans “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 argument0644sets permissions in octal (the leading zero in C is mandatory): owner read/write (6), group and others read-only (4).O_RDONLY— equals zero;straceprints 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-1anderrno = 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.
Common Pitfalls
-
“Keeping a loop counter in
rcxacross asyscall.”
Fact: before the callrcxholds0x1111111111111111; afterwrite, it holds0x40102c—the address of the next instruction.
Cause: the CPU saves the return address inrcxandsysretreads it back from there;rcxis never preserved.
Fix: keep live values inr8–r10,rbx, or on the stack, and treatrcxandr11as clobbered acrosssyscall. -
"
openreturned-1, so the kernel returned-1."
Fact: in GDB atraw_errno,rax = -2, whileerrnoin C99 is2;straceprints= -1 ENOENT.
Cause: a raw syscall returns-errno, and the libc wrapper converts it to-1pluserrno.
Fix: in assembly, testraxfor negative values; in C99, check-1and inspecterrnoimmediately after the call. -
"
O_RDONLYis a non-zero flag you OR with other flags."
Fact:openat(..., O_RDONLY) = 3shows no non-zero bit in the access-mode field:O_RDONLY == 0.
Cause: access mode is encoded in the lowest two bits, and0already means read-only.
Fix: never test flags for non-zero to detectO_RDONLY, and don’t passO_RDONLYwhere a write mask is expected. -
“A single
readreturning fewer bytes means data was lost.”
Fact:read(3, "B.", 4) = 2near EOF, yet the file is intact.
Cause:readreturns whatever bytes are immediately available; a short read isn’t an error.
Fix: accumulate bytes in a loop until you reach the desired length or0, just likewrite_alldoes 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
readrequests 4 bytes,lseekmoves to offset 6, and a secondreadrequests 4 more bytes. - Print both chunks via
writeseparated by a newline. - If
openreturns a negative value, exit immediately with status1without attempting to read. - On success, exit with the sum of the lengths of the two chunks read.
Verification criteria.
strace -e trace=open,openat,read,lseek,close ./build/fd_probeshows all five steps and their exact byte counts.- In GDB at a label after
open,raxprints3. - The second
readreturns2when the file is eight bytes long. - After renaming the input file, the program exits with
1and GDB showsrax = -2. 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 offset6as the second argument andSEEK_SET(0) as the third. - After
open,fdis3because0,1, and2are already open. - When the file is missing,
openreturns-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
syscallis a hardware ring-0 transition instruction, not an ordinarycall.syscallsaves the return address inrcxandRFLAGSinr11; both are clobbered.- The fourth syscall argument goes in
r10becausercxis reserved for the return address. - Raw syscalls return
-errno; libc turns that into-1anderrno. - A file descriptor is an index into the process table; VFS maps it to
struct fileand an inode. lseekupdates the offset instruct file, andreadcan return fewer bytes than requested.
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.