learner@ksa:~/gl-c01$
>_ Kernel Systems Academy
Linux Systems I/O & Buffering in C
Embedded Linux, systems, and infrastructure C engineers
Outcome: Engineer crash-safe, race-free Linux C11 file and stream I/O software across raw POSIX descriptors, VFS open-file tables, atomic positional syscalls, and two-stage buffered stdio streams.
- m01/ Series Orientation, Kernel Boundary & C Toolchain
- m02/ Core Unbuffered POSIX File I/O
- m03/ Kernel Open-File Internals, Errors & Sparse Files
- m04/ File Sharing, Atomic Operations & Descriptor Control
- m05/ Standard C Library (stdio) Streams & Formatted I/O
- m06/ Two-Layer I/O Buffering, Durability & Capstone Engine
m01/
>_ Kernel Systems Academy
# Series Orientation, Kernel Boundary & C Toolchain
Onboard into the 4-course Linux Systems C series across Ring 3 / Ring 0 hardware boundaries, master the 4-stage GCC/Make C11 toolchain and POSIX boundary types, and trace glibc wrappers, CRT startup, and errno diagnostics under strace.
- 1.1 Welcome to Linux Systems C
- 1.2 GCC Pipeline, Make & POSIX Types
- 1.3 Syscall Wrappers, CRT, errno & strace
lab → Multi-File C11 Static Archive & Syscall Boundary Tracer
GL-C01 · 1.1 (m01-l01)
>_ Kernel Systems Academy
# Welcome to Linux Systems C
What you'll learn
- Compare bare-metal MMIO firmware, Ring 0
struct file_operationsdrivers, and Ring 3 C processes across fault isolation. - Map the seven Linux kernel subsystems and the
linux-vdso.so.1zero-trap fastpath acrossGL-C01throughGL-C04. - Compile and execute a strict ISO C11 sanity binary while separating Ring 3 RAM loops from Ring 0 syscall traps.
GL-C01 · 1.1 (m01-l01)
>_ Kernel Systems Academy
# Why Systems C Needs a Hardware Kernel Boundary
- Suppose an engineer ports a bare-metal microcontroller routine
*(volatile uint32_t *)0x0209C000 = 1U;dir…
GL-C01 · 1.1 (m01-l01)
>_ Kernel Systems Academy
# Why Systems C Needs a Hardware Kernel Boundary
- Naive C code fails at this boundary for two complementary reasons.
GL-C01 · 1.1 (m01-l01)
>_ Kernel Systems Academy
# Why Systems C Needs a Hardware Kernel Boundary
- Welcome to
GL-C01(Linux Systems I/O & Buffering in C), the foundational first course of our four-c…
GL-C01 · 1.1 (m01-l01)
>_ Kernel Systems Academy
# Why Systems C Needs a Hardware Kernel Boundary
- 1.
GL-C01 · 1.1 (m01-l01)
>_ Kernel Systems Academy
# Mental model
note: Think of an airport security checkpoint separating the public terminal from the active runway tarmac. Travelers organize itineraries freely inside the public hall, but loading cargo onto an aircraft requires handing parcels through a guarded counter to badged ground crew.
Where it stops working: Unlike a physical counter staffed by separate people, a CPU system call switches privilege levels on the exact same processor core in nanoseconds via architectural trap registers.
GL-C01 · 1.1 (m01-l01)
>_ Kernel Systems Academy
# Hardware Privilege Rings, Syscall Gate & vDSO
definition: Privilege Rings (Ring 3 / EL0 vs Ring 0 / EL1): Originating in Multics protection rings and enforced by the x86-64 Current Privilege Level (CPL) or ARM Exception Level (EL), user C processes execute in unprivileged Ring 3 (EL0) inside isolated virtual address spaces, whereas the Linux kernel executes in Ring 0 (EL1) with full MMU, interrupt, and MMIO authority. A System Call Gate (syscall on x86-64 System V ABI; svc #0 on ARMv7 AAPCS) switches privilege synchronously on the active core, while the Virtual Dynamic Shared Object (vDSO, linux-vdso.so.1) maps read-only kernel timekeeper pages into Ring 3 so clock_gettime() reads monotonic clocks with zero traps.
GL-C01 · 1.1 (m01-l01)
>_ Kernel Systems Academy
# Why Systems C Needs a Hardware Kernel Boundary
Figure 1.1a: Hardware privilege boundary — Ring 3 C helpers and linux-vdso.so.1 execute in user space, while system calls cross the ABI trap gate into the seven Ring 0 Linux kernel subsystems.
GL-C01 · 1.1 (m01-l01)
>_ Kernel Systems Academy
# Virtual vs Physical Memory: How the MMU Isolates Processes & Guards Silicon
- Why did
*(volatile uint32_t *)0x0209C000 = 1U;crashmain()withSIGSEGVinstead of toggling aGPIO…
GL-C01 · 1.1 (m01-l01)
>_ Kernel Systems Academy
# Virtual vs Physical Memory: How the MMU Isolates Processes & Guards Silicon
- 1.
GL-C01 · 1.1 (m01-l01)
>_ Kernel Systems Academy
# Virtual vs Physical Memory: How the MMU Isolates Processes & Guards Silicon
Figure 1.1b: Virtual vs physical memory — the CPU MMU translates identical virtual addresses in PID 410 and PID 411 to separate 4 KiB physical RAM frames while blocking raw Ring-3 MMIO pointers with SIGSEGV.
GL-C01 · 1.1 (m01-l01)
>_ Kernel Systems Academy
# One Layer Down: ABI Trap Registers, Seven Subsystems, and Latency Math
- When a user-space C program invokes a system call, the CPU does not jump to an arbitrary kernel address.
GL-C01 · 1.1 (m01-l01)
>_ Kernel Systems Academy
# One Layer Down: ABI Trap Registers, Seven Subsystems, and Latency Math
- Quantifying transition cost explains why systems C separates
Ring 3computation fromRing 0traps.
GL-C01 · 1.1 (m01-l01)
>_ Kernel Systems Academy
# One Layer Down: ABI Trap Registers, Seven Subsystems, and Latency Math
Raw MMIO dereferences in Ring 3 fault immediately in the MMU (SIGSEGV), protecting sibling processes and silicon.
User-space C logic and kernel drivers meet strictly across the VFS system call boundary.
GL-C01 · 1.1 (m01-l01)
>_ Kernel Systems Academy
# Benchmarking Ring 3 + vDSO vs Syscall Traps in ISO C11
- Because POSIX abstracts files, pipes, sockets, and
/devnodes behind uniform integer descriptors, standar…
GL-C01 · 1.1 (m01-l01)
>_ Kernel Systems Academy
# hello_systems.c
learner@ksa:~/gl-c01/m01-l01$ bat hello_systems.c───────┬──────────────────────────────────────────────────────────────────────────────── │ File: hello_systems.c───────┼──────────────────────────────────────────────────────────────────────────────── 1 │ #define _GNU_SOURCE 2 │ #include <stdint.h> 3 │ #include <stdio.h> 4 │ #include <stdlib.h> 5 │ #include <string.h> 6 │ #include <sys/syscall.h> 7 │ #include <time.h> 8 │ #include <unistd.h> 9 │ 10 │ struct course_banner { 11 │ char code[8]; 12 │ uint32_t magic; 13 │ uint16_t modules; 14 │ };───────┴────────────────────────────────────────────────────────────────────────────────GL-C01 · 1.1 (m01-l01)
>_ Kernel Systems Academy
# Benchmarking Ring 3 + vDSO vs Syscall Traps in ISO C11
learner@ksa:~/gl-c01/m01-l01$ gcc -fdiagnostics-color=always -std=c11 -O2 -Wall -Wextra -Werror hello_systems.c -o hello_systemslearner@ksa:~/gl-c01/m01-l01$ ./hello_systemslearner@ksa:~/gl-c01/m01-l01$ grep -q 'vdso' /proc/self/maps && echo vdso_mapped=1learner@ksa:~/gl-c01/m01-l01$ sh -c 'strace -e trace=clock_gettime ./hello_systems 2>&1 >/dev/null | grep -c "^clock_gettime" || true'learner@ksa:~/gl-c01/m01-l01$ strace -e trace=getpid ./hello_systems 2>&1 >/dev/null | grep -c '^getpid('learner@ksa:~/gl-c01/m01-l01$ rm -f hello_systemscourse=GL-C01 code_len=6 modules=6 u32_bytes=4 vmem_ok=1vdso_mapped=102000learner@ksa:~/gl-c01/m01-l01$ GL-C01 · 1.1 (m01-l01)
>_ Kernel Systems Academy
# Tracing the Execution Split, Pitfalls & Practice
- Look closely at what
./hello_systemsandstracejust proved on Linux 6.12.
GL-C01 · 1.1 (m01-l01)
>_ Kernel Systems Academy
# Warning
warning: Symptom: An engineer runs strace ./daemon to verify whether monotonic timestamping is firing, sees zero clock_gettime lines, and falsely concludes the timer code was compiled out. Root Cause: On x86-64 and ARMv7 Linux, glibc resolves clock_gettime() and gettimeofday() through linux-vdso.so.1 (AT_SYSINFO_EHDR) in Ring 3 without executing syscall or svc #0, and strace only intercepts kernel privilege switches. Fix: Trace user-space library calls with ltrace or gdb breakpoints rather than strace whenever inspecting vDSO-accelerated routines.
GL-C01 · 1.1 (m01-l01)
>_ Kernel Systems Academy
# Warning
warning: Symptom: A legacy hardware diagnostic ported from bare-metal C dereferences (volatile uint32_t *)0x0209C000 inside main() and crashes immediately with SIGSEGV (exit code 139). Root Cause: Every pointer in a Linux user process is a Ring 3 virtual address translated by per-process page tables; unmapped physical bus addresses fault in the MMU before touching interconnect wires. Fix: Access hardware strictly through VFS character device nodes (/dev/gpiochip*, /dev/spidev*, /dev/i2c-*) backed by Ring 0 kernel drivers (Later: user-space peripheral buses are covered in GL-C04, and Ring 0 struct file_operations driver authoring is covered in GL-E04).
GL-C01 · 1.1 (m01-l01)
>_ Kernel Systems Academy
# Guided Practice: Predicting Trap Counts Across Mixed Loops
- Suppose you extend
hello_systems.cwith a loop of500iterations where each iteration calls `memcpy(dst…
GL-C01 · 1.1 (m01-l01)
>_ Kernel Systems Academy
# Guided Practice: Predicting Trap Counts Across Mixed Loops
- 1.
GL-C01 · 1.1 (m01-l01)
>_ Kernel Systems Academy
# Independent Practice: Trap-Amortization Breakeven Estimator
- Write a standalone C11 program
trap_budget.ccompiled with-std=c11 -O2 -Wall -Wextra -Werrorthat meas…
GL-C01 · 1.1 (m01-l01)
>_ Kernel Systems Academy
# Quick check
? An embedded firmware engineer porting bare-metal MCU LED code to a Linux user-space daemon attempts to dereference physical GPIO register 0x0209C000 directly inside main(). What happens when the process runs?
Select an option or press R to reveal.
Correct: B
User-space processes run in virtual memory under MMU protection; hardware peripherals are accessed only by trapping into Ring 0 kernel drivers via VFS nodes.
Common misconception: Engineers moving from bare-metal microcontroller firmware often assume C pointers in Linux main() address physical MMIO registers directly.
GL-C01 · 1.1 (m01-l01)
>_ Kernel Systems Academy
# Quick check
? How do user-space C applications and Linux kernel character drivers cooperate when controlling a /dev/led0 device node?
Select an option or press R to reveal.
Correct: A
VFS decouples user applications from kernel drivers; drivers validate user virtual addresses via copy_from_user() before touching hardware registers.
Common misconception: Confusing user-space systems C programming with authoring Ring 0 kernel modules blurs the hardware protection boundary.
GL-C01 · 1.1 (m01-l01)
>_ Kernel Systems Academy
# Quick check
? Why does GL-C01 open the four-course Linux Systems C series with VFS file descriptors and stdio buffering before IPC/sockets (GL-C03) or embedded peripherals (GL-C04)?
Select an option or press R to reveal.
Correct: B
Because VFS unifies files, pipes, sockets, and /dev device nodes behind integer descriptors, mastering descriptors, error handling, and buffering in GL-C01 underpins the entire series.
Common misconception: Treating file I/O as "only disk files" misses the core Unix design where integer descriptors represent nearly every kernel I/O channel.
GL-C01 · 1.1 (m01-l01)
>_ Kernel Systems Academy
# Quick check
? A latency benchmark calls clock_gettime(CLOCK_MONOTONIC, &ts) two thousand times, yet strace -e trace=clock_gettime ./bench prints 0 syscall lines when you review the trace. Which mechanism accounts for this observation?
Select an option or press R to reveal.
Correct: B
linux-vdso.so.1 exposes kernel-maintained timekeeper counters inside a read-only user-space shared page, bypassing synchronous syscall / svc #0 traps completely.
Common misconception: Assuming every POSIX time or identity query enters Ring 0 leads engineers to misread 0-line strace captures on vDSO fastpaths.
GL-C01 · 1.1 (m01-l01)
>_ Kernel Systems Academy
# Summary
GL-C01opens the 4-course Linux Systems Programming in C series by establishing the toolchain, VFS descriptor, andstdiobuffering foundation used across filesystems, IPC, sockets, and/devperipherals.- Bare-metal firmware mixes user logic and raw MMIO register writes in one flat address space, whereas Linux isolates
Ring 3/EL0user processes fromRing 0/EL1struct file_operationsdrivers via the MMU. - Standard system calls cross from
Ring 3/EL0user mode intoRing 0/EL1Linux kernel mode via synchronous CPU traps across seven core subsystems, whilelinux-vdso.so.1(AT_SYSINFO_EHDR) servesclock_gettime()from a read-only shared page with zero traps. - Standard user-space C code compiles cleanly across x86-64 workstations and embedded
ARMv7targets when built with strict-std=c11 -Wall -Wextra -Werrordiscipline.
GL-C01 · 1.1 (m01-l01)
>_ Kernel Systems Academy
# Summary
- Next, before invoking raw Linux kernel descriptors directly, we will dissect the four-stage GCC and static-…
GL-C01 · 1.1 (m01-l01)
>_ Kernel Systems Academy
# Key takeaways
- Standard system calls cross from
Ring 3/EL0user mode intoRing 0/EL1Linux kernel mode via synchronous CPU traps across seven core subsystems, whilelinux-vdso.so.1(AT_SYSINFO_EHDR) servesclock_gettime()from a read-only shared page with zero traps. - Standard user-space C code compiles cleanly across x86-64 workstations and embedded
ARMv7targets when built with strict-std=c11 -Wall -Wextra -Werrordiscipline. - Next, before invoking raw Linux kernel descriptors directly, we will dissect the four-stage GCC and static-archive build pipeline, POSIX feature-test macros, boundary integer types, and ISO C11 Undefined Behavior defenses.
GL-C01 · 1.2 (m01-l02)
>_ Kernel Systems Academy
# GCC Pipeline, Make & POSIX Types
What you'll learn
- Build multi-file ISO C11 targets across GCC stages (
-E,-S,-c,ar rcs, link) with-Wall -Wextra -Werror. - Configure
_POSIX_C_SOURCEand_FILE_OFFSET_BITS=64before headers usingman 2andman 3interface contracts. - Audit C11 code for Undefined Behavior,
-fno-commoncollisions,size_t/ssize_twraparound, and octal0644bugs.
GL-C01 · 1.2 (m01-l02)
>_ Kernel Systems Academy
# Why Sloppy C Types and Opaque Builds Break Systems Software
- Consider a network packet validator written as
if (payload_len + 16 < payload_len) return -1;where `payl…
GL-C01 · 1.2 (m01-l02)
>_ Kernel Systems Academy
# Why Sloppy C Types and Opaque Builds Break Systems Software
- Naive C habits fail because developers conflate hardware assembly behavior with the abstract machine specif…
GL-C01 · 1.2 (m01-l02)
>_ Kernel Systems Academy
# Mental model
note: Think of a precision machine shop with an assembly blueprint, calipers calibrated in millimeters versus signed tolerances, and standardized part bins. Reading the wrong scale or skipping the torque specification produces parts that look close on the bench and shear under load.
Where it stops working: Unlike physical tolerances that degrade gradually, mixing unsigned size_t with signed ssize_t -1 or decimal 644 with octal 0644 flips exact bits instantaneously.
GL-C01 · 1.2 (m01-l02)
>_ Kernel Systems Academy
# Four-Stage GCC Pipeline, Feature Macros & C11 UB
definition: Four-Stage Translation Pipeline & Tentative Definitions: Originating in early Unix cpp -> cc1 -> as -> ld passes, GCC lowers ISO C11 source across preprocessing (-E -> .i), compilation (-S -> .s), assembly (-c -> relocatable Executable and Linkable Format .o), and linking (ar rcs static .a archives or -fPIC -shared .so objects). Feature-Test Macros (_POSIX_C_SOURCE, named by IEEE 1003.1 to gate namespace exposure) unlock POSIX declarations above ISO C11, while Undefined Behavior (UB, C11 §3.4.3) designates operations—such as signed overflow or strict-aliasing violations—for which the standard imposes zero requirements.
GL-C01 · 1.2 (m01-l02)
>_ Kernel Systems Academy
# One Layer Down: ELF Object Sections, Alignment Math & Link Order
- Across Stage 3 (
gcc -c), the assembler partitions each relocatable.ofile into distinct ELF sections:…
GL-C01 · 1.2 (m01-l02)
>_ Kernel Systems Academy
# One Layer Down: ELF Object Sections, Alignment Math & Link Order
- Struct layout and boundary sizing obey exact binary alignment arithmetic.
GL-C01 · 1.2 (m01-l02)
>_ Kernel Systems Academy
# One Layer Down: ELF Object Sections, Alignment Math & Link Order
Figure 1.2: Four-stage GCC/archive builds, struct padded_hdr byte-alignment math, and signed/unsigned POSIX boundary contracts.
GL-C01 · 1.2 (m01-l02)
>_ Kernel Systems Academy
# One Layer Down: ELF Object Sections, Alignment Math & Link Order
Stage 1 (-E) — Define _POSIX_C_SOURCE and _FILE_OFFSET_BITS=64 on lines 1..2 before any header is included.
Feature-test macros, strict C11 warning/sanitizer flags, and single-pass archive link ordering eliminate silent type and symbol bugs at build time.
GL-C01 · 1.2 (m01-l02)
>_ Kernel Systems Academy
# Feature-Test Macros,Incremental Make & Sanitizer Flags
- Under strict
-std=c11, GCC defines__STRICT_ANSI__and hides POSIX symbols (fileno,pread, `fdatasy…
GL-C01 · 1.2 (m01-l02)
>_ Kernel Systems Academy
# Makefile
learner@ksa:~/gl-c01/m01-l02$ bat Makefile───────┬──────────────────────────────────────────────────────────────────────────────── │ File: Makefile───────┼──────────────────────────────────────────────────────────────────────────────── 1 │ CC := gcc 2 │ CFLAGS := -std=c11 -Wall -Wextra -Werror -MMD -MP -g -O2 3 │ SAN := -fsanitize=address,undefined -fno-omit-frame-pointer 4 │ 5 │ .PHONY: all sanitize clean 6 │ all: inspector 7 │ 8 │ libsysbuf.a: sysbuf.o 9 │ ar rcs $@ $^ 10 │ 11 │ inspector: inspector.o libsysbuf.a 12 │ $(CC) $(CFLAGS) inspector.o -L. -lsysbuf -o $@ 13 │ 14 │ sanitize: sysbuf.c inspector.c───────┴────────────────────────────────────────────────────────────────────────────────GL-C01 · 1.2 (m01-l02)
>_ Kernel Systems Academy
# Auditing Binary Frames, Struct Padding, Strict Aliasing & Octal Modes
- Save
type_bridge.cbelow.
GL-C01 · 1.2 (m01-l02)
>_ Kernel Systems Academy
# type_bridge.c
learner@ksa:~/gl-c01/m01-l02$ bat type_bridge.c───────┬──────────────────────────────────────────────────────────────────────────────── │ File: type_bridge.c───────┼──────────────────────────────────────────────────────────────────────────────── 1 │ #define _FILE_OFFSET_BITS 64 2 │ #define _POSIX_C_SOURCE 200809L 3 │ #include <stdalign.h> 4 │ #include <stddef.h> 5 │ #include <stdint.h> 6 │ #include <stdio.h> 7 │ #include <stdlib.h> 8 │ #include <string.h> 9 │ #include <sys/stat.h> 10 │ #include <sys/types.h> 11 │ 12 │ struct padded_hdr { 13 │ uint8_t tag; 14 │ uint32_t seq;───────┴────────────────────────────────────────────────────────────────────────────────GL-C01 · 1.2 (m01-l02)
>_ Kernel Systems Academy
# Stepping Through All Four GCC Stages, nm & Sanitizers
- Execute all four GCC translation stages (
-E,-S,-c, and final link with `-fsanitize=address,undefine…
GL-C01 · 1.2 (m01-l02)
>_ Kernel Systems Academy
# Stepping Through All Four GCC Stages, nm & Sanitizers
learner@ksa:~/gl-c01/m01-l02$ gcc -fdiagnostics-color=always -std=c11 -Wall -Wextra -Werror -E type_bridge.c -o type_bridge.ilearner@ksa:~/gl-c01/m01-l02$ gcc -fdiagnostics-color=always -std=c11 -Wall -Wextra -Werror -S type_bridge.c -o type_bridge.slearner@ksa:~/gl-c01/m01-l02$ gcc -fdiagnostics-color=always -std=c11 -Wall -Wextra -Werror -c type_bridge.c -o type_bridge.olearner@ksa:~/gl-c01/m01-l02$ nm type_bridge.o | grep -c ' T main$'learner@ksa:~/gl-c01/m01-l02$ gcc -fdiagnostics-color=always -std=c11 -O2 -Wall -Wextra -Werror -fsanitize=address,undefined type_bridge.c -o type_bridgelearner@ksa:~/gl-c01/m01-l02$ ./type_bridge && rm -f type_bridge.i type_bridge.s type_bridge.o type_bridge1arr_sizeof=16 strlen_at_nul=2 ptr_decayed=1 ovf_guard=1ssize_signed=1 off_bits=64 oct_0644=420 dec_644_oct=01204hdr_sz=12 seq_off=4 align=4 f32_hex=0x3f800000learner@ksa:~/gl-c01/m01-l02$ GL-C01 · 1.2 (m01-l02)
>_ Kernel Systems Academy
# Why Strict Types, Visibility & Sanitizers Catch Silent Corruption
- Stepping across
.i->.s->.o-> ELF proved each layer's contract empirically.
GL-C01 · 1.2 (m01-l02)
>_ Kernel Systems Academy
# Guided Practice: Reordering Struct Fields & Fixing Aliasing UB
- Examine
struct padded_hdr(12bytes:uint8_t tag; uint32_t seq; uint16_t flags;) and the broken stric…
GL-C01 · 1.2 (m01-l02)
>_ Kernel Systems Academy
# Guided Practice: Reordering Struct Fields & Fixing Aliasing UB
- 1.
GL-C01 · 1.2 (m01-l02)
>_ Kernel Systems Academy
# Independent Practice: Static Archive Link-Order & -fno-common Audit
- Create three files (
frame.h,frame.c,driver_cli.c) whereframe.hdeclares `extern size_t g_frames_…
GL-C01 · 1.2 (m01-l02)
>_ Kernel Systems Academy
# Warning
warning: Symptom: GCC rejects fileno(), pread(), or strnlen() with implicit declaration of function under -std=c11 -Werror even though #define _POSIX_C_SOURCE 200809L is present in the .c file. Root Cause: A project header (such as #include "config.h") included <stdio.h> above the #define, freezing <features.h> in strict ISO C11 mode for the rest of the translation unit. Fix: Place #define _POSIX_C_SOURCE 200809L and #define _FILE_OFFSET_BITS 64 on lines 1–2 of every .c file (or pass -D_POSIX_C_SOURCE=200809L -D_FILE_OFFSET_BITS=64 in CFLAGS).
GL-C01 · 1.2 (m01-l02)
>_ Kernel Systems Academy
# Warning
warning: Symptom: A length guard if (signed_len + hdr_sz < signed_len) return -1; passes -Wall -Wextra cleanly yet allows heap corruption at -O2, or int status; inside common.h triggers multiple definition of 'status' on GCC 13. Root Cause: Signed integer overflow is ISO C11 Undefined Behavior so -O2 folds a + 16 < a to false, and GCC 10+ defaults to -fno-common so tentative definitions in headers emit colliding .bss globals. Fix: Validate capacities via unsigned size_t subtraction (if (len > cap - hdr_sz)), and declare extern int status; in headers with exactly one .c definition.
GL-C01 · 1.2 (m01-l02)
>_ Kernel Systems Academy
# Quick check
? You need the authoritative header requirements, return contract, and error codes for the Linux kernel write() system call rather than the user terminal messaging utility. Which command opens the right manual section?
Select an option or press R to reveal.
Correct: B
Section 2 documents Linux kernel system calls, whereas section 1 covers shell commands and section 3 covers C library functions.
Common misconception: Typing man write without a section number opens write(1), the terminal user-messaging utility, instead of the write(2) syscall.
GL-C01 · 1.2 (m01-l02)
>_ Kernel Systems Academy
# Quick check
? (Review from earlier lesson) Why does compiling with gcc -c sysbuf.c -o sysbuf.o succeed even when sysbuf.c defines Ring 3 helper functions without defining main()?
Select an option or press R to reveal.
Correct: A
Stage 3 (-c) emits relocatable machine code (.text, .data, .bss) plus unresolved symbol tables that ld resolves during Stage 4 linking.
Common misconception: Developers accustomed to single-file gcc app.c commands often conflate object assembly (-c) with final executable linking.
GL-C01 · 1.2 (m01-l02)
>_ Kernel Systems Academy
# Quick check
? What permission bitmask is produced in C if a developer writes mode_t m = 644; instead of mode_t m = 0644;?
Select an option or press R to reveal.
Correct: C
C integer literals starting with 1..9 are decimal; 644 == 512 + 128 + 4 == 01204 in octal, scrambling inode permissions.
Common misconception: Because shell chmod 644 interprets digits as octal by convention, C programmers frequently omit the mandatory leading 0 on 0644.
GL-C01 · 1.2 (m01-l02)
>_ Kernel Systems Academy
# Quick check
? A packet parser validates int payload_len (>= 0) with if (payload_len + 16 < payload_len) return -1; before malloc((size_t)(payload_len + 16)). Why does gcc -std=c11 -O2 delete that guard when you review the generated .s assembly?
Select an option or press R to reveal.
Correct: B
Optimizing C11 compilers assume signed integer overflow cannot occur on any valid path; validate capacities via unsigned size_t subtraction (len > cap - 16U) and test under -fsanitize=address,undefined.
Common misconception: Treating signed C integer overflow as benign two's-complement wraparound silently turns bounds checks into dead code at -O2.
GL-C01 · 1.2 (m01-l02)
>_ Kernel Systems Academy
# Summary
- Compile multi-file systems C projects explicitly across preprocessing (
-E), compilation (-S), assembly (-c), archiving (ar rcs), and linking with-std=c11 -Wall -Wextra -Werrorand-fsanitize=address,undefined. - Define feature-test macros (
_POSIX_C_SOURCE 200809L,_FILE_OFFSET_BITS 64) before the very first#include, and useexterndeclarations in headers so GCC-fno-commonnever hits tentative-definition collisions. - Consult
man 2for Linux kernel syscalls andman 3forglibcfunctions, verifyingSYNOPSIS,RETURN VALUE, andERRORSbefore writing callers. - Pair unsigned
size_tcapacities with signedssize_t/off_treturn checks, pass(const uint8_t *, len)for binary data, write octal0644permissions, and replace signed-overflow or pointer-aliasing UB with unsigned subtraction andmemcpy().
GL-C01 · 1.2 (m01-l02)
>_ Kernel Systems Academy
# Summary
- Next, we will link C11 translation units against
glibc(libc.so.6), trace dynamic.plt/.got.pltrel…
GL-C01 · 1.2 (m01-l02)
>_ Kernel Systems Academy
# Key takeaways
- Consult
man 2for Linux kernel syscalls andman 3forglibcfunctions, verifyingSYNOPSIS,RETURN VALUE, andERRORSbefore writing callers. - Pair unsigned
size_tcapacities with signedssize_t/off_treturn checks, pass(const uint8_t *, len)for binary data, write octal0644permissions, and replace signed-overflow or pointer-aliasing UB with unsigned subtraction andmemcpy(). - Next, we will link C11 translation units against
glibc(libc.so.6), trace dynamic.plt/.got.pltrelocations and C Runtime (CRT)_startinitialization, inspecterrno, and count exact traps understrace.
GL-C01 · 1.3 (m01-l03)
>_ Kernel Systems Academy
# Syscall Wrappers, CRT, errno & strace
What you'll learn
- Distinguish pure Ring 3
glibchelpers (strlen,memcpy) from Ring 0 syscall wrappers and.plt/.got.pltstubs. - Trace ELF startup from
PT_INTERPand CRT_start->__libc_start_main->main()across descriptors0,1,2. - Diagnose negative kernel
-errnotranslations via thread-localerrno,perror(), andstrerror()(EBADF,EINTR).
GL-C01 · 1.3 (m01-l03)
>_ Kernel Systems Academy
# Why main() Is Not First and Not Every libc Call Enters Ring 0
- Two mysteries ambush almost every engineer debugging a deployed Linux binary for the first time.
GL-C01 · 1.3 (m01-l03)
>_ Kernel Systems Academy
# Why main() Is Not First and Not Every libc Call Enters Ring 0
- Both failures stem from treating
main()and<stdio.h>/<unistd.h>as black boxes.
GL-C01 · 1.3 (m01-l03)
>_ Kernel Systems Academy
# Mental model
note: Think of a corporate mailroom inside your office building. Drafting memos or sorting spreadsheets happens right at your desk, whereas sending a registered courier pouch goes through a mailroom clerk who stamps the manifest, hands it to external transport, and records any delivery rejection code on your receipt.
Where it stops working: Unlike an office clerk who works asynchronously, a glibc syscall wrapper executes synchronously on the calling thread's stack and CPU registers before returning control.
GL-C01 · 1.3 (m01-l03)
>_ Kernel Systems Academy
# CRT Startup, PLT/GOT Trampolines & Syscall Wrappers
definition: C Runtime Startup (crt1.o _start) & Dynamic Linkage (.plt / .got.plt): Named for the C Runtime object linked ahead of user .o files, _start aligns the initial stack pointer pushed by execve() (argc, argv[], envp[], and Elf_auxv_t auxiliary vectors) and calls __libc_start_main(). In Position-Independent Executables (PIE), external calls jump through a read-only Procedure Linkage Table (.plt) stub that dereferences a Global Offset Table (.got.plt) JUMP_SLOT resolved by the PT_INTERP dynamic linker (ld-linux). Syscall Wrappers issue the CPU trap and translate kernel returns in [-4095, -1] into positive thread-local errno plus (ssize_t)-1.
GL-C01 · 1.3 (m01-l03)
>_ Kernel Systems Academy
# One Layer Down: execve Stack Layout, -4095..-1 Error Math & PLT Dispatch
- During
execve(), the Linux kernel ELF loader maps.text(PROT_READ | PROT_EXEC),.rodata(`PROT_REA…
GL-C01 · 1.3 (m01-l03)
>_ Kernel Systems Academy
# One Layer Down: execve Stack Layout, -4095..-1 Error Math & PLT Dispatch
- Why does the Linux kernel reserve
[-4095, -1](0xfffffffffffff001..0xffffffffffffffffon 64-bit) in `%r…
GL-C01 · 1.3 (m01-l03)
>_ Kernel Systems Academy
# One Layer Down: execve Stack Layout, -4095..-1 Error Math & PLT Dispatch
Figure 1.3: ELF PT_INTERP and crt1.o _start startup chain, PLT/GOT dynamic linkage, and [-4095, -1] thread-local errno demultiplexing.
GL-C01 · 1.3 (m01-l03)
>_ Kernel Systems Academy
# One Layer Down: execve Stack Layout, -4095..-1 Error Math & PLT Dispatch
execve() builds the 16-byte aligned stack (argc, argv, envp, auxv) and loads PT_INTERP (missing loader => ENOENT).
Execution starts in PT_INTERP and crt1.o _start before main(), and only Ring 0 syscall wrappers enter strace or set thread-local errno on failure.
GL-C01 · 1.3 (m01-l03)
>_ Kernel Systems Academy
# Inspecting Standard Descriptors, GOT/PLT Relocations & errno
- Include
<unistd.h>,<errno.h>,<stdio.h>, and<string.h>under#define _POSIX_C_SOURCE 200809L.
GL-C01 · 1.3 (m01-l03)
>_ Kernel Systems Academy
# Probing .init_array Constructors, Pure Loops, EBADF & strace
- Save
crt_wrapper_probe.cbelow.
GL-C01 · 1.3 (m01-l03)
>_ Kernel Systems Academy
# crt_wrapper_probe.c
learner@ksa:~/gl-c01/m01-l03$ bat crt_wrapper_probe.c───────┬──────────────────────────────────────────────────────────────────────────────── │ File: crt_wrapper_probe.c───────┼──────────────────────────────────────────────────────────────────────────────── 1 │ #define _POSIX_C_SOURCE 200809L 2 │ #include <errno.h> 3 │ #include <gnu/libc-version.h> 4 │ #include <stdio.h> 5 │ #include <stdlib.h> 6 │ #include <string.h> 7 │ #include <unistd.h> 8 │ 9 │ static int g_ctor_ran = 0; 10 │ 11 │ __attribute__((constructor)) 12 │ static void on_crt_init(void) { 13 │ g_ctor_ran = 1; 14 │ }───────┴────────────────────────────────────────────────────────────────────────────────GL-C01 · 1.3 (m01-l03)
>_ Kernel Systems Academy
# Verifying PT_INTERP, JUMP_SLOT Relocations, strace & Lab 1
- Compile
crt_wrapper_probe, verifyPT_INTERPandwrite's.got.pltJUMP_SLOTrelocation with `reade…
GL-C01 · 1.3 (m01-l03)
>_ Kernel Systems Academy
# Verifying PT_INTERP, JUMP_SLOT Relocations, strace & Lab 1
learner@ksa:~/gl-c01/m01-l03$ gcc -fdiagnostics-color=always -std=c11 -Wall -Wextra -Werror crt_wrapper_probe.c -o crt_wrapper_probelearner@ksa:~/gl-c01/m01-l03$ ./crt_wrapper_probe frame-07 && echo exit_status=$?learner@ksa:~/gl-c01/m01-l03$ ldd ./crt_wrapper_probe | grep -o 'libc\.so\.6' | head -n 1learner@ksa:~/gl-c01/m01-l03$ readelf -lW ./crt_wrapper_probe | grep -c 'Requesting program interpreter'learner@ksa:~/gl-c01/m01-l03$ readelf -rW ./crt_wrapper_probe | grep -c 'JUMP_SLOT.*write'learner@ksa:~/gl-c01/m01-l03$ strace -e trace=write ./crt_wrapper_probe frame-07 2>&1 >/dev/null | grep -c '^write('glibc=2.39 ctor=1 argc=2 pure_acc=8000 argv_null=1 ebadf_ok=1exit_status=0libc.so.6112learner@ksa:~/gl-c01/m01-l03$ GL-C01 · 1.3 (m01-l03)
>_ Kernel Systems Academy
# Verifying PT_INTERP, JUMP_SLOT Relocations, strace & Lab 1
- Inspect the recorded
stracesession:ld-linuxmaps/etc/ld.so.cacheandlibc.so.6first, the `1,000…
GL-C01 · 1.3 (m01-l03)
>_ Kernel Systems Academy
# Verifying PT_INTERP, JUMP_SLOT Relocations, strace & Lab 1
learner@ksa:~/gl-c01/m01-l03$ strace -e trace=openat,write,close ./crt_wrapper_probe frame-07GL-C01 · 1.3 (m01-l03)
>_ Kernel Systems Academy
# Lab: lab_m01_toolchain_tracer
- 1.
Verify: ./check.sh exits 0.
GL-C01 · 1.3 (m01-l03)
>_ Kernel Systems Academy
# Tracing Control from PT_INTERP and _start to $?
- When the shell invoked
./crt_wrapper_probe frame-07,execve()loadedPT_INTERP, mappedlibc.so.6, a…
GL-C01 · 1.3 (m01-l03)
>_ Kernel Systems Academy
# Guided Practice: Link-Time Fault Injection with -Wl,--wrap=write
- GNU
ld's--wrap=writeflag redirects calls towrite()to__wrap_write()while exposing the real wra…
GL-C01 · 1.3 (m01-l03)
>_ Kernel Systems Academy
# Guided Practice: Link-Time Fault Injection with -Wl,--wrap=write
- 1.
GL-C01 · 1.3 (m01-l03)
>_ Kernel Systems Academy
# Independent Practice: Auxiliary Vector (auxv) Hardware & Page-Size Inspector
- Write a standalone C11 binary
auxv_probe.c(-std=c11 -Wall -Wextra -Werror) that calls `getauxval(AT_PA…
GL-C01 · 1.3 (m01-l03)
>_ Kernel Systems Academy
# Warning
warning: Symptom: A helper runs ssize_t n = write(fd, buf, len); if (errno != 0) log_fatal(errno); and aborts with a stale "Bad file descriptor" error even when n == (ssize_t)len. Root Cause: Successful POSIX syscall wrappers never reset errno back to 0; errno retains whatever nonzero code an earlier failed probe left behind. Fix: Check errno strictly inside if (n == -1) (and save int saved_err = errno; before any logging call).
GL-C01 · 1.3 (m01-l03)
>_ Kernel Systems Academy
# Warning
warning: Symptom: Running ./crt_wrapper_probe with zero CLI arguments crashes with SIGSEGV at strlen(argv[1]), or returning -1 from main() reports 255 in shell $?. Root Cause: With no CLI arguments, argc == 1 and argv[1] == NULL; meanwhile, POSIX waitpid() / exit_group() masks exit codes to status & 0xFF (-1 & 0xFF == 255). Fix: Check argc > idx before dereferencing argv[idx], and return EXIT_SUCCESS (0) or documented positive exit codes (1..125).
GL-C01 · 1.3 (m01-l03)
>_ Kernel Systems Academy
# Quick check
? While profiling a binary packet parser under strace, you observe write() traps in the trace output, but zero lines for strlen(), memcpy(), or snprintf(). Why?
Select an option or press R to reveal.
Correct: B
strace intercepts user-to-kernel syscall traps; pure user-space library helpers read and write caller virtual memory without entering Ring 0.
Common misconception: Many C programmers assume every function declared in system or standard headers is a 1-to-1 system call wrapper.
GL-C01 · 1.3 (m01-l03)
>_ Kernel Systems Academy
# Quick check
? (Review from earlier lesson) A write(fd, buf, len) call fails because fd was -1. What values do the Linux kernel trap return register and the user-space glibc wrapper produce respectively?
Select an option or press R to reveal.
Correct: B
Linux syscall ABI registers return -errno in [-4095, -1] on failure; glibc wrappers store -ret in thread-local errno and return -1.
Common misconception: Inspecting errno without first testing rc == -1 misreads stale error codes left over from earlier calls.
GL-C01 · 1.3 (m01-l03)
>_ Kernel Systems Academy
# Quick check
? Which routine executes as the ELF entry point before main(int argc, char *argv[]) and guarantees argv[argc] == NULL?
Select an option or press R to reveal.
Correct: A
_start (crt1.o) bridges the initial execve() stack (argc, argv, envp, auxv) to __libc_start_main(), runs .init_array and main(), and exits via exit_group().
Common misconception: Introductory C textbooks often give the impression that main() is the first instruction executed when a program starts.
GL-C01 · 1.3 (m01-l03)
>_ Kernel Systems Academy
# Quick check
? You copy a cross-compiled ./sensor_agent ELF executable onto a minimal ARMv7 rootfs, verify ls -l ./sensor_agent shows -rwxr-xr-x, yet running ./sensor_agent prints execve: No such file or directory (ENOENT). What is missing when you review the binary with readelf -lW?
Select an option or press R to reveal.
Correct: B
During execve() of a dynamically linked binary, the Linux kernel opens the PT_INTERP interpreter path; if that loader file is missing on disk, execve() fails with ENOENT even though ./sensor_agent exists!
Common misconception: Engineers frequently waste hours checking PATH and +x permissions when ENOENT on execve() actually reports a missing PT_INTERP runtime linker.
GL-C01 · 1.3 (m01-l03)
>_ Kernel Systems Academy
# Summary
glibc(libc.so.6) separates pureRing 3memory/string helpers (strlen(),memcpy(),snprintf()) fromRing 0syscall wrappers (write(),read(),openat()) routed through.plt/.got.pltJUMP_SLOTrelocations andPT_INTERP.- Every POSIX process inherits
STDIN_FILENO(0),STDOUT_FILENO(1), andSTDERR_FILENO(2) open at startup. - When a syscall fails, the Linux kernel returns
-errnoin[-4095, -1]and theglibcwrapper sets positive thread-localerrno(EBADF,EINTR, formatted viaperror()/strerror()) and returns-1. - ELF binaries enter at
_start(crt1.o) ->__libc_start_main()withargc,argv[],envp[], andElf_auxv_ton the initial stack, executing.init_arrayconstructors beforemain()and forwardingstatus & 0xFFto$?.
GL-C01 · 1.3 (m01-l03)
>_ Kernel Systems Academy
# Summary
- With toolchain, ELF startup,
errno, andstracemastered, Module 2 opens disk files directly to control…
GL-C01 · 1.3 (m01-l03)
>_ Kernel Systems Academy
# Key takeaways
- When a syscall fails, the Linux kernel returns
-errnoin[-4095, -1]and theglibcwrapper sets positive thread-localerrno(EBADF,EINTR, formatted viaperror()/strerror()) and returns-1. - ELF binaries enter at
_start(crt1.o) ->__libc_start_main()withargc,argv[],envp[], andElf_auxv_ton the initial stack, executing.init_arrayconstructors beforemain()and forwardingstatus & 0xFFto$?. - With toolchain, ELF startup,
errno, andstracemastered, Module 2 opens disk files directly to control per-process descriptor allocation,open()bitmasks, andmode & ~umaskpermissions.
m02/
>_ Kernel Systems Academy
# Core Unbuffered POSIX File I/O
Acquire and manage per-process file descriptors with exact open() flags and mode & ~umask permissions, build partial-count and EINTR-resilient read_full() and write_all() loops, and implement side-effect-safe lseek() byte-slicing tools.
- 2.1 Descriptors, open Flags & Permissions
- 2.2 Byte I/O with write, read & close
- 2.3 File Offsets & lseek Slicing
lab → Byte-Exact Framed Slice Copier
GL-C01 · 2.1 (m02-l01)
>_ Kernel Systems Academy
# Descriptors, open Flags & Permissions
What you'll learn
- Verify lowest-unused descriptor allocation across
0..2, slot reuse afterclose(), and dentry removal viaunlink(). - Select
open()O_ACCMODEmodes andO_CREAT,O_EXCL,O_TRUNC,O_APPEND,O_CLOEXEC, andO_TMPFILEflags. - Derive creation permissions via
mode & ~umaskand UB-free unsigned shifts (1U << bit) without variadic stack bugs.
GL-C01 · 2.1 (m02-l01)
>_ Kernel Systems Academy
# Why Naive open() Calls Leak Handles, Corrupt Modes & Trigger UB
- Picture a background daemon that closes
STDIN_FILENO(0),STDOUT_FILENO(1), andSTDERR_FILENO(`…
GL-C01 · 2.1 (m02-l01)
>_ Kernel Systems Academy
# Why Naive open() Calls Leak Handles, Corrupt Modes & Trigger UB
- Naive code stumbles on
open()because C lacks function overloading (forcing<fcntl.h>to declare `open(…
GL-C01 · 2.1 (m02-l01)
>_ Kernel Systems Academy
# Mental model
note: Think of a numbered coat-check rack with brass tags 0 through 1023. Slots 0, 1, and 2 are pre-hung at shift start, every new coat claims the lowest empty hook, and returning a tag immediately frees that hook for the next guest.
Where it stops working: Unlike brass coat tags, an open file descriptor also carries kernel access-mode and close-on-exec flags enforced on every subsequent read, write, or execve call.
GL-C01 · 2.1 (m02-l01)
>_ Kernel Systems Academy
# File Descriptors, O_ACCMODE & Process umask
definition: File Descriptor (fd) & Lowest-Unused Allocation: Coined in Seventh Edition Unix for a non-negative int array index into a process's private files_struct descriptor table (0..RLIMIT_NOFILE - 1), POSIX mandates that open() and openat() allocate the lowest-numbered unused slot (returning -1 with EMFILE when full). Access Mode (O_ACCMODE) is a 2-bit field (03 octal: O_RDONLY = 0, O_WRONLY = 1, O_RDWR = 2), while User File-Creation Mask (umask) clears disallowed permission bits on O_CREAT / O_TMPFILE via effective_mode = mode & ~umask.
GL-C01 · 2.1 (m02-l01)
>_ Kernel Systems Academy
# One Layer Down: fdtable Bitmap Scan, st_mode Bit Algebra & Unsigned Shifts
- Inside the Linux kernel (
fs/file.c),__alloc_fd()locates the lowest free descriptor inO(1)amortize…
GL-C01 · 2.1 (m02-l01)
>_ Kernel Systems Academy
# One Layer Down: fdtable Bitmap Scan, st_mode Bit Algebra & Unsigned Shifts
- When
O_CREATorO_TMPFILEcreates a new inode, VFS combines the 4-bit file type (S_IFREG = 0100000) w…
GL-C01 · 2.1 (m02-l01)
>_ Kernel Systems Academy
# One Layer Down: fdtable Bitmap Scan, st_mode Bit Algebra & Unsigned Shifts
Figure 2.1a: Per-process descriptor table lowest-slot allocation and open() flag composition.
GL-C01 · 2.1 (m02-l01)
>_ Kernel Systems Academy
# One Layer Down: fdtable Bitmap Scan, st_mode Bit Algebra & Unsigned Shifts
Figure 2.1b: Kernel fdtable O(1) bitmap scan and 16-bit POSIX mode_t / ~umask bitfield algebra.
GL-C01 · 2.1 (m02-l01)
>_ Kernel Systems Academy
# One Layer Down: fdtable Bitmap Scan, st_mode Bit Algebra & Unsigned Shifts
Compose one O_ACCMODE access value with O_CREAT | O_EXCL | O_CLOEXEC and an explicit octal mode_t.
Every open() claims the lowest unused fdtable slot, seals FD_CLOEXEC atomically when O_CLOEXEC is passed, and masks new inode permissions by ~umask.
GL-C01 · 2.1 (m02-l01)
>_ Kernel Systems Academy
# Variadic open() Prototypes, openat() & unlink()
- Include
<fcntl.h>,<sys/stat.h>,<sys/types.h>, and<unistd.h>under `#define _POSIX_C_SOURCE 20080…
GL-C01 · 2.1 (m02-l01)
>_ Kernel Systems Academy
# open
open(2) GL-C01 Quick Reference open(2) NAME open, openat - open or create a file and allocate a descriptor SYNOPSIS #include <fcntl.h> int open(const char *pathname, int flags, ... /* mode_t mode */); int openat(int dirfd, const char *pathname, int flags, ...); STANDARDS POSIX.1-2008; openat() requires _POSIX_C_SOURCE >= 200809L. RETURN VALUE Returns lowest-numbered unused descriptor (>= 0), or -1 with errno set. ERRORS EACCES Requested access mode or directory search permission denied. EEXIST O_CREAT | O_EXCL specified and pathname already exists. EINTR Blocked open on a slow device or FIFO interrupted by signal. Kernel Systems Academy m02-l01 open(2) GL-C01 quick reference · full manual page: man 2 open GL-C01 · 2.1 (m02-l01)
>_ Kernel Systems Academy
# Auditing Lowest-Slot Reuse, O_ACCMODE, umask & UB-Free Rotates
- Save
open_perm_audit.cbelow.
GL-C01 · 2.1 (m02-l01)
>_ Kernel Systems Academy
# open_perm_audit.c
learner@ksa:~/gl-c01/m02-l01$ bat open_perm_audit.c───────┬──────────────────────────────────────────────────────────────────────────────── │ File: open_perm_audit.c───────┼──────────────────────────────────────────────────────────────────────────────── 1 │ #define _POSIX_C_SOURCE 200809L 2 │ #include <errno.h> 3 │ #include <fcntl.h> 4 │ #include <stdint.h> 5 │ #include <stdio.h> 6 │ #include <stdlib.h> 7 │ #include <sys/stat.h> 8 │ #include <sys/types.h> 9 │ #include <unistd.h> 10 │ 11 │ static inline uint32_t rotl32_safe(uint32_t x, unsigned int n) { 12 │ return (x << (n & 31U)) | (x >> ((-n) & 31U)); 13 │ }───────┴────────────────────────────────────────────────────────────────────────────────GL-C01 · 2.1 (m02-l01)
>_ Kernel Systems Academy
# Verifying Descriptor Slots and Masked Inode Permissions
- Compile
open_perm_auditunder-fsanitize=undefined, verify the runtime invariants, inspect the effectiv…
GL-C01 · 2.1 (m02-l01)
>_ Kernel Systems Academy
# Verifying Descriptor Slots and Masked Inode Permissions
learner@ksa:~/gl-c01/m02-l01$ gcc -fdiagnostics-color=always -std=c11 -Wall -Wextra -Werror -fsanitize=undefined open_perm_audit.c -o open_perm_auditlearner@ksa:~/gl-c01/m02-l01$ ./open_perm_auditlearner@ksa:~/gl-c01/m02-l01$ echo "$(stat -c '%a' /tmp/ksa_m02_a.tmp) $(stat -c '%a' /tmp/ksa_m02_b.tmp)" && rm -f /tmp/ksa_m02_a.tmp /tmp/ksa_m02_b.tmp open_perm_auditstd_fds=0,1,2 consecutive=1 reused_lowest=1excl_eexist=1 unlink_ok=1 rot_ub_safe=1644 644learner@ksa:~/gl-c01/m02-l01$ GL-C01 · 2.1 (m02-l01)
>_ Kernel Systems Academy
# Tracing Bitmap Reuse, O_ACCMODE & umask Enforcement
- Every check in
open_perm_auditconfirmed the VFS descriptor contract:fd1andfd2claimed consecutive…
GL-C01 · 2.1 (m02-l01)
>_ Kernel Systems Academy
# Guided Practice: Exact Private Keyfile Creation Under Loose umask
- Suppose an administrator runs your key-provisioning tool in a shell whose
umaskis0000(clearing zero…
GL-C01 · 2.1 (m02-l01)
>_ Kernel Systems Academy
# Guided Practice: Exact Private Keyfile Creation Under Loose umask
- 1.
GL-C01 · 2.1 (m02-l01)
>_ Kernel Systems Academy
# Independent Practice: Descriptor-Leak Exhaustion (EMFILE) Probe
- Write a C11 diagnostic
emfile_probe.cthat lowers the process's softRLIMIT_NOFILEceiling to16insi…
GL-C01 · 2.1 (m02-l01)
>_ Kernel Systems Academy
# Warning
warning: Symptom: Newly created log files appear on disk with random permissions like --w-r-xr-T (01252) that change from run to run! Root Cause: Calling variadic open(path, O_WRONLY | O_CREAT) with two arguments causes the kernel wrapper to read uninitialized ABI register %rdx / r2 garbage as mode_t mode. Fix: Always pass an explicit octal mode (0644 or 0600) whenever flags includes O_CREAT or O_TMPFILE.
GL-C01 · 2.1 (m02-l01)
>_ Kernel Systems Academy
# Warning
warning: Symptom: Writing if (flags & O_RDONLY) to verify read-only access evaluates to 0 (false) on every descriptor in the system! Root Cause: On Linux and POSIX, O_RDONLY has integer value 0 (O_WRONLY == 1, O_RDWR == 2), so bitwise AND with 0 always yields 0. Fix: Mask the 2-bit access field with (flags & O_ACCMODE) == O_RDONLY.
GL-C01 · 2.1 (m02-l01)
>_ Kernel Systems Academy
# Quick check
? A process starts with standard descriptors 0, 1, and 2 open, calls close(0) to close standard input, and immediately calls open("/etc/hostname", O_RDONLY | O_CLOEXEC). Which integer descriptor does open() return?
Select an option or press R to reveal.
Correct: B
Closing 0 marks slot 0 free in files_struct; the lowest-unused-slot rule guarantees the next open() returns 0.
Common misconception: Assuming open() never returns 0, 1, or 2 causes daemons that close standard streams without binding /dev/null to corrupt data files via printf() or perror().
GL-C01 · 2.1 (m02-l01)
>_ Kernel Systems Academy
# Quick check
? (Review from previous module) If a process running with umask 0027 calls open("key.bin", O_WRONLY | O_CREAT | O_EXCL | O_CLOEXEC, S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP | S_IROTH), what effective octal mode is stored on the new inode?
Select an option or press R to reveal.
Correct: A
Requested mode is 0664 (rw-rw-r--); masking off bits set in umask 0027 (----w-rwx) yields 0640 (rw-r-----).
Common misconception: Expecting open(..., mode) to stamp mode verbatim without ~umask masking leaves group-write bits unexpectedly cleared or world-read bits exposed.
GL-C01 · 2.1 (m02-l01)
>_ Kernel Systems Academy
# Quick check
? Why do production Linux C services include O_CLOEXEC directly inside open() rather than calling fcntl(fd, F_SETFD, FD_CLOEXEC) on the next line?
Select an option or press R to reveal.
Correct: C
Setting FD_CLOEXEC inside open() guarantees no concurrent thread can inherit the open descriptor across execve() between two syscalls.
Common misconception: Relying on a post-open fcntl(F_SETFD) call leaks sensitive descriptors in multithreaded servers spawning helper processes.
GL-C01 · 2.1 (m02-l01)
>_ Kernel Systems Academy
# Quick check
? A framing header defines #define HDR_URGENT (1 << 31) and uint32_t rot(uint32_t x, unsigned int n) { return (x << n) | (x >> (32 - n)); }. Why does -fsanitize=undefined abort on HDR_URGENT and rot(v, 0U)?
Select an option or press R to reveal.
Correct: B
Shifting into a signed 32-bit sign bit or shifting a 32-bit integer by >= 32 invokes ISO C11 Undefined Behavior; unsigned 1U / UINT32_C(1) literals and & 31U masks eliminate both UB hazards.
Common misconception: Expressions like (1 << 31) and x >> (32 - n) compile silently at -O0 on some flags yet trigger UBSan faults and -O2 miscompilations at n == 0.
GL-C01 · 2.1 (m02-l01)
>_ Kernel Systems Academy
# Summary
- Every process indexes open VFS objects through non-negative
intfile descriptors (0..RLIMIT_NOFILE - 1), pre-opening0,1, and2and always allocating the lowest unused integer. open()requires one access mode (O_RDONLY,O_WRONLY, orO_RDWR, tested viaO_ACCMODE) combined with creation and status flags (O_CREAT,O_EXCL,O_TRUNC,O_APPEND,O_CLOEXEC).- Whenever
O_CREATorO_TMPFILEis present, pass the thirdmode_targument (0644orS_I*macros); the kernel applieseffective_mode = mode & ~umask, and custom bitmasks must use unsigned shifts (1U << bit). - Close descriptors in reverse acquisition order on error paths so long-running daemons never exhaust
RLIMIT_NOFILE(EMFILE).
GL-C01 · 2.1 (m02-l01)
>_ Kernel Systems Academy
# Summary
- Next, with open descriptors in hand, we will implement binary-safe
write_all()andread_full()loops ac…
GL-C01 · 2.1 (m02-l01)
>_ Kernel Systems Academy
# Key takeaways
- Whenever
O_CREATorO_TMPFILEis present, pass the thirdmode_targument (0644orS_I*macros); the kernel applieseffective_mode = mode & ~umask, and custom bitmasks must use unsigned shifts (1U << bit). - Close descriptors in reverse acquisition order on error paths so long-running daemons never exhaust
RLIMIT_NOFILE(EMFILE). - Next, with open descriptors in hand, we will implement binary-safe
write_all()andread_full()loops across all fourssize_treturn regimes,MAX_RW_COUNT, and Linuxclose()error semantics.
GL-C01 · 2.2 (m02-l02)
>_ Kernel Systems Academy
# Byte I/O with write, read & close
What you'll learn
- Classify all four
ssize_treturn regimes ofread()andwrite()(full, short count,MAX_RW_COUNT,0EOF,-1). - Implement binary-safe
write_all()andread_full()retry loops overuint8_t *buffers without NUL assumptions. - Audit
close(fd)returns for deferred writebackEIOfaults without ever retryingclose()afterEINTRon Linux.
GL-C01 · 2.2 (m02-l02)
>_ Kernel Systems Academy
# Why Single-Shot read() / write() & Retried close() Corrupt Data
- Consider three bugs pulled straight from real incident postmortems.
GL-C01 · 2.2 (m02-l02)
>_ Kernel Systems Academy
# Why Single-Shot read() / write() & Retried close() Corrupt Data
- Single-shot transfers fail because POSIX
read()andwrite()are byte-stream primitives permitted to tra…
GL-C01 · 2.2 (m02-l02)
>_ Kernel Systems Academy
# Mental model
note: Think of unloading a 64-crate freight container with a forklift whose pallet load varies per trip. After each trip you count the crates actually moved, advance your manifest tally, and loop until zero crates remain—or stop cleanly when the container is empty.
Where it stops working: Unlike physical crates, a signal arriving mid-transfer before any byte moves causes read() or write() to return -1 with EINTR rather than 0.
GL-C01 · 2.2 (m02-l02)
>_ Kernel Systems Academy
# Short Counts, MAX_RW_COUNT & Linux close()
definition: Short Count (0 < n < count) & MAX_RW_COUNT (0x7ffff000): In POSIX read() and write(), any positive ssize_t return value strictly smaller than count is a legal partial transfer, not an error. Inside the Linux kernel (include/linux/fs.h), MAX_RW_COUNT (INT_MAX & PAGE_MASK = 0x7ffff000 = 2,147,479,552 bytes) caps every individual VFS transfer one 4 KiB page below 2 GiB so internal 32-bit page-offset calculations never overflow. Linux close() Contract (close(2)): The kernel removes fd from files_struct unconditionally upon syscall entry; deferred writeback failures return -1 (EIO), and retrying close(fd) is strictly forbidden.
GL-C01 · 2.2 (m02-l02)
>_ Kernel Systems Academy
# One Layer Down: All Four ssize_t Regimes & Pointer-Advance Math
- Every call to
ssize_t read(int fd, void *buf, size_t count)or `ssize_t write(int fd, const void *buf, si…
GL-C01 · 2.2 (m02-l02)
>_ Kernel Systems Academy
# One Layer Down: All Four ssize_t Regimes & Pointer-Advance Math
Figure 2.2: All four ssize_t return regimes, MAX_RW_COUNT (0x7ffff000) chunking, and single-shot Linux close(fd) semantics.
GL-C01 · 2.2 (m02-l02)
>_ Kernel Systems Academy
# One Layer Down: All Four ssize_t Regimes & Pointer-Advance Math
Cast void * to uint8_t * so byte-exact pointer advancement (p + done) obeys strict ISO C11.
Robust POSIX byte I/O wraps every read() and write() in a uint8_t * retry loop and checks close(fd) exactly once without retrying.
GL-C01 · 2.2 (m02-l02)
>_ Kernel Systems Academy
# Prototypes, Raw Non-NUL Buffers & close(2) Reference
- Include
<unistd.h>,<errno.h>, and<stdint.h>under#define _POSIX_C_SOURCE 200809L.
GL-C01 · 2.2 (m02-l02)
>_ Kernel Systems Academy
# read
read(2) GL-C01 Quick Reference read(2) NAME read, write, close - transfer raw bytes across an open file descriptor SYNOPSIS #include <unistd.h> ssize_t read(int fd, void *buf, size_t count); ssize_t write(int fd, const void *buf, size_t count); int close(int fd); STANDARDS POSIX.1-2008; Linux caps single calls to MAX_RW_COUNT (0x7ffff000). RETURN VALUE read() and write() return bytes transferred (>= 0; 0 on read means EOF), or -1 with errno set. close() returns 0 on success or -1 on error. ERRORS EAGAIN Non-blocking descriptor (O_NONBLOCK) cannot transfer immediately. Kernel Systems Academy m02-l02 read(2) GL-C01 quick reference · full manual page: man 2 read GL-C01 · 2.2 (m02-l02)
>_ Kernel Systems Academy
# Implementing Pipe-Tested write_all() and read_full() Loops
- Save
short_io_loop.cbelow.
GL-C01 · 2.2 (m02-l02)
>_ Kernel Systems Academy
# short_io_loop.c
learner@ksa:~/gl-c01/m02-l02$ bat short_io_loop.c───────┬──────────────────────────────────────────────────────────────────────────────── │ File: short_io_loop.c───────┼──────────────────────────────────────────────────────────────────────────────── 1 │ #define _POSIX_C_SOURCE 200809L 2 │ #include <errno.h> 3 │ #include <fcntl.h> 4 │ #include <stdint.h> 5 │ #include <stdio.h> 6 │ #include <stdlib.h> 7 │ #include <string.h> 8 │ #include <sys/stat.h> 9 │ #include <unistd.h> 10 │ 11 │ static int write_all(int fd, const void *buf, size_t count) { 12 │ const uint8_t *p = (const uint8_t *)buf; 13 │ size_t left = count; 14 │ while (left > 0U) {───────┴────────────────────────────────────────────────────────────────────────────────GL-C01 · 2.2 (m02-l02)
>_ Kernel Systems Academy
# Verifying Pipe Short Reads, Binary Reassembly & strace
- Compile
short_io_loop.c, verify the real7-byte short pipe read (pipe_short=7), byte-exact64-byte…
GL-C01 · 2.2 (m02-l02)
>_ Kernel Systems Academy
# Verifying Pipe Short Reads, Binary Reassembly & strace
learner@ksa:~/gl-c01/m02-l02$ gcc -fdiagnostics-color=always -std=c11 -Wall -Wextra -Werror short_io_loop.c -o short_io_looplearner@ksa:~/gl-c01/m02-l02$ ./short_io_looplearner@ksa:~/gl-c01/m02-l02$ strace -e trace=write ./short_io_loop 2>&1 >/dev/null | grep -c '^write('first_window=20 rest_window=44 total_match=1eof_read=0 label=HDR0 pipe_short=7 calls_ge_1=16learner@ksa:~/gl-c01/m02-l02$ GL-C01 · 2.2 (m02-l02)
>_ Kernel Systems Academy
# Verifying Pipe Short Reads, Binary Reassembly & strace
- Under
strace, observe the two pipe writes (7and13bytes), the three file writes (17,19, and `2…
GL-C01 · 2.2 (m02-l02)
>_ Kernel Systems Academy
# Verifying Pipe Short Reads, Binary Reassembly & strace
learner@ksa:~/gl-c01/m02-l02$ strace -e trace=openat,write,read,close ./short_io_loopGL-C01 · 2.2 (m02-l02)
>_ Kernel Systems Academy
# Why write_all() and read_full() Anchor Every Storage Protocol
- Look at
strace_m02_l02: whenpfd[1]held only7bytes,read(pfd[0], prx, 20)legally returned7(…
GL-C01 · 2.2 (m02-l02)
>_ Kernel Systems Academy
# Guided Practice: Diagnosing a Torn-Header Framing Bug
- A student writes a length-prefixed packet reader `uint32_t len; if (read(fd, &len, 4) <= 0) return -1; read…
GL-C01 · 2.2 (m02-l02)
>_ Kernel Systems Academy
# Guided Practice: Diagnosing a Torn-Header Framing Bug
- 1.
GL-C01 · 2.2 (m02-l02)
>_ Kernel Systems Academy
# Independent Practice: CLOCK_MONOTONIC Chunk-Size Throughput Sweep
- Write a C11 benchmark
chunk_sweep.c(-std=c11 -O2 -Wall -Wextra -Werror) that writes and reads back a `…
GL-C01 · 2.2 (m02-l02)
>_ Kernel Systems Academy
# Warning
warning: Symptom: Calling char buf[64]; ssize_t n = read(fd, buf, 64); printf("%s\n", buf); prints valid configuration text followed by binary stack garbage or crashes with SIGSEGV. Root Cause: read() copies raw bytes and never appends a '\0' terminator; when n == 64 (or n < 64 over dirty stack bytes), %s scans past valid data until hitting a chance zero byte. Fix: Read at most sizeof(buf) - 1 bytes and assign buf[n] = '\0', or use printf("%.*s\n", (int)n, buf).
GL-C01 · 2.2 (m02-l02)
>_ Kernel Systems Academy
# Warning
warning: Symptom: Wrapping close(fd) in while (close(fd) == -1 && errno == EINTR) {} inside a multithreaded daemon randomly closes another thread's newly opened file or client socket! Root Cause: On the Linux kernel, close(fd) releases slot fd from files_struct before flushing driver state; if a sibling thread immediately allocates that lowest unused fd, retrying close(fd) closes the sibling's handle! Fix: Check if (close(fd) == -1) once to log deferred EIO, and never retry close(fd) on Linux.
GL-C01 · 2.2 (m02-l02)
>_ Kernel Systems Academy
# Quick check
? (Review from earlier lesson) What happens when size_t n = read(fd, buf, 256); executes on an invalid descriptor (EBADF) inside a while (total < 256) loop?
Select an option or press R to reveal.
Correct: B
Storing (ssize_t)-1 into unsigned size_t converts -1 to SIZE_MAX; always capture read() and write() in signed ssize_t.
Common misconception: Confusing size_t (requested capacity) with ssize_t (signed return count) causes severe memory-safety bugs on error paths.
GL-C01 · 2.2 (m02-l02)
>_ Kernel Systems Academy
# Quick check
? When read(fd, buf, 4096) returns 0 on a regular file or open pipe, what state did the caller encounter?
Select an option or press R to reveal.
Correct: A
For count > 0, read() == 0 unambiguously marks clean EOF, whereas transient non-blocking emptiness or signal interruption returns -1 with EAGAIN or EINTR.
Common misconception: Retrying read() infinitely when n == 0 pins a CPU core at 100% utilization as soon as a peer closes its pipe or socket.
GL-C01 · 2.2 (m02-l02)
>_ Kernel Systems Academy
# Quick check
? If the Linux kernel automatically closes all open descriptors when a process exits, why must long-running C services explicitly call and check close(fd)?
Select an option or press R to reveal.
Correct: B
Long-lived daemons run continuously; leaking one descriptor per request hits EMFILE, and deferred filesystem writeback failures often surface at close().
Common misconception: Relying on process-exit descriptor cleanup works only in short-lived CLI one-liners and fails rapidly in production services.
GL-C01 · 2.2 (m02-l02)
>_ Kernel Systems Academy
# Quick check
? On 64-bit Linux, a backup engine allocates a 3 GiB RAM buffer and calls ssize_t n = read(fd, buf, 3ULL << 30); once on a local 4 GiB ext4 disk file with zero signals pending. What does read() return?
Select an option or press R to reveal.
Correct: B
Linux caps every individual read() and write() syscall at MAX_RW_COUNT (0x7ffff000), proving why read_full() and write_all() loops are mandatory even on local disk files.
Common misconception: Assuming short counts occur only on network sockets or pipes corrupts >= 2 GiB snapshots and database checkpoints.
GL-C01 · 2.2 (m02-l02)
>_ Kernel Systems Academy
# Summary
write()andread()return signedssize_tacross four regimes: full count, positive short count (0 < n < count, including the LinuxMAX_RW_COUNT0x7ffff000cap),0(cleanEOFonread()), and-1(EINTRretry vs fatalerrno).- Wrap binary transfers in
write_all()andread_full()loops that castvoid *touint8_t *and advance(p + done, count - done). - Never pass raw
read()buffers to NUL-terminated string routines without reservingsizeof(buf) - 1and writing'\0'explicitly. - Always call
close(fd), checkclose(fd) == -1for deferredEIOfaults, and never retryclose(fd)on the Linux kernel.
GL-C01 · 2.2 (m02-l02)
>_ Kernel Systems Academy
# Summary
- Next, we move beyond sequential byte streams to random-access cursor positioning with 64-bit
lseek(), spa…
GL-C01 · 2.2 (m02-l02)
>_ Kernel Systems Academy
# Key takeaways
- Never pass raw
read()buffers to NUL-terminated string routines without reservingsizeof(buf) - 1and writing'\0'explicitly. - Always call
close(fd), checkclose(fd) == -1for deferredEIOfaults, and never retryclose(fd)on the Linux kernel. - Next, we move beyond sequential byte streams to random-access cursor positioning with 64-bit
lseek(), sparse-extent queries (SEEK_DATA/SEEK_HOLE), and pre-validated byte slicing.
GL-C01 · 2.3 (m02-l03)
>_ Kernel Systems Academy
# File Offsets & lseek Slicing
What you'll learn
- Reposition
struct file.f_posvia 64-bitlseek()(SEEK_SET,SEEK_CUR,SEEK_END,SEEK_DATA,SEEK_HOLE). - Diagnose signed
off_toverflow hazards, negative-offsetEINVALerrors, andESPIPErejections on pipes and sockets. - Construct all five canonical POSIX
open()andlseek()byte-slicing patterns after pre-validating source bounds.
GL-C01 · 2.3 (m02-l03)
>_ Kernel Systems Academy
# Why Shared f_pos Cursors & Eager O_TRUNC Opens Destroy Files
- Two subtle failures appear whenever engineers graduate from sequential
read()/write()streams to random…
GL-C01 · 2.3 (m02-l03)
>_ Kernel Systems Academy
# Why Shared f_pos Cursors & Eager O_TRUNC Opens Destroy Files
- Random-access I/O requires three engineering habits: explicit cursor positioning via 64-bit
lseek(), over…
GL-C01 · 2.3 (m02-l03)
>_ Kernel Systems Academy
# Mental model
note: Think of a magnetic tape deck equipped with a digital byte counter. Every play or record pass advances the counter automatically by the bytes transferred, while fast-forward or rewind jumps the tape head relative to zero, the current counter, or the tape end.
Where it stops working: Unlike physical tape, lseek() updates only an in-memory integer offset inside the Linux kernel without spinning disks or transferring a single byte.
GL-C01 · 2.3 (m02-l03)
>_ Kernel Systems Academy
# Shared File Offset (f_pos), lseek() & Extent Seeks
definition: File Offset (f_pos) & lseek(fd, offset, whence): Named from "long seek" in Seventh Edition Unix (when file offsets widened from 16-bit int to 32-bit long, and later to signed 64-bit off_t under _FILE_OFFSET_BITS=64), lseek() updates the in-memory f_pos coordinate inside the kernel's open file description relative to SEEK_SET (0), SEEK_CUR (f_pos), or SEEK_END (i_size). Linux 3.1+ (standardized in POSIX.1-2024) adds SEEK_DATA and SEEK_HOLE to jump directly across allocated extents and sparse holes in O(extents) metadata time.
GL-C01 · 2.3 (m02-l03)
>_ Kernel Systems Academy
# One Layer Down: f_pos_lock, Signed off_t Algebra & Five Canonical Patterns
- Inside
fs/read_write.c(ksys_lseek), the Linux kernel acquiresfile->f_pos_lock(a per-struct file…
GL-C01 · 2.3 (m02-l03)
>_ Kernel Systems Academy
# One Layer Down: f_pos_lock, Signed off_t Algebra & Five Canonical Patterns
- Because
off_tis signed ([-2^63, 2^63 - 1]under_FILE_OFFSET_BITS=64so negativeSEEK_CURdelt…
GL-C01 · 2.3 (m02-l03)
>_ Kernel Systems Academy
# One Layer Down: f_pos_lock, Signed off_t Algebra & Five Canonical Patterns
Figure 2.3: Positioning struct file.f_pos with lseek(), guarding 64-bit off_t subtraction bounds, and pre-validating sources before O_TRUNC opens.
GL-C01 · 2.3 (m02-l03)
>_ Kernel Systems Academy
# One Layer Down: f_pos_lock, Signed off_t Algebra & Five Canonical Patterns
Probe source size with lseek(sfd, 0, SEEK_END) first so pipes/sockets fail fast with ESPIPE before touching dst.
Validate source seekability and subtraction bounds via lseek() before opening any destination pathname with O_CREAT | O_TRUNC.
GL-C01 · 2.3 (m02-l03)
>_ Kernel Systems Academy
# 64-Bit lseek(2) Reference & Cross-Architecture ILP32 Rules
- Always define
#define _FILE_OFFSET_BITS 64(plus#define _GNU_SOURCEwhen callingSEEK_DATA/ `SEEK_H…
GL-C01 · 2.3 (m02-l03)
>_ Kernel Systems Academy
# lseek
lseek(2) GL-C01 Quick Reference lseek(2) NAME lseek - reposition read/write file offset inside struct file SYNOPSIS #define _FILE_OFFSET_BITS 64 #include <unistd.h> off_t lseek(int fd, off_t offset, int whence); STANDARDS POSIX.1-2008; SEEK_DATA and SEEK_HOLE require _GNU_SOURCE (or POSIX.1-2024). RETURN VALUE Returns resulting byte offset from start of file, or (off_t)-1 on error. ERRORS EBADF fd is not an open file descriptor. EINVAL whence is invalid, or resulting file offset would be negative. ENXIO SEEK_DATA or SEEK_HOLE offset is at or beyond end-of-file. Kernel Systems Academy m02-l03 lseek(2) GL-C01 quick reference · full manual page: man 2 lseek GL-C01 · 2.3 (m02-l03)
>_ Kernel Systems Academy
# Implementing All Five Canonical Patterns & Extent Seeks in C11
- Save
offset_patterns.cbelow.
GL-C01 · 2.3 (m02-l03)
>_ Kernel Systems Academy
# offset_patterns.c
learner@ksa:~/gl-c01/m02-l03$ bat offset_patterns.c───────┬──────────────────────────────────────────────────────────────────────────────── │ File: offset_patterns.c───────┼──────────────────────────────────────────────────────────────────────────────── 1 │ #define _GNU_SOURCE 2 │ #define _FILE_OFFSET_BITS 64 3 │ #include <errno.h> 4 │ #include <fcntl.h> 5 │ #include <stdint.h> 6 │ #include <stdio.h> 7 │ #include <stdlib.h> 8 │ #include <string.h> 9 │ #include <sys/stat.h> 10 │ #include <sys/types.h> 11 │ #include <unistd.h> 12 │ 13 │ static int safe_add_off(off_t cur, off_t delta, off_t *out) { 14 │ if (delta > 0 && cur > (off_t)INT64_MAX - delta) {───────┴────────────────────────────────────────────────────────────────────────────────GL-C01 · 2.3 (m02-l03)
>_ Kernel Systems Academy
# Tracing lseek Calls and Completing Lab 2
- Check the exact boundary indices before executing: starting at byte
500,[500..1023]spans524zero b…
GL-C01 · 2.3 (m02-l03)
>_ Kernel Systems Academy
# Tracing lseek Calls and Completing Lab 2
learner@ksa:~/gl-c01/m02-l03$ gcc -fdiagnostics-color=always -std=c11 -Wall -Wextra -Werror offset_patterns.c -o offset_patternslearner@ksa:~/gl-c01/m02-l03$ printf 'stream' | ./offset_patternslearner@ksa:~/gl-c01/m02-l03$ printf 'stream' | strace -e trace=lseek ./offset_patterns 2>&1 | grep -c 'SEEK_'learner@ksa:~/gl-c01/m02-l03$ rm -f offset_patternsp1_enoent=1 p3_eexist=1 src_size=2048 dst_size=1024cur_after=1524 boundary=0x00,0xff ovf=1 ext=1 err=1,18learner@ksa:~/gl-c01/m02-l03$ GL-C01 · 2.3 (m02-l03)
>_ Kernel Systems Academy
# Lab: lab_m02_framed_copy
- 1.
Verify: ./check.sh exits 0.
GL-C01 · 2.3 (m02-l03)
>_ Kernel Systems Academy
# Zero-Disk f_pos Updates Bridge to Kernel Open-File Tables
- Every
lseek()inoffset_patternsupdatedfile->f_posin kernel RAM with zero block transfers, extract…
GL-C01 · 2.3 (m02-l03)
>_ Kernel Systems Academy
# Guided Practice: Cursor-Preserving Header Peek Helper
- Write a helper
int peek_magic_at_zero(int fd, uint32_t *magic_out)that reads the 4-byte header at byte `…
GL-C01 · 2.3 (m02-l03)
>_ Kernel Systems Academy
# Guided Practice: Cursor-Preserving Header Peek Helper
- 1.
GL-C01 · 2.3 (m02-l03)
>_ Kernel Systems Academy
# Independent Practice: Reverse-Chunk Binary Trailer Scanner
- Write a C11 utility
tail_magic_scan.c(_FILE_OFFSET_BITS=64,-Wall -Wextra -Werror) that locates the…
GL-C01 · 2.3 (m02-l03)
>_ Kernel Systems Academy
# Warning
warning: Symptom: Overwriting a 7,000-byte configuration file with a new 5,200-byte payload via open(dst, O_WRONLY | O_CREAT, 0644) leaves 1,800 bytes of stale trailing text at [5200..6999]! Root Cause: Omitting O_TRUNC preserves existing i_size and trailing blocks past the newly written prefix. Fix: Pass O_TRUNC on full-file overwrites (or write a staged temporary file and rename() atomically).
GL-C01 · 2.3 (m02-l03)
>_ Kernel Systems Academy
# Warning
warning: Symptom: Cross-compiling a partition-slicing tool for 32-bit ARMv7 (Cortex-A7) works on 500 MiB test files, then fails in the field with EOVERFLOW on a 3 GiB rootfs image. Root Cause: Without #define _FILE_OFFSET_BITS 64 before system headers, 32-bit ILP32 off_t is a signed 32-bit long capped at 2,147,483,647 bytes. Fix: Define _FILE_OFFSET_BITS 64 at line 1 of every C11 I/O source file (or in CFLAGS).
GL-C01 · 2.3 (m02-l03)
>_ Kernel Systems Academy
# Quick check
? Which lseek() invocation lets a diagnostic helper retrieve the active byte offset of a seekable descriptor fd without changing its position?
Select an option or press R to reveal.
Correct: B
SEEK_CUR adds 0 to file->f_pos and returns the active off_t coordinate unchanged.
Common misconception: Calling lseek(fd, 0, SEEK_SET) to "check" offset 0 silently rewinds f_pos to the start of the file.
GL-C01 · 2.3 (m02-l03)
>_ Kernel Systems Academy
# Quick check
? (Review from earlier lesson) Why must copy_slice() validate src_fd with lseek(src_fd, 0, SEEK_END) before calling open(dst_path, O_WRONLY | O_CREAT | O_TRUNC | O_CLOEXEC, 0644)?
Select an option or press R to reveal.
Correct: A
Pre-validating source seekability and bounds guarantees that invalid arguments abort with zero filesystem side effects.
Common misconception: Opening all input and output paths at the top of a function before validating preconditions leaves truncated 0-byte files behind on errors.
GL-C01 · 2.3 (m02-l03)
>_ Kernel Systems Academy
# Quick check
? An application opens a brand-new file with O_RDWR | O_CREAT | O_TRUNC, writes 512 bytes via write_all(), and immediately calls read_full(fd, buf, 512). What does read_full() return?
Select an option or press R to reveal.
Correct: C
One open file description (struct file) owns a single f_pos shared by read() and write(); writing 512 bytes from 0 leaves f_pos at 512 (EOF).
Common misconception: Picturing independent read and write offsets on one O_RDWR descriptor is one of the most common early POSIX I/O bugs.
GL-C01 · 2.3 (m02-l03)
>_ Kernel Systems Academy
# Quick check
? A virtual-machine archiver needs to copy only allocated data extents from a 64 GiB sparse image (63 GiB unallocated holes) without polluting the kernel page cache. Which Linux lseek() idiom achieves O(extents) traversal?
Select an option or press R to reveal.
Correct: B
SEEK_DATA and SEEK_HOLE walk the filesystem extent tree in O(extents) metadata operations without synthesizing gigabytes of zero-filled page-cache folios.
Common misconception: Scanning sparse holes with read() forces VFS to zero-fill user buffers across every unallocated gigabyte.
GL-C01 · 2.3 (m02-l03)
>_ Kernel Systems Academy
# Summary
- Sequential
read()andwrite()calls automatically advance the descriptor's shared byte offsetf_posby the transferred count. lseek(fd, offset, whence)repositionsf_posrelative toSEEK_SET,SEEK_CUR(lseek(fd, 0, SEEK_CUR)queries position),SEEK_END, or sparse extents (SEEK_DATA,SEEK_HOLE).- Guard signed 64-bit
off_tbounds via subtraction (req_len <= (size_t)(src_sz - req_off)) under_FILE_OFFSET_BITS 64, and handle(off_t)-1errors (EINVALon negative target offsets,ESPIPEon pipes/sockets). - Combine
ENOENTprobes,O_CREAT | O_EXCLatomic creation,O_TRUNCoverwrites, and pre-validatedSEEK_ENDbounds checks to build side-effect-safe binary slicing tools.
GL-C01 · 2.3 (m02-l03)
>_ Kernel Systems Academy
# Summary
- With core unbuffered POSIX file operations complete, Module 3 peers inside the Linux kernel to map static o…
GL-C01 · 2.3 (m02-l03)
>_ Kernel Systems Academy
# Key takeaways
- Guard signed 64-bit
off_tbounds via subtraction (req_len <= (size_t)(src_sz - req_off)) under_FILE_OFFSET_BITS 64, and handle(off_t)-1errors (EINVALon negative target offsets,ESPIPEon pipes/sockets). - Combine
ENOENTprobes,O_CREAT | O_EXCLatomic creation,O_TRUNCoverwrites, and pre-validatedSEEK_ENDbounds checks to build side-effect-safe binary slicing tools. - With core unbuffered POSIX file operations complete, Module 3 peers inside the Linux kernel to map static on-disk inodes, the three-tier dynamic VFS open-file hierarchy, thread-local
errnounwinding, and sparse extent holes.
m03/
>_ Kernel Systems Academy
# Kernel Open-File Internals, Errors & Sparse Files
Trace static on-disk directory entries and inodes into the dynamic 3-tier Linux kernel VFS open-file hierarchy, preserve thread-local errno across exit() vs _exit() termination paths, and engineer sparse hole files with O_TRUNC and O_APPEND.
- 3.1 Disk Inodes & Kernel VFS Tables
- 3.2 Thread-Local errno & Exit Paths
- 3.3 Sparse Holes, O_TRUNC & O_APPEND
lab → Sparse Partition Image Builder & Hole Inspector
GL-C01 · 3.1 (m03-l01)
>_ Kernel Systems Academy
# Disk Inodes & Kernel VFS Tables
What you'll learn
- Distinguish static disk structures (superblock, inode table, dentries, 4 KiB blocks) from dynamic VFS RAM tables.
- Trace
files_struct->struct file(f_pos,f_op) ->struct inodeand type-safeCONTAINER_OF/offsetofmath. - Inspect hard-link
st_ino/st_nlinksharing viastat()and livef_pos/O_CLOEXECflags in/proc/self/fdinfo.
GL-C01 · 3.1 (m03-l01)
>_ Kernel Systems Academy
# Why rm Can Free Zero Disk Bytes & Inodes Never Store Filenames
- Every production systems engineer eventually receives the midnight alert:
/var/logis99%full, an oper…
GL-C01 · 3.1 (m03-l01)
>_ Kernel Systems Academy
# Why rm Can Free Zero Disk Bytes & Inodes Never Store Filenames
- Mental models that picture a "file" as a named blob attached directly to an integer
fdbreak down complet…
GL-C01 · 3.1 (m03-l01)
>_ Kernel Systems Academy
# Mental model
note: Think of a library card catalog versus an active reading-room checkout slip. Multiple catalog cards in different drawers can reference the exact same numbered shelf volume, while each reader at a table holds a personal bookmark slip tracking their current page in that volume.
Where it stops working: Unlike paper catalog cards, the Linux kernel caches active 4 KiB book pages inside shared RAM (the page cache) rather than fetching from disk on every read or write.
GL-C01 · 3.1 (m03-l01)
>_ Kernel Systems Academy
# Directory Entry (dentry), Inode, Three-Tier VFS & CONTAINER_OF
definition: Index Node (inode) vs Directory Entry (dentry): Named by Dennis Ritchie for "index node", an on-disk inode stores numeric ownership (st_uid, st_gid), st_mode, st_size, st_blocks, hard-link count (st_nlink), and data-block extents—never the filename. Parent directory entries (dentries) map human strings ("sensor.log") to st_ino numbers. Three-Tier VFS Hierarchy: open() links per-process files_struct (fd, FD_CLOEXEC) -> system-wide struct file (f_pos, f_flags, f_count, f_op) -> shared VFS struct inode + 4 KiB RAM Page Cache, while CONTAINER_OF(ptr, type, member) recovers enclosing driver structs from embedded VFS anchors via offsetof subtraction.
GL-C01 · 3.1 (m03-l01)
>_ Kernel Systems Academy
# Why rm Can Free Zero Disk Bytes & Inodes Never Store Filenames
Figure 3.1a: Static ext4 disk layout — directory entries map filenames to inode numbers in the Inode Table, which index 4 KiB data blocks.
GL-C01 · 3.1 (m03-l01)
>_ Kernel Systems Academy
# One Layer Down: Block Geometry, Reclamation Condition & CONTAINER_OF Math
- On non-volatile storage,
512-byte hardware sectors are grouped into4 KiB(4,096-byte) filesystem blo…
GL-C01 · 3.1 (m03-l01)
>_ Kernel Systems Academy
# One Layer Down: Block Geometry, Reclamation Condition & CONTAINER_OF Math
- How does pure ISO C inside the Linux kernel dispatch a single
read(fd, buf, len)syscall acrossext4ex…
GL-C01 · 3.1 (m03-l01)
>_ Kernel Systems Academy
# One Layer Down: Block Geometry, Reclamation Condition & CONTAINER_OF Math
Figure 3.1b: Dynamic Linux kernel VFS pointer chain (task_struct -> fdtable -> struct file -> inode -> address_space), orphan block survival, and CONTAINER_OF recovery.
GL-C01 · 3.1 (m03-l01)
>_ Kernel Systems Academy
# One Layer Down: Block Geometry, Reclamation Condition & CONTAINER_OF Math
Each process PCB (task_struct) owns a private files_struct slot array storing FD_CLOEXEC and a struct file pointer.
Filenames map to inode numbers on disk, while open descriptors index through private FD slots into struct file cursors and one shared VFS inode page cache.
GL-C01 · 3.1 (m03-l01)
>_ Kernel Systems Academy
# Observing Live VFS State with stat(), link() & /proc/self/fdinfo
- Include
<sys/stat.h>,<fcntl.h>,<stddef.h>, and<unistd.h>under#define _POSIX_C_SOURCE 200809L.
GL-C01 · 3.1 (m03-l01)
>_ Kernel Systems Academy
# Probing Hard Links, Orphaned Open Inodes, CONTAINER_OF & fdinfo
- Save
vfs_fdinfo_probe.cbelow.
GL-C01 · 3.1 (m03-l01)
>_ Kernel Systems Academy
# vfs_fdinfo_probe.c
learner@ksa:~/gl-c01/m03-l01$ bat vfs_fdinfo_probe.c───────┬──────────────────────────────────────────────────────────────────────────────── │ File: vfs_fdinfo_probe.c───────┼──────────────────────────────────────────────────────────────────────────────── 1 │ #define _POSIX_C_SOURCE 200809L 2 │ #include <errno.h> 3 │ #include <fcntl.h> 4 │ #include <stddef.h> 5 │ #include <stdint.h> 6 │ #include <stdio.h> 7 │ #include <stdlib.h> 8 │ #include <string.h> 9 │ #include <sys/stat.h> 10 │ #include <unistd.h> 11 │ 12 │ #define CONTAINER_OF(ptr, type, member) \ 13 │ ((type *)((char *)(1 ? (ptr) : &((type *)0)->member) - \ 14 │ offsetof(type, member)))───────┴────────────────────────────────────────────────────────────────────────────────GL-C01 · 3.1 (m03-l01)
>_ Kernel Systems Academy
# Verifying Shared st_ino, Orphan Inode Survival & fdinfo
- Compile and execute
vfs_fdinfo_probe: confirmpath_aandpath_bshare onest_ino(hard_links=2),…
GL-C01 · 3.1 (m03-l01)
>_ Kernel Systems Academy
# Verifying Shared st_ino, Orphan Inode Survival & fdinfo
learner@ksa:~/gl-c01/m03-l01$ gcc -fdiagnostics-color=always -std=c11 -Wall -Wextra -Werror vfs_fdinfo_probe.c -o vfs_fdinfo_probelearner@ksa:~/gl-c01/m03-l01$ ./vfs_fdinfo_probelearner@ksa:~/gl-c01/m03-l01$ strace -e trace=link,linkat ./vfs_fdinfo_probe 2>&1 | grep -c 'ksa_vfs_b.dat'learner@ksa:~/gl-c01/m03-l01$ rm -f vfs_fdinfo_probesame_inode=1 hard_links=2 st_size=128 orphan_alive=1fdinfo_pos=128 cloexec_in_flags=1 intrusive_ok=11learner@ksa:~/gl-c01/m03-l01$ GL-C01 · 3.1 (m03-l01)
>_ Kernel Systems Academy
# Why Page-Cache & Reference-Counted Inodes Outlive Directory Names
- Notice how
orphan_alive=1demystified the10 GiBunlinked-log incident in twenty lines of C!
GL-C01 · 3.1 (m03-l01)
>_ Kernel Systems Academy
# Guided Practice: Tracing CONTAINER_OF Byte Arithmetic by Hand
- Given
struct rx_ring { uint64_t drops; uint32_t mask; struct vfs_hook hook; };on 64-bit Linux where `&r.…
GL-C01 · 3.1 (m03-l01)
>_ Kernel Systems Academy
# Guided Practice: Tracing CONTAINER_OF Byte Arithmetic by Hand
- 1.
GL-C01 · 3.1 (m03-l01)
>_ Kernel Systems Academy
# Independent Practice: Live Process Open-File & Orphan Inspector
- Write a C11 tool
self_fd_audit.cthat opens two regular files (unlinking one while keeping its descriptor…
GL-C01 · 3.1 (m03-l01)
>_ Kernel Systems Academy
# Warning
warning: Symptom: Removing a runaway /var/log/app.log file with rm clears the directory listing, yet df -h shows 0 freed gigabytes and new writes fail with ENOSPC. Root Cause: The running process still holds an open struct file (f_count > 0) referencing the unlinked inode (st_nlink == 0), blocking block reclamation until close(). Fix: Signal the service (SIGHUP / SIGUSR1) to close and reopen its log descriptor, or truncate the active file in place (truncate -s 0 / O_TRUNC).
GL-C01 · 3.1 (m03-l01)
>_ Kernel Systems Academy
# Warning
warning: Symptom: Decommissioning an embedded flash partition after unlink() or a quick mkfs allows forensic sector reads to recover plaintext keys. Root Cause: Quick-formatting resets only the superblock and inode/block bitmaps, and unlink() clears directory entries and inode metadata without overwriting physical 4 KiB data blocks. Fix: Overwrite sensitive payloads explicitly (fdatasync before unlink) or issue block-device secure erase (BLKSECDISCARD).
GL-C01 · 3.1 (m03-l01)
>_ Kernel Systems Academy
# Quick check
? Where is a regular file's human-readable filename stored inside a POSIX filesystem such as ext4?
Select an option or press R to reveal.
Correct: B
Inodes store metadata and extent pointers but never filenames; directory entries map names to st_ino numbers, enabling multiple hard links (st_nlink >= 2) to share one inode.
Common misconception: Assuming an inode stores its own filename makes hard links and cross-directory renames impossible to reason about.
GL-C01 · 3.1 (m03-l01)
>_ Kernel Systems Academy
# Quick check
? (Review from earlier lesson) Which kernel structure stores the active byte offset f_pos returned by lseek(fd, 0, SEEK_CUR)?
Select an option or press R to reveal.
Correct: B
f_pos and open status flags (O_APPEND, O_NONBLOCK) reside in struct file and are exposed live through /proc/self/fdinfo/<fd>.
Common misconception: Storing f_pos in struct inode would cause independent processes to clobber each other's read offsets, whereas storing it in files_struct would prevent dup()/fork() cursor sharing.
GL-C01 · 3.1 (m03-l01)
>_ Kernel Systems Academy
# Quick check
? When two independent processes open /etc/hosts with O_RDONLY simultaneously, how many copies of /etc/hosts's 4 KiB data pages does the Linux kernel maintain in RAM?
Select an option or press R to reveal.
Correct: B
Each open() allocates a separate struct file (f_pos), but both point to the single in-memory struct inode and its unified 4 KiB page cache.
Common misconception: "Unbuffered POSIX I/O" means unbuffered in user space (glibc), not uncached in the Linux kernel page cache!
GL-C01 · 3.1 (m03-l01)
>_ Kernel Systems Academy
# Quick check
? How does the Linux VFS implement zero-overhead polymorphism and generic intrusive list manipulation in ISO C across ext4, pipefs, procfs, and /dev drivers?
Select an option or press R to reveal.
Correct: B
Function-pointer vtables (f_op), compile-time offsetof recovery (CONTAINER_OF), and indirect pointers (**pp) achieve type-safe polymorphic dispatch with zero extra heap allocations.
Common misconception: Heap-allocated void * wrapper nodes add pointer indirection, cache misses, and unchecked cast bugs avoided by intrusive CONTAINER_OF design.
GL-C01 · 3.1 (m03-l01)
>_ Kernel Systems Academy
# Summary
- Block storage groups
512-byte sectors into4 KiBblocks organized into boot block, superblock, inode table (metadata + extents, never filenames), and directory/data blocks. - Directory entries map filenames to
st_inonumbers (ls -i,stat()), allowing hard links (link()) to share one underlying inode (st_nlink >= 2). - Calling
open()links three dynamic kernel RAM tiers: per-processfiles_struct(fd,FD_CLOEXEC) -> system-widestruct file(f_flags,f_pos,f_count,f_op) -> shared VFSstruct inode+ page cache. - VFS dispatches generic syscalls through
struct file_operationsvtables while subsystems recover enclosing types intrusively viaoffsetof(CONTAINER_OF) and unlink list nodes viastruct node **pp.
GL-C01 · 3.1 (m03-l01)
>_ Kernel Systems Academy
# Summary
- Next, we trace how VFS failures propagate back to user space via thread-local
errno, how multi-resource f…
GL-C01 · 3.1 (m03-l01)
>_ Kernel Systems Academy
# Key takeaways
- VFS dispatches generic syscalls through
struct file_operationsvtables while subsystems recover enclosing types intrusively viaoffsetof(CONTAINER_OF) and unlink list nodes viastruct node **pp. /proc/self/fdinfo/<fd>exposes live kernelpos:and octalflags:, and physical blocks are reclaimed only when bothst_nlink == 0andf_count == 0.- Next, we trace how VFS failures propagate back to user space via thread-local
errno, how multi-resource functions unwind cleanly in reverse (LIFO) order, and whyexit()and_exit()diverge on buffered output.
GL-C01 · 3.2 (m03-l02)
>_ Kernel Systems Academy
# Thread-Local errno & Exit Paths
What you'll learn
- Capture thread-local
errnointosaved_errnoimmediately after-1returns and format diagnostics viastrerror_r(). - Unwind multi-resource C acquisition chains in reverse LIFO order using leak-free
goto out_*labels and cleanup guards. - Contrast
exit()(atexitLIFO hooks +stdioflush) against immediate_exit()/_Exit()kernel termination.
GL-C01 · 3.2 (m03-l02)
>_ Kernel Systems Academy
# Why Intervening Calls Clobber errno & _exit() Drops Output
- Two bugs turn routine error-handling code into hours of misdirection.
GL-C01 · 3.2 (m03-l02)
>_ Kernel Systems Academy
# Why Intervening Calls Clobber errno & _exit() Drops Output
- Reliable error handling and termination in systems C rest on three strict mechanisms: preserving thread-loc…
GL-C01 · 3.2 (m03-l02)
>_ Kernel Systems Academy
# Mental model
note: Think of a cockpit master-caution lamp paired with a latched fault-code display, and a normal gate shutdown checklist versus an emergency fuel-cutoff lever. You read the fault register only after the caution lamp trips, and pulling emergency cutoff halts engines immediately without running cabin shutdown routines.
Where it stops working: Unlike a hardware fault lamp that stays latched until manually reset, calling another library function such as printf() can silently overwrite thread-local errno mid-handler.
GL-C01 · 3.2 (m03-l02)
>_ Kernel Systems Academy
# Thread-Local errno, strerror_r(), LIFO goto & _exit()
definition: Thread-Local errno (*__errno_location()): Originally a single global int in early Unix, ISO C11 / POSIX <errno.h> defines errno as a modifiable lvalue backed by per-thread Thread-Local Storage (%fs: segment on x86-64; CP15 TPIDRURO on ARMv7) so concurrent threads never race on fault codes. strerror_r(err, buf, len) formats err into caller-supplied stack memory without shared static-buffer races. LIFO goto Unwinding releases N acquired resources in strict reverse order (R_N -> ... -> R_1), while _exit(status) (<unistd.h>) traps straight to kernel exit_group() without running user-space atexit() or stdio fflush().
GL-C01 · 3.2 (m03-l02)
>_ Kernel Systems Academy
# One Layer Down: TLS Resolution, goto State Invariants & Exit Lifecycles
- When a
glibcwrapper sees%rax/r0in[-4095, -1], it writes(int)(-ret)into `*__errno_location…
GL-C01 · 3.2 (m03-l02)
>_ Kernel Systems Academy
# One Layer Down: TLS Resolution, goto State Invariants & Exit Lifecycles
- In functions acquiring
kresources sequentially (R_1 = open,R_2 = mmap,R_3 = malloc), naive neste…
GL-C01 · 3.2 (m03-l02)
>_ Kernel Systems Academy
# One Layer Down: TLS Resolution, goto State Invariants & Exit Lifecycles
Figure 3.2: Preserving thread-local errno against intervening clobbers, unwinding resources in LIFO goto order, and contrasting exit() against _exit().
GL-C01 · 3.2 (m03-l02)
>_ Kernel Systems Academy
# One Layer Down: TLS Resolution, goto State Invariants & Exit Lifecycles
Initialize int rc = -1 and NULL/-1 sentinels up front so early goto jumps never mask errors or free garbage.
Capture saved_errno immediately on -1, unwind partial resources in reverse LIFO order, and choose deliberately between buffered exit() and immediate _exit().
GL-C01 · 3.2 (m03-l02)
>_ Kernel Systems Academy
# XSI vs GNU strerror_r() & Scope-Guard Cleanup Notes
- Watch a subtle header portability detail on Linux: under
#define _POSIX_C_SOURCE 200809Lwithout `_GN…
GL-C01 · 3.2 (m03-l02)
>_ Kernel Systems Academy
# Proving saved_errno Clobber Immunity, LIFO goto & exit() vs _exit()
- Save
errno_exit_lab.cbelow.
GL-C01 · 3.2 (m03-l02)
>_ Kernel Systems Academy
# errno_exit_lab.c
learner@ksa:~/gl-c01/m03-l02$ bat errno_exit_lab.c───────┬──────────────────────────────────────────────────────────────────────────────── │ File: errno_exit_lab.c───────┼──────────────────────────────────────────────────────────────────────────────── 1 │ #define _POSIX_C_SOURCE 200809L 2 │ #include <errno.h> 3 │ #include <fcntl.h> 4 │ #include <stdio.h> 5 │ #include <stdlib.h> 6 │ #include <string.h> 7 │ #include <sys/stat.h> 8 │ #include <unistd.h> 9 │ 10 │ static const char *g_atexit_path = "/tmp/ksa_atexit_marker.tmp"; 11 │ 12 │ static void cleanup_handler(void) { 13 │ int flags = O_WRONLY | O_CREAT | O_TRUNC | O_CLOEXEC; 14 │ int mfd = open(g_atexit_path, flags, 0644);───────┴────────────────────────────────────────────────────────────────────────────────GL-C01 · 3.2 (m03-l02)
>_ Kernel Systems Academy
# Comparing Flushed exit() vs Dropped _exit() Output
- Compile
errno_exit_lab, redirectemit_exitandemit_uexitinto/tmpfiles, verify `exit_flushed_byt…
GL-C01 · 3.2 (m03-l02)
>_ Kernel Systems Academy
# Comparing Flushed exit() vs Dropped _exit() Output
learner@ksa:~/gl-c01/m03-l02$ gcc -fdiagnostics-color=always -std=c11 -Wall -Wextra -Werror errno_exit_lab.c -o errno_exit_lablearner@ksa:~/gl-c01/m03-l02$ rm -f /tmp/ksa_atexit_marker.tmplearner@ksa:~/gl-c01/m03-l02$ ./errno_exit_lab emit_exit > /tmp/ksa_stdio_exit.tmplearner@ksa:~/gl-c01/m03-l02$ ./errno_exit_lab emit_uexit > /tmp/ksa_stdio_uexit.tmplearner@ksa:~/gl-c01/m03-l02$ ./errno_exit_lablearner@ksa:~/gl-c01/m03-l02$ strace -e trace=exit_group ./errno_exit_lab emit_uexit 2>&1 >/dev/null | grep -c 'exit_group(0)'learner@ksa:~/gl-c01/m03-l02$ rm -f errno_exit_labbad_fd=-1 saved_errno=2 is_enoent=1 msg_ok=1 lifo_ok=1exit_flushed_bytes=13 uexit_flushed_bytes=0 atexit=101learner@ksa:~/gl-c01/m03-l02$ GL-C01 · 3.2 (m03-l02)
>_ Kernel Systems Academy
# Why Cleanup Ordering & User-Space Teardown Govern Reliability
- Both
emit_exitandemit_uexitended at kernelexit_group(0)(`$?
GL-C01 · 3.2 (m03-l02)
>_ Kernel Systems Academy
# Note
note: Later: When spawning child processes in GL-C02, a fork() child whose execve() fails must call _exit(127) rather than exit(127)—otherwise the child flushes a second copy of its parent's inherited user-space stdio buffers!
GL-C01 · 3.2 (m03-l02)
>_ Kernel Systems Academy
# Guided Practice: Refactoring a Leaky 3-Step Initializer to LIFO goto
- A helper acquires
fd1 = open(a, ...),fd2 = open(b, ...), andbuf = malloc(4096), returning-1dire…
GL-C01 · 3.2 (m03-l02)
>_ Kernel Systems Academy
# Guided Practice: Refactoring a Leaky 3-Step Initializer to LIFO goto
- 1.
GL-C01 · 3.2 (m03-l02)
>_ Kernel Systems Academy
# Independent Practice: GCC __attribute__((cleanup)) RAII Scope Guard
- Write a standalone C11 test
cleanup_guard.c(-std=c11 -Wall -Wextra -Werror) defining `static void auto…
GL-C01 · 3.2 (m03-l02)
>_ Kernel Systems Academy
# Warning
warning: Symptom: An error branch if (open(p, O_RDONLY) == -1) { printf("Failed %s\n", p); perror("reason"); } prints reason: Inappropriate ioctl for device (ENOTTY) whenever stdout is redirected to a file! Root Cause: First-use printf() probes isatty(1) internally, which fails on regular files with ENOTTY and overwrites thread-local errno before perror() reads it. Fix: Save int saved_errno = errno; on the line immediately following open() == -1 and format saved_errno via strerror_r().
GL-C01 · 3.2 (m03-l02)
>_ Kernel Systems Academy
# Warning
warning: Symptom: Initializing int rc = 0; at the top of a goto-cleanup function causes an early if (fd2 < 0) goto out_fd1; branch to return 0 (success) to its caller with uninitialized output pointers! Root Cause: Forgetting rc = -1 before jumping leaves the optimistic 0 value intact. Fix: Always initialize int rc = -1; at function entry and assign rc = 0; only on the final line before the cleanup labels.
GL-C01 · 3.2 (m03-l02)
>_ Kernel Systems Academy
# Quick check
? (Review from earlier lesson) After ssize_t n = read(fd, buf, 64);, when is a C11 program permitted to inspect errno?
Select an option or press R to reveal.
Correct: B
Successful POSIX calls never reset errno to 0; only an explicit -1 (or NULL) error return guarantees errno holds that call's fault code.
Common misconception: Checking errno != 0 after a succeeding call misdiagnoses leftover ENOTTY or ENOENT values from earlier library internals.
GL-C01 · 3.2 (m03-l02)
>_ Kernel Systems Academy
# Quick check
? Which termination call bypasses atexit() handlers and drops unflushed user-space stdio FILE buffers by trapping directly into the Linux kernel?
Select an option or press R to reveal.
Correct: C
_exit() and _Exit() invoke the kernel exit_group syscall immediately without running user-space glibc atexit() hooks or fflush().
Common misconception: Mixing up exit() and _exit() either loses buffered output in CLI tools or double-flushes inherited buffers in failed fork() children.
GL-C01 · 3.2 (m03-l02)
>_ Kernel Systems Academy
# Quick check
? In a multithreaded Linux daemon compiled with #define _POSIX_C_SOURCE 200809L, which pattern safely formats a saved errno value without shared static-buffer races?
Select an option or press R to reveal.
Correct: B
Thread-local errno isolates fault integers per thread, while XSI strerror_r() formats the message into caller-supplied stack storage thread-safely.
Common misconception: Classic strerror() may overwrite a shared internal buffer across concurrent threads or signal handlers.
GL-C01 · 3.2 (m03-l02)
>_ Kernel Systems Academy
# Quick check
? A C function acquires open() -> mmap() -> malloc() and unwinds failures via numbered goto labels (goto out_buf; goto out_map; goto out_fd;). Which two initializations prevent the classic goto cleanup defects?
Select an option or press R to reveal.
Correct: B
Starting with int rc = -1 and NULL/-1 sentinels guarantees every early goto unwinds acquired resources in reverse (LIFO) order and returns -1 cleanly.
Common misconception: Optimistically setting int rc = 0 at the top of a goto-unwound function silently masks failures whenever a branch forgets rc = -1.
GL-C01 · 3.2 (m03-l02)
>_ Kernel Systems Academy
# Summary
- Failed Linux kernel syscalls return
-errnoin registers;glibcwrappers store the positive code in thread-localerrno(<errno.h>) and return-1. - Successful calls never reset
errnoto0; checkret == -1first, captureint saved_errno = errno;immediately, and format viaperror()or thread-safestrerror_r(). - Memorize core diagnostic codes:
ENOENT(2),EINTR(4),EIO(5),EBADF(9),EAGAIN(11),EACCES(13),EEXIST(17),EINVAL(22),ENOSPC(28), andESPIPE(29). - Unwind multi-resource C functions in reverse (
LIFO) order via numberedgotolabels (int rc = -1andNULL/-1initializers) while preservingerrnoacrossclose().
GL-C01 · 3.2 (m03-l02)
>_ Kernel Systems Academy
# Summary
- Next, we return to on-disk extent allocation to engineer sparse hole files, measure
st_sizeversus `st_bl…
GL-C01 · 3.2 (m03-l02)
>_ Kernel Systems Academy
# Key takeaways
- Unwind multi-resource C functions in reverse (
LIFO) order via numberedgotolabels (int rc = -1andNULL/-1initializers) while preservingerrnoacrossclose(). returninmainandexit()executeatexit()handlers (LIFO) and flushstdiostreams, whereas_exit()/_Exit()trap straight to kernelexit_group().- Next, we return to on-disk extent allocation to engineer sparse hole files, measure
st_sizeversusst_blocks * 512, and test the read/write cursor asymmetry ofO_RDWR | O_APPEND.
GL-C01 · 3.3 (m03-l03)
>_ Kernel Systems Academy
# Sparse Holes, O_TRUNC & O_APPEND
What you'll learn
- Construct sparse hole files by seeking past EOF with
lseek()and verify VFS0x00synthesis across unallocated extents. - Measure logical
st_sizevs allocated 512-byte sectors (st_blocks * 512) viafstat()and reclaim extents viaO_TRUNC. - Verify
O_RDWR | O_APPENDcursor asymmetry provinglseek()governsread()whilewrite()jumpsf_posto EOF.
GL-C01 · 3.3 (m03-l03)
>_ Kernel Systems Academy
# Why Literal Zero-Fills Exhaust Flash & O_APPEND Ignores lseek() on Writes
- Imagine two storage bugs that pass casual functional checks yet fail dramatically on embedded targets.
GL-C01 · 3.3 (m03-l03)
>_ Kernel Systems Academy
# Why Literal Zero-Fills Exhaust Flash & O_APPEND Ignores lseek() on Writes
- Both defects vanish once you understand how the Linux kernel decouples logical file length (
st_size)…
GL-C01 · 3.3 (m03-l03)
>_ Kernel Systems Academy
# Mental model
note: Think of a numbered loose-leaf binder versus a bound ledger stamped APPEND-ONLY. In the binder you can insert page 1,000 without buying paper for pages 2 through 999, whereas on the append-only ledger you may flip back to read page 1 anytime, yet every pen stroke is forced onto the bottom line.
Where it stops working: Unlike an empty gap in a ring binder, reading across an unallocated Linux sparse hole returns clean 0x00 bytes synthesized by VFS rather than an error.
GL-C01 · 3.3 (m03-l03)
>_ Kernel Systems Academy
# Sparse Extent Holes, POSIX 512-Byte st_blocks & O_APPEND Asymmetry
definition: Sparse Extent Hole: When lseek() positions f_pos past current EOF (i_size) and a subsequent write() commits data, POSIX filesystems (ext4, XFS, Btrfs, tmpfs) record an unallocated extent gap (hole) for [old_eof .. seek_offset), allocating physical blocks only for written pages while VFS synthesizes 0x00 bytes on read(). struct stat.st_blocks: Defined in POSIX.1 in fixed 512-byte sector units (historically Seventh Edition Unix disk sectors, never st_blksize!) so physical byte allocation always equals st_blocks * 512. O_APPEND Asymmetry: On an O_RDWR | O_APPEND description, lseek() governs read() normally, whereas every write() atomically resets f_pos = i_size under inode->i_rwsem.
GL-C01 · 3.3 (m03-l03)
>_ Kernel Systems Academy
# One Layer Down: Extent Trees, Sector Accounting Math & O_APPEND Locking
- Inside
ext4orXFS, an inode's extent tree maps logical block numbers (4 KiBunits) to physical devic…
GL-C01 · 3.3 (m03-l03)
>_ Kernel Systems Academy
# One Layer Down: Extent Trees, Sector Accounting Math & O_APPEND Locking
- Meanwhile, inspect how
O_TRUNCandO_APPENDact at different lifecycle moments inside VFS:
GL-C01 · 3.3 (m03-l03)
>_ Kernel Systems Academy
# One Layer Down: Extent Trees, Sector Accounting Math & O_APPEND Locking
Figure 3.3: Logical st_size versus physical st_blocks * 512 on a sparse hole file, O_TRUNC extent reclamation, and O_RDWR | O_APPEND write-cursor override.
GL-C01 · 3.3 (m03-l03)
>_ Kernel Systems Academy
# One Layer Down: Extent Trees, Sector Accounting Math & O_APPEND Locking
Seeking past EOF via lseek(hfd, 65536, SEEK_SET) advances f_pos in RAM without writing physical zero blocks.
Sparse holes decouple logical st_size from physical st_blocks * 512 allocation, while O_APPEND forces writes—never reads—to current i_size.
GL-C01 · 3.3 (m03-l03)
>_ Kernel Systems Academy
# fstat(2) Inspection Contract & Sparse-Filesystem Notes
- Include
<sys/stat.h>,<sys/types.h>,<fcntl.h>, and<unistd.h>under#define _FILE_OFFSET_BITS 64…
GL-C01 · 3.3 (m03-l03)
>_ Kernel Systems Academy
# Probing Sparse Holes, O_TRUNC Reclamation & O_RDWR | O_APPEND
- Save
hole_append_probe.cbelow.
GL-C01 · 3.3 (m03-l03)
>_ Kernel Systems Academy
# hole_append_probe.c
learner@ksa:~/gl-c01/m03-l03$ bat hole_append_probe.c───────┬──────────────────────────────────────────────────────────────────────────────── │ File: hole_append_probe.c───────┼──────────────────────────────────────────────────────────────────────────────── 1 │ #define _FILE_OFFSET_BITS 64 2 │ #define _POSIX_C_SOURCE 200809L 3 │ #include <errno.h> 4 │ #include <fcntl.h> 5 │ #include <stdint.h> 6 │ #include <stdio.h> 7 │ #include <stdlib.h> 8 │ #include <string.h> 9 │ #include <sys/stat.h> 10 │ #include <sys/types.h> 11 │ #include <unistd.h> 12 │ 13 │ int main(void) { 14 │ const char *hpath = "/tmp/ksa_hole_demo.bin";───────┴────────────────────────────────────────────────────────────────────────────────GL-C01 · 3.3 (m03-l03)
>_ Kernel Systems Academy
# Verifying Sparse Sector Counts, O_APPEND Asymmetry & Lab 3
- Compile and run
hole_append_probe, confirmhole_logical=69632withhole_phys_lt=1andtrunc_sz=0, v…
GL-C01 · 3.3 (m03-l03)
>_ Kernel Systems Academy
# Verifying Sparse Sector Counts, O_APPEND Asymmetry & Lab 3
learner@ksa:~/gl-c01/m03-l03$ gcc -fdiagnostics-color=always -std=c11 -Wall -Wextra -Werror hole_append_probe.c -o hole_append_probelearner@ksa:~/gl-c01/m03-l03$ ./hole_append_probelearner@ksa:~/gl-c01/m03-l03$ strace -e trace=openat ./hole_append_probe 2>&1 | grep -c 'O_APPEND'learner@ksa:~/gl-c01/m03-l03$ rm -f hole_append_probehole_logical=69632 hole_phys_lt=1 hole_zero=1 trunc_sz=0append_read0=0x11 byte0_kept=0x11 eof_byte4=0x551learner@ksa:~/gl-c01/m03-l03$ GL-C01 · 3.3 (m03-l03)
>_ Kernel Systems Academy
# Lab: lab_m03_sparse_image
- 1.
Verify: ./check.sh exits 0.
GL-C01 · 3.3 (m03-l03)
>_ Kernel Systems Academy
# Kernel-Locked O_APPEND Sets Up Module 4 File Sharing
- Inside
fs/read_write.c,O_APPENDworks because the kernel acquiresinode->i_rwsem, sets `kiocb.ki_pos…
GL-C01 · 3.3 (m03-l03)
>_ Kernel Systems Academy
# Guided Practice: Sparse-Aware File Copier Loop
- A naive
cpimplementation copies a sparse image by callingread()andwrite()unconditionally, inflat…
GL-C01 · 3.3 (m03-l03)
>_ Kernel Systems Academy
# Guided Practice: Sparse-Aware File Copier Loop
- 1.
GL-C01 · 3.3 (m03-l03)
>_ Kernel Systems Academy
# Independent Practice: Extent Map & Sparsity Ratio Reporter
- Write a C11 CLI
sparse_stat.c(#define _GNU_SOURCE,#define _FILE_OFFSET_BITS 64, `-Wall -Wextra -Wer…
GL-C01 · 3.3 (m03-l03)
>_ Kernel Systems Academy
# Warning
warning: Symptom: A storage engine opens its file with O_RDWR | O_APPEND, executes lseek(fd, 0, SEEK_SET) + write(fd, &hdr, 64) to update a superblock checksum in place, and discovers byte 0 never changed while st_size grew by 64 bytes! Root Cause: O_APPEND overrides f_pos to i_size on every write() regardless of prior lseek() calls. Fix: Open descriptors requiring in-place header overwrites without O_APPEND (or use stateless pwrite() on a non-append descriptor).
GL-C01 · 3.3 (m03-l03)
>_ Kernel Systems Academy
# Warning
warning: Symptom: Multiplying st.st_blocks * st.st_blksize to compute physical disk consumption over-reports storage usage by 8x on standard 4 KiB ext4 filesystems! Root Cause: POSIX fixes st_blocks in 512-byte units regardless of st_blksize (4,096 or 65,536). Fix: Always compute physical bytes as (long long)st.st_blocks * 512LL.
GL-C01 · 3.3 (m03-l03)
>_ Kernel Systems Academy
# Quick check
? A program creates an empty file on ext4, calls lseek(fd, 1048576, SEEK_SET) (1 MiB), and writes 64 bytes. What do st.st_size and (long long)st.st_blocks * 512LL report via fstat()?
Select an option or press R to reveal.
Correct: B
Seeking past EOF and writing extends logical st_size across the gap while allocating physical blocks solely for the written 4 KiB extent.
Common misconception: Confusing ls -lh (st_size) with du -h (st_blocks * 512) makes sparse images look fully allocated when they occupy kilobytes on media.
GL-C01 · 3.3 (m03-l03)
>_ Kernel Systems Academy
# Quick check
? (Review from earlier lesson) An existing 4-byte file {0x10, 0x20, 0x30, 0x40} is opened with open(path, O_RDWR | O_APPEND | O_CLOEXEC). The caller runs lseek(fd, 1, SEEK_SET), read(fd, &r, 1), lseek(fd, 0, SEEK_SET), and write(fd, &w, 1) where w = 0x99. What byte does read() fetch, and at what offset does 0x99 land?
Select an option or press R to reveal.
Correct: C
On O_RDWR | O_APPEND, lseek() controls read offsets normally, while the kernel forces every write() to current i_size.
Common misconception: Expecting lseek(fd, 0, SEEK_SET) to override O_APPEND for one write() is a classic storage bug.
GL-C01 · 3.3 (m03-l03)
>_ Kernel Systems Academy
# Quick check
? (Review from previous module) What happens when an existing 8 KiB log file is opened via open(path, O_WRONLY | O_APPEND | O_TRUNC | O_CLOEXEC) and the process writes two 16-byte records?
Select an option or press R to reveal.
Correct: B
O_TRUNC runs once at open() time, while O_APPEND governs subsequent write() calls on the truncated file.
Common misconception: Assuming O_APPEND | O_TRUNC is invalid overlooks how log-rotation utilities cleanly reset an append-only log file.
GL-C01 · 3.3 (m03-l03)
>_ Kernel Systems Academy
# Quick check
? On an XFS partition formatted with a 64 KiB (65,536-byte) block size (st.st_blksize == 65536), fstat() on a small file reports st.st_blocks == 128. How many physical bytes are allocated on disk?
Select an option or press R to reveal.
Correct: B
Regardless of whether st_blksize is 4 KiB or 64 KiB, st_blocks always counts 512-byte sectors (128 * 512 == 65,536 = one 64 KiB XFS block).
Common misconception: Multiplying st_blocks by st_blksize produces huge multi-megabyte errors on 64 KiB-block filesystems.
GL-C01 · 3.3 (m03-l03)
>_ Kernel Systems Academy
# Summary
- Seeking past
EOFwithlseek()and callingwrite()creates a sparse hole file:read()across unallocated holes returns VFS-synthesized0x00bytes without consuming physical disk blocks. fstat()separates logical byte lengthst.st_size(ls -lh) from physical allocation(long long)st.st_blocks * 512LL(du -h, unconditionally counted in512-byte POSIX units).O_TRUNC(paired withO_WRONLYorO_RDWR) resetsst_sizeto0and reclaims allocated extents duringopen().O_APPENDleavesread()seekable vialseek(), yet forces everywrite()inside the Linux kernel to jump atomically toi_sizeregardless of priorlseek()calls.
GL-C01 · 3.3 (m03-l03)
>_ Kernel Systems Academy
# Summary
- With VFS tables,
errnounwinding, and sparse extents in place, Module 4 tackles descriptor sharing (`dup2…
GL-C01 · 3.3 (m03-l03)
>_ Kernel Systems Academy
# Key takeaways
O_TRUNC(paired withO_WRONLYorO_RDWR) resetsst_sizeto0and reclaims allocated extents duringopen().O_APPENDleavesread()seekable vialseek(), yet forces everywrite()inside the Linux kernel to jump atomically toi_sizeregardless of priorlseek()calls.- With VFS tables,
errnounwinding, and sparse extents in place, Module 4 tackles descriptor sharing (dup2/dup3), atomicO_EXCL& statelesspread/pwrite, and runtimefcntl/ioctlcontrol.
m04/
>_ Kernel Systems Academy
# File Sharing, Atomic Operations & Descriptor Control
Control kernel open-file table sharing across dual opens and dup/dup2/dup3, eliminate TOCTOU and offset races with O_EXCL and stateless pread/pwrite, and manipulate live descriptors with fcntl, ioctl, and ftruncate.
- 4.1 Shared File Tables & dup Redirection
- 4.2 Atomic Kernel I/O: O_EXCL & pread
- 4.3 Descriptor Control: fcntl & ioctl
lab → Lab 4: Race-Free Positional Record Store with O_EXCL, pread/pwrite, and fcntl
GL-C01 · 4.1 (m04-l01)
>_ Kernel Systems Academy
# Shared File Tables & dup Redirection
What you'll learn
- Compare the three Linux kernel file-sharing topologies across dual
open(),dup/dup2/dup3, andfork()inheritance. - Reproduce independent-cursor overwrite hazards versus cooperating
O_APPENDwrites across dualopen()descriptors. - Implement
STDOUT_FILENOredirection and restoration while handlingdup2(fd, fd)vsdup3(fd, fd, O_CLOEXEC)EINVAL.
GL-C01 · 4.1 (m04-l01)
>_ Kernel Systems Academy
# Why Dual open() Overwrites Data & dup3(fd, fd, O_CLOEXEC) Fails
- Two subtle bugs surface whenever subsystems share files or redirect standard streams.
GL-C01 · 4.1 (m04-l01)
>_ Kernel Systems Academy
# Why Dual open() Overwrites Data & dup3(fd, fd, O_CLOEXEC) Fails
- Predicting every multi-descriptor interaction in Linux requires tracing exactly which tier of the three-tab…
GL-C01 · 4.1 (m04-l01)
>_ Kernel Systems Academy
# Mental model
note: Opening a file twice is like giving two editors separate bookmarks inside the same shared binder, whereas duplicating a descriptor clips two string tags onto a single shared bookmark that moves whenever either editor turns a page.
Where it stops working: Physical binder pages show ink collisions visually, whereas two independent kernel file descriptions overwrite cached bytes in RAM without warning unless O_APPEND serializes writes.
GL-C01 · 4.1 (m04-l01)
>_ Kernel Systems Academy
# Dual-Open Independence vs Descriptor Aliasing (dup/dup2/dup3)
definition: Dual open() Topology: Calling open() twice on one pathname allocates two distinct struct file objects (f_count = 1 each, independent f_pos and f_flags) pointing to one shared struct inode. Descriptor Duplication (dup, dup2, dup3): Named for "duplicate file descriptor" in early Unix, dup*() allocates or rebinds a files_struct slot to point at the exact same struct file (atomic_long_inc(&file->f_count)), sharing f_pos and f_flags (O_APPEND, O_NONBLOCK) while keeping slot-level FD_CLOEXEC independent per descriptor integer.
GL-C01 · 4.1 (m04-l01)
>_ Kernel Systems Academy
# Why Dual open() Overwrites Data & dup3(fd, fd, O_CLOEXEC) Fails
Figure 4.1a: Same-process dual open() — fd1 and fd2 allocate independent struct file cursors pointing to one shared VFS inode.
GL-C01 · 4.1 (m04-l01)
>_ Kernel Systems Academy
# Why Dual open() Overwrites Data & dup3(fd, fd, O_CLOEXEC) Fails
Figure 4.1b: Two independent processes opening the same pathname — separate PCBs and separate struct file cursors share one VFS inode.
GL-C01 · 4.1 (m04-l01)
>_ Kernel Systems Academy
# One Layer Down: f_count Reference Math & Per-Slot FD_CLOEXEC Bitmaps
- Inside
task_struct->files->fdt,close_on_execis a per-descriptor bitmask stored alongsidefd_array[]…
GL-C01 · 4.1 (m04-l01)
>_ Kernel Systems Academy
# One Layer Down: f_count Reference Math & Per-Slot FD_CLOEXEC Bitmaps
Figure 4.1c: dup() / dup2() / dup3() — two descriptor slots alias one shared struct file cursor (f_count = 2) while keeping FD_CLOEXEC isolated per slot.
GL-C01 · 4.1 (m04-l01)
>_ Kernel Systems Academy
# One Layer Down: f_count Reference Math & Per-Slot FD_CLOEXEC Bitmaps
Flush stdout first and call saved_out = dup(STDOUT_FILENO) to increment the terminal struct file's f_count to 2.
Only open() allocates a fresh struct file cursor; dup/dup2/dup3 alias an existing struct file, and safe STDOUT redirection flushes before and after rebinding.
GL-C01 · 4.1 (m04-l01)
>_ Kernel Systems Academy
# One Layer Down: f_count Reference Math & Per-Slot FD_CLOEXEC Bitmaps
Figure 4.1d: Kernel descriptor-to-file-to-inode topologies across dual open(), dup/dup2/dup3, fork(), and leak-free STDOUT redirection.
GL-C01 · 4.1 (m04-l01)
>_ Kernel Systems Academy
# dup(2) / dup2(2) / dup3(2) Contracts & Safe STDOUT_FILENO Redirection
- Define
#define _GNU_SOURCEbefore<unistd.h>and<fcntl.h>on Linux 6.12 to exposedup3().
GL-C01 · 4.1 (m04-l01)
>_ Kernel Systems Academy
# Proving Dual-Open Overwrites, dup3 Slot Isolation & stdout Restore
- Save
dual_open_dup.cbelow.
GL-C01 · 4.1 (m04-l01)
>_ Kernel Systems Academy
# dual_open_dup.c
learner@ksa:~/gl-c01/m04-l01$ bat dual_open_dup.c───────┬──────────────────────────────────────────────────────────────────────────────── │ File: dual_open_dup.c───────┼──────────────────────────────────────────────────────────────────────────────── 1 │ #define _GNU_SOURCE 2 │ #include <errno.h> 3 │ #include <fcntl.h> 4 │ #include <stdio.h> 5 │ #include <stdlib.h> 6 │ #include <string.h> 7 │ #include <sys/stat.h> 8 │ #include <unistd.h> 9 │ 10 │ static int has_cloexec_fdinfo(int target_fd) { 11 │ char p[64], buf[256]; 12 │ snprintf(p, sizeof(p), "/proc/self/fdinfo/%d", target_fd); 13 │ int ifd = open(p, O_RDONLY | O_CLOEXEC); 14 │ if (ifd < 0) return 0;───────┴────────────────────────────────────────────────────────────────────────────────GL-C01 · 4.1 (m04-l01)
>_ Kernel Systems Academy
# Verifying Cursor Topologies and Clean Redirection Restore
- Compile and execute
dual_open_dup: confirmdual_no_appendclobbers down to8bytes (BBBBBBBB), `dua…
GL-C01 · 4.1 (m04-l01)
>_ Kernel Systems Academy
# Verifying Cursor Topologies and Clean Redirection Restore
learner@ksa:~/gl-c01/m04-l01$ gcc -fdiagnostics-color=always -std=c11 -Wall -Wextra -Werror dual_open_dup.c -o dual_open_duplearner@ksa:~/gl-c01/m04-l01$ ./dual_open_duplearner@ksa:~/gl-c01/m04-l01$ test ! -e /tmp/ksa_m04_l01_over.bin && test ! -e /tmp/ksa_m04_l01_app.bin && rm -f dual_open_dupdual_no_append: bytes=8 payload=BBBBBBBBdual_o_append: bytes=16 payload=AABBAABBAABBAABBdup_cursor: shared_f_pos=8 dup2_self=noop dup3_self_einval=yes cloexec=0/1redir_restored: captured=KSA-DUP|STDOUT_CAPTUREDlearner@ksa:~/gl-c01/m04-l01$ GL-C01 · 4.1 (m04-l01)
>_ Kernel Systems Academy
# Tracing f_count Lifetimes Across Redirection Boundaries
- Notice how
dup2(fd, STDOUT_FILENO)atomically closed descriptor1's terminal reference and bound slot `…
GL-C01 · 4.1 (m04-l01)
>_ Kernel Systems Academy
# Guided Practice: Writing a Self-Safe move_fd_cloexec() Helper
- Write a helper
int move_fd_cloexec(int src_fd, int dst_fd)that movessrc_fdontodst_fdwith `FD_CLO…
GL-C01 · 4.1 (m04-l01)
>_ Kernel Systems Academy
# Guided Practice: Writing a Self-Safe move_fd_cloexec() Helper
- 1.
GL-C01 · 4.1 (m04-l01)
>_ Kernel Systems Academy
# Independent Practice: Combined stdout + stderr (2>&1) Capture Harness
- Write a C11 test harness
capture_both.c(-std=c11 -Wall -Wextra -Werror) that mimics shell `> combined.…
GL-C01 · 4.1 (m04-l01)
>_ Kernel Systems Academy
# Warning
warning: Symptom: Redirected printf() text prints onto the terminal after calling dup2(saved_out, STDOUT_FILENO) instead of landing inside the target file! Root Cause: When redirected to a regular file, stdout buffers output inside glibc RAM (_IOFBF); restoring descriptor 1 before calling fflush(stdout) flushes those buffered bytes onto the restored terminal descriptor. Fix: Call fflush(stdout) both before redirecting STDOUT_FILENO and immediately before restoring saved_out.
GL-C01 · 4.1 (m04-l01)
>_ Kernel Systems Academy
# Warning
warning: Symptom: dup3(fd, target_fd, O_CLOEXEC) fails sporadically in daemon startup tests with errno == EINVAL. Root Cause: Whenever target_fd was previously closed, open() may allocate fd == target_fd, and Linux dup3() explicitly rejects oldfd == newfd with EINVAL. Fix: Guard if (fd != target_fd) around dup3() + close(fd), and set FD_CLOEXEC via fcntl(fd, F_SETFD, FD_CLOEXEC) on the fd == target_fd branch.
GL-C01 · 4.1 (m04-l01)
>_ Kernel Systems Academy
# Quick check
? A single process calls fd1 = open("audit.bin", O_RDWR) on an existing 64-byte file, then calls fd2 = open("audit.bin", O_RDWR) without O_APPEND. After write(fd1, "ABCD", 4), what does lseek(fd2, 0, SEEK_CUR) return?
Select an option or press R to reveal.
Correct: A
Every open() allocates a fresh struct file open file description with f_pos = 0, even when pointing to the same struct inode.
Common misconception: Confusing shared page-cache data (struct inode) with shared cursors (struct file) produces silent dual-open overwrite bugs.
GL-C01 · 4.1 (m04-l01)
>_ Kernel Systems Academy
# Quick check
? You duplicate fd1 onto fd2 via dup3(fd1, fd2, O_CLOEXEC) where fd1 was opened without O_CLOEXEC. Which properties are shared between fd1 and fd2, and which remain separate?
Select an option or press R to reveal.
Correct: B
FD_CLOEXEC lives in the per-process files_struct bitmap, whereas f_pos and status flags reside in the shared struct file.
Common misconception: Assuming dup3(..., O_CLOEXEC) also marks fd1 close-on-exec leaves fd1 leaking across execve() if fd1 is not closed.
GL-C01 · 4.1 (m04-l01)
>_ Kernel Systems Academy
# Quick check
? (Review from earlier lesson) Suppose fd1 = dup(fd0) aliases a regular file at offset 0, and write(fd0, buf, 16) returns a short count of 10 bytes before a signal interrupts transfer. How must a retry write on fd1 proceed?
Select an option or press R to reveal.
Correct: B
Combining short-count retry loops (m02-l02) with dup() aliasing shows fd0's 10-byte write already moved the shared f_pos to 10.
Common misconception: Retrying from buf + 0 on an aliased descriptor writes duplicate prefix bytes into the file.
GL-C01 · 4.1 (m04-l01)
>_ Kernel Systems Academy
# Quick check
? What is the exact runtime difference between dup2(5, 5) and dup3(5, 5, O_CLOEXEC) when descriptor 5 is a valid open file?
Select an option or press R to reveal.
Correct: B
POSIX specifies dup2(fd, fd) as a no-op, whereas Linux dup3() rejects oldfd == newfd with EINVAL so callers never falsely assume FD_CLOEXEC was updated on a self-dup.
Common misconception: Replacing dup2() with dup3() blindly without a fd != target check introduces latent EINVAL crashes when fd equals target.
GL-C01 · 4.1 (m04-l01)
>_ Kernel Systems Academy
# Summary
- Two
open()calls on the same path create two independentstruct fileentries with separatef_poscursors over one sharedstruct inodeand page cache. dup(),dup2(), anddup3()bind multiple descriptor integers to onestruct file, sharingf_posandf_flagswhile keepingFD_CLOEXECprivate to each descriptor slot.dup2(fd, fd)is a safe no-op returningfd, whereasdup3(fd, fd, O_CLOEXEC)returns-1witherrno == EINVAL.- Redirecting
STDOUT_FILENOsafely requires saving slot1viadup(), flushingstdoutbefore and after redirection, restoring viadup2(), and closing the saved duplicate.
GL-C01 · 4.1 (m04-l01)
>_ Kernel Systems Academy
# Summary
- Next, we eliminate multi-process creation races (
TOCTOU) and multithreaded shared-cursor races using `O_C…
GL-C01 · 4.1 (m04-l01)
>_ Kernel Systems Academy
# Key takeaways
dup2(fd, fd)is a safe no-op returningfd, whereasdup3(fd, fd, O_CLOEXEC)returns-1witherrno == EINVAL.- Redirecting
STDOUT_FILENOsafely requires saving slot1viadup(), flushingstdoutbefore and after redirection, restoring viadup2(), and closing the saved duplicate. - Next, we eliminate multi-process creation races (
TOCTOU) and multithreaded shared-cursor races usingO_CREAT | O_EXCL, directory-pinnedopenat(), and statelesspread()/pwrite().
GL-C01 · 4.2 (m04-l02)
>_ Kernel Systems Academy
# Atomic Kernel I/O: O_EXCL & pread
What you'll learn
- Diagnose preemption
TOCTOUraces (access+open) and cursor-clobber races (lseek+write) across workers. - Enforce atomic exclusive creation with
O_CREAT | O_EXCLand directory-pinnedopenat(dirfd, ...)VFS lookups. - Execute stateless positional transfers via
pread()andpwrite()while verifyingstruct file.f_posstays unchanged.
GL-C01 · 4.2 (m04-l02)
>_ Kernel Systems Academy
# Why Two-Syscall Sequences Fail Under Preemption
- On a preemptive Symmetric Multiprocessing (
SMP) Linux kernel, a hardware timer interrupt or higher-priori…
GL-C01 · 4.2 (m04-l02)
>_ Kernel Systems Academy
# Why Two-Syscall Sequences Fail Under Preemption
- User-space mutexes cannot coordinate independent processes, and two-syscall sequences cannot close kernel p…
GL-C01 · 4.2 (m04-l02)
>_ Kernel Systems Academy
# Mental model
note: Calling lseek() and then write() on a shared descriptor is like shouting a shelf coordinate across a busy warehouse and hoping nobody shouts another coordinate before your crate lands; pwrite() stamps the exact bay coordinate directly onto the crate.
Where it stops working: Physical warehouse bays block two crates mechanically, whereas concurrent pwrite calls targeting overlapping byte offsets still race unless callers partition fixed-size slots or synchronize access.
GL-C01 · 4.2 (m04-l02)
>_ Kernel Systems Academy
# TOCTOU, Positional I/O (pread/pwrite) & Directory-Pinned *at() Calls
definition: Time-Of-Check to Time-Of-Use (TOCTOU) & O_CREAT | O_EXCL: Named in 1970s operating-system security audits for races between verifying a pathname precondition and acting on it, open(..., O_CREAT | O_EXCL, mode) tests dentry absence and allocates the inode atomically under the parent directory's i_rwsem lock (never following a terminal symlink). Positional I/O (pread / pwrite): Transfers bytes at an explicit off_t offset via stack-local kiocb.ki_pos without reading or modifying struct file.f_pos. Directory-Pinned *at() Calls (openat, renameat, unlinkat): Anchor relative lookups to a verified O_DIRECTORY dirfd so intermediate directory prefixes cannot be swapped mid-flight.
GL-C01 · 4.2 (m04-l02)
>_ Kernel Systems Academy
# Why Two-Syscall Sequences Fail Under Preemption
Figure 4.2a: Scheduler preemption between lseek() and write() clobbers shared cursors; stateless pread()/pwrite() and directory-pinned *at() calls close race windows.
GL-C01 · 4.2 (m04-l02)
>_ Kernel Systems Academy
# Why Two-Syscall Sequences Fail Under Preemption
Figure 4.2b: Time-of-check-to-time-of-use file-creation race between two processes versus atomic O_CREAT | O_EXCL.
GL-C01 · 4.2 (m04-l02)
>_ Kernel Systems Academy
# One Layer Down: kiocb.ki_pos vs f_pos_lock & Retry Offset Math
- Look inside
fs/read_write.c(ksys_pread64vsksys_read) to see whypread()scales linearly across…
GL-C01 · 4.2 (m04-l02)
>_ Kernel Systems Academy
# One Layer Down: kiocb.ki_pos vs f_pos_lock & Retry Offset Math
Pin an O_DIRECTORY descriptor dfd and create staging files via openat(..., O_CREAT | O_EXCL | O_NOFOLLOW | O_CLOEXEC, 0600).
Fuse check-and-act inside single atomic kernel syscalls: openat(O_CREAT|O_EXCL), stateless pread/pwrite, and renameat + fsync(dfd).
GL-C01 · 4.2 (m04-l02)
>_ Kernel Systems Academy
# pread(2) / pwrite(2) Reference & the Linux O_APPEND Quirk
- Define
#define _POSIX_C_SOURCE 200809Land#define _FILE_OFFSET_BITS 64before<unistd.h>and `<fcntl…
GL-C01 · 4.2 (m04-l02)
>_ Kernel Systems Academy
# pread
pread(2) GL-C01 Quick Reference pread(2) NAME pread, pwrite - read from or write to a descriptor at a given offset SYNOPSIS #define _POSIX_C_SOURCE 200809L #include <unistd.h> ssize_t pread(int fd, void *buf, size_t count, off_t offset); ssize_t pwrite(int fd, const void *buf, size_t count, off_t offset); STANDARDS POSIX.1-2008; maps to pread64 / pwrite64 syscalls on Linux. RETURN VALUE Returns bytes transferred (>= 0; 0 on pread means EOF), or -1 on error. The file offset (struct file.f_pos) is NOT changed. ERRORS EBADF fd is not valid or not open for the requested direction. Kernel Systems Academy m04-l02 pread(2) GL-C01 quick reference · full manual page: man 2 pread GL-C01 · 4.2 (m04-l02)
>_ Kernel Systems Academy
# Reproducing Cursor Races vs Stateless pread/pwrite & atomic_replace_at
- Save
atomic_idioms.cbelow.
GL-C01 · 4.2 (m04-l02)
>_ Kernel Systems Academy
# atomic_idioms.c
learner@ksa:~/gl-c01/m04-l02$ bat atomic_idioms.c───────┬──────────────────────────────────────────────────────────────────────────────── │ File: atomic_idioms.c───────┼──────────────────────────────────────────────────────────────────────────────── 1 │ #define _FILE_OFFSET_BITS 64 2 │ #define _POSIX_C_SOURCE 200809L 3 │ #include <errno.h> 4 │ #include <fcntl.h> 5 │ #include <stdint.h> 6 │ #include <stdio.h> 7 │ #include <stdlib.h> 8 │ #include <string.h> 9 │ #include <unistd.h> 10 │ 11 │ static int pwrite_full(int fd, const void *buf, size_t len, off_t off) { 12 │ const uint8_t *p = (const uint8_t *)buf; 13 │ size_t done = 0U; 14 │ while (done < len) {───────┴────────────────────────────────────────────────────────────────────────────────GL-C01 · 4.2 (m04-l02)
>_ Kernel Systems Academy
# Verifying Stateless pread64/pwrite64 Under strace
- Compile and run
atomic_idioms, verifyracy_lseekvsatomic_pio(parked_f_pos=4) andreplace_at=1,…
GL-C01 · 4.2 (m04-l02)
>_ Kernel Systems Academy
# Verifying Stateless pread64/pwrite64 Under strace
learner@ksa:~/gl-c01/m04-l02$ gcc -fdiagnostics-color=always -std=c11 -Wall -Wextra -Werror atomic_idioms.c -o atomic_idiomslearner@ksa:~/gl-c01/m04-l02$ ./atomic_idiomslearner@ksa:~/gl-c01/m04-l02$ test ! -e /tmp/ksa_m04_l02.lock && test ! -e /tmp/ksa_m04_l02_slots.binexcl_create: second_ret=-1 eexist=yesracy_lseek: slot0=00000000 unexpected_size=24atomic_pio: s0=SLOT0_OK s1=SLOT1_OK parked_f_pos=4atomic_append: bytes=9 log=REC1|REC2 replace_at=1learner@ksa:~/gl-c01/m04-l02$ GL-C01 · 4.2 (m04-l02)
>_ Kernel Systems Academy
# Verifying Stateless pread64/pwrite64 Under strace
- Under
strace, observeO_CREAT|O_EXCLreturning-1 EEXISTon the second lock attempt andpwrite64/`p…
GL-C01 · 4.2 (m04-l02)
>_ Kernel Systems Academy
# Verifying Stateless pread64/pwrite64 Under strace
learner@ksa:~/gl-c01/m04-l02$ strace -e trace=openat,pwrite64,pread64,unlink,unlinkat,close ./atomic_idiomsGL-C01 · 4.2 (m04-l02)
>_ Kernel Systems Academy
# How Kernel i_rwsem and Stateless kiocb Close Race Windows
- Every race in
atomic_idiomsdisappeared as soon as check-and-use moved inside one kernel boundary: `O_CRE…
GL-C01 · 4.2 (m04-l02)
>_ Kernel Systems Academy
# Guided Practice: Writing pread_full() with Short-Count & EOF Handling
- Complete the companion helper
ssize_t pread_full(int fd, void *buf, size_t len, off_t off)matching `pwri…
GL-C01 · 4.2 (m04-l02)
>_ Kernel Systems Academy
# Guided Practice: Writing pread_full() with Short-Count & EOF Handling
- 1.
GL-C01 · 4.2 (m04-l02)
>_ Kernel Systems Academy
# Independent Practice: renameat2(..., RENAME_NOREPLACE) Lockless Publisher
- On Linux 3.15+ (
#define _GNU_SOURCE),renameat2(dfd, tmp_name, dfd, target_name, RENAME_NOREPLACE)atom…
GL-C01 · 4.2 (m04-l02)
>_ Kernel Systems Academy
# Warning
warning: Symptom: Calling pwrite(fd, &super_hdr, 64, 0) on Linux to overwrite a file header at offset 0 silently appends super_hdr to the end of the file instead! Root Cause: On Linux (deviating from strict POSIX), if fd was opened with O_APPEND, pwrite() ignores its offset parameter and forces every write to i_size. Fix: Open descriptors used for positional pwrite() updates without O_APPEND (or maintain a separate non-append header descriptor).
GL-C01 · 4.2 (m04-l02)
>_ Kernel Systems Academy
# Warning
warning: Symptom: Guarding daemon lockfile creation with if (access(lock_path, F_OK) != 0) open(lock_path, O_WRONLY | O_CREAT, 0600); allows two daemon instances to start concurrently or follow an attacker-planted symlink. Root Cause: Scheduler preemption between access() and open() creates a TOCTOU race window, and open() without O_EXCL follows symlinks. Fix: Remove access() and execute a single openat(dfd, name, O_WRONLY | O_CREAT | O_EXCL | O_NOFOLLOW | O_CLOEXEC, 0600).
GL-C01 · 4.2 (m04-l02)
>_ Kernel Systems Academy
# Quick check
? Eight worker threads share one int fd opened with O_RDWR | O_CLOEXEC on an indexed record store (f_pos is currently 128). Thread 3 calls pread(fd, buf, 64, 4096) and reads 64 bytes. What is f_pos afterward?
Select an option or press R to reveal.
Correct: B
Positional pread() and pwrite() leave struct file.f_pos completely untouched and avoid f_pos_lock contention across threads.
Common misconception: Expecting pread() to advance f_pos causes subtle offset bugs when mixing positional and sequential reads.
GL-C01 · 4.2 (m04-l02)
>_ Kernel Systems Academy
# Quick check
? Two independent collector processes open /var/log/events.bin without O_APPEND and execute lseek(fd, 0, SEEK_END) followed by write(fd, rec, 32). Why do committed records randomly vanish under load?
Select an option or press R to reveal.
Correct: A
Because lseek() and write() are separate syscalls over independent struct file cursors, both processes compute the same old i_size before either writes.
Common misconception: Assuming lseek(fd, 0, SEEK_END) reserves the tail offset until the next write() causes silent multi-process data loss; use O_APPEND.
GL-C01 · 4.2 (m04-l02)
>_ Kernel Systems Academy
# Quick check
? (Review from earlier lesson) When pwrite(fd, buf, 4096, slot_off) returns a short count of 1024 bytes, how must a production C11 retry loop issue the next call?
Select an option or press R to reveal.
Correct: B
Because pwrite() never updates f_pos, retrying a partial positional write requires advancing both p + done and off + done.
Common misconception: Leaving slot_off unchanged in a pwrite() retry loop overwrites the start of the slot with the tail of the buffer.
GL-C01 · 4.2 (m04-l02)
>_ Kernel Systems Academy
# Quick check
? Why do security-hardened daemons replace path-string open("/tmp/work/cfg.tmp", ...) + rename() with an O_RDONLY | O_DIRECTORY | O_CLOEXEC directory descriptor (openat with O_CREAT | O_EXCL | O_NOFOLLOW | O_CLOEXEC, fdatasync(tfd), renameat(), and fsync(dfd))?
Select an option or press R to reveal.
Correct: B
Pinning operations to an open O_DIRECTORY dfd prevents path-prefix substitution, while fdatasync(tfd) before renameat() and fsync(dfd) afterward harden both payload and directory link.
Common misconception: Calling rename() without syncing the staged file first and the parent directory afterward can leave zero-byte or missing config files after a power cut.
GL-C01 · 4.2 (m04-l02)
>_ Kernel Systems Academy
# Summary
- Any file invariant split across two user-space syscalls (
access+open, orlseek+write) is vulnerable to kernel scheduler preemption races. open(..., O_CREAT | O_EXCL, mode)fuses existence testing and inode creation into one atomic VFS directory operation failing withEEXISTon collision.pread()andpwrite()transfer bytes at an explicitoff_tcoordinate without reading or mutatingstruct file.f_pos(providedO_APPENDis clear on Linux).- Opening log descriptors with
O_APPENDserializes offset placement (ki_pos = i_size) and payload copy underinode->i_rwsem.
GL-C01 · 4.2 (m04-l02)
>_ Kernel Systems Academy
# Summary
- Next, we complete Module 4 by controlling live descriptors at runtime using
fcntl()flag tiers, ABI-stabl…
GL-C01 · 4.2 (m04-l02)
>_ Kernel Systems Academy
# Key takeaways
- Opening log descriptors with
O_APPENDserializes offset placement (ki_pos = i_size) and payload copy underinode->i_rwsem. - Directory-pinned
openat()(O_CREAT | O_EXCL | O_NOFOLLOW | O_CLOEXEC) paired withfdatasync(tfd),renameat(), andfsync(dfd)closes path-prefixTOCTOUraces and delivers crash-safe atomic replacement. - Next, we complete Module 4 by controlling live descriptors at runtime using
fcntl()flag tiers, ABI-stableioctl()structures, andftruncate()file resizing.
GL-C01 · 4.3 (m04-l03)
>_ Kernel Systems Academy
# Descriptor Control: fcntl & ioctl
What you'll learn
- Modify descriptor (
FD_CLOEXEC) and mutablestruct fileflags (O_APPEND,O_NONBLOCK) viafcntl()andO_ACCMODE. - Validate ABI-stable
ioctl()structs (_Static_assert, zeroed padding) alongsideFIONREADandTIOCGWINSZENOTTY. - Resize regular files with
ftruncate()andtruncate()while accounting for unchangedf_posand zero-filled extensions.
GL-C01 · 4.3 (m04-l03)
>_ Kernel Systems Academy
# Why Blind F_SETFL Wipes Flags & Sloppy ioctl Structs Fail With ENOTTY
- Three runtime descriptor bugs ambush systems engineers regularly.
GL-C01 · 4.3 (m04-l03)
>_ Kernel Systems Academy
# Why Blind F_SETFL Wipes Flags & Sloppy ioctl Structs Fail With ENOTTY
- Controlling already-open descriptors cleanly requires respecting the VFS boundary between **Tier A per-slot…
GL-C01 · 4.3 (m04-l03)
>_ Kernel Systems Academy
# Mental model
note: Using fcntl() and ioctl() on an open descriptor is like flipping circuit breakers on a live industrial valve panel without shutting down or unbolting the pipeline, while ftruncate() trims or extends the storage tank directly.
Where it stops working: Moving a tank wall physically pushes a floating gauge back inside bounds, whereas shrinking a file with ftruncate leaves f_pos stranded past the new end-of-file.
GL-C01 · 4.3 (m04-l03)
>_ Kernel Systems Academy
# fcntl() Flag Tiers, Out-of-Band ioctl() & ftruncate()
definition: File Control (fcntl): Standardized in POSIX <fcntl.h> as the runtime VFS multiplexer separating slot-local descriptor attributes (F_DUPFD_CLOEXEC, F_GETFD/F_SETFD for FD_CLOEXEC) from shared struct file.f_flags (F_GETFL/F_SETFL). Input/Output Control (ioctl) & ENOTTY: Named from Seventh Edition Unix teletype ("TTY") out-of-band control—which is why applying a terminal request like TIOCGWINSZ to a regular file or pipe still returns historical ENOTTY ("Not a typewriter")! ftruncate(fd, length): Resizes inode->i_size on a writable regular file without modifying struct file.f_pos.
GL-C01 · 4.3 (m04-l03)
>_ Kernel Systems Academy
# One Layer Down: 32-Bit _IOC Command Bitfields & F_SETFL Mask Rules
- Inside
<uapi/asm-generic/ioctl.h>, Linux packs four fields into every 32-bit_IO,_IOR,_IOW, and `…
GL-C01 · 4.3 (m04-l03)
>_ Kernel Systems Academy
# One Layer Down: 32-Bit _IOC Command Bitfields & F_SETFL Mask Rules
Figure 4.3: 32-bit _IOC command bitfield encoding, fcntl() Tier A vs Tier B flag control, and ftruncate() cursor invariants.
GL-C01 · 4.3 (m04-l03)
>_ Kernel Systems Academy
# One Layer Down: 32-Bit _IOC Command Bitfields & F_SETFL Mask Rules
Clone or update per-slot FD_CLOEXEC via F_DUPFD_CLOEXEC and F_GETFD / F_SETFD without disturbing aliases.
Separate per-slot FD_CLOEXEC from read-modify-write F_SETFL status flags, lock ioctl struct sizes with _Static_assert, and reposition f_pos after ftruncate().
GL-C01 · 4.3 (m04-l03)
>_ Kernel Systems Academy
# fcntl(2) Quick Reference & Read-Modify-Write Discipline
- Define
#define _GNU_SOURCEand#define _FILE_OFFSET_BITS 64before<fcntl.h>,<unistd.h>, and `<sys…
GL-C01 · 4.3 (m04-l03)
>_ Kernel Systems Academy
# fcntl
fcntl(2) GL-C01 Quick Reference fcntl(2) NAME fcntl, ftruncate - manipulate file descriptor flags and inode size SYNOPSIS #include <fcntl.h> #include <unistd.h> int fcntl(int fd, int cmd, ... /* arg */); int ftruncate(int fd, off_t length); STANDARDS POSIX.1-2008; F_DUPFD_CLOEXEC requires POSIX.1-2008 (_POSIX_C_SOURCE >= 200809L). RETURN VALUE F_DUPFD* returns new fd; F_GETFD / F_GETFL return flags (>= 0); F_SETFD, F_SETFL, and ftruncate() return 0 on success, or -1 on error. ERRORS EBADF fd is not an open descriptor (or not open for writing on ftruncate). Kernel Systems Academy m04-l03 fcntl(2) GL-C01 quick reference · full manual page: man 2 fcntl GL-C01 · 4.3 (m04-l03)
>_ Kernel Systems Academy
# Probing fcntl Tiers, ABI-Verified ioctl & ftruncate Cursor Invariants
- Save
desc_ctl.cbelow.
GL-C01 · 4.3 (m04-l03)
>_ Kernel Systems Academy
# desc_ctl.c
learner@ksa:~/gl-c01/m04-l03$ bat desc_ctl.c───────┬──────────────────────────────────────────────────────────────────────────────── │ File: desc_ctl.c───────┼──────────────────────────────────────────────────────────────────────────────── 1 │ #define _GNU_SOURCE 2 │ #define _FILE_OFFSET_BITS 64 3 │ #include <errno.h> 4 │ #include <fcntl.h> 5 │ #include <stdint.h> 6 │ #include <stdio.h> 7 │ #include <stdlib.h> 8 │ #include <string.h> 9 │ #include <sys/ioctl.h> 10 │ #include <sys/stat.h> 11 │ #include <unistd.h> 12 │ 13 │ struct ksa_dev_cfg { 14 │ uint32_t rate_hz;───────┴────────────────────────────────────────────────────────────────────────────────GL-C01 · 4.3 (m04-l03)
>_ Kernel Systems Academy
# Verifying Flag Bitmasks, FIONREAD, ftruncate & Lab 4
- Compile
desc_ctl.c, pipe a 19-byte payload (TELEMETRY_PING_2026) intoSTDIN_FILENO, verify every outp…
GL-C01 · 4.3 (m04-l03)
>_ Kernel Systems Academy
# Verifying Flag Bitmasks, FIONREAD, ftruncate & Lab 4
learner@ksa:~/gl-c01/m04-l03$ gcc -fdiagnostics-color=always -std=c11 -Wall -Wextra -Werror desc_ctl.c -o desc_ctllearner@ksa:~/gl-c01/m04-l03$ printf 'TELEMETRY_PING_2026' | ./desc_ctllearner@ksa:~/gl-c01/m04-l03$ test ! -e /tmp/ksa_m04_l03.dat && rm -f desc_ctlfcntl_state: hi_ge40=yes cloexec=0->1 acc=O_RDWR append=1ioctl_probe: pipe_fionread=19 winsize_enotty=yes ioc_sz=16resize_check: shrunk=16 f_pos=32->32 ext=64 zero=0learner@ksa:~/gl-c01/m04-l03$ GL-C01 · 4.3 (m04-l03)
>_ Kernel Systems Academy
# Lab: lab_m04_atomic_kv
- 1.
Verify: ./check.sh exits 0.
GL-C01 · 4.3 (m04-l03)
>_ Kernel Systems Academy
# Kernel Mechanics Across fcntl, ioctl & Inode Resizing
- In
desc_ctl,F_DUPFD_CLOEXECscannedfiles_structstarting at slot40and setFD_CLOEXECatomical…
GL-C01 · 4.3 (m04-l03)
>_ Kernel Systems Academy
# Guided Practice: Safe Read-Modify-Write set_nonblocking() Helper
- Write a reusable helper
int set_nonblocking(int fd, int enable)that sets or clearsO_NONBLOCKwithout…
GL-C01 · 4.3 (m04-l03)
>_ Kernel Systems Academy
# Guided Practice: Safe Read-Modify-Write set_nonblocking() Helper
- 1.
GL-C01 · 4.3 (m04-l03)
>_ Kernel Systems Academy
# Independent Practice: _IOC Bitfield Decoder & Struct ABI Auditor
- Write a C11 utility
ioctl_decode.c(-std=c11 -Wall -Wextra -Werror) that takes three real Linuxioctl…
GL-C01 · 4.3 (m04-l03)
>_ Kernel Systems Academy
# Warning
warning: Symptom: Calling fcntl(fd, F_SETFL, O_NONBLOCK) on an active shared log file silently disables O_APPEND, causing log lines to overwrite offset 0! Root Cause: F_SETFL overwrites all mutable status bits in struct file.f_flags rather than setting a single bit. Fix: Always execute read-modify-write: int fl = fcntl(fd, F_GETFL); if (fl != -1) fcntl(fd, F_SETFL, fl | O_NONBLOCK);.
GL-C01 · 4.3 (m04-l03)
>_ Kernel Systems Academy
# Warning
warning: Symptom: Resetting a 4,096-byte state file via ftruncate(fd, 0) and immediately calling write(fd, hdr, 32) (without O_APPEND) produces a 4,128-byte file starting with 4,096 zero bytes! Root Cause: ftruncate() updates inode->i_size to 0 while leaving struct file.f_pos stranded at 4096, turning the next sequential write() into a sparse-hole extension. Fix: Call lseek(fd, 0, SEEK_SET) right after ftruncate(), or write via pwrite(fd, hdr, 32, 0).
GL-C01 · 4.3 (m04-l03)
>_ Kernel Systems Academy
# Quick check
? Given int fl = fcntl(fd, F_GETFL); (fl != -1), which expression correctly tests whether fd was opened read-only (O_RDONLY)?
Select an option or press R to reveal.
Correct: B
Because O_RDONLY equals 0 on Linux, (fl & O_RDONLY) always evaluates to 0; masking the 2-bit access field with O_ACCMODE is mandatory.
Common misconception: Treating O_RDONLY as a nonzero single-bit flag causes read-only checks to fail on every file descriptor.
GL-C01 · 4.3 (m04-l03)
>_ Kernel Systems Academy
# Quick check
? Which set of flags can be modified at runtime on an already-open Linux file descriptor via fcntl(fd, F_SETFL, new_flags)?
Select an option or press R to reveal.
Correct: C
Access modes (O_ACCMODE) and open-time creation flags are ignored by F_SETFL, whereas FD_CLOEXEC belongs to F_SETFD.
Common misconception: Attempting to upgrade an O_RDONLY handle to O_RDWR via F_SETFL silently leaves the descriptor read-only.
GL-C01 · 4.3 (m04-l03)
>_ Kernel Systems Academy
# Quick check
? (Review from earlier lesson) You duplicate fd1 to fd2 = fcntl(fd1, F_DUPFD_CLOEXEC, 10) and then call fcntl(fd1, F_SETFL, fl | O_NONBLOCK). What is the resulting state of fd2?
Select an option or press R to reveal.
Correct: B
Like dup3(), F_DUPFD_CLOEXEC aliases one shared struct file (f_flags including O_NONBLOCK) while keeping per-slot FD_CLOEXEC isolated.
Common misconception: Setting O_NONBLOCK on an aliased stdout or pipe descriptor surprises sibling processes that share that struct file.
GL-C01 · 4.3 (m04-l03)
>_ Kernel Systems Academy
# Quick check
? Why does placing unsigned long or unnamed compiler padding inside a custom _IOWR('k', 0x11, struct cfg) ioctl payload break 32-bit ARMv7 user binaries on a 64-bit kernel (ENOTTY) and risk data leaks?
Select an option or press R to reveal.
Correct: B
Fixed-width <stdint.h> types, explicit zeroed reserved fields, memset(), and _Static_assert keep _IOC_SIZE(cmd) invariant across 32-bit and 64-bit builds.
Common misconception: Assuming ioctl numbers are independent of sizeof(struct) causes puzzling ENOTTY errors across 32/64-bit user/kernel boundaries.
GL-C01 · 4.3 (m04-l03)
>_ Kernel Systems Academy
# Summary
fcntl()separates per-descriptor slot control (F_DUPFD_CLOEXEC,F_GETFD/F_SETFDforFD_CLOEXEC) from sharedstruct filestatus flags (F_GETFL/F_SETFL).F_SETFLtogglesO_APPEND,O_NONBLOCK,O_ASYNC,O_DIRECT, andO_NOATIMEvia read-modify-write, while(flags & O_ACCMODE)remains immutable afteropen().ioctl()dispatches out-of-band driver and subsystem queries (FIONREAD,TIOCGWINSZ) and fails withENOTTYon unsupported file types.- Custom
_IOR/_IOW/_IOWRUAPI structs encodesizeof(struct)into_IOC_SIZE(cmd), requiring<stdint.h>fixed-width fields, explicit reserved padding,memset(), and_Static_assert.
GL-C01 · 4.3 (m04-l03)
>_ Kernel Systems Academy
# Summary
- Having mastered raw kernel descriptors across Modules 1–4, Module 5 steps back into
Ring 3to dissect how…
GL-C01 · 4.3 (m04-l03)
>_ Kernel Systems Academy
# Key takeaways
- Custom
_IOR/_IOW/_IOWRUAPI structs encodesizeof(struct)into_IOC_SIZE(cmd), requiring<stdint.h>fixed-width fields, explicit reserved padding,memset(), and_Static_assert. ftruncate()(requiring a writablefd) andtruncate()resizeinode->i_sizewithout modifyingstruct file.f_pos.- Having mastered raw kernel descriptors across Modules 1–4, Module 5 steps back into
Ring 3to dissect howglibc<stdio.h>FILEstreams amortize syscall traps, handle binaryfread/fwritetails, and parse text safely.
m05/
>_ Kernel Systems Academy
# Standard C Library (stdio) Streams & Formatted I/O
Map glibc FILE streams and fopen mode strings to kernel openat flags, serialize fixed binary records safely with fread/fwrite/fseeko and feof/ferror triage, and construct truncation-safe snprintf and fgets/strtol codecs.
- 5.1 Standard I/O Streams & fopen Modes
- 5.2 Binary Stream I/O, fseeko & EOF
- 5.3 Bounded snprintf & Safe Text Parsing
lab → Lab 5: Bounded stdio Sensor Log Parser & Binary Codec
GL-C01 · 5.1 (m05-l01)
>_ Kernel Systems Academy
# Standard I/O Streams & fopen Modes
What you'll learn
- Analyze how
glibcFILEcontrol blocks amortize Ring 3-to-Ring 0 syscall traps above raw integer file descriptors. - Translate every C11 and
glibcfopen()mode string (b,e,x) to its exactopenat()kernel flag bitmask. - Verify
stdin/stdout/stderrdescriptor bindings,open_memstream()buffers, and checkedfclose()error handling.
GL-C01 · 5.1 (m05-l01)
>_ Kernel Systems Academy
# Why Raw Syscalls Stall Tiny Writes & Plain "w+" Opens Races
- Suppose a high-rate telemetry collector formats
4,096four-byte voltage samples per batch and emits each…
GL-C01 · 5.1 (m05-l01)
>_ Kernel Systems Academy
# Why Raw Syscalls Stall Tiny Writes & Plain "w+" Opens Races
- High-throughput, leak-free stream I/O requires understanding how
glibc's user-spaceFILEcontrol block…
GL-C01 · 5.1 (m05-l01)
>_ Kernel Systems Academy
# Mental model
note: Using raw syscalls for tiny writes is like carrying individual parcels across a guarded border checkpoint one by one, whereas a stdio FILE stream packs parcels into a user-space crate and crosses the border only when the crate fills.
Where it stops working: A physical crate sitting in your warehouse survives a building power cut, whereas bytes held inside a user-space FILE buffer vanish if the process crashes or calls _exit() before flushing.
GL-C01 · 5.1 (m05-l01)
>_ Kernel Systems Academy
# Standard I/O Stream (FILE), Mode Extensions & Memory Streams
definition: Standard I/O Stream (FILE): Introduced by Mike Lesk and Dennis Ritchie in the Portable I/O Library (<stdio.h>), FILE (struct _IO_FILE in glibc) is an opaque Ring 3 control block wrapping an underlying _fileno descriptor with user-space _IO_read_ptr/_IO_write_ptr heap buffers, an internal mutex lock, and sticky EOF/error bits. glibc Mode Extensions ("e", "x"): Append O_CLOEXEC ("e") and O_EXCL ("x") to the initial openat() syscall. Memory Streams (open_memstream, fmemopen): Standardized in POSIX.1-2008 to bind FILE * virtual-function tables directly onto heap or caller RAM (fileno() == -1, EBADF).
GL-C01 · 5.1 (m05-l01)
>_ Kernel Systems Academy
# One Layer Down: _IO_FILE Cursor Pointers & Syscall Amortization Math
- Inside
glibc(libio/bits/types/struct_FILE.h), writingsbytes viafwrite()orfputs()checks whe…
GL-C01 · 5.1 (m05-l01)
>_ Kernel Systems Academy
# One Layer Down: _IO_FILE Cursor Pointers & Syscall Amortization Math
Figure 5.1: User-space glibc struct _IO_FILE state, open_memstream() vtables, and exact fopen() mode-to-openat() flag translations.
GL-C01 · 5.1 (m05-l01)
>_ Kernel Systems Academy
# One Layer Down: _IO_FILE Cursor Pointers & Syscall Amortization Math
Open streams with glibc 'e' (O_CLOEXEC) and 'x' (O_EXCL) suffixes inside a single atomic openat() syscall.
Append glibc 'e' and 'x' safety suffixes on fopen(), batch tiny records in Ring 3 heap RAM, and always check fclose(fp) == 0.
GL-C01 · 5.1 (m05-l01)
>_ Kernel Systems Academy
# Stream Headers, Checked fclose() & open_memstream()
- Define
#define _POSIX_C_SOURCE 200809Lbefore<stdio.h>,<fcntl.h>,<time.h>, and<unistd.h>so `…
GL-C01 · 5.1 (m05-l01)
>_ Kernel Systems Academy
# Probing fopen Kernel Flags, open_memstream & Amortization Speedup
- Save
fopen_modes_probe.cbelow.
GL-C01 · 5.1 (m05-l01)
>_ Kernel Systems Academy
# fopen_modes_probe.c
learner@ksa:~/gl-c01/m05-l01$ bat fopen_modes_probe.c───────┬──────────────────────────────────────────────────────────────────────────────── │ File: fopen_modes_probe.c───────┼──────────────────────────────────────────────────────────────────────────────── 1 │ #define _POSIX_C_SOURCE 200809L 2 │ #include <errno.h> 3 │ #include <fcntl.h> 4 │ #include <stdint.h> 5 │ #include <stdio.h> 6 │ #include <stdlib.h> 7 │ #include <string.h> 8 │ #include <sys/stat.h> 9 │ #include <time.h> 10 │ #include <unistd.h> 11 │ 12 │ static uint64_t diff_ns(struct timespec a, struct timespec b) { 13 │ return (uint64_t)(b.tv_sec - a.tv_sec) * 1000000000ULL + 14 │ (uint64_t)(b.tv_nsec - a.tv_nsec);───────┴────────────────────────────────────────────────────────────────────────────────GL-C01 · 5.1 (m05-l01)
>_ Kernel Systems Academy
# Verifying Stream Flags, Memory Streams & Amortization Speedup
- Compile and execute
fopen_modes_probe: confirmstd_streams(0, 1, 2),"w+xe"(O_RDWR, `FD_CLOEXEC…
GL-C01 · 5.1 (m05-l01)
>_ Kernel Systems Academy
# Verifying Stream Flags, Memory Streams & Amortization Speedup
learner@ksa:~/gl-c01/m05-l01$ gcc -fdiagnostics-color=always -std=c11 -O2 -Wall -Wextra -Werror fopen_modes_probe.c -o fopen_modes_probelearner@ksa:~/gl-c01/m05-l01$ ./fopen_modes_probelearner@ksa:~/gl-c01/m05-l01$ test ! -e /tmp/ksa_m05_l01.log && rm -f fopen_modes_probestd_streams: in=0 out=1 err=2mode_wplus_xe: wpe_ok=1 acc=O_RDWR append=0 cloexec=1 wx=1mode_aplus_e: acc=O_RDWR append=1 cloexec=1 bytes=11 mem=1 buf_faster=1learner@ksa:~/gl-c01/m05-l01$ GL-C01 · 5.1 (m05-l01)
>_ Kernel Systems Academy
# Inside glibc fopen(), Buffer Flush & open_memstream()
- When
fopen(path, "w+xe")executed,glibcallocatedstruct _IO_FILEon the heap and called `openat(AT_…
GL-C01 · 5.1 (m05-l01)
>_ Kernel Systems Academy
# Guided Practice: Auditing fopen Mode Strings for strace Verification
- Predict the exact
openat()flag mask printed bystrace -e trace=openatfor each of the following three…
GL-C01 · 5.1 (m05-l01)
>_ Kernel Systems Academy
# Guided Practice: Auditing fopen Mode Strings for strace Verification
- 1.
GL-C01 · 5.1 (m05-l01)
>_ Kernel Systems Academy
# Independent Practice: Zero-File fmemopen() & open_memstream() Unit Test
- Write a C11 test
memstream_roundtrip.c(-std=c11 -Wall -Wextra -Werror) containing a serializer `int wr…
GL-C01 · 5.1 (m05-l01)
>_ Kernel Systems Academy
# Warning
warning: Symptom: A multithreaded service opens configuration streams via fopen(path, "w+") and leaks open descriptors across fork() + execve() into child processes, or clobbers files created concurrently. Root Cause: Standard C "w+" omits O_CLOEXEC and O_EXCL. Fix: Append glibc's "e" modifier ("re", "w+e", "ae") on all Linux daemon streams, and add "x" ("wxe", "w+xe") for atomic exclusive file creation.
GL-C01 · 5.1 (m05-l01)
>_ Kernel Systems Academy
# Warning
warning: Symptom: Small fputs() writes return >= 0 without error, yet disk-full (ENOSPC) corruption goes completely undetected because the caller wrote fclose(fp); without checking its return code! Root Cause: Buffered writes stay in Ring 3 RAM until the buffer fills or fclose(fp) flushes remaining bytes via write(), reporting ENOSPC or EIO only through fclose() returning EOF (-1). Fix: Always treat if (fclose(fp) != 0) on writable streams as an I/O failure.
GL-C01 · 5.1 (m05-l01)
>_ Kernel Systems Academy
# Quick check
? Which openat() flag bitmask does glibc pass to the Linux kernel when you call fopen("/var/log/app.log", "a+e")?
Select an option or press R to reveal.
Correct: B
Mode "a+" selects read/write update access with creation and kernel-enforced append (O_RDWR | O_CREAT | O_APPEND), and "e" adds O_CLOEXEC.
Common misconception: Confusing "a+" with "r+" omits O_CREAT | O_APPEND, while confusing "a" with "a+" omits O_RDWR.
GL-C01 · 5.1 (m05-l01)
>_ Kernel Systems Academy
# Quick check
? Why does fopen("capture.bin", "rb") behave identically to fopen("capture.bin", "r") on Linux?
Select an option or press R to reveal.
Correct: B
ISO C11 includes "b" for non-POSIX operating systems that alter newline characters in text mode; on Linux, text and binary streams transfer identical bytes.
Common misconception: Expecting "b" to alter stdio buffering size or alignment misdiagnoses flush timing issues.
GL-C01 · 5.1 (m05-l01)
>_ Kernel Systems Academy
# Quick check
? (Review from earlier lesson) When fopen(path, "wxe") returns NULL with errno == EEXIST because a rival worker just created path, which kernel mechanism prevented a TOCTOU overwrite?
Select an option or press R to reveal.
Correct: B
"x" maps directly to O_EXCL alongside O_CREAT, invoking the kernel's atomic dentry test-and-create under i_rwsem.
Common misconception: O_EXCL is an open-time creation guard and cannot be toggled afterward via F_SETFL.
GL-C01 · 5.1 (m05-l01)
>_ Kernel Systems Academy
# Quick check
? You want to unit-test a C serializer int emit_frame(FILE *out) completely in RAM without creating /tmp files or allocating kernel descriptors. Which POSIX.1-2008 function creates a dynamically growing heap-backed FILE * stream?
Select an option or press R to reveal.
Correct: B
open_memstream() and fmemopen() attach the glibc FILE vtable directly onto heap or caller RAM without opening any kernel descriptor.
Common misconception: Creating temporary /tmp files just to test FILE * serializers introduces race conditions, cleanup leaks, and unnecessary VFS overhead.
GL-C01 · 5.1 (m05-l01)
>_ Kernel Systems Academy
# Summary
glibcFILEstreams wrap integer file descriptors with user-space_IO_read_ptr/_IO_write_ptrbuffers and sticky status bits to amortize Ring 3-to-Ring 0 syscall overhead.- Every hosted C process starts with pre-opened
stdin(0),stdout(1), andstderr(2) streams in<stdio.h>. fopen()modes"r","r+","w","w+","a", and"a+"map deterministically toO_RDONLY/O_RDWR/O_WRONLYplusO_CREAT,O_TRUNC, orO_APPEND, while"b"is a POSIX no-op.- Linux
glibcextensions"e"(O_CLOEXEC) and"x"(O_EXCL) close descriptor-leak and creation-race windows inside the initialopenat(), andfclose(fp)must always be checked on writable streams.
GL-C01 · 5.1 (m05-l01)
>_ Kernel Systems Academy
# Summary
- Next, we serialize fixed-width binary structs over
FILE *streams using item-countedfread()/fwrite()…
GL-C01 · 5.1 (m05-l01)
>_ Kernel Systems Academy
# Key takeaways
- Linux
glibcextensions"e"(O_CLOEXEC) and"x"(O_EXCL) close descriptor-leak and creation-race windows inside the initialopenat(), andfclose(fp)must always be checked on writable streams. - POSIX.1-2008
open_memstream()andfmemopen()backFILE *streams directly with RAM (fileno() == -1,EBADF). - Next, we serialize fixed-width binary structs over
FILE *streams using item-countedfread()/fwrite(), 64-bitfseeko()/ftello(), stickyfeof()/ferror()triage, and 257-stateintfgetc().
GL-C01 · 5.2 (m05-l02)
>_ Kernel Systems Academy
# Binary Stream I/O, fseeko & EOF
What you'll learn
- Serialize and read fixed-width binary structs via item-counted
fwrite()/fread()while recovering torn tail bytes. - Reposition 64-bit streams portably with
fseeko(),ftello(), andrewind()across C11+turnaround barriers. - Disambiguate short counts with
feof(),ferror(), andintfgetc()withoutwhile (!feof(fp))or0xFFcharbugs.
GL-C01 · 5.2 (m05-l02)
>_ Kernel Systems Academy
# Why while (!feof(fp)) & char c = fgetc(fp) Break Binary Readers
- Three
<stdio.h>bugs survive code review with alarming frequency.
GL-C01 · 5.2 (m05-l02)
>_ Kernel Systems Academy
# Why while (!feof(fp)) & char c = fgetc(fp) Break Binary Readers
- Writing rock-solid binary
stdiocode requires mastering four exact contracts: item-countedfread/`fwrit…
GL-C01 · 5.2 (m05-l02)
>_ Kernel Systems Academy
# Mental model
note: Calling fread(recs, sizeof(rec), K, fp) is like asking a bottling machine to fill K six-packs rather than counting individual bottles — if five loose bottles remain when the tank runs dry, the machine reports zero completed six-packs.
Where it stops working: A bottling line leaves partial bottles visible on the belt, whereas fread() leaves the partial record bytes indeterminate inside your destination buffer and advances the stream position across them.
GL-C01 · 5.2 (m05-l02)
>_ Kernel Systems Academy
# Item-Counted I/O, Sticky Stream Indicators & 257-State EOF
definition: Item-Counted Stream I/O (fread / fwrite): Unlike raw read()/write() (ssize_t bytes), fread(ptr, size, nmemb, fp) returns size_t complete items (0..nmemb). 64-Bit Stream Offsets (fseeko / ftello): Replace ISO C long (32-bit on ILP32 ARMv7) with 64-bit off_t and enforce C11 "+" update-stream turnaround synchronization. Sticky Indicators (feof, ferror) & 257-State EOF: _IO_EOF_SEEN turns on only after a read attempts to cross EOF (persisting until clearerr/rewind/fseeko), while fgetc() returns unsigned char widened to int (0..255) plus negative EOF (-1)—257 states requiring an int variable.
GL-C01 · 5.2 (m05-l02)
>_ Kernel Systems Academy
# One Layer Down: Torn-Tail Division Math & the Pigeonhole Proof for int fgetc()
- Inside
glibc(iofread.c),fread(ptr, size, nmemb, fp)computes requested bytesR = size * nmemb(ch…
GL-C01 · 5.2 (m05-l02)
>_ Kernel Systems Academy
# One Layer Down: Torn-Tail Division Math & the Pigeonhole Proof for int fgetc()
- Similarly, the Pigeonhole Principle explains why
charcan never holdfgetc(fp): every 8-bit byte `0…
GL-C01 · 5.2 (m05-l02)
>_ Kernel Systems Academy
# One Layer Down: Torn-Tail Division Math & the Pigeonhole Proof for int fgetc()
Figure 5.2: Item-counted fread() torn-tail division, C11 '+' stream turnaround barriers, and 257-state int fgetc() safety.
GL-C01 · 5.2 (m05-l02)
>_ Kernel Systems Academy
# One Layer Down: Torn-Tail Division Math & the Pigeonhole Proof for int fgetc()
Serialize fixed-width records verified with _Static_assert via fwrite() and track 64-bit offsets with ftello().
Drive binary loops on fread()'s item count, synchronize '+' turnarounds with 64-bit fseeko(), and always store fgetc() in an int.
GL-C01 · 5.2 (m05-l02)
>_ Kernel Systems Academy
# 64-Bit Feature Macros & C11 Update-Stream ("+") Turnaround Rules
- Place
#define _POSIX_C_SOURCE 200809Land#define _FILE_OFFSET_BITS 64at lines 1–2 before<stdio.h>…
GL-C01 · 5.2 (m05-l02)
>_ Kernel Systems Academy
# Testing Torn Tails, Turnaround Barriers, 257-State fgetc & feof Timing
- Save
binary_stream_eof.cbelow.
GL-C01 · 5.2 (m05-l02)
>_ Kernel Systems Academy
# binary_stream_eof.c
learner@ksa:~/gl-c01/m05-l02$ bat binary_stream_eof.c───────┬──────────────────────────────────────────────────────────────────────────────── │ File: binary_stream_eof.c───────┼──────────────────────────────────────────────────────────────────────────────── 1 │ #define _POSIX_C_SOURCE 200809L 2 │ #define _FILE_OFFSET_BITS 64 3 │ #include <stdint.h> 4 │ #include <stdio.h> 5 │ #include <unistd.h> 6 │ 7 │ struct sample_rec { 8 │ uint32_t seq; 9 │ int32_t mv; 10 │ uint64_t ts_ns; 11 │ }; 12 │ _Static_assert(sizeof(struct sample_rec) == 16, "packed by natural alignment"); 13 │ 14 │ int main(void) {───────┴────────────────────────────────────────────────────────────────────────────────GL-C01 · 5.2 (m05-l02)
>_ Kernel Systems Academy
# Verifying Torn-Tail Counts, fgetc 257-State Safety & EOF Timing
- Compile and run
binary_stream_eof: observeitems=3(54 / 16),byte_tailrecovering all6torn byt…
GL-C01 · 5.2 (m05-l02)
>_ Kernel Systems Academy
# Verifying Torn-Tail Counts, fgetc 257-State Safety & EOF Timing
learner@ksa:~/gl-c01/m05-l02$ gcc -fdiagnostics-color=always -std=c11 -Wall -Wextra -Werror binary_stream_eof.c -o binary_stream_eoflearner@ksa:~/gl-c01/m05-l02$ ./binary_stream_eoflearner@ksa:~/gl-c01/m05-l02$ test ! -e /tmp/ksa_m05_l02.bin && rm -f binary_stream_eofitem_read: total=54 items=3 eof=1 err=0 last_mv=3310byte_tail: cleared=1 bytes=6 hex0=AA fgetc_257=1eof_timing: loops=3 r3=3 exact=0 r4=0 past=1learner@ksa:~/gl-c01/m05-l02$ GL-C01 · 5.2 (m05-l02)
>_ Kernel Systems Academy
# Why Byte-Exact Tail Recovery Needs size = 1 or ftello()
- Notice what happened when
fread(out, 16, 4, fp)hit the54-byte torn file: it returned3items, yet t…
GL-C01 · 5.2 (m05-l02)
>_ Kernel Systems Academy
# Guided Practice: Detecting a Torn Struct Tail with size = 1
- Rewrite the
while (fread(&cur, sizeof(cur), 1, fp) == 1)loop so it distinguishes cleanEOFfrom a…
GL-C01 · 5.2 (m05-l02)
>_ Kernel Systems Academy
# Guided Practice: Detecting a Torn Struct Tail with size = 1
- 1.
GL-C01 · 5.2 (m05-l02)
>_ Kernel Systems Academy
# Independent Practice: In-Place Binary Record Patcher on "r+be"
- Write a C11 program
patch_record.c(_FILE_OFFSET_BITS=64,-Wall -Wextra -Werror) that writes5`str…
GL-C01 · 5.2 (m05-l02)
>_ Kernel Systems Academy
# Warning
warning: Symptom: A binary parser written as while (!feof(fp)) { fread(&rec, sizeof(rec), 1, fp); emit(&rec); } emits the final record twice on every file and hangs infinitely on read errors (EIO). Root Cause: feof(fp) turns nonzero only after a read attempts to cross EOF, and never turns on when ferror(fp) halts input. Fix: Loop on while (fread(&rec, sizeof(rec), 1, fp) == 1) and test ferror(fp) vs feof(fp) once after the loop exits.
GL-C01 · 5.2 (m05-l02)
>_ Kernel Systems Academy
# Warning
warning: Symptom: Calling fwrite(&hdr, sizeof(hdr), 1, fp) followed immediately by fread(&rec, sizeof(rec), 1, fp) on a "w+" or "r+" stream returns stale or corrupted bytes. Root Cause: ISO C11 requires an explicit flush or positioning call when switching between output and input on an update ("+") stream so glibc synchronizes _IO_write_ptr and _IO_read_ptr. Fix: Insert fseeko(fp, target_off, SEEK_SET) (or fseeko(fp, 0, SEEK_CUR)) at every read/write turnaround.
GL-C01 · 5.2 (m05-l02)
>_ Kernel Systems Academy
# Quick check
? A file contains 38 bytes. You open it at offset 0 and call size_t n = fread(recs, 16, 4, fp);. What does fread() return, and what are feof(fp) and ferror(fp)?
Select an option or press R to reveal.
Correct: B
fread() returns complete 16-byte items (38 / 16 == 2) and sets feof(fp) when hitting end-of-file partway through item 3.
Common misconception: Confusing fread()'s item return count with a raw byte count misses partial tail bytes; pass size = 1 when byte granularity is required.
GL-C01 · 5.2 (m05-l02)
>_ Kernel Systems Academy
# Quick check
? Why should portable Linux C11 code prefer fseeko() and ftello() (under _FILE_OFFSET_BITS=64) over classic ISO C fseek() and ftell()?
Select an option or press R to reveal.
Correct: B
On 32-bit architectures (sizeof(long) == 4), ftell() fails with EOVERFLOW above 2 GiB, whereas 64-bit off_t handles multi-terabyte files cleanly.
Common misconception: Assuming long is 64 bits everywhere breaks large-file support when cross-compiling for 32-bit embedded targets.
GL-C01 · 5.2 (m05-l02)
>_ Kernel Systems Academy
# Quick check
? (Review from earlier lesson) Suppose you truncate an open stream's backing file via fflush(fp); ftruncate(fileno(fp), 48);. Why must you still call rewind(fp) (or fseeko(fp, 0, SEEK_SET)) before reading from byte 0?
Select an option or press R to reveal.
Correct: B
ftruncate() leaves f_pos untouched (m04-l03), and rewind(fp) resynchronizes glibc's user-space read pointers with kernel offset 0.
Common misconception: Mutating fileno(fp) behind stdio's back without flushing first and seeking afterward desynchronizes user-space and kernel cursors.
GL-C01 · 5.2 (m05-l02)
>_ Kernel Systems Academy
# Quick check
? A developer writes char c; while ((c = fgetc(fp)) != EOF) on x86-64 Linux, passes ASCII tests, and cross-compiles for 32-bit ARMv7 (Cortex-A7) Linux. What happens on each target when reading a binary file containing byte 0xFF?
Select an option or press R to reveal.
Correct: B
fgetc() returns 257 distinct states (0..255 plus -1 EOF), requiring an int variable prior to ch != EOF comparison.
Common misconception: Testing char c = fgetc(fp) only on 7-bit ASCII text on x86-64 masks both the binary 0xFF bug and the ARM infinite loop.
GL-C01 · 5.2 (m05-l02)
>_ Kernel Systems Academy
# Summary
fread()andfwrite()return counts of complete items (0..nmemb); usesize = 1for exact byte counts orsize = sizeof(struct)for aligned fixed records.fgetc()andgetchar()return257intstates (0..255plus(int)-1EOF); narrowing intocharcauses0xFFfalseEOFon x86-64 and infinite loops on unsigned-charARMv7.- Prefer 64-bit
fseeko()andftello()(off_t), and rememberrewind(fp)resets both offset0and stickyfeof/ferrorflags. - On update (
"+") streams, always insertfseeko()(orfflush()after writes) when switching betweenfwrite()andfread().
GL-C01 · 5.2 (m05-l02)
>_ Kernel Systems Academy
# Summary
- Next, we complete Module 5 by building truncation-safe
snprintf()formatters (PRIu64,%zu) and fault-…
GL-C01 · 5.2 (m05-l02)
>_ Kernel Systems Academy
# Key takeaways
- On update (
"+") streams, always insertfseeko()(orfflush()after writes) when switching betweenfwrite()andfread(). - Drive read loops with
while (fread(...) == 1)rather thanwhile (!feof(fp)), then inspectferror(fp)vsfeof(fp)once after termination. - Next, we complete Module 5 by building truncation-safe
snprintf()formatters (PRIu64,%zu) and fault-isolatedfgets()+strtol()line parsers.
GL-C01 · 5.3 (m05-l03)
>_ Kernel Systems Academy
# Bounded snprintf & Safe Text Parsing
What you'll learn
- Format fixed-width and pointer-sized integers portably (
%zu,PRId64,PRIu64) viasnprintf()with-Wformatclean. - Detect formatted output truncation deterministically by checking
ret < 0 || (size_t)ret >= sizeon everysnprintf(). - Construct fault-isolated text parsers combining line-bounded
fgets(), width-capped scansets, andERANGEstrtol().
GL-C01 · 5.3 (m05-l03)
>_ Kernel Systems Academy
# Why Unchecked snprintf Accumulators & Raw fscanf Cause Exploits
- Most C engineers know
sprintf()is banned—yet a subtlesnprintf()anti-pattern causes buffer overflows…
GL-C01 · 5.3 (m05-l03)
>_ Kernel Systems Academy
# Why Unchecked snprintf Accumulators & Raw fscanf Cause Exploits
- Bulletproof text formatting and parsing in C11 rest on three rules: checking
snprintf()'s hypothetical-le…
GL-C01 · 5.3 (m05-l03)
>_ Kernel Systems Academy
# Mental model
note: Calling sprintf() is like pouring hot metal into a mold with no overflow lip, whereas snprintf() caps the pour at the rim and reports the exact volume that would have filled an uncapped mold.
Where it stops working: Overflowed metal spills visibly onto the shop floor, whereas snprintf() silently truncates excess characters unless the caller checks whether the returned length is greater than or equal to the buffer capacity.
GL-C01 · 5.3 (m05-l03)
>_ Kernel Systems Academy
# Bounded snprintf(), <inttypes.h> Macros & Scanset Framing
definition: snprintf(buf, size, fmt, ...) Return Contract (ISO C99/C11 §7.21.6.5): Writes at most size - 1 characters plus a guaranteed terminating '\0' (whenever size > 0), and returns int ret equal to the character count that would have been written excluding '\0' (ret < 0 on encoding error; (size_t)ret >= size if and only if output was truncated). Fixed-Width Format Macros (PRIu64, PRId64): String-literal macros in <inttypes.h> concatenated at compile time ("lu" on LP64 x86-64 vs "llu" on ILP32 ARMv7) so -Wformat -Werror stays clean across ABIs.
GL-C01 · 5.3 (m05-l03)
>_ Kernel Systems Academy
# One Layer Down: Safe Buffer-Append Algebra & Off-by-One Scanset Widths
- To append multiple formatted segments into
char buf[CAP]at cursorsize_t pos(0 <= pos < CAP), let r…
GL-C01 · 5.3 (m05-l03)
>_ Kernel Systems Academy
# One Layer Down: Safe Buffer-Append Algebra & Off-by-One Scanset Widths
- On input, notice the critical
1-byte asymmetry betweenfgets()andsscanf()width specifiers for `cha…
GL-C01 · 5.3 (m05-l03)
>_ Kernel Systems Academy
# One Layer Down: Safe Buffer-Append Algebra & Off-by-One Scanset Widths
Figure 5.3: Truncation-checked snprintf() accumulator math, <inttypes.h> specifiers, and fault-isolated fgets() + strtol() parsing.
GL-C01 · 5.3 (m05-l03)
>_ Kernel Systems Academy
# One Layer Down: Safe Buffer-Append Algebra & Off-by-One Scanset Widths
Frame bounded lines with fgets(line, sizeof(line), fp) and check ferror(fp) vs feof(fp) on NULL exit.
Check (size_t)ret < rem before advancing snprintf() cursors, and isolate line framing with fgets() before tokenizing via (sizeof - 1) scansets and strtol().
GL-C01 · 5.3 (m05-l03)
>_ Kernel Systems Academy
# <inttypes.h> Specifiers, dprintf(3) & strtol(3) Validation
- Include
<stdio.h>,<stdlib.h>,<inttypes.h>,<stdint.h>,<limits.h>, and<errno.h>under `#defi…
GL-C01 · 5.3 (m05-l03)
>_ Kernel Systems Academy
# Building a Truncation-Checked Formatter & Fault-Isolated Line Parser
- Save
fmt_safe_codec.cbelow.
GL-C01 · 5.3 (m05-l03)
>_ Kernel Systems Academy
# fmt_safe_codec.c
learner@ksa:~/gl-c01/m05-l03$ bat fmt_safe_codec.c───────┬──────────────────────────────────────────────────────────────────────────────── │ File: fmt_safe_codec.c───────┼──────────────────────────────────────────────────────────────────────────────── 1 │ #define _POSIX_C_SOURCE 200809L 2 │ #include <errno.h> 3 │ #include <fcntl.h> 4 │ #include <inttypes.h> 5 │ #include <limits.h> 6 │ #include <stdarg.h> 7 │ #include <stdint.h> 8 │ #include <stdio.h> 9 │ #include <stdlib.h> 10 │ #include <string.h> 11 │ #include <unistd.h> 12 │ 13 │ static int buf_appendf(char *buf, size_t cap, size_t *pos, 14 │ const char *fmt, ...) {───────┴────────────────────────────────────────────────────────────────────────────────GL-C01 · 5.3 (m05-l03)
>_ Kernel Systems Academy
# Verifying Truncation Math, Oversized-Line Draining & Lab 5
- Compile and execute
fmt_safe_codec: confirmreq=28vscap=16(trunc=1,app_guard=1), confirm `par…
GL-C01 · 5.3 (m05-l03)
>_ Kernel Systems Academy
# Verifying Truncation Math, Oversized-Line Draining & Lab 5
learner@ksa:~/gl-c01/m05-l03$ gcc -fdiagnostics-color=always -std=c11 -Wall -Wextra -Werror fmt_safe_codec.c -o fmt_safe_codeclearner@ksa:~/gl-c01/m05-l03$ ./fmt_safe_codeclearner@ksa:~/gl-c01/m05-l03$ test ! -e /tmp/ksa_m05_l03.txt && rm -f fmt_safe_codecsnprintf_check: req=28 cap=16 trunc=1 app_guard=1 prefix=ts=9000000001 iparser_check: ok=2 bad=3 sum_mv=3175learner@ksa:~/gl-c01/m05-l03$ GL-C01 · 5.3 (m05-l03)
>_ Kernel Systems Academy
# Lab: lab_m05_telemetry_codec
- 1.
Verify: ./check.sh exits 0.
GL-C01 · 5.3 (m05-l03)
>_ Kernel Systems Academy
# Why Line Isolation Outperforms Stream fscanf()
- Look at how
fgets()+strtol()isolated every failure mode infmt_safe_codec: when the52-byte `ove…
GL-C01 · 5.3 (m05-l03)
>_ Kernel Systems Academy
# Guided Practice: Exact-Fit Dynamic String Allocation via snprintf(NULL, 0, ...)
- Write a function
char *format_alloc(const char *tag, uint64_t seq, ssize_t delta)that allocates an exact…
GL-C01 · 5.3 (m05-l03)
>_ Kernel Systems Academy
# Guided Practice: Exact-Fit Dynamic String Allocation via snprintf(NULL, 0, ...)
- 1.
GL-C01 · 5.3 (m05-l03)
>_ Kernel Systems Academy
# Independent Practice: Strict Key-Value Config Parser (strtoul Hex & Octal)
- Write a C11 parser
kv_cfg_check.c(-std=c11 -Wall -Wextra -Werror) that reads `"key = value # comment\n…
GL-C01 · 5.3 (m05-l03)
>_ Kernel Systems Academy
# Warning
warning: Symptom: Chaining pos += snprintf(buf + pos, sizeof(buf) - pos, ...) without checking each return value overflows buf on the next call after truncation! Root Cause: snprintf() returns the needed length (>= sizeof(buf) - pos), pushing pos past sizeof(buf) and wrapping unsigned sizeof(buf) - pos near SIZE_MAX. Fix: Validate if (ret < 0 || (size_t)ret >= sizeof(buf) - pos) before every pos += (size_t)ret.
GL-C01 · 5.3 (m05-l03)
>_ Kernel Systems Academy
# Warning
warning: Symptom: Writing char key[32]; sscanf(line, "%32s", key); overwrites 1 byte past key[31] on 32-character inputs (ASan stack-buffer-overflow). Root Cause: scanf/sscanf field widths count payload characters excluding the mandatory terminating '\0' byte (32 + 1 = 33 bytes). Fix: Always set scanf string/scanset widths to sizeof(buf) - 1 (%31s or %31[^,\n] for char[32]).
GL-C01 · 5.3 (m05-l03)
>_ Kernel Systems Academy
# Quick check
? Given char buf[10]; int r = snprintf(buf, sizeof(buf), "sensor_%04d", 42);, what value is stored in r, and what condition proves output truncated?
Select an option or press R to reveal.
Correct: B
"sensor_0042" contains 11 characters; snprintf() writes "sensor_00\0" (9 chars + NUL) and returns 11, satisfying (size_t)11 >= 10.
Common misconception: Expecting snprintf() to return sizeof(buf) - 1 or -1 on truncation breaks buffer-growth and bounds guards.
GL-C01 · 5.3 (m05-l03)
>_ Kernel Systems Academy
# Quick check
? Which format string portably prints a size_t byte count followed by a uint64_t timestamp across both 32-bit ARMv7 and 64-bit x86-64 Linux builds under -Wall -Werror?
Select an option or press R to reveal.
Correct: B
%zu matches size_t on every C11 target, while <inttypes.h> expands PRIu64 to "llu" on 32-bit ARMv7 and "lu" on 64-bit LP64 x86-64.
Common misconception: Hard-coding %lu for uint64_t passes on 64-bit x86-64 yet fails -Wformat and corrupts stack arguments on 32-bit ARMv7!
GL-C01 · 5.3 (m05-l03)
>_ Kernel Systems Academy
# Quick check
? (Review from earlier lesson) When fgets(line, sizeof(line), fp) returns NULL, how do you distinguish clean end-of-file from an underlying kernel read() fault?
Select an option or press R to reveal.
Correct: B
Like short counts on fread(), fgets() == NULL occurs on both clean EOF (feof(fp)) and stream errors (ferror(fp)).
Common misconception: Treating every fgets() == NULL as normal end-of-file silently accepts truncated input when a pipe or disk read fails mid-line.
GL-C01 · 5.3 (m05-l03)
>_ Kernel Systems Academy
# Quick check
? Why does production C11 text parsing prefer fgets() + strtol(num_s, &endp, 10) over fscanf(fp, "%d", &val) or atoi(num_s)?
Select an option or press R to reveal.
Correct: B
Line framing with fgets() guarantees forward stream progress on corrupt lines, while strtol() provides deterministic error and overflow reporting.
Common misconception: Using atoi() returns 0 on "ERR" and invokes Undefined Behavior on overflow, while fscanf("%d") stalls indefinitely on non-digit bytes.
GL-C01 · 5.3 (m05-l03)
>_ Kernel Systems Academy
# Summary
- Never call
sprintf(); bound every formatted write withsnprintf(buf, sz, ...)(ordprintf(fd, ...)) and checkret < 0 || (size_t)ret >= szbefore advancing buffer offsets. - Pair
size_t/ssize_twith%zu/%zdand 64-bit fixed integers with<inttypes.h>PRId64/PRIu64so-Wformat -Werrorbuilds cleanly across 32-bit and 64-bit targets. - Cap
scanf/sscanfstring and scanset widths atsizeof(buf) - 1(%31[^\n]forchar[32]) to reserve1byte for'\0'. - Parse text line-first via
fgets()(draining oversized lines) +strtol()(endpandERANGEchecks) so malformed records never wedge the stream.
GL-C01 · 5.3 (m05-l03)
>_ Kernel Systems Academy
# Summary
- With both kernel descriptors and
Ring 3stdiostreams in your toolkit, Module 6 unites both layers to m…
GL-C01 · 5.3 (m05-l03)
>_ Kernel Systems Academy
# Key takeaways
- Cap
scanf/sscanfstring and scanset widths atsizeof(buf) - 1(%31[^\n]forchar[32]) to reserve1byte for'\0'. - Parse text line-first via
fgets()(draining oversized lines) +strtol()(endpandERANGEchecks) so malformed records never wedge the stream. - With both kernel descriptors and
Ring 3stdiostreams in your toolkit, Module 6 unites both layers to master kernel page-cache durability (fsync,fdatasync,O_DIRECT), two-stagefflush+fdatasynccommits, and our capstone crash-safeCRC32Write-Ahead Log!
m06/
>_ Kernel Systems Academy
# Two-Layer I/O Buffering, Durability & Capstone Engine
Master kernel page-cache writeback barriers (fsync, fdatasync, directory sync), sector-aligned O_DIRECT DMA, user-space setvbuf/fflush/fdopen ownership rules, and synthesize a crash-safe CRC32 Write-Ahead Log storage engine.
- 6.1 Page Cache, fsync & Direct I/O
- 6.2 stdio Buffering & Descriptor Interop
- 6.3 Capstone: Crash-Safe Binary Log
lab → Lab 6 Capstone: Crash-Consistent CRC32 Write-Ahead Log & KV Engine
GL-C01 · 6.1 (m06-l01)
>_ Kernel Systems Academy
# Page Cache, fsync & Direct I/O
What you'll learn
- Distinguish
SIGKILLsurvival in the volatile Linux kernel page cache from power-loss durability on storage media. - Select
fsync(),fdatasync(),O_DSYNC, and parent-directoryfsync(dir_fd)barriers for crash-consistent persistence. - Allocate
STATX_DIOALIGN-aligned buffers viaposix_memalign()forO_DIRECTDMA while handlingtmpfsEINVAL.
GL-C01 · 6.1 (m06-l01)
>_ Kernel Systems Academy
# Why write() Loses Data on Power Loss & rename() Needs Directory fsync
- Two post-outage failures shock engineers who confuse process-crash survival with power-loss durability.
GL-C01 · 6.1 (m06-l01)
>_ Kernel Systems Academy
# Why write() Loses Data on Power Loss & rename() Needs Directory fsync
- Engineering crash-consistent storage on Linux requires distinguishing **process death (
SIGKILL, where ker…
GL-C01 · 6.1 (m06-l01)
>_ Kernel Systems Academy
# Mental model
note: A successful write() call is like handing a ledger entry to a clerk who pins it onto an erasable whiteboard in RAM; only fsync() or fdatasync() waits until the clerk engraves the entry onto non-volatile stone.
Where it stops working: Erasing a physical whiteboard loses everything in the room, whereas a user-space process crash (SIGSEGV or SIGKILL) leaves dirty kernel page-cache pages intact for normal background writeback.
GL-C01 · 6.1 (m06-l01)
>_ Kernel Systems Academy
# Page Cache Writeback, fdatasync(), Dir Sync & O_DIRECT
definition: Page Cache Writeback: Buffered write() copies user bytes into inode->i_mapping XArray folios marked PG_dirty and governed by vm.dirty_background_ratio (10%) and vm.dirty_ratio (20%). fsync(fd) vs fdatasync(fd): fsync() flushes dirty data folios plus all inode metadata (mtime, ctime, i_size) and issues a storage controller cache flush (REQ_PREFLUSH / NVMe Flush), whereas fdatasync() skips metadata flushes when i_size and extent maps have not changed (~2x fewer media round-trips on preallocated logs!). O_DIRECT: Bypasses the page cache via Direct Memory Access (DMA) when memory address, byte count, and file offset satisfy statx() STATX_DIOALIGN alignment.
GL-C01 · 6.1 (m06-l01)
>_ Kernel Systems Academy
# One Layer Down: O_DIRECT 3-Way Modulo Invariant & mmap Page Faults
- When opening a block-backed file with
O_DIRECT(queried dynamically on Linux 6.1+ via `statx(fd, "", AT_E…
GL-C01 · 6.1 (m06-l01)
>_ Kernel Systems Academy
# One Layer Down: O_DIRECT 3-Way Modulo Invariant & mmap Page Faults
Figure 6.1: Unified VFS page cache, mmap() MAP_SHARED vs MAP_PRIVATE CoW faults, fdatasync()/dir_fd barriers, and 3-way aligned O_DIRECT DMA.
GL-C01 · 6.1 (m06-l01)
>_ Kernel Systems Academy
# One Layer Down: O_DIRECT 3-Way Modulo Invariant & mmap Page Faults
Query STATX_DIOALIGN for posix_memalign() O_DIRECT buffers, or pre-size WAL segments so i_size stays fixed.
Buffered writes only reach volatile DRAM; power-cut durability requires fdatasync()/fsync() plus fsync(dir_fd) on directory updates.
GL-C01 · 6.1 (m06-l01)
>_ Kernel Systems Academy
# Sync Prototypes, posix_memalign(3) & mmap(2) Reference
- Define
#define _GNU_SOURCEand#define _FILE_OFFSET_BITS 64before<fcntl.h>,<sys/mman.h>, `<sys/s…
GL-C01 · 6.1 (m06-l01)
>_ Kernel Systems Academy
# mmap
mmap(2) GL-C01 Quick Reference mmap(2) NAME mmap, munmap, msync, fdatasync - map page-cache folios and sync media SYNOPSIS #include <sys/mman.h> #include <unistd.h> void *mmap(void *addr, size_t length, int prot, int flags, int fd, off_t offset); int munmap(void *addr, size_t length); int msync(void *addr, size_t length, int flags); int fdatasync(int fd); STANDARDS POSIX.1-2008; O_DIRECT and STATX_DIOALIGN require _GNU_SOURCE on Linux. RETURN VALUE mmap() returns mapped address, or MAP_FAILED ((void *)-1) on error. Kernel Systems Academy m06-l01 mmap(2) GL-C01 quick reference · full manual page: man 2 mmap GL-C01 · 6.1 (m06-l01)
>_ Kernel Systems Academy
# Probing Sync Barriers, mmap CoW vs Shared & STATX_DIOALIGN O_DIRECT
- Save
pagecache_odirect.cbelow.
GL-C01 · 6.1 (m06-l01)
>_ Kernel Systems Academy
# pagecache_odirect.c
learner@ksa:~/gl-c01/m06-l01$ bat pagecache_odirect.c───────┬──────────────────────────────────────────────────────────────────────────────── │ File: pagecache_odirect.c───────┼──────────────────────────────────────────────────────────────────────────────── 1 │ #define _GNU_SOURCE 2 │ #define _FILE_OFFSET_BITS 64 3 │ #include <errno.h> 4 │ #include <fcntl.h> 5 │ #include <stdint.h> 6 │ #include <stdio.h> 7 │ #include <stdlib.h> 8 │ #include <string.h> 9 │ #include <sys/mman.h> 10 │ #include <sys/resource.h> 11 │ #include <sys/stat.h> 12 │ #include <unistd.h> 13 │ 14 │ int main(void) {───────┴────────────────────────────────────────────────────────────────────────────────GL-C01 · 6.1 (m06-l01)
>_ Kernel Systems Academy
# Verifying Durability Barriers, mmap CoW & O_DIRECT Alignment
- Compile and run
pagecache_odirect: verifyfdatasync=1,fsync=1,dir_fsync=1,mmap_cow=1, and `odi…
GL-C01 · 6.1 (m06-l01)
>_ Kernel Systems Academy
# Verifying Durability Barriers, mmap CoW & O_DIRECT Alignment
learner@ksa:~/gl-c01/m06-l01$ gcc -fdiagnostics-color=always -std=c11 -Wall -Wextra -Werror pagecache_odirect.c -o pagecache_odirectlearner@ksa:~/gl-c01/m06-l01$ ./pagecache_odirectlearner@ksa:~/gl-c01/m06-l01$ test ! -e /tmp/ksa_m06_l01.wal && test ! -e /tmp/ksa_m06_l01_dio.bin && rm -f pagecache_odirectdurability: fdatasync=1 fsync=1 dir_fsync=1 mmap_cow=1odirect: mem_ok=1 aligned_io=1 unaligned_einval=1learner@ksa:~/gl-c01/m06-l01$ GL-C01 · 6.1 (m06-l01)
>_ Kernel Systems Academy
# Inside Writeback Flushes, CoW Shadow Pages & Block DMA
- Notice how
pagecache_odirectexposed the unified VFS page cache from three angles:pwrite()dirtied pag…
GL-C01 · 6.1 (m06-l01)
>_ Kernel Systems Academy
# Guided Practice: Preallocated WAL Segment Initializer (fallocate + fdatasync)
- Why do high-throughput WAL writers pre-size segments (
ftruncateorposix_fallocate) once at creation be…
GL-C01 · 6.1 (m06-l01)
>_ Kernel Systems Academy
# Guided Practice: Preallocated WAL Segment Initializer (fallocate + fdatasync)
- 1.
GL-C01 · 6.1 (m06-l01)
>_ Kernel Systems Academy
# Independent Practice: CLOCK_MONOTONIC Buffered write vs O_DSYNC Latency Distribution
- Write a C11 benchmark
sync_latency.c(-std=c11 -O2 -Wall -Wextra -Werror) on a disk-backed directory (s…
GL-C01 · 6.1 (m06-l01)
>_ Kernel Systems Academy
# Warning
warning: Symptom: An atomic updater runs write(tfd) -> fsync(tfd) -> close(tfd) -> rename("cfg.tmp", "cfg.json") and still loses the update on a sudden power cut! Root Cause: fsync(tfd) persisted the file's data blocks and inode, but rename() modified the parent directory's dentry in volatile RAM without syncing the directory inode. Fix: Open the parent directory (O_RDONLY | O_DIRECTORY | O_CLOEXEC), call fsync(dir_fd) after rename() (or O_CREAT), and close dir_fd.
GL-C01 · 6.1 (m06-l01)
>_ Kernel Systems Academy
# Warning
warning: Symptom: Adding O_DIRECT to an existing log writer causes write(fd, line, strlen(line)) to fail with EINVAL (or causes open("/tmp/x", O_DIRECT) on tmpfs to fail with EINVAL). Root Cause: O_DIRECT rejects unaligned malloc/stack buffers, non-block-multiple byte counts, unaligned file offsets, and RAM-backed filesystems (tmpfs). Fix: Query STATX_DIOALIGN, allocate posix_memalign() buffers for block-aligned engines, or use buffered writes + fdatasync() for variable-length records.
GL-C01 · 6.1 (m06-l01)
>_ Kernel Systems Academy
# Quick check
? Why do Write-Ahead Log (WAL) storage engines prefer fdatasync(fd) over fsync(fd) when committing records into a preallocated segment file?
Select an option or press R to reveal.
Correct: B
Inside a pre-sized WAL segment where i_size does not change, fdatasync() avoids a second storage commit for timestamp metadata.
Common misconception: Confusing fdatasync() with fflush() mistakes a hardware media barrier for a user-space RAM flush.
GL-C01 · 6.1 (m06-l01)
>_ Kernel Systems Academy
# Quick check
? Which three values must all be integer multiples of the device's STATX_DIOALIGN alignment boundary when calling pread() or pwrite() on an O_DIRECT descriptor?
Select an option or press R to reveal.
Correct: B
Block-controller DMA bypasses kernel bounce buffers, requiring aligned virtual/physical memory addresses, byte counts, and file offsets.
Common misconception: Aligning only the posix_memalign() pointer while passing a 500-byte length or unaligned offset still fails with EINVAL.
GL-C01 · 6.1 (m06-l01)
>_ Kernel Systems Academy
# Quick check
? (Review from earlier lesson) Suppose you open a file without O_DIRECT and later enable O_DIRECT at runtime via fcntl(). Which fcntl() call sequence is required?
Select an option or press R to reveal.
Correct: B
O_DIRECT is a mutable open-file status flag in struct file.f_flags updated via read-modify-write F_GETFL + F_SETFL (m04-l03).
Common misconception: Passing O_DIRECT to F_SETFD corrupts FD_CLOEXEC, while omitting F_GETFL wipes flags like O_NONBLOCK.
GL-C01 · 6.1 (m06-l01)
>_ Kernel Systems Academy
# Quick check
? When a process calls mmap(NULL, 4096, PROT_READ | PROT_WRITE, flags, fd, 0) on a file whose 4 KiB folio is already resident in the VFS page cache, how do fault counters and store visibility behave under MAP_SHARED vs MAP_PRIVATE?
Select an option or press R to reveal.
Correct: B
Demand-paged mmap() populates page-table entries lazily (ru_minflt in RAM vs ru_majflt from media), aliasing VFS folios under MAP_SHARED and cloning CoW pages under MAP_PRIVATE.
Common misconception: Expecting MAP_PRIVATE stores to modify fd—or assuming mmap() performs eager disk reads before memory is touched—misreads VFS demand paging.
GL-C01 · 6.1 (m06-l01)
>_ Kernel Systems Academy
# Summary
- A successful
write()only places bytes in the volatile Linux kernel page cache (SIGKILL-safe, not power-fail durable) until an explicit sync barrier completes. fsync(fd)flushes data and all inode metadata,fdatasync(fd)skips non-essential timestamp flushes,O_SYNC/O_DSYNCenforce per-write syncs, andfsync(dir_fd)hardens newly created or renamed directory entries.- Demand-paged
mmap()faults in VFS page-cache folios on first touch (ru_minfltvsru_majflt), aliasing dirty folios underMAP_SHAREDand cloning Copy-on-Write shadow pages underMAP_PRIVATE. O_DIRECTbypasses the page cache viastatx()(STATX_DIOALIGN) +posix_memalign()when buffer address, transfer length, and file offset are aligned, whileposix_fadvise(..., POSIX_FADV_DONTNEED)evicts cold sequential cache pages.
GL-C01 · 6.1 (m06-l01)
>_ Kernel Systems Academy
# Summary
- Next, we connect
Ring 3<stdio.h>buffering (_IOFBF,_IOLBF,_IONBF) directly onto thisRing 0…
GL-C01 · 6.1 (m06-l01)
>_ Kernel Systems Academy
# Key takeaways
- Demand-paged
mmap()faults in VFS page-cache folios on first touch (ru_minfltvsru_majflt), aliasing dirty folios underMAP_SHAREDand cloning Copy-on-Write shadow pages underMAP_PRIVATE. O_DIRECTbypasses the page cache viastatx()(STATX_DIOALIGN) +posix_memalign()when buffer address, transfer length, and file offset are aligned, whileposix_fadvise(..., POSIX_FADV_DONTNEED)evicts cold sequential cache pages.- Next, we connect
Ring 3<stdio.h>buffering (_IOFBF,_IOLBF,_IONBF) directly onto thisRing 0page-cache model to master the two-stagefflush->fdatasynccommit pipeline andfdopen/filenoownership rules.
GL-C01 · 6.2 (m06-l02)
>_ Kernel Systems Academy
# stdio Buffering & Descriptor Interop
What you'll learn
- Configure
_IOFBF,_IOLBF, and_IONBFviasetvbuf()and prevent unflushed data loss or duplicatefork()flushes. - Execute the two-stage commit barrier (
fwrite->fflush->fdatasync(fileno(fp))->fclose) for durablestdio. - Enforce single-owner descriptor lifetime rules when bridging raw descriptors and
FILE *streams viafdopen()/fileno().
GL-C01 · 6.2 (m06-l02)
>_ Kernel Systems Academy
# Why fdatasync(fileno(fp)) Alone Syncs Nothing & Double-Close Murders Sockets
- Two catastrophic bugs occur whenever engineers mix
<stdio.h>FILE *streams with raw POSIX descriptors…
GL-C01 · 6.2 (m06-l02)
>_ Kernel Systems Academy
# Why fdatasync(fileno(fp)) Alone Syncs Nothing & Double-Close Murders Sockets
- Mastering two-layer Linux I/O means tracking bytes across both RAM caches (
Ring 3FILEbuffer -> `R…
GL-C01 · 6.2 (m06-l02)
>_ Kernel Systems Academy
# Mental model
note: Two-layer Linux I/O is a two-hop mailroom: fwrite() drops letters into your desk outbox in user space, fflush() carries that outbox down to the kernel loading dock in RAM, and fdatasync() dispatches the delivery truck onto permanent flash media.
Where it stops working: Closing a physical outbox leaves the loading dock doorway open, whereas fclose(fp) closes the underlying kernel file descriptor too — calling close(fd) again closes an unrelated descriptor!
GL-C01 · 6.2 (m06-l02)
>_ Kernel Systems Academy
# setvbuf() Policies, Two-Stage Durability & fdopen() Ownership
definition: stdio Buffering Policies (_IOFBF, _IOLBF, _IONBF): Configured via setvbuf(fp, buf, mode, size) before the first I/O operation on fp: Full Buffering (_IOFBF) (default when !isatty(fd)—files, pipes, sockets) holds size bytes (4..8 KiB) until full; Line Buffering (_IOLBF) (default on interactive TTYs) flushes on '\n'; Unbuffered (_IONBF) (default on stderr) issues write() per call. Two-Stage Durability Barrier: fwrite() -> fflush(fp) (Ring 3 -> Ring 0 page cache) -> fdatasync(fileno(fp)) (Ring 0 -> NVM media). fdopen(fd, mode) Ownership: Transfers ownership of fd to fp (fclose(fp) closes fd); fileno(fp) borrows _fileno without transferring ownership.
GL-C01 · 6.2 (m06-l02)
>_ Kernel Systems Academy
# One Layer Down: Two-Zone State Machine & isatty() Mode Selection
- When
glibcfirst touchesstdout(fd 1),_IO_file_doallocate()invokesfstat(1, &st)/isatty(1)…
GL-C01 · 6.2 (m06-l02)
>_ Kernel Systems Academy
# One Layer Down: Two-Zone State Machine & isatty() Mode Selection
Figure 6.2a: Complete two-zone user-space stdio and Linux kernel page cache buffering, flush, and bypass architecture.
GL-C01 · 6.2 (m06-l02)
>_ Kernel Systems Academy
# One Layer Down: Two-Zone State Machine & isatty() Mode Selection
Stage 1 — fwrite() stages (B, 0, 0) in glibc's Ring 3 heap buffer with zero syscalls (_exit loses it).
Durable stdio commits require Stage 2 fflush(fp) before Stage 3 fdatasync(fileno(fp)), followed by single-owner fclose(fp).
GL-C01 · 6.2 (m06-l02)
>_ Kernel Systems Academy
# One Layer Down: Two-Zone State Machine & isatty() Mode Selection
Figure 6.2b: Two-stage durability state transitions, setvbuf() policies, and single-owner fdopen() versus borrowed fileno().
GL-C01 · 6.2 (m06-l02)
>_ Kernel Systems Academy
# setvbuf(3) Lifetime Rule & fdopen(3) Error Handling
- Include
<stdio.h>,<fcntl.h>,<time.h>, and<unistd.h>under#define _POSIX_C_SOURCE 200809L.
GL-C01 · 6.2 (m06-l02)
>_ Kernel Systems Academy
# Probing _IOFBF/_IOLBF/_IONBF, Two-Stage Sync & Ownership Transfer
- Save
stdio_buf_interop.cbelow.
GL-C01 · 6.2 (m06-l02)
>_ Kernel Systems Academy
# stdio_buf_interop.c
learner@ksa:~/gl-c01/m06-l02$ bat stdio_buf_interop.c───────┬──────────────────────────────────────────────────────────────────────────────── │ File: stdio_buf_interop.c───────┼──────────────────────────────────────────────────────────────────────────────── 1 │ #define _POSIX_C_SOURCE 200809L 2 │ #include <errno.h> 3 │ #include <fcntl.h> 4 │ #include <stdint.h> 5 │ #include <stdio.h> 6 │ #include <stdlib.h> 7 │ #include <string.h> 8 │ #include <sys/stat.h> 9 │ #include <time.h> 10 │ #include <unistd.h> 11 │ 12 │ static uint64_t span_ns(struct timespec a, struct timespec b) { 13 │ return (uint64_t)(b.tv_sec - a.tv_sec) * 1000000000ULL + 14 │ (uint64_t)(b.tv_nsec - a.tv_nsec);───────┴────────────────────────────────────────────────────────────────────────────────GL-C01 · 6.2 (m06-l02)
>_ Kernel Systems Academy
# Verifying Two-Zone Flush Boundaries, Single-Owner Close & Speedup
- Compile and execute
stdio_buf_interop: verifyiofbf=0->11,iolbf=5->9,ionbf=3->3,pre_flush=0->…
GL-C01 · 6.2 (m06-l02)
>_ Kernel Systems Academy
# Verifying Two-Zone Flush Boundaries, Single-Owner Close & Speedup
learner@ksa:~/gl-c01/m06-l02$ gcc -fdiagnostics-color=always -std=c11 -O2 -Wall -Wextra -Werror stdio_buf_interop.c -o stdio_buf_interoplearner@ksa:~/gl-c01/m06-l02$ ./stdio_buf_interoplearner@ksa:~/gl-c01/m06-l02$ test ! -e /tmp/ksa_m06_l02.commit && rm -f stdio_buf_interopbuf_modes: iofbf=0->11 iolbf=5->9 ionbf=3->3pipeline_owner: pre_flush=0 post_flush=14 sync=1 raw_ebadf=1 iofbf_faster=1learner@ksa:~/gl-c01/m06-l02$ GL-C01 · 6.2 (m06-l02)
>_ Kernel Systems Academy
# Why pre_flush=0 Proves Both Sync Stages Are Mandatory
- Seeing
pre_flush=0right afterfwrite(rec, 1, 14, fp)settles the durability debate permanently: the Li…
GL-C01 · 6.2 (m06-l02)
>_ Kernel Systems Academy
# Guided Practice: Borrowing raw_fd Safely via dup() + fdopen()
- Suppose a protocol handler receives
int client_fdfrom a caller whose contract statesclient_fd**must…
GL-C01 · 6.2 (m06-l02)
>_ Kernel Systems Academy
# Guided Practice: Borrowing raw_fd Safely via dup() + fdopen()
- 1.
GL-C01 · 6.2 (m06-l02)
>_ Kernel Systems Academy
# Independent Practice: Durable Checkpoint Writer Function
- Write a standalone C11 module
durable_save.c(-std=c11 -Wall -Wextra -Werror) implementing `int save_ch…
GL-C01 · 6.2 (m06-l02)
>_ Kernel Systems Academy
# Warning
warning: Symptom: A helper runs char fastbuf[8192]; setvbuf(fp, fastbuf, _IOFBF, sizeof(fastbuf)); return fp;, causing random stack corruption and SIGSEGV inside main() on later fprintf() or fclose() calls! Root Cause: Non-NULL buf pointers passed to setvbuf() are stored inside fp and written into long after the helper's stack frame returns! Fix: Pass buf = NULL (setvbuf(fp, NULL, _IOFBF, 8192)) so glibc allocates and frees heap storage automatically.
GL-C01 · 6.2 (m06-l02)
>_ Kernel Systems Academy
# Warning
warning: Symptom: Running int fd = open(...); FILE *fp = fdopen(fd, "r"); ... fclose(fp); close(fd); passes single-threaded tests, then randomly disconnects live client sockets under multithreaded load! Root Cause: fclose(fp) already closed fd; when a sibling thread reuses that lowest-numbered descriptor integer, the redundant close(fd) kills the sibling's handle! Fix: Transfer ownership cleanly (fd = -1 after fdopen succeeds); call close(fd) only on the branch where fdopen() returned NULL.
GL-C01 · 6.2 (m06-l02)
>_ Kernel Systems Academy
# Quick check
? Why does a background daemon whose stdout is redirected to /var/log/daemon.log stop emitting printf("worker ready\n"); lines immediately until 4 KiB or 8 KiB of text accumulates?
Select an option or press R to reveal.
Correct: B
stdout defaults to _IOLBF only on interactive terminals; redirecting stdout to a file or systemd pipe selects _IOFBF unless setvbuf(stdout, NULL, _IOLBF, 0) or fflush(stdout) is called.
Common misconception: Assuming '\n' flushes printf() unconditionally causes mystifying blank log files in systemd and container deployments.
GL-C01 · 6.2 (m06-l02)
>_ Kernel Systems Academy
# Quick check
? Which exact call sequence guarantees that records written via fwrite(..., fp) survive a sudden machine power loss before closing fp?
Select an option or press R to reveal.
Correct: B
fflush(fp) pushes Ring 3 bytes to the Ring 0 page cache, fdatasync(fileno(fp)) commits dirty folios to non-volatile media, and fclose(fp) frees fp and closes _fileno once (fclose never calls fsync).
Common misconception: Calling fdatasync before fflush syncs stale kernel RAM while data sits in user space, and assuming fclose() implies fsync() loses data on power failure.
GL-C01 · 6.2 (m06-l02)
>_ Kernel Systems Academy
# Quick check
? (Review from earlier lesson) If you must wrap raw_fd inside a temporary FILE * stream without allowing fclose(fp) to close raw_fd, which descriptor primitive solves this cleanly?
Select an option or press R to reveal.
Correct: B
Duplicating raw_fd increments struct file.f_count to 2; fclose(fp) closes d (f_count -> 1), keeping raw_fd open.
Common misconception: FD_CLOEXEC controls execve() inheritance, not fclose().
GL-C01 · 6.2 (m06-l02)
>_ Kernel Systems Academy
# Quick check
? What happens if a parent process writes "HEADER\n" into a redirected _IOFBF stdout file without calling fflush(stdout) and then calls fork(), after which both parent and child return cleanly from main()?
Select an option or press R to reveal.
Correct: B
Unflushed Ring 3 FILE buffers live in user virtual memory cloned by fork(); calling fflush(NULL) before fork() (and _exit() in failed execve children) prevents duplicate output!
Common misconception: Confusing kernel struct file state with Ring 3 glibc heap memory misses why fork() duplicates buffered stdio bytes.
GL-C01 · 6.2 (m06-l02)
>_ Kernel Systems Academy
# Summary
glibcFILEstreams support_IOFBF(full, default on files/pipes),_IOLBF(line, default on terminals), and_IONBF(unbuffered, default onstderr), configured viasetvbuf(fp, NULL, mode, sz)before any I/O.- Normal
exit()flushes all user-spaceFILEstreams, whereas_exit()traps straight to kernelexit_group()and drops unflushedRing 3buffers (andfflush(NULL)must precedefork()). - Power-safe
stdiodurability requires the strict two-stage barrierfwrite()->fflush(fp)->fdatasync(fileno(fp))-> checkedfclose(fp). fdopen(fd, mode)transfers descriptor ownership tofp(fclose(fp)closesfd);fileno(fp)borrows_filenowithout transferring ownership.
GL-C01 · 6.2 (m06-l02)
>_ Kernel Systems Academy
# Summary
- Now, in our final capstone lesson (
m06-l03), we synthesize every mechanism from Modules 1 through 6 into…
GL-C01 · 6.2 (m06-l02)
>_ Kernel Systems Academy
# Key takeaways
- Power-safe
stdiodurability requires the strict two-stage barrierfwrite()->fflush(fp)->fdatasync(fileno(fp))-> checkedfclose(fp). fdopen(fd, mode)transfers descriptor ownership tofp(fclose(fp)closesfd);fileno(fp)borrows_filenowithout transferring ownership.- Now, in our final capstone lesson (
m06-l03), we synthesize every mechanism from Modules 1 through 6 into a crash-consistentCRC32+ monotonic-epoch Write-Ahead Log (WAL) storage engine!
GL-C01 · 6.3 (m06-l03)
>_ Kernel Systems Academy
# Capstone: Crash-Safe Binary Log
What you'll learn
- Construct self-describing binary Write-Ahead Log frames with magic bytes, 64-bit
seqepochs, lengths, and IEEECRC32. - Implement startup crash-recovery scanning that detects torn or corrupt tail frames and heals the log via
ftruncate(). - Serve lock-free latest-key reads via an in-memory offset index and stateless
pread()without moving the append cursor.
GL-C01 · 6.3 (m06-l03)
>_ Kernel Systems Academy
# Why In-Place Updates Corrupt State & CRC32 Alone Fails Recycled Logs
- Imagine an embedded power-controller key-value store that updates
"vcore"from"1150mV"(6bytes) to…
GL-C01 · 6.3 (m06-l03)
>_ Kernel Systems Academy
# Why In-Place Updates Corrupt State & CRC32 Alone Fails Recycled Logs
- Production storage engines (
SQLiteWAL,RocksDB,etcdRaft logs) solve both hazards by uniting every…
GL-C01 · 6.3 (m06-l03)
>_ Kernel Systems Academy
# Mental model
note: A crash-safe Write-Ahead Log is like an aircraft flight recorder tape sealed frame-by-frame with sequence numbers and checksum stamps: if power cuts mid-frame, recovery inspectors snip off the broken tail frame cleanly and read any earlier frame by exact byte offset without moving the recording head.
Where it stops working: Snipping physical tape requires hand splicing, whereas ftruncate() updates inode->i_size atomically in the filesystem while leaving concurrent pread() readers completely lock-free at earlier offsets.
GL-C01 · 6.3 (m06-l03)
>_ Kernel Systems Academy
# Write-Ahead Log (WAL), Reflected CRC32 & Monotonic Epoch
definition: Write-Ahead Log (WAL): Originated in the ARIES recovery architecture (Mohan et al.), an append-only binary log where mutations append immutable frames flushed via fdatasync() before acknowledgment, startup recovery truncates uncommitted crash tails via ftruncate(), and point queries read latest committed offsets via stateless pread(). Reflected IEEE 802.3 CRC32 (0xEDB88320U) & Monotonic seq: Processes bits Least-Significant-Bit (LSB)-first over [seq, klen, vlen, key, val] to detect bit-rot and torn writes, while h.seq == expected_seq stops recovery deterministically at recycled-sector boundaries.
GL-C01 · 6.3 (m06-l03)
>_ Kernel Systems Academy
# One Layer Down: 24-Byte Frame Geometry & Branchless GF(2) CRC32 Math
- Each WAL record begins with an ABI-locked
24-byte header (struct wal_hdr: `uint32_t magic, crc32, klen,…
GL-C01 · 6.3 (m06-l03)
>_ Kernel Systems Academy
# One Layer Down: 24-Byte Frame Geometry & Branchless GF(2) CRC32 Math
Figure 6.3: ABI-locked 24-byte CRC32+seq WAL frame layout, recycled-tail ftruncate() crash healing, and lock-free pread() indexing.
GL-C01 · 6.3 (m06-l03)
>_ Kernel Systems Academy
# One Layer Down: 24-Byte Frame Geometry & Branchless GF(2) CRC32 Math
Seal [seq, klen, vlen, key, val] inside a 24-byte header with branchless CRC32 and commit via write_all() + fdatasync().
Seal immutable WAL frames with branchless CRC32 + monotonic seq, flush via fdatasync(), heal crash tails with ftruncate() + lseek(), and read lock-free via pread().
GL-C01 · 6.3 (m06-l03)
>_ Kernel Systems Academy
# Startup Recovery State Machine & Cursor Resynchronization
- Walk through the four validation gates executed at byte offset
offduring startup recovery (exp_seqsta…
GL-C01 · 6.3 (m06-l03)
>_ Kernel Systems Academy
# Building Mini-WAL Commit, Stale-Epoch Guard, Healing & pread Lookup
- Save
mini_wal_demo.cbelow.
GL-C01 · 6.3 (m06-l03)
>_ Kernel Systems Academy
# mini_wal_demo.c
learner@ksa:~/gl-c01/m06-l03$ bat mini_wal_demo.c───────┬──────────────────────────────────────────────────────────────────────────────── │ File: mini_wal_demo.c───────┼──────────────────────────────────────────────────────────────────────────────── 1 │ #define _FILE_OFFSET_BITS 64 2 │ #define _POSIX_C_SOURCE 200809L 3 │ #include <errno.h> 4 │ #include <fcntl.h> 5 │ #include <stdint.h> 6 │ #include <stdio.h> 7 │ #include <string.h> 8 │ #include <sys/stat.h> 9 │ #include <unistd.h> 10 │ 11 │ #define WAL_MAGIC 0x4B57414CU 12 │ 13 │ struct wal_hdr { 14 │ uint32_t magic, crc32, klen, vlen;───────┴────────────────────────────────────────────────────────────────────────────────GL-C01 · 6.3 (m06-l03)
>_ Kernel Systems Academy
# Verifying Crash-Tail Healing, Stateless pread Lookup & Lab 6
- Compile and execute
mini_wal_demo: verifyclean=105,crashed=145,healed=105(recs=3), and `vcore…
GL-C01 · 6.3 (m06-l03)
>_ Kernel Systems Academy
# Verifying Crash-Tail Healing, Stateless pread Lookup & Lab 6
learner@ksa:~/gl-c01/m06-l03$ gcc -fdiagnostics-color=always -std=c11 -Wall -Wextra -Werror mini_wal_demo.c -o mini_wal_demolearner@ksa:~/gl-c01/m06-l03$ ./mini_wal_demolearner@ksa:~/gl-c01/m06-l03$ test ! -e /tmp/ksa_m06_l03.wal && rm -f mini_wal_demowal_recovery: clean=105 crashed=145 healed=105 recs=3wal_lookup: vcore=1200mV writer_fpos=105learner@ksa:~/gl-c01/m06-l03$ GL-C01 · 6.3 (m06-l03)
>_ Kernel Systems Academy
# Lab: lab_m06_durable_wal
- 1.
Verify: ./check.sh exits 0.
GL-C01 · 6.3 (m06-l03)
>_ Kernel Systems Academy
# Full-Course Synthesis & Bridge to GL-C02
- Trace how every layer in
mini_wal_demoreinforced the others:O_CLOEXECprevented handle leaks, subtrac…
GL-C01 · 6.3 (m06-l03)
>_ Kernel Systems Academy
# Note
note: Later: In Course 2 (GL-C02: linux-c-proc-threads), you will build on these VFS descriptor and durability foundations to master directory trees (opendir/readdir, statx), asynchronous POSIX signals (sigaction, signal masks), multi-process execution (fork, execve, waitpid), and pthread mutex/condvar concurrency!
GL-C01 · 6.3 (m06-l03)
>_ Kernel Systems Academy
# Guided Practice: Adding Tombstone (DELETE) Records to an Append-Only WAL
- How do append-only WAL engines delete a key like
"pll_hz"without erasing or mutating earlier frames in p…
GL-C01 · 6.3 (m06-l03)
>_ Kernel Systems Academy
# Guided Practice: Adding Tombstone (DELETE) Records to an Append-Only WAL
- 1.
GL-C01 · 6.3 (m06-l03)
>_ Kernel Systems Academy
# Independent Practice: Atomic WAL Log Compaction (compact_wal_at)
- Over months of updates, an append-only WAL accumulates superseded frames.
GL-C01 · 6.3 (m06-l03)
>_ Kernel Systems Academy
# Warning
warning: Symptom: Computing a WAL frame's CRC32 over key and val bytes while excluding klen, vlen, and seq lets a corrupted length field shift frame boundaries or trigger gigabyte malloc() calls! Root Cause: Unchecksummed header lengths allow bit-flips in klen/vlen to reinterpret payload bytes as adjacent headers. Fix: Enforce strict upper caps on klen and vlen before reading payloads, and include seq, klen, vlen, key, and val inside the CRC32 envelope.
GL-C01 · 6.3 (m06-l03)
>_ Kernel Systems Academy
# Warning
warning: Symptom: After ftruncate(fd, valid_off) heals a 145-byte crashed WAL back to 105 bytes, the next write() (on a non-O_APPEND handle) injects a 40-byte zero hole at [105..144]! Root Cause: ftruncate() updates inode->i_size to 105 without moving struct file.f_pos down from 145. Fix: Call lseek(fd, valid_off, SEEK_SET) immediately after ftruncate() (or write via O_APPEND / explicit pwrite() offsets).
GL-C01 · 6.3 (m06-l03)
>_ Kernel Systems Academy
# Quick check
? During startup recovery of an append-only WAL, the scanner verifies 3 intact frames ending at byte 105, followed by 11 bytes of a 4th frame cut short by a power outage. What is the exact recovery action?
Select an option or press R to reveal.
Correct: B
Because wal_put() acknowledges commits only after fdatasync() completes, an incomplete tail frame was never acknowledged and is safely truncated at 105.
Common misconception: Zero-padding torn frames fabricates corrupt data, while deleting the log destroys durable committed state.
GL-C01 · 6.3 (m06-l03)
>_ Kernel Systems Academy
# Quick check
? Why does sequential replay of an append-only WAL from offset 0 to valid_off support key updates ("vcore" changing from "1150mV" to "1200mV") without mutating earlier bytes in place?
Select an option or press R to reveal.
Correct: B
Replaying immutable frames in commit order naturally supersedes older offsets in the RAM index while avoiding in-place power-loss corruption.
Common misconception: Overwriting variable-length records in place mid-file cannot be made atomic against sudden power loss without write-ahead logging or copy-on-write rename.
GL-C01 · 6.3 (m06-l03)
>_ Kernel Systems Academy
# Quick check
? (Review from earlier lesson) Why can reader threads execute pread(fd, buf, vlen, val_off) concurrently on the WAL descriptor while a writer appends new frames at the tail?
Select an option or press R to reveal.
Correct: B
Pairing immutable historical frames with stateless pread() (m04-l02) eliminates lseek() + read() cursor contention completely.
Common misconception: Using lseek() + read() on a shared WAL descriptor races across readers and clobbers a non-append writer's f_pos.
GL-C01 · 6.3 (m06-l03)
>_ Kernel Systems Academy
# Quick check
? Why do production WAL engines that recycle preallocated log segments pair reflected IEEE 802.3 CRC32 (0xEDB88320U & -(crc & 1U)) with a strictly monotonic 64-bit seq header field?
Select an option or press R to reveal.
Correct: B
CRC32 catches bit-rot and partial writes within a frame, while a monotonic 64-bit seq counter detects epoch boundaries across recycled segments.
Common misconception: Checking magic and CRC32 alone on recycled WAL files silently resurrects stale transactions after an unclean shutdown!
GL-C01 · 6.3 (m06-l03)
>_ Kernel Systems Academy
# Summary
- A crash-safe Write-Ahead Log unites
O_CLOEXEChandle hygiene, binary length-prefixedCRC32framing,fdatasync()+ directoryfsync()barriers,ftruncate()torn-tail healing, and statelesspread()indexed reads. - Reflected IEEE 802.3
CRC32(0xEDB88320U) processes bitsLSB-first using the branchless mask-(crc & 1U)over[seq, klen, vlen, key, val], while monotonic 64-bitseqprevents stale recycled blocks from replaying. - Append-only immutable frames replace in-place overwrites with sequential tail appends, enabling lock-free
pread()lookups on committed offsets. - With Linux file I/O, VFS descriptor tables,
stdiocodecs, and two-layer durability mastered inGL-C01, you are ready for filesystems, signals, processes, and threads inGL-C02.
GL-C01 · 6.3 (m06-l03)
>_ Kernel Systems Academy
# Key takeaways
- Reflected IEEE 802.3
CRC32(0xEDB88320U) processes bitsLSB-first using the branchless mask-(crc & 1U)over[seq, klen, vlen, key, val], while monotonic 64-bitseqprevents stale recycled blocks from replaying. - Append-only immutable frames replace in-place overwrites with sequential tail appends, enabling lock-free
pread()lookups on committed offsets. - With Linux file I/O, VFS descriptor tables,
stdiocodecs, and two-layer durability mastered inGL-C01, you are ready for filesystems, signals, processes, and threads inGL-C02.