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.
Print this handbook or save as PDF (A4 or Letter) for offline engineering reference. Terminal listings convert automatically to crisp white ink-saving frames in print.
m01/
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.
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.
Why Systems C Needs a Hardware Kernel Boundary
Suppose an engineer ports a bare-metal microcontroller routine *(volatile uint32_t *)0x0209C000 = 1U; directly into main() of a Linux telemetry daemon to toggle a status pin. On a microcontroller without a Memory Management Unit (MMU), that store hits a physical Memory-Mapped Input/Output (MMIO) peripheral register—and one corrupted pointer in a string parser silently overwrites motor-control or flash-erase registers across the entire board. Under the Linux kernel, executing that identical store inside main() terminates the process within nanoseconds with SIGSEGV (Segmentation fault) while every sibling service and hardware peripheral keeps running unharmed.
Naive C code fails at this boundary for two complementary reasons. First, treating user-space pointers as physical bus addresses violates hardware virtual-memory protection. Second, going to the opposite extreme—issuing a 1-byte kernel write call inside a tight loop—stalls the processor in privilege-switch overhead that costs hundreds of CPU cycles per byte. Production systems engineers must know exactly which instructions execute freely in user Random-Access Memory (RAM), which operations cross the synchronous kernel trap gate, and which read-only kernel queries bypass traps altogether.
Welcome to GL-C01 (Linux Systems I/O & Buffering in C), the foundational first course of our four-course Linux Systems Programming in C series:
GL-C01(This Course): ISO C11 toolchain discipline, Application Binary Interface (ABI) mechanics, unbuffered Portable Operating System Interface (POSIX) file descriptors, Virtual File System (VFS) open-file tables, atomic positional operations,stdiobuffering, and crash-consistent Write-Ahead Log (WAL) storage.GL-C02: Filesystem metadata, directory traversal, signals, multi-process lifecycles, and POSIX threads (pthreads).GL-C03: Non-blocking I/O,poll/epollevent multiplexing, Inter-Process Communication (IPC), and TCP/UDP network sockets.GL-C04: User-space embedded Linux peripherals (sysfs,evdev,I2C/SPI/UART, DRM display, V4L2 camera, and ALSA audio).
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.
definition (Hardware Privilege Rings, Syscall Gate & vDSO): 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.
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.
Virtual vs Physical Memory: How the MMU Isolates Processes & Guards Silicon
Why did *(volatile uint32_t *)0x0209C000 = 1U; crash main() with SIGSEGV instead of toggling a GPIO pin, and how can two C programs run simultaneously without overwriting each other's variables? Because on a Linux system, no user-space C pointer ever holds a physical RAM or bus address. Every pointer (&b, malloc(), function addresses) holds a Virtual Address (VA) translated on every single load, store, and instruction fetch by silicon inside the CPU called the Memory Management Unit (MMU). Follow the three columns of Figure 1.1b:
- Per-Process Virtual Address Spaces (Left Column): When Process A (
PID 410) and Process B (PID 411) run the same binary, both can hold the exact same virtual address0x00404010! Each virtual address splits into an upper Virtual Page Number (VPN) and a lower12-bit Page Offset ([11:0],0..4095inside a4 KiBpage). - Hardware Page Tables &
TLBLookup (Center Column): A privileged CPU register (CR3on x86-64;TTBR0onARMv7-A) points theMMUat the currently scheduled process's kernel-managed page table (cached in nanoseconds inside the Translation Lookaside Buffer,TLB). PID410's page table mapsVPN 0x00404to physical frame0x82140(U=1user-accessible,RW), while PID411's table maps the sameVPN 0x00404to a completely disjoint physicalDDRframe0x9A030! - Protected Physical
MMIOSilicon (Right Column): Physical peripheral registers such asGPIO1(0x0209C000) andCCMclocks (0x020C4000) have no valid user-space page-table entry (V=0/U=0). The instantRing 3code dereferences0x0209C000, theMMUaborts the bus cycle in hardware and traps into the kernel page-fault handler (SIGSEGV), whereasRing 0kernel drivers map0x0209C000into kernel-only virtual memory viaioremap()with uncachedDeviceattributes!
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.
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. On x86-64 System V ABI, the wrapper loads the syscall number into %rax and up to six arguments into %rdi, %rsi, %rdx, %r10, %r8, and %r9, then executes syscall; the hardware saves the user instruction pointer into %rcx, masks flags via IA32_FMASK, switches to the per-thread kernel stack, and enters entry_SYSCALL_64. On 32-bit ARMv7 (Cortex-A7 EABI), the syscall number goes into r7, arguments occupy r0..r5, and svc #0 vector-traps into Supervisor (SVC) mode. Inside Ring 0, the Linux kernel mediates hardware and shared resources across seven core subsystems: system calls, VFS, virtual memory (MMU), process scheduling, IPC, networking, and device drivers (struct file_operations callbacks using copy_from_user() and copy_to_user()).
Quantifying transition cost explains why systems C separates Ring 3 computation from Ring 0 traps. On modern x86-64 and ARMv7 cores with kernel page-table isolation and Spectre/Meltdown mitigations, one null getpid() syscall trap costs roughly t_trap = 120..350 ns, whereas a pure Ring 3 function call (strlen()) or a vDSO clock_gettime(CLOCK_MONOTONIC, &ts) read of the kernel's seqcount page via AT_SYSINFO_EHDR costs t_vdso = 15..25 ns. Emitting N = 1,000,000 four-byte records via unbuffered write() burns N * t_trap = ~250 ms in pure mode-switch overhead before counting storage latency; batching into 8 KiB (8,192-byte) chunks cuts trap count to ceil(4,000,000 / 8,192) = 489 calls (~0.12 ms), a more than 2,000x reduction in trap overhead!
| Execution Path | CPU Privilege & Address Space | Entry Mechanism | Typical Latency | Failure Blast Radius & strace Visibility |
|---|---|---|---|---|
| Bare-metal MCU firmware | Unprotected flat physical bus | Direct *(volatile uint32_t *) | 2..10 ns | Corrupts any peripheral; halts entire board |
Pure Ring 3 C helper | Ring 3 / EL0 virtual RAM | Standard ABI call / bl | 1..5 ns | Process SIGSEGV only; 0 strace lines |
linux-vdso.so.1 fastpath | Ring 3 / EL0 read-only shared page | AT_SYSINFO_EHDR call (clock_gettime) | 15..25 ns | Read-only isolation; 0 strace lines |
| User-to-kernel syscall | Ring 3 -> Ring 0 VFS gate | syscall (x86-64) / svc #0 (ARMv7) | 120..350 ns | Kernel validates copy_from_user(); 1:1 strace |
| Kernel character driver | Ring 0 / EL1 kernel virtual space | struct file_operations vtable | Hardware-bound | Kernel oops or panic (GL-E04 scope) |
- Step 1. Raw MMIO dereferences in Ring 3 fault immediately in the MMU (SIGSEGV), protecting sibling processes and silicon.
- Step 2. Pure Ring 3 C helpers and linux-vdso.so.1 clock_gettime() execute in user virtual memory with zero kernel traps.
- Step 3. System calls issue a synchronous syscall / svc #0 CPU trap across the ABI gate into Ring 0.
- Step 4. VFS dispatches file and /dev operations to driver struct file_operations callbacks using copy_from_user().
Figure 1.1c. User-space C logic and kernel drivers meet strictly across the VFS system call boundary.
Benchmarking Ring 3 + vDSO vs Syscall Traps in ISO C11
Because POSIX abstracts files, pipes, sockets, and /dev nodes behind uniform integer descriptors, standard user-space C code compiles cleanly across x86-64 workstations and embedded ARMv7 targets under -std=c11 -Wall -Wextra -Werror. Save hello_systems.c below: it verifies fixed-width <stdint.h> layout, inspects its isolated Ring 3 stack virtual address, and times 2,000 clock_gettime(CLOCK_MONOTONIC) vDSO reads against 2,000 real getpid() kernel traps via syscall(SYS_getpid).
learner@ksa:~/gl-c01/m01-l01$ bat -H 17 -H 25 -H 31 hello_systems.c File: hello_systems.c #define _GNU_SOURCE #include <stdint.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <sys/syscall.h> #include <time.h> #include <unistd.h> struct course_banner { char code[8]; uint32_t magic; uint16_t modules; }; static uint64_t ns_since(struct timespec a, struct timespec b) { return (uint64_t)(b.tv_sec - a.tv_sec) * 1000000000ULL + (uint64_t)(b.tv_nsec - a.tv_nsec); } int main(void) { struct course_banner b = {"GL-C01", 0x4B534131U, 6U}; size_t code_len = strlen(b.code); uintptr_t vaddr = (uintptr_t)(const void *)&b; struct timespec t0, t1, t2, probe; volatile long sink = 0; clock_gettime(CLOCK_MONOTONIC, &t0); for (int i = 0; i < 2000; i++) { clock_gettime(CLOCK_MONOTONIC, &probe); } clock_gettime(CLOCK_MONOTONIC, &t1); for (int i = 0; i < 2000; i++) { sink += syscall(SYS_getpid); } clock_gettime(CLOCK_MONOTONIC, &t2); (void)sink; uint64_t vdso_ns = ns_since(t0, t1); uint64_t trap_ns = ns_since(t1, t2); printf("course=%s code_len=%zu modules=%u u32_bytes=%zu vmem_ok=%d\n", b.code, code_len, (unsigned int)b.modules, sizeof(b.magic), vaddr > 4096U && trap_ns > vdso_ns); return EXIT_SUCCESS; }- Define _GNU_SOURCE before headers so <time.h> and <sys/syscall.h> expose CLOCK_MONOTONIC and raw syscall(SYS_getpid).
- clock_gettime(CLOCK_MONOTONIC) reads the kernel timekeeper page mapped in linux-vdso.so.1 without trapping into Ring 0.
- syscall(SYS_getpid) forces a real CPU privilege switch on every iteration so we can contrast trap cost against vDSO reads.
learner@ksa:~/gl-c01/m01-l01gcc -fdiagnostics-color=always -std=c11 -O2 -Wall -Wextra -Werror hello_systems.c -o hello_systemslearner@ksa:~/gl-c01/m01-l01./hello_systemscourse=GL-C01 code_len=6 modules=6 u32_bytes=4 vmem_ok=1learner@ksa:~/gl-c01/m01-l01grep -q 'vdso' /proc/self/maps && echo vdso_mapped=1vdso_mapped=1learner@ksa:~/gl-c01/m01-l01sh -c 'strace -e trace=clock_gettime ./hello_systems 2>&1 >/dev/null | grep -c "^clock_gettime" || true'0learner@ksa:~/gl-c01/m01-l01strace -e trace=getpid ./hello_systems 2>&1 >/dev/null | grep -c '^getpid('2000learner@ksa:~/gl-c01/m01-l01rm -f hello_systemslearner@ksa:~/gl-c01/m01-l01Tracing the Execution Split, Pitfalls & Practice
Look closely at what ./hello_systems and strace just proved on Linux 6.12. Initializing struct course_banner and calling strlen(b.code) ran strictly inside unprivileged Ring 3 against virtual stack pages above 0x1000 (vaddr > 4096U). Next, 2,000 calls to clock_gettime(CLOCK_MONOTONIC, &probe) read the shared linux-vdso.so.1 kernel page directly in Ring 3, recording vdso_traps=0 under strace, whereas 2,000 raw syscall(SYS_getpid) calls crossed the hardware trap gate 2,000 times (getpid_traps=2000) and consumed substantially higher wall-clock time (trap_ns > vdso_ns).
Common Production Pitfalls
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.
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).
Guided Practice: Predicting Trap Counts Across Mixed Loops
Suppose you extend hello_systems.c with a loop of 500 iterations where each iteration calls memcpy(dst, src, 32), clock_gettime(CLOCK_MONOTONIC, &ts), and write(STDOUT_FILENO, "ok\n", 3) on an unbuffered descriptor. Before testing:
- Step 1 (Classify each call's ring boundary): Identify which of the three calls touches only
Ring 3stack/heap RAM, which reads thevDSOshared page, and which issues asyscall/svc #0trap—review the execution-path table above if unsure. - Step 2 (Compute exact
straceline counts): Predict the exact integer count printed bystrace -cformemcpy,clock_gettime, andwrite(0,0, and500), then verify by adding a10-iterationwrite(STDOUT_FILENO, ...)loop to a scratch copy ofhello_systems.c.
Independent Practice: Trap-Amortization Breakeven Estimator
Write a standalone C11 program trap_budget.c compiled with -std=c11 -O2 -Wall -Wextra -Werror that measures the median per-call latency (across N = 10,000 iterations using CLOCK_MONOTONIC) of (a) a pure Ring 3 byte-accumulation function over a 64-byte array, (b) clock_gettime(CLOCK_MONOTONIC), and (c) syscall(SYS_getpid). Print the measured ratio trap_ns / vdso_ns, and calculate how many 16-byte sensor records must be batched into one 4,096-byte buffer so privilege-switch time stays below 1% of a 1 ms sampling budget.
Knowledge Check
? check 1 · 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?
- [ ] The Linux kernel maps physical MMIO into every process so
main()can retrieve register bits without review - [x] The MMU blocks the unprivileged
Ring 3/EL0virtual-memory access and deliversSIGSEGV, leaving hardware state intact - [ ]
gcc -std=c11rewrites raw pointer dereferences intostruct file_operationsdriver calls at compile time
Answer: The MMU blocks the unprivileged Ring 3 / EL0 virtual-memory access and delivers SIGSEGV, leaving hardware state intact
Why: 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.
? check 2 · How do user-space C applications and Linux kernel character drivers cooperate when controlling a /dev/led0 device node?
- [x] User space invokes uniform VFS system calls, and the Linux kernel dispatches
.writeor.ioctlin the driver'sstruct file_operationsusingcopy_from_user()to retrieve caller data safely - [ ] The driver directly dereferences unvalidated user pointers without review because
Ring 0trusts allRing 3addresses - [ ] Application
.cfiles include kernel driver headers and link into a single bare-metal image
Answer: User space invokes uniform VFS system calls, and the Linux kernel dispatches .write or .ioctl in the driver's struct file_operations using copy_from_user() to retrieve caller data safely
Why: 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.
? check 3 · 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)?
- [ ] Only regular disk files use integer descriptors; sockets and
/devnodes require unrelated handle types - [x] The Linux kernel exposes regular files, pipes, sockets, and
/devcharacter devices through the same integer descriptor model and VFS syscall boundary - [ ]
GL-C01requires writing custom kernel modules before compiling any user-space C binary
Answer: The Linux kernel exposes regular files, pipes, sockets, and /dev character devices through the same integer descriptor model and VFS syscall boundary
Why: 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.
? check 4 · 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?
- [ ]
clock_gettime()expands to a compile-time constant integer macro inside<time.h> - [x] The Linux kernel maps
linux-vdso.so.1(AT_SYSINFO_EHDR) as a read-only shared page soclock_gettime()can retrieve timekeeper sequence counters directly inRing 3/EL0with zero privilege-switching traps - [ ]
stracesuppresses section-2 calls that complete faster than1microsecond
Answer: The Linux kernel maps linux-vdso.so.1 (AT_SYSINFO_EHDR) as a read-only shared page so clock_gettime() can retrieve timekeeper sequence counters directly in Ring 3 / EL0 with zero privilege-switching traps
Why: 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.
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.
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.
Step sequence — frame strip: steps_m01_l01
Raw MMIO dereferences in Ring 3 fault immediately in the MMU (SIGSEGV), protecting sibling processes and silicon.
reveals: step1
highlights: step1
Pure Ring 3 C helpers and linux-vdso.so.1 clock_gettime() execute in user virtual memory with zero kernel traps.
reveals: step2
highlights: step2
System calls issue a synchronous syscall / svc #0 CPU trap across the ABI gate into Ring 0.
reveals: step3
highlights: step3
VFS dispatches file and /dev operations to driver struct file_operations callbacks using copy_from_user().
reveals: step4
highlights: step4
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.
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 payload_len is a signed int, paired with size_t n = read(fd, buf, cap); and open(path, O_CREAT | O_WRONLY, 644). Under -O0 unit tests on small ASCII inputs, every line appears to work. Under -O2 in production, GCC deletes the signed-overflow check completely—allowing an attacker passing INT_MAX - 4 to allocate a 12-byte heap buffer for a 2 GiB copy—while a -1 read() failure wraps unsigned size_t n to 18,446,744,073,709,551,615 (SIZE_MAX), and decimal 644 stamps sticky bit 01204 (--w----r-T) onto disk!
Naive C habits fail because developers conflate hardware assembly behavior with the abstract machine specified by ISO/IEC 9899:2011 (ISO C11), rely on IDE build buttons that hide linker flags and archive ordering, and guess header contracts instead of reading manual sections. Writing reliable Ring 3 systems code requires deterministic command-line builds, exact POSIX boundary types, and zero tolerance for Undefined Behavior (UB).
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.
definition (Four-Stage GCC Pipeline, Feature Macros & C11 UB): 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.
One Layer Down: ELF Object Sections, Alignment Math & Link Order
Across Stage 3 (gcc -c), the assembler partitions each relocatable .o file into distinct ELF sections: .text (machine instructions), .rodata (string literals and const tables), .data (initialized globals), .bss (Block Started by Symbol: zero-initialized globals occupying zero on-disk bytes), and .symtab + .rela.text relocation records. In ISO C11, writing int g_status; at file scope without extern is a tentative definition; GCC 10+ enables -fno-common by default, emitting a strong .bss definition in every .o that includes such a header and failing at link time with multiple definition. Declare extern int g_status; in .h headers, define it once in one .c file, and mark file-private helpers static (STB_LOCAL in nm / readelf -sW). Furthermore, the GNU linker resolves static .a archives in a single left-to-right pass, so gcc main.o -L. -lsysbuf succeeds whereas gcc -L. -lsysbuf main.o leaves main.o's symbols unresolved!
Struct layout and boundary sizing obey exact binary alignment arithmetic. Every scalar type of alignment A = 2^k bytes must start at a byte offset O satisfying O_aligned = (O + A - 1) & ~(A - 1). Inside struct padded_hdr { uint8_t tag; uint32_t seq; uint16_t flags; }, tag occupies byte 0, seq (A = 4) rounds offset 1 up to (1 + 3) & ~3 = 4 (inserting 3 padding bytes [1..3]), flags (A = 2) lands at byte 8, and total sizeof(struct padded_hdr) rounds 10 up to a multiple of max(A) = 4, yielding 12 bytes! Likewise, decimal 644 equals 512 + 128 + 4 = 01204 in octal, whereas octal 0644 equals 6 * 64 + 4 * 8 + 4 * 1 = 420 in base 10 (rw-r--r--).
| Type / Category | C11 / POSIX Specification | Exact Bit / Sign Contract & Engineering Rule |
|---|---|---|
size_t / ssize_t | Unsigned capacity vs signed return | size_t (%zu) sizes buffers; ssize_t (%zd) holds 0..SSIZE_MAX or -1 error |
off_t (_FILE_OFFSET_BITS=64) | Signed 64-bit byte coordinate | Addresses up to 2^63 - 1 (8 EiB) on both 64-bit x86-64 and 32-bit ARMv7 |
mode_t & uint8_t | Octal permission mask & raw byte | Write leading-zero 0644 (never 644); pass (const uint8_t *, len), never strlen() |
man 1 / man 2 / man 3 | Linux manual sections | 1 shell utilities, 2 Linux kernel syscalls, 3 glibc library functions |
| Implementation-Defined | Documented target ABI choice | Plain char is unsigned [0..255] on ARMv7 EABI vs signed [-128..127] on x86-64 |
Undefined Behavior (UB) | Unreachable on valid paths | Signed overflow (a + b < a folded to 0 at -O2), shift >= width, -fstrict-aliasing casts |
Figure 1.2. Four-stage GCC/archive builds, struct padded_hdr byte-alignment math, and signed/unsigned POSIX boundary contracts.
- Step 1. Stage 1 (-E) — Define _POSIX_C_SOURCE and _FILE_OFFSET_BITS=64 on lines 1..2 before any header is included.
- Step 2. Stage 2 (-S -O2) — Compile strict C11 to assembly; use unsigned subtraction so -O2 never deletes signed-overflow guards.
- Step 3. Stage 3 (-c & ar rcs) — Emit ELF .text/.rodata/.data/.bss sections under -fno-common and index static .a archives.
- Step 4. Stage 4 (ld + ASan/UBSan) — Place -lsysbuf after caller .o files and gate CI with -fsanitize=address,undefined.
Figure 1.2b. Feature-test macros, strict C11 warning/sanitizer flags, and single-pass archive link ordering eliminate silent type and symbol bugs at build time.
Feature-Test Macros,Incremental Make & Sanitizer Flags
Under strict -std=c11, GCC defines __STRICT_ANSI__ and hides POSIX symbols (fileno, pread, fdatasync, strnlen) inside <stdio.h> and <unistd.h> unless #define _POSIX_C_SOURCE 200809L and #define _FILE_OFFSET_BITS 64 appear before the very first #include in every translation unit. Pair -Wall -Wextra -Werror with -MMD -MP in GNU Make so header edits trigger automatic rebuilds, and run CI tests under AddressSanitizer and UndefinedBehaviorSanitizer (-fsanitize=address,undefined -fno-omit-frame-pointer).
learner@ksa:~/gl-c01/m01-l02$ bat -H 2 -H 9 -H 12 Makefile File: Makefile CC := gcc CFLAGS := -std=c11 -Wall -Wextra -Werror -MMD -MP -g -O2 SAN := -fsanitize=address,undefined -fno-omit-frame-pointer .PHONY: all sanitize clean all: inspector libsysbuf.a: sysbuf.o ar rcs $@ $^ inspector: inspector.o libsysbuf.a $(CC) $(CFLAGS) inspector.o -L. -lsysbuf -o $@ sanitize: sysbuf.c inspector.c $(CC) $(CFLAGS) $(SAN) inspector.c sysbuf.c -o inspector_san -include *.d clean: rm -f *.o *.d *.a inspector inspector_san- -MMD -MP emits .d header dependency rules so editing a .h struct layout rebuilds affected .o files automatically.
- ar rcs creates static archive libsysbuf.a and writes the symbol index table required by ld.
- Place -lsysbuf AFTER inspector.o so the single-pass linker resolves inspector.o's undefined references.
Auditing Binary Frames, Struct Padding, Strict Aliasing & Octal Modes
Save type_bridge.c below. It proves seven foundational systems C contracts in one sanitizer-clean binary: sizeof(raw_frame) (16) vs strlen() truncating at embedded 0x00 (2), array-to-pointer decay (sizeof(buf_ptr) == sizeof(void *)), unsigned subtraction capacity checks (safe_frame_fits), 64-bit off_t, octal 0644 (420) vs decimal 644 (01204), offsetof()/alignof() padding math, and -fstrict-aliasing-safe float -> uint32_t bit extraction via memcpy() (compiled to a single register move at -O2).
learner@ksa:~/gl-c01/m01-l02$ bat -H 1 -H 2 -H 23 -H 29 type_bridge.c File: type_bridge.c #define _FILE_OFFSET_BITS 64 #define _POSIX_C_SOURCE 200809L #include <stdalign.h> #include <stddef.h> #include <stdint.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <sys/stat.h> #include <sys/types.h> struct padded_hdr { uint8_t tag; uint32_t seq; uint16_t flags; }; static size_t pointer_sizeof(const uint8_t *buf_ptr) { return sizeof(buf_ptr); } static uint32_t pun_float_bits(float v) { uint32_t bits = 0U; memcpy(&bits, &v, sizeof(bits)); return bits; } static int safe_frame_fits(size_t payload, size_t hdr_sz, size_t cap) { return (hdr_sz <= cap) && (payload <= cap - hdr_sz); } int main(void) { const uint8_t raw_frame[16] = { 0x4BU, 0x53U, 0x00U, 0x41U, 0x10U, 0x20U, 0x30U, 0x40U }; size_t arr_bytes = sizeof(raw_frame); size_t cstr_len = strlen((const char *)raw_frame); size_t ptr_bytes = pointer_sizeof(raw_frame); mode_t oct_mode = 0644; mode_t dec_bug = 644; uint32_t fbits = pun_float_bits(1.0f); int ovf_rejected = !safe_frame_fits(SIZE_MAX - 4U, 12U, 4096U); printf("arr_sizeof=%zu strlen_at_nul=%zu ptr_decayed=%d ovf_guard=%d\n", arr_bytes, cstr_len, ptr_bytes != arr_bytes && ptr_bytes == sizeof(void *), ovf_rejected); printf("ssize_signed=%d off_bits=%zu oct_0644=%u dec_644_oct=0%o\n", (ssize_t)-1 < 0, sizeof(off_t) * 8U, (unsigned int)oct_mode, (unsigned int)dec_bug); printf("hdr_sz=%zu seq_off=%zu align=%zu f32_hex=0x%08x\n", sizeof(struct padded_hdr), offsetof(struct padded_hdr, seq), alignof(struct padded_hdr), fbits); return EXIT_SUCCESS; }- Feature-test macros MUST precede every #include so <features.h> exposes 64-bit off_t and POSIX.1-2008 prototypes.
- memcpy(&bits, &v, sizeof(bits)) extracts IEEE-754 bits legally under C11 -fstrict-aliasing and compiles to zero memory traffic at -O2.
- Unsigned subtraction cap - hdr_sz avoids signed integer overflow UB that GCC -O2 would fold away.
Stepping Through All Four GCC Stages, nm & Sanitizers
Execute all four GCC translation stages (-E, -S, -c, and final link with -fsanitize=address,undefined), inspect symbol visibility in type_bridge.o with nm (t local static helpers vs T global main), and verify ./type_bridge.
learner@ksa:~/gl-c01/m01-l02gcc -fdiagnostics-color=always -std=c11 -Wall -Wextra -Werror -E type_bridge.c -o type_bridge.ilearner@ksa:~/gl-c01/m01-l02gcc -fdiagnostics-color=always -std=c11 -Wall -Wextra -Werror -S type_bridge.c -o type_bridge.slearner@ksa:~/gl-c01/m01-l02gcc -fdiagnostics-color=always -std=c11 -Wall -Wextra -Werror -c type_bridge.c -o type_bridge.olearner@ksa:~/gl-c01/m01-l02nm type_bridge.o | grep -c ' T main$'1learner@ksa:~/gl-c01/m01-l02gcc -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_bridgearr_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-l02Why Strict Types, Visibility & Sanitizers Catch Silent Corruption
Stepping across .i -> .s -> .o -> ELF proved each layer's contract empirically. In type_bridge.o, nm reported main as T (STB_GLOBAL in .text) while static helpers stayed module-private so they cannot collide across .o files. At runtime under ASan + UBSan, raw_frame occupied 16 stack bytes while strlen() stopped at raw_frame[2] == 0x00 (2), pointer_sizeof() confirmed array-to-pointer decay (8 bytes on 64-bit), struct padded_hdr measured 12 bytes (seq_off=4, align=4), safe_frame_fits() blocked SIZE_MAX - 4U + 12U wraparound without UB, and memcpy() extracted 0x3f800000 (1.0f) cleanly.
Guided Practice: Reordering Struct Fields & Fixing Aliasing UB
Examine struct padded_hdr (12 bytes: uint8_t tag; uint32_t seq; uint16_t flags;) and the broken strict-aliasing cast uint32_t bad = *(uint32_t *)&float_val;:
- Step 1 (Eliminate internal padding): Reorder the three members of
struct padded_hdrfrom largest alignment (uint32_t) to smallest (uint8_t) without adding non-portable__attribute__((packed))(which causes unaligned bus faults on strict ARM hardware), and compute the newsizeof(struct compact_hdr)(8bytes) using the alignment formula above. - Step 2 (Verify with
_Static_assert): Add_Static_assert(sizeof(struct compact_hdr) == 8, "compact layout");in a local copy oftype_bridge.c, replace any pointer-cast punning withmemcpy(), and confirmgcc -std=c11 -O2 -Wall -Wextra -Werrorexits0.
Independent Practice: Static Archive Link-Order & -fno-common Audit
Create three files (frame.h, frame.c, driver_cli.c) where frame.h declares extern size_t g_frames_encoded; and size_t encode_u32_be(uint8_t *dst, size_t cap, uint32_t val); (writing big-endian bytes via unsigned shifts val >> 24, (val >> 16) & 0xFFU, etc.). Archive frame.o into libframe.a via ar rcs, confirm nm -g libframe.a lists encode_u32_be and g_frames_encoded, verify that wrong link order (gcc -L. -lframe driver_cli.o) fails while gcc driver_cli.o -L. -lframe succeeds, and run under -fsanitize=address,undefined.
Common Production Pitfalls
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).
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.
Knowledge Check
? check 1 · 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?
- [ ]
man 1 writeto retrieve user shell command documentation - [x]
man 2 writeto retrieve Linux kernel system call specifications - [ ]
man 3 writeto review pure C string formatting helpers
Answer: man 2 write to retrieve Linux kernel system call specifications
Why: 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.
? check 2 · (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()?
- [x]
-cstops after Stage 3 (assembly) to emit a relocatable.oobject file; symbol resolution for_startandmain()happens only at Stage 4 (linking) - [ ]
-cinjects a syntheticRing 0struct file_operationsentry point when you review.text - [ ]
ar rcssynthesizes a defaultmain()inside static.aarchives
Answer: -c stops after Stage 3 (assembly) to emit a relocatable .o object file; symbol resolution for _start and main() happens only at Stage 4 (linking)
Why: 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.
? check 3 · What permission bitmask is produced in C if a developer writes mode_t m = 644; instead of mode_t m = 0644;?
- [ ] Standard
rw-r--r--(0644), becausemode_tparses integer digits in base 8 automatically - [ ]
rwxrwxrwx(0777), because integers above511saturate all permission bits - [x] Octal
01204(--w----r-T: sticky bit + owner write + other read, missing owner read!), because644without a leading0is base-10644
Answer: Octal 01204 (--w----r-T: sticky bit + owner write + other read, missing owner read!), because 644 without a leading 0 is base-10 644
Why: 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.
? check 4 · 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?
- [ ] Because
16is smaller thanalignof(max_align_t)on 64-bit Linux - [x] Because signed
intoverflow is ISO C11 Undefined Behavior, permitting-O2to assumepayload_len + 16never wraps negative and fold< payload_lento0 - [ ] Because
-O2automatically widens 32-bitintarithmetic to 128-bit registers
Answer: Because signed int overflow is ISO C11 Undefined Behavior, permitting -O2 to assume payload_len + 16 never wraps negative and fold < payload_len to 0
Why: 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.
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().
Next, we will link C11 translation units against glibc (libc.so.6), trace dynamic .plt/.got.plt relocations and C Runtime (CRT) _start initialization, inspect errno, and count exact traps under strace.
Step sequence — frame strip: steps_m01_l02
Stage 1 (-E) — Define _POSIX_C_SOURCE and _FILE_OFFSET_BITS=64 on lines 1..2 before any header is included.
reveals: step1
highlights: step1
Stage 2 (-S -O2) — Compile strict C11 to assembly; use unsigned subtraction so -O2 never deletes signed-overflow guards.
reveals: step2
highlights: step2
Stage 3 (-c & ar rcs) — Emit ELF .text/.rodata/.data/.bss sections under -fno-common and index static .a archives.
reveals: step3
highlights: step3
Stage 4 (ld + ASan/UBSan) — Place -lsysbuf after caller .o files and gate CI with -fsanitize=address,undefined.
reveals: step4
highlights: step4
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).
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. First, you copy a freshly cross-compiled ./sensor_agent binary onto a minimal ARMv7 root filesystem, verify -rwxr-xr-x permissions with ls -l, execute ./sensor_agent, and the shell prints No such file or directory (ENOENT) for a file sitting right in front of you! Second, inside a running service, a developer writes errno = 0; write(fd, buf, 8); printf("ok\n"); if (errno != 0) abort();—and the service aborts with Inappropriate ioctl for device (ENOTTY) whenever stdout is redirected to a log file, even though write() succeeded!
Both failures stem from treating main() and <stdio.h>/<unistd.h> as black boxes. Execution of a dynamically linked Executable and Linkable Format (ELF) binary begins inside the kernel's PT_INTERP dynamic loader (ld-linux) and C Runtime (CRT) _start preamble long before main(), while the GNU C Library (glibc, libc.so.6) mixes pure Ring 3 RAM algorithms, buffered stream helpers, and thin Ring 0 syscall wrappers that leave thread-local errno untouched on success.
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.
definition (CRT Startup, PLT/GOT Trampolines & Syscall Wrappers): 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.
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_READ), and .data/.bss (PROT_READ | PROT_WRITE virtual memory areas), opens the interpreter path named in the PT_INTERP program header (such as /lib64/ld-linux-x86-64.so.2 or /lib/ld-linux-armhf.so.3—returning ENOENT if that loader file is missing!), and constructs the initial user stack (16-byte aligned on x86-64 System V; 8-byte aligned on ARMv7 AAPCS): argc, argv[0..argc-1], NULL, envp[0..M-1], NULL, and Elf_auxv_t (key, val) pairs (AT_PAGESZ, AT_SYSINFO_EHDR). _start hands main to __libc_start_main(), which initializes Thread-Local Storage (TLS) for errno, executes .init_array constructors, invokes main(argc, argv, envp) with STDIN_FILENO (0), STDOUT_FILENO (1), and STDERR_FILENO (2) pre-opened, and passes main's return value (status & 0xFF) through .fini_array/atexit() to exit_group().
Why does the Linux kernel reserve [-4095, -1] (0xfffffffffffff001..0xffffffffffffffff on 64-bit) in %rax / r0 for syscall errors instead of returning -1 directly? Because valid virtual addresses and byte counts can occupy nearly the entire unsigned register space except the final 4,095 bytes of the top kernel guard page! Inside every glibc syscall wrapper, one unsigned comparison is_err(r) <==> (unsigned long)r > (unsigned long)(-4096L) tests for error. When true, glibc computes *__errno_location() = (int)(-r) (for example, -(-9) == EBADF) and returns -1; when false (r >= 0), glibc returns r without touching errno.
libc.so.6 / ELF Layer | Concrete Symbols | Kernel Trap Count | Error & Inspection Mechanism |
|---|---|---|---|
Pure Ring 3 library helper | strlen(), memcpy(), strtol(), snprintf() | 0 traps | Operates strictly in user RAM; invisible to strace |
Ring 0 syscall wrapper | write(), read(), openat(), close() | 1 trap per call | r in [-4095,-1] sets TLS errno, returns -1; 1:1 in strace |
Buffered stdio stream | printf(), fwrite(), fputs() | 1 trap per buffer flush | Batches into FILE heap buffer (4..8 KiB) before write() |
.plt / .got.plt & PT_INTERP | write@plt, R_*_JUMP_SLOT, ld-linux | Loader openat/mmap at start | Inspect via readelf -l -rW, objdump -d, LD_DEBUG=bindings |
Figure 1.3. ELF PT_INTERP and crt1.o _start startup chain, PLT/GOT dynamic linkage, and [-4095, -1] thread-local errno demultiplexing.
- Step 1. execve() builds the 16-byte aligned stack (argc, argv, envp, auxv) and loads PT_INTERP (missing loader => ENOENT).
- Step 2. crt1.o _start invokes __libc_start_main(), initializes TLS errno, runs .init_array constructors, and calls main().
- Step 3. Pure Ring 3 helpers run in RAM (0 traps), whereas write@plt jumps via .got.plt into libc's syscall instruction.
- Step 4. Kernel returns in [-4095, -1] populate thread-local errno and return -1; successful calls leave errno untouched.
Figure 1.3b. 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.
Inspecting Standard Descriptors, GOT/PLT Relocations & errno
Include <unistd.h>, <errno.h>, <stdio.h>, and <string.h> under #define _POSIX_C_SOURCE 200809L. Every POSIX process inherits STDIN_FILENO (0), STDOUT_FILENO (1), and STDERR_FILENO (2). When ssize_t write(int fd, const void *buf, size_t count) returns -1, capture int saved_err = errno; on the very next line (EBADF 9 indicates a closed or negative descriptor; EINTR 4 indicates a signal interrupted a blocked call before any byte moved) and format diagnostics via perror() or strerror(). Because external calls route through .plt/.got.plt, engineers can also interpose fault-injection shims without recompiling via LD_PRELOAD or at link time via gcc -Wl,--wrap=write.
Probing .init_array Constructors, Pure Loops, EBADF & strace
Save crt_wrapper_probe.c below. It registers an __attribute__((constructor)) function inside .init_array (on_crt_init) to prove __libc_start_main() executes constructors before main(), verifies argv[argc] == NULL and getpagesize() via <unistd.h>, executes 1,000 pure Ring 3 strlen() calls (0 traps), deliberately triggers write(-1, "X", 1U) to verify bad_rc == -1 && saved_err == EBADF, formats a report in Ring 3 via snprintf(), and emits it through an EINTR-safe write_all_fd(STDOUT_FILENO, ...) loop.
learner@ksa:~/gl-c01/m01-l03$ bat -H 12 -H 21 -H 39 -H 40 crt_wrapper_probe.c File: crt_wrapper_probe.c #define _POSIX_C_SOURCE 200809L #include <errno.h> #include <gnu/libc-version.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <unistd.h> static int g_ctor_ran = 0; __attribute__((constructor)) static void on_crt_init(void) { g_ctor_ran = 1; } static int write_all_fd(int fd, const char *buf, size_t len) { size_t sent = 0U; while (sent < len) { ssize_t n = write(fd, buf + sent, len - sent); if (n < 0) { if (errno == EINTR) { continue; } return -1; } sent += (size_t)n; } return 0; } int main(int argc, char *argv[]) { const char *arg1 = (argc > 1) ? argv[1] : "none"; size_t acc = 0U; for (int i = 0; i < 1000; i++) { acc += strlen(arg1); } errno = 0; ssize_t bad_rc = write(-1, "X", 1U); int saved_err = errno; int ebadf_ok = (bad_rc == -1 && saved_err == EBADF && strlen(strerror(saved_err)) > 0U); char line[192]; const char *fmt = "glibc=%s ctor=%d argc=%d pure_acc=%zu " "argv_null=%d ebadf_ok=%d\n"; int n = snprintf(line, sizeof(line), fmt, gnu_get_libc_version(), g_ctor_ran, argc, acc, argv[argc] == NULL, ebadf_ok); if (n < 0 || (size_t)n >= sizeof(line)) { return EXIT_FAILURE; } if (write_all_fd(STDOUT_FILENO, line, (size_t)n) == -1) { perror("write stdout"); return EXIT_FAILURE; } return EXIT_SUCCESS; }- __attribute__((constructor)) places a function pointer into ELF .init_array, invoked by __libc_start_main() before main().
- Retry write() when n < 0 && errno == EINTR; advance buf + sent on any short positive count.
- Save errno into saved_err immediately after bad_rc == -1 so later snprintf() or stdio calls cannot clobber it.
Verifying PT_INTERP, JUMP_SLOT Relocations, strace & Lab 1
Compile crt_wrapper_probe, verify PT_INTERP and write's .got.plt JUMP_SLOT relocation with readelf, and confirm under strace that 1,000 strlen() calls + 1 snprintf() call emit zero syscalls while write fires exactly twice (write(-1, ...) -> -1 EBADF and write(1, ...) -> 62). Then complete lab_m01_toolchain_tracer.
learner@ksa:~/gl-c01/m01-l03gcc -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=$?glibc=2.39 ctor=1 argc=2 pure_acc=8000 argv_null=1 ebadf_ok=1exit_status=0learner@ksa:~/gl-c01/m01-l03ldd ./crt_wrapper_probe | grep -o 'libc\.so\.6' | head -n 1libc.so.6learner@ksa:~/gl-c01/m01-l03readelf -lW ./crt_wrapper_probe | grep -c 'Requesting program interpreter'1learner@ksa:~/gl-c01/m01-l03readelf -rW ./crt_wrapper_probe | grep -c 'JUMP_SLOT.*write'1learner@ksa:~/gl-c01/m01-l03strace -e trace=write ./crt_wrapper_probe frame-07 2>&1 >/dev/null | grep -c '^write('2learner@ksa:~/gl-c01/m01-l03Inspect the recorded strace session: ld-linux maps /etc/ld.so.cache and libc.so.6 first, the 1,000-iteration strlen() loop produces zero trace lines, write(-1, "X", 1) fails with EBADF, and write(1, ...) flushes the summary line before +++ exited with 0 +++.
learner@ksa:~/gl-c01/m01-l03strace strace -e trace=openat,write,close \./crt_wrapper_probe frame-07execve("/usr/bin/strace", ["strace", "-e", "trace=openat,write,close", "./crt_wrapper_probe", "frame-07"], 0x7ffc2d34d990 /* 161 vars */) = 0brk(NULL) = 0x63149dedd000mmap(NULL, 8192, PROT_READ|PROT_WRITE, MAP_PRIVATE|MAP_ANONYMOUS, -1, 0) = 0x7bf2ffcb2000access("/etc/ld.so.preload", R_OK) = -1 ENOENT (No such file or directory)openat(AT_FDCWD, "/etc/ld.so.cache", O_RDONLY|O_CLOEXEC) = 3fstat(3, {st_mode=S_IFREG|0644, st_size=147944, ...}) = 0mmap(NULL, 147944, PROT_READ, MAP_PRIVATE, 3, 0) = 0x7bf2ffc8d000close(3) = 0openat(AT_FDCWD, "/lib/x86_64-linux-gnu/libunwind-ptrace.so.0", O_RDONLY|O_CLOEXEC) = 3read(3, "\177ELF\2\1\1\0\0\0\0\0\0\0\0\0\3\0>\0\1\0\0\0\0\0\0\0\0\0\0\0"..., 832) = 832fstat(3, {st_mode=S_IFREG|0644, st_size=18656, ...}) = 0mmap(NULL, 20808, PROT_READ, MAP_PRIVATE|MAP_DENYWRITE, 3, 0) = 0x7bf2ffc87000mmap(0x7bf2ffc88000, 8192, PROT_READ|PROT_EXEC, MAP_PRIVATE|MAP_FIXED|MAP_DENYWRITE, 3, 0x1000) = 0x7bf2ffc88000mmap(0x7bf2ffc8a000, 4096, PROT_READ, MAP_PRIVATE|MAP_FIXED|MAP_DENYWRITE, 3, 0x3000) = 0x7bf2ffc8a000mmap(0x7bf2ffc8b000, 8192, PROT_READ|PROT_WRITE, MAP_PRIVATE|MAP_FIXED|MAP_DENYWRITE, 3, 0x3000) = 0x7bf2ffc8b000close(3) = 0openat(AT_FDCWD, "/lib/x86_64-linux-gnu/libunwind-x86_64.so.8", O_RDONLY|O_CLOEXEC) = 3read(3, "\177ELF\2\1\1\0\0\0\0\0\0\0\0\0\3\0>\0\1\0\0\0\0\0\0\0\0\0\0\0"..., 832) = 832fstat(3, {st_mode=S_IFREG|0644, st_size=67672, ...}) = 0mmap(NULL, 113136, PROT_READ, MAP_PRIVATE|MAP_DENYWRITE, 3, 0) = 0x7bf2ffc6b000mmap(0x7bf2ffc6d000, 49152, PROT_READ|PROT_EXEC, MAP_PRIVATE|MAP_FIXED|MAP_DENYWRITE, 3, 0x2000) = 0x7bf2ffc6d000mmap(0x7bf2ffc79000, 8192, PROT_READ, MAP_PRIVATE|MAP_FIXED|MAP_DENYWRITE, 3, 0xe000) = 0x7bf2ffc79000mmap(0x7bf2ffc7b000, 8192, PROT_READ|PROT_WRITE, MAP_PRIVATE|MAP_FIXED|MAP_DENYWRITE, 3, 0xf000) = 0x7bf2ffc7b000mmap(0x7bf2ffc7d000, 39408, PROT_READ|PROT_WRITE, MAP_PRIVATE|MAP_FIXED|MAP_ANONYMOUS, -1, 0) = 0x7bf2ffc7d000close(3) = 0openat(AT_FDCWD, "/lib/x86_64-linux-gnu/libc.so.6", O_RDONLY|O_CLOEXEC) = 3read(3, "\177ELF\2\1\1\3\0\0\0\0\0\0\0\0\3\0>\0\1\0\0\0\220\243\2\0\0\0\0\0"..., 832) = 832pread64(3, "\6\0\0\0\4\0\0\0@\0\0\0\0\0\0\0@\0\0\0\0\0\0\0@\0\0\0\0\0\0\0"..., 784, 64) = 784fstat(3, {st_mode=S_IFREG|0755, st_size=2129424, ...}) = 0pread64(3, "\6\0\0\0\4\0\0\0@\0\0\0\0\0\0\0@\0\0\0\0\0\0\0@\0\0\0\0\0\0\0"..., 784, 64) = 784mmap(NULL, 2174352, PROT_READ, MAP_PRIVATE|MAP_DENYWRITE, 3, 0) = 0x7bf2ffa00000mmap(0x7bf2ffa28000, 1609728, PROT_READ|PROT_EXEC, MAP_PRIVATE|MAP_FIXED|MAP_DENYWRITE, 3, 0x28000) = 0x7bf2ffa28000mmap(0x7bf2ffbb1000, 323584, PROT_READ, MAP_PRIVATE|MAP_FIXED|MAP_DENYWRITE, 3, 0x1b1000) = 0x7bf2ffbb1000mmap(0x7bf2ffc00000, 24576, PROT_READ|PROT_WRITE, MAP_PRIVATE|MAP_FIXED|MAP_DENYWRITE, 3, 0x1ff000) = 0x7bf2ffc00000mmap(0x7bf2ffc06000, 52624, PROT_READ|PROT_WRITE, MAP_PRIVATE|MAP_FIXED|MAP_ANONYMOUS, -1, 0) = 0x7bf2ffc06000close(3) = 0openat(AT_FDCWD, "/lib/x86_64-linux-gnu/liblzma.so.5", O_RDONLY|O_CLOEXEC) = 3read(3, "\177ELF\2\1\1\0\0\0\0\0\0\0\0\0\3\0>\0\1\0\0\0\0\0\0\0\0\0\0\0"..., 832) = 832fstat(3, {st_mode=S_IFREG|0644, st_size=202904, ...}) = 0mmap(NULL, 200728, PROT_READ, MAP_PRIVATE|MAP_DENYWRITE, 3, 0) = 0x7bf2ffc39000mmap(0x7bf2ffc3c000, 139264, PROT_READ|PROT_EXEC, MAP_PRIVATE|MAP_FIXED|MAP_DENYWRITE, 3, 0x3000) = 0x7bf2ffc3c000mmap(0x7bf2ffc5e000, 45056, PROT_READ, MAP_PRIVATE|MAP_FIXED|MAP_DENYWRITE, 3, 0x25000) = 0x7bf2ffc5e000mmap(0x7bf2ffc69000, 8192, PROT_READ|PROT_WRITE, MAP_PRIVATE|MAP_FIXED|MAP_DENYWRITE, 3, 0x30000) = 0x7bf2ffc69000close(3) = 0openat(AT_FDCWD, "/lib/x86_64-linux-gnu/libunwind.so.8", O_RDONLY|O_CLOEXEC) = 3read(3, "\177ELF\2\1\1\0\0\0\0\0\0\0\0\0\3\0>\0\1\0\0\0\0\0\0\0\0\0\0\0"..., 832) = 832fstat(3, {st_mode=S_IFREG|0644, st_size=63776, ...}) = 0mmap(NULL, 109328, PROT_READ, MAP_PRIVATE|MAP_DENYWRITE, 3, 0) = 0x7bf2ffc1e000mmap(0x7bf2ffc21000, 40960, PROT_READ|PROT_EXEC, MAP_PRIVATE|MAP_FIXED|MAP_DENYWRITE, 3, 0x3000) = 0x7bf2ffc21000mmap(0x7bf2ffc2b000, 8192, PROT_READ, MAP_PRIVATE|MAP_FIXED|MAP_DENYWRITE, 3, 0xd000) = 0x7bf2ffc2b000mmap(0x7bf2ffc2d000, 8192, PROT_READ|PROT_WRITE, MAP_PRIVATE|MAP_FIXED|MAP_DENYWRITE, 3, 0xe000) = 0x7bf2ffc2d000mmap(0x7bf2ffc2f000, 39696, PROT_READ|PROT_WRITE, MAP_PRIVATE|MAP_FIXED|MAP_ANONYMOUS, -1, 0) = 0x7bf2ffc2f000close(3) = 0mmap(NULL, 8192, PROT_READ|PROT_WRITE, MAP_PRIVATE|MAP_ANONYMOUS, -1, 0) = 0x7bf2ffc1c000arch_prctl(ARCH_SET_FS, 0x7bf2ffc1d380) = 0set_tid_address(0x7bf2ffc1d650) = 2867173set_robust_list(0x7bf2ffc1d660, 24) = 0rseq(0x7bf2ffc1dca0, 0x20, 0, 0x53053053) = 0mprotect(0x7bf2ffc00000, 16384, PROT_READ) = 0mprotect(0x7bf2ffc69000, 4096, PROT_READ) = 0mprotect(0x7bf2ffc2d000, 4096, PROT_READ) = 0mprotect(0x7bf2ffc7b000, 4096, PROT_READ) = 0mprotect(0x7bf2ffc8b000, 4096, PROT_READ) = 0mprotect(0x63147f23a000, 417792, PROT_READ) = 0mprotect(0x7bf2ffcf2000, 8192, PROT_READ) = 0prlimit64(0, RLIMIT_STACK, NULL, {rlim_cur=8192*1024, rlim_max=RLIM64_INFINITY}) = 0munmap(0x7bf2ffc8d000, 147944) = 0getrandom("\x31\x7c\x75\xe8\x86\xc7\x2f\x48", 8, GRND_NONBLOCK) = 8brk(NULL) = 0x63149dedd000brk(0x63149defe000) = 0x63149defe000openat(AT_FDCWD, "/usr/lib/locale/locale-archive", O_RDONLY|O_CLOEXEC) = 3fstat(3, {st_mode=S_IFREG|0644, st_size=5719296, ...}) = 0mmap(NULL, 5719296, PROT_READ, MAP_PRIVATE, 3, 0) = 0x7bf2ff400000close(3) = 0openat(AT_FDCWD, "/usr/share/locale/locale.alias", O_RDONLY|O_CLOEXEC) = 3fstat(3, {st_mode=S_IFREG|0644, st_size=2996, ...}) = 0read(3, "# Locale name alias data base.\n#"..., 4096) = 2996read(3, "", 4096) = 0close(3) = 0openat(AT_FDCWD, "/usr/lib/locale/C.UTF-8/LC_IDENTIFICATION", O_RDONLY|O_CLOEXEC) = -1 ENOENT (No such file or directory)openat(AT_FDCWD, "/usr/lib/locale/C.utf8/LC_IDENTIFICATION", O_RDONLY|O_CLOEXEC) = 3fstat(3, {st_mode=S_IFREG|0644, st_size=258, ...}) = 0mmap(NULL, 258, PROT_READ, MAP_PRIVATE, 3, 0) = 0x7bf2ffcb1000close(3) = 0openat(AT_FDCWD, "/usr/lib/x86_64-linux-gnu/gconv/gconv-modules.cache", O_RDONLY|O_CLOEXEC) = 3fstat(3, {st_mode=S_IFREG|0644, st_size=27028, ...}) = 0mmap(NULL, 27028, PROT_READ, MAP_SHARED, 3, 0) = 0x7bf2ffcaa000close(3) = 0futex(0x7bf2ffc0572c, FUTEX_WAKE_PRIVATE, 2147483647) = 0openat(AT_FDCWD, "/usr/lib/locale/C.UTF-8/LC_MEASUREMENT", O_RDONLY|O_CLOEXEC) = -1 ENOENT (No such file or directory)openat(AT_FDCWD, "/usr/lib/locale/C.utf8/LC_MEASUREMENT", O_RDONLY|O_CLOEXEC) = 3fstat(3, {st_mode=S_IFREG|0644, st_size=23, ...}) = 0mmap(NULL, 23, PROT_READ, MAP_PRIVATE, 3, 0) = 0x7bf2ffca9000close(3) = 0openat(AT_FDCWD, "/usr/lib/locale/C.UTF-8/LC_TELEPHONE", O_RDONLY|O_CLOEXEC) = -1 ENOENT (No such file or directory)openat(AT_FDCWD, "/usr/lib/locale/C.utf8/LC_TELEPHONE", O_RDONLY|O_CLOEXEC) = 3fstat(3, {st_mode=S_IFREG|0644, st_size=47, ...}) = 0mmap(NULL, 47, PROT_READ, MAP_PRIVATE, 3, 0) = 0x7bf2ffca8000close(3) = 0openat(AT_FDCWD, "/usr/lib/locale/C.UTF-8/LC_ADDRESS", O_RDONLY|O_CLOEXEC) = -1 ENOENT (No such file or directory)openat(AT_FDCWD, "/usr/lib/locale/C.utf8/LC_ADDRESS", O_RDONLY|O_CLOEXEC) = 3fstat(3, {st_mode=S_IFREG|0644, st_size=127, ...}) = 0mmap(NULL, 127, PROT_READ, MAP_PRIVATE, 3, 0) = 0x7bf2ffca7000close(3) = 0openat(AT_FDCWD, "/usr/lib/locale/C.UTF-8/LC_NAME", O_RDONLY|O_CLOEXEC) = -1 ENOENT (No such file or directory)openat(AT_FDCWD, "/usr/lib/locale/C.utf8/LC_NAME", O_RDONLY|O_CLOEXEC) = 3fstat(3, {st_mode=S_IFREG|0644, st_size=62, ...}) = 0mmap(NULL, 62, PROT_READ, MAP_PRIVATE, 3, 0) = 0x7bf2ffca6000close(3) = 0openat(AT_FDCWD, "/usr/lib/locale/C.UTF-8/LC_PAPER", O_RDONLY|O_CLOEXEC) = -1 ENOENT (No such file or directory)openat(AT_FDCWD, "/usr/lib/locale/C.utf8/LC_PAPER", O_RDONLY|O_CLOEXEC) = 3fstat(3, {st_mode=S_IFREG|0644, st_size=34, ...}) = 0mmap(NULL, 34, PROT_READ, MAP_PRIVATE, 3, 0) = 0x7bf2ffca5000close(3) = 0openat(AT_FDCWD, "/usr/lib/locale/C.UTF-8/LC_MESSAGES", O_RDONLY|O_CLOEXEC) = -1 ENOENT (No such file or directory)openat(AT_FDCWD, "/usr/lib/locale/C.utf8/LC_MESSAGES", O_RDONLY|O_CLOEXEC) = 3fstat(3, {st_mode=S_IFDIR|0755, st_size=4096, ...}) = 0close(3) = 0openat(AT_FDCWD, "/usr/lib/locale/C.utf8/LC_MESSAGES/SYS_LC_MESSAGES", O_RDONLY|O_CLOEXEC) = 3fstat(3, {st_mode=S_IFREG|0644, st_size=48, ...}) = 0mmap(NULL, 48, PROT_READ, MAP_PRIVATE, 3, 0) = 0x7bf2ffca4000close(3) = 0openat(AT_FDCWD, "/usr/lib/locale/C.UTF-8/LC_MONETARY", O_RDONLY|O_CLOEXEC) = -1 ENOENT (No such file or directory)openat(AT_FDCWD, "/usr/lib/locale/C.utf8/LC_MONETARY", O_RDONLY|O_CLOEXEC) = 3fstat(3, {st_mode=S_IFREG|0644, st_size=270, ...}) = 0mmap(NULL, 270, PROT_READ, MAP_PRIVATE, 3, 0) = 0x7bf2ffca3000close(3) = 0openat(AT_FDCWD, "/usr/lib/locale/C.UTF-8/LC_COLLATE", O_RDONLY|O_CLOEXEC) = -1 ENOENT (No such file or directory)openat(AT_FDCWD, "/usr/lib/locale/C.utf8/LC_COLLATE", O_RDONLY|O_CLOEXEC) = 3fstat(3, {st_mode=S_IFREG|0644, st_size=1406, ...}) = 0mmap(NULL, 1406, PROT_READ, MAP_PRIVATE, 3, 0) = 0x7bf2ffca2000close(3) = 0openat(AT_FDCWD, "/usr/lib/locale/C.UTF-8/LC_TIME", O_RDONLY|O_CLOEXEC) = -1 ENOENT (No such file or directory)openat(AT_FDCWD, "/usr/lib/locale/C.utf8/LC_TIME", O_RDONLY|O_CLOEXEC) = 3fstat(3, {st_mode=S_IFREG|0644, st_size=3360, ...}) = 0mmap(NULL, 3360, PROT_READ, MAP_PRIVATE, 3, 0) = 0x7bf2ffca1000close(3) = 0openat(AT_FDCWD, "/usr/lib/locale/C.UTF-8/LC_NUMERIC", O_RDONLY|O_CLOEXEC) = -1 ENOENT (No such file or directory)openat(AT_FDCWD, "/usr/lib/locale/C.utf8/LC_NUMERIC", O_RDONLY|O_CLOEXEC) = 3fstat(3, {st_mode=S_IFREG|0644, st_size=50, ...}) = 0mmap(NULL, 50, PROT_READ, MAP_PRIVATE, 3, 0) = 0x7bf2ffca0000close(3) = 0openat(AT_FDCWD, "/usr/lib/locale/C.UTF-8/LC_CTYPE", O_RDONLY|O_CLOEXEC) = -1 ENOENT (No such file or directory)openat(AT_FDCWD, "/usr/lib/locale/C.utf8/LC_CTYPE", O_RDONLY|O_CLOEXEC) = 3fstat(3, {st_mode=S_IFREG|0644, st_size=360460, ...}) = 0mmap(NULL, 360460, PROT_READ, MAP_PRIVATE, 3, 0) = 0x7bf2ff9a7000close(3) = 0getpid() = 2867173uname({sysname="Linux", nodename="sabertooth", ...}) = 0openat(AT_FDCWD, "/proc/sys/kernel/pid_max", O_RDONLY) = 3read(3, "4194304\n", 23) = 8close(3) = 0rt_sigaction(SIGCHLD, {sa_handler=SIG_DFL, sa_mask=[], sa_flags=SA_RESTORER, sa_restorer=0x7bf2ffa45330}, {sa_handler=SIG_DFL, sa_mask=[], sa_flags=0}, 8) = 0getuid() = 1000getgid() = 1000clone(child_stack=NULL, flags=CLONE_CHILD_CLEARTID|CLONE_CHILD_SETTID|SIGCHLD, child_tidptr=0x7bf2ffc1d650) = 2867174ptrace(PTRACE_SEIZE, 2867174, NULL, 0) = 0kill(2867174, SIGKILL) = 0wait4(2867174, [{WIFSIGNALED(s) && WTERMSIG(s) == SIGKILL}], 0, NULL) = 2867174--- SIGCHLD {si_signo=SIGCHLD, si_code=CLD_KILLED, si_pid=2867174, si_uid=1000, si_status=SIGKILL, si_utime=0, si_stime=0} ---clone(child_stack=NULL, flags=CLONE_CHILD_CLEARTID|CLONE_CHILD_SETTID|SIGCHLD, child_tidptr=0x7bf2ffc1d650) = 2867175wait4(2867175, [{WIFSTOPPED(s) && WSTOPSIG(s) == SIGSTOP}], 0, NULL) = 2867175--- SIGCHLD {si_signo=SIGCHLD, si_code=CLD_TRAPPED, si_pid=2867175, si_uid=1000, si_status=SIGSTOP, si_utime=0, si_stime=0} ---ptrace(PTRACE_SETOPTIONS, 2867175, NULL, PTRACE_O_TRACESYSGOOD) = 0ptrace(PTRACE_GET_SYSCALL_INFO, 2867175, 88, {op=PTRACE_SYSCALL_INFO_NONE, arch=AUDIT_ARCH_X86_64, instruction_pointer=0x7bf2ffa4553b, stack_pointer=0x7fffc19333a8}) = 24ptrace(PTRACE_SYSCALL, 2867175, NULL, 0) = 0--- SIGCHLD {si_signo=SIGCHLD, si_code=CLD_TRAPPED, si_pid=2867175, si_uid=1000, si_status=SIGTRAP, si_utime=0, si_stime=0} ---wait4(2867175, [{WIFSTOPPED(s) && WSTOPSIG(s) == SIGTRAP | 0x80}], 0, NULL) = 2867175ptrace(PTRACE_GET_SYSCALL_INFO, 2867175, 88, {op=PTRACE_SYSCALL_INFO_ENTRY, arch=AUDIT_ARCH_X86_64, instruction_pointer=0x7bf2ffb274ed, stack_pointer=0x7fffc1933398, entry={nr=__NR_chdir, args=[0x63147f215d9a, 0xbad1fed1, 0xbad2fed2, 0xbad3fed3, 0xbad4fed4, 0xbad5fed5]}}) = 80ptrace(PTRACE_SYSCALL, 2867175, NULL, 0) = 0wait4(2867175, [{WIFSTOPPED(s) && WSTOPSIG(s) == SIGTRAP | 0x80}], 0, NULL) = 2867175--- SIGCHLD {si_signo=SIGCHLD, si_code=CLD_TRAPPED, si_pid=2867175, si_uid=1000, si_status=SIGTRAP, si_utime=0, si_stime=0} ---ptrace(PTRACE_GET_SYSCALL_INFO, 2867175, 88, {op=PTRACE_SYSCALL_INFO_EXIT, arch=AUDIT_ARCH_X86_64, instruction_pointer=0x7bf2ffb274ed, stack_pointer=0x7fffc1933398, exit={rval=-ENOENT, is_error=1}}) = 33ptrace(PTRACE_SYSCALL, 2867175, NULL, 0) = 0--- SIGCHLD {si_signo=SIGCHLD, si_code=CLD_TRAPPED, si_pid=2867175, si_uid=1000, si_status=SIGTRAP, si_utime=0, si_stime=0} ---wait4(2867175, [{WIFSTOPPED(s) && WSTOPSIG(s) == SIGTRAP | 0x80}], 0, NULL) = 2867175ptrace(PTRACE_GET_SYSCALL_INFO, 2867175, 88, {op=PTRACE_SYSCALL_INFO_ENTRY, arch=AUDIT_ARCH_X86_64, instruction_pointer=0x7bf2ffb274ed, stack_pointer=0x7fffc1933398, entry={nr=__NR_gettid, args=[0xcaf0bea0, 0xcaf1bea1, 0xcaf2bea2, 0xcaf3bea3, 0xcaf4bea4, 0xcaf5bea5]}}) = 80ptrace(PTRACE_SYSCALL, 2867175, NULL, 0) = 0wait4(2867175, [{WIFSTOPPED(s) && WSTOPSIG(s) == SIGTRAP | 0x80}], 0, NULL) = 2867175--- SIGCHLD {si_signo=SIGCHLD, si_code=CLD_TRAPPED, si_pid=2867175, si_uid=1000, si_status=SIGTRAP, si_utime=0, si_stime=0} ---ptrace(PTRACE_GET_SYSCALL_INFO, 2867175, 88, {op=PTRACE_SYSCALL_INFO_EXIT, arch=AUDIT_ARCH_X86_64, instruction_pointer=0x7bf2ffb274ed, stack_pointer=0x7fffc1933398, exit={rval=2867175, is_error=0}}) = 33ptrace(PTRACE_SYSCALL, 2867175, NULL, 0) = 0wait4(2867175, [{WIFSTOPPED(s) && WSTOPSIG(s) == SIGTRAP | 0x80}], 0, NULL) = 2867175--- SIGCHLD {si_signo=SIGCHLD, si_code=CLD_TRAPPED, si_pid=2867175, si_uid=1000, si_status=SIGTRAP, si_utime=0, si_stime=0} ---ptrace(PTRACE_GET_SYSCALL_INFO, 2867175, 88, {op=PTRACE_SYSCALL_INFO_ENTRY, arch=AUDIT_ARCH_X86_64, instruction_pointer=0x7bf2ffb274ed, stack_pointer=0x7fffc1933398, entry={nr=__NR_exit_group, args=[0, 0xfac1c0d1, 0xfac2c0d2, 0xfac3c0d3, 0xfac4c0d4, 0xfac5c0d5]}}) = 80ptrace(PTRACE_SYSCALL, 2867175, NULL, 0) = 0wait4(2867175, [{WIFEXITED(s) && WEXITSTATUS(s) == 0}], 0, NULL) = 2867175--- SIGCHLD {si_signo=SIGCHLD, si_code=CLD_EXITED, si_pid=2867175, si_uid=1000, si_status=0, si_utime=0, si_stime=0} ---pipe2([3, 4], 0) = 0close(4) = 0fcntl(3, F_GETFD) = 0fcntl(3, F_SETFD, FD_CLOEXEC) = 0close(3) = 0newfstatat(AT_FDCWD, "./crt_wrapper_probe", {st_mode=S_IFREG|0775, st_size=16416, ...}, 0) = 0clone(child_stack=NULL, flags=CLONE_CHILD_CLEARTID|CLONE_CHILD_SETTID|SIGCHLD, child_tidptr=0x7bf2ffc1d650) = 2867176wait4(2867176, [{WIFSTOPPED(s) && WSTOPSIG(s) == SIGSTOP}], WSTOPPED, NULL) = 2867176--- SIGCHLD {si_signo=SIGCHLD, si_code=CLD_STOPPED, si_pid=2867176, si_uid=1000, si_status=SIGSTOP, si_utime=0, si_stime=0} ---ptrace(PTRACE_SEIZE, 2867176, NULL, PTRACE_O_TRACESYSGOOD|PTRACE_O_TRACEEXEC|PTRACE_O_TRACEEXIT) = 0--- SIGCHLD {si_signo=SIGCHLD, si_code=CLD_STOPPED, si_pid=2867176, si_uid=1000, si_status=0, si_utime=0, si_stime=0} ---ptrace(PTRACE_INTERRUPT, 2867176) = 0kill(2867176, SIGCONT) = 0close(0) = 0pipe2([0, 3], 0) = 0close(3) = 0fcntl(0, F_GETFD) = 0fcntl(0, F_SETFD, FD_CLOEXEC) = 0close(1) = 0pipe2([1, 3], 0) = 0close(3) = 0fcntl(1, F_GETFD) = 0fcntl(1, F_SETFD, FD_CLOEXEC) = 0rt_sigaction(SIGTTOU, {sa_handler=SIG_IGN, sa_mask=[], sa_flags=SA_RESTORER, sa_restorer=0x7bf2ffa45330}, NULL, 8) = 0rt_sigaction(SIGTTIN, {sa_handler=SIG_IGN, sa_mask=[], sa_flags=SA_RESTORER, sa_restorer=0x7bf2ffa45330}, NULL, 8) = 0rt_sigaction(SIGHUP, {sa_handler=0x63147f135f10, sa_mask=[], sa_flags=SA_RESTORER, sa_restorer=0x7bf2ffa45330}, NULL, 8) = 0rt_sigaction(SIGINT, {sa_handler=0x63147f135f10, sa_mask=[], sa_flags=SA_RESTORER, sa_restorer=0x7bf2ffa45330}, NULL, 8) = 0rt_sigaction(SIGQUIT, {sa_handler=0x63147f135f10, sa_mask=[], sa_flags=SA_RESTORER, sa_restorer=0x7bf2ffa45330}, NULL, 8) = 0rt_sigaction(SIGPIPE, {sa_handler=0x63147f135f10, sa_mask=[], sa_flags=SA_RESTORER, sa_restorer=0x7bf2ffa45330}, NULL, 8) = 0rt_sigaction(SIGTERM, {sa_handler=0x63147f135f10, sa_mask=[], sa_flags=SA_RESTORER, sa_restorer=0x7bf2ffa45330}, NULL, 8) = 0rt_sigprocmask(SIG_BLOCK, [ALRM], NULL, 8) = 0rt_sigaction(SIGALRM, {sa_handler=0x63147f141c20, sa_mask=[], sa_flags=SA_RESTORER, sa_restorer=0x7bf2ffa45330}, NULL, 8) = 0wait4(-1, [{WIFSTOPPED(s) && WSTOPSIG(s) == SIGSTOP}|PTRACE_EVENT_STOP<<16], __WALL, NULL) = 2867176wait4(-1, 0x7fffc19335dc, WNOHANG|__WALL, NULL) = 0ptrace(PTRACE_LISTEN, 2867176) = 0wait4(-1, [{WIFSTOPPED(s) && WSTOPSIG(s) == SIGTRAP}|PTRACE_EVENT_STOP<<16], __WALL, NULL) = 2867176--- SIGCHLD {si_signo=SIGCHLD, si_code=CLD_CONTINUED, si_pid=2867176, si_uid=1000, si_status=SIGCONT, si_utime=0, si_stime=0} ---wait4(-1, 0x7fffc19335dc, WNOHANG|__WALL, NULL) = 0ptrace(PTRACE_SYSCALL, 2867176, NULL, 0) = 0wait4(-1, [{WIFSTOPPED(s) && WSTOPSIG(s) == SIGCONT}], __WALL, NULL) = 2867176--- SIGCHLD {si_signo=SIGCHLD, si_code=CLD_TRAPPED, si_pid=2867176, si_uid=1000, si_status=SIGCONT, si_utime=0, si_stime=0} ---ptrace(PTRACE_GETSIGINFO, 2867176, NULL, {si_signo=SIGCONT, si_code=SI_USER, si_pid=2867173, si_uid=1000}) = 0wait4(-1, 0x7fffc19335dc, WNOHANG|__WALL, NULL) = 0ptrace(PTRACE_SYSCALL, 2867176, NULL, SIGCONT) = 0wait4(-1, [{WIFSTOPPED(s) && WSTOPSIG(s) == SIGTRAP | 0x80}], __WALL, NULL) = 2867176--- SIGCHLD {si_signo=SIGCHLD, si_code=CLD_TRAPPED, si_pid=2867176, si_uid=1000, si_status=SIGTRAP, si_utime=0, si_stime=0} ---wait4(-1, 0x7fffc19335dc, WNOHANG|__WALL, NULL) = 0ptrace(PTRACE_GET_SYSCALL_INFO, 2867176, 88, {op=PTRACE_SYSCALL_INFO_ENTRY, arch=AUDIT_ARCH_X86_64, instruction_pointer=0x7bf2ffaeeffb, stack_pointer=0x7fffc1932288, entry={nr=__NR_execve, args=[0x7fffc1932360, 0x7fffc1933870, 0x7fffc1933888, 0x7bf2ffcf50b8, 0x1, 0x7bf2ffc1d380]}}) = 80ptrace(PTRACE_SYSCALL, 2867176, NULL, 0) = 0wait4(-1, [{WIFSTOPPED(s) && WSTOPSIG(s) == SIGTRAP}|PTRACE_EVENT_EXEC<<16], __WALL, NULL) = 2867176--- SIGCHLD {si_signo=SIGCHLD, si_code=CLD_TRAPPED, si_pid=2867176, si_uid=1000, si_status=SIGTRAP, si_utime=0, si_stime=0} ---ptrace(PTRACE_GETEVENTMSG, 2867176, NULL, [2867176]) = 0wait4(-1, 0x7fffc19335dc, WNOHANG|__WALL, NULL) = 0ptrace(PTRACE_SYSCALL, 2867176, NULL, 0) = 0--- SIGCHLD {si_signo=SIGCHLD, si_code=CLD_TRAPPED, si_pid=2867176, si_uid=1000, si_status=SIGTRAP, si_utime=0, si_stime=0} ---wait4(-1, [{WIFSTOPPED(s) && WSTOPSIG(s) == SIGTRAP | 0x80}], __WALL, NULL) = 2867176wait4(-1, 0x7fffc19335dc, WNOHANG|__WALL, NULL) = 0ptrace(PTRACE_SYSCALL, 2867176, NULL, 0) = 0wait4(-1, [{WIFSTOPPED(s) && WSTOPSIG(s) == SIGTRAP | 0x80}], __WALL, NULL) = 2867176--- SIGCHLD {si_signo=SIGCHLD, si_code=CLD_TRAPPED, si_pid=2867176, si_uid=1000, si_status=SIGTRAP, si_utime=0, si_stime=0} ---wait4(-1, 0x7fffc19335dc, WNOHANG|__WALL, NULL) = 0ptrace(PTRACE_GET_SYSCALL_INFO, 2867176, 88, {op=PTRACE_SYSCALL_INFO_ENTRY, arch=AUDIT_ARCH_X86_64, instruction_pointer=0x76292a2539bb, stack_pointer=0x7ffedaa374d8, entry={nr=__NR_brk, args=[0, 0x76292a265a18, 0, 0x37f, 0, 0x76292a265440]}}) = 80ptrace(PTRACE_SYSCALL, 2867176, NULL, 0) = 0wait4(-1, [{WIFSTOPPED(s) && WSTOPSIG(s) == SIGTRAP | 0x80}], __WALL, NULL) = 2867176--- SIGCHLD {si_signo=SIGCHLD, si_code=CLD_TRAPPED, si_pid=2867176, si_uid=1000, si_status=SIGTRAP, si_utime=0, si_stime=0} ---wait4(-1, 0x7fffc19335dc, WNOHANG|__WALL, NULL) = 0ptrace(PTRACE_SYSCALL, 2867176, NULL, 0) = 0wait4(-1, [{WIFSTOPPED(s) && WSTOPSIG(s) == SIGTRAP | 0x80}], __WALL, NULL) = 2867176--- SIGCHLD {si_signo=SIGCHLD, si_code=CLD_TRAPPED, si_pid=2867176, si_uid=1000, si_status=SIGTRAP, si_utime=0, si_stime=0} ---wait4(-1, 0x7fffc19335dc, WNOHANG|__WALL, NULL) = 0ptrace(PTRACE_GET_SYSCALL_INFO, 2867176, 88, {op=PTRACE_SYSCALL_INFO_ENTRY, arch=AUDIT_ARCH_X86_64, instruction_pointer=0x76292a254d1c, stack_pointer=0x7ffedaa37160, entry={nr=__NR_mmap, args=[0, 0x2000, 0x3, 0x22, 0xffffffff, 0]}}) = 80ptrace(PTRACE_SYSCALL, 2867176, NULL, 0) = 0wait4(-1, [{WIFSTOPPED(s) && WSTOPSIG(s) == SIGTRAP | 0x80}], __WALL, NULL) = 2867176--- SIGCHLD {si_signo=SIGCHLD, si_code=CLD_TRAPPED, si_pid=2867176, si_uid=1000, si_status=SIGTRAP, si_utime=0, si_stime=0} ---wait4(-1, 0x7fffc19335dc, WNOHANG|__WALL, NULL) = 0ptrace(PTRACE_SYSCALL, 2867176, NULL, 0) = 0wait4(-1, [{WIFSTOPPED(s) && WSTOPSIG(s) == SIGTRAP | 0x80}], __WALL, NULL) = 2867176--- SIGCHLD {si_signo=SIGCHLD, si_code=CLD_TRAPPED, si_pid=2867176, si_uid=1000, si_status=SIGTRAP, si_utime=0, si_stime=0} ---wait4(-1, 0x7fffc19335dc, WNOHANG|__WALL, NULL) = 0ptrace(PTRACE_GET_SYSCALL_INFO, 2867176, 88, {op=PTRACE_SYSCALL_INFO_ENTRY, arch=AUDIT_ARCH_X86_64, instruction_pointer=0x76292a2548bb, stack_pointer=0x7ffedaa37218, entry={nr=__NR_access, args=[0x76292a25e5b0, 0x4, 0x5ec1e6425e10, 0x22, 0x76292a22f000, 0x76292a265440]}}) = 80ptrace(PTRACE_SYSCALL, 2867176, NULL, 0) = 0--- SIGCHLD {si_signo=SIGCHLD, si_code=CLD_TRAPPED, si_pid=2867176, si_uid=1000, si_status=SIGTRAP, si_utime=0, si_stime=0} ---wait4(-1, [{WIFSTOPPED(s) && WSTOPSIG(s) == SIGTRAP | 0x80}], __WALL, NULL) = 2867176wait4(-1, 0x7fffc19335dc, WNOHANG|__WALL, NULL) = 0ptrace(PTRACE_SYSCALL, 2867176, NULL, 0) = 0--- SIGCHLD {si_signo=SIGCHLD, si_code=CLD_TRAPPED, si_pid=2867176, si_uid=1000, si_status=SIGTRAP, si_utime=0, si_stime=0} ---wait4(-1, [{WIFSTOPPED(s) && WSTOPSIG(s) == SIGTRAP | 0x80}], __WALL, NULL) = 2867176wait4(-1, 0x7fffc19335dc, WNOHANG|__WALL, NULL) = 0ptrace(PTRACE_GET_SYSCALL_INFO, 2867176, 88, {op=PTRACE_SYSCALL_INFO_ENTRY, arch=AUDIT_ARCH_X86_64, instruction_pointer=0x76292a254b61, stack_pointer=0x7ffedaa365b0, entry={nr=__NR_openat, args=[0xffffff9c, 0x76292a25d38f, 0x80000, 0, 0xffff, 0]}}) = 80fstat(2, {st_mode=S_IFIFO|0600, st_size=0, ...}) = 0process_vm_readv(2867176, [{iov_base="2\0dl-lookup.c\0out of memory\n\0, v"..., iov_len=4096}], 1, [{iov_base=0x76292a25d000, iov_len=4096}], 1, 0) = 4096write(2, "openat(AT_FDCWD, \"/etc/ld.so.cac"..., 55) = 55ptrace(PTRACE_SYSCALL, 2867176, NULL, 0) = 0wait4(-1, [{WIFSTOPPED(s) && WSTOPSIG(s) == SIGTRAP | 0x80}], __WALL, NULL) = 2867176--- SIGCHLD {si_signo=SIGCHLD, si_code=CLD_TRAPPED, si_pid=2867176, si_uid=1000, si_status=SIGTRAP, si_utime=0, si_stime=0} ---wait4(-1, 0x7fffc19335dc, WNOHANG|__WALL, NULL) = 0ptrace(PTRACE_GET_SYSCALL_INFO, 2867176, 88, {op=PTRACE_SYSCALL_INFO_EXIT, arch=AUDIT_ARCH_X86_64, instruction_pointer=0x76292a254b61, stack_pointer=0x7ffedaa365b0, exit={rval=3, is_error=0}}) = 33write(2, ") = 3\n", 6) = 6ptrace(PTRACE_SYSCALL, 2867176, NULL, 0) = 0--- SIGCHLD {si_signo=SIGCHLD, si_code=CLD_TRAPPED, si_pid=2867176, si_uid=1000, si_status=SIGTRAP, si_utime=0, si_stime=0} ---wait4(-1, [{WIFSTOPPED(s) && WSTOPSIG(s) == SIGTRAP | 0x80}], __WALL, NULL) = 2867176wait4(-1, 0x7fffc19335dc, WNOHANG|__WALL, NULL) = 0ptrace(PTRACE_GET_SYSCALL_INFO, 2867176, 88, {op=PTRACE_SYSCALL_INFO_ENTRY, arch=AUDIT_ARCH_X86_64, instruction_pointer=0x76292a2548eb, stack_pointer=0x7ffedaa365b8, entry={nr=__NR_fstat, args=[0x3, 0x7ffedaa365c0, 0x80000, 0, 0xffff, 0]}}) = 80ptrace(PTRACE_SYSCALL, 2867176, NULL, 0) = 0--- SIGCHLD {si_signo=SIGCHLD, si_code=CLD_TRAPPED, si_pid=2867176, si_uid=1000, si_status=SIGTRAP, si_utime=0, si_stime=0} ---wait4(-1, [{WIFSTOPPED(s) && WSTOPSIG(s) == SIGTRAP | 0x80}], __WALL, NULL) = 2867176wait4(-1, 0x7fffc19335dc, WNOHANG|__WALL, NULL) = 0ptrace(PTRACE_SYSCALL, 2867176, NULL, 0) = 0--- SIGCHLD {si_signo=SIGCHLD, si_code=CLD_TRAPPED, si_pid=2867176, si_uid=1000, si_status=SIGTRAP, si_utime=0, si_stime=0} ---wait4(-1, [{WIFSTOPPED(s) && WSTOPSIG(s) == SIGTRAP | 0x80}], __WALL, NULL) = 2867176wait4(-1, 0x7fffc19335dc, WNOHANG|__WALL, NULL) = 0ptrace(PTRACE_GET_SYSCALL_INFO, 2867176, 88, {op=PTRACE_SYSCALL_INFO_ENTRY, arch=AUDIT_ARCH_X86_64, instruction_pointer=0x76292a254d1c, stack_pointer=0x7ffedaa365a0, entry={nr=__NR_mmap, args=[0, 0x241e8, 0x1, 0x2, 0x3, 0]}}) = 80ptrace(PTRACE_SYSCALL, 2867176, NULL, 0) = 0wait4(-1, [{WIFSTOPPED(s) && WSTOPSIG(s) == SIGTRAP | 0x80}], __WALL, NULL) = 2867176--- SIGCHLD {si_signo=SIGCHLD, si_code=CLD_TRAPPED, si_pid=2867176, si_uid=1000, si_status=SIGTRAP, si_utime=0, si_stime=0} ---wait4(-1, 0x7fffc19335dc, WNOHANG|__WALL, NULL) = 0ptrace(PTRACE_SYSCALL, 2867176, NULL, 0) = 0--- SIGCHLD {si_signo=SIGCHLD, si_code=CLD_TRAPPED, si_pid=2867176, si_uid=1000, si_status=SIGTRAP, si_utime=0, si_stime=0} ---wait4(-1, [{WIFSTOPPED(s) && WSTOPSIG(s) == SIGTRAP | 0x80}], __WALL, NULL) = 2867176wait4(-1, 0x7fffc19335dc, WNOHANG|__WALL, NULL) = 0ptrace(PTRACE_GET_SYSCALL_INFO, 2867176, 88, {op=PTRACE_SYSCALL_INFO_ENTRY, arch=AUDIT_ARCH_X86_64, instruction_pointer=0x76292a254a1b, stack_pointer=0x7ffedaa365b8, entry={nr=__NR_close, args=[0x3, 0x241e8, 0x1, 0x2, 0x3, 0]}}) = 80write(2, "close(3", 7) = 7ptrace(PTRACE_SYSCALL, 2867176, NULL, 0) = 0--- SIGCHLD {si_signo=SIGCHLD, si_code=CLD_TRAPPED, si_pid=2867176, si_uid=1000, si_status=SIGTRAP, si_utime=0, si_stime=0} ---wait4(-1, [{WIFSTOPPED(s) && WSTOPSIG(s) == SIGTRAP | 0x80}], __WALL, NULL) = 2867176wait4(-1, 0x7fffc19335dc, WNOHANG|__WALL, NULL) = 0ptrace(PTRACE_GET_SYSCALL_INFO, 2867176, 88, {op=PTRACE_SYSCALL_INFO_EXIT, arch=AUDIT_ARCH_X86_64, instruction_pointer=0x76292a254a1b, stack_pointer=0x7ffedaa365b8, exit={rval=0, is_error=0}}) = 33write(2, ") "..., 37) = 37ptrace(PTRACE_SYSCALL, 2867176, NULL, 0) = 0wait4(-1, [{WIFSTOPPED(s) && WSTOPSIG(s) == SIGTRAP | 0x80}], __WALL, NULL) = 2867176--- SIGCHLD {si_signo=SIGCHLD, si_code=CLD_TRAPPED, si_pid=2867176, si_uid=1000, si_status=SIGTRAP, si_utime=0, si_stime=0} ---wait4(-1, 0x7fffc19335dc, WNOHANG|__WALL, NULL) = 0ptrace(PTRACE_GET_SYSCALL_INFO, 2867176, 88, {op=PTRACE_SYSCALL_INFO_ENTRY, arch=AUDIT_ARCH_X86_64, instruction_pointer=0x76292a254b61, stack_pointer=0x7ffedaa36720, entry={nr=__NR_openat, args=[0xffffff9c, 0x76292a225140, 0x80000, 0, 0x7ffedaa367d7, 0]}}) = 80process_vm_readv(2867176, [{iov_base="PP\"*)v\0\0\362\316%*)v\0\0\0\0\0\0\0\0\0\0@\260%*)v\0\0"..., iov_len=4096}], 1, [{iov_base=0x76292a225000, iov_len=4096}], 1, 0) = 4096write(2, "openat(AT_FDCWD, \"/lib/x86_64-li"..., 70) = 70ptrace(PTRACE_SYSCALL, 2867176, NULL, 0) = 0--- SIGCHLD {si_signo=SIGCHLD, si_code=CLD_TRAPPED, si_pid=2867176, si_uid=1000, si_status=SIGTRAP, si_utime=0, si_stime=0} ---wait4(-1, [{WIFSTOPPED(s) && WSTOPSIG(s) == SIGTRAP | 0x80}], __WALL, NULL) = 2867176wait4(-1, 0x7fffc19335dc, WNOHANG|__WALL, NULL) = 0ptrace(PTRACE_GET_SYSCALL_INFO, 2867176, 88, {op=PTRACE_SYSCALL_INFO_EXIT, arch=AUDIT_ARCH_X86_64, instruction_pointer=0x76292a254b61, stack_pointer=0x7ffedaa36720, exit={rval=3, is_error=0}}) = 33write(2, ") = 3\n", 6) = 6ptrace(PTRACE_SYSCALL, 2867176, NULL, 0) = 0--- SIGCHLD {si_signo=SIGCHLD, si_code=CLD_TRAPPED, si_pid=2867176, si_uid=1000, si_status=SIGTRAP, si_utime=0, si_stime=0} ---wait4(-1, [{WIFSTOPPED(s) && WSTOPSIG(s) == SIGTRAP | 0x80}], __WALL, NULL) = 2867176wait4(-1, 0x7fffc19335dc, WNOHANG|__WALL, NULL) = 0ptrace(PTRACE_GET_SYSCALL_INFO, 2867176, 88, {op=PTRACE_SYSCALL_INFO_ENTRY, arch=AUDIT_ARCH_X86_64, instruction_pointer=0x76292a254bd8, stack_pointer=0x7ffedaa36728, entry={nr=__NR_read, args=[0x3, 0x7ffedaa367f8, 0x340, 0, 0x7ffedaa367d7, 0]}}) = 80ptrace(PTRACE_SYSCALL, 2867176, NULL, 0) = 0--- SIGCHLD {si_signo=SIGCHLD, si_code=CLD_TRAPPED, si_pid=2867176, si_uid=1000, si_status=SIGTRAP, si_utime=0, si_stime=0} ---wait4(-1, [{WIFSTOPPED(s) && WSTOPSIG(s) == SIGTRAP | 0x80}], __WALL, NULL) = 2867176wait4(-1, 0x7fffc19335dc, WNOHANG|__WALL, NULL) = 0ptrace(PTRACE_SYSCALL, 2867176, NULL, 0) = 0--- SIGCHLD {si_signo=SIGCHLD, si_code=CLD_TRAPPED, si_pid=2867176, si_uid=1000, si_status=SIGTRAP, si_utime=0, si_stime=0} ---wait4(-1, [{WIFSTOPPED(s) && WSTOPSIG(s) == SIGTRAP | 0x80}], __WALL, NULL) = 2867176wait4(-1, 0x7fffc19335dc, WNOHANG|__WALL, NULL) = 0ptrace(PTRACE_GET_SYSCALL_INFO, 2867176, 88, {op=PTRACE_SYSCALL_INFO_ENTRY, arch=AUDIT_ARCH_X86_64, instruction_pointer=0x76292a254bae, stack_pointer=0x7ffedaa36408, entry={nr=__NR_pread64, args=[0x3, 0x7ffedaa36410, 0x310, 0x40, 0x7ffedaa367d7, 0]}}) = 80ptrace(PTRACE_SYSCALL, 2867176, NULL, 0) = 0--- SIGCHLD {si_signo=SIGCHLD, si_code=CLD_TRAPPED, si_pid=2867176, si_uid=1000, si_status=SIGTRAP, si_utime=0, si_stime=0} ---wait4(-1, [{WIFSTOPPED(s) && WSTOPSIG(s) == SIGTRAP | 0x80}], __WALL, NULL) = 2867176wait4(-1, 0x7fffc19335dc, WNOHANG|__WALL, NULL) = 0ptrace(PTRACE_SYSCALL, 2867176, NULL, 0) = 0--- SIGCHLD {si_signo=SIGCHLD, si_code=CLD_TRAPPED, si_pid=2867176, si_uid=1000, si_status=SIGTRAP, si_utime=0, si_stime=0} ---wait4(-1, [{WIFSTOPPED(s) && WSTOPSIG(s) == SIGTRAP | 0x80}], __WALL, NULL) = 2867176wait4(-1, 0x7fffc19335dc, WNOHANG|__WALL, NULL) = 0ptrace(PTRACE_GET_SYSCALL_INFO, 2867176, 88, {op=PTRACE_SYSCALL_INFO_ENTRY, arch=AUDIT_ARCH_X86_64, instruction_pointer=0x76292a2548eb, stack_pointer=0x7ffedaa365f8, entry={nr=__NR_fstat, args=[0x3, 0x7ffedaa36690, 0x3, 0x40, 0x76292a225140, 0x76292a2682e0]}}) = 80ptrace(PTRACE_SYSCALL, 2867176, NULL, 0) = 0--- SIGCHLD {si_signo=SIGCHLD, si_code=CLD_TRAPPED, si_pid=2867176, si_uid=1000, si_status=SIGTRAP, si_utime=0, si_stime=0} ---wait4(-1, [{WIFSTOPPED(s) && WSTOPSIG(s) == SIGTRAP | 0x80}], __WALL, NULL) = 2867176wait4(-1, 0x7fffc19335dc, WNOHANG|__WALL, NULL) = 0ptrace(PTRACE_SYSCALL, 2867176, NULL, 0) = 0--- SIGCHLD {si_signo=SIGCHLD, si_code=CLD_TRAPPED, si_pid=2867176, si_uid=1000, si_status=SIGTRAP, si_utime=0, si_stime=0} ---wait4(-1, [{WIFSTOPPED(s) && WSTOPSIG(s) == SIGTRAP | 0x80}], __WALL, NULL) = 2867176wait4(-1, 0x7fffc19335dc, WNOHANG|__WALL, NULL) = 0ptrace(PTRACE_GET_SYSCALL_INFO, 2867176, 88, {op=PTRACE_SYSCALL_INFO_ENTRY, arch=AUDIT_ARCH_X86_64, instruction_pointer=0x76292a254bae, stack_pointer=0x7ffedaa362d8, entry={nr=__NR_pread64, args=[0x3, 0x7ffedaa362e0, 0x310, 0x40, 0xc0ff, 0]}}) = 80ptrace(PTRACE_SYSCALL, 2867176, NULL, 0) = 0--- SIGCHLD {si_signo=SIGCHLD, si_code=CLD_TRAPPED, si_pid=2867176, si_uid=1000, si_status=SIGTRAP, si_utime=0, si_stime=0} ---wait4(-1, [{WIFSTOPPED(s) && WSTOPSIG(s) == SIGTRAP | 0x80}], __WALL, NULL) = 2867176wait4(-1, 0x7fffc19335dc, WNOHANG|__WALL, NULL) = 0ptrace(PTRACE_SYSCALL, 2867176, NULL, 0) = 0--- SIGCHLD {si_signo=SIGCHLD, si_code=CLD_TRAPPED, si_pid=2867176, si_uid=1000, si_status=SIGTRAP, si_utime=0, si_stime=0} ---wait4(-1, [{WIFSTOPPED(s) && WSTOPSIG(s) == SIGTRAP | 0x80}], __WALL, NULL) = 2867176wait4(-1, 0x7fffc19335dc, WNOHANG|__WALL, NULL) = 0ptrace(PTRACE_GET_SYSCALL_INFO, 2867176, 88, {op=PTRACE_SYSCALL_INFO_ENTRY, arch=AUDIT_ARCH_X86_64, instruction_pointer=0x76292a254d1c, stack_pointer=0x7ffedaa35fb0, entry={nr=__NR_mmap, args=[0, 0x212d90, 0x1, 0x802, 0x3, 0]}}) = 80ptrace(PTRACE_SYSCALL, 2867176, NULL, 0) = 0wait4(-1, [{WIFSTOPPED(s) && WSTOPSIG(s) == SIGTRAP | 0x80}], __WALL, NULL) = 2867176--- SIGCHLD {si_signo=SIGCHLD, si_code=CLD_TRAPPED, si_pid=2867176, si_uid=1000, si_status=SIGTRAP, si_utime=0, si_stime=0} ---wait4(-1, 0x7fffc19335dc, WNOHANG|__WALL, NULL) = 0ptrace(PTRACE_SYSCALL, 2867176, NULL, 0) = 0--- SIGCHLD {si_signo=SIGCHLD, si_code=CLD_TRAPPED, si_pid=2867176, si_uid=1000, si_status=SIGTRAP, si_utime=0, si_stime=0} ---wait4(-1, [{WIFSTOPPED(s) && WSTOPSIG(s) == SIGTRAP | 0x80}], __WALL, NULL) = 2867176wait4(-1, 0x7fffc19335dc, WNOHANG|__WALL, NULL) = 0ptrace(PTRACE_GET_SYSCALL_INFO, 2867176, 88, {op=PTRACE_SYSCALL_INFO_ENTRY, arch=AUDIT_ARCH_X86_64, instruction_pointer=0x76292a254d1c, stack_pointer=0x7ffedaa35fb0, entry={nr=__NR_mmap, args=[0x762929e28000, 0x189000, 0x5, 0x812, 0x3, 0x28000]}}) = 80ptrace(PTRACE_SYSCALL, 2867176, NULL, 0) = 0--- SIGCHLD {si_signo=SIGCHLD, si_code=CLD_TRAPPED, si_pid=2867176, si_uid=1000, si_status=SIGTRAP, si_utime=0, si_stime=0} ---wait4(-1, [{WIFSTOPPED(s) && WSTOPSIG(s) == SIGTRAP | 0x80}], __WALL, NULL) = 2867176wait4(-1, 0x7fffc19335dc, WNOHANG|__WALL, NULL) = 0ptrace(PTRACE_SYSCALL, 2867176, NULL, 0) = 0--- SIGCHLD {si_signo=SIGCHLD, si_code=CLD_TRAPPED, si_pid=2867176, si_uid=1000, si_status=SIGTRAP, si_utime=0, si_stime=0} ---wait4(-1, [{WIFSTOPPED(s) && WSTOPSIG(s) == SIGTRAP | 0x80}], __WALL, NULL) = 2867176wait4(-1, 0x7fffc19335dc, WNOHANG|__WALL, NULL) = 0ptrace(PTRACE_GET_SYSCALL_INFO, 2867176, 88, {op=PTRACE_SYSCALL_INFO_ENTRY, arch=AUDIT_ARCH_X86_64, instruction_pointer=0x76292a254d1c, stack_pointer=0x7ffedaa35fb0, entry={nr=__NR_mmap, args=[0x762929fb1000, 0x4f000, 0x1, 0x812, 0x3, 0x1b1000]}}) = 80ptrace(PTRACE_SYSCALL, 2867176, NULL, 0) = 0wait4(-1, [{WIFSTOPPED(s) && WSTOPSIG(s) == SIGTRAP | 0x80}], __WALL, NULL) = 2867176--- SIGCHLD {si_signo=SIGCHLD, si_code=CLD_TRAPPED, si_pid=2867176, si_uid=1000, si_status=SIGTRAP, si_utime=0, si_stime=0} ---wait4(-1, 0x7fffc19335dc, WNOHANG|__WALL, NULL) = 0ptrace(PTRACE_SYSCALL, 2867176, NULL, 0) = 0--- SIGCHLD {si_signo=SIGCHLD, si_code=CLD_TRAPPED, si_pid=2867176, si_uid=1000, si_status=SIGTRAP, si_utime=0, si_stime=0} ---wait4(-1, [{WIFSTOPPED(s) && WSTOPSIG(s) == SIGTRAP | 0x80}], __WALL, NULL) = 2867176wait4(-1, 0x7fffc19335dc, WNOHANG|__WALL, NULL) = 0ptrace(PTRACE_GET_SYSCALL_INFO, 2867176, 88, {op=PTRACE_SYSCALL_INFO_ENTRY, arch=AUDIT_ARCH_X86_64, instruction_pointer=0x76292a254d1c, stack_pointer=0x7ffedaa35fb0, entry={nr=__NR_mmap, args=[0x76292a000000, 0x6000, 0x3, 0x812, 0x3, 0x1ff000]}}) = 80ptrace(PTRACE_SYSCALL, 2867176, NULL, 0) = 0wait4(-1, [{WIFSTOPPED(s) && WSTOPSIG(s) == SIGTRAP | 0x80}], __WALL, NULL) = 2867176--- SIGCHLD {si_signo=SIGCHLD, si_code=CLD_TRAPPED, si_pid=2867176, si_uid=1000, si_status=SIGTRAP, si_utime=0, si_stime=0} ---wait4(-1, 0x7fffc19335dc, WNOHANG|__WALL, NULL) = 0ptrace(PTRACE_SYSCALL, 2867176, NULL, 0) = 0wait4(-1, [{WIFSTOPPED(s) && WSTOPSIG(s) == SIGTRAP | 0x80}], __WALL, NULL) = 2867176--- SIGCHLD {si_signo=SIGCHLD, si_code=CLD_TRAPPED, si_pid=2867176, si_uid=1000, si_status=SIGTRAP, si_utime=0, si_stime=0} ---wait4(-1, 0x7fffc19335dc, WNOHANG|__WALL, NULL) = 0ptrace(PTRACE_GET_SYSCALL_INFO, 2867176, 88, {op=PTRACE_SYSCALL_INFO_ENTRY, arch=AUDIT_ARCH_X86_64, instruction_pointer=0x76292a254d1c, stack_pointer=0x7ffedaa35fb0, entry={nr=__NR_mmap, args=[0x76292a006000, 0xcd90, 0x3, 0x32, 0xffffffff, 0]}}) = 80ptrace(PTRACE_SYSCALL, 2867176, NULL, 0) = 0--- SIGCHLD {si_signo=SIGCHLD, si_code=CLD_TRAPPED, si_pid=2867176, si_uid=1000, si_status=SIGTRAP, si_utime=0, si_stime=0} ---wait4(-1, [{WIFSTOPPED(s) && WSTOPSIG(s) == SIGTRAP | 0x80}], __WALL, NULL) = 2867176wait4(-1, 0x7fffc19335dc, WNOHANG|__WALL, NULL) = 0ptrace(PTRACE_SYSCALL, 2867176, NULL, 0) = 0wait4(-1, [{WIFSTOPPED(s) && WSTOPSIG(s) == SIGTRAP | 0x80}], __WALL, NULL) = 2867176--- SIGCHLD {si_signo=SIGCHLD, si_code=CLD_TRAPPED, si_pid=2867176, si_uid=1000, si_status=SIGTRAP, si_utime=0, si_stime=0} ---wait4(-1, 0x7fffc19335dc, WNOHANG|__WALL, NULL) = 0ptrace(PTRACE_GET_SYSCALL_INFO, 2867176, 88, {op=PTRACE_SYSCALL_INFO_ENTRY, arch=AUDIT_ARCH_X86_64, instruction_pointer=0x76292a254a1b, stack_pointer=0x7ffedaa362d8, entry={nr=__NR_close, args=[0x3, 0x76292a225160, 0x1, 0xc0000002, 0x762929e00378, 0x4]}}) = 80write(2, "close(3", 7) = 7ptrace(PTRACE_SYSCALL, 2867176, NULL, 0) = 0--- SIGCHLD {si_signo=SIGCHLD, si_code=CLD_TRAPPED, si_pid=2867176, si_uid=1000, si_status=SIGTRAP, si_utime=0, si_stime=0} ---wait4(-1, [{WIFSTOPPED(s) && WSTOPSIG(s) == SIGTRAP | 0x80}], __WALL, NULL) = 2867176wait4(-1, 0x7fffc19335dc, WNOHANG|__WALL, NULL) = 0ptrace(PTRACE_GET_SYSCALL_INFO, 2867176, 88, {op=PTRACE_SYSCALL_INFO_EXIT, arch=AUDIT_ARCH_X86_64, instruction_pointer=0x76292a254a1b, stack_pointer=0x7ffedaa362d8, exit={rval=0, is_error=0}}) = 33write(2, ") "..., 37) = 37ptrace(PTRACE_SYSCALL, 2867176, NULL, 0) = 0wait4(-1, [{WIFSTOPPED(s) && WSTOPSIG(s) == SIGTRAP | 0x80}], __WALL, NULL) = 2867176--- SIGCHLD {si_signo=SIGCHLD, si_code=CLD_TRAPPED, si_pid=2867176, si_uid=1000, si_status=SIGTRAP, si_utime=0, si_stime=0} ---wait4(-1, 0x7fffc19335dc, WNOHANG|__WALL, NULL) = 0ptrace(PTRACE_GET_SYSCALL_INFO, 2867176, 88, {op=PTRACE_SYSCALL_INFO_ENTRY, arch=AUDIT_ARCH_X86_64, instruction_pointer=0x76292a254d1c, stack_pointer=0x7ffedaa37180, entry={nr=__NR_mmap, args=[0, 0x3000, 0x3, 0x22, 0xffffffff, 0]}}) = 80ptrace(PTRACE_SYSCALL, 2867176, NULL, 0) = 0wait4(-1, [{WIFSTOPPED(s) && WSTOPSIG(s) == SIGTRAP | 0x80}], __WALL, NULL) = 2867176--- SIGCHLD {si_signo=SIGCHLD, si_code=CLD_TRAPPED, si_pid=2867176, si_uid=1000, si_status=SIGTRAP, si_utime=0, si_stime=0} ---wait4(-1, 0x7fffc19335dc, WNOHANG|__WALL, NULL) = 0ptrace(PTRACE_SYSCALL, 2867176, NULL, 0) = 0wait4(-1, [{WIFSTOPPED(s) && WSTOPSIG(s) == SIGTRAP | 0x80}], __WALL, NULL) = 2867176--- SIGCHLD {si_signo=SIGCHLD, si_code=CLD_TRAPPED, si_pid=2867176, si_uid=1000, si_status=SIGTRAP, si_utime=0, si_stime=0} ---wait4(-1, 0x7fffc19335dc, WNOHANG|__WALL, NULL) = 0ptrace(PTRACE_GET_SYSCALL_INFO, 2867176, 88, {op=PTRACE_SYSCALL_INFO_ENTRY, arch=AUDIT_ARCH_X86_64, instruction_pointer=0x76292a24f11d, stack_pointer=0x7ffedaa37200, entry={nr=__NR_arch_prctl, args=[0x1002, 0x76292a1fd740, 0xffff89d6d5e01f30, 0x22, 0xffffffff, 0]}}) = 80ptrace(PTRACE_SYSCALL, 2867176, NULL, 0) = 0--- SIGCHLD {si_signo=SIGCHLD, si_code=CLD_TRAPPED, si_pid=2867176, si_uid=1000, si_status=SIGTRAP, si_utime=0, si_stime=0} ---wait4(-1, [{WIFSTOPPED(s) && WSTOPSIG(s) == SIGTRAP | 0x80}], __WALL, NULL) = 2867176wait4(-1, 0x7fffc19335dc, WNOHANG|__WALL, NULL) = 0ptrace(PTRACE_SYSCALL, 2867176, NULL, 0) = 0--- SIGCHLD {si_signo=SIGCHLD, si_code=CLD_TRAPPED, si_pid=2867176, si_uid=1000, si_status=SIGTRAP, si_utime=0, si_stime=0} ---wait4(-1, [{WIFSTOPPED(s) && WSTOPSIG(s) == SIGTRAP | 0x80}], __WALL, NULL) = 2867176wait4(-1, 0x7fffc19335dc, WNOHANG|__WALL, NULL) = 0ptrace(PTRACE_GET_SYSCALL_INFO, 2867176, 88, {op=PTRACE_SYSCALL_INFO_ENTRY, arch=AUDIT_ARCH_X86_64, instruction_pointer=0x76292a243f12, stack_pointer=0x7ffedaa371d0, entry={nr=__NR_set_tid_address, args=[0x76292a1fda10, 0x76292a1fd740, 0x76292a2680c8, 0x22, 0xffffffff, 0]}}) = 80ptrace(PTRACE_SYSCALL, 2867176, NULL, 0) = 0--- SIGCHLD {si_signo=SIGCHLD, si_code=CLD_TRAPPED, si_pid=2867176, si_uid=1000, si_status=SIGTRAP, si_utime=0, si_stime=0} ---wait4(-1, [{WIFSTOPPED(s) && WSTOPSIG(s) == SIGTRAP | 0x80}], __WALL, NULL) = 2867176wait4(-1, 0x7fffc19335dc, WNOHANG|__WALL, NULL) = 0ptrace(PTRACE_SYSCALL, 2867176, NULL, 0) = 0--- SIGCHLD {si_signo=SIGCHLD, si_code=CLD_TRAPPED, si_pid=2867176, si_uid=1000, si_status=SIGTRAP, si_utime=0, si_stime=0} ---wait4(-1, [{WIFSTOPPED(s) && WSTOPSIG(s) == SIGTRAP | 0x80}], __WALL, NULL) = 2867176wait4(-1, 0x7fffc19335dc, WNOHANG|__WALL, NULL) = 0ptrace(PTRACE_GET_SYSCALL_INFO, 2867176, 88, {op=PTRACE_SYSCALL_INFO_ENTRY, arch=AUDIT_ARCH_X86_64, instruction_pointer=0x76292a243f6e, stack_pointer=0x7ffedaa371d0, entry={nr=__NR_set_robust_list, args=[0x76292a1fda20, 0x18, 0x76292a2680c8, 0x22, 0xffffffff, 0]}}) = 80ptrace(PTRACE_SYSCALL, 2867176, NULL, 0) = 0--- SIGCHLD {si_signo=SIGCHLD, si_code=CLD_TRAPPED, si_pid=2867176, si_uid=1000, si_status=SIGTRAP, si_utime=0, si_stime=0} ---wait4(-1, [{WIFSTOPPED(s) && WSTOPSIG(s) == SIGTRAP | 0x80}], __WALL, NULL) = 2867176wait4(-1, 0x7fffc19335dc, WNOHANG|__WALL, NULL) = 0ptrace(PTRACE_SYSCALL, 2867176, NULL, 0) = 0--- SIGCHLD {si_signo=SIGCHLD, si_code=CLD_TRAPPED, si_pid=2867176, si_uid=1000, si_status=SIGTRAP, si_utime=0, si_stime=0} ---wait4(-1, [{WIFSTOPPED(s) && WSTOPSIG(s) == SIGTRAP | 0x80}], __WALL, NULL) = 2867176wait4(-1, 0x7fffc19335dc, WNOHANG|__WALL, NULL) = 0ptrace(PTRACE_GET_SYSCALL_INFO, 2867176, 88, {op=PTRACE_SYSCALL_INFO_ENTRY, arch=AUDIT_ARCH_X86_64, instruction_pointer=0x76292a243fe6, stack_pointer=0x7ffedaa371d0, entry={nr=__NR_rseq, args=[0x76292a1fe060, 0x20, 0, 0x53053053, 0, 0x76292a265440]}}) = 80ptrace(PTRACE_SYSCALL, 2867176, NULL, 0) = 0wait4(-1, [{WIFSTOPPED(s) && WSTOPSIG(s) == SIGTRAP | 0x80}], __WALL, NULL) = 2867176--- SIGCHLD {si_signo=SIGCHLD, si_code=CLD_TRAPPED, si_pid=2867176, si_uid=1000, si_status=SIGTRAP, si_utime=0, si_stime=0} ---wait4(-1, 0x7fffc19335dc, WNOHANG|__WALL, NULL) = 0ptrace(PTRACE_SYSCALL, 2867176, NULL, 0) = 0wait4(-1, [{WIFSTOPPED(s) && WSTOPSIG(s) == SIGTRAP | 0x80}], __WALL, NULL) = 2867176--- SIGCHLD {si_signo=SIGCHLD, si_code=CLD_TRAPPED, si_pid=2867176, si_uid=1000, si_status=SIGTRAP, si_utime=0, si_stime=0} ---wait4(-1, 0x7fffc19335dc, WNOHANG|__WALL, NULL) = 0ptrace(PTRACE_GET_SYSCALL_INFO, 2867176, 88, {op=PTRACE_SYSCALL_INFO_ENTRY, arch=AUDIT_ARCH_X86_64, instruction_pointer=0x76292a254dab, stack_pointer=0x7ffedaa370e8, entry={nr=__NR_mprotect, args=[0x76292a000000, 0x4000, 0x1, 0x76292a225160, 0x76292a225160, 0]}}) = 80ptrace(PTRACE_SYSCALL, 2867176, NULL, 0) = 0wait4(-1, [{WIFSTOPPED(s) && WSTOPSIG(s) == SIGTRAP | 0x80}], __WALL, NULL) = 2867176--- SIGCHLD {si_signo=SIGCHLD, si_code=CLD_TRAPPED, si_pid=2867176, si_uid=1000, si_status=SIGTRAP, si_utime=0, si_stime=0} ---wait4(-1, 0x7fffc19335dc, WNOHANG|__WALL, NULL) = 0ptrace(PTRACE_SYSCALL, 2867176, NULL, 0) = 0--- SIGCHLD {si_signo=SIGCHLD, si_code=CLD_TRAPPED, si_pid=2867176, si_uid=1000, si_status=SIGTRAP, si_utime=0, si_stime=0} ---wait4(-1, [{WIFSTOPPED(s) && WSTOPSIG(s) == SIGTRAP | 0x80}], __WALL, NULL) = 2867176wait4(-1, 0x7fffc19335dc, WNOHANG|__WALL, NULL) = 0ptrace(PTRACE_GET_SYSCALL_INFO, 2867176, 88, {op=PTRACE_SYSCALL_INFO_ENTRY, arch=AUDIT_ARCH_X86_64, instruction_pointer=0x76292a254dab, stack_pointer=0x7ffedaa370e8, entry={nr=__NR_mprotect, args=[0x5ec1e6425000, 0x1000, 0x1, 0x76292a2682e0, 0x76292a2682e0, 0x762929eb4460]}}) = 80ptrace(PTRACE_SYSCALL, 2867176, NULL, 0) = 0wait4(-1, [{WIFSTOPPED(s) && WSTOPSIG(s) == SIGTRAP | 0x80}], __WALL, NULL) = 2867176--- SIGCHLD {si_signo=SIGCHLD, si_code=CLD_TRAPPED, si_pid=2867176, si_uid=1000, si_status=SIGTRAP, si_utime=0, si_stime=0} ---wait4(-1, 0x7fffc19335dc, WNOHANG|__WALL, NULL) = 0ptrace(PTRACE_SYSCALL, 2867176, NULL, 0) = 0--- SIGCHLD {si_signo=SIGCHLD, si_code=CLD_TRAPPED, si_pid=2867176, si_uid=1000, si_status=SIGTRAP, si_utime=0, si_stime=0} ---wait4(-1, [{WIFSTOPPED(s) && WSTOPSIG(s) == SIGTRAP | 0x80}], __WALL, NULL) = 2867176wait4(-1, 0x7fffc19335dc, WNOHANG|__WALL, NULL) = 0ptrace(PTRACE_GET_SYSCALL_INFO, 2867176, 88, {op=PTRACE_SYSCALL_INFO_ENTRY, arch=AUDIT_ARCH_X86_64, instruction_pointer=0x76292a254dab, stack_pointer=0x7ffedaa370e8, entry={nr=__NR_mprotect, args=[0x76292a265000, 0x2000, 0x1, 0x76292a267ab0, 0x76292a267ab0, 0]}}) = 80ptrace(PTRACE_SYSCALL, 2867176, NULL, 0) = 0wait4(-1, [{WIFSTOPPED(s) && WSTOPSIG(s) == SIGTRAP | 0x80}], __WALL, NULL) = 2867176--- SIGCHLD {si_signo=SIGCHLD, si_code=CLD_TRAPPED, si_pid=2867176, si_uid=1000, si_status=SIGTRAP, si_utime=0, si_stime=0} ---wait4(-1, 0x7fffc19335dc, WNOHANG|__WALL, NULL) = 0ptrace(PTRACE_SYSCALL, 2867176, NULL, 0) = 0wait4(-1, [{WIFSTOPPED(s) && WSTOPSIG(s) == SIGTRAP | 0x80}], __WALL, NULL) = 2867176--- SIGCHLD {si_signo=SIGCHLD, si_code=CLD_TRAPPED, si_pid=2867176, si_uid=1000, si_status=SIGTRAP, si_utime=0, si_stime=0} ---wait4(-1, 0x7fffc19335dc, WNOHANG|__WALL, NULL) = 0ptrace(PTRACE_GET_SYSCALL_INFO, 2867176, 88, {op=PTRACE_SYSCALL_INFO_ENTRY, arch=AUDIT_ARCH_X86_64, instruction_pointer=0x762929f1d454, stack_pointer=0x7ffedaa371d8, entry={nr=__NR_prlimit64, args=[0, 0x3, 0, 0x7ffedaa371e0, 0, 0xd]}}) = 80ptrace(PTRACE_SYSCALL, 2867176, NULL, 0) = 0--- SIGCHLD {si_signo=SIGCHLD, si_code=CLD_TRAPPED, si_pid=2867176, si_uid=1000, si_status=SIGTRAP, si_utime=0, si_stime=0} ---wait4(-1, [{WIFSTOPPED(s) && WSTOPSIG(s) == SIGTRAP | 0x80}], __WALL, NULL) = 2867176wait4(-1, 0x7fffc19335dc, WNOHANG|__WALL, NULL) = 0ptrace(PTRACE_SYSCALL, 2867176, NULL, 0) = 0wait4(-1, [{WIFSTOPPED(s) && WSTOPSIG(s) == SIGTRAP | 0x80}], __WALL, NULL) = 2867176--- SIGCHLD {si_signo=SIGCHLD, si_code=CLD_TRAPPED, si_pid=2867176, si_uid=1000, si_status=SIGTRAP, si_utime=0, si_stime=0} ---wait4(-1, 0x7fffc19335dc, WNOHANG|__WALL, NULL) = 0ptrace(PTRACE_GET_SYSCALL_INFO, 2867176, 88, {op=PTRACE_SYSCALL_INFO_ENTRY, arch=AUDIT_ARCH_X86_64, instruction_pointer=0x76292a254ddb, stack_pointer=0x7ffedaa37208, entry={nr=__NR_munmap, args=[0x76292a200000, 0x241e8, 0, 0x7ffedaa371e0, 0, 0x76292a265440]}}) = 80ptrace(PTRACE_SYSCALL, 2867176, NULL, 0) = 0wait4(-1, [{WIFSTOPPED(s) && WSTOPSIG(s) == SIGTRAP | 0x80}], __WALL, NULL) = 2867176--- SIGCHLD {si_signo=SIGCHLD, si_code=CLD_TRAPPED, si_pid=2867176, si_uid=1000, si_status=SIGTRAP, si_utime=0, si_stime=0} ---wait4(-1, 0x7fffc19335dc, WNOHANG|__WALL, NULL) = 0ptrace(PTRACE_SYSCALL, 2867176, NULL, 0) = 0wait4(-1, [{WIFSTOPPED(s) && WSTOPSIG(s) == SIGTRAP | 0x80}], __WALL, NULL) = 2867176--- SIGCHLD {si_signo=SIGCHLD, si_code=CLD_TRAPPED, si_pid=2867176, si_uid=1000, si_status=SIGTRAP, si_utime=0, si_stime=0} ---wait4(-1, 0x7fffc19335dc, WNOHANG|__WALL, NULL) = 0ptrace(PTRACE_GET_SYSCALL_INFO, 2867176, 88, {op=PTRACE_SYSCALL_INFO_ENTRY, arch=AUDIT_ARCH_X86_64, instruction_pointer=0x762929f1c804, stack_pointer=0x7ffedaa37398, entry={nr=__NR_write, args=[0xffffffff, 0x5ec1e642400d, 0x1, 0x7ffedaa371e0, 0, 0x76292a234380]}}) = 80process_vm_readv(2867176, [{iov_base="\1\0\2\0\0\0\0\0none\0X\0\0glibc=%s ctor=%d"..., iov_len=4096}], 1, [{iov_base=0x5ec1e6424000, iov_len=4096}], 1, 0) = 4096write(2, "write(-1, \"X\", 1", 16) = 16ptrace(PTRACE_SYSCALL, 2867176, NULL, 0) = 0--- SIGCHLD {si_signo=SIGCHLD, si_code=CLD_TRAPPED, si_pid=2867176, si_uid=1000, si_status=SIGTRAP, si_utime=0, si_stime=0} ---wait4(-1, [{WIFSTOPPED(s) && WSTOPSIG(s) == SIGTRAP | 0x80}], __WALL, NULL) = 2867176wait4(-1, 0x7fffc19335dc, WNOHANG|__WALL, NULL) = 0ptrace(PTRACE_GET_SYSCALL_INFO, 2867176, 88, {op=PTRACE_SYSCALL_INFO_EXIT, arch=AUDIT_ARCH_X86_64, instruction_pointer=0x762929f1c804, stack_pointer=0x7ffedaa37398, exit={rval=-EBADF, is_error=1}}) = 33write(2, ") = -1 EBA"..., 57) = 57ptrace(PTRACE_SYSCALL, 2867176, NULL, 0) = 0wait4(-1, [{WIFSTOPPED(s) && WSTOPSIG(s) == SIGTRAP | 0x80}], __WALL, NULL) = 2867176--- SIGCHLD {si_signo=SIGCHLD, si_code=CLD_TRAPPED, si_pid=2867176, si_uid=1000, si_status=SIGTRAP, si_utime=0, si_stime=0} ---wait4(-1, 0x7fffc19335dc, WNOHANG|__WALL, NULL) = 0ptrace(PTRACE_GET_SYSCALL_INFO, 2867176, 88, {op=PTRACE_SYSCALL_INFO_ENTRY, arch=AUDIT_ARCH_X86_64, instruction_pointer=0x762929f1c804, stack_pointer=0x7ffedaa37358, entry={nr=__NR_write, args=[0x1, 0x7ffedaa373e0, 0x3e, 0, 0x64, 0]}}) = 80process_vm_readv(2867176, [{iov_base="\0\0\0\0\0\0\0\0\260z&*)v\0\0\307\16\340=\376\177\0\0\327\331%*)v\0\0"..., iov_len=4096}], 1, [{iov_base=0x7ffedaa37000, iov_len=4096}], 1, 0) = 4096write(2, "write(1, \"glibc=2.39 ctor=1 argc"..., 50) = 50ptrace(PTRACE_SYSCALL, 2867176, NULL, 0) = 0wait4(-1, [{WIFSTOPPED(s) && WSTOPSIG(s) == SIGTRAP | 0x80}], __WALL, NULL) = 2867176--- SIGCHLD {si_signo=SIGCHLD, si_code=CLD_TRAPPED, si_pid=2867176, si_uid=1000, si_status=SIGTRAP, si_utime=0, si_stime=0} ---wait4(-1, 0x7fffc19335dc, WNOHANG|__WALL, NULL) = 0ptrace(PTRACE_GET_SYSCALL_INFO, 2867176, 88, {op=PTRACE_SYSCALL_INFO_EXIT, arch=AUDIT_ARCH_X86_64, instruction_pointer=0x762929f1c804, stack_pointer=0x7ffedaa37358, exit={rval=62, is_error=0}}) = 33write(2, ") = 62\n", 7) = 7ptrace(PTRACE_SYSCALL, 2867176, NULL, 0) = 0wait4(-1, [{WIFSTOPPED(s) && WSTOPSIG(s) == SIGTRAP | 0x80}], __WALL, NULL) = 2867176--- SIGCHLD {si_signo=SIGCHLD, si_code=CLD_TRAPPED, si_pid=2867176, si_uid=1000, si_status=SIGTRAP, si_utime=0, si_stime=0} ---wait4(-1, 0x7fffc19335dc, WNOHANG|__WALL, NULL) = 0ptrace(PTRACE_GET_SYSCALL_INFO, 2867176, 88, {op=PTRACE_SYSCALL_INFO_ENTRY, arch=AUDIT_ARCH_X86_64, instruction_pointer=0x762929eee2dd, stack_pointer=0x7ffedaa37458, entry={nr=__NR_exit_group, args=[0, 0xffffffffffffff88, 0xe7, 0x7ffedaa3738f, 0x7ffedaa37400, 0]}}) = 80ptrace(PTRACE_SYSCALL, 2867176, NULL, 0) = 0--- SIGCHLD {si_signo=SIGCHLD, si_code=CLD_TRAPPED, si_pid=2867176, si_uid=1000, si_status=SIGTRAP, si_utime=0, si_stime=0} ---wait4(-1, [{WIFSTOPPED(s) && WSTOPSIG(s) == SIGTRAP}|PTRACE_EVENT_EXIT<<16], __WALL, NULL) = 2867176wait4(-1, 0x7fffc19335dc, WNOHANG|__WALL, NULL) = 0ptrace(PTRACE_SYSCALL, 2867176, NULL, 0) = 0wait4(-1, [{WIFEXITED(s) && WEXITSTATUS(s) == 0}], __WALL, NULL) = 2867176--- SIGCHLD {si_signo=SIGCHLD, si_code=CLD_EXITED, si_pid=2867176, si_uid=1000, si_status=0, si_utime=0, si_stime=0} ---wait4(-1, 0x7fffc19335dc, WNOHANG|__WALL, NULL) = -1 ECHILD (No child processes)write(2, "+++ exited with 0 +++\n", 22) = 22wait4(-1, 0x7fffc19335dc, __WALL, NULL) = -1 ECHILD (No child processes)exit_group(0) = ?+++ exited with 0 +++1. Motivation
Embedded and infrastructure teams routinely ship corrupted binary packets or crash in production because a framing helper called strlen() on a payload containing 0x00 bytes, stored write()'s signed ssize_t -1 error in unsigned size_t (wrapping to SIZE_MAX), or compiled without -Wall -Wextra -Werror across separate translation units. In this studio laboratory, you will engineer a warning-clean multi-file ISO C11 static library (libsysbuf.a) and CLI boundary tracer (inspector) that strictly separates zero-syscall Ring 3 framing from EINTR-resilient Ring 0 write() transfers and errno validation.
2. Learning Objectives
- Build a multi-file ISO C11 static archive (
ar rcs libsysbuf.a sysbuf.o) and linked executable (inspector) using GNU Make with-std=c11 -Wall -Wextra -Werror -O2 -g. - Implement zero-syscall
Ring 3big-endian binary header encoding (sysbuf_encode_header) across payloads containing embedded0x00bytes withoutstrlen()truncation. - Implement a partial-count and
EINTR-safesysbuf_write_all()loop over signedssize_tand verify negative-descriptor-1(EBADF) diagnostics via thread-localerrno. - Verify under
stracethatRing 3framing, XOR checksumming, andsnprintf()formatting emit0kernelwritetraps prior to the single terminal flush.
3. Environment Requirements
- Host Execution Environment (Tested): POSIX-compliant Linux
6.12LTS (x86_64,glibc2.39+), executing insidelabs/lab_m01_toolchain_tracer/. - Target Board Portability (
ARMv7Cortex-A7): All C11 source files use<stdint.h>exact-width types (uint8_t,uint16_t), explicit big-endian shifts, andsize_t/ssize_t%zuformatting so the identical archive cross-compiles cleanly underarm-linux-gnueabihf-gccwith identical24-byte wire output.
4. Required Software & Hardware
- Software Toolchain:
gcc(GCC11+with ISO C11 support), GNUmake, GNU Binutils (ar,nm,readelf),strace, and/bin/sh. - Hardware: Standard Linux host workstation or container (
0privileged/devnodes or root capabilities required).
5. Complete Executable Commands
Run each command from labs/lab_m01_toolchain_tracer/ to observe the broken starter, build the static archive, inspect ELF symbols, and run the automated TAP 13 test harness:
learner@ksa:~/gl-c01/m01-l03$ bat script.sh File: script.sh # 1. Confirm starter/ fails check.sh deterministically (demonstrating the bugs to fix) cp starter/* files/ 2>/dev/null || true # (Note: coursec labs tests starter/ in a temp copy; inspect starter/ directly!) make -C files clean && make -C files # 2. Inspect archive members and global symbol table (.symtab) inside libsysbuf.a ar t files/libsysbuf.a nm -g files/libsysbuf.a # 3. Execute the CLI summary mode (verifies EBADF on fd=-1 and prints 1 formatted line) ./files/inspector # 4. Inspect exact raw binary frame bytes (24 bytes: 16-byte KSB1 header + 8-byte payload) ./files/inspector --raw | od -tx1 -An # 5. Count Ring 0 write() traps under strace (1 failed write(-1) + 1 stdout flush = 2) strace -e trace=write ./files/inspector 2>&1 >/dev/null | grep -c '^write(' # 6. Run the full TAP version 13 verification suite sh check.sh*Why each command runs:* make -C files compiles sysbuf.o and inspector.o separately before archiving libsysbuf.a via ar rcs and linking -L. -lsysbuf after inspector.o; nm -g confirms exported global symbols (T sysbuf_encode_header, T sysbuf_write_all); od -tx1 proves embedded 0x00 bytes survive intact; strace proves Ring 3 framing triggers zero kernel traps; and sh check.sh validates every contract end-to-end.
6. Annotated Source Code (starter/ Flaws vs files/ Reference)
Flawed Baseline (starter/sysbuf.c & starter/Makefile)
- Missing strict compiler flags:
starter/Makefileomits-std=c11 -Wall -Wextra -Werrorand static-archive rules. - Binary
0x00truncation (starter/sysbuf.c):size_t wrong_len = strlen((const char *)payload);stops atpayload[1] == 0x00, encoding length1instead of8and skipping the XOR checksum (0x00instead of0xb6). - Unsigned
size_terror wrap (starter/sysbuf.c):size_t n = (size_t)write(fd, buf, count);wraps(ssize_t)-1toSIZE_MAXand fails to retry short writes orerrno == EINTR.
Warning-Clean Reference (files/sysbuf.c & files/inspector.c)
sysbuf_encode_header()(files/sysbuf.c): Zeroesdst[0..15], copies"KSB1", shiftschannelandpayload_leninto big-endian network order ((val >> 8U) & 0xFFU), iteratesfor (size_t i = 0; i < payload_len; i++)to computexor_sum(0xb6) andzero_count(2), and returns16with0syscalls.sysbuf_write_all()(files/sysbuf.c): Castsconst void *toconst uint8_t *, capturesssize_t written = write(fd, cursor, remaining), retries whenwritten < 0 && errno == EINTR, returns-1on fatal errors (EBADF), and advances(cursor += (size_t)written, remaining -= (size_t)written)untilremaining == 0U.main()(files/inspector.c): Checksargc > 1 && strcmp(argv[1], "--raw") == 0safely before touchingargv[1], testssysbuf_write_all(-1, ...)(bad_rc == -1 && errno == EBADF), formats a boundedsnprintf()line (ret < 0 || (size_t)ret >= sizeof(line)), and flushes once viasysbuf_write_all(STDOUT_FILENO, ...).
7. Expected Output
learner@ksa:~/gl-c01/m01-l03$ bat listing.txt File: listing.txt $ ./files/inspector frame_bytes=24 payload_bytes=8 null_bytes=2 checksum=0xb6 ebadf_ok=1 glibc=2.39 $ sh check.sh TAP version 13 1..5 ok 1 - builds libsysbuf.a and inspector cleanly with -std=c11 -Wall -Wextra -Werror ok 2 - archives sysbuf.o inside libsysbuf.a via ar ok 3 - preserves embedded 0x00 bytes, XOR checksum 0xb6, and EBADF errno handling ok 4 - emits exact 24-byte raw binary frame with KSB1 header and big-endian lengths ok 5 - executes pure Ring 3 framing with exactly 2 write() syscalls under strace # pass 5/58. Explanation of Observed Behavior
On payload {0x4B, 0x00, 0x53, 0x00, 0x41, 0x01, 0xFE, 0x10}, bitwise XOR evaluates $0x4B \oplus 0x00 \oplus 0x53 \oplus 0x00 \oplus 0x41 \oplus 0x01 \oplus 0xFE \oplus 0x10 = 0xB6$, while counting 0x00 bytes yields null_bytes=2. Under strace -e trace=write, sysbuf_encode_header() and snprintf() execute strictly inside Ring 3 stack RAM (0 trace lines). Calling write(-1, ...) traps into Ring 0, where VFS fdget_pos(-1) returns -EBADF (-9); glibc stores +9 in thread-local errno and returns -1 (ebadf_ok=1). Finally, sysbuf_write_all(STDOUT_FILENO, ...) flushes the entire line in 1 successful write(1, ...) syscall.
9. Experiment Variations
- Reversed Link-Order Experiment: Run
gcc -std=c11 files/inspector.o -Lfiles -lsysbuf -o /tmp/ok_binversusgcc -std=c11 -Lfiles -lsysbuf files/inspector.o -o /tmp/fail_bin(with-DSYSBUF_LINK_ARCHIVE) to observe GNUlddiscardlibsysbuf.abefore seeinginspector.o's unresolved symbols (undefined reference to 'sysbuf_encode_header'). - Link-Time
EINTRInjection (--wrap=write): Link a test wrapper with-Wl,--wrap=writethat returns-1witherrno = EINTRon every odd call and4bytes on every even call, confirmingsysbuf_write_all()still emits all24--rawbytes intact. - Sanitizer Verification: Rebuild with
CFLAGS="-std=c11 -Wall -Wextra -Werror -O1 -g -fsanitize=address,undefined"and verify zeroASanorUBSandiagnostics.
10. Performance Measurements
Measured on the Host x86_64 Linux 6.12 LTS build environment using CLOCK_MONOTONIC across 5 warmup runs and N = 35 timed end-to-end ./inspector executions:
| Metric | Measured Host (x86_64 Linux 6.12) | Target Board Expectation (ARMv7 Cortex-A7 @ 900 MHz) |
|---|---|---|
End-to-end ./inspector latency (p50 / p95 / p99) | 2,543.1 us / 2,869.9 us / 2,896.0 us | ~9,500–14,000 us (dominated by execve + ld-linux dynamic linking) |
In-process sysbuf_encode_header() (24 B, Ring 3) | < 15 ns (0 syscalls) | ~45–80 ns (0 svc #0 traps) |
Total write() syscalls (strace -c) | 2 (1 EBADF + 1 stdout) | 2 (identical ABI syscall count) |
11. Troubleshooting
| Symptom | Root Cause | Fix |
|---|---|---|
undefined reference to 'sysbuf_encode_header' | -lsysbuf placed before inspector.o on the gcc link command line | Move -L. -lsysbuf after all .o object files that call it |
payload_bytes=8 yet checksum=0x4b and header[7]=1 | strlen() used instead of payload_len, stopping at payload[1] == 0x00 | Iterate for (size_t i = 0; i < payload_len; i++) over const uint8_t * |
implicit declaration of function under -std=c11 | #define _POSIX_C_SOURCE 200809L missing or placed below #include | Put #define _POSIX_C_SOURCE 200809L on line 1 of every .c file |
ebadf_ok=0 despite write(-1, ...) failing | An intervening printf() or helper ran before reading errno | Capture int saved_err = errno; immediately on the line after bad_rc = ... |
12. Guided Questions
- Why does
sysbuf_encode_header()accept(const uint8_t *payload, size_t payload_len)instead ofconst char *payload?
- *Hint 1:* Inspect bytes
1and3of the test payload{0x4B, 0x00, 0x53, 0x00, ...}and trace what C string functions treat0x00as. - *Hint 2:* Also recall from
m01-l02whether plaincharhas the same signedness onx86_64versusARMv7EABI when computing bitwise checksums!
- Why does
sysbuf.ccastconst void *buftoconst uint8_t *cursorinsidesysbuf_write_all()?
- *Hint 1:* What happens in strict ISO C11 (
-Wpointer-arith -Werror) if you writebuf += writtendirectly onconst void *buf? - *Hint 2:* Why is
const void *still preferred on the public parameter list ofsysbuf_write_all()?
13. Independent Challenges
- Near Transfer — Frame Decoder & Verifier (
sysbuf_decode_header): Addint sysbuf_decode_header(const uint8_t src[16], const uint8_t *payload, size_t cap, uint16_t *chan_out, size_t *len_out)tosysbuf.cthat validates"KSB1", reconstructs16-bit big-endianchannelandpayload_len, rejectspayload_len > cap(EINVAL), and verifies both the XOR checksum and0x00-byte count (Ebadmsg/EPROTOon mismatch). - Far Transfer — Shared Library (
libsysbuf.so) vs Static Archive (libsysbuf.a): ExtendMakefileto buildlibsysbuf.so(-fPIC -shared), compare.plt/.got.pltJUMP_SLOTentries inreadelf -rWbetween the statically archived and dynamically linkedinspectorbinaries, and measure startup overhead acrossN = 50runs.
14. Solutions & Explanations
- Guided Question 1: Binary protocols treat
0x00as an ordinary value rather than a terminator (strlen()stops at index1), anduint8_tguarantees unsigned[0..255]arithmetic across both signed-charx86_64and unsigned-charARMv7targets. - Guided Question 2: Standard C leaves
voidan incomplete type (sizeof(void)is invalid; GNU C treatsvoid * + 1as a non-standard extension rejected under-Wpedantic/-Werror), so internal byte stepping requiresconst uint8_t *, while keepingconst void *on the public signature allows callers to pass structs orchar *buffers without noisy pointer casts. - Challenge 1 Key Idiom: Reconstruct big-endian
uint16_tvia((uint16_t)src[6] << 8U) | (uint16_t)src[7](casting touint16_t/unsignedbefore shifting to avoid signed promotion surprises) and validatelen <= capbefore scanningpayload.
Run locally in your terminal and check off each verification milestone.
Not started
Tracing Control from PT_INTERP and _start to $?
When the shell invoked ./crt_wrapper_probe frame-07, execve() loaded PT_INTERP, mapped libc.so.6, and entered _start (crt1.o), which called __libc_start_main(). That preamble initialized TLS errno, ran on_crt_init() (ctor=1), and passed argc = 2, argv[1] = "frame-07", and argv[2] = NULL into main(). Inside main(), write(-1, "X", 1U) returned -9 (-EBADF) in %rax, which glibc negated into positive errno = 9 (EBADF) and return value -1. Finally, return EXIT_SUCCESS exited via exit_group(0) (exit_status=0).
Guided Practice: Link-Time Fault Injection with -Wl,--wrap=write
GNU ld's --wrap=write flag redirects calls to write() to __wrap_write() while exposing the real wrapper as __real_write(), letting you test EINTR retry loops deterministically without sending asynchronous signals:
- Step 1 (Write the shim signature): Define
ssize_t __wrap_write(int fd, const void *buf, size_t count)so that on its very first call (static int injected = 0;) it setserrno = EINTR;and returns-1, and on all subsequent calls forwards toextern ssize_t __real_write(int fd, const void *buf, size_t count);. - Step 2 (Verify
write_all_fdrecovery): Linkcrt_wrapper_probe.cwith-Wl,--wrap=writeand confirmwrite_all_fd()retries transparently and prints the complete62-byte output line withexit_status=0.
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_PAGESZ) and getauxval(AT_SYSINFO_EHDR) from <sys/auxv.h>, verifies AT_PAGESZ >= 4096UL and AT_SYSINFO_EHDR != 0UL (confirming the ELF header magic \x7fELF at the mapped vDSO base address in Ring 3 memory!), and confirms under strace -e trace=openat,write ./auxv_probe that reading auxv values emits 0 additional kernel traps after dynamic linking.
Common Production Pitfalls
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).
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).
Knowledge Check
? check 1 · 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?
- [ ]
stracefails to retrieve<string.h>and<stdio.h>calls unless the binary is linked statically - [x] Pure
glibclibrary helpers compute strictly inRing 3user RAM without executing a CPU syscall trap into the Linux kernel - [ ]
crt1.ooffloadsstrlen()andmemcpy()into kernel worker threads beforemain()starts
Answer: Pure glibc library helpers compute strictly in Ring 3 user RAM without executing a CPU syscall trap into the Linux kernel
Why: 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.
? check 2 · (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?
- [ ] Kernel returns
0andglibcsetserrnoto-9without review of our earlier lesson'sssize_tcontract - [x] Kernel returns negative
-EBADF(-9), and theglibcwrapper stores positiveEBADF(9) in thread-localerrnoand returns(ssize_t)-1so the caller can retrieve the error code - [ ] Both the kernel and
glibcreturn positiveEBADF(9), resettingerrnoto0on the nextwrite()
Answer: Kernel returns negative -EBADF (-9), and the glibc wrapper stores positive EBADF (9) in thread-local errno and returns (ssize_t)-1 so the caller can retrieve the error code
Why: 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.
? check 3 · Which routine executes as the ELF entry point before main(int argc, char *argv[]) and guarantees argv[argc] == NULL?
- [x]
_startincrt1.o, which calls__libc_start_main()to initialize TLS/errno, run.init_arrayconstructors, invokemain(argc, argv), and forwardmain's return code toexit() - [ ] The Linux kernel jumps straight to
main()with zero C runtime preamble - [ ]
lddpre-populateserrnoandargv[]inside.rodatawhen you review earlier lesson stages
Answer: _start in crt1.o, which calls __libc_start_main() to initialize TLS/errno, run .init_array constructors, invoke main(argc, argv), and forward main's return code to exit()
Why: _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.
? check 4 · 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?
- [ ] The
./sensor_agentbinary is missing amain()symbol when you review.symtabfrom our earlier lesson - [x] The dynamic loader path stored in the ELF
PT_INTERPsegment (such as/lib/ld-linux-armhf.so.3) is absent from the target rootfs - [ ]
stracemust be installed before.plt/.got.pltbinaries can execute
Answer: The dynamic loader path stored in the ELF PT_INTERP segment (such as /lib/ld-linux-armhf.so.3) is absent from the target rootfs
Why: 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.
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$?.
With toolchain, ELF startup, errno, and strace mastered, Module 2 opens disk files directly to control per-process descriptor allocation, open() bitmasks, and mode & ~umask permissions.
Step sequence — frame strip: steps_m01_l03
execve() builds the 16-byte aligned stack (argc, argv, envp, auxv) and loads PT_INTERP (missing loader => ENOENT).
reveals: step1
highlights: step1
crt1.o _start invokes __libc_start_main(), initializes TLS errno, runs .init_array constructors, and calls main().
reveals: step2
highlights: step2
Pure Ring 3 helpers run in RAM (0 traps), whereas write@plt jumps via .got.plt into libc's syscall instruction.
reveals: step3
highlights: step3
Kernel returns in [-4095, -1] populate thread-local errno and return -1; successful calls leave errno untouched.
reveals: step4
highlights: step4
m02/
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.
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.
Why Naive open() Calls Leak Handles, Corrupt Modes & Trigger UB
Picture a background daemon that closes STDIN_FILENO (0), STDOUT_FILENO (1), and STDERR_FILENO (2) during startup without reopening /dev/null, then calls int db_fd = open("/var/lib/app/keys.db", O_RDWR | O_CREAT) with two arguments, and later calls perror("warn") when a network timeout occurs. Three silent disasters strike in sequence: open() allocates slot 2 (STDERR_FILENO) as db_fd so perror() overwrites keys.db with ASCII error text; omitting the third mode_t argument with O_CREAT pulls random caller register garbage into the new inode's permission bits; and omitting O_CLOEXEC leaks db_fd into every child helper spawned via execve()!
Naive code stumbles on open() because C lacks function overloading (forcing <fcntl.h> to declare open() as a variadic function), Linux encodes O_RDONLY as 0 rather than a bitmask flag, and the kernel silently clears requested permission bits through the process umask. Mastering unbuffered POSIX I/O begins with exact command of descriptor table indexing, open() flag composition, and unsigned bit-mask algebra.
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.
definition (File Descriptors, O_ACCMODE & Process umask): 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.
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 in O(1) amortized time using a two-level unsigned long bitmap inside files->fdt: a top-level bitword identifies the first 64-slot chunk with a 0 bit, and a hardware find-first-zero instruction (tzcnt / clz) selects the exact lowest free integer (3 in a fresh process where 0, 1, and 2 are open). Closing a descriptor clears its bitmap bit immediately, so the very next open() reclaims that exact slot.
When O_CREAT or O_TMPFILE creates a new inode, VFS combines the 4-bit file type (S_IFREG = 0100000) with masked 12-bit permissions via effective_mode = mode & ~current->fs->umask. For requested mode = 0666 (110 110 110 binary: rw-rw-rw-) under standard umask = 0022 (000 010 010, so ~0022 masks out group-write and other-write), bitwise AND yields 0666 & 0755 = 0644 (rw-r--r--). Whenever composing custom bitmasks or rotating 32-bit protocol flags in ISO C11, always shift unsigned types (1U << 31, UINT32_C(1) << bit): 1 << 31 overflows a 32-bit signed int (UB), and (x << n) | (x >> (32 - n)) evaluates x >> 32 (UB) when n == 0! Writing (x << (n & 31U)) | (x >> ((-n) & 31U)) eliminates both UB edges and compiles to a single rol/ror instruction at -O2.
open() Flag / Macro | Octal / Mask Category | Exact Linux 6.12 VFS Contract | |
|---|---|---|---|
O_RDONLY / O_WRONLY / O_RDWR | 0 / 1 / 2 (O_ACCMODE = 03) | Mutually exclusive access modes; test via (fl & O_ACCMODE) == O_RDONLY | |
O_CREAT & O_TMPFILE | Creation flags | Require 3rd mode_t argument (0644 or S_I*); O_TMPFILE creates unnamed inode | |
O_EXCL | Atomic existence guard | With O_CREAT, fails atomically with EEXIST if path exists (never follows final symlink) | |
O_TRUNC & O_APPEND | Open / write modifiers | O_TRUNC resets length to 0; O_APPEND moves cursor to i_size before every write() | |
O_CLOEXEC | Descriptor-slot flag | Sets FD_CLOEXEC atomically at open so execve() never leaks fd to child binaries | |
O_NOFOLLOW & O_DIRECTORY | Path traversal guards | Fails with ELOOP if target is a symlink or ENOTDIR if target is not a directory | |
| `S_IRUSR\ | S_IWUSR / S_IRGRP / S_IROTH` | 0600 / 0040 / 0004 | Owner rw-, group r--, other r-- (0644), masked by ~umask |
Figure 2.1a. Per-process descriptor table lowest-slot allocation and open() flag composition.
Figure 2.1b. Kernel fdtable O(1) bitmap scan and 16-bit POSIX mode_t / ~umask bitfield algebra.
- Step 1. Compose one O_ACCMODE access value with O_CREAT | O_EXCL | O_CLOEXEC and an explicit octal mode_t.
- Step 2. Kernel __alloc_fd() scans files_struct->fdt open_fds in O(1) to claim the lowest unused integer slot.
- Step 3. VFS computes effective_mode = mode & ~umask on newly created inodes; inspect modes via (fl & O_ACCMODE).
- Step 4. Closing a descriptor clears its bitmap bit immediately so the next open() reclaims that lowest slot.
Figure 2.1c. Every open() claims the lowest unused fdtable slot, seals FD_CLOEXEC atomically when O_CLOEXEC is passed, and masks new inode permissions by ~umask.
Variadic open() Prototypes, openat() & unlink()
Include <fcntl.h>, <sys/stat.h>, <sys/types.h>, and <unistd.h> under #define _POSIX_C_SOURCE 200809L. In glibc 2.39, user-space open(path, flags, ...) forwards internally to openat(AT_FDCWD, path, flags, mode). Release descriptors in reverse acquisition order (close(fd2) then close(fd1)) so error branches never leak slots toward RLIMIT_NOFILE (EMFILE), and remove directory entries cleanly via int unlink(const char *pathname).
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. EISDIR pathname refers to a directory and write access was requested. EMFILE Per-process RLIMIT_NOFILE descriptor table is full. ENOENT O_CREAT was not set and pathname is missing. FLAGS O_CLOEXEC Atomically set FD_CLOEXEC so execve(2) closes fd. O_CREAT Create regular file if missing; requires octal mode. O_EXCL With O_CREAT, fail atomically with EEXIST if path exists. O_TRUNC Truncate existing regular file to 0 bytes on writable open. O_APPEND Move file offset to current i_size before every write(2). SEE ALSO close(2), fcntl(2), read(2), umask(2), unlink(2), write(2) Kernel Systems Academy Lesson 2.1 open(2) GL-C01 quick reference · full manual page: man 2 open Auditing Lowest-Slot Reuse, O_ACCMODE, umask & UB-Free Rotates
Save open_perm_audit.c below. It verifies STDIN_FILENO..STDERR_FILENO (0,1,2), sets umask(0022), creates p1 (0666 & ~0022 == 0644) and p2 (S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH), proves close(fd1) causes the next open() (fd3) to reclaim that exact lowest integer, checks (fl & O_ACCMODE) == O_RDONLY, confirms O_CREAT | O_EXCL fails with EEXIST, verifies unlink() (ENOENT), and tests UB-free UINT32_C(1) << 31 + rotl32_safe(..., 0U) under -fsanitize=undefined.
learner@ksa:~/gl-c01/m02-l01$ bat -H 12 -H 26 -H 41 open_perm_audit.c File: open_perm_audit.c #define _POSIX_C_SOURCE 200809L #include <errno.h> #include <fcntl.h> #include <stdint.h> #include <stdio.h> #include <stdlib.h> #include <sys/stat.h> #include <sys/types.h> #include <unistd.h> static inline uint32_t rotl32_safe(uint32_t x, unsigned int n) { return (x << (n & 31U)) | (x >> ((-n) & 31U)); } int main(void) { const char *p1 = "/tmp/ksa_m02_a.tmp"; const char *p2 = "/tmp/ksa_m02_b.tmp"; const char *p3 = "/tmp/ksa_m02_del.tmp"; (void)unlink(p1); (void)unlink(p2); (void)unlink(p3); mode_t old_mask = umask(0022); int fd1 = open(p1, O_RDWR | O_CREAT | O_EXCL | O_CLOEXEC, 0666); int fd2 = open(p2, O_WRONLY | O_CREAT | O_TRUNC | O_CLOEXEC, S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH); int fd_del = open(p3, O_WRONLY | O_CREAT | O_TRUNC | O_CLOEXEC, 0600); if (fd1 == -1 || fd2 == -1 || fd_del == -1) { perror("open"); umask(old_mask); return EXIT_FAILURE; } (void)close(fd_del); int consecutive = (fd2 == fd1 + 1); if (close(fd1) == -1) { umask(old_mask); return EXIT_FAILURE; } int fd3 = open(p1, O_RDONLY | O_CLOEXEC); int fl3 = (fd3 != -1) ? fcntl(fd3, F_GETFL) : -1; int acc_rdonly = (fl3 != -1 && (fl3 & O_ACCMODE) == O_RDONLY); int reused_lowest = (fd3 == fd1 && acc_rdonly); errno = 0; int dup_excl = open(p1, O_WRONLY | O_CREAT | O_EXCL | O_CLOEXEC, 0644); int excl_eexist = (dup_excl == -1 && errno == EEXIST); int unlinked = (unlink(p3) == 0); errno = 0; int gone_fd = open(p3, O_RDONLY | O_CLOEXEC); int unlink_ok = (unlinked && gone_fd == -1 && errno == ENOENT); uint32_t hi_mask = UINT32_C(1) << 31; int rot_ok = (rotl32_safe(hi_mask, 0U) == 0x80000000U && rotl32_safe(hi_mask, 1U) == 0x00000001U); if (fd3 != -1) (void)close(fd3); (void)close(fd2); umask(old_mask); printf("std_fds=%d,%d,%d consecutive=%d reused_lowest=%d\n", STDIN_FILENO, STDOUT_FILENO, STDERR_FILENO, consecutive, reused_lowest); printf("excl_eexist=%d unlink_ok=%d rot_ub_safe=%d\n", excl_eexist, unlink_ok, rot_ok); return EXIT_SUCCESS; }- Masking shift counts with & 31U avoids x >> 32 Undefined Behavior when n == 0 while compiling to a single rotate instruction.
- Pass 0666 with O_CREAT | O_EXCL | O_CLOEXEC; kernel stores 0666 & ~0022 = 0644 atomically.
- Mask with O_ACCMODE (never flags & O_RDONLY) to verify fd3 opened read-only.
Verifying Descriptor Slots and Masked Inode Permissions
Compile open_perm_audit under -fsanitize=undefined, verify the runtime invariants, inspect the effective octal permissions (644 644) stored on disk via stat -c '%a', and remove the scratch files.
learner@ksa:~/gl-c01/m02-l01gcc -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_auditstd_fds=0,1,2 consecutive=1 reused_lowest=1excl_eexist=1 unlink_ok=1 rot_ub_safe=1learner@ksa:~/gl-c01/m02-l01echo "$(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_audit644 644learner@ksa:~/gl-c01/m02-l01Tracing Bitmap Reuse, O_ACCMODE & umask Enforcement
Every check in open_perm_audit confirmed the VFS descriptor contract: fd1 and fd2 claimed consecutive slots (3 and 4), closing fd1 cleared bit 3 in files_struct so fd3 immediately reclaimed slot 3 (reused_lowest=1), (fl3 & O_ACCMODE) == O_RDONLY verified read-only access cleanly, and 0666 & ~0022 stamped 0644 onto disk while O_CREAT | O_EXCL blocked duplicate creation with EEXIST.
Guided Practice: Exact Private Keyfile Creation Under Loose umask
Suppose an administrator runs your key-provisioning tool in a shell whose umask is 0000 (clearing zero bits!), and you need /tmp/ksa_secret.key created atomically with exact owner-only 0600 (rw-------) permissions even if umask is 0000 or 0077:
- Step 1 (Compute
effective_modeacross bothumaskextremes): Evaluate0600 & ~0000and0600 & ~0077(0600in both cases!), then evaluate what would happen ifumaskwere0200(0600 & ~0200 == 0400, stripping owner write!). - Step 2 (Complete the
open()call): Write the exactopen()call combiningO_WRONLY,O_CREAT,O_EXCL,O_NOFOLLOW, andO_CLOEXECwithS_IRUSR | S_IWUSR, saving and restoringumask(0077)around creation so group/other bits can never be set.
Independent Practice: Descriptor-Leak Exhaustion (EMFILE) Probe
Write a C11 diagnostic emfile_probe.c that lowers the process's soft RLIMIT_NOFILE ceiling to 16 inside main() using getrlimit(RLIMIT_NOFILE, &rl) and setrlimit(RLIMIT_NOFILE, &rl) (<sys/resource.h>), opens /dev/null with O_RDONLY | O_CLOEXEC in a bounded array until open() returns -1, asserts errno == EMFILE, closes every acquired descriptor in strict reverse (LIFO) order, and proves a fresh open("/dev/null", O_RDONLY | O_CLOEXEC) succeeds again at the lowest slot (3).
Common Production Pitfalls
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.
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.
Knowledge Check
? check 1 · 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?
- [ ]
3, because slots0..2remain reserved permanently - [x]
0, because the Linux kernel always allocates the lowest-numbered unused slot in the process descriptor table - [ ]
1023, because descriptors allocate downward fromRLIMIT_NOFILE - 1
Answer: 0, because the Linux kernel always allocates the lowest-numbered unused slot in the process descriptor table
Why: 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().
? check 2 · (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?
- [x]
0640(rw-r-----), computed via0664 & ~0027using octal bitmasks from the previous module - [ ]
0664(rw-rw-r--), because symbolicS_I*macros bypassumask - [ ]
0627, computed by bitwise ORingmode | umask
Answer: 0640 (rw-r-----), computed via 0664 & ~0027 using octal bitmasks from the previous module
Why: 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.
? check 3 · 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?
- [ ]
O_CLOEXECflushes dirty kernel pages to storage twice as fast - [ ]
O_CLOEXECunlinks temporary files automatically whenclose()runs - [x]
O_CLOEXECsetsFD_CLOEXECatomically when the slot is allocated, eliminating the multithreaded race window where another thread callsfork()+execve()beforefcntl()runs
Answer: O_CLOEXEC sets FD_CLOEXEC atomically when the slot is allocated, eliminating the multithreaded race window where another thread calls fork() + execve() before fcntl() runs
Why: 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.
? check 4 · 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)?
- [ ] Unsigned
uint32_tbit shifts are forbidden in strict-std=c11 - [x]
1is a 32-bit signedintso1 << 31overflows the sign bit (C11 UB), andn == 0evaluatesx >> 32(shift by bit-width UB); use1U << 31and(x << (n & 31U)) | (x >> ((-n) & 31U)) - [ ]
rot(v, 0U)requires#include <fcntl.h>to unlock barrel-shifter intrinsics
Answer: 1 is a 32-bit signed int so 1 << 31 overflows the sign bit (C11 UB), and n == 0 evaluates x >> 32 (shift by bit-width UB); use 1U << 31 and (x << (n & 31U)) | (x >> ((-n) & 31U))
Why: 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.
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).
Next, with open descriptors in hand, we will implement binary-safe write_all() and read_full() loops across all four ssize_t return regimes, MAX_RW_COUNT, and Linux close() error semantics.
Step sequence — frame strip: steps_m02_l01
Compose one O_ACCMODE access value with O_CREAT | O_EXCL | O_CLOEXEC and an explicit octal mode_t.
reveals: step1
highlights: step1
Kernel __alloc_fd() scans files_struct->fdt open_fds in O(1) to claim the lowest unused integer slot.
reveals: step2
highlights: step2
VFS computes effective_mode = mode & ~umask on newly created inodes; inspect modes via (fl & O_ACCMODE).
reveals: step3
highlights: step3
Closing a descriptor clears its bitmap bit immediately so the next open() reclaims that lowest slot.
reveals: step4
highlights: step4
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.
Why Single-Shot read() / write() & Retried close() Corrupt Data
Consider three bugs pulled straight from real incident postmortems. First, a telemetry copier runs ssize_t n = read(src, buf, 1024); write(dst, buf, 1024);—when the final file chunk holds 30 bytes, write() dumps 994 bytes of uninitialized stack secrets into dst! Second, a checkpoint tool allocates a 3 GiB RAM buffer on 64-bit Linux and calls read(fd, buf, 3ULL << 30) once on a local ext4 file with zero signals pending—and silently truncates the snapshot at 2,147,479,552 bytes! Third, a multithreaded server wraps close(fd) in while (close(fd) == -1 && errno == EINTR) {}—and randomly disconnects a brand-new client socket opened microseconds earlier on another thread!
Single-shot transfers fail because POSIX read() and write() are byte-stream primitives permitted to transfer fewer bytes than requested ("short counts") across pipes, sockets, terminals, signal interruptions, and kernel VFS chunk caps. Meanwhile, read() never NUL-terminates raw bytes, and Linux close(fd) detaches the descriptor slot before waiting on driver flush hooks.
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.
definition (Short Counts, MAX_RW_COUNT & Linux close()): 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.
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, size_t count) (count > 0) lands in one of four disjoint mathematical regimes. Because ISO C11 forbids pointer arithmetic on void * (sizeof(void) is incomplete), production wrappers cast buf to uint8_t * (1-byte stride) and maintain the loop invariant done + left == count via next_ptr = p + done and remaining = count - done. On a 3 GiB (3,221,225,472-byte) regular-file transfer, Iteration 1 transfers MAX_RW_COUNT (2,147,479,552 bytes) and Iteration 2 transfers the remaining 3,221,225,472 - 2,147,479,552 = 1,073,745,920 bytes (1 GiB + 4 KiB), followed by n == 0 at End-Of-File (EOF).
ssize_t n Regime | Meaning in Linux 6.12 VFS | Mandatory Caller Loop Action |
|---|---|---|
n == (ssize_t)count | Full requested window transferred; f_pos += n | Advance done += (size_t)n; loop terminates cleanly |
0 < n < (ssize_t)count | Legal short count (pipe/socket/signal/MAX_RW_COUNT) | Advance p += (size_t)n, subtract (size_t)n from left, continue |
n == 0 (count > 0) | On read(): clean EOF (0 bytes remain); on write(): zero progress | Break read_full() cleanly and return (ssize_t)done |
n == -1 | Zero bytes moved on this call; cause in thread-local errno | If errno == EINTR, retry unchanged (p, left); else return -1 |
Figure 2.2. All four ssize_t return regimes, MAX_RW_COUNT (0x7ffff000) chunking, and single-shot Linux close(fd) semantics.
- Step 1. Cast void * to uint8_t * so byte-exact pointer advancement (p + done) obeys strict ISO C11.
- Step 2. Capture returns in signed ssize_t; retry unchanged (p + done, count - done) only when n < 0 && errno == EINTR.
- Step 3. Break cleanly on n == 0 (EOF) and advance done += (size_t)n across pipe bursts or 0x7ffff000 MAX_RW_COUNT caps.
- Step 4. Inspect close(fd) == -1 once to log deferred EIO, and never retry close(fd) after slot deallocation.
Figure 2.2b. Robust POSIX byte I/O wraps every read() and write() in a uint8_t * retry loop and checks close(fd) exactly once without retrying.
Prototypes, Raw Non-NUL Buffers & close(2) Reference
Include <unistd.h>, <errno.h>, and <stdint.h> under #define _POSIX_C_SOURCE 200809L. Remember two non-negotiable rules alongside the retry loop: first, read() transfers raw uninterpreted bytes (including embedded 0x00) and never appends '\0', so text callers must cap reads at sizeof(buf) - 1 and assign buf[n] = '\0' (or format bounded printf("%.*s", (int)n, buf)); second, always inspect if (close(fd) == -1) on writable files so deferred network/filesystem EIO errors are logged rather than silently dropped.
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. EBADF fd is not a valid open descriptor or lacks required access mode. EINTR Interrupted by signal before any bytes moved on this call. EIO Low-level storage error (may surface at write() or close()). ENOSPC Filesystem or block device has no free space for write(). EPIPE write() hit a pipe/socket with closed readers (raises SIGPIPE). NOTES Never retry close(fd) after EINTR on Linux; fd is already deallocated. SEE ALSO fcntl(2), fsync(2), lseek(2), open(2), pread(2) Kernel Systems Academy Lesson 2.2 read(2) GL-C01 quick reference · full manual page: man 2 read Implementing Pipe-Tested write_all() and read_full() Loops
Save short_io_loop.c below. To prove read_full() reassembles genuine kernel short counts (not merely full single-shot disk reads!), it streams a 64-byte binary frame (starting with "HDR0" and embedding 0x00 bytes every 8th offset) in uneven 7-, 19-, and 38-byte write_all() bursts across both a live kernel pipe() (forcing read_full() to loop across partial chunks: pipe_calls >= 2) and a regular file (eof_read == 0), while checking close() returns.
learner@ksa:~/gl-c01/m02-l02$ bat -H 14 -H 32 -H 68 short_io_loop.c File: short_io_loop.c #define _POSIX_C_SOURCE 200809L #include <errno.h> #include <fcntl.h> #include <stdint.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <sys/stat.h> #include <unistd.h> static int write_all(int fd, const void *buf, size_t count) { const uint8_t *p = (const uint8_t *)buf; size_t left = count; while (left > 0U) { ssize_t n = write(fd, p, left); if (n < 0) { if (errno == EINTR) { continue; } return -1; } p += (size_t)n; left -= (size_t)n; } return 0; } static ssize_t read_full(int fd, void *buf, size_t count, unsigned int *calls_out) { uint8_t *p = (uint8_t *)buf; size_t total = 0U; unsigned int calls = 0U; while (total < count) { calls++; ssize_t n = read(fd, p + total, count - total); if (n == 0) { break; } if (n < 0) { if (errno == EINTR) { continue; } return -1; } total += (size_t)n; } if (calls_out != NULL) { *calls_out = calls; } return (ssize_t)total; } int main(void) { const char *path = "/tmp/ksa_m02_io.bin"; (void)unlink(path); uint8_t tx[64]; for (size_t i = 0; i < sizeof(tx); i++) { tx[i] = (i % 8U == 3U) ? 0x00U : (uint8_t)(0x20U + i); } memcpy(tx, "HDR0", 4U); int pfd[2]; if (pipe(pfd) == -1) return EXIT_FAILURE; uint8_t prx[20]; unsigned int pipe_calls = 0U; if (write_all(pfd[1], tx, 7U) == -1) return EXIT_FAILURE; ssize_t p1 = read(pfd[0], prx, sizeof(prx)); if (p1 != 7 || write_all(pfd[1], tx + 7U, 13U) == -1) return EXIT_FAILURE; if (close(pfd[1]) == -1) return EXIT_FAILURE; ssize_t p2 = read_full(pfd[0], prx + 7U, 13U, &pipe_calls); (void)close(pfd[0]); int wfd = open(path, O_WRONLY | O_CREAT | O_TRUNC | O_CLOEXEC, 0644); if (wfd == -1) return EXIT_FAILURE; if (write_all(wfd, tx, 17U) == -1 || write_all(wfd, tx + 17U, 19U) == -1 || write_all(wfd, tx + 36U, 28U) == -1 || close(wfd) == -1) { (void)unlink(path); return EXIT_FAILURE; } int rfd = open(path, O_RDONLY | O_CLOEXEC); if (rfd == -1) return EXIT_FAILURE; uint8_t rx[64]; memset(rx, 0xFFU, sizeof(rx)); ssize_t got = read_full(rfd, rx, 20U, NULL); ssize_t rest = read_full(rfd, rx + 20U, 44U, NULL); uint8_t probe = 0U; ssize_t eof_ret = read(rfd, &probe, 1U); int match = (memcmp(tx, rx, sizeof(tx)) == 0 && memcmp(tx, prx, sizeof(prx)) == 0 && p2 == 13); char safe_label[5]; memcpy(safe_label, rx, 4U); safe_label[4] = '\0'; if (close(rfd) == -1 || unlink(path) == -1) return EXIT_FAILURE; printf("first_window=%zd rest_window=%zd total_match=%d\n", got, rest, match); printf("eof_read=%zd label=%s pipe_short=%zd calls_ge_1=%d\n", eof_ret, safe_label, p1, pipe_calls >= 1U); return EXIT_SUCCESS; }- Cast const void * to const uint8_t * so byte-exact pointer arithmetic p += (size_t)n is valid ISO C11.
- Break cleanly when read() returns 0 (EOF) so truncated files return exact accumulated byte count instead of spinning.
- Writing 7 bytes into the pipe before reading 20 bytes forces a real kernel short read (7 bytes), proving read_full() loops.
Verifying Pipe Short Reads, Binary Reassembly & strace
Compile short_io_loop.c, verify the real 7-byte short pipe read (pipe_short=7), byte-exact 64-byte binary reassembly (total_match=1), and clean eof_read=0, then inspect the exact write and read syscalls under strace.
learner@ksa:~/gl-c01/m02-l02gcc -fdiagnostics-color=always -std=c11 -Wall -Wextra -Werror short_io_loop.c -o short_io_looplearner@ksa:~/gl-c01/m02-l02./short_io_loopfirst_window=20 rest_window=44 total_match=1eof_read=0 label=HDR0 pipe_short=7 calls_ge_1=1learner@ksa:~/gl-c01/m02-l02strace -e trace=write ./short_io_loop 2>&1 >/dev/null | grep -c '^write('6learner@ksa:~/gl-c01/m02-l02Under strace, observe the two pipe writes (7 and 13 bytes), the three file writes (17, 19, and 28 bytes), and the final 0 return on read() at byte 64.
learner@ksa:~/gl-c01/m02-l02strace strace -e trace=openat,write,read,close \./short_io_loopexecve("/usr/bin/strace", ["strace", "-e", "trace=openat,write,read,close", "./short_io_loop"], 0x7ffd6f876428 /* 161 vars */) = 0brk(NULL) = 0x555b3e2be000mmap(NULL, 8192, PROT_READ|PROT_WRITE, MAP_PRIVATE|MAP_ANONYMOUS, -1, 0) = 0x72033e6c3000access("/etc/ld.so.preload", R_OK) = -1 ENOENT (No such file or directory)openat(AT_FDCWD, "/etc/ld.so.cache", O_RDONLY|O_CLOEXEC) = 3fstat(3, {st_mode=S_IFREG|0644, st_size=147944, ...}) = 0mmap(NULL, 147944, PROT_READ, MAP_PRIVATE, 3, 0) = 0x72033e69e000close(3) = 0openat(AT_FDCWD, "/lib/x86_64-linux-gnu/libunwind-ptrace.so.0", O_RDONLY|O_CLOEXEC) = 3read(3, "\177ELF\2\1\1\0\0\0\0\0\0\0\0\0\3\0>\0\1\0\0\0\0\0\0\0\0\0\0\0"..., 832) = 832fstat(3, {st_mode=S_IFREG|0644, st_size=18656, ...}) = 0mmap(NULL, 20808, PROT_READ, MAP_PRIVATE|MAP_DENYWRITE, 3, 0) = 0x72033e698000mmap(0x72033e699000, 8192, PROT_READ|PROT_EXEC, MAP_PRIVATE|MAP_FIXED|MAP_DENYWRITE, 3, 0x1000) = 0x72033e699000mmap(0x72033e69b000, 4096, PROT_READ, MAP_PRIVATE|MAP_FIXED|MAP_DENYWRITE, 3, 0x3000) = 0x72033e69b000mmap(0x72033e69c000, 8192, PROT_READ|PROT_WRITE, MAP_PRIVATE|MAP_FIXED|MAP_DENYWRITE, 3, 0x3000) = 0x72033e69c000close(3) = 0openat(AT_FDCWD, "/lib/x86_64-linux-gnu/libunwind-x86_64.so.8", O_RDONLY|O_CLOEXEC) = 3read(3, "\177ELF\2\1\1\0\0\0\0\0\0\0\0\0\3\0>\0\1\0\0\0\0\0\0\0\0\0\0\0"..., 832) = 832fstat(3, {st_mode=S_IFREG|0644, st_size=67672, ...}) = 0mmap(NULL, 113136, PROT_READ, MAP_PRIVATE|MAP_DENYWRITE, 3, 0) = 0x72033e67c000mmap(0x72033e67e000, 49152, PROT_READ|PROT_EXEC, MAP_PRIVATE|MAP_FIXED|MAP_DENYWRITE, 3, 0x2000) = 0x72033e67e000mmap(0x72033e68a000, 8192, PROT_READ, MAP_PRIVATE|MAP_FIXED|MAP_DENYWRITE, 3, 0xe000) = 0x72033e68a000mmap(0x72033e68c000, 8192, PROT_READ|PROT_WRITE, MAP_PRIVATE|MAP_FIXED|MAP_DENYWRITE, 3, 0xf000) = 0x72033e68c000mmap(0x72033e68e000, 39408, PROT_READ|PROT_WRITE, MAP_PRIVATE|MAP_FIXED|MAP_ANONYMOUS, -1, 0) = 0x72033e68e000close(3) = 0openat(AT_FDCWD, "/lib/x86_64-linux-gnu/libc.so.6", O_RDONLY|O_CLOEXEC) = 3read(3, "\177ELF\2\1\1\3\0\0\0\0\0\0\0\0\3\0>\0\1\0\0\0\220\243\2\0\0\0\0\0"..., 832) = 832pread64(3, "\6\0\0\0\4\0\0\0@\0\0\0\0\0\0\0@\0\0\0\0\0\0\0@\0\0\0\0\0\0\0"..., 784, 64) = 784fstat(3, {st_mode=S_IFREG|0755, st_size=2129424, ...}) = 0pread64(3, "\6\0\0\0\4\0\0\0@\0\0\0\0\0\0\0@\0\0\0\0\0\0\0@\0\0\0\0\0\0\0"..., 784, 64) = 784mmap(NULL, 2174352, PROT_READ, MAP_PRIVATE|MAP_DENYWRITE, 3, 0) = 0x72033e400000mmap(0x72033e428000, 1609728, PROT_READ|PROT_EXEC, MAP_PRIVATE|MAP_FIXED|MAP_DENYWRITE, 3, 0x28000) = 0x72033e428000mmap(0x72033e5b1000, 323584, PROT_READ, MAP_PRIVATE|MAP_FIXED|MAP_DENYWRITE, 3, 0x1b1000) = 0x72033e5b1000mmap(0x72033e600000, 24576, PROT_READ|PROT_WRITE, MAP_PRIVATE|MAP_FIXED|MAP_DENYWRITE, 3, 0x1ff000) = 0x72033e600000mmap(0x72033e606000, 52624, PROT_READ|PROT_WRITE, MAP_PRIVATE|MAP_FIXED|MAP_ANONYMOUS, -1, 0) = 0x72033e606000close(3) = 0openat(AT_FDCWD, "/lib/x86_64-linux-gnu/liblzma.so.5", O_RDONLY|O_CLOEXEC) = 3read(3, "\177ELF\2\1\1\0\0\0\0\0\0\0\0\0\3\0>\0\1\0\0\0\0\0\0\0\0\0\0\0"..., 832) = 832fstat(3, {st_mode=S_IFREG|0644, st_size=202904, ...}) = 0mmap(NULL, 200728, PROT_READ, MAP_PRIVATE|MAP_DENYWRITE, 3, 0) = 0x72033e64a000mmap(0x72033e64d000, 139264, PROT_READ|PROT_EXEC, MAP_PRIVATE|MAP_FIXED|MAP_DENYWRITE, 3, 0x3000) = 0x72033e64d000mmap(0x72033e66f000, 45056, PROT_READ, MAP_PRIVATE|MAP_FIXED|MAP_DENYWRITE, 3, 0x25000) = 0x72033e66f000mmap(0x72033e67a000, 8192, PROT_READ|PROT_WRITE, MAP_PRIVATE|MAP_FIXED|MAP_DENYWRITE, 3, 0x30000) = 0x72033e67a000close(3) = 0openat(AT_FDCWD, "/lib/x86_64-linux-gnu/libunwind.so.8", O_RDONLY|O_CLOEXEC) = 3read(3, "\177ELF\2\1\1\0\0\0\0\0\0\0\0\0\3\0>\0\1\0\0\0\0\0\0\0\0\0\0\0"..., 832) = 832fstat(3, {st_mode=S_IFREG|0644, st_size=63776, ...}) = 0mmap(NULL, 109328, PROT_READ, MAP_PRIVATE|MAP_DENYWRITE, 3, 0) = 0x72033e62f000mmap(0x72033e632000, 40960, PROT_READ|PROT_EXEC, MAP_PRIVATE|MAP_FIXED|MAP_DENYWRITE, 3, 0x3000) = 0x72033e632000mmap(0x72033e63c000, 8192, PROT_READ, MAP_PRIVATE|MAP_FIXED|MAP_DENYWRITE, 3, 0xd000) = 0x72033e63c000mmap(0x72033e63e000, 8192, PROT_READ|PROT_WRITE, MAP_PRIVATE|MAP_FIXED|MAP_DENYWRITE, 3, 0xe000) = 0x72033e63e000mmap(0x72033e640000, 39696, PROT_READ|PROT_WRITE, MAP_PRIVATE|MAP_FIXED|MAP_ANONYMOUS, -1, 0) = 0x72033e640000close(3) = 0mmap(NULL, 8192, PROT_READ|PROT_WRITE, MAP_PRIVATE|MAP_ANONYMOUS, -1, 0) = 0x72033e62d000arch_prctl(ARCH_SET_FS, 0x72033e62e380) = 0set_tid_address(0x72033e62e650) = 2867201set_robust_list(0x72033e62e660, 24) = 0rseq(0x72033e62eca0, 0x20, 0, 0x53053053) = 0mprotect(0x72033e600000, 16384, PROT_READ) = 0mprotect(0x72033e67a000, 4096, PROT_READ) = 0mprotect(0x72033e63e000, 4096, PROT_READ) = 0mprotect(0x72033e68c000, 4096, PROT_READ) = 0mprotect(0x72033e69c000, 4096, PROT_READ) = 0mprotect(0x555b3a8e4000, 417792, PROT_READ) = 0mprotect(0x72033e703000, 8192, PROT_READ) = 0prlimit64(0, RLIMIT_STACK, NULL, {rlim_cur=8192*1024, rlim_max=RLIM64_INFINITY}) = 0munmap(0x72033e69e000, 147944) = 0getrandom("\xc3\x8c\x68\xa3\xd9\x6b\xad\xf6", 8, GRND_NONBLOCK) = 8brk(NULL) = 0x555b3e2be000brk(0x555b3e2df000) = 0x555b3e2df000openat(AT_FDCWD, "/usr/lib/locale/locale-archive", O_RDONLY|O_CLOEXEC) = 3fstat(3, {st_mode=S_IFREG|0644, st_size=5719296, ...}) = 0mmap(NULL, 5719296, PROT_READ, MAP_PRIVATE, 3, 0) = 0x72033de00000close(3) = 0openat(AT_FDCWD, "/usr/share/locale/locale.alias", O_RDONLY|O_CLOEXEC) = 3fstat(3, {st_mode=S_IFREG|0644, st_size=2996, ...}) = 0read(3, "# Locale name alias data base.\n#"..., 4096) = 2996read(3, "", 4096) = 0close(3) = 0openat(AT_FDCWD, "/usr/lib/locale/C.UTF-8/LC_IDENTIFICATION", O_RDONLY|O_CLOEXEC) = -1 ENOENT (No such file or directory)openat(AT_FDCWD, "/usr/lib/locale/C.utf8/LC_IDENTIFICATION", O_RDONLY|O_CLOEXEC) = 3fstat(3, {st_mode=S_IFREG|0644, st_size=258, ...}) = 0mmap(NULL, 258, PROT_READ, MAP_PRIVATE, 3, 0) = 0x72033e6c2000close(3) = 0openat(AT_FDCWD, "/usr/lib/x86_64-linux-gnu/gconv/gconv-modules.cache", O_RDONLY|O_CLOEXEC) = 3fstat(3, {st_mode=S_IFREG|0644, st_size=27028, ...}) = 0mmap(NULL, 27028, PROT_READ, MAP_SHARED, 3, 0) = 0x72033e6bb000close(3) = 0futex(0x72033e60572c, FUTEX_WAKE_PRIVATE, 2147483647) = 0openat(AT_FDCWD, "/usr/lib/locale/C.UTF-8/LC_MEASUREMENT", O_RDONLY|O_CLOEXEC) = -1 ENOENT (No such file or directory)openat(AT_FDCWD, "/usr/lib/locale/C.utf8/LC_MEASUREMENT", O_RDONLY|O_CLOEXEC) = 3fstat(3, {st_mode=S_IFREG|0644, st_size=23, ...}) = 0mmap(NULL, 23, PROT_READ, MAP_PRIVATE, 3, 0) = 0x72033e6ba000close(3) = 0openat(AT_FDCWD, "/usr/lib/locale/C.UTF-8/LC_TELEPHONE", O_RDONLY|O_CLOEXEC) = -1 ENOENT (No such file or directory)openat(AT_FDCWD, "/usr/lib/locale/C.utf8/LC_TELEPHONE", O_RDONLY|O_CLOEXEC) = 3fstat(3, {st_mode=S_IFREG|0644, st_size=47, ...}) = 0mmap(NULL, 47, PROT_READ, MAP_PRIVATE, 3, 0) = 0x72033e6b9000close(3) = 0openat(AT_FDCWD, "/usr/lib/locale/C.UTF-8/LC_ADDRESS", O_RDONLY|O_CLOEXEC) = -1 ENOENT (No such file or directory)openat(AT_FDCWD, "/usr/lib/locale/C.utf8/LC_ADDRESS", O_RDONLY|O_CLOEXEC) = 3fstat(3, {st_mode=S_IFREG|0644, st_size=127, ...}) = 0mmap(NULL, 127, PROT_READ, MAP_PRIVATE, 3, 0) = 0x72033e6b8000close(3) = 0openat(AT_FDCWD, "/usr/lib/locale/C.UTF-8/LC_NAME", O_RDONLY|O_CLOEXEC) = -1 ENOENT (No such file or directory)openat(AT_FDCWD, "/usr/lib/locale/C.utf8/LC_NAME", O_RDONLY|O_CLOEXEC) = 3fstat(3, {st_mode=S_IFREG|0644, st_size=62, ...}) = 0mmap(NULL, 62, PROT_READ, MAP_PRIVATE, 3, 0) = 0x72033e6b7000close(3) = 0openat(AT_FDCWD, "/usr/lib/locale/C.UTF-8/LC_PAPER", O_RDONLY|O_CLOEXEC) = -1 ENOENT (No such file or directory)openat(AT_FDCWD, "/usr/lib/locale/C.utf8/LC_PAPER", O_RDONLY|O_CLOEXEC) = 3fstat(3, {st_mode=S_IFREG|0644, st_size=34, ...}) = 0mmap(NULL, 34, PROT_READ, MAP_PRIVATE, 3, 0) = 0x72033e6b6000close(3) = 0openat(AT_FDCWD, "/usr/lib/locale/C.UTF-8/LC_MESSAGES", O_RDONLY|O_CLOEXEC) = -1 ENOENT (No such file or directory)openat(AT_FDCWD, "/usr/lib/locale/C.utf8/LC_MESSAGES", O_RDONLY|O_CLOEXEC) = 3fstat(3, {st_mode=S_IFDIR|0755, st_size=4096, ...}) = 0close(3) = 0openat(AT_FDCWD, "/usr/lib/locale/C.utf8/LC_MESSAGES/SYS_LC_MESSAGES", O_RDONLY|O_CLOEXEC) = 3fstat(3, {st_mode=S_IFREG|0644, st_size=48, ...}) = 0mmap(NULL, 48, PROT_READ, MAP_PRIVATE, 3, 0) = 0x72033e6b5000close(3) = 0openat(AT_FDCWD, "/usr/lib/locale/C.UTF-8/LC_MONETARY", O_RDONLY|O_CLOEXEC) = -1 ENOENT (No such file or directory)openat(AT_FDCWD, "/usr/lib/locale/C.utf8/LC_MONETARY", O_RDONLY|O_CLOEXEC) = 3fstat(3, {st_mode=S_IFREG|0644, st_size=270, ...}) = 0mmap(NULL, 270, PROT_READ, MAP_PRIVATE, 3, 0) = 0x72033e6b4000close(3) = 0openat(AT_FDCWD, "/usr/lib/locale/C.UTF-8/LC_COLLATE", O_RDONLY|O_CLOEXEC) = -1 ENOENT (No such file or directory)openat(AT_FDCWD, "/usr/lib/locale/C.utf8/LC_COLLATE", O_RDONLY|O_CLOEXEC) = 3fstat(3, {st_mode=S_IFREG|0644, st_size=1406, ...}) = 0mmap(NULL, 1406, PROT_READ, MAP_PRIVATE, 3, 0) = 0x72033e6b3000close(3) = 0openat(AT_FDCWD, "/usr/lib/locale/C.UTF-8/LC_TIME", O_RDONLY|O_CLOEXEC) = -1 ENOENT (No such file or directory)openat(AT_FDCWD, "/usr/lib/locale/C.utf8/LC_TIME", O_RDONLY|O_CLOEXEC) = 3fstat(3, {st_mode=S_IFREG|0644, st_size=3360, ...}) = 0mmap(NULL, 3360, PROT_READ, MAP_PRIVATE, 3, 0) = 0x72033e6b2000close(3) = 0openat(AT_FDCWD, "/usr/lib/locale/C.UTF-8/LC_NUMERIC", O_RDONLY|O_CLOEXEC) = -1 ENOENT (No such file or directory)openat(AT_FDCWD, "/usr/lib/locale/C.utf8/LC_NUMERIC", O_RDONLY|O_CLOEXEC) = 3fstat(3, {st_mode=S_IFREG|0644, st_size=50, ...}) = 0mmap(NULL, 50, PROT_READ, MAP_PRIVATE, 3, 0) = 0x72033e6b1000close(3) = 0openat(AT_FDCWD, "/usr/lib/locale/C.UTF-8/LC_CTYPE", O_RDONLY|O_CLOEXEC) = -1 ENOENT (No such file or directory)openat(AT_FDCWD, "/usr/lib/locale/C.utf8/LC_CTYPE", O_RDONLY|O_CLOEXEC) = 3fstat(3, {st_mode=S_IFREG|0644, st_size=360460, ...}) = 0mmap(NULL, 360460, PROT_READ, MAP_PRIVATE, 3, 0) = 0x72033e3a7000close(3) = 0getpid() = 2867201uname({sysname="Linux", nodename="sabertooth", ...}) = 0openat(AT_FDCWD, "/proc/sys/kernel/pid_max", O_RDONLY) = 3read(3, "4194304\n", 23) = 8close(3) = 0rt_sigaction(SIGCHLD, {sa_handler=SIG_DFL, sa_mask=[], sa_flags=SA_RESTORER, sa_restorer=0x72033e445330}, {sa_handler=SIG_DFL, sa_mask=[], sa_flags=0}, 8) = 0getuid() = 1000getgid() = 1000clone(child_stack=NULL, flags=CLONE_CHILD_CLEARTID|CLONE_CHILD_SETTID|SIGCHLD, child_tidptr=0x72033e62e650) = 2867202ptrace(PTRACE_SEIZE, 2867202, NULL, 0) = 0kill(2867202, SIGKILL) = 0wait4(2867202, [{WIFSIGNALED(s) && WTERMSIG(s) == SIGKILL}], 0, NULL) = 2867202--- SIGCHLD {si_signo=SIGCHLD, si_code=CLD_KILLED, si_pid=2867202, si_uid=1000, si_status=SIGKILL, si_utime=0, si_stime=0} ---clone(child_stack=NULL, flags=CLONE_CHILD_CLEARTID|CLONE_CHILD_SETTID|SIGCHLD, child_tidptr=0x72033e62e650) = 2867203--- SIGCHLD {si_signo=SIGCHLD, si_code=CLD_TRAPPED, si_pid=2867203, si_uid=1000, si_status=SIGSTOP, si_utime=0, si_stime=0} ---wait4(2867203, [{WIFSTOPPED(s) && WSTOPSIG(s) == SIGSTOP}], 0, NULL) = 2867203ptrace(PTRACE_SETOPTIONS, 2867203, NULL, PTRACE_O_TRACESYSGOOD) = 0ptrace(PTRACE_GET_SYSCALL_INFO, 2867203, 88, {op=PTRACE_SYSCALL_INFO_NONE, arch=AUDIT_ARCH_X86_64, instruction_pointer=0x72033e44553b, stack_pointer=0x7fff31d57fe8}) = 24ptrace(PTRACE_SYSCALL, 2867203, NULL, 0) = 0wait4(2867203, [{WIFSTOPPED(s) && WSTOPSIG(s) == SIGTRAP | 0x80}], 0, NULL) = 2867203--- SIGCHLD {si_signo=SIGCHLD, si_code=CLD_TRAPPED, si_pid=2867203, si_uid=1000, si_status=SIGTRAP, si_utime=0, si_stime=0} ---ptrace(PTRACE_GET_SYSCALL_INFO, 2867203, 88, {op=PTRACE_SYSCALL_INFO_ENTRY, arch=AUDIT_ARCH_X86_64, instruction_pointer=0x72033e5274ed, stack_pointer=0x7fff31d57fd8, entry={nr=__NR_chdir, args=[0x555b3a8bfd9a, 0xbad1fed1, 0xbad2fed2, 0xbad3fed3, 0xbad4fed4, 0xbad5fed5]}}) = 80ptrace(PTRACE_SYSCALL, 2867203, NULL, 0) = 0wait4(2867203, [{WIFSTOPPED(s) && WSTOPSIG(s) == SIGTRAP | 0x80}], 0, NULL) = 2867203--- SIGCHLD {si_signo=SIGCHLD, si_code=CLD_TRAPPED, si_pid=2867203, si_uid=1000, si_status=SIGTRAP, si_utime=0, si_stime=0} ---ptrace(PTRACE_GET_SYSCALL_INFO, 2867203, 88, {op=PTRACE_SYSCALL_INFO_EXIT, arch=AUDIT_ARCH_X86_64, instruction_pointer=0x72033e5274ed, stack_pointer=0x7fff31d57fd8, exit={rval=-ENOENT, is_error=1}}) = 33ptrace(PTRACE_SYSCALL, 2867203, NULL, 0) = 0--- SIGCHLD {si_signo=SIGCHLD, si_code=CLD_TRAPPED, si_pid=2867203, si_uid=1000, si_status=SIGTRAP, si_utime=0, si_stime=0} ---wait4(2867203, [{WIFSTOPPED(s) && WSTOPSIG(s) == SIGTRAP | 0x80}], 0, NULL) = 2867203ptrace(PTRACE_GET_SYSCALL_INFO, 2867203, 88, {op=PTRACE_SYSCALL_INFO_ENTRY, arch=AUDIT_ARCH_X86_64, instruction_pointer=0x72033e5274ed, stack_pointer=0x7fff31d57fd8, entry={nr=__NR_gettid, args=[0xcaf0bea0, 0xcaf1bea1, 0xcaf2bea2, 0xcaf3bea3, 0xcaf4bea4, 0xcaf5bea5]}}) = 80ptrace(PTRACE_SYSCALL, 2867203, NULL, 0) = 0--- SIGCHLD {si_signo=SIGCHLD, si_code=CLD_TRAPPED, si_pid=2867203, si_uid=1000, si_status=SIGTRAP, si_utime=0, si_stime=0} ---wait4(2867203, [{WIFSTOPPED(s) && WSTOPSIG(s) == SIGTRAP | 0x80}], 0, NULL) = 2867203ptrace(PTRACE_GET_SYSCALL_INFO, 2867203, 88, {op=PTRACE_SYSCALL_INFO_EXIT, arch=AUDIT_ARCH_X86_64, instruction_pointer=0x72033e5274ed, stack_pointer=0x7fff31d57fd8, exit={rval=2867203, is_error=0}}) = 33ptrace(PTRACE_SYSCALL, 2867203, NULL, 0) = 0--- SIGCHLD {si_signo=SIGCHLD, si_code=CLD_TRAPPED, si_pid=2867203, si_uid=1000, si_status=SIGTRAP, si_utime=0, si_stime=0} ---wait4(2867203, [{WIFSTOPPED(s) && WSTOPSIG(s) == SIGTRAP | 0x80}], 0, NULL) = 2867203ptrace(PTRACE_GET_SYSCALL_INFO, 2867203, 88, {op=PTRACE_SYSCALL_INFO_ENTRY, arch=AUDIT_ARCH_X86_64, instruction_pointer=0x72033e5274ed, stack_pointer=0x7fff31d57fd8, entry={nr=__NR_exit_group, args=[0, 0xfac1c0d1, 0xfac2c0d2, 0xfac3c0d3, 0xfac4c0d4, 0xfac5c0d5]}}) = 80ptrace(PTRACE_SYSCALL, 2867203, NULL, 0) = 0wait4(2867203, [{WIFEXITED(s) && WEXITSTATUS(s) == 0}], 0, NULL) = 2867203--- SIGCHLD {si_signo=SIGCHLD, si_code=CLD_EXITED, si_pid=2867203, si_uid=1000, si_status=0, si_utime=0, si_stime=0} ---pipe2([3, 4], 0) = 0close(4) = 0fcntl(3, F_GETFD) = 0fcntl(3, F_SETFD, FD_CLOEXEC) = 0close(3) = 0newfstatat(AT_FDCWD, "./short_io_loop", {st_mode=S_IFREG|0775, st_size=16520, ...}, 0) = 0clone(child_stack=NULL, flags=CLONE_CHILD_CLEARTID|CLONE_CHILD_SETTID|SIGCHLD, child_tidptr=0x72033e62e650) = 2867204wait4(2867204, [{WIFSTOPPED(s) && WSTOPSIG(s) == SIGSTOP}], WSTOPPED, NULL) = 2867204--- SIGCHLD {si_signo=SIGCHLD, si_code=CLD_STOPPED, si_pid=2867204, si_uid=1000, si_status=SIGSTOP, si_utime=0, si_stime=0} ---ptrace(PTRACE_SEIZE, 2867204, NULL, PTRACE_O_TRACESYSGOOD|PTRACE_O_TRACEEXEC|PTRACE_O_TRACEEXIT) = 0--- SIGCHLD {si_signo=SIGCHLD, si_code=CLD_STOPPED, si_pid=2867204, si_uid=1000, si_status=0, si_utime=0, si_stime=0} ---ptrace(PTRACE_INTERRUPT, 2867204) = 0kill(2867204, SIGCONT) = 0close(0) = 0pipe2([0, 3], 0) = 0close(3) = 0fcntl(0, F_GETFD) = 0fcntl(0, F_SETFD, FD_CLOEXEC) = 0close(1) = 0pipe2([1, 3], 0) = 0close(3) = 0fcntl(1, F_GETFD) = 0fcntl(1, F_SETFD, FD_CLOEXEC) = 0rt_sigaction(SIGTTOU, {sa_handler=SIG_IGN, sa_mask=[], sa_flags=SA_RESTORER, sa_restorer=0x72033e445330}, NULL, 8) = 0rt_sigaction(SIGTTIN, {sa_handler=SIG_IGN, sa_mask=[], sa_flags=SA_RESTORER, sa_restorer=0x72033e445330}, NULL, 8) = 0rt_sigaction(SIGHUP, {sa_handler=0x555b3a7dff10, sa_mask=[], sa_flags=SA_RESTORER, sa_restorer=0x72033e445330}, NULL, 8) = 0rt_sigaction(SIGINT, {sa_handler=0x555b3a7dff10, sa_mask=[], sa_flags=SA_RESTORER, sa_restorer=0x72033e445330}, NULL, 8) = 0rt_sigaction(SIGQUIT, {sa_handler=0x555b3a7dff10, sa_mask=[], sa_flags=SA_RESTORER, sa_restorer=0x72033e445330}, NULL, 8) = 0rt_sigaction(SIGPIPE, {sa_handler=0x555b3a7dff10, sa_mask=[], sa_flags=SA_RESTORER, sa_restorer=0x72033e445330}, NULL, 8) = 0rt_sigaction(SIGTERM, {sa_handler=0x555b3a7dff10, sa_mask=[], sa_flags=SA_RESTORER, sa_restorer=0x72033e445330}, NULL, 8) = 0rt_sigprocmask(SIG_BLOCK, [ALRM], NULL, 8) = 0rt_sigaction(SIGALRM, {sa_handler=0x555b3a7ebc20, sa_mask=[], sa_flags=SA_RESTORER, sa_restorer=0x72033e445330}, NULL, 8) = 0wait4(-1, [{WIFSTOPPED(s) && WSTOPSIG(s) == SIGSTOP}|PTRACE_EVENT_STOP<<16], __WALL, NULL) = 2867204wait4(-1, 0x7fff31d5821c, WNOHANG|__WALL, NULL) = 0ptrace(PTRACE_LISTEN, 2867204) = 0wait4(-1, [{WIFSTOPPED(s) && WSTOPSIG(s) == SIGTRAP}|PTRACE_EVENT_STOP<<16], __WALL, NULL) = 2867204--- SIGCHLD {si_signo=SIGCHLD, si_code=CLD_CONTINUED, si_pid=2867204, si_uid=1000, si_status=SIGCONT, si_utime=0, si_stime=0} ---wait4(-1, 0x7fff31d5821c, WNOHANG|__WALL, NULL) = 0ptrace(PTRACE_SYSCALL, 2867204, NULL, 0) = 0wait4(-1, [{WIFSTOPPED(s) && WSTOPSIG(s) == SIGCONT}], __WALL, NULL) = 2867204--- SIGCHLD {si_signo=SIGCHLD, si_code=CLD_TRAPPED, si_pid=2867204, si_uid=1000, si_status=SIGCONT, si_utime=0, si_stime=0} ---ptrace(PTRACE_GETSIGINFO, 2867204, NULL, {si_signo=SIGCONT, si_code=SI_USER, si_pid=2867201, si_uid=1000}) = 0wait4(-1, 0x7fff31d5821c, WNOHANG|__WALL, NULL) = 0ptrace(PTRACE_SYSCALL, 2867204, NULL, SIGCONT) = 0wait4(-1, [{WIFSTOPPED(s) && WSTOPSIG(s) == SIGTRAP | 0x80}], __WALL, NULL) = 2867204--- SIGCHLD {si_signo=SIGCHLD, si_code=CLD_TRAPPED, si_pid=2867204, si_uid=1000, si_status=SIGTRAP, si_utime=0, si_stime=0} ---wait4(-1, 0x7fff31d5821c, WNOHANG|__WALL, NULL) = 0ptrace(PTRACE_GET_SYSCALL_INFO, 2867204, 88, {op=PTRACE_SYSCALL_INFO_ENTRY, arch=AUDIT_ARCH_X86_64, instruction_pointer=0x72033e4eeffb, stack_pointer=0x7fff31d56ec8, entry={nr=__NR_execve, args=[0x7fff31d56fa0, 0x7fff31d584b0, 0x7fff31d584c0, 0x72033e7060b8, 0x1, 0x72033e62e380]}}) = 80ptrace(PTRACE_SYSCALL, 2867204, NULL, 0) = 0wait4(-1, [{WIFSTOPPED(s) && WSTOPSIG(s) == SIGTRAP}|PTRACE_EVENT_EXEC<<16], __WALL, NULL) = 2867204--- SIGCHLD {si_signo=SIGCHLD, si_code=CLD_TRAPPED, si_pid=2867204, si_uid=1000, si_status=SIGTRAP, si_utime=0, si_stime=0} ---ptrace(PTRACE_GETEVENTMSG, 2867204, NULL, [2867204]) = 0wait4(-1, 0x7fff31d5821c, WNOHANG|__WALL, NULL) = 0ptrace(PTRACE_SYSCALL, 2867204, NULL, 0) = 0wait4(-1, [{WIFSTOPPED(s) && WSTOPSIG(s) == SIGTRAP | 0x80}], __WALL, NULL) = 2867204--- SIGCHLD {si_signo=SIGCHLD, si_code=CLD_TRAPPED, si_pid=2867204, si_uid=1000, si_status=SIGTRAP, si_utime=0, si_stime=0} ---wait4(-1, 0x7fff31d5821c, WNOHANG|__WALL, NULL) = 0ptrace(PTRACE_SYSCALL, 2867204, NULL, 0) = 0wait4(-1, [{WIFSTOPPED(s) && WSTOPSIG(s) == SIGTRAP | 0x80}], __WALL, NULL) = 2867204--- SIGCHLD {si_signo=SIGCHLD, si_code=CLD_TRAPPED, si_pid=2867204, si_uid=1000, si_status=SIGTRAP, si_utime=0, si_stime=0} ---wait4(-1, 0x7fff31d5821c, WNOHANG|__WALL, NULL) = 0ptrace(PTRACE_GET_SYSCALL_INFO, 2867204, 88, {op=PTRACE_SYSCALL_INFO_ENTRY, arch=AUDIT_ARCH_X86_64, instruction_pointer=0x78d508ca19bb, stack_pointer=0x7ffce96cbd58, entry={nr=__NR_brk, args=[0, 0x78d508cb3a18, 0, 0x37f, 0, 0x78d508cb3440]}}) = 80ptrace(PTRACE_SYSCALL, 2867204, NULL, 0) = 0--- SIGCHLD {si_signo=SIGCHLD, si_code=CLD_TRAPPED, si_pid=2867204, si_uid=1000, si_status=SIGTRAP, si_utime=0, si_stime=0} ---wait4(-1, [{WIFSTOPPED(s) && WSTOPSIG(s) == SIGTRAP | 0x80}], __WALL, NULL) = 2867204wait4(-1, 0x7fff31d5821c, WNOHANG|__WALL, NULL) = 0ptrace(PTRACE_SYSCALL, 2867204, NULL, 0) = 0wait4(-1, [{WIFSTOPPED(s) && WSTOPSIG(s) == SIGTRAP | 0x80}], __WALL, NULL) = 2867204--- SIGCHLD {si_signo=SIGCHLD, si_code=CLD_TRAPPED, si_pid=2867204, si_uid=1000, si_status=SIGTRAP, si_utime=0, si_stime=0} ---wait4(-1, 0x7fff31d5821c, WNOHANG|__WALL, NULL) = 0ptrace(PTRACE_GET_SYSCALL_INFO, 2867204, 88, {op=PTRACE_SYSCALL_INFO_ENTRY, arch=AUDIT_ARCH_X86_64, instruction_pointer=0x78d508ca2d1c, stack_pointer=0x7ffce96cb9e0, entry={nr=__NR_mmap, args=[0, 0x2000, 0x3, 0x22, 0xffffffff, 0]}}) = 80ptrace(PTRACE_SYSCALL, 2867204, NULL, 0) = 0wait4(-1, [{WIFSTOPPED(s) && WSTOPSIG(s) == SIGTRAP | 0x80}], __WALL, NULL) = 2867204--- SIGCHLD {si_signo=SIGCHLD, si_code=CLD_TRAPPED, si_pid=2867204, si_uid=1000, si_status=SIGTRAP, si_utime=0, si_stime=0} ---wait4(-1, 0x7fff31d5821c, WNOHANG|__WALL, NULL) = 0ptrace(PTRACE_SYSCALL, 2867204, NULL, 0) = 0wait4(-1, [{WIFSTOPPED(s) && WSTOPSIG(s) == SIGTRAP | 0x80}], __WALL, NULL) = 2867204--- SIGCHLD {si_signo=SIGCHLD, si_code=CLD_TRAPPED, si_pid=2867204, si_uid=1000, si_status=SIGTRAP, si_utime=0, si_stime=0} ---wait4(-1, 0x7fff31d5821c, WNOHANG|__WALL, NULL) = 0ptrace(PTRACE_GET_SYSCALL_INFO, 2867204, 88, {op=PTRACE_SYSCALL_INFO_ENTRY, arch=AUDIT_ARCH_X86_64, instruction_pointer=0x78d508ca28bb, stack_pointer=0x7ffce96cba98, entry={nr=__NR_access, args=[0x78d508cac5b0, 0x4, 0x5b3dadc8adf0, 0x22, 0x78d508c7d000, 0x78d508cb3440]}}) = 80ptrace(PTRACE_SYSCALL, 2867204, NULL, 0) = 0--- SIGCHLD {si_signo=SIGCHLD, si_code=CLD_TRAPPED, si_pid=2867204, si_uid=1000, si_status=SIGTRAP, si_utime=0, si_stime=0} ---wait4(-1, [{WIFSTOPPED(s) && WSTOPSIG(s) == SIGTRAP | 0x80}], __WALL, NULL) = 2867204wait4(-1, 0x7fff31d5821c, WNOHANG|__WALL, NULL) = 0ptrace(PTRACE_SYSCALL, 2867204, NULL, 0) = 0wait4(-1, [{WIFSTOPPED(s) && WSTOPSIG(s) == SIGTRAP | 0x80}], __WALL, NULL) = 2867204--- SIGCHLD {si_signo=SIGCHLD, si_code=CLD_TRAPPED, si_pid=2867204, si_uid=1000, si_status=SIGTRAP, si_utime=0, si_stime=0} ---wait4(-1, 0x7fff31d5821c, WNOHANG|__WALL, NULL) = 0ptrace(PTRACE_GET_SYSCALL_INFO, 2867204, 88, {op=PTRACE_SYSCALL_INFO_ENTRY, arch=AUDIT_ARCH_X86_64, instruction_pointer=0x78d508ca2b61, stack_pointer=0x7ffce96cae30, entry={nr=__NR_openat, args=[0xffffff9c, 0x78d508cab38f, 0x80000, 0, 0xffff, 0]}}) = 80fstat(2, {st_mode=S_IFIFO|0600, st_size=0, ...}) = 0process_vm_readv(2867204, [{iov_base="2\0dl-lookup.c\0out of memory\n\0, v"..., iov_len=4096}], 1, [{iov_base=0x78d508cab000, iov_len=4096}], 1, 0) = 4096write(2, "openat(AT_FDCWD, \"/etc/ld.so.cac"..., 55) = 55ptrace(PTRACE_SYSCALL, 2867204, NULL, 0) = 0--- SIGCHLD {si_signo=SIGCHLD, si_code=CLD_TRAPPED, si_pid=2867204, si_uid=1000, si_status=SIGTRAP, si_utime=0, si_stime=0} ---wait4(-1, [{WIFSTOPPED(s) && WSTOPSIG(s) == SIGTRAP | 0x80}], __WALL, NULL) = 2867204wait4(-1, 0x7fff31d5821c, WNOHANG|__WALL, NULL) = 0ptrace(PTRACE_GET_SYSCALL_INFO, 2867204, 88, {op=PTRACE_SYSCALL_INFO_EXIT, arch=AUDIT_ARCH_X86_64, instruction_pointer=0x78d508ca2b61, stack_pointer=0x7ffce96cae30, exit={rval=3, is_error=0}}) = 33write(2, ") = 3\n", 6) = 6ptrace(PTRACE_SYSCALL, 2867204, NULL, 0) = 0--- SIGCHLD {si_signo=SIGCHLD, si_code=CLD_TRAPPED, si_pid=2867204, si_uid=1000, si_status=SIGTRAP, si_utime=0, si_stime=0} ---wait4(-1, [{WIFSTOPPED(s) && WSTOPSIG(s) == SIGTRAP | 0x80}], __WALL, NULL) = 2867204wait4(-1, 0x7fff31d5821c, WNOHANG|__WALL, NULL) = 0ptrace(PTRACE_GET_SYSCALL_INFO, 2867204, 88, {op=PTRACE_SYSCALL_INFO_ENTRY, arch=AUDIT_ARCH_X86_64, instruction_pointer=0x78d508ca28eb, stack_pointer=0x7ffce96cae38, entry={nr=__NR_fstat, args=[0x3, 0x7ffce96cae40, 0x80000, 0, 0xffff, 0]}}) = 80ptrace(PTRACE_SYSCALL, 2867204, NULL, 0) = 0--- SIGCHLD {si_signo=SIGCHLD, si_code=CLD_TRAPPED, si_pid=2867204, si_uid=1000, si_status=SIGTRAP, si_utime=0, si_stime=0} ---wait4(-1, [{WIFSTOPPED(s) && WSTOPSIG(s) == SIGTRAP | 0x80}], __WALL, NULL) = 2867204wait4(-1, 0x7fff31d5821c, WNOHANG|__WALL, NULL) = 0ptrace(PTRACE_SYSCALL, 2867204, NULL, 0) = 0--- SIGCHLD {si_signo=SIGCHLD, si_code=CLD_TRAPPED, si_pid=2867204, si_uid=1000, si_status=SIGTRAP, si_utime=0, si_stime=0} ---wait4(-1, [{WIFSTOPPED(s) && WSTOPSIG(s) == SIGTRAP | 0x80}], __WALL, NULL) = 2867204wait4(-1, 0x7fff31d5821c, WNOHANG|__WALL, NULL) = 0ptrace(PTRACE_GET_SYSCALL_INFO, 2867204, 88, {op=PTRACE_SYSCALL_INFO_ENTRY, arch=AUDIT_ARCH_X86_64, instruction_pointer=0x78d508ca2d1c, stack_pointer=0x7ffce96cae20, entry={nr=__NR_mmap, args=[0, 0x241e8, 0x1, 0x2, 0x3, 0]}}) = 80ptrace(PTRACE_SYSCALL, 2867204, NULL, 0) = 0wait4(-1, [{WIFSTOPPED(s) && WSTOPSIG(s) == SIGTRAP | 0x80}], __WALL, NULL) = 2867204--- SIGCHLD {si_signo=SIGCHLD, si_code=CLD_TRAPPED, si_pid=2867204, si_uid=1000, si_status=SIGTRAP, si_utime=0, si_stime=0} ---wait4(-1, 0x7fff31d5821c, WNOHANG|__WALL, NULL) = 0ptrace(PTRACE_SYSCALL, 2867204, NULL, 0) = 0--- SIGCHLD {si_signo=SIGCHLD, si_code=CLD_TRAPPED, si_pid=2867204, si_uid=1000, si_status=SIGTRAP, si_utime=0, si_stime=0} ---wait4(-1, [{WIFSTOPPED(s) && WSTOPSIG(s) == SIGTRAP | 0x80}], __WALL, NULL) = 2867204wait4(-1, 0x7fff31d5821c, WNOHANG|__WALL, NULL) = 0ptrace(PTRACE_GET_SYSCALL_INFO, 2867204, 88, {op=PTRACE_SYSCALL_INFO_ENTRY, arch=AUDIT_ARCH_X86_64, instruction_pointer=0x78d508ca2a1b, stack_pointer=0x7ffce96cae38, entry={nr=__NR_close, args=[0x3, 0x241e8, 0x1, 0x2, 0x3, 0]}}) = 80write(2, "close(3", 7) = 7ptrace(PTRACE_SYSCALL, 2867204, NULL, 0) = 0--- SIGCHLD {si_signo=SIGCHLD, si_code=CLD_TRAPPED, si_pid=2867204, si_uid=1000, si_status=SIGTRAP, si_utime=0, si_stime=0} ---wait4(-1, [{WIFSTOPPED(s) && WSTOPSIG(s) == SIGTRAP | 0x80}], __WALL, NULL) = 2867204wait4(-1, 0x7fff31d5821c, WNOHANG|__WALL, NULL) = 0ptrace(PTRACE_GET_SYSCALL_INFO, 2867204, 88, {op=PTRACE_SYSCALL_INFO_EXIT, arch=AUDIT_ARCH_X86_64, instruction_pointer=0x78d508ca2a1b, stack_pointer=0x7ffce96cae38, exit={rval=0, is_error=0}}) = 33write(2, ") "..., 37) = 37ptrace(PTRACE_SYSCALL, 2867204, NULL, 0) = 0wait4(-1, [{WIFSTOPPED(s) && WSTOPSIG(s) == SIGTRAP | 0x80}], __WALL, NULL) = 2867204--- SIGCHLD {si_signo=SIGCHLD, si_code=CLD_TRAPPED, si_pid=2867204, si_uid=1000, si_status=SIGTRAP, si_utime=0, si_stime=0} ---wait4(-1, 0x7fff31d5821c, WNOHANG|__WALL, NULL) = 0ptrace(PTRACE_GET_SYSCALL_INFO, 2867204, 88, {op=PTRACE_SYSCALL_INFO_ENTRY, arch=AUDIT_ARCH_X86_64, instruction_pointer=0x78d508ca2b61, stack_pointer=0x7ffce96cafa0, entry={nr=__NR_openat, args=[0xffffff9c, 0x78d508c73140, 0x80000, 0, 0x7ffce96cb057, 0]}}) = 80process_vm_readv(2867204, [{iov_base="P0\307\10\325x\0\0\362\256\312\10\325x\0\0\0\0\0\0\0\0\0\0@\220\312\10\325x\0\0"..., iov_len=4096}], 1, [{iov_base=0x78d508c73000, iov_len=4096}], 1, 0) = 4096write(2, "openat(AT_FDCWD, \"/lib/x86_64-li"..., 70) = 70ptrace(PTRACE_SYSCALL, 2867204, NULL, 0) = 0--- SIGCHLD {si_signo=SIGCHLD, si_code=CLD_TRAPPED, si_pid=2867204, si_uid=1000, si_status=SIGTRAP, si_utime=0, si_stime=0} ---wait4(-1, [{WIFSTOPPED(s) && WSTOPSIG(s) == SIGTRAP | 0x80}], __WALL, NULL) = 2867204wait4(-1, 0x7fff31d5821c, WNOHANG|__WALL, NULL) = 0ptrace(PTRACE_GET_SYSCALL_INFO, 2867204, 88, {op=PTRACE_SYSCALL_INFO_EXIT, arch=AUDIT_ARCH_X86_64, instruction_pointer=0x78d508ca2b61, stack_pointer=0x7ffce96cafa0, exit={rval=3, is_error=0}}) = 33write(2, ") = 3\n", 6) = 6ptrace(PTRACE_SYSCALL, 2867204, NULL, 0) = 0--- SIGCHLD {si_signo=SIGCHLD, si_code=CLD_TRAPPED, si_pid=2867204, si_uid=1000, si_status=SIGTRAP, si_utime=0, si_stime=0} ---wait4(-1, [{WIFSTOPPED(s) && WSTOPSIG(s) == SIGTRAP | 0x80}], __WALL, NULL) = 2867204wait4(-1, 0x7fff31d5821c, WNOHANG|__WALL, NULL) = 0ptrace(PTRACE_GET_SYSCALL_INFO, 2867204, 88, {op=PTRACE_SYSCALL_INFO_ENTRY, arch=AUDIT_ARCH_X86_64, instruction_pointer=0x78d508ca2bd8, stack_pointer=0x7ffce96cafa8, entry={nr=__NR_read, args=[0x3, 0x7ffce96cb078, 0x340, 0, 0x7ffce96cb057, 0]}}) = 80write(2, "read(3, ", 8) = 8ptrace(PTRACE_SYSCALL, 2867204, NULL, 0) = 0--- SIGCHLD {si_signo=SIGCHLD, si_code=CLD_TRAPPED, si_pid=2867204, si_uid=1000, si_status=SIGTRAP, si_utime=0, si_stime=0} ---wait4(-1, [{WIFSTOPPED(s) && WSTOPSIG(s) == SIGTRAP | 0x80}], __WALL, NULL) = 2867204wait4(-1, 0x7fff31d5821c, WNOHANG|__WALL, NULL) = 0ptrace(PTRACE_GET_SYSCALL_INFO, 2867204, 88, {op=PTRACE_SYSCALL_INFO_EXIT, arch=AUDIT_ARCH_X86_64, instruction_pointer=0x78d508ca2bd8, stack_pointer=0x7ffce96cafa8, exit={rval=832, is_error=0}}) = 33process_vm_readv(2867204, [{iov_base="\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\340b\313\10\325x\0\0@1\307\10\325x\0\0"..., iov_len=4096}], 1, [{iov_base=0x7ffce96cb000, iov_len=4096}], 1, 0) = 4096write(2, "\"\\177ELF\\2\\1\\1\\3\\0\\0\\0\\0\\0\\0\\0\\0"..., 84) = 84ptrace(PTRACE_SYSCALL, 2867204, NULL, 0) = 0--- SIGCHLD {si_signo=SIGCHLD, si_code=CLD_TRAPPED, si_pid=2867204, si_uid=1000, si_status=SIGTRAP, si_utime=0, si_stime=0} ---wait4(-1, [{WIFSTOPPED(s) && WSTOPSIG(s) == SIGTRAP | 0x80}], __WALL, NULL) = 2867204wait4(-1, 0x7fff31d5821c, WNOHANG|__WALL, NULL) = 0ptrace(PTRACE_GET_SYSCALL_INFO, 2867204, 88, {op=PTRACE_SYSCALL_INFO_ENTRY, arch=AUDIT_ARCH_X86_64, instruction_pointer=0x78d508ca2bae, stack_pointer=0x7ffce96cac88, entry={nr=__NR_pread64, args=[0x3, 0x7ffce96cac90, 0x310, 0x40, 0x7ffce96cb057, 0]}}) = 80ptrace(PTRACE_SYSCALL, 2867204, NULL, 0) = 0--- SIGCHLD {si_signo=SIGCHLD, si_code=CLD_TRAPPED, si_pid=2867204, si_uid=1000, si_status=SIGTRAP, si_utime=0, si_stime=0} ---wait4(-1, [{WIFSTOPPED(s) && WSTOPSIG(s) == SIGTRAP | 0x80}], __WALL, NULL) = 2867204wait4(-1, 0x7fff31d5821c, WNOHANG|__WALL, NULL) = 0ptrace(PTRACE_SYSCALL, 2867204, NULL, 0) = 0--- SIGCHLD {si_signo=SIGCHLD, si_code=CLD_TRAPPED, si_pid=2867204, si_uid=1000, si_status=SIGTRAP, si_utime=0, si_stime=0} ---wait4(-1, [{WIFSTOPPED(s) && WSTOPSIG(s) == SIGTRAP | 0x80}], __WALL, NULL) = 2867204wait4(-1, 0x7fff31d5821c, WNOHANG|__WALL, NULL) = 0ptrace(PTRACE_GET_SYSCALL_INFO, 2867204, 88, {op=PTRACE_SYSCALL_INFO_ENTRY, arch=AUDIT_ARCH_X86_64, instruction_pointer=0x78d508ca28eb, stack_pointer=0x7ffce96cae78, entry={nr=__NR_fstat, args=[0x3, 0x7ffce96caf10, 0x3, 0x40, 0x78d508c73140, 0x78d508cb62e0]}}) = 80ptrace(PTRACE_SYSCALL, 2867204, NULL, 0) = 0--- SIGCHLD {si_signo=SIGCHLD, si_code=CLD_TRAPPED, si_pid=2867204, si_uid=1000, si_status=SIGTRAP, si_utime=0, si_stime=0} ---wait4(-1, [{WIFSTOPPED(s) && WSTOPSIG(s) == SIGTRAP | 0x80}], __WALL, NULL) = 2867204wait4(-1, 0x7fff31d5821c, WNOHANG|__WALL, NULL) = 0ptrace(PTRACE_SYSCALL, 2867204, NULL, 0) = 0--- SIGCHLD {si_signo=SIGCHLD, si_code=CLD_TRAPPED, si_pid=2867204, si_uid=1000, si_status=SIGTRAP, si_utime=0, si_stime=0} ---wait4(-1, [{WIFSTOPPED(s) && WSTOPSIG(s) == SIGTRAP | 0x80}], __WALL, NULL) = 2867204wait4(-1, 0x7fff31d5821c, WNOHANG|__WALL, NULL) = 0ptrace(PTRACE_GET_SYSCALL_INFO, 2867204, 88, {op=PTRACE_SYSCALL_INFO_ENTRY, arch=AUDIT_ARCH_X86_64, instruction_pointer=0x78d508ca2bae, stack_pointer=0x7ffce96cab58, entry={nr=__NR_pread64, args=[0x3, 0x7ffce96cab60, 0x310, 0x40, 0xc0ff, 0]}}) = 80ptrace(PTRACE_SYSCALL, 2867204, NULL, 0) = 0--- SIGCHLD {si_signo=SIGCHLD, si_code=CLD_TRAPPED, si_pid=2867204, si_uid=1000, si_status=SIGTRAP, si_utime=0, si_stime=0} ---wait4(-1, [{WIFSTOPPED(s) && WSTOPSIG(s) == SIGTRAP | 0x80}], __WALL, NULL) = 2867204wait4(-1, 0x7fff31d5821c, WNOHANG|__WALL, NULL) = 0ptrace(PTRACE_SYSCALL, 2867204, NULL, 0) = 0--- SIGCHLD {si_signo=SIGCHLD, si_code=CLD_TRAPPED, si_pid=2867204, si_uid=1000, si_status=SIGTRAP, si_utime=0, si_stime=0} ---wait4(-1, [{WIFSTOPPED(s) && WSTOPSIG(s) == SIGTRAP | 0x80}], __WALL, NULL) = 2867204wait4(-1, 0x7fff31d5821c, WNOHANG|__WALL, NULL) = 0ptrace(PTRACE_GET_SYSCALL_INFO, 2867204, 88, {op=PTRACE_SYSCALL_INFO_ENTRY, arch=AUDIT_ARCH_X86_64, instruction_pointer=0x78d508ca2d1c, stack_pointer=0x7ffce96ca830, entry={nr=__NR_mmap, args=[0, 0x212d90, 0x1, 0x802, 0x3, 0]}}) = 80ptrace(PTRACE_SYSCALL, 2867204, NULL, 0) = 0--- SIGCHLD {si_signo=SIGCHLD, si_code=CLD_TRAPPED, si_pid=2867204, si_uid=1000, si_status=SIGTRAP, si_utime=0, si_stime=0} ---wait4(-1, [{WIFSTOPPED(s) && WSTOPSIG(s) == SIGTRAP | 0x80}], __WALL, NULL) = 2867204wait4(-1, 0x7fff31d5821c, WNOHANG|__WALL, NULL) = 0ptrace(PTRACE_SYSCALL, 2867204, NULL, 0) = 0--- SIGCHLD {si_signo=SIGCHLD, si_code=CLD_TRAPPED, si_pid=2867204, si_uid=1000, si_status=SIGTRAP, si_utime=0, si_stime=0} ---wait4(-1, [{WIFSTOPPED(s) && WSTOPSIG(s) == SIGTRAP | 0x80}], __WALL, NULL) = 2867204wait4(-1, 0x7fff31d5821c, WNOHANG|__WALL, NULL) = 0ptrace(PTRACE_GET_SYSCALL_INFO, 2867204, 88, {op=PTRACE_SYSCALL_INFO_ENTRY, arch=AUDIT_ARCH_X86_64, instruction_pointer=0x78d508ca2d1c, stack_pointer=0x7ffce96ca830, entry={nr=__NR_mmap, args=[0x78d508a28000, 0x189000, 0x5, 0x812, 0x3, 0x28000]}}) = 80ptrace(PTRACE_SYSCALL, 2867204, NULL, 0) = 0wait4(-1, [{WIFSTOPPED(s) && WSTOPSIG(s) == SIGTRAP | 0x80}], __WALL, NULL) = 2867204--- SIGCHLD {si_signo=SIGCHLD, si_code=CLD_TRAPPED, si_pid=2867204, si_uid=1000, si_status=SIGTRAP, si_utime=0, si_stime=0} ---wait4(-1, 0x7fff31d5821c, WNOHANG|__WALL, NULL) = 0ptrace(PTRACE_SYSCALL, 2867204, NULL, 0) = 0--- SIGCHLD {si_signo=SIGCHLD, si_code=CLD_TRAPPED, si_pid=2867204, si_uid=1000, si_status=SIGTRAP, si_utime=0, si_stime=0} ---wait4(-1, [{WIFSTOPPED(s) && WSTOPSIG(s) == SIGTRAP | 0x80}], __WALL, NULL) = 2867204wait4(-1, 0x7fff31d5821c, WNOHANG|__WALL, NULL) = 0ptrace(PTRACE_GET_SYSCALL_INFO, 2867204, 88, {op=PTRACE_SYSCALL_INFO_ENTRY, arch=AUDIT_ARCH_X86_64, instruction_pointer=0x78d508ca2d1c, stack_pointer=0x7ffce96ca830, entry={nr=__NR_mmap, args=[0x78d508bb1000, 0x4f000, 0x1, 0x812, 0x3, 0x1b1000]}}) = 80ptrace(PTRACE_SYSCALL, 2867204, NULL, 0) = 0--- SIGCHLD {si_signo=SIGCHLD, si_code=CLD_TRAPPED, si_pid=2867204, si_uid=1000, si_status=SIGTRAP, si_utime=0, si_stime=0} ---wait4(-1, [{WIFSTOPPED(s) && WSTOPSIG(s) == SIGTRAP | 0x80}], __WALL, NULL) = 2867204wait4(-1, 0x7fff31d5821c, WNOHANG|__WALL, NULL) = 0ptrace(PTRACE_SYSCALL, 2867204, NULL, 0) = 0--- SIGCHLD {si_signo=SIGCHLD, si_code=CLD_TRAPPED, si_pid=2867204, si_uid=1000, si_status=SIGTRAP, si_utime=0, si_stime=0} ---wait4(-1, [{WIFSTOPPED(s) && WSTOPSIG(s) == SIGTRAP | 0x80}], __WALL, NULL) = 2867204wait4(-1, 0x7fff31d5821c, WNOHANG|__WALL, NULL) = 0ptrace(PTRACE_GET_SYSCALL_INFO, 2867204, 88, {op=PTRACE_SYSCALL_INFO_ENTRY, arch=AUDIT_ARCH_X86_64, instruction_pointer=0x78d508ca2d1c, stack_pointer=0x7ffce96ca830, entry={nr=__NR_mmap, args=[0x78d508c00000, 0x6000, 0x3, 0x812, 0x3, 0x1ff000]}}) = 80ptrace(PTRACE_SYSCALL, 2867204, NULL, 0) = 0--- SIGCHLD {si_signo=SIGCHLD, si_code=CLD_TRAPPED, si_pid=2867204, si_uid=1000, si_status=SIGTRAP, si_utime=0, si_stime=0} ---wait4(-1, [{WIFSTOPPED(s) && WSTOPSIG(s) == SIGTRAP | 0x80}], __WALL, NULL) = 2867204wait4(-1, 0x7fff31d5821c, WNOHANG|__WALL, NULL) = 0ptrace(PTRACE_SYSCALL, 2867204, NULL, 0) = 0--- SIGCHLD {si_signo=SIGCHLD, si_code=CLD_TRAPPED, si_pid=2867204, si_uid=1000, si_status=SIGTRAP, si_utime=0, si_stime=0} ---wait4(-1, [{WIFSTOPPED(s) && WSTOPSIG(s) == SIGTRAP | 0x80}], __WALL, NULL) = 2867204wait4(-1, 0x7fff31d5821c, WNOHANG|__WALL, NULL) = 0ptrace(PTRACE_GET_SYSCALL_INFO, 2867204, 88, {op=PTRACE_SYSCALL_INFO_ENTRY, arch=AUDIT_ARCH_X86_64, instruction_pointer=0x78d508ca2d1c, stack_pointer=0x7ffce96ca830, entry={nr=__NR_mmap, args=[0x78d508c06000, 0xcd90, 0x3, 0x32, 0xffffffff, 0]}}) = 80ptrace(PTRACE_SYSCALL, 2867204, NULL, 0) = 0--- SIGCHLD {si_signo=SIGCHLD, si_code=CLD_TRAPPED, si_pid=2867204, si_uid=1000, si_status=SIGTRAP, si_utime=0, si_stime=0} ---wait4(-1, [{WIFSTOPPED(s) && WSTOPSIG(s) == SIGTRAP | 0x80}], __WALL, NULL) = 2867204wait4(-1, 0x7fff31d5821c, WNOHANG|__WALL, NULL) = 0ptrace(PTRACE_SYSCALL, 2867204, NULL, 0) = 0wait4(-1, [{WIFSTOPPED(s) && WSTOPSIG(s) == SIGTRAP | 0x80}], __WALL, NULL) = 2867204--- SIGCHLD {si_signo=SIGCHLD, si_code=CLD_TRAPPED, si_pid=2867204, si_uid=1000, si_status=SIGTRAP, si_utime=0, si_stime=0} ---wait4(-1, 0x7fff31d5821c, WNOHANG|__WALL, NULL) = 0ptrace(PTRACE_GET_SYSCALL_INFO, 2867204, 88, {op=PTRACE_SYSCALL_INFO_ENTRY, arch=AUDIT_ARCH_X86_64, instruction_pointer=0x78d508ca2a1b, stack_pointer=0x7ffce96cab58, entry={nr=__NR_close, args=[0x3, 0x78d508c73160, 0x1, 0xc0000002, 0x78d508a00378, 0x4]}}) = 80write(2, "close(3", 7) = 7ptrace(PTRACE_SYSCALL, 2867204, NULL, 0) = 0--- SIGCHLD {si_signo=SIGCHLD, si_code=CLD_TRAPPED, si_pid=2867204, si_uid=1000, si_status=SIGTRAP, si_utime=0, si_stime=0} ---wait4(-1, [{WIFSTOPPED(s) && WSTOPSIG(s) == SIGTRAP | 0x80}], __WALL, NULL) = 2867204wait4(-1, 0x7fff31d5821c, WNOHANG|__WALL, NULL) = 0ptrace(PTRACE_GET_SYSCALL_INFO, 2867204, 88, {op=PTRACE_SYSCALL_INFO_EXIT, arch=AUDIT_ARCH_X86_64, instruction_pointer=0x78d508ca2a1b, stack_pointer=0x7ffce96cab58, exit={rval=0, is_error=0}}) = 33write(2, ") "..., 37) = 37ptrace(PTRACE_SYSCALL, 2867204, NULL, 0) = 0wait4(-1, [{WIFSTOPPED(s) && WSTOPSIG(s) == SIGTRAP | 0x80}], __WALL, NULL) = 2867204--- SIGCHLD {si_signo=SIGCHLD, si_code=CLD_TRAPPED, si_pid=2867204, si_uid=1000, si_status=SIGTRAP, si_utime=0, si_stime=0} ---wait4(-1, 0x7fff31d5821c, WNOHANG|__WALL, NULL) = 0ptrace(PTRACE_GET_SYSCALL_INFO, 2867204, 88, {op=PTRACE_SYSCALL_INFO_ENTRY, arch=AUDIT_ARCH_X86_64, instruction_pointer=0x78d508ca2d1c, stack_pointer=0x7ffce96cba00, entry={nr=__NR_mmap, args=[0, 0x3000, 0x3, 0x22, 0xffffffff, 0]}}) = 80ptrace(PTRACE_SYSCALL, 2867204, NULL, 0) = 0--- SIGCHLD {si_signo=SIGCHLD, si_code=CLD_TRAPPED, si_pid=2867204, si_uid=1000, si_status=SIGTRAP, si_utime=0, si_stime=0} ---wait4(-1, [{WIFSTOPPED(s) && WSTOPSIG(s) == SIGTRAP | 0x80}], __WALL, NULL) = 2867204wait4(-1, 0x7fff31d5821c, WNOHANG|__WALL, NULL) = 0ptrace(PTRACE_SYSCALL, 2867204, NULL, 0) = 0--- SIGCHLD {si_signo=SIGCHLD, si_code=CLD_TRAPPED, si_pid=2867204, si_uid=1000, si_status=SIGTRAP, si_utime=0, si_stime=0} ---wait4(-1, [{WIFSTOPPED(s) && WSTOPSIG(s) == SIGTRAP | 0x80}], __WALL, NULL) = 2867204wait4(-1, 0x7fff31d5821c, WNOHANG|__WALL, NULL) = 0ptrace(PTRACE_GET_SYSCALL_INFO, 2867204, 88, {op=PTRACE_SYSCALL_INFO_ENTRY, arch=AUDIT_ARCH_X86_64, instruction_pointer=0x78d508c9d11d, stack_pointer=0x7ffce96cba80, entry={nr=__NR_arch_prctl, args=[0x1002, 0x78d508c4b740, 0xffff872af73b3f30, 0x22, 0xffffffff, 0]}}) = 80ptrace(PTRACE_SYSCALL, 2867204, NULL, 0) = 0--- SIGCHLD {si_signo=SIGCHLD, si_code=CLD_TRAPPED, si_pid=2867204, si_uid=1000, si_status=SIGTRAP, si_utime=0, si_stime=0} ---wait4(-1, [{WIFSTOPPED(s) && WSTOPSIG(s) == SIGTRAP | 0x80}], __WALL, NULL) = 2867204wait4(-1, 0x7fff31d5821c, WNOHANG|__WALL, NULL) = 0ptrace(PTRACE_SYSCALL, 2867204, NULL, 0) = 0--- SIGCHLD {si_signo=SIGCHLD, si_code=CLD_TRAPPED, si_pid=2867204, si_uid=1000, si_status=SIGTRAP, si_utime=0, si_stime=0} ---wait4(-1, [{WIFSTOPPED(s) && WSTOPSIG(s) == SIGTRAP | 0x80}], __WALL, NULL) = 2867204wait4(-1, 0x7fff31d5821c, WNOHANG|__WALL, NULL) = 0ptrace(PTRACE_GET_SYSCALL_INFO, 2867204, 88, {op=PTRACE_SYSCALL_INFO_ENTRY, arch=AUDIT_ARCH_X86_64, instruction_pointer=0x78d508c91f12, stack_pointer=0x7ffce96cba50, entry={nr=__NR_set_tid_address, args=[0x78d508c4ba10, 0x78d508c4b740, 0x78d508cb60c8, 0x22, 0xffffffff, 0]}}) = 80ptrace(PTRACE_SYSCALL, 2867204, NULL, 0) = 0--- SIGCHLD {si_signo=SIGCHLD, si_code=CLD_TRAPPED, si_pid=2867204, si_uid=1000, si_status=SIGTRAP, si_utime=0, si_stime=0} ---wait4(-1, [{WIFSTOPPED(s) && WSTOPSIG(s) == SIGTRAP | 0x80}], __WALL, NULL) = 2867204wait4(-1, 0x7fff31d5821c, WNOHANG|__WALL, NULL) = 0ptrace(PTRACE_SYSCALL, 2867204, NULL, 0) = 0--- SIGCHLD {si_signo=SIGCHLD, si_code=CLD_TRAPPED, si_pid=2867204, si_uid=1000, si_status=SIGTRAP, si_utime=0, si_stime=0} ---wait4(-1, [{WIFSTOPPED(s) && WSTOPSIG(s) == SIGTRAP | 0x80}], __WALL, NULL) = 2867204wait4(-1, 0x7fff31d5821c, WNOHANG|__WALL, NULL) = 0ptrace(PTRACE_GET_SYSCALL_INFO, 2867204, 88, {op=PTRACE_SYSCALL_INFO_ENTRY, arch=AUDIT_ARCH_X86_64, instruction_pointer=0x78d508c91f6e, stack_pointer=0x7ffce96cba50, entry={nr=__NR_set_robust_list, args=[0x78d508c4ba20, 0x18, 0x78d508cb60c8, 0x22, 0xffffffff, 0]}}) = 80ptrace(PTRACE_SYSCALL, 2867204, NULL, 0) = 0--- SIGCHLD {si_signo=SIGCHLD, si_code=CLD_TRAPPED, si_pid=2867204, si_uid=1000, si_status=SIGTRAP, si_utime=0, si_stime=0} ---wait4(-1, [{WIFSTOPPED(s) && WSTOPSIG(s) == SIGTRAP | 0x80}], __WALL, NULL) = 2867204wait4(-1, 0x7fff31d5821c, WNOHANG|__WALL, NULL) = 0ptrace(PTRACE_SYSCALL, 2867204, NULL, 0) = 0--- SIGCHLD {si_signo=SIGCHLD, si_code=CLD_TRAPPED, si_pid=2867204, si_uid=1000, si_status=SIGTRAP, si_utime=0, si_stime=0} ---wait4(-1, [{WIFSTOPPED(s) && WSTOPSIG(s) == SIGTRAP | 0x80}], __WALL, NULL) = 2867204wait4(-1, 0x7fff31d5821c, WNOHANG|__WALL, NULL) = 0ptrace(PTRACE_GET_SYSCALL_INFO, 2867204, 88, {op=PTRACE_SYSCALL_INFO_ENTRY, arch=AUDIT_ARCH_X86_64, instruction_pointer=0x78d508c91fe6, stack_pointer=0x7ffce96cba50, entry={nr=__NR_rseq, args=[0x78d508c4c060, 0x20, 0, 0x53053053, 0, 0x78d508cb3440]}}) = 80ptrace(PTRACE_SYSCALL, 2867204, NULL, 0) = 0--- SIGCHLD {si_signo=SIGCHLD, si_code=CLD_TRAPPED, si_pid=2867204, si_uid=1000, si_status=SIGTRAP, si_utime=0, si_stime=0} ---wait4(-1, [{WIFSTOPPED(s) && WSTOPSIG(s) == SIGTRAP | 0x80}], __WALL, NULL) = 2867204wait4(-1, 0x7fff31d5821c, WNOHANG|__WALL, NULL) = 0ptrace(PTRACE_SYSCALL, 2867204, NULL, 0) = 0wait4(-1, [{WIFSTOPPED(s) && WSTOPSIG(s) == SIGTRAP | 0x80}], __WALL, NULL) = 2867204--- SIGCHLD {si_signo=SIGCHLD, si_code=CLD_TRAPPED, si_pid=2867204, si_uid=1000, si_status=SIGTRAP, si_utime=0, si_stime=0} ---wait4(-1, 0x7fff31d5821c, WNOHANG|__WALL, NULL) = 0ptrace(PTRACE_GET_SYSCALL_INFO, 2867204, 88, {op=PTRACE_SYSCALL_INFO_ENTRY, arch=AUDIT_ARCH_X86_64, instruction_pointer=0x78d508ca2dab, stack_pointer=0x7ffce96cb968, entry={nr=__NR_mprotect, args=[0x78d508c00000, 0x4000, 0x1, 0x78d508c73160, 0x78d508c73160, 0]}}) = 80ptrace(PTRACE_SYSCALL, 2867204, NULL, 0) = 0--- SIGCHLD {si_signo=SIGCHLD, si_code=CLD_TRAPPED, si_pid=2867204, si_uid=1000, si_status=SIGTRAP, si_utime=0, si_stime=0} ---wait4(-1, [{WIFSTOPPED(s) && WSTOPSIG(s) == SIGTRAP | 0x80}], __WALL, NULL) = 2867204wait4(-1, 0x7fff31d5821c, WNOHANG|__WALL, NULL) = 0ptrace(PTRACE_SYSCALL, 2867204, NULL, 0) = 0--- SIGCHLD {si_signo=SIGCHLD, si_code=CLD_TRAPPED, si_pid=2867204, si_uid=1000, si_status=SIGTRAP, si_utime=0, si_stime=0} ---wait4(-1, [{WIFSTOPPED(s) && WSTOPSIG(s) == SIGTRAP | 0x80}], __WALL, NULL) = 2867204wait4(-1, 0x7fff31d5821c, WNOHANG|__WALL, NULL) = 0ptrace(PTRACE_GET_SYSCALL_INFO, 2867204, 88, {op=PTRACE_SYSCALL_INFO_ENTRY, arch=AUDIT_ARCH_X86_64, instruction_pointer=0x78d508ca2dab, stack_pointer=0x7ffce96cb968, entry={nr=__NR_mprotect, args=[0x5b3dadc8a000, 0x1000, 0x1, 0x78d508cb62e0, 0x78d508cb62e0, 0x78d508b1b3b0]}}) = 80ptrace(PTRACE_SYSCALL, 2867204, NULL, 0) = 0--- SIGCHLD {si_signo=SIGCHLD, si_code=CLD_TRAPPED, si_pid=2867204, si_uid=1000, si_status=SIGTRAP, si_utime=0, si_stime=0} ---wait4(-1, [{WIFSTOPPED(s) && WSTOPSIG(s) == SIGTRAP | 0x80}], __WALL, NULL) = 2867204wait4(-1, 0x7fff31d5821c, WNOHANG|__WALL, NULL) = 0ptrace(PTRACE_SYSCALL, 2867204, NULL, 0) = 0--- SIGCHLD {si_signo=SIGCHLD, si_code=CLD_TRAPPED, si_pid=2867204, si_uid=1000, si_status=SIGTRAP, si_utime=0, si_stime=0} ---wait4(-1, [{WIFSTOPPED(s) && WSTOPSIG(s) == SIGTRAP | 0x80}], __WALL, NULL) = 2867204wait4(-1, 0x7fff31d5821c, WNOHANG|__WALL, NULL) = 0ptrace(PTRACE_GET_SYSCALL_INFO, 2867204, 88, {op=PTRACE_SYSCALL_INFO_ENTRY, arch=AUDIT_ARCH_X86_64, instruction_pointer=0x78d508ca2dab, stack_pointer=0x7ffce96cb968, entry={nr=__NR_mprotect, args=[0x78d508cb3000, 0x2000, 0x1, 0x78d508cb5ab0, 0x78d508cb5ab0, 0]}}) = 80ptrace(PTRACE_SYSCALL, 2867204, NULL, 0) = 0--- SIGCHLD {si_signo=SIGCHLD, si_code=CLD_TRAPPED, si_pid=2867204, si_uid=1000, si_status=SIGTRAP, si_utime=0, si_stime=0} ---wait4(-1, [{WIFSTOPPED(s) && WSTOPSIG(s) == SIGTRAP | 0x80}], __WALL, NULL) = 2867204wait4(-1, 0x7fff31d5821c, WNOHANG|__WALL, NULL) = 0ptrace(PTRACE_SYSCALL, 2867204, NULL, 0) = 0wait4(-1, [{WIFSTOPPED(s) && WSTOPSIG(s) == SIGTRAP | 0x80}], __WALL, NULL) = 2867204--- SIGCHLD {si_signo=SIGCHLD, si_code=CLD_TRAPPED, si_pid=2867204, si_uid=1000, si_status=SIGTRAP, si_utime=0, si_stime=0} ---wait4(-1, 0x7fff31d5821c, WNOHANG|__WALL, NULL) = 0ptrace(PTRACE_GET_SYSCALL_INFO, 2867204, 88, {op=PTRACE_SYSCALL_INFO_ENTRY, arch=AUDIT_ARCH_X86_64, instruction_pointer=0x78d508b1d454, stack_pointer=0x7ffce96cba58, entry={nr=__NR_prlimit64, args=[0, 0x3, 0, 0x7ffce96cba60, 0, 0xd]}}) = 80ptrace(PTRACE_SYSCALL, 2867204, NULL, 0) = 0--- SIGCHLD {si_signo=SIGCHLD, si_code=CLD_TRAPPED, si_pid=2867204, si_uid=1000, si_status=SIGTRAP, si_utime=0, si_stime=0} ---wait4(-1, [{WIFSTOPPED(s) && WSTOPSIG(s) == SIGTRAP | 0x80}], __WALL, NULL) = 2867204wait4(-1, 0x7fff31d5821c, WNOHANG|__WALL, NULL) = 0ptrace(PTRACE_SYSCALL, 2867204, NULL, 0) = 0wait4(-1, [{WIFSTOPPED(s) && WSTOPSIG(s) == SIGTRAP | 0x80}], __WALL, NULL) = 2867204--- SIGCHLD {si_signo=SIGCHLD, si_code=CLD_TRAPPED, si_pid=2867204, si_uid=1000, si_status=SIGTRAP, si_utime=0, si_stime=0} ---wait4(-1, 0x7fff31d5821c, WNOHANG|__WALL, NULL) = 0ptrace(PTRACE_GET_SYSCALL_INFO, 2867204, 88, {op=PTRACE_SYSCALL_INFO_ENTRY, arch=AUDIT_ARCH_X86_64, instruction_pointer=0x78d508ca2ddb, stack_pointer=0x7ffce96cba88, entry={nr=__NR_munmap, args=[0x78d508c4e000, 0x241e8, 0, 0x7ffce96cba60, 0, 0x78d508cb3440]}}) = 80ptrace(PTRACE_SYSCALL, 2867204, NULL, 0) = 0wait4(-1, [{WIFSTOPPED(s) && WSTOPSIG(s) == SIGTRAP | 0x80}], __WALL, NULL) = 2867204--- SIGCHLD {si_signo=SIGCHLD, si_code=CLD_TRAPPED, si_pid=2867204, si_uid=1000, si_status=SIGTRAP, si_utime=0, si_stime=0} ---wait4(-1, 0x7fff31d5821c, WNOHANG|__WALL, NULL) = 0ptrace(PTRACE_SYSCALL, 2867204, NULL, 0) = 0wait4(-1, [{WIFSTOPPED(s) && WSTOPSIG(s) == SIGTRAP | 0x80}], __WALL, NULL) = 2867204--- SIGCHLD {si_signo=SIGCHLD, si_code=CLD_TRAPPED, si_pid=2867204, si_uid=1000, si_status=SIGTRAP, si_utime=0, si_stime=0} ---wait4(-1, 0x7fff31d5821c, WNOHANG|__WALL, NULL) = 0ptrace(PTRACE_GET_SYSCALL_INFO, 2867204, 88, {op=PTRACE_SYSCALL_INFO_ENTRY, arch=AUDIT_ARCH_X86_64, instruction_pointer=0x78d508b1c69b, stack_pointer=0x7ffce96cbc28, entry={nr=__NR_unlink, args=[0x5b3dadc89008, 0x7ffce96cbe68, 0x7ffce96cbe78, 0x7ffce96cba60, 0, 0x78d508c82380]}}) = 80ptrace(PTRACE_SYSCALL, 2867204, NULL, 0) = 0--- SIGCHLD {si_signo=SIGCHLD, si_code=CLD_TRAPPED, si_pid=2867204, si_uid=1000, si_status=SIGTRAP, si_utime=0, si_stime=0} ---wait4(-1, [{WIFSTOPPED(s) && WSTOPSIG(s) == SIGTRAP | 0x80}], __WALL, NULL) = 2867204wait4(-1, 0x7fff31d5821c, WNOHANG|__WALL, NULL) = 0ptrace(PTRACE_SYSCALL, 2867204, NULL, 0) = 0--- SIGCHLD {si_signo=SIGCHLD, si_code=CLD_TRAPPED, si_pid=2867204, si_uid=1000, si_status=SIGTRAP, si_utime=0, si_stime=0} ---wait4(-1, [{WIFSTOPPED(s) && WSTOPSIG(s) == SIGTRAP | 0x80}], __WALL, NULL) = 2867204wait4(-1, 0x7fff31d5821c, WNOHANG|__WALL, NULL) = 0ptrace(PTRACE_GET_SYSCALL_INFO, 2867204, 88, {op=PTRACE_SYSCALL_INFO_ENTRY, arch=AUDIT_ARCH_X86_64, instruction_pointer=0x78d508b1b6ad, stack_pointer=0x7ffce96cbc28, entry={nr=__NR_pipe2, args=[0x7ffce96cbc80, 0, 0x4, 0x7ffce96cba60, 0, 0x78d508c82380]}}) = 80ptrace(PTRACE_SYSCALL, 2867204, NULL, 0) = 0--- SIGCHLD {si_signo=SIGCHLD, si_code=CLD_TRAPPED, si_pid=2867204, si_uid=1000, si_status=SIGTRAP, si_utime=0, si_stime=0} ---wait4(-1, [{WIFSTOPPED(s) && WSTOPSIG(s) == SIGTRAP | 0x80}], __WALL, NULL) = 2867204wait4(-1, 0x7fff31d5821c, WNOHANG|__WALL, NULL) = 0ptrace(PTRACE_SYSCALL, 2867204, NULL, 0) = 0--- SIGCHLD {si_signo=SIGCHLD, si_code=CLD_TRAPPED, si_pid=2867204, si_uid=1000, si_status=SIGTRAP, si_utime=0, si_stime=0} ---wait4(-1, [{WIFSTOPPED(s) && WSTOPSIG(s) == SIGTRAP | 0x80}], __WALL, NULL) = 2867204wait4(-1, 0x7fff31d5821c, WNOHANG|__WALL, NULL) = 0ptrace(PTRACE_GET_SYSCALL_INFO, 2867204, 88, {op=PTRACE_SYSCALL_INFO_ENTRY, arch=AUDIT_ARCH_X86_64, instruction_pointer=0x78d508b1c804, stack_pointer=0x7ffce96cbbd8, entry={nr=__NR_write, args=[0x4, 0x7ffce96cbcb0, 0x7, 0x7ffce96cba60, 0, 0x78d508c82380]}}) = 80process_vm_readv(2867204, [{iov_base="\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0@1\307\10\0\0\0\0"..., iov_len=4096}], 1, [{iov_base=0x7ffce96cb000, iov_len=4096}], 1, 0) = 4096write(2, "write(4, \"HDR0$%&\", 7", 21) = 21ptrace(PTRACE_SYSCALL, 2867204, NULL, 0) = 0--- SIGCHLD {si_signo=SIGCHLD, si_code=CLD_TRAPPED, si_pid=2867204, si_uid=1000, si_status=SIGTRAP, si_utime=0, si_stime=0} ---wait4(-1, [{WIFSTOPPED(s) && WSTOPSIG(s) == SIGTRAP | 0x80}], __WALL, NULL) = 2867204wait4(-1, 0x7fff31d5821c, WNOHANG|__WALL, NULL) = 0ptrace(PTRACE_GET_SYSCALL_INFO, 2867204, 88, {op=PTRACE_SYSCALL_INFO_EXIT, arch=AUDIT_ARCH_X86_64, instruction_pointer=0x78d508b1c804, stack_pointer=0x7ffce96cbbd8, exit={rval=7, is_error=0}}) = 33write(2, ") = 7\n", 23) = 23ptrace(PTRACE_SYSCALL, 2867204, NULL, 0) = 0--- SIGCHLD {si_signo=SIGCHLD, si_code=CLD_TRAPPED, si_pid=2867204, si_uid=1000, si_status=SIGTRAP, si_utime=0, si_stime=0} ---wait4(-1, [{WIFSTOPPED(s) && WSTOPSIG(s) == SIGTRAP | 0x80}], __WALL, NULL) = 2867204wait4(-1, 0x7fff31d5821c, WNOHANG|__WALL, NULL) = 0ptrace(PTRACE_GET_SYSCALL_INFO, 2867204, 88, {op=PTRACE_SYSCALL_INFO_ENTRY, arch=AUDIT_ARCH_X86_64, instruction_pointer=0x78d508b1bcf1, stack_pointer=0x7ffce96cbc28, entry={nr=__NR_read, args=[0x3, 0x7ffce96cbc90, 0x14, 0x7ffce96cba60, 0, 0x78d508c82380]}}) = 80write(2, "read(3, ", 8) = 8ptrace(PTRACE_SYSCALL, 2867204, NULL, 0) = 0--- SIGCHLD {si_signo=SIGCHLD, si_code=CLD_TRAPPED, si_pid=2867204, si_uid=1000, si_status=SIGTRAP, si_utime=0, si_stime=0} ---wait4(-1, [{WIFSTOPPED(s) && WSTOPSIG(s) == SIGTRAP | 0x80}], __WALL, NULL) = 2867204wait4(-1, 0x7fff31d5821c, WNOHANG|__WALL, NULL) = 0ptrace(PTRACE_GET_SYSCALL_INFO, 2867204, 88, {op=PTRACE_SYSCALL_INFO_EXIT, arch=AUDIT_ARCH_X86_64, instruction_pointer=0x78d508b1bcf1, stack_pointer=0x7ffce96cbc28, exit={rval=7, is_error=0}}) = 33process_vm_readv(2867204, [{iov_base="\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0@1\307\10\0\0\0\0"..., iov_len=4096}], 1, [{iov_base=0x7ffce96cb000, iov_len=4096}], 1, 0) = 4096write(2, "\"HDR0$%&\", 20) "..., 36) = 36ptrace(PTRACE_SYSCALL, 2867204, NULL, 0) = 0--- SIGCHLD {si_signo=SIGCHLD, si_code=CLD_TRAPPED, si_pid=2867204, si_uid=1000, si_status=SIGTRAP, si_utime=0, si_stime=0} ---wait4(-1, [{WIFSTOPPED(s) && WSTOPSIG(s) == SIGTRAP | 0x80}], __WALL, NULL) = 2867204wait4(-1, 0x7fff31d5821c, WNOHANG|__WALL, NULL) = 0ptrace(PTRACE_GET_SYSCALL_INFO, 2867204, 88, {op=PTRACE_SYSCALL_INFO_ENTRY, arch=AUDIT_ARCH_X86_64, instruction_pointer=0x78d508b1c804, stack_pointer=0x7ffce96cbbd8, entry={nr=__NR_write, args=[0x4, 0x7ffce96cbcb7, 0xd, 0x7ffce96cba60, 0, 0x78d508c82380]}}) = 80process_vm_readv(2867204, [{iov_base="\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0@1\307\10\0\0\0\0"..., iov_len=4096}], 1, [{iov_base=0x7ffce96cb000, iov_len=4096}], 1, 0) = 4096write(2, "write(4, \"'()*\\0,-./012\\0\", 13", 30) = 30ptrace(PTRACE_SYSCALL, 2867204, NULL, 0) = 0--- SIGCHLD {si_signo=SIGCHLD, si_code=CLD_TRAPPED, si_pid=2867204, si_uid=1000, si_status=SIGTRAP, si_utime=0, si_stime=0} ---wait4(-1, [{WIFSTOPPED(s) && WSTOPSIG(s) == SIGTRAP | 0x80}], __WALL, NULL) = 2867204wait4(-1, 0x7fff31d5821c, WNOHANG|__WALL, NULL) = 0ptrace(PTRACE_GET_SYSCALL_INFO, 2867204, 88, {op=PTRACE_SYSCALL_INFO_EXIT, arch=AUDIT_ARCH_X86_64, instruction_pointer=0x78d508b1c804, stack_pointer=0x7ffce96cbbd8, exit={rval=13, is_error=0}}) = 33write(2, ") = 13\n", 15) = 15ptrace(PTRACE_SYSCALL, 2867204, NULL, 0) = 0--- SIGCHLD {si_signo=SIGCHLD, si_code=CLD_TRAPPED, si_pid=2867204, si_uid=1000, si_status=SIGTRAP, si_utime=0, si_stime=0} ---wait4(-1, [{WIFSTOPPED(s) && WSTOPSIG(s) == SIGTRAP | 0x80}], __WALL, NULL) = 2867204wait4(-1, 0x7fff31d5821c, WNOHANG|__WALL, NULL) = 0ptrace(PTRACE_GET_SYSCALL_INFO, 2867204, 88, {op=PTRACE_SYSCALL_INFO_ENTRY, arch=AUDIT_ARCH_X86_64, instruction_pointer=0x78d508b16984, stack_pointer=0x7ffce96cbc28, entry={nr=__NR_close, args=[0x4, 0x7ffce96cbcb7, 0xd, 0x7ffce96cba60, 0, 0x78d508c82380]}}) = 80write(2, "close(4", 7) = 7ptrace(PTRACE_SYSCALL, 2867204, NULL, 0) = 0--- SIGCHLD {si_signo=SIGCHLD, si_code=CLD_TRAPPED, si_pid=2867204, si_uid=1000, si_status=SIGTRAP, si_utime=0, si_stime=0} ---wait4(-1, [{WIFSTOPPED(s) && WSTOPSIG(s) == SIGTRAP | 0x80}], __WALL, NULL) = 2867204wait4(-1, 0x7fff31d5821c, WNOHANG|__WALL, NULL) = 0ptrace(PTRACE_GET_SYSCALL_INFO, 2867204, 88, {op=PTRACE_SYSCALL_INFO_EXIT, arch=AUDIT_ARCH_X86_64, instruction_pointer=0x78d508b16984, stack_pointer=0x7ffce96cbc28, exit={rval=0, is_error=0}}) = 33write(2, ") "..., 37) = 37ptrace(PTRACE_SYSCALL, 2867204, NULL, 0) = 0--- SIGCHLD {si_signo=SIGCHLD, si_code=CLD_TRAPPED, si_pid=2867204, si_uid=1000, si_status=SIGTRAP, si_utime=0, si_stime=0} ---wait4(-1, [{WIFSTOPPED(s) && WSTOPSIG(s) == SIGTRAP | 0x80}], __WALL, NULL) = 2867204wait4(-1, 0x7fff31d5821c, WNOHANG|__WALL, NULL) = 0ptrace(PTRACE_GET_SYSCALL_INFO, 2867204, 88, {op=PTRACE_SYSCALL_INFO_ENTRY, arch=AUDIT_ARCH_X86_64, instruction_pointer=0x78d508b1bcf1, stack_pointer=0x7ffce96cbbd8, entry={nr=__NR_read, args=[0x3, 0x7ffce96cbc97, 0xd, 0x7ffce96cba60, 0, 0x78d508c82380]}}) = 80write(2, "read(3, ", 8) = 8ptrace(PTRACE_SYSCALL, 2867204, NULL, 0) = 0--- SIGCHLD {si_signo=SIGCHLD, si_code=CLD_TRAPPED, si_pid=2867204, si_uid=1000, si_status=SIGTRAP, si_utime=0, si_stime=0} ---wait4(-1, [{WIFSTOPPED(s) && WSTOPSIG(s) == SIGTRAP | 0x80}], __WALL, NULL) = 2867204wait4(-1, 0x7fff31d5821c, WNOHANG|__WALL, NULL) = 0ptrace(PTRACE_GET_SYSCALL_INFO, 2867204, 88, {op=PTRACE_SYSCALL_INFO_EXIT, arch=AUDIT_ARCH_X86_64, instruction_pointer=0x78d508b1bcf1, stack_pointer=0x7ffce96cbbd8, exit={rval=13, is_error=0}}) = 33process_vm_readv(2867204, [{iov_base="\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0@1\307\10\0\0\0\0"..., iov_len=4096}], 1, [{iov_base=0x7ffce96cb000, iov_len=4096}], 1, 0) = 4096write(2, "\"'()*\\0,-./012\\0\", 13) "..., 37) = 37ptrace(PTRACE_SYSCALL, 2867204, NULL, 0) = 0--- SIGCHLD {si_signo=SIGCHLD, si_code=CLD_TRAPPED, si_pid=2867204, si_uid=1000, si_status=SIGTRAP, si_utime=0, si_stime=0} ---wait4(-1, [{WIFSTOPPED(s) && WSTOPSIG(s) == SIGTRAP | 0x80}], __WALL, NULL) = 2867204wait4(-1, 0x7fff31d5821c, WNOHANG|__WALL, NULL) = 0ptrace(PTRACE_GET_SYSCALL_INFO, 2867204, 88, {op=PTRACE_SYSCALL_INFO_ENTRY, arch=AUDIT_ARCH_X86_64, instruction_pointer=0x78d508b16984, stack_pointer=0x7ffce96cbc28, entry={nr=__NR_close, args=[0x3, 0x7ffce96cbc97, 0x1, 0x7ffce96cba60, 0, 0x78d508c82380]}}) = 80write(2, "close(3", 7) = 7ptrace(PTRACE_SYSCALL, 2867204, NULL, 0) = 0--- SIGCHLD {si_signo=SIGCHLD, si_code=CLD_TRAPPED, si_pid=2867204, si_uid=1000, si_status=SIGTRAP, si_utime=0, si_stime=0} ---wait4(-1, [{WIFSTOPPED(s) && WSTOPSIG(s) == SIGTRAP | 0x80}], __WALL, NULL) = 2867204wait4(-1, 0x7fff31d5821c, WNOHANG|__WALL, NULL) = 0ptrace(PTRACE_GET_SYSCALL_INFO, 2867204, 88, {op=PTRACE_SYSCALL_INFO_EXIT, arch=AUDIT_ARCH_X86_64, instruction_pointer=0x78d508b16984, stack_pointer=0x7ffce96cbc28, exit={rval=0, is_error=0}}) = 33write(2, ") "..., 37) = 37ptrace(PTRACE_SYSCALL, 2867204, NULL, 0) = 0--- SIGCHLD {si_signo=SIGCHLD, si_code=CLD_TRAPPED, si_pid=2867204, si_uid=1000, si_status=SIGTRAP, si_utime=0, si_stime=0} ---wait4(-1, [{WIFSTOPPED(s) && WSTOPSIG(s) == SIGTRAP | 0x80}], __WALL, NULL) = 2867204wait4(-1, 0x7fff31d5821c, WNOHANG|__WALL, NULL) = 0ptrace(PTRACE_GET_SYSCALL_INFO, 2867204, 88, {op=PTRACE_SYSCALL_INFO_ENTRY, arch=AUDIT_ARCH_X86_64, instruction_pointer=0x78d508b1b405, stack_pointer=0x7ffce96cbbb0, entry={nr=__NR_openat, args=[0xffffff9c, 0x5b3dadc89008, 0x80241, 0x1a4, 0, 0x78d508c82380]}}) = 80process_vm_readv(2867204, [{iov_base="\1\0\2\0\0\0\0\0/tmp/ksa_m02_io.bin\0HDR0"..., iov_len=4096}], 1, [{iov_base=0x5b3dadc89000, iov_len=4096}], 1, 0) = 4096write(2, "openat(AT_FDCWD, \"/tmp/ksa_m02_i"..., 80) = 80ptrace(PTRACE_SYSCALL, 2867204, NULL, 0) = 0wait4(-1, [{WIFSTOPPED(s) && WSTOPSIG(s) == SIGTRAP | 0x80}], __WALL, NULL) = 2867204--- SIGCHLD {si_signo=SIGCHLD, si_code=CLD_TRAPPED, si_pid=2867204, si_uid=1000, si_status=SIGTRAP, si_utime=0, si_stime=0} ---wait4(-1, 0x7fff31d5821c, WNOHANG|__WALL, NULL) = 0ptrace(PTRACE_GET_SYSCALL_INFO, 2867204, 88, {op=PTRACE_SYSCALL_INFO_EXIT, arch=AUDIT_ARCH_X86_64, instruction_pointer=0x78d508b1b405, stack_pointer=0x7ffce96cbbb0, exit={rval=3, is_error=0}}) = 33write(2, ") = 3\n", 6) = 6ptrace(PTRACE_SYSCALL, 2867204, NULL, 0) = 0--- SIGCHLD {si_signo=SIGCHLD, si_code=CLD_TRAPPED, si_pid=2867204, si_uid=1000, si_status=SIGTRAP, si_utime=0, si_stime=0} ---wait4(-1, [{WIFSTOPPED(s) && WSTOPSIG(s) == SIGTRAP | 0x80}], __WALL, NULL) = 2867204wait4(-1, 0x7fff31d5821c, WNOHANG|__WALL, NULL) = 0ptrace(PTRACE_GET_SYSCALL_INFO, 2867204, 88, {op=PTRACE_SYSCALL_INFO_ENTRY, arch=AUDIT_ARCH_X86_64, instruction_pointer=0x78d508b1c804, stack_pointer=0x7ffce96cbbd8, entry={nr=__NR_write, args=[0x3, 0x7ffce96cbcb0, 0x11, 0x1a4, 0, 0x78d508c82380]}}) = 80process_vm_readv(2867204, [{iov_base="\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0@1\307\10\0\0\0\0"..., iov_len=4096}], 1, [{iov_base=0x7ffce96cb000, iov_len=4096}], 1, 0) = 4096write(2, "write(3, \"HDR0$%&'()*\\0,-./0\", 1"..., 33) = 33ptrace(PTRACE_SYSCALL, 2867204, NULL, 0) = 0wait4(-1, [{WIFSTOPPED(s) && WSTOPSIG(s) == SIGTRAP | 0x80}], __WALL, NULL) = 2867204--- SIGCHLD {si_signo=SIGCHLD, si_code=CLD_TRAPPED, si_pid=2867204, si_uid=1000, si_status=SIGTRAP, si_utime=0, si_stime=0} ---wait4(-1, 0x7fff31d5821c, WNOHANG|__WALL, NULL) = 0ptrace(PTRACE_GET_SYSCALL_INFO, 2867204, 88, {op=PTRACE_SYSCALL_INFO_EXIT, arch=AUDIT_ARCH_X86_64, instruction_pointer=0x78d508b1c804, stack_pointer=0x7ffce96cbbd8, exit={rval=17, is_error=0}}) = 33write(2, ") = 17\n", 12) = 12ptrace(PTRACE_SYSCALL, 2867204, NULL, 0) = 0--- SIGCHLD {si_signo=SIGCHLD, si_code=CLD_TRAPPED, si_pid=2867204, si_uid=1000, si_status=SIGTRAP, si_utime=0, si_stime=0} ---wait4(-1, [{WIFSTOPPED(s) && WSTOPSIG(s) == SIGTRAP | 0x80}], __WALL, NULL) = 2867204wait4(-1, 0x7fff31d5821c, WNOHANG|__WALL, NULL) = 0ptrace(PTRACE_GET_SYSCALL_INFO, 2867204, 88, {op=PTRACE_SYSCALL_INFO_ENTRY, arch=AUDIT_ARCH_X86_64, instruction_pointer=0x78d508b1c804, stack_pointer=0x7ffce96cbbd8, entry={nr=__NR_write, args=[0x3, 0x7ffce96cbcc1, 0x13, 0x1a4, 0, 0x78d508c82380]}}) = 80process_vm_readv(2867204, [{iov_base="\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0@1\307\10\0\0\0\0"..., iov_len=4096}], 1, [{iov_base=0x7ffce96cb000, iov_len=4096}], 1, 0) = 4096write(2, "write(3, \"12\\000456789:\\0<=>?@AB"..., 39) = 39ptrace(PTRACE_SYSCALL, 2867204, NULL, 0) = 0--- SIGCHLD {si_signo=SIGCHLD, si_code=CLD_TRAPPED, si_pid=2867204, si_uid=1000, si_status=SIGTRAP, si_utime=0, si_stime=0} ---wait4(-1, [{WIFSTOPPED(s) && WSTOPSIG(s) == SIGTRAP | 0x80}], __WALL, NULL) = 2867204wait4(-1, 0x7fff31d5821c, WNOHANG|__WALL, NULL) = 0ptrace(PTRACE_GET_SYSCALL_INFO, 2867204, 88, {op=PTRACE_SYSCALL_INFO_EXIT, arch=AUDIT_ARCH_X86_64, instruction_pointer=0x78d508b1c804, stack_pointer=0x7ffce96cbbd8, exit={rval=19, is_error=0}}) = 33write(2, ") = 19\n", 7) = 7ptrace(PTRACE_SYSCALL, 2867204, NULL, 0) = 0--- SIGCHLD {si_signo=SIGCHLD, si_code=CLD_TRAPPED, si_pid=2867204, si_uid=1000, si_status=SIGTRAP, si_utime=0, si_stime=0} ---wait4(-1, [{WIFSTOPPED(s) && WSTOPSIG(s) == SIGTRAP | 0x80}], __WALL, NULL) = 2867204wait4(-1, 0x7fff31d5821c, WNOHANG|__WALL, NULL) = 0ptrace(PTRACE_GET_SYSCALL_INFO, 2867204, 88, {op=PTRACE_SYSCALL_INFO_ENTRY, arch=AUDIT_ARCH_X86_64, instruction_pointer=0x78d508b1c804, stack_pointer=0x7ffce96cbbd8, entry={nr=__NR_write, args=[0x3, 0x7ffce96cbcd4, 0x1c, 0x1a4, 0, 0x78d508c82380]}}) = 80process_vm_readv(2867204, [{iov_base="\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0@1\307\10\0\0\0\0"..., iov_len=4096}], 1, [{iov_base=0x7ffce96cb000, iov_len=4096}], 1, 0) = 4096write(2, "write(3, \"DEFGHIJ\\0LMNOPQR\\0TUVW"..., 47) = 47ptrace(PTRACE_SYSCALL, 2867204, NULL, 0) = 0--- SIGCHLD {si_signo=SIGCHLD, si_code=CLD_TRAPPED, si_pid=2867204, si_uid=1000, si_status=SIGTRAP, si_utime=0, si_stime=0} ---wait4(-1, [{WIFSTOPPED(s) && WSTOPSIG(s) == SIGTRAP | 0x80}], __WALL, NULL) = 2867204wait4(-1, 0x7fff31d5821c, WNOHANG|__WALL, NULL) = 0ptrace(PTRACE_GET_SYSCALL_INFO, 2867204, 88, {op=PTRACE_SYSCALL_INFO_EXIT, arch=AUDIT_ARCH_X86_64, instruction_pointer=0x78d508b1c804, stack_pointer=0x7ffce96cbbd8, exit={rval=28, is_error=0}}) = 33write(2, ") = 28\n", 7) = 7ptrace(PTRACE_SYSCALL, 2867204, NULL, 0) = 0--- SIGCHLD {si_signo=SIGCHLD, si_code=CLD_TRAPPED, si_pid=2867204, si_uid=1000, si_status=SIGTRAP, si_utime=0, si_stime=0} ---wait4(-1, [{WIFSTOPPED(s) && WSTOPSIG(s) == SIGTRAP | 0x80}], __WALL, NULL) = 2867204wait4(-1, 0x7fff31d5821c, WNOHANG|__WALL, NULL) = 0ptrace(PTRACE_GET_SYSCALL_INFO, 2867204, 88, {op=PTRACE_SYSCALL_INFO_ENTRY, arch=AUDIT_ARCH_X86_64, instruction_pointer=0x78d508b16984, stack_pointer=0x7ffce96cbc28, entry={nr=__NR_close, args=[0x3, 0x7ffce96cbcd4, 0x1c, 0x1a4, 0, 0x78d508c82380]}}) = 80write(2, "close(3", 7) = 7ptrace(PTRACE_SYSCALL, 2867204, NULL, 0) = 0--- SIGCHLD {si_signo=SIGCHLD, si_code=CLD_TRAPPED, si_pid=2867204, si_uid=1000, si_status=SIGTRAP, si_utime=0, si_stime=0} ---wait4(-1, [{WIFSTOPPED(s) && WSTOPSIG(s) == SIGTRAP | 0x80}], __WALL, NULL) = 2867204wait4(-1, 0x7fff31d5821c, WNOHANG|__WALL, NULL) = 0ptrace(PTRACE_GET_SYSCALL_INFO, 2867204, 88, {op=PTRACE_SYSCALL_INFO_EXIT, arch=AUDIT_ARCH_X86_64, instruction_pointer=0x78d508b16984, stack_pointer=0x7ffce96cbc28, exit={rval=0, is_error=0}}) = 33write(2, ") "..., 37) = 37ptrace(PTRACE_SYSCALL, 2867204, NULL, 0) = 0--- SIGCHLD {si_signo=SIGCHLD, si_code=CLD_TRAPPED, si_pid=2867204, si_uid=1000, si_status=SIGTRAP, si_utime=0, si_stime=0} ---wait4(-1, [{WIFSTOPPED(s) && WSTOPSIG(s) == SIGTRAP | 0x80}], __WALL, NULL) = 2867204wait4(-1, 0x7fff31d5821c, WNOHANG|__WALL, NULL) = 0ptrace(PTRACE_GET_SYSCALL_INFO, 2867204, 88, {op=PTRACE_SYSCALL_INFO_ENTRY, arch=AUDIT_ARCH_X86_64, instruction_pointer=0x78d508b1b405, stack_pointer=0x7ffce96cbbb0, entry={nr=__NR_openat, args=[0xffffff9c, 0x5b3dadc89008, 0x80000, 0, 0, 0x78d508c82380]}}) = 80process_vm_readv(2867204, [{iov_base="\1\0\2\0\0\0\0\0/tmp/ksa_m02_io.bin\0HDR0"..., iov_len=4096}], 1, [{iov_base=0x5b3dadc89000, iov_len=4096}], 1, 0) = 4096write(2, "openat(AT_FDCWD, \"/tmp/ksa_m02_i"..., 58) = 58ptrace(PTRACE_SYSCALL, 2867204, NULL, 0) = 0--- SIGCHLD {si_signo=SIGCHLD, si_code=CLD_TRAPPED, si_pid=2867204, si_uid=1000, si_status=SIGTRAP, si_utime=0, si_stime=0} ---wait4(-1, [{WIFSTOPPED(s) && WSTOPSIG(s) == SIGTRAP | 0x80}], __WALL, NULL) = 2867204wait4(-1, 0x7fff31d5821c, WNOHANG|__WALL, NULL) = 0ptrace(PTRACE_GET_SYSCALL_INFO, 2867204, 88, {op=PTRACE_SYSCALL_INFO_EXIT, arch=AUDIT_ARCH_X86_64, instruction_pointer=0x78d508b1b405, stack_pointer=0x7ffce96cbbb0, exit={rval=3, is_error=0}}) = 33write(2, ") = 3\n", 6) = 6ptrace(PTRACE_SYSCALL, 2867204, NULL, 0) = 0--- SIGCHLD {si_signo=SIGCHLD, si_code=CLD_TRAPPED, si_pid=2867204, si_uid=1000, si_status=SIGTRAP, si_utime=0, si_stime=0} ---wait4(-1, [{WIFSTOPPED(s) && WSTOPSIG(s) == SIGTRAP | 0x80}], __WALL, NULL) = 2867204wait4(-1, 0x7fff31d5821c, WNOHANG|__WALL, NULL) = 0ptrace(PTRACE_GET_SYSCALL_INFO, 2867204, 88, {op=PTRACE_SYSCALL_INFO_ENTRY, arch=AUDIT_ARCH_X86_64, instruction_pointer=0x78d508b1bcf1, stack_pointer=0x7ffce96cbbd8, entry={nr=__NR_read, args=[0x3, 0x7ffce96cbcf0, 0x14, 0, 0, 0x78d508c82380]}}) = 80write(2, "read(3, ", 8) = 8ptrace(PTRACE_SYSCALL, 2867204, NULL, 0) = 0wait4(-1, [{WIFSTOPPED(s) && WSTOPSIG(s) == SIGTRAP | 0x80}], __WALL, NULL) = 2867204--- SIGCHLD {si_signo=SIGCHLD, si_code=CLD_TRAPPED, si_pid=2867204, si_uid=1000, si_status=SIGTRAP, si_utime=0, si_stime=0} ---wait4(-1, 0x7fff31d5821c, WNOHANG|__WALL, NULL) = 0ptrace(PTRACE_GET_SYSCALL_INFO, 2867204, 88, {op=PTRACE_SYSCALL_INFO_EXIT, arch=AUDIT_ARCH_X86_64, instruction_pointer=0x78d508b1bcf1, stack_pointer=0x7ffce96cbbd8, exit={rval=20, is_error=0}}) = 33process_vm_readv(2867204, [{iov_base="\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0@1\307\10\0\0\0\0"..., iov_len=4096}], 1, [{iov_base=0x7ffce96cb000, iov_len=4096}], 1, 0) = 4096write(2, "\"HDR0$%&'()*\\0,-./012\\0\", 20) "..., 37) = 37ptrace(PTRACE_SYSCALL, 2867204, NULL, 0) = 0--- SIGCHLD {si_signo=SIGCHLD, si_code=CLD_TRAPPED, si_pid=2867204, si_uid=1000, si_status=SIGTRAP, si_utime=0, si_stime=0} ---wait4(-1, [{WIFSTOPPED(s) && WSTOPSIG(s) == SIGTRAP | 0x80}], __WALL, NULL) = 2867204wait4(-1, 0x7fff31d5821c, WNOHANG|__WALL, NULL) = 0ptrace(PTRACE_GET_SYSCALL_INFO, 2867204, 88, {op=PTRACE_SYSCALL_INFO_ENTRY, arch=AUDIT_ARCH_X86_64, instruction_pointer=0x78d508b1bcf1, stack_pointer=0x7ffce96cbbd8, entry={nr=__NR_read, args=[0x3, 0x7ffce96cbd04, 0x2c, 0, 0, 0x78d508c82380]}}) = 80write(2, "read(3, ", 8) = 8ptrace(PTRACE_SYSCALL, 2867204, NULL, 0) = 0--- SIGCHLD {si_signo=SIGCHLD, si_code=CLD_TRAPPED, si_pid=2867204, si_uid=1000, si_status=SIGTRAP, si_utime=0, si_stime=0} ---wait4(-1, [{WIFSTOPPED(s) && WSTOPSIG(s) == SIGTRAP | 0x80}], __WALL, NULL) = 2867204wait4(-1, 0x7fff31d5821c, WNOHANG|__WALL, NULL) = 0ptrace(PTRACE_GET_SYSCALL_INFO, 2867204, 88, {op=PTRACE_SYSCALL_INFO_EXIT, arch=AUDIT_ARCH_X86_64, instruction_pointer=0x78d508b1bcf1, stack_pointer=0x7ffce96cbbd8, exit={rval=44, is_error=0}}) = 33process_vm_readv(2867204, [{iov_base="\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0@1\307\10\0\0\0\0"..., iov_len=4096}], 1, [{iov_base=0x7ffce96cb000, iov_len=4096}], 1, 0) = 4096write(2, "\"456789:\\0<=>?@AB\\0DEFGHIJ\\0LMNO"..., 52) = 52ptrace(PTRACE_SYSCALL, 2867204, NULL, 0) = 0--- SIGCHLD {si_signo=SIGCHLD, si_code=CLD_TRAPPED, si_pid=2867204, si_uid=1000, si_status=SIGTRAP, si_utime=0, si_stime=0} ---wait4(-1, [{WIFSTOPPED(s) && WSTOPSIG(s) == SIGTRAP | 0x80}], __WALL, NULL) = 2867204wait4(-1, 0x7fff31d5821c, WNOHANG|__WALL, NULL) = 0ptrace(PTRACE_GET_SYSCALL_INFO, 2867204, 88, {op=PTRACE_SYSCALL_INFO_ENTRY, arch=AUDIT_ARCH_X86_64, instruction_pointer=0x78d508b1bcf1, stack_pointer=0x7ffce96cbc28, entry={nr=__NR_read, args=[0x3, 0x7ffce96cbc37, 0x1, 0, 0, 0x78d508c82380]}}) = 80write(2, "read(3, ", 8) = 8ptrace(PTRACE_SYSCALL, 2867204, NULL, 0) = 0--- SIGCHLD {si_signo=SIGCHLD, si_code=CLD_TRAPPED, si_pid=2867204, si_uid=1000, si_status=SIGTRAP, si_utime=0, si_stime=0} ---wait4(-1, [{WIFSTOPPED(s) && WSTOPSIG(s) == SIGTRAP | 0x80}], __WALL, NULL) = 2867204wait4(-1, 0x7fff31d5821c, WNOHANG|__WALL, NULL) = 0ptrace(PTRACE_GET_SYSCALL_INFO, 2867204, 88, {op=PTRACE_SYSCALL_INFO_EXIT, arch=AUDIT_ARCH_X86_64, instruction_pointer=0x78d508b1bcf1, stack_pointer=0x7ffce96cbc28, exit={rval=0, is_error=0}}) = 33write(2, "\"\", 1) "..., 36) = 36ptrace(PTRACE_SYSCALL, 2867204, NULL, 0) = 0--- SIGCHLD {si_signo=SIGCHLD, si_code=CLD_TRAPPED, si_pid=2867204, si_uid=1000, si_status=SIGTRAP, si_utime=0, si_stime=0} ---wait4(-1, [{WIFSTOPPED(s) && WSTOPSIG(s) == SIGTRAP | 0x80}], __WALL, NULL) = 2867204wait4(-1, 0x7fff31d5821c, WNOHANG|__WALL, NULL) = 0ptrace(PTRACE_GET_SYSCALL_INFO, 2867204, 88, {op=PTRACE_SYSCALL_INFO_ENTRY, arch=AUDIT_ARCH_X86_64, instruction_pointer=0x78d508b16984, stack_pointer=0x7ffce96cbc28, entry={nr=__NR_close, args=[0x3, 0x7ffce96cbc90, 0, 0, 0, 0x78d508c82380]}}) = 80write(2, "close(3", 7) = 7ptrace(PTRACE_SYSCALL, 2867204, NULL, 0) = 0--- SIGCHLD {si_signo=SIGCHLD, si_code=CLD_TRAPPED, si_pid=2867204, si_uid=1000, si_status=SIGTRAP, si_utime=0, si_stime=0} ---wait4(-1, [{WIFSTOPPED(s) && WSTOPSIG(s) == SIGTRAP | 0x80}], __WALL, NULL) = 2867204wait4(-1, 0x7fff31d5821c, WNOHANG|__WALL, NULL) = 0ptrace(PTRACE_GET_SYSCALL_INFO, 2867204, 88, {op=PTRACE_SYSCALL_INFO_EXIT, arch=AUDIT_ARCH_X86_64, instruction_pointer=0x78d508b16984, stack_pointer=0x7ffce96cbc28, exit={rval=0, is_error=0}}) = 33write(2, ") "..., 37) = 37ptrace(PTRACE_SYSCALL, 2867204, NULL, 0) = 0--- SIGCHLD {si_signo=SIGCHLD, si_code=CLD_TRAPPED, si_pid=2867204, si_uid=1000, si_status=SIGTRAP, si_utime=0, si_stime=0} ---wait4(-1, [{WIFSTOPPED(s) && WSTOPSIG(s) == SIGTRAP | 0x80}], __WALL, NULL) = 2867204wait4(-1, 0x7fff31d5821c, WNOHANG|__WALL, NULL) = 0ptrace(PTRACE_GET_SYSCALL_INFO, 2867204, 88, {op=PTRACE_SYSCALL_INFO_ENTRY, arch=AUDIT_ARCH_X86_64, instruction_pointer=0x78d508b1c69b, stack_pointer=0x7ffce96cbc28, entry={nr=__NR_unlink, args=[0x5b3dadc89008, 0x7ffce96cbc90, 0, 0, 0, 0x78d508c82380]}}) = 80ptrace(PTRACE_SYSCALL, 2867204, NULL, 0) = 0wait4(-1, [{WIFSTOPPED(s) && WSTOPSIG(s) == SIGTRAP | 0x80}], __WALL, NULL) = 2867204--- SIGCHLD {si_signo=SIGCHLD, si_code=CLD_TRAPPED, si_pid=2867204, si_uid=1000, si_status=SIGTRAP, si_utime=0, si_stime=0} ---wait4(-1, 0x7fff31d5821c, WNOHANG|__WALL, NULL) = 0ptrace(PTRACE_SYSCALL, 2867204, NULL, 0) = 0wait4(-1, [{WIFSTOPPED(s) && WSTOPSIG(s) == SIGTRAP | 0x80}], __WALL, NULL) = 2867204--- SIGCHLD {si_signo=SIGCHLD, si_code=CLD_TRAPPED, si_pid=2867204, si_uid=1000, si_status=SIGTRAP, si_utime=0, si_stime=0} ---wait4(-1, 0x7fff31d5821c, WNOHANG|__WALL, NULL) = 0ptrace(PTRACE_GET_SYSCALL_INFO, 2867204, 88, {op=PTRACE_SYSCALL_INFO_ENTRY, arch=AUDIT_ARCH_X86_64, instruction_pointer=0x78d508b1761b, stack_pointer=0x7ffce96cb858, entry={nr=__NR_fstat, args=[0x1, 0x7ffce96cb860, 0x78d508c02ee0, 0, 0x64, 0]}}) = 80ptrace(PTRACE_SYSCALL, 2867204, NULL, 0) = 0--- SIGCHLD {si_signo=SIGCHLD, si_code=CLD_TRAPPED, si_pid=2867204, si_uid=1000, si_status=SIGTRAP, si_utime=0, si_stime=0} ---wait4(-1, [{WIFSTOPPED(s) && WSTOPSIG(s) == SIGTRAP | 0x80}], __WALL, NULL) = 2867204wait4(-1, 0x7fff31d5821c, WNOHANG|__WALL, NULL) = 0ptrace(PTRACE_SYSCALL, 2867204, NULL, 0) = 0--- SIGCHLD {si_signo=SIGCHLD, si_code=CLD_TRAPPED, si_pid=2867204, si_uid=1000, si_status=SIGTRAP, si_utime=0, si_stime=0} ---wait4(-1, [{WIFSTOPPED(s) && WSTOPSIG(s) == SIGTRAP | 0x80}], __WALL, NULL) = 2867204wait4(-1, 0x7fff31d5821c, WNOHANG|__WALL, NULL) = 0ptrace(PTRACE_GET_SYSCALL_INFO, 2867204, 88, {op=PTRACE_SYSCALL_INFO_ENTRY, arch=AUDIT_ARCH_X86_64, instruction_pointer=0x78d508aa9e69, stack_pointer=0x7ffce96cb7e0, entry={nr=__NR_getrandom, args=[0x78d508c0b178, 0x8, 0x1, 0, 0x64, 0]}}) = 80ptrace(PTRACE_SYSCALL, 2867204, NULL, 0) = 0--- SIGCHLD {si_signo=SIGCHLD, si_code=CLD_TRAPPED, si_pid=2867204, si_uid=1000, si_status=SIGTRAP, si_utime=0, si_stime=0} ---wait4(-1, [{WIFSTOPPED(s) && WSTOPSIG(s) == SIGTRAP | 0x80}], __WALL, NULL) = 2867204wait4(-1, 0x7fff31d5821c, WNOHANG|__WALL, NULL) = 0ptrace(PTRACE_SYSCALL, 2867204, NULL, 0) = 0--- SIGCHLD {si_signo=SIGCHLD, si_code=CLD_TRAPPED, si_pid=2867204, si_uid=1000, si_status=SIGTRAP, si_utime=0, si_stime=0} ---wait4(-1, [{WIFSTOPPED(s) && WSTOPSIG(s) == SIGTRAP | 0x80}], __WALL, NULL) = 2867204wait4(-1, 0x7fff31d5821c, WNOHANG|__WALL, NULL) = 0ptrace(PTRACE_GET_SYSCALL_INFO, 2867204, 88, {op=PTRACE_SYSCALL_INFO_ENTRY, arch=AUDIT_ARCH_X86_64, instruction_pointer=0x78d508b1da0b, stack_pointer=0x7ffce96cb718, entry={nr=__NR_brk, args=[0, 0x78d508c04b20, 0x78d508c04b20, 0x1, 0x21000, 0]}}) = 80ptrace(PTRACE_SYSCALL, 2867204, NULL, 0) = 0--- SIGCHLD {si_signo=SIGCHLD, si_code=CLD_TRAPPED, si_pid=2867204, si_uid=1000, si_status=SIGTRAP, si_utime=0, si_stime=0} ---wait4(-1, [{WIFSTOPPED(s) && WSTOPSIG(s) == SIGTRAP | 0x80}], __WALL, NULL) = 2867204wait4(-1, 0x7fff31d5821c, WNOHANG|__WALL, NULL) = 0ptrace(PTRACE_SYSCALL, 2867204, NULL, 0) = 0--- SIGCHLD {si_signo=SIGCHLD, si_code=CLD_TRAPPED, si_pid=2867204, si_uid=1000, si_status=SIGTRAP, si_utime=0, si_stime=0} ---wait4(-1, [{WIFSTOPPED(s) && WSTOPSIG(s) == SIGTRAP | 0x80}], __WALL, NULL) = 2867204wait4(-1, 0x7fff31d5821c, WNOHANG|__WALL, NULL) = 0ptrace(PTRACE_GET_SYSCALL_INFO, 2867204, 88, {op=PTRACE_SYSCALL_INFO_ENTRY, arch=AUDIT_ARCH_X86_64, instruction_pointer=0x78d508b1da0b, stack_pointer=0x7ffce96cb718, entry={nr=__NR_brk, args=[0x5b3db8db0000, 0x78d508c04b20, 0x78d508c0bd70, 0x1, 0x21000, 0]}}) = 80ptrace(PTRACE_SYSCALL, 2867204, NULL, 0) = 0--- SIGCHLD {si_signo=SIGCHLD, si_code=CLD_TRAPPED, si_pid=2867204, si_uid=1000, si_status=SIGTRAP, si_utime=0, si_stime=0} ---wait4(-1, [{WIFSTOPPED(s) && WSTOPSIG(s) == SIGTRAP | 0x80}], __WALL, NULL) = 2867204wait4(-1, 0x7fff31d5821c, WNOHANG|__WALL, NULL) = 0ptrace(PTRACE_SYSCALL, 2867204, NULL, 0) = 0wait4(-1, [{WIFSTOPPED(s) && WSTOPSIG(s) == SIGTRAP | 0x80}], __WALL, NULL) = 2867204--- SIGCHLD {si_signo=SIGCHLD, si_code=CLD_TRAPPED, si_pid=2867204, si_uid=1000, si_status=SIGTRAP, si_utime=0, si_stime=0} ---wait4(-1, 0x7fff31d5821c, WNOHANG|__WALL, NULL) = 0ptrace(PTRACE_GET_SYSCALL_INFO, 2867204, 88, {op=PTRACE_SYSCALL_INFO_ENTRY, arch=AUDIT_ARCH_X86_64, instruction_pointer=0x78d508b1c804, stack_pointer=0x7ffce96cbb68, entry={nr=__NR_write, args=[0x1, 0x5b3db8d8f2a0, 0x5d, 0x7ffce96cbc0f, 0x7ffce96cbc80, 0]}}) = 80process_vm_readv(2867204, [{iov_base="\0\0\0\0\0\0\0\0\221\2\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0"..., iov_len=4096}], 1, [{iov_base=0x5b3db8d8f000, iov_len=4096}], 1, 0) = 4096write(2, "write(1, \"first_window=20 rest_w"..., 50) = 50ptrace(PTRACE_SYSCALL, 2867204, NULL, 0) = 0--- SIGCHLD {si_signo=SIGCHLD, si_code=CLD_TRAPPED, si_pid=2867204, si_uid=1000, si_status=SIGTRAP, si_utime=0, si_stime=0} ---wait4(-1, [{WIFSTOPPED(s) && WSTOPSIG(s) == SIGTRAP | 0x80}], __WALL, NULL) = 2867204wait4(-1, 0x7fff31d5821c, WNOHANG|__WALL, NULL) = 0ptrace(PTRACE_GET_SYSCALL_INFO, 2867204, 88, {op=PTRACE_SYSCALL_INFO_EXIT, arch=AUDIT_ARCH_X86_64, instruction_pointer=0x78d508b1c804, stack_pointer=0x7ffce96cbb68, exit={rval=93, is_error=0}}) = 33write(2, ") = 93\n", 7) = 7ptrace(PTRACE_SYSCALL, 2867204, NULL, 0) = 0--- SIGCHLD {si_signo=SIGCHLD, si_code=CLD_TRAPPED, si_pid=2867204, si_uid=1000, si_status=SIGTRAP, si_utime=0, si_stime=0} ---wait4(-1, [{WIFSTOPPED(s) && WSTOPSIG(s) == SIGTRAP | 0x80}], __WALL, NULL) = 2867204wait4(-1, 0x7fff31d5821c, WNOHANG|__WALL, NULL) = 0ptrace(PTRACE_GET_SYSCALL_INFO, 2867204, 88, {op=PTRACE_SYSCALL_INFO_ENTRY, arch=AUDIT_ARCH_X86_64, instruction_pointer=0x78d508aee2dd, stack_pointer=0x7ffce96cbcd8, entry={nr=__NR_exit_group, args=[0, 0xffffffffffffff88, 0xe7, 0x7ffce96cbc0f, 0x7ffce96cbc80, 0]}}) = 80ptrace(PTRACE_SYSCALL, 2867204, NULL, 0) = 0--- SIGCHLD {si_signo=SIGCHLD, si_code=CLD_TRAPPED, si_pid=2867204, si_uid=1000, si_status=SIGTRAP, si_utime=0, si_stime=0} ---wait4(-1, [{WIFSTOPPED(s) && WSTOPSIG(s) == SIGTRAP}|PTRACE_EVENT_EXIT<<16], __WALL, NULL) = 2867204wait4(-1, 0x7fff31d5821c, WNOHANG|__WALL, NULL) = 0ptrace(PTRACE_SYSCALL, 2867204, NULL, 0) = 0wait4(-1, [{WIFEXITED(s) && WEXITSTATUS(s) == 0}], __WALL, NULL) = 2867204--- SIGCHLD {si_signo=SIGCHLD, si_code=CLD_EXITED, si_pid=2867204, si_uid=1000, si_status=0, si_utime=0, si_stime=0} ---wait4(-1, 0x7fff31d5821c, WNOHANG|__WALL, NULL) = -1 ECHILD (No child processes)write(2, "+++ exited with 0 +++\n", 22) = 22wait4(-1, 0x7fff31d5821c, __WALL, NULL) = -1 ECHILD (No child processes)exit_group(0) = ?+++ exited with 0 +++Why write_all() and read_full() Anchor Every Storage Protocol
Look at strace_m02_l02: when pfd[1] held only 7 bytes, read(pfd[0], prx, 20) legally returned 7 (pipe_short=7) rather than blocking for 20 bytes! Without a retry loop advancing p + total and count - total, the caller would lose 13 bytes of the header. On /tmp/ksa_m02_io.bin, read_full() reassembled all 64 bytes—including eight embedded 0x00 bytes that would have truncated strcpy()—and confirmed read() == 0 at EOF.
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_full(fd, payload, len, NULL);:
- Step 1 (Spot the partial-header hazard): Trace what happens on a slow serial link or pipe when
read(fd, &len, 4)returns2(> 0): how many bytes ofuint32_t lenremain uninitialized stack garbage, and where do the remaining2header bytes land duringread_full(fd, payload, ...)? - Step 2 (Fix the exact-count check): Replace the raw
read()withssize_t hdr_n = read_full(fd, &len, sizeof(len), NULL);and write the three-way check distinguishinghdr_n == 0(clean stream end between frames),0 < hdr_n < 4(truncated frameEPROTO), andhdr_n == -1(syscall error).
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 1 MiB (1,048,576-byte) /tmp/ksa_sweep.bin file using write_all() and read_full() across chunk sizes 16 B, 512 B, 4,096 B (4 KiB), and 65,536 B (64 KiB). Time each pass with CLOCK_MONOTONIC, compute throughput in MiB/s and syscall count (1,048,576 / chunk), and verify memcmp() equality before unlinking the file.
Common Production Pitfalls
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).
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.
Knowledge Check
? check 1 · (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?
- [ ]
nbecomes0, terminating the loop cleanly at EOF - [x]
-1wraps to unsignedSIZE_MAX(from our earlier lesson onsize_tvsssize_t), bypassing< 0error checks and advancingbuf + totalwildly out of bounds - [ ]
-std=c11promotessize_tto signedssize_tautomatically
Answer: -1 wraps to unsigned SIZE_MAX (from our earlier lesson on size_t vs ssize_t), bypassing < 0 error checks and advancing buf + total wildly out of bounds
Why: 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.
? check 2 · When read(fd, buf, 4096) returns 0 on a regular file or open pipe, what state did the caller encounter?
- [x] Clean EOF: the regular-file offset sits at or past end-of-file (or all write descriptors on the pipe have closed)
- [ ] A non-blocking
EAGAINcondition requiring an immediate retry - [ ] A signal interruption equivalent to
EINTR
Answer: Clean EOF: the regular-file offset sits at or past end-of-file (or all write descriptors on the pipe have closed)
Why: 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.
? check 3 · 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)?
- [ ] Unclosed descriptors survive
exit_group()until the host reboots - [x] Omitting
close(fd)exhaustsRLIMIT_NOFILE(EMFILE) at runtime, and ignoringclose(fd) == -1silently drops deferred writebackEIOerrors - [ ]
read()blocks on all descriptors whenever an older descriptor stays open
Answer: Omitting close(fd) exhausts RLIMIT_NOFILE (EMFILE) at runtime, and ignoring close(fd) == -1 silently drops deferred writeback EIO errors
Why: 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.
? check 4 · 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?
- [ ]
3221225472(3 GiB), because local regular disk files never return short counts - [x] At most
2147479552(0x7ffff000=MAX_RW_COUNT), because the Linux kernel VFS caps every singleread()orwrite()transfer one4 KiBpage below2 GiB - [ ]
-1witherrno == EFBIGwhenevercountexceeds4096bytes
Answer: At most 2147479552 (0x7ffff000 = MAX_RW_COUNT), because the Linux kernel VFS caps every single read() or write() transfer one 4 KiB page below 2 GiB
Why: 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.
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.
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.
Step sequence — frame strip: steps_m02_l02
Cast void * to uint8_t * so byte-exact pointer advancement (p + done) obeys strict ISO C11.
reveals: step1
highlights: step1
Capture returns in signed ssize_t; retry unchanged (p + done, count - done) only when n < 0 && errno == EINTR.
reveals: step2
highlights: step2
Break cleanly on n == 0 (EOF) and advance done += (size_t)n across pipe bursts or 0x7ffff000 MAX_RW_COUNT caps.
reveals: step3
highlights: step3
Inspect close(fd) == -1 once to log deferred EIO, and never retry close(fd) after slot deallocation.
reveals: step4
highlights: step4
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.
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-access binary records. First, a developer opens a scratch file with O_RDWR | O_CREAT | O_TRUNC, writes a 512-byte calibration table, immediately calls read_full(fd, verify_buf, 512) to verify it, and gets 0 bytes (EOF)—because a single descriptor maintains one shared kernel offset (f_pos), now parked at byte 512! Second, a slice-extraction CLI opens dst_path with O_WRONLY | O_CREAT | O_TRUNC at line 1 of copy_slice() and then checks lseek(src_fd, 0, SEEK_END): when a user accidentally pipes stdin (ESPIPE) or requests an out-of-range offset, the tool aborts with an error message after wiping the existing destination file to 0 bytes!
Random-access I/O requires three engineering habits: explicit cursor positioning via 64-bit lseek(), overflow-safe signed off_t arithmetic, and strict precondition validation on source descriptors before mutating or truncating any destination pathname.
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.
definition (Shared File Offset (f_pos), lseek() & Extent Seeks): 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.
One Layer Down: f_pos_lock, Signed off_t Algebra & Five Canonical Patterns
Inside fs/read_write.c (ksys_lseek), the Linux kernel acquires file->f_pos_lock (a per-struct file mutex serializing concurrent lseek/read/write updates on shared handles), dispatches file->f_op->llseek, validates that the computed target coordinate is non-negative (>= 0, returning -EINVAL otherwise) and does not exceed sb->s_maxbytes (-EINVAL / -EOVERFLOW), writes file->f_pos, and returns the new off_t position—performing zero block I/O. Pipes, FIFOs, and sockets lack a seekable .llseek handler (noop_llseek / no_llseek) and reject lseek() immediately with -ESPIPE.
Because off_t is signed ([-2^63, 2^63 - 1] under _FILE_OFFSET_BITS=64 so negative SEEK_CUR deltas and (off_t)-1 error sentinels work), adding an untrusted positive length to offset directly (offset + length > file_size) risks signed 64-bit overflow Undefined Behavior! Always rearrange slice-bound validation as subtraction after checking non-negativity: 0 <= offset && offset <= file_size && length <= (size_t)(file_size - offset). That single subtraction formula is 100% immune to signed overflow across the entire 64-bit off_t range.
Pattern / whence Mode | Syscall Idiom | Kernel Offset / Return Contract | ||
|---|---|---|---|---|
SEEK_SET / SEEK_CUR / SEEK_END | lseek(fd, off, whence) | Sets 0 + off, f_pos + off (0 queries cursor), or i_size + off | ||
SEEK_DATA / SEEK_HOLE | lseek(fd, off, SEEK_DATA) | Returns next allocated byte >= off or hole >= off (ENXIO past EOF) | ||
| 1. Existing-file probe | `open(p, O_RDONLY \ | O_CLOEXEC)` | Verifies p exists (ENOENT if absent) with zero mutation | |
| 2 & 3. Clean vs exclusive create | O_CREAT vs `O_CREAT \ | O_EXCL` | O_EXCL fails atomically with EEXIST if p already exists | |
| 4. Destructive replace | `O_WRONLY \ | O_CREAT \ | O_TRUNC` | Resets i_size = 0 on open so stale trailing bytes never survive |
5. Side-effect-safe slice [N, N+L) | SEEK_END check -> SEEK_SET(N) -> open(dst) | Validates seekability (ESPIPE) & bounds before touching dst |
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.
- Step 1. Probe source size with lseek(sfd, 0, SEEK_END) first so pipes/sockets fail fast with ESPIPE before touching dst.
- Step 2. Validate 0 <= off <= src_sz && len <= (size_t)(src_sz - off) via subtraction to avoid signed off_t overflow UB.
- Step 3. Seek sfd to req_off via SEEK_SET and read_full() the window, advancing shared f_pos cleanly.
- Step 4. Open dst with O_WRONLY | O_CREAT | O_TRUNC | O_CLOEXEC and commit the verified slice via write_all().
Figure 2.3b. Validate source seekability and subtraction bounds via lseek() before opening any destination pathname with O_CREAT | O_TRUNC.
64-Bit lseek(2) Reference & Cross-Architecture ILP32 Rules
Always define #define _FILE_OFFSET_BITS 64 (plus #define _GNU_SOURCE when calling SEEK_DATA / SEEK_HOLE) above <sys/types.h>, <fcntl.h>, and <unistd.h>. On 64-bit x86-64 (LP64), off_t is natively 64-bit, whereas on 32-bit ARMv7 (ILP32), omitting _FILE_OFFSET_BITS 64 leaves off_t as a 32-bit signed long (2 GiB - 1 limit, failing with EOVERFLOW on larger images) and routes to legacy lseek instead of _llseek.
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. EOVERFLOW Resulting file offset cannot be represented in off_t. ESPIPE fd refers to a pipe, FIFO, or socket (non-seekable stream). NOTES lseek(fd, 0, SEEK_CUR) queries the active offset without moving f_pos. SEE ALSO dup(2), ftruncate(2), open(2), pread(2), read(2), write(2) Kernel Systems Academy Lesson 2.3 lseek(2) GL-C01 quick reference · full manual page: man 2 lseek Implementing All Five Canonical Patterns & Extent Seeks in C11
Save offset_patterns.c below. It verifies UB-free safe_add_off() overflow guards, executes all five canonical patterns (ENOENT probe, O_CREAT | O_EXCL 2,048-byte creation + EEXIST guard, SEEK_END + SEEK_DATA/SEEK_HOLE extent probes + negative EINVAL check, pre-validated [500..1524) slice extraction into an O_TRUNC target), and confirms ESPIPE when STDIN_FILENO is a pipe!
learner@ksa:~/gl-c01/m02-l03$ bat -H 14 -H 91 -H 106 offset_patterns.c File: offset_patterns.c #define _GNU_SOURCE #define _FILE_OFFSET_BITS 64 #include <errno.h> #include <fcntl.h> #include <stdint.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <sys/stat.h> #include <sys/types.h> #include <unistd.h> static int safe_add_off(off_t cur, off_t delta, off_t *out) { if (delta > 0 && cur > (off_t)INT64_MAX - delta) { return -1; } if (delta < 0 && cur < 0 - delta) { return -1; } *out = cur + delta; return 0; } static int write_all(int fd, const void *buf, size_t count) { const uint8_t *p = (const uint8_t *)buf; size_t left = count; while (left > 0U) { ssize_t n = write(fd, p, left); if (n < 0) { if (errno == EINTR) continue; return -1; } p += (size_t)n; left -= (size_t)n; } return 0; } static ssize_t read_full(int fd, void *buf, size_t count) { uint8_t *p = (uint8_t *)buf; size_t total = 0U; while (total < count) { ssize_t n = read(fd, p + total, count - total); if (n == 0) break; if (n < 0) { if (errno == EINTR) continue; return -1; } total += (size_t)n; } return (ssize_t)total; } int main(void) { const char *src = "/tmp/ksa_pat_src.bin"; const char *dst = "/tmp/ksa_pat_dst.bin"; (void)unlink(src); (void)unlink(dst); off_t guarded = 0; int ovf_caught = (safe_add_off((off_t)INT64_MAX - 10, 32, &guarded) == -1); errno = 0; int missing_fd = open(src, O_RDONLY | O_CLOEXEC); int p1_enoent = (missing_fd == -1 && errno == ENOENT); int sfd = open(src, O_RDWR | O_CREAT | O_EXCL | O_CLOEXEC, S_IRWXU | S_IRGRP | S_IROTH); if (sfd == -1) return EXIT_FAILURE; uint8_t zeros[1024], ones[1024]; memset(zeros, 0x00U, sizeof(zeros)); memset(ones, 0xFFU, sizeof(ones)); if (write_all(sfd, zeros, sizeof(zeros)) == -1 || write_all(sfd, ones, sizeof(ones)) == -1) { return EXIT_FAILURE; } errno = 0; int dup_fd = open(src, O_WRONLY | O_CREAT | O_EXCL | O_CLOEXEC, 0644); int p3_eexist = (dup_fd == -1 && errno == EEXIST); off_t src_sz = lseek(sfd, 0, SEEK_END); off_t d0 = lseek(sfd, 0, SEEK_DATA); off_t h0 = lseek(sfd, 0, SEEK_HOLE); int extent_ok = (d0 == 0 && h0 == src_sz); errno = 0; off_t neg_rc = lseek(sfd, -5000, SEEK_END); int neg_einval = (neg_rc == (off_t)-1 && errno == EINVAL); off_t req_off = 500; size_t req_len = 1024U; if (src_sz < 0 || req_off > src_sz || req_len > (size_t)(src_sz - req_off) || lseek(sfd, req_off, SEEK_SET) == (off_t)-1) { return EXIT_FAILURE; } uint8_t slice[1024]; ssize_t got = read_full(sfd, slice, req_len); off_t cur_after = lseek(sfd, 0, SEEK_CUR); int dfd = open(dst, O_WRONLY | O_CREAT | O_TRUNC | O_CLOEXEC, S_IRWXU | S_IRGRP | S_IROTH); if (dfd == -1 || write_all(dfd, slice, (size_t)got) == -1) { return EXIT_FAILURE; } off_t dst_sz = lseek(dfd, 0, SEEK_END); errno = 0; off_t pipe_rc = lseek(STDIN_FILENO, 0, SEEK_CUR); int pipe_espipe = (pipe_rc == (off_t)-1 && errno == ESPIPE); (void)close(dfd); (void)close(sfd); (void)unlink(src); (void)unlink(dst); printf("p1_enoent=%d p3_eexist=%d src_size=%lld dst_size=%lld\n", p1_enoent, p3_eexist, (long long)src_sz, (long long)dst_sz); printf("cur_after=%lld boundary=0x%02x,0x%02x ovf=%d ext=%d err=%d,%d\n", (long long)cur_after, slice[523], slice[524], ovf_caught, extent_ok, neg_einval, pipe_espipe); return EXIT_SUCCESS; }- Test cur > INT64_MAX - delta before addition so untrusted 64-bit offsets never trigger signed overflow UB.
- SEEK_DATA and SEEK_HOLE query filesystem extent metadata directly without reading data blocks into RAM.
- Validate src_sz and slice bounds on sfd BEFORE opening dst with O_CREAT | O_TRUNC so errors leave dst untouched.
Tracing lseek Calls and Completing Lab 2
Check the exact boundary indices before executing: starting at byte 500, [500..1023] spans 524 zero bytes (slice[0..523] == 0x00), while slice[524] corresponds to file offset 1024 (0xff), advancing f_pos to 1524. Pipe input into STDIN_FILENO to trigger ESPIPE, count all 8 lseek calls under strace, and complete lab_m02_framed_copy.
learner@ksa:~/gl-c01/m02-l03gcc -fdiagnostics-color=always -std=c11 -Wall -Wextra -Werror offset_patterns.c -o offset_patternslearner@ksa:~/gl-c01/m02-l03printf 'stream' | ./offset_patternsp1_enoent=1 p3_eexist=1 src_size=2048 dst_size=1024cur_after=1524 boundary=0x00,0xff ovf=1 ext=1 err=1,1learner@ksa:~/gl-c01/m02-l03printf 'stream' | strace -e trace=lseek ./offset_patterns 2>&1 | grep -c 'SEEK_'8learner@ksa:~/gl-c01/m02-l03rm -f offset_patternslearner@ksa:~/gl-c01/m02-l031. Motivation
File-extraction and firmware-slicing utilities fail dangerously in the field when they open output files with O_CREAT | O_TRUNC before checking whether the input descriptor is seekable or holds enough bytes—wiping an existing configuration or firmware backup to 0 bytes whenever a user accidentally passes a pipe (ESPIPE) or an out-of-range offset! Compounding that bug, single-shot read()/write() calls drop bytes on partial transfers, strlen() truncates binary slices at 0x00, and decimal 644 scrambles inode permissions. Here you will build framed_copy, a side-effect-safe, binary-exact POSIX slice extractor.
2. Learning Objectives
- Implement
EINTR- and short-count-resilientwrite_all()andread_full()loops overuint8_tbuffers using signedssize_treturn checks. - Validate input seekability (
ESPIPE) and 64-bitoff_tslice bounds (offset <= src_sizeandlength <= src_size - offset) vialseek(src_fd, 0, SEEK_END)before opening or truncatingdst_path. - Enforce
O_CLOEXEC,O_TRUNC, octal0644(S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH) permissions, and checkedclose()error propagation (EIO).
3. Environment Requirements
- Host Execution Environment (Tested): Linux
6.12LTS (x86_64,glibc2.39+),#define _FILE_OFFSET_BITS 64and#define _POSIX_C_SOURCE 200809L. - Target Board Portability (
ARMv7Cortex-A7): Defining_FILE_OFFSET_BITS 64before all headers widensoff_tfrom 32-bitlong(2 GiB - 1ceiling onILP32ARMv7) to signed 64-bit, enabling identical multi-gigabyte partition slicing on 32-bit embedded targets.
4. Required Software & Hardware
- Software Toolchain:
gcc(-std=c11 -Wall -Wextra -Werror),strace,cmp/sha256sum,stat, and/bin/sh. - Hardware: Standard Linux host environment (
0root privileges required).
5. Complete Executable Commands
Run from labs/lab_m02_framed_copy/:
learner@ksa:~/gl-c01/m02-l03$ bat script.sh File: script.sh # 1. Compile the reference implementation with strict C11 and 64-bit off_t flags gcc -std=c11 -O2 -Wall -Wextra -Werror files/framed_copy.c -o /tmp/framed_copy # 2. Seed an 8 KiB binary file containing embedded 0x00 and 0xFF bytes dd if=/dev/urandom of=/tmp/ksa_src.bin bs=1024 count=8 status=none # 3. Extract exact 2048-byte window [500, 2548) and verify byte-for-byte identity /tmp/framed_copy /tmp/ksa_src.bin /tmp/ksa_dst.bin 500 2048 dd if=/tmp/ksa_src.bin bs=1 skip=500 count=2048 status=none | cmp -s - /tmp/ksa_dst.bin && echo "MATCH_OK" # 4. Verify side-effect safety: piped stdin fails with ESPIPE WITHOUT touching /tmp/ksa_dst.bin! printf 'pipe_bytes' | /tmp/framed_copy /dev/stdin /tmp/ksa_dst.bin 0 4 || stat -c 'preserved_bytes=%s mode=%a' /tmp/ksa_dst.bin # 5. Clean up scratch files and run the full TAP 13 test suite rm -f /tmp/framed_copy /tmp/ksa_src.bin /tmp/ksa_dst.bin sh check.sh*Why each command runs:* dd generates arbitrary binary bytes (including 0x00); cmp -s proves byte-exact extraction at offset 500; piping /dev/stdin triggers ESPIPE on lseek() to verify /tmp/ksa_dst.bin keeps preserved_bytes=2048 and mode=644; and sh check.sh runs all automated checks.
6. Annotated Source Code (starter/ Flaws vs files/ Reference)
Flawed Baseline (starter/framed_copy.c)
- Destructive eager
open(): Opensdst_fdon line 20 before checking whethersrc_fdis seekable or long enough. - Decimal
644& missingO_TRUNC/O_CLOEXEC:open(argv[2], O_WRONLY | O_CREAT, 644)stamps sticky octal01204(--w----r-T) and leaves stale trailing bytes intact when overwriting larger files! - Unchecked
atol()&strlen(buf):atol()invokes UB on overflow, fixedchar buf[8192]overflows whenlength > 8192, andwrite(dst_fd, buf, strlen(buf))truncates at the first0x00byte.
Warning-Clean Reference (files/framed_copy.c)
- CLI Parsing (
main): Parses<offset>withstrtoll(errno == 0,*end == '\0',raw_off >= 0) and<length>withstrtoull(<= SIZE_MAX). - Precondition Ordering (
copy_slice): Openssrc_fd(O_RDONLY | O_CLOEXEC), queriessrc_size = lseek(src_fd, 0, SEEK_END)(aborting immediately onESPIPE!), validates subtraction boundsoffset <= src_size && (uintmax_t)(src_size - offset) >= (uintmax_t)length(zero signed-overflow risk), seekssrc_fdtooffset, and only then opensdst_fd(O_WRONLY | O_CREAT | O_TRUNC | O_CLOEXEC,0644). - Streaming Loop & Checked
close(): Streams4,096-byte chunks throughread_full()andwrite_all(), preserveserrnoacross error-pathclose()calls, and verifiesclose(dst_fd) == 0so deferred writebackEIOfaults are never masked.
7. Expected Output
learner@ksa:~/gl-c01/m02-l03$ bat listing.txt File: listing.txt $ sh check.sh TAP version 13 1..6 ok 1 - compiles cleanly with -std=c11 -Wall -Wextra -Werror ok 2 - copies binary slice with embedded 0x00 bytes and sets octal 0644 mode ok 3 - truncates pre-existing larger destination file via O_TRUNC ok 4 - rejects out-of-bounds slice without creating or modifying dst_path ok 5 - rejects non-seekable pipe input (ESPIPE) without touching dst_path ok 6 - handles 0-byte slice cleanly # pass 6/68. Explanation of Observed Behavior
When copy_slice() runs against a 64 KiB binary file for [4096, 36864) (32 KiB), lseek(src_fd, 0, SEEK_END) reads inode->i_size in kernel RAM (0 disk I/O), lseek(src_fd, 4096, SEEK_SET) positions src_fd's struct file.f_pos to 4096, open(dst_path, ... | O_TRUNC, 0644) resets any prior destination extents and masks 0644 & ~umask, and eight 4 KiB iterations transfer all 32,768 bytes without ever scanning for '\0'. When /dev/stdin is a pipe, lseek(src_fd, 0, SEEK_END) returns (off_t)-1 with errno == ESPIPE at line 62—returning -1 before line 83 ever touches dst_path.
9. Experiment Variations
- Chunk-Size Syscall Trade-Off: Change
uint8_t chunk[4096]tochunk[64]vschunk[65536]on a1 MiBslice and comparestrace -c -e trace=read,writesyscall counts (16,384calls vs256calls vs16calls). umaskSensitivity Test: Run(umask 0077 && ./framed_copy src.bin dst.bin 0 64 && stat -c '%a' dst.bin)to confirm the kernel computes0644 & ~0077 = 0600(rw-------).- Zero-Length Boundary: Run
./framed_copy src.bin empty.bin 2048 0at exactEOF(offset == src_size,length == 0) to confirm a valid0-byte file is created cleanly (copied=0).
10. Performance Measurements
Measured on Host x86_64 Linux 6.12 LTS (CLOCK_MONOTONIC, 5 warmup runs, N = 35 timed extractions of a 32 KiB slice from a 64 KiB file):
| Metric | Measured Host (x86_64 Linux 6.12) | Target Board Expectation (ARMv7 Cortex-A7 eMMC) |
|---|---|---|
32 KiB slice CLI latency (p50 / p95 / p99) | 2,950.3 us / 3,299.9 us / 3,608.9 us | ~11,000–18,000 us (page-cache warm; higher on cold eMMC read) |
Kernel lseek + read + write calls (32 KiB) | 2 + 8 + 8 (18 data-path syscalls) | 2 + 8 + 8 (_llseek on 32-bit ARMv7) |
11. Troubleshooting
| Symptom | Root Cause | Fix | |||
|---|---|---|---|---|---|
Destination file shrinks to 0 bytes when offset is invalid | `open(dst_path, ... \ | O_TRUNC) executed before lseek(src_fd, 0, SEEK_END)` bounds check | Validate src_size and bounds before opening dst_path | ||
| Output file has trailing stale bytes from an earlier run | O_TRUNC omitted on open(dst_path, ...) | Include `O_WRONLY \ | O_CREAT \ | O_TRUNC \ | O_CLOEXEC` |
offset + length wraps negative on huge values | Signed off_t overflow Undefined Behavior | Check offset <= src_size first, then (uintmax_t)(src_size - offset) < length | |||
Permissions show --w----r-T (1204) | Passed decimal 644 instead of octal 0644 | Use 0644 or `S_IRUSR \ | S_IWUSR \ | S_IRGRP \ | S_IROTH` |
12. Guided Questions
- Why does
copy_slice()treatgot < (ssize_t)wantfromread_full()as an error (EIO) even though we already verifiedoffset + length <= src_size?
- *Hint 1:* Can another process concurrently call
ftruncate()onsrc_pathbetween yourSEEK_ENDcheck and yourread_full()loop? - *Hint 2:* What does
read_full()return ifsrc_pathshrinks mid-copy and hits prematureEOF(0)?
- Why do we save
int saved = errno;before callingclose(src_fd)on error branches?
- *Hint 1:* Check
m03-l02's rules on whetherclose()can modifyerrnoor leave callers guessing ifclose()itself hits an internal check. - *Hint 2:* Trace what
perror("copy_slice")inmain()prints iferrnowas overwritten during cleanup!
13. Independent Challenges
- Near Transfer — Atomic Staging Slice Extractor: Upgrade
copy_slice()so that instead of truncatingdst_pathin place (which leaves a partialdst_pathifSIGKILLhits mid-copy), it writes into<dst_path>.tmp.<pid>opened withO_CREAT | O_EXCL | O_CLOEXECand atomicallyrename()s ontodst_pathonly afterclose()succeeds! - Far Transfer — Zero-Copy Kernel
copy_file_range(2)Fastpath: On Linux4.5+(#define _GNU_SOURCE), replace the user-spaceread_full/write_all4 KiBbounce buffer withcopy_file_range(src_fd, &in_off, dst_fd, NULL, left, 0)(falling back toread_full/write_allonEXDEVcross-filesystem copies) and benchmark64 MiBthroughput (MiB/s) withCLOCK_MONOTONIC.
14. Solutions & Explanations
- Guided Question 1: Because Unix filesystems allow concurrent processes to truncate an open file without mandatory locking,
read_full()returning< wantdetects concurrent truncation (EIO) instead of silently writing fewer bytes thancopied=<length>promised. - Guided Question 2: Saving
errnobeforeclose()guaranteesperror("copy_slice")reports the exact root cause (ESPIPE,EINVAL,ENOSPC) rather than any side effect of cleanup. - Challenge 2 Key Idiom:
ssize_t n = copy_file_range(src_fd, NULL, dst_fd, NULL, left, 0);copies page-cache folios (or issues filesystem CoWreflinkclones onBtrfs/XFS) entirely insideRing 0with zero user-spacememcpy()traffic!
Run locally in your terminal and check off each verification milestone.
Not started
Zero-Disk f_pos Updates Bridge to Kernel Open-File Tables
Every lseek() in offset_patterns updated file->f_pos in kernel RAM with zero block transfers, extracting [500..1524) cleanly while rejecting negative offsets (EINVAL) and unseekable pipes (ESPIPE). That naturally raises the architectural focus of Module 3: where inside the Linux kernel does f_pos reside relative to on-disk inodes and directory entries, and how can user space inspect live f_pos and f_flags state via /proc/self/fdinfo/?
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 0 of an open seekable descriptor and restores fd's original f_pos before returning:
- Step 1 (Snapshot active
f_pos): Calloff_t saved = lseek(fd, 0, SEEK_CUR);and return-1immediately ifsaved == (off_t)-1(catchingESPIPEon pipes before moving anything). - Step 2 (Rewind, read full 4 bytes, and restore): Seek to
0(SEEK_SET), read4bytes viaread_full(), and calllseek(fd, saved, SEEK_SET)on both the success path and any short-read path so callers never observe a mutated cursor.
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 last occurrence of a 4-byte marker "SYNC" inside an arbitrarily large regular file without reading from byte 0: query off_t end = lseek(fd, 0, SEEK_END), step backward in 4,096-byte windows (overlapping by 3 bytes across window seams so a "SYNC" straddling a 4 KiB boundary is never missed!), and print the exact 64-bit byte offset.
Common Production Pitfalls
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).
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).
Knowledge Check
? check 1 · Which lseek() invocation lets a diagnostic helper retrieve the active byte offset of a seekable descriptor fd without changing its position?
- [ ]
lseek(fd, 0, SEEK_SET)to retrieve byte zero - [x]
lseek(fd, 0, SEEK_CUR)to computecurrent_offset + 0without movingf_pos - [ ]
lseek(fd, 0, SEEK_END)to query total file byte size
Answer: lseek(fd, 0, SEEK_CUR) to compute current_offset + 0 without moving f_pos
Why: 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.
? check 2 · (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)?
- [x] Opening
dst_pathwithO_CREAT | O_TRUNCfirst creates an empty file or destroys an existing destination even whensrc_fdis an unseekable pipe (ESPIPE) or the requested slice exceedssrc_sz - [ ] The Linux kernel forbids
lseek()whenever two regular file descriptors are open simultaneously - [ ]
O_CLOEXECapplies only to the last descriptor opened by a process
Answer: Opening dst_path with O_CREAT | O_TRUNC first creates an empty file or destroys an existing destination even when src_fd is an unseekable pipe (ESPIPE) or the requested slice exceeds src_sz
Why: 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.
? check 3 · 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?
- [ ]
512, becauseO_RDWRmaintains separate read and write cursors in the kernel - [ ]
-1witherrno == ESPIPE, because newly created files are non-seekable - [x]
0(clean EOF), becausewrite_all()advanced the single sharedf_poscursor to512andlseek(fd, 0, SEEK_SET)was not called before reading
Answer: 0 (clean EOF), because write_all() advanced the single shared f_pos cursor to 512 and lseek(fd, 0, SEEK_SET) was not called before reading
Why: 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.
? check 4 · 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?
- [ ] Reading
4,096-byte chunks in aread()loop and testing whether all4,096bytes equal0x00 - [x] Alternating
lseek(fd, cur, SEEK_DATA)andlseek(fd, data_off, SEEK_HOLE)under_GNU_SOURCEand_FILE_OFFSET_BITS=64untilENXIOindicates end-of-file - [ ] Calling
lseek(fd, -1, SEEK_SET)to skip unallocated extents
Answer: Alternating lseek(fd, cur, SEEK_DATA) and lseek(fd, data_off, SEEK_HOLE) under _GNU_SOURCE and _FILE_OFFSET_BITS=64 until ENXIO indicates end-of-file
Why: 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.
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.
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 errno unwinding, and sparse extent holes.
Step sequence — frame strip: steps_m02_l03
Probe source size with lseek(sfd, 0, SEEK_END) first so pipes/sockets fail fast with ESPIPE before touching dst.
reveals: step1
highlights: step1
Validate 0 <= off <= src_sz && len <= (size_t)(src_sz - off) via subtraction to avoid signed off_t overflow UB.
reveals: step2
highlights: step2
Seek sfd to req_off via SEEK_SET and read_full() the window, advancing shared f_pos cleanly.
reveals: step3
highlights: step3
Open dst with O_WRONLY | O_CREAT | O_TRUNC | O_CLOEXEC and commit the verified slice via write_all().
reveals: step4
highlights: step4
m03/
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.
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.
Why rm Can Free Zero Disk Bytes & Inodes Never Store Filenames
Every production systems engineer eventually receives the midnight alert: /var/log is 99% full, an operator deletes a 10 GiB /var/log/telemetry.log file with rm, ls -la /var/log confirms the filename is gone, yet df -h still reports 99% disk usage and ENOSPC continues! Equally puzzling to newcomers, creating a hard link ln a.cfg b.cfg makes mutations through a.cfg appear instantly in b.cfg, and unlinking a.cfg leaves b.cfg intact—even though no bytes were copied.
Mental models that picture a "file" as a named blob attached directly to an integer fd break down completely on both scenarios. Solving storage leaks, cursor sharing, and polymorphic device I/O requires separating static on-disk partition structures from the three-tier dynamic Virtual File System (VFS) hierarchy constructed in kernel RAM whenever open() executes.
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.
definition (Directory Entry (dentry), Inode, Three-Tier VFS & CONTAINER_OF): 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 , while CONTAINER_OF(ptr, type, member) recovers enclosing driver structs from embedded VFS anchors via offsetof subtraction.
Figure 3.1a. Static ext4 disk layout — directory entries map filenames to inode numbers in the Inode Table, which index 4 KiB data blocks.
One Layer Down: Block Geometry, Reclamation Condition & CONTAINER_OF Math
On non-volatile storage, 512-byte hardware sectors are grouped into 4 KiB (4,096-byte) filesystem blocks partitioned across four static regions: boot block, superblock (filesystem geometry, free-inode and free-block bitmaps), inode table, and data blocks (storing both regular file payloads and directory (name, st_ino) records). Because unlink() only deletes one directory entry and decrements inode->i_nlink, the Linux kernel reclaims an inode and its physical 4 KiB extents if and only if both reference counters hit zero simultaneously: reclaim_blocks(inode) <==> (inode->i_nlink == 0) && (sum(file->f_count) == 0). Until the logging daemon closes its open struct file (f_count -> 0), all 10 GiB of unlinked blocks remain allocated!
How does pure ISO C inside the Linux kernel dispatch a single read(fd, buf, len) syscall across ext4 extents, pipefs ring buffers, /proc virtual files, and /dev character drivers with zero heap wrapper overhead? Every struct file carries a const struct file_operations *f_op function-pointer table (.read, .write, .llseek, .unlocked_ioctl). Subsystems embed generic anchor structs intrusively inside domain structs at compile-time byte offset delta = offsetof(type, member), recovering the outer object via byte-pointer subtraction CONTAINER_OF(p, T, m) = (T *)((char *)p - offsetof(T, m)). Paired with indirect-pointer list traversal (struct vfs_hook **pp = &head;), intrusive C containers achieve zero-allocation polymorphism and branchless node unlinking without special-casing prev == NULL.
| Storage / Kernel Tier | Memory / Media Location | Core State Fields | Sharing & Lifetime Scope |
|---|---|---|---|
1. Process FD table (files_struct) | task_struct->files (RAM) | fd integer, FD_CLOEXEC, struct file * | Private per process (clone without CLONE_FILES) |
2. Open file (struct file) | Kernel filp slab cache (RAM) | f_flags, f_pos, f_count, f_op, f_inode | Allocated per open(); shared across dup()/fork() |
3. VFS struct inode + Page Cache | Kernel inode + XArray folios (RAM) | i_ino, i_size, i_nlink, i_rwsem, 4 KiB pages | Single unified instance per active file |
| 4. Static partition structures | NVMe / eMMC 4 KiB blocks | Superblock, inode table, dentry blocks, extents | Persistent across power cycles |
Figure 3.1b. Dynamic Linux kernel VFS pointer chain (task_struct -> fdtable -> struct file -> inode -> address_space), orphan block survival, and CONTAINER_OF recovery.
- Step 1. Each process PCB (task_struct) owns a private files_struct slot array storing FD_CLOEXEC and a struct file pointer.
- Step 2. System-wide struct file tracks open status flags (f_flags), active byte cursor (f_pos), and reference count (f_count).
- Step 3. All open struct file instances for the same file point to one VFS struct inode and one shared 4 KiB RAM page cache.
- Step 4. Physical disk blocks are reclaimed only when both st_nlink == 0 (unlinked) and f_count == 0 (all FDs closed).
Figure 3.1c. 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.
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. Call stat(path, &st) or fstat(fd, &st) to inspect st_ino, st_nlink, st_mode, st_size, and st_blocks; call link(oldpath, newpath) to attach a second directory entry to the same st_ino (st_nlink++); and read /proc/self/fdinfo/<fd> to inspect the live kernel pos: (struct file.f_pos) and octal flags: (including O_CLOEXEC = 02000000 on x86-64/ARM).
Probing Hard Links, Orphaned Open Inodes, CONTAINER_OF & fdinfo
Save vfs_fdinfo_probe.c below. It verifies type-checked CONTAINER_OF(&c2.hook, struct dev_chan, hook) recovery and branchless indirect-pointer list removal (unlink_hook_branchless), links path_b to path_a (st_nlink == 2, identical st_ino), inspects /proc/self/fdinfo/<fd> (pos: 128, O_CLOEXEC set), and then unlinks both filenames while fd remains open—proving fstat(fd, &st_unlinked) reports st_nlink == 0 while all 128 payload bytes remain readable from the live VFS inode until close(fd)!
learner@ksa:~/gl-c01/m03-l01$ bat -H 13 -H 28 -H 74 -H 89 vfs_fdinfo_probe.c File: vfs_fdinfo_probe.c #define _POSIX_C_SOURCE 200809L #include <errno.h> #include <fcntl.h> #include <stddef.h> #include <stdint.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <sys/stat.h> #include <unistd.h> #define CONTAINER_OF(ptr, type, member) \ ((type *)((char *)(1 ? (ptr) : &((type *)0)->member) - \ offsetof(type, member))) struct vfs_hook { struct vfs_hook *next; int tag; }; struct dev_chan { uint32_t id; struct vfs_hook hook; }; static void unlink_hook_branchless(struct vfs_hook **head, const struct vfs_hook *target) { struct vfs_hook **pp = head; while (*pp != NULL && *pp != target) { pp = &(*pp)->next; } if (*pp != NULL) { *pp = target->next; } } int main(void) { struct dev_chan c1 = {101U, {NULL, 1}}; struct dev_chan c2 = {202U, {NULL, 2}}; c1.hook.next = &c2.hook; struct vfs_hook *head = &c1.hook; struct dev_chan *rec = CONTAINER_OF(&c2.hook, struct dev_chan, hook); unlink_hook_branchless(&head, &c1.hook); int intrusive_ok = (rec->id == 202U && head == &c2.hook); const char *path_a = "/tmp/ksa_vfs_a.dat"; const char *path_b = "/tmp/ksa_vfs_b.dat"; (void)unlink(path_a); (void)unlink(path_b); int fd = open(path_a, O_RDWR | O_CREAT | O_TRUNC | O_CLOEXEC, 0644); if (fd == -1) return EXIT_FAILURE; if (link(path_a, path_b) == -1) { (void)close(fd); (void)unlink(path_a); return EXIT_FAILURE; } uint8_t payload[128]; memset(payload, 0x42U, sizeof(payload)); if (write(fd, payload, sizeof(payload)) != (ssize_t)sizeof(payload)) { return EXIT_FAILURE; } struct stat sta, stb, stf, st_orphan; if (stat(path_a, &sta) == -1 || stat(path_b, &stb) == -1 || fstat(fd, &stf) == -1) { return EXIT_FAILURE; } char fdinfo_path[64]; snprintf(fdinfo_path, sizeof(fdinfo_path), "/proc/self/fdinfo/%d", fd); int info_fd = open(fdinfo_path, O_RDONLY | O_CLOEXEC); long long kernel_pos = -1; unsigned long kernel_flags = 0UL; if (info_fd != -1) { char info_buf[512]; ssize_t n = read(info_fd, info_buf, sizeof(info_buf) - 1U); if (n > 0) { info_buf[n] = '\0'; const char *p_pos = strstr(info_buf, "pos:"); const char *p_flg = strstr(info_buf, "flags:"); if (p_pos != NULL) kernel_pos = strtoll(p_pos + 4, NULL, 10); if (p_flg != NULL) kernel_flags = strtoul(p_flg + 6, NULL, 8); } (void)close(info_fd); } (void)unlink(path_a); (void)unlink(path_b); uint8_t check_byte = 0U; int orphan_alive = (fstat(fd, &st_orphan) == 0 && st_orphan.st_nlink == 0U && lseek(fd, 0, SEEK_SET) == 0 && read(fd, &check_byte, 1U) == 1 && check_byte == 0x42U); (void)close(fd); int same_ino = (sta.st_ino == stb.st_ino && sta.st_ino == stf.st_ino && sta.st_ino > 0U); int cloexec_bit = ((kernel_flags & (unsigned long)O_CLOEXEC) != 0UL); printf("same_inode=%d hard_links=%lu st_size=%lld orphan_alive=%d\n", same_ino, (unsigned long)sta.st_nlink, (long long)sta.st_size, orphan_alive); printf("fdinfo_pos=%lld cloexec_in_flags=%d intrusive_ok=%d\n", kernel_pos, cloexec_bit, intrusive_ok); return EXIT_SUCCESS; }- Ternary type-check (1 ? (ptr) : &((type *)0)->member) triggers a compile error if ptr does not match member's exact type.
- Indirect pointer struct vfs_hook **pp updates head or prev->next uniformly without an if (prev == NULL) branch.
- Reading /proc/self/fdinfo/<fd> queries live kernel struct file.f_pos and octal flags directly from procfs.
Verifying Shared st_ino, Orphan Inode Survival & fdinfo
Compile and execute vfs_fdinfo_probe: confirm path_a and path_b share one st_ino (hard_links=2), orphan_alive=1 proves st_nlink == 0 keeps data alive while fd stays open, /proc/self/fdinfo/<fd> reports pos: 128 and O_CLOEXEC, and strace logs the hard-link syscall.
learner@ksa:~/gl-c01/m03-l01gcc -fdiagnostics-color=always -std=c11 -Wall -Wextra -Werror vfs_fdinfo_probe.c -o vfs_fdinfo_probelearner@ksa:~/gl-c01/m03-l01./vfs_fdinfo_probesame_inode=1 hard_links=2 st_size=128 orphan_alive=1fdinfo_pos=128 cloexec_in_flags=1 intrusive_ok=1learner@ksa:~/gl-c01/m03-l01strace -e trace=link,linkat ./vfs_fdinfo_probe 2>&1 | grep -c 'ksa_vfs_b.dat'1learner@ksa:~/gl-c01/m03-l01rm -f vfs_fdinfo_probelearner@ksa:~/gl-c01/m03-l01Why Page-Cache & Reference-Counted Inodes Outlive Directory Names
Notice how orphan_alive=1 demystified the 10 GiB unlinked-log incident in twenty lines of C! Unlinking path_a and path_b dropped st_orphan.st_nlink to 0 and removed both directory entries from /tmp, yet because fd still held struct file.f_count == 1, the VFS struct inode and its 4 KiB page-cache folio stayed alive in RAM (check_byte == 0x42) until close(fd) dropped f_count to 0 and freed the blocks!
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.hook is at virtual address 0x7ffc10004010:
- Step 1 (Calculate
offsetof(struct rx_ring, hook)): Compute the offset ofdrops(0..7),mask(8..11), andhook(which contains a64-bit pointernextrequiring8-byte alignment, inserting4padding bytes[12..15]sooffsetof == 16). - Step 2 (Recover the enclosing address): Subtract
16(0x10) from(char *)0x7ffc10004010(0x7ffc10004000), and verify in a 10-line C test withoffsetof(struct rx_ring, hook)andCONTAINER_OF.
Independent Practice: Live Process Open-File & Orphan Inspector
Write a C11 tool self_fd_audit.c that opens two regular files (unlinking one while keeping its descriptor open), iterates integers fd = 0..15, calls fstat(fd, &st) (errno == EBADF skips unused slots), reads /proc/self/fdinfo/<fd> for every open slot, and prints a formatted table of fd, st_ino, st_nlink (highlighting st_nlink == 0 unlinked open files!), pos, and O_CLOEXEC.
Common Production Pitfalls
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).
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).
Knowledge Check
? check 1 · Where is a regular file's human-readable filename stored inside a POSIX filesystem such as ext4?
- [ ] Inside a fixed 256-byte name array embedded in the file's own on-disk inode
- [x] Inside the data blocks of its parent directory as a directory entry mapping the filename string to an
st_inoinode number - [ ] Exclusively inside
task_struct->filesuntilclose()flushes it to the superblock
Answer: Inside the data blocks of its parent directory as a directory entry mapping the filename string to an st_ino inode number
Why: 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.
? check 2 · (Review from earlier lesson) Which kernel structure stores the active byte offset f_pos returned by lseek(fd, 0, SEEK_CUR)?
- [ ] The per-process
files_structdescriptor slot alongsideFD_CLOEXEC - [x] The system-wide open file description (
struct file), which holdsf_pos,f_flags,f_op, andf_count - [ ] The on-disk partition superblock
Answer: The system-wide open file description (struct file), which holds f_pos, f_flags, f_op, and f_count
Why: 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.
? check 3 · 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?
- [ ] Two separate kernel copies, one inside each process's
task_struct - [x] One shared copy inside the VFS
struct inodepage cache, read through each process's independentstruct filecursor - [ ] Zero copies in RAM, because unbuffered
read()bypasses kernel RAM completely
Answer: One shared copy inside the VFS struct inode page cache, read through each process's independent struct file cursor
Why: 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!
? check 4 · How does the Linux VFS implement zero-overhead polymorphism and generic intrusive list manipulation in ISO C across ext4, pipefs, procfs, and /dev drivers?
- [ ] By wrapping every open file in a heap-allocated
void *box and downcasting blindly - [x] By dispatching through
struct file_operationsfunction-pointer vtables, recovering enclosing structs from embedded members viaoffsetofsubtraction (CONTAINER_OF), and unlinking nodes via indirect pointers (struct vfs_hook **pp) - [ ] By generating separate per-filesystem
read()binaries insideglibc
Answer: By dispatching through struct file_operations function-pointer vtables, recovering enclosing structs from embedded members via offsetof subtraction (CONTAINER_OF), and unlinking nodes via indirect pointers (struct vfs_hook **pp)
Why: 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.
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. /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 why exit() and _exit() diverge on buffered output.
Step sequence — frame strip: steps_m03_l01
Each process PCB (task_struct) owns a private files_struct slot array storing FD_CLOEXEC and a struct file pointer.
reveals: step1
highlights: step1
System-wide struct file tracks open status flags (f_flags), active byte cursor (f_pos), and reference count (f_count).
reveals: step2
highlights: step2
All open struct file instances for the same file point to one VFS struct inode and one shared 4 KiB RAM page cache.
reveals: step3
highlights: step3
Physical disk blocks are reclaimed only when both st_nlink == 0 (unlinked) and f_count == 0 (all FDs closed).
reveals: step4
highlights: step4
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.
Why Intervening Calls Clobber errno & _exit() Drops Output
Two bugs turn routine error-handling code into hours of misdirection. First, a daemon whose stdout is redirected to /var/log/service.log executes if (open("/etc/shadow", O_RDONLY) == -1) { printf("open failed\n"); perror("cause"); }—and logs cause: Inappropriate ioctl for device (ENOTTY) instead of Permission denied (EACCES)! Why? Because on its first write to redirected stdout, printf() calls isatty(1) (ioctl(1, TCGETS, ...)), which fails on a regular file with ENOTTY and overwrites errno before perror() runs! Second, a CLI helper stages printf("READY") without a newline and terminates via _exit(0)—leaving a 0-byte output file on disk even though $? is 0!
Reliable error handling and termination in systems C rest on three strict mechanisms: preserving thread-local errno before any intervening call, unwinding partially acquired resources in reverse Last-In-First-Out (LIFO) order via structured goto labels, and choosing deliberately between library exit() cleanup and immediate kernel _exit() termination.
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.
definition (Thread-Local errno, strerror_r(), LIFO goto & _exit()): 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().
One Layer Down: TLS Resolution, goto State Invariants & Exit Lifecycles
When a glibc wrapper sees %rax / r0 in [-4095, -1], it writes (int)(-ret) into *__errno_location(). Notice the two asymmetry rules: (1) a successful syscall (ret >= 0) never writes 0 into errno, and (2) cleanup calls (close(), free(), printf(), unlink()) may internally invoke syscalls that overwrite errno. Therefore, every error handler must follow the atomic three-step capture pattern: check ret == -1, copy int saved_errno = errno; on line 1 of the branch, and restore errno = saved_errno; before returning -1 to callers.
In functions acquiring k resources sequentially (R_1 = open, R_2 = mmap, R_3 = malloc), naive nested if blocks require k * (k - 1) / 2 duplicated cleanup calls (3 resources -> 3 error branches; 5 resources -> 10 error branches, virtually guaranteeing a descriptor leak!). Structured LIFO goto unwinding reduces cleanup to exactly k lines executed linearly from the jump target downward, governed by two mathematical invariants: initialize int rc = -1; before the first check (setting rc = 0; only after R_k succeeds), and initialize pointers/descriptors to NULL/-1 before any goto.
| Mechanism / Error Code | Numeric / Header Contract | Exact Runtime Behavior | |
|---|---|---|---|
ENOENT (2) / EEXIST (17) | <errno.h> path status | Missing file (no O_CREAT) / existing path (`O_CREAT \ | O_EXCL`) |
EINTR (4) / EAGAIN (11) | <errno.h> transient status | Signal interrupted blocked call / O_NONBLOCK channel not ready | |
EIO (5) / EBADF (9) / ENOSPC (28) | <errno.h> I/O & handle faults | Media I/O failure / invalid fd / out of storage blocks | |
EACCES (13) / EINVAL (22) / ESPIPE (29) | <errno.h> permission & seek | Mode denied / invalid flag or < 0 offset / lseek on pipe | |
return n; / exit(status) | <stdlib.h> user-space teardown | Runs atexit() (LIFO), flushes FILE buffers, calls _exit() | |
_exit(status) / _Exit(status) | <unistd.h> / <stdlib.h> trap | Immediate kernel exit_group(status & 0xFF); drops user stdio buffers |
Figure 3.2. Preserving thread-local errno against intervening clobbers, unwinding resources in LIFO goto order, and contrasting exit() against _exit().
- Step 1. Initialize int rc = -1 and NULL/-1 sentinels up front so early goto jumps never mask errors or free garbage.
- Step 2. Snapshot int saved_errno = errno on line 1 of an error branch before printf() or close() can overwrite TLS errno.
- Step 3. Release R_k down to R_1 in reverse LIFO goto order and restore errno = saved_errno before returning -1.
- Step 4. Use return/exit() to run atexit() and flush stdio buffers, or _exit() to enter exit_group() immediately.
Figure 3.2b. Capture saved_errno immediately on -1, unwind partial resources in reverse LIFO order, and choose deliberately between buffered exit() and immediate _exit().
XSI vs GNU strerror_r() & Scope-Guard Cleanup Notes
Watch a subtle header portability detail on Linux: under #define _POSIX_C_SOURCE 200809L without _GNU_SOURCE, <string.h> exposes standard POSIX XSI int strerror_r(int errnum, char *buf, size_t buflen) (0 on success), whereas defining _GNU_SOURCE switches strerror_r() to a GNU-specific char * return signature that may return a static string literal without copying into buf! Keeping _POSIX_C_SOURCE 200809L in portable error-formatting modules guarantees the XSI int contract across Linux, BSD, and macOS.
Proving saved_errno Clobber Immunity, LIFO goto & exit() vs _exit()
Save errno_exit_lab.c below. Run as emit_exit or emit_uexit with stdout redirected to a file, printf("%s", "BUFFERED_13B!") leaves 13 bytes inside glibc's user-space stdout buffer: exit(EXIT_SUCCESS) runs atexit() (10 bytes) and flushes all 13 bytes, whereas _exit(EXIT_SUCCESS) enters exit_group(0) immediately (0 bytes on disk!). Run with zero arguments, ./errno_exit_lab reproduces the printf() ENOTTY clobber on live errno while proving saved_errno preserves ENOENT (2) for strerror_r(), and verifies reverse-order stage_lifo_probe() goto cleanup!
learner@ksa:~/gl-c01/m03-l02$ bat -H 24 -H 49 -H 64 -H 65 errno_exit_lab.c File: errno_exit_lab.c #define _POSIX_C_SOURCE 200809L #include <errno.h> #include <fcntl.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <sys/stat.h> #include <unistd.h> static const char *g_atexit_path = "/tmp/ksa_atexit_marker.tmp"; static void cleanup_handler(void) { int flags = O_WRONLY | O_CREAT | O_TRUNC | O_CLOEXEC; int mfd = open(g_atexit_path, flags, 0644); if (mfd >= 0) { ssize_t wr = write(mfd, "ATEXIT_RAN", 10U); (void)wr; (void)close(mfd); } } static int stage_lifo_probe(int inject_fail, int *closed_order) { int rc = -1; int fd = open("/dev/null", O_RDONLY | O_CLOEXEC); void *buf = NULL; if (fd < 0) { goto out; } buf = malloc(128U); if (buf == NULL || inject_fail) { int err_hold = inject_fail ? EPROTO : errno; *closed_order = 1; errno = err_hold; goto out_buf; } rc = 0; out_buf: free(buf); if (*closed_order == 1) { *closed_order = 2; } { int keep = errno; (void)close(fd); errno = keep; } out: return rc; } int main(int argc, char *argv[]) { if (argc > 1 && strcmp(argv[1], "emit_exit") == 0) { (void)atexit(cleanup_handler); printf("%s", "BUFFERED_13B!"); exit(EXIT_SUCCESS); } if (argc > 1 && strcmp(argv[1], "emit_uexit") == 0) { printf("%s", "BUFFERED_13B!"); _exit(EXIT_SUCCESS); } const char *p_exit = "/tmp/ksa_stdio_exit.tmp"; const char *p_uexit = "/tmp/ksa_stdio_uexit.tmp"; errno = 0; int bad_fd = open("/tmp/ksa_nonexistent_99182.cfg", O_RDONLY | O_CLOEXEC); int saved_errno = errno; char msg_buf[128]; int r_rc = strerror_r(saved_errno, msg_buf, sizeof(msg_buf)); int lifo_step = 0; errno = 0; int lifo_ok = (stage_lifo_probe(1, &lifo_step) == -1 && errno == EPROTO && lifo_step == 2 && stage_lifo_probe(0, &lifo_step) == 0); struct stat st_exit, st_uexit, st_marker; long long b_exit = (stat(p_exit, &st_exit) == 0) ? (long long)st_exit.st_size : -1LL; long long b_uexit = (stat(p_uexit, &st_uexit) == 0) ? (long long)st_uexit.st_size : -1LL; long long b_atexit = (stat(g_atexit_path, &st_marker) == 0) ? (long long)st_marker.st_size : 0LL; (void)unlink(p_exit); (void)unlink(p_uexit); (void)unlink(g_atexit_path); printf("bad_fd=%d saved_errno=%d is_enoent=%d msg_ok=%d lifo_ok=%d\n", bad_fd, saved_errno, saved_errno == ENOENT && r_rc == 0, strstr(msg_buf, "No such") != NULL, lifo_ok); printf("exit_flushed_bytes=%lld uexit_flushed_bytes=%lld atexit=%lld\n", b_exit, b_uexit, b_atexit); return EXIT_SUCCESS; }- Initialize rc = -1 and buf = NULL up front so jumping to out_buf or out never leaks fd or returns 0 on failure.
- _exit(EXIT_SUCCESS) traps straight to exit_group(0), dropping the 13 unflushed bytes in stdout's Ring 3 FILE buffer.
- Capture saved_errno BEFORE any intervening call; strerror_r() formats ENOENT into caller stack memory thread-safely.
Comparing Flushed exit() vs Dropped _exit() Output
Compile errno_exit_lab, redirect emit_exit and emit_uexit into /tmp files, verify exit_flushed_bytes=13 vs uexit_flushed_bytes=0 and atexit=10, and confirm under strace that emit_uexit traps directly to exit_group(0).
learner@ksa:~/gl-c01/m03-l02gcc -fdiagnostics-color=always -std=c11 -Wall -Wextra -Werror errno_exit_lab.c -o errno_exit_lablearner@ksa:~/gl-c01/m03-l02rm -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_labbad_fd=-1 saved_errno=2 is_enoent=1 msg_ok=1 lifo_ok=1exit_flushed_bytes=13 uexit_flushed_bytes=0 atexit=10learner@ksa:~/gl-c01/m03-l02strace -e trace=exit_group ./errno_exit_lab emit_uexit 2>&1 >/dev/null | grep -c 'exit_group(0)'1learner@ksa:~/gl-c01/m03-l02rm -f errno_exit_lablearner@ksa:~/gl-c01/m03-l02Why Cleanup Ordering & User-Space Teardown Govern Reliability
Both emit_exit and emit_uexit ended at kernel exit_group(0) ($? == 0), yet only exit() walked the atexit() stack (atexit=10) and flushed stdout's user-space FILE buffer (13 bytes vs 0 bytes) before trapping! Meanwhile, inside stage_lifo_probe(), preserving int keep = errno; around close(fd) ensured cleanup calls could never clobber the root-cause EPROTO diagnostic returned to the caller.
Scope Boundary — Child _exit() After Failed execve(): 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!
Guided Practice: Refactoring a Leaky 3-Step Initializer to LIFO goto
A helper acquires fd1 = open(a, ...), fd2 = open(b, ...), and buf = malloc(4096), returning -1 directly on each error (if (fd2 < 0) return -1;—leaking fd1!):
- Step 1 (Order the reverse labels): Write the three bottom labels in strict reverse acquisition order (
out_buf:freeingbuf,out_fd2:closingfd2,out_fd1:closingfd1,out:returningrc), initializingint rc = -1;at the top. - Step 2 (Preserve
errnoacrossclose()): Saveint err = errno;before jumping on failure and restoreerrno = err;right beforereturn rc;soclose(fd1)cannot overwrite theopen(b)ormalloc()error code.
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_close_fd(int *fdp) { if (*fdp >= 0) { int e = errno; (void)close(*fdp); errno = e; *fdp = -1; } } attached via __attribute__((cleanup(auto_close_fd))) int fd = open(...). Verify via /proc/self/fdinfo/ or lowest-slot reuse in main() that returning early on an injected error closes fd automatically while preserving errno.
Common Production Pitfalls
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().
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.
Knowledge Check
? check 1 · (Review from earlier lesson) After ssize_t n = read(fd, buf, 64);, when is a C11 program permitted to inspect errno?
- [ ] Whenever
errno != 0, even ifn == 64, becauseglibcclearserrnoto0on success - [x] Strictly when
n == -1(our earlier lesson's error regime), savingint saved_errno = errno;before any logging or cleanup call - [ ] Whenever
n == 0at clean EOF, to test whetherENOSPCoccurred
Answer: Strictly when n == -1 (our earlier lesson's error regime), saving int saved_errno = errno; before any logging or cleanup call
Why: 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.
? check 2 · Which termination call bypasses atexit() handlers and drops unflushed user-space stdio FILE buffers by trapping directly into the Linux kernel?
- [ ]
exit(EXIT_FAILURE)from<stdlib.h> - [ ]
return EXIT_FAILURE;at the end ofmain() - [x]
_exit(EXIT_FAILURE)from<unistd.h>(or ISO C11_Exit(EXIT_FAILURE))
Answer: _exit(EXIT_FAILURE) from <unistd.h> (or ISO C11 _Exit(EXIT_FAILURE))
Why: _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.
? check 3 · 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?
- [ ] Calling
strerror(errno)directly insidefprintf(stderr, ...)afterclose(fd) - [x] Capturing
int err = errno;immediately and callingstrerror_r(err, buf, sizeof(buf))with a caller-owned stack buffer - [ ] Parsing
/usr/include/asm-generic/errno-base.hfrom disk at runtime
Answer: Capturing int err = errno; immediately and calling strerror_r(err, buf, sizeof(buf)) with a caller-owned stack buffer
Why: 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.
? check 4 · 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?
- [ ] Initialize
int rc = 0;at entry and leavevoid *buf;uninitialized untilmalloc()runs - [x] Initialize
int rc = -1;up front (settingrc = 0only after all acquisitions succeed) and initialize pointers/descriptors toNULL/-1so reverse-order (LIFO) labels never return0on failure or pass garbage tofree() - [ ] Call
_exit(1)inside library helpers instead of closing descriptors
Answer: Initialize int rc = -1; up front (setting rc = 0 only after all acquisitions succeed) and initialize pointers/descriptors to NULL/-1 so reverse-order (LIFO) labels never return 0 on failure or pass garbage to free()
Why: 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.
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(). 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_size versus st_blocks * 512, and test the read/write cursor asymmetry of O_RDWR | O_APPEND.
Step sequence — frame strip: steps_m03_l02
Initialize int rc = -1 and NULL/-1 sentinels up front so early goto jumps never mask errors or free garbage.
reveals: step1
highlights: step1
Snapshot int saved_errno = errno on line 1 of an error branch before printf() or close() can overwrite TLS errno.
reveals: step2
highlights: step2
Release R_k down to R_1 in reverse LIFO goto order and restore errno = saved_errno before returning -1.
reveals: step3
highlights: step3
Use return/exit() to run atexit() and flush stdio buffers, or _exit() to enter exit_group() immediately.
reveals: step4
highlights: step4
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.
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. First, a factory provisioning utility builds a 4 GiB raw partition image containing a 64 KiB bootloader at offset 0 and a 64 B trailer at 4 GiB - 64 by calling write() in a 4 KiB zero-fill loop—stalling production flashing for minutes, burning 4 GiB of eMMC write endurance, and failing with ENOSPC on a 2 GiB /tmp RAM disk! Second, a telemetry journal opens its file with O_RDWR | O_APPEND, calls lseek(fd, 0, SEEK_SET) + write(fd, &super_hdr, 64) to update a header counter at byte 0, and discovers after reboot that byte 0 still holds the old header while 64 unexpected bytes were appended to the tail of the log!
Both defects vanish once you understand how the Linux kernel decouples logical file length (st_size) from physically allocated extents (st_blocks), and how O_TRUNC and O_APPEND manipulate inode->i_size and struct file.f_pos asymmetrically.
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.
definition (Sparse Extent Holes, POSIX 512-Byte st_blocks & O_APPEND Asymmetry): 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.
One Layer Down: Extent Trees, Sector Accounting Math & O_APPEND Locking
Inside ext4 or XFS, an inode's extent tree maps logical block numbers (4 KiB units) to physical device blocks ([logical_blk, len -> phys_blk]). Seeking from 0 to 4,194,240 (4 MiB - 64 B) and writing 64 bytes allocates only the final 4 KiB block (logical_blk = 1023, 1 physical 4 KiB block = 8 POSIX 512-byte sectors). Comparing fstat() fields quantifies exact space efficiency via bytes_logical = st.st_size and bytes_physical = (long long)st.st_blocks * 512LL. For our 4 MiB (4,194,304-byte) sparse image with one 4 KiB tail block (st_blocks = 8), bytes_physical = 8 * 512 = 4,096 B (99.90% physical block savings!). Notice why multiplying st_blocks * st_blksize (8 * 4096 = 32,768) is a classic bug: st_blksize (4,096) is merely the preferred I/O buffer hint, whereas st_blocks is unconditionally denominated in 512-byte units.
Meanwhile, inspect how O_TRUNC and O_APPEND act at different lifecycle moments inside VFS:
| Open Flag Combination | Action During open() | lseek() + read() Behavior | lseek() + write() Behavior | ||
|---|---|---|---|---|---|
O_RDWR (no O_APPEND) | Preserves i_size, sets f_pos = 0 | Reads from f_pos, advances f_pos | Writes at f_pos (in-place overwrite) | ||
| `O_WRONLY \ | O_TRUNC` | Frees all extents/holes, sets i_size = 0 | Rejects read() with EBADF | Writes sequentially from 0 | |
| `O_RDWR \ | O_APPEND` | Preserves i_size, sets f_pos = 0 | Honors lseek() at any offset! | Ignores lseek(); jumps f_pos to i_size! | |
| `O_WRONLY \ | O_APPEND \ | O_TRUNC` | Frees old extents once at open() | Rejects read() with EBADF | Atomically appends every write() at new EOF |
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.
- Step 1. Seeking past EOF via lseek(hfd, 65536, SEEK_SET) advances f_pos in RAM without writing physical zero blocks.
- Step 2. Writing a 4 KiB tail block sets st_size = 69,632 while physical usage st_blocks * 512LL equals 4,096 B.
- Step 3. Reading across unallocated hole extents synthesizes clean 0x00 bytes in VFS; O_TRUNC frees all extents.
- Step 4. On O_RDWR | O_APPEND, lseek(0) works for read(), whereas write() locks i_rwsem and jumps atomically to EOF.
Figure 3.3b. Sparse holes decouple logical st_size from physical st_blocks * 512 allocation, while O_APPEND forces writes—never reads—to current i_size.
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 and #define _POSIX_C_SOURCE 200809L. Both ext4, XFS, Btrfs, and Linux tmpfs (shmem) track sparse holes per 4 KiB page, so st.st_blocks * 512LL < st.st_size holds across workstation disks, /tmp tmpfs mounts, and embedded root filesystems alike (whereas legacy FAT32 SD partitions lack sparse-extent metadata and zero-fill gaps physically).
Probing Sparse Holes, O_TRUNC Reclamation & O_RDWR | O_APPEND
Save hole_append_probe.c below. First, it creates /tmp/ksa_hole_demo.bin, seeks straight to offset 65536 (64 KiB, leaving [0..65535] unallocated), writes one 4,096-byte 0xFF block (st_size == 69632 while st_blocks * 512 < 69632), rewinds to 0 to prove VFS synthesizes 0x00 bytes across the hole, and reopens with O_WRONLY | O_TRUNC (trunc_size == 0, trunc_blocks == 0). Second, it seeds {0x11, 0x22, 0x33, 0x44}, reopens with O_RDWR | O_APPEND, proves lseek(0) + read() reads 0x11 at offset 0, and proves lseek(0) + write() ignores offset 0 and appends 0x55 at offset 4!
learner@ksa:~/gl-c01/m03-l03$ bat -H 20 -H 44 -H 65 hole_append_probe.c File: hole_append_probe.c #define _FILE_OFFSET_BITS 64 #define _POSIX_C_SOURCE 200809L #include <errno.h> #include <fcntl.h> #include <stdint.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <sys/stat.h> #include <sys/types.h> #include <unistd.h> int main(void) { const char *hpath = "/tmp/ksa_hole_demo.bin"; const char *apath = "/tmp/ksa_append_demo.bin"; (void)unlink(hpath); (void)unlink(apath); int hfd = open(hpath, O_RDWR | O_CREAT | O_EXCL | O_CLOEXEC, 0644); if (hfd == -1 || lseek(hfd, 65536, SEEK_SET) == (off_t)-1) { return EXIT_FAILURE; } uint8_t block[4096]; memset(block, 0xFFU, sizeof(block)); if (write(hfd, block, sizeof(block)) != (ssize_t)sizeof(block)) { return EXIT_FAILURE; } struct stat hst; if (fstat(hfd, &hst) == -1 || lseek(hfd, 0, SEEK_SET) == (off_t)-1) { return EXIT_FAILURE; } uint8_t hole_sample[16]; memset(hole_sample, 0xAAU, sizeof(hole_sample)); if (read(hfd, hole_sample, sizeof(hole_sample)) != (ssize_t)sizeof(hole_sample)) { return EXIT_FAILURE; } int hole_zero = 1; for (size_t i = 0; i < sizeof(hole_sample); i++) { if (hole_sample[i] != 0x00U) hole_zero = 0; } (void)close(hfd); int tfd = open(hpath, O_WRONLY | O_TRUNC | O_CLOEXEC); struct stat tst; if (tfd == -1 || fstat(tfd, &tst) == -1) return EXIT_FAILURE; (void)close(tfd); (void)unlink(hpath); int sfd = open(apath, O_WRONLY | O_CREAT | O_TRUNC | O_CLOEXEC, 0644); const uint8_t init4[4] = {0x11U, 0x22U, 0x33U, 0x44U}; if (sfd == -1 || write(sfd, init4, 4U) != 4) return EXIT_FAILURE; (void)close(sfd); int afd = open(apath, O_RDWR | O_APPEND | O_CLOEXEC); uint8_t rbyte = 0U; const uint8_t tag4[4] = {0x55U, 0x55U, 0x55U, 0x55U}; if (afd == -1 || lseek(afd, 0, SEEK_SET) == (off_t)-1 || read(afd, &rbyte, 1U) != 1) { return EXIT_FAILURE; } if (lseek(afd, 0, SEEK_SET) == (off_t)-1 || write(afd, tag4, 4U) != 4) { return EXIT_FAILURE; } uint8_t all8[8] = {0}; if (lseek(afd, 0, SEEK_SET) == (off_t)-1 || read(afd, all8, 8U) != 8) { return EXIT_FAILURE; } (void)close(afd); (void)unlink(apath); long long phys = (long long)hst.st_blocks * 512LL; printf("hole_logical=%lld hole_phys_lt=%d hole_zero=%d trunc_sz=%lld\n", (long long)hst.st_size, phys < (long long)hst.st_size, hole_zero, (long long)tst.st_size); printf("append_read0=0x%02x byte0_kept=0x%02x eof_byte4=0x%02x\n", rbyte, all8[0], all8[4]); return EXIT_SUCCESS; }- Seeking to 65536 past EOF and writing 4096 bytes leaves [0..65535] unallocated (0 disk sectors for the 64 KiB hole).
- O_TRUNC resets st_size to 0 and releases allocated extents back to the filesystem during open().
- On O_RDWR | O_APPEND, lseek(0) works for read(), but write() atomically jumps f_pos to EOF (offset 4).
Verifying Sparse Sector Counts, O_APPEND Asymmetry & Lab 3
Compile and run hole_append_probe, confirm hole_logical=69632 with hole_phys_lt=1 and trunc_sz=0, verify byte0_kept=0x11 and eof_byte4=0x55 on O_RDWR | O_APPEND, and complete lab_m03_sparse_image.
learner@ksa:~/gl-c01/m03-l03gcc -fdiagnostics-color=always -std=c11 -Wall -Wextra -Werror hole_append_probe.c -o hole_append_probelearner@ksa:~/gl-c01/m03-l03./hole_append_probehole_logical=69632 hole_phys_lt=1 hole_zero=1 trunc_sz=0append_read0=0x11 byte0_kept=0x11 eof_byte4=0x55learner@ksa:~/gl-c01/m03-l03strace -e trace=openat ./hole_append_probe 2>&1 | grep -c 'O_APPEND'1learner@ksa:~/gl-c01/m03-l03rm -f hole_append_probelearner@ksa:~/gl-c01/m03-l031. Motivation
Embedded Board Support Package (BSP) build scripts routinely assemble 4 MiB to 32 GiB raw flash/SD partition images containing a small bootloader header at byte 0 and a backup GPT/trailer table at the end of the image. Writing physical 0x00 buffers across every empty megabyte wastes gigabytes of CI disk space, hammers SSD/eMMC write amplification, and slows image generation by 100x. Simultaneously, engineers who attach audit tags using O_RDWR | O_APPEND frequently assume lseek(fd, 0, SEEK_SET) lets write() patch the superblock at byte 0. In this lab, you will build sparse_img to master sparse extent holes, st_size vs st_blocks * 512 accounting, and O_RDWR | O_APPEND cursor asymmetry.
2. Learning Objectives
- Construct a
4 MiB(4,194,304-byte) sparse partition image usinglseek(fd, 4194240, SEEK_SET)so unallocated interior extents consume0physical disk blocks. - Measure and verify logical length (
st.st_size == 4194304) against physical sector allocation ((long long)st.st_blocks * 512LL < 131072) viafstat(), while proving VFS synthesizes0x00bytes on reads inside the hole. - Demonstrate
O_RDWR | O_APPENDasymmetry by provinglseek(afd, 0, SEEK_SET)positionsread()at byte0("KSA_SPARSE_SB_V1") while forcingwrite()atomically toEOF(4194304 + tag_len).
3. Environment Requirements
- Host Execution Environment (Tested): Linux
6.12LTS (x86_64,glibc2.39+) on sparse-capable POSIX filesystems (ext4,XFS,Btrfs, ortmpfs). - Target Board Portability (
ARMv7Cortex-A7):#define _FILE_OFFSET_BITS 64ensuresoff_tandstruct stat(fstat64) handle>= 2 GiBsparse images identically on 32-bitARMv7ext4/f2fsroot partitions (note:VFATboot partitions do not support sparse holes and allocate physical zero clusters).
4. Required Software & Hardware
- Software Toolchain:
gcc(-std=c11 -Wall -Wextra -Werror),stat,ls,du,strace, and/bin/sh. - Hardware: Standard Linux host environment.
5. Complete Executable Commands
Run from labs/lab_m03_sparse_image/:
learner@ksa:~/gl-c01/m03-l03$ bat script.sh File: script.sh # 1. Compile the warning-clean sparse partition builder gcc -std=c11 -O2 -Wall -Wextra -Werror files/sparse_img.c -o /tmp/sparse_img # 2. Build a 4 MiB sparse image and append an 8-byte audit trailer via O_RDWR | O_APPEND /tmp/sparse_img /tmp/ksa_part.img --append-tag AUDIT_01 # 3. Contrast logical EOF size (ls -lh) against physical allocated blocks (du -h & stat) ls -lh /tmp/ksa_part.img du -h /tmp/ksa_part.img stat -c 'logical=%s blocks_512=%b phys_bytes=%B_unit_check' /tmp/ksa_part.img # 4. Verify only 3 write() syscalls ran (vs 1,024 in the broken starter!) strace -e trace=write,lseek /tmp/sparse_img /tmp/ksa_part.img --append-tag AUDIT_01 # 5. Clean up and execute the full TAP 13 test suite rm -f /tmp/sparse_img /tmp/ksa_part.img sh check.sh*Why each command runs:* ls -lh reads st_size (4.1M), whereas du -h sums st_blocks * 512 (8.0K or 12K—two or three 4 KiB blocks total!); strace proves lseek() skipped the 4 MiB gap in 1 metadata call with zero zero-fill writes; and sh check.sh validates starter failure and reference compliance.
6. Annotated Source Code (starter/ Flaws vs files/ Reference)
Flawed Baseline (starter/sparse_img.c)
- Physical zero-fill loop: Calls
write(fd, zero, 4096)1,024times, allocating4,194,304physical bytes (8,192512-byte sectors) and failingphys_bytes < 131072. - Missing
O_TRUNC&O_CLOEXEC: Re-running over an existing larger image leaves trailing garbage intact, and descriptors leak onexecve(). - Missing trailer, hole verification, and
O_APPENDproof: Never writes the superblock/trailer markers or testsO_RDWR | O_APPEND.
Warning-Clean Reference (files/sparse_img.c)
- Sparse Construction: Opens
<img_path>withO_RDWR | O_CREAT | O_TRUNC | O_CLOEXEC(0644), writes64-byte"KSA_SPARSE_SB_V1"(0x5A-padded) at0, callslseek(fd, 4194240, SEEK_SET)across the unallocated[64 .. 4194239]gap, and writes64-byte"KSA_SPARSE_TR_V1"(0xA5-padded) at4194240. - Hole & Sector Verification: Queries
fstat(fd, &st), computesphys_bytes = (long long)st.st_blocks * 512LL(8,192bytes = two4 KiBblocks!), seeks to2097152(2 MiB), pre-fillshole_bufwith0xFF, and provesread_full()overwrites all64bytes with VFS-synthesized0x00. O_APPENDAsymmetry Proof: Reopens withO_RDWR | O_APPEND | O_CLOEXEC, seeks to0to read"KSA_SPARSE_SB_V1", seeks to0again beforewrite_all(afd, append_tag, tag_len), and verifies byte0stayed"KSA_SPARSE_SB_V1"whilest_sizegrew to4194304 + tag_len!
7. Expected Output
learner@ksa:~/gl-c01/m03-l03$ bat listing.txt File: listing.txt $ /tmp/sparse_img /tmp/ksa_part.img --append-tag AUDIT_01 logical_size=4194312 phys_bytes=12288 hole_zero_ok=1 superblock_ok=1 append_eof_ok=1 $ sh check.sh TAP version 13 1..5 ok 1 - compiles cleanly with -std=c11 -Wall -Wextra -Werror ok 2 - creates 4 MiB logical image using < 128 KiB physical disk blocks ok 3 - synthesizes 0x00 bytes when reading across unallocated sparse hole ok 4 - preserves superblock at offset 0 while O_APPEND forces write to EOF ok 5 - reclaims stale blocks via O_TRUNC on rebuild # pass 5/58. Explanation of Observed Behavior
Writing [0..63] allocates logical block 0 (4,096 bytes); seeking to 4,194,240 and writing [4194240..4194303] allocates logical block 1023 (4,096 bytes), leaving blocks 1..1022 (1,022 * 4 KiB = 4,186,112 bytes) unmapped in the inode's extent tree (phys_bytes = 8,192 before --append-tag, 12,288 after appending 8 bytes into logical block 1024). During --append-tag, lseek(afd, 0, SEEK_SET) sets struct file.f_pos = 0 for read(), then vfs_write() sees O_APPEND in f_flags and resets kiocb.ki_pos = i_size (4,194,304) atomically under inode->i_rwsem.
9. Experiment Variations
- Extent Enumeration (
filefrag/SEEK_DATA): Runfilefrag -v /tmp/ksa_part.img(or addlseek(fd, 0, SEEK_HOLE)/lseek(fd, 4096, SEEK_DATA)) to inspect the exact physical extent ranges[0..4095]and[4190208..4194303]. - Naive
cpInflation Test: Comparecp --sparse=never /tmp/ksa_part.img /tmp/dense.img(du -hjumps to4.0M!) againstcp --sparse=always /tmp/ksa_part.img /tmp/sparse_copy.img(du -hstays12K!). - Punching Holes Dynamically (
fallocate): On Linux (#define _GNU_SOURCE), testfallocate(fd, FALLOC_FL_PUNCH_HOLE | FALLOC_FL_KEEP_SIZE, 0, 4096)to deallocate block0back into a sparse hole without changingst_size!
10. Performance Measurements
Measured on Host x86_64 Linux 6.12 LTS (CLOCK_MONOTONIC, 5 warmup runs, N = 35 runs creating 4 MiB image + --append-tag AUDIT_01):
| Metric | Sparse lseek Reference (files/) | Dense Zero-Fill Starter (starter/) | Target ARMv7 Cortex-A7 eMMC Expectation |
|---|---|---|---|
End-to-end build latency (p50 / p95 / p99) | 2,999.4 us / 3,335.8 us / 3,341.4 us | ~6,800+ us (RAM cache) / >80 ms synced | ~12 ms sparse vs >250 ms dense eMMC writes |
Physical storage allocated (st_blocks * 512) | 8,192 B (12,288 B with tag; 99.7% saved) | 4,194,304 B (0% saved) | Identical ext4 4 KiB block allocation |
Kernel write() syscalls | 2 (3 with --append-tag) | 1,024 | 2 (3 with --append-tag) |
11. Troubleshooting
| Symptom | Root Cause | Fix | ||
|---|---|---|---|---|
phys_bytes equals 4194304 or 33554432 | Wrote literal zero buffers, or multiplied st_blocks * st_blksize (4096) instead of 512 | Use lseek() across holes and multiply st.st_blocks * 512LL | ||
superblock_ok=0 after --append-tag | Opened afd without O_APPEND, allowing lseek(0) + write() to clobber byte 0 | Pass `O_RDWR \ | O_APPEND \ | O_CLOEXEC` |
EOVERFLOW on > 2 GiB sparse offsets on 32-bit builds | Missing #define _FILE_OFFSET_BITS 64 before #include | Place #define _FILE_OFFSET_BITS 64 on line 1 |
12. Guided Questions
- Why does
lseek(fd, 4194304, SEEK_SET)followed immediately byclose(fd)(with NOwrite()) leavest_size == 0instead of4194304?
- *Hint 1:* Which kernel structure does
lseek()mutate (struct file.f_posvsstruct inode.i_size)? - *Hint 2:* Which syscall resizes
inode->i_sizeto4194304without writing trailing payload bytes if your image ends with a sparse hole?
- Why did appending an
8-byte tag at offset4,194,304increasephys_bytesby4,096bytes (8st_blocksunits) instead of8bytes?
- *Hint 1:* Offset
4,194,304(4 MiB) sits at exact4 KiBblock index1024(4194304 / 4096 == 1024). - *Hint 2:* What is the minimum physical allocation unit of an
ext4/tmpfspage-backed filesystem?
13. Independent Challenges
- Near Transfer — Multi-Partition GPT-Style Sparse Table Builder: Extend
sparse_img.cto accept<boot_bin>and<rootfs_bin>payloads placed at1 MiB(1,048,576) and64 MiB(67,108,864) inside a512 MiBlogical image, verifying viaSEEK_DATA/SEEK_HOLEthat exactly the non-zero regions are allocated. - Far Transfer — Sparse Archive Serializer (
--pack/--unpack): Build a sparse-aware archiver that scans any sparse image withSEEK_DATA/SEEK_HOLE, emits compact[uint64_t offset, uint64_t length, data...]records, and reconstructs an identical sparse target (st_sizeandst_blocks * 512preserved).
14. Solutions & Explanations
- Guided Question 1:
lseek()updates onlystruct file.f_posin RAM without touchingstruct inode.i_size; only a subsequentwrite()pasti_size(or an explicitftruncate(fd, 4194304)) extends the inode's logical EOF! - Guided Question 2: Filesystems allocate storage in whole
4 KiB(4,096-byte =8 * 512B) blocks/folios; writing byte0of block1024allocates that entire4 KiBblock (phys_bytesrises from8,192to12,288).
Run locally in your terminal and check off each verification milestone.
Not started
Kernel-Locked O_APPEND Sets Up Module 4 File Sharing
Inside fs/read_write.c, O_APPEND works because the kernel acquires inode->i_rwsem, sets kiocb.ki_pos = i_size_read(inode), and copies user bytes into the page cache before releasing the lock—making O_APPEND atomic across cooperating processes! Module 4 builds directly on that insight: what happens when a process opens one file twice versus duplicating a descriptor with dup2()/dup3(), and how do pread() and pwrite() perform random-access updates without touching f_pos at all?
Guided Practice: Sparse-Aware File Copier Loop
A naive cp implementation copies a sparse image by calling read() and write() unconditionally, inflating a 64 KiB-allocated 1 GiB image into 1 GiB of physical zero blocks:
- Step 1 (Detect all-zero
4 KiBbuffers orSEEK_DATAextents): Write a helperstatic int is_all_zero(const uint8_t *buf, size_t n)(or useSEEK_DATA/SEEK_HOLEfromm02-l03). - Step 2 (Preserve trailing holes at
EOF): When skipping a4 KiBzero chunk ondst_fdvialseek(dst_fd, 4096, SEEK_CUR), remember thatlseek()pastEOFalone does not extendst_sizeif the file ends with a hole—callftruncate(dst_fd, src_st.st_size)(covered in depth in Module 4) or verifySEEK_ENDwhen finalizing!
Independent Practice: Extent Map & Sparsity Ratio Reporter
Write a C11 CLI sparse_stat.c (#define _GNU_SOURCE, #define _FILE_OFFSET_BITS 64, -Wall -Wextra -Werror) that creates a 16 MiB test file containing three 4 KiB data islands at 0, 4 MiB, and 12 MiB, walks every [data_start, hole_start) extent using SEEK_DATA and SEEK_HOLE, and prints logical bytes (st_size), physical bytes (st_blocks * 512), extent count (3), and exact sparsity percentage.
Common Production Pitfalls
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).
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.
Knowledge Check
? check 1 · 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()?
- [ ]
st_size == 64andst_blocks * 512 == 64, becauselseek()pastEOFis ignored - [x]
st_size == 1048640(1 MiB + 64), whilest_blocks * 512equals one filesystem block (4,096bytes) because the1 MiBgap is an unallocated sparse hole - [ ]
st_size == 1048640andst_blocks * 512 == 1048640, because VFS writes1 MiBof physical zeros synchronously
Answer: st_size == 1048640 (1 MiB + 64), while st_blocks * 512 equals one filesystem block (4,096 bytes) because the 1 MiB gap is an unallocated sparse hole
Why: 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.
? check 2 · (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?
- [ ]
read()returns0(EOF) becauseO_APPENDforces reads to end-of-file, and0x99lands at offset4 - [ ]
read()fetches0x20at offset1, and0x99overwrites offset0becauselseek(fd, 0, SEEK_SET)precededwrite() - [x]
read()fetches0x20at offset1(O_APPENDleaves reads seekable), whereaswrite()ignoreslseek()and atomically appends0x99at offset4(EOF)
Answer: read() fetches 0x20 at offset 1 (O_APPEND leaves reads seekable), whereas write() ignores lseek() and atomically appends 0x99 at offset 4 (EOF)
Why: 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.
? check 3 · (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?
- [ ]
open()fails withEINVALbecauseO_APPENDandO_TRUNCcannot be combined - [x]
O_TRUNCresetsst_sizeto0and frees old extents once duringopen(), after whichO_APPENDatomically appends the two records at[0..15]and[16..31](st_size == 32) - [ ]
O_APPENDcancelsO_TRUNC, preserving the8 KiBprefix and appending at8192
Answer: O_TRUNC resets st_size to 0 and frees old extents once during open(), after which O_APPEND atomically appends the two records at [0..15] and [16..31] (st_size == 32)
Why: 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.
? check 4 · 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?
- [ ]
8,388,608bytes (128 * st.st_blksize) - [x]
65,536bytes (128 * 512), because POSIX definesst_blocksin fixed512-byte units regardless ofst_blksize - [ ]
524,288bytes (128 * 4096)
Answer: 65,536 bytes (128 * 512), because POSIX defines st_blocks in fixed 512-byte units regardless of st_blksize
Why: 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.
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.
With VFS tables, errno unwinding, and sparse extents in place, Module 4 tackles descriptor sharing (dup2/dup3), atomic O_EXCL & stateless pread/pwrite, and runtime fcntl/ioctl control.
Step sequence — frame strip: steps_m03_l03
Seeking past EOF via lseek(hfd, 65536, SEEK_SET) advances f_pos in RAM without writing physical zero blocks.
reveals: step1
highlights: step1
Writing a 4 KiB tail block sets st_size = 69,632 while physical usage st_blocks * 512LL equals 4,096 B.
reveals: step2
highlights: step2
Reading across unallocated hole extents synthesizes clean 0x00 bytes in VFS; O_TRUNC frees all extents.
reveals: step3
highlights: step3
On O_RDWR | O_APPEND, lseek(0) works for read(), whereas write() locks i_rwsem and jumps atomically to EOF.
reveals: step4
highlights: step4
m04/
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.
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.
Why Dual open() Overwrites Data & dup3(fd, fd, O_CLOEXEC) Fails
Two subtle bugs surface whenever subsystems share files or redirect standard streams. First, two components inside one process each call open("/var/log/audit.bin", O_WRONLY | O_CREAT, 0644) without O_APPEND and alternate 4-byte writes—instead of an 8-byte log, the second component's f_pos = 0 overwrites the first component's bytes in the shared page cache! Second, a daemon helper redirects output to STDOUT_FILENO (1) via dup3(log_fd, STDOUT_FILENO, O_CLOEXEC): it works for months until startup happens to run with descriptor 1 closed so open() allocates log_fd == 1—causing dup3(1, 1, O_CLOEXEC) to fail immediately with EINVAL!
Predicting every multi-descriptor interaction in Linux requires tracing exactly which tier of the three-table VFS hierarchy (files_struct slot vs struct file description vs struct inode) is cloned versus aliased across dual open(), dup/dup2/dup3, and fork().
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.
definition (Dual-Open Independence vs Descriptor Aliasing (dup/dup2/dup3)): 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.
Figure 4.1a. Same-process dual open() — fd1 and fd2 allocate independent struct file cursors pointing to one shared VFS inode.
Figure 4.1b. Two independent processes opening the same pathname — separate PCBs and separate struct file cursors share one VFS inode.
One Layer Down: f_count Reference Math & Per-Slot FD_CLOEXEC Bitmaps
Inside task_struct->files->fdt, close_on_exec is a per-descriptor bitmask stored alongside fd_array[], not inside struct file. Consequently, dup(oldfd) and dup2(oldfd, newfd) always clear FD_CLOEXEC (0) on the new slot (so shell redirections like cmd > out.txt survive execve()!), whereas Linux dup3(oldfd, newfd, O_CLOEXEC) sets FD_CLOEXEC (1) atomically on newfd without altering oldfd's bit. Meanwhile, file->f_count tracks total slot references across all processes: file->f_count = sum_over_procs(count(d : p->fdt->fd[d] == file)). Closing oldfd decrements f_count from 2 to 1; VFS invokes f_op->release and frees struct file only when the final alias closes (f_count -> 0).
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.
| Sharing Topology | files_struct Slot (FD_CLOEXEC) | struct file (f_pos, f_flags, f_count) | struct inode & | Production Consequence |
|---|---|---|---|---|
Dual open() (1 or 2 procs) | Separate slot & FD_CLOEXEC | Separate struct file (f_pos = 0 each) | Shared 1 inode & cache | Silent overwrites unless O_APPEND or pwrite |
dup() / dup2() | Separate slot (FD_CLOEXEC = 0 on new) | Shared 1 struct file (f_count++) | Shared 1 inode & cache | Lockstep f_pos; dup2(fd, fd) is a safe no-op |
dup3(old, new, O_CLOEXEC) | Separate slot (FD_CLOEXEC = 1 on new) | Shared 1 struct file (f_count++) | Shared 1 inode & cache | Rejects old == new with -1 (EINVAL)! |
fork() (Later: GL-C02) | Cloned files_struct table | Shared 1 struct file (f_count++) | Shared 1 inode & cache | Parent & child advance one shared f_pos |
- Step 1. Flush stdout first and call saved_out = dup(STDOUT_FILENO) to increment the terminal struct file's f_count to 2.
- Step 2. Call dup2(log_fd, STDOUT_FILENO) to atomically rebind slot 1 onto log_fd (guarding fd != 1 if using dup3).
- Step 3. Emit redirected output and call fflush(stdout) BEFORE restoring slot 1 so _IOFBF bytes land in log_fd.
- Step 4. Restore dup2(saved_out, STDOUT_FILENO) and close(saved_out) so terminal f_count returns cleanly to 1.
Figure 4.1d. 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.
Figure 4.1d. Kernel descriptor-to-file-to-inode topologies across dual open(), dup/dup2/dup3, fork(), and leak-free STDOUT redirection.
dup(2) / dup2(2) / dup3(2) Contracts & Safe STDOUT_FILENO Redirection
Define #define _GNU_SOURCE before <unistd.h> and <fcntl.h> on Linux 6.12 to expose dup3(). Notice why dup3(fd, fd, O_CLOEXEC) intentionally fails with EINVAL: POSIX forced dup2(fd, fd) to be a no-op, which tragically leaves FD_CLOEXEC unchanged if a caller mistakenly assumed dup2 cleared it; dup3 closed that design flaw by rejecting oldfd == newfd outright. When temporarily redirecting STDOUT_FILENO, always follow the four-step cycle: saved = dup(STDOUT_FILENO) -> fflush(stdout) + dup2(target_fd, STDOUT_FILENO) -> emit output + fflush(stdout) -> dup2(saved, STDOUT_FILENO) + close(saved).
Proving Dual-Open Overwrites, dup3 Slot Isolation & stdout Restore
Save dual_open_dup.c below. It contrasts dual open() without O_APPEND (8 overwritten bytes "BBBBBBBB") against dual open() with O_APPEND (16 concatenated bytes "AABBAABBAABBAABB"), verifies dup() shared f_pos == 8, tests dup2(fd, fd) no-op vs dup3(fd, fd, O_CLOEXEC) EINVAL, proves per-slot O_CLOEXEC (0/1) via /proc/self/fdinfo/, and executes a full STDOUT_FILENO save-redirect-fflush-restore cycle!
learner@ksa:~/gl-c01/m04-l01$ bat -H 25 -H 73 -H 86 dual_open_dup.c File: dual_open_dup.c #define _GNU_SOURCE #include <errno.h> #include <fcntl.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <sys/stat.h> #include <unistd.h> static int has_cloexec_fdinfo(int target_fd) { char p[64], buf[256]; snprintf(p, sizeof(p), "/proc/self/fdinfo/%d", target_fd); int ifd = open(p, O_RDONLY | O_CLOEXEC); if (ifd < 0) return 0; ssize_t n = read(ifd, buf, sizeof(buf) - 1U); (void)close(ifd); if (n <= 0) return 0; buf[n] = '\0'; const char *f = strstr(buf, "flags:"); unsigned long fl = (f != NULL) ? strtoul(f + 6, NULL, 8) : 0UL; return ((fl & (unsigned long)O_CLOEXEC) != 0UL) ? 1 : 0; } static int run_dual_writes(const char *path, int extra_flags, char *out, size_t cap) { int base = O_RDWR | O_CREAT | O_TRUNC | O_CLOEXEC | extra_flags; int fd1 = open(path, base, 0644); int fd2 = open(path, O_RDWR | O_CLOEXEC | extra_flags); if (fd1 < 0 || fd2 < 0) return -1; struct stat s1, s2; if (fstat(fd1, &s1) < 0 || fstat(fd2, &s2) < 0 || s1.st_ino != s2.st_ino) { (void)close(fd1); (void)close(fd2); return -1; } for (int i = 0; i < 4; i++) { if (write(fd1, "AA", 2) != 2 || write(fd2, "BB", 2) != 2) { (void)close(fd1); (void)close(fd2); return -1; } } if (lseek(fd1, 0, SEEK_SET) < 0) return -1; ssize_t n = read(fd1, out, cap - 1U); (void)close(fd2); (void)close(fd1); (void)unlink(path); if (n < 0) return -1; out[n] = '\0'; return (int)n; } int main(void) { char over_buf[32] = {0}, app_buf[32] = {0}; int n_over = run_dual_writes("/tmp/ksa_m04_l01_over.bin", 0, over_buf, sizeof(over_buf)); int n_app = run_dual_writes("/tmp/ksa_m04_l01_app.bin", O_APPEND, app_buf, sizeof(app_buf)); if (n_over < 0 || n_app < 0) return 1; const char *rpath = "/tmp/ksa_m04_l01_redir.txt"; int fd = open(rpath, O_RDWR | O_CREAT | O_TRUNC, 0644); if (fd < 0) return 1; int alias = dup(fd); if (alias < 0) return 1; if (write(fd, "KSA-", 4) != 4 || write(alias, "DUP|", 4) != 4) return 1; off_t shared_pos = lseek(fd, 0, SEEK_CUR); int same_dup2 = dup2(fd, fd); errno = 0; int same_dup3 = dup3(fd, fd, O_CLOEXEC); int dup3_err = errno; int clo_fd = dup3(fd, 42, O_CLOEXEC); if (clo_fd != 42) return 1; int orig_clo = has_cloexec_fdinfo(fd); int dup3_clo = has_cloexec_fdinfo(clo_fd); (void)close(clo_fd); (void)close(alias); fflush(stdout); int saved_out = dup(STDOUT_FILENO); if (saved_out < 0 || dup2(fd, STDOUT_FILENO) < 0) return 1; printf("STDOUT_CAPTURED"); fflush(stdout); if (dup2(saved_out, STDOUT_FILENO) < 0) return 1; (void)close(saved_out); char cap_buf[64] = {0}; if (lseek(fd, 0, SEEK_SET) < 0) return 1; ssize_t cn = read(fd, cap_buf, sizeof(cap_buf) - 1U); (void)close(fd); (void)unlink(rpath); if (cn < 0) return 1; printf("dual_no_append: bytes=%d payload=%s\n", n_over, over_buf); printf("dual_o_append: bytes=%d payload=%s\n", n_app, app_buf); printf("dup_cursor: shared_f_pos=%lld dup2_self=%s " "dup3_self_einval=%s cloexec=%d/%d\n", (long long)shared_pos, (same_dup2 == fd) ? "noop" : "err", (same_dup3 == -1 && dup3_err == EINVAL) ? "yes" : "no", orig_clo, dup3_clo); printf("redir_restored: captured=%s\n", cap_buf); return 0; }- Two open() calls create independent struct file cursors; without O_APPEND, fd2's write at f_pos=0 overwrites fd1's bytes.
- dup2(fd, fd) is a POSIX no-op returning fd, whereas Linux dup3(fd, fd, O_CLOEXEC) returns -1 with errno == EINVAL.
- Flush stdout BEFORE restoring saved_out onto STDOUT_FILENO so buffered printf bytes land in the capture file, not the terminal.
Verifying Cursor Topologies and Clean Redirection Restore
Compile and execute dual_open_dup: confirm dual_no_append clobbers down to 8 bytes (BBBBBBBB), dual_o_append preserves all 16 bytes, dup advances shared_f_pos=8 with cloexec=0/1, and printf("STDOUT_CAPTURED") lands inside cap_buf before STDOUT_FILENO returns to your terminal!
learner@ksa:~/gl-c01/m04-l01gcc -fdiagnostics-color=always -std=c11 -Wall -Wextra -Werror dual_open_dup.c -o dual_open_duplearner@ksa:~/gl-c01/m04-l01./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-l01test ! -e /tmp/ksa_m04_l01_over.bin && test ! -e /tmp/ksa_m04_l01_app.bin && rm -f dual_open_duplearner@ksa:~/gl-c01/m04-l01Tracing f_count Lifetimes Across Redirection Boundaries
Notice how dup2(fd, STDOUT_FILENO) atomically closed descriptor 1's terminal reference and bound slot 1 onto fd's struct file (f_pos == 8), so printf("STDOUT_CAPTURED") + fflush(stdout) appended 15 bytes at [8..22] (KSA-DUP|STDOUT_CAPTURED)! Rebinding saved_out back onto slot 1 and closing saved_out restored f_count == 1 on the terminal description with zero leaked handles.
Guided Practice: Writing a Self-Safe move_fd_cloexec() Helper
Write a helper int move_fd_cloexec(int src_fd, int dst_fd) that moves src_fd onto dst_fd with FD_CLOEXEC guaranteed 1 on dst_fd even when src_fd == dst_fd:
- Step 1 (Handle
src_fd != dst_fd): Calldup3(src_fd, dst_fd, O_CLOEXEC)(retrying onEINTR), and if it succeeds, callclose(src_fd)once and returndst_fd. - Step 2 (Handle
src_fd == dst_fdwithoutEINVAL): Whensrc_fd == dst_fd, skipdup3()and callfcntl(dst_fd, F_SETFD, FD_CLOEXEC)(returning-1ifdst_fdis invalid,EBADF) so self-redirection never fails!
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.log 2>&1: save both STDOUT_FILENO and STDERR_FILENO via dup(), bind a scratch log file onto 1 and 2 via dup2(), write interleaved printf() and fprintf(stderr, ...) lines, flush and restore both standard descriptors, and verify in memory that both streams concatenated without overwriting one another (shared struct file!).
Common Production Pitfalls
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.
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.
Knowledge Check
? check 1 · 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?
- [x]
0, because the secondopen()allocated an independentstruct filewhosef_posinitialized to0 - [ ]
4, because both descriptors reference the samestruct inodein the page cache - [ ]
64, because secondaryopen()calls default to end-of-file
Answer: 0, because the second open() allocated an independent struct file whose f_pos initialized to 0
Why: 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.
? check 2 · 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?
- [ ] Both
f_posandFD_CLOEXECare shared identically acrossfd1andfd2 - [x]
f_posandstruct filestatus flags (O_APPEND,O_NONBLOCK) are shared, whileFD_CLOEXECis set only onfd2's descriptor slot - [ ] Neither
f_posnorFD_CLOEXECis shared;dup3()allocates a separatestruct file
Answer: f_pos and struct file status flags (O_APPEND, O_NONBLOCK) are shared, while FD_CLOEXEC is set only on fd2's descriptor slot
Why: 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.
? check 3 · (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?
- [ ] Call
write(fd1, buf, 16)from byte0becausefd1kept its own offset - [x] Call
write(fd1, buf + 10, 6)becausefd0andfd1alias onestruct filewhosef_posalready advanced to10 - [ ] Abort because short counts on regular files always set
errno = ESPIPE
Answer: Call write(fd1, buf + 10, 6) because fd0 and fd1 alias one struct file whose f_pos already advanced to 10
Why: 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.
? check 4 · What is the exact runtime difference between dup2(5, 5) and dup3(5, 5, O_CLOEXEC) when descriptor 5 is a valid open file?
- [ ] Both calls succeed and return
5withFD_CLOEXECset on slot5 - [x]
dup2(5, 5)succeeds as a POSIX no-op returning5(leavingFD_CLOEXECunchanged), whereasdup3(5, 5, O_CLOEXEC)fails with-1anderrno == EINVAL - [ ]
dup2(5, 5)closes descriptor5permanently and returns-1(EBADF)
Answer: dup2(5, 5) succeeds as a POSIX no-op returning 5 (leaving FD_CLOEXEC unchanged), whereas dup3(5, 5, O_CLOEXEC) fails with -1 and errno == EINVAL
Why: 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.
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.
Next, we eliminate multi-process creation races (TOCTOU) and multithreaded shared-cursor races using O_CREAT | O_EXCL, directory-pinned openat(), and stateless pread() / pwrite().
Step sequence — frame strip: steps_m04_l01
Flush stdout first and call saved_out = dup(STDOUT_FILENO) to increment the terminal struct file's f_count to 2.
reveals: step1
highlights: step1
Call dup2(log_fd, STDOUT_FILENO) to atomically rebind slot 1 onto log_fd (guarding fd != 1 if using dup3).
reveals: step2
highlights: step2
Emit redirected output and call fflush(stdout) BEFORE restoring slot 1 so _IOFBF bytes land in log_fd.
reveals: step3
highlights: step3
Restore dup2(saved_out, STDOUT_FILENO) and close(saved_out) so terminal f_count returns cleanly to 1.
reveals: step4
highlights: step4
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.
Why Two-Syscall Sequences Fail Under Preemption
On a preemptive Symmetric Multiprocessing (SMP) Linux kernel, a hardware timer interrupt or higher-priority wakeup can suspend your thread at the exact nanosecond boundary between any two user-space system calls. Two classic anti-patterns fail catastrophically across that gap. First, a privileged daemon runs if (access("/tmp/run.pid", F_OK) == -1) fd = open("/tmp/run.pid", O_WRONLY | O_CREAT | O_TRUNC, 0600);: an unprivileged local user plants a symlink /tmp/run.pid -> /etc/crontab in the microsecond between access() and open(), tricking the root daemon into truncating /etc/crontab! Second, two threads sharing one int fd run lseek(fd, slot_off, SEEK_SET); write(fd, rec, 64);: Thread B's lseek() preempts Thread A before Thread A's write(), diverting Thread A's record onto Thread B's slot and extending the file unexpectedly!
User-space mutexes cannot coordinate independent processes, and two-syscall sequences cannot close kernel path-walk races. Eliminating Time-Of-Check to Time-Of-Use (TOCTOU) and cursor-clobber bugs requires fusing check-and-act into a single atomic VFS operation.
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.
definition (TOCTOU, Positional I/O (pread/pwrite) & Directory-Pinned *at() Calls): 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.
Figure 4.2a. Scheduler preemption between lseek() and write() clobbers shared cursors; stateless pread()/pwrite() and directory-pinned *at() calls close race windows.
Figure 4.2b. Time-of-check-to-time-of-use file-creation race between two processes versus atomic O_CREAT | O_EXCL.
One Layer Down: kiocb.ki_pos vs f_pos_lock & Retry Offset Math
Look inside fs/read_write.c (ksys_pread64 vs ksys_read) to see why pread() scales linearly across CPU cores while lseek() + read() serializes and races. Normal ksys_read() acquires file->f_pos_lock on every call just to snapshot and update file->f_pos—creating cache-line contention across 8 worker threads sharing one fd even if a user mutex wraps lseek + read! By contrast, ksys_pread64() never touches file->f_pos_lock or file->f_pos: it initializes a kernel-stack struct kiocb directly with your offset parameter and dispatches straight to the page cache. When wrapping pread() / pwrite() against short counts or EINTR, advance both the buffer pointer and explicit byte coordinate by done: p_next = p + done, off_next = off + (off_t)done, and rem = len - done.
| Broken Two-Syscall Sequence | Preemption Race Hazard | Atomic Single-Syscall Idiom | Kernel Lock / Cursor Guarantee | ||||
|---|---|---|---|---|---|---|---|
access(p, F_OK) -> open(p, O_CREAT) | Symlink hijack or dual winner | `openat(dfd, name, O_WRONLY\ | O_CREAT\ | O_EXCL\ | O_NOFOLLOW\ | O_CLOEXEC, 0600)` | Parent i_rwsem; loser gets -1 (EEXIST) |
lseek(fd, off, SEEK_SET) -> write | Shared f_pos clobbered mid-flight | pwrite(fd, buf, n, off) / pread(fd, buf, n, off) | Zero f_pos touch; zero f_pos_lock contention | ||||
lseek(fd, 0, SEEK_END) -> write | Concurrent writer overwritten at tail | `open(..., O_WRONLY\ | O_APPEND) + write()` | Target inode->i_rwsem sets ki_pos = i_size | |||
In-place config overwrite (O_TRUNC) | Torn half-written file on crash | openat(O_EXCL) -> write -> fdatasync -> renameat -> fsync(dfd) | Readers see either old or complete new file |
- Step 1. Pin an O_DIRECTORY descriptor dfd and create staging files via openat(..., O_CREAT | O_EXCL | O_NOFOLLOW | O_CLOEXEC, 0600).
- Step 2. Transfer fixed-offset records via stateless pwrite_full(), advancing both p + done and off + done on short counts.
- Step 3. Commit staged file blocks via fdatasync(tfd) and verify close(tfd) == 0 before publishing.
- Step 4. Atomically swap the directory entry with renameat(dfd, tmp, dfd, final) and persist via fsync(dfd).
Figure 4.2c. Fuse check-and-act inside single atomic kernel syscalls: openat(O_CREAT|O_EXCL), stateless pread/pwrite, and renameat + fsync(dfd).
pread(2) / pwrite(2) Reference & the Linux O_APPEND Quirk
Define #define _POSIX_C_SOURCE 200809L and #define _FILE_OFFSET_BITS 64 before <unistd.h> and <fcntl.h>. Memorize one critical Linux kernel deviation documented in man 2 pwrite: POSIX states pwrite() writes at offset regardless of O_APPEND, but on Linux, if fd has O_APPEND set, pwrite() ignores offset and appends to EOF! Always keep O_APPEND clear on descriptors used for random-access pwrite() slot updates.
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. EINVAL offset is negative (or unaligned when O_DIRECT is active). EINTR Interrupted by signal before any bytes transferred. ESPIPE fd refers to a pipe, FIFO, or socket. BUGS On Linux, pwrite() on an O_APPEND descriptor ignores offset and appends! SEE ALSO fdatasync(2), lseek(2), openat(2), read(2), write(2) Kernel Systems Academy Lesson 4.2 pread(2) GL-C01 quick reference · full manual page: man 2 pread Reproducing Cursor Races vs Stateless pread/pwrite & atomic_replace_at
Save atomic_idioms.c below. It proves O_CREAT | O_EXCL rejects a rival creator with EEXIST, reproduces the exact lseek + write shared-cursor clobber (slot0=00000000, unexpected_size=24), fixes it via pwrite_full() and pread() across slots 0 and 8 while f_pos stays parked at 4, verifies cooperating O_APPEND writes, and executes directory-pinned atomic_replace_at() (openat + fdatasync + renameat + fsync(dfd)).
learner@ksa:~/gl-c01/m04-l02$ bat -H 14 -H 28 -H 69 atomic_idioms.c File: atomic_idioms.c #define _FILE_OFFSET_BITS 64 #define _POSIX_C_SOURCE 200809L #include <errno.h> #include <fcntl.h> #include <stdint.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <unistd.h> static int pwrite_full(int fd, const void *buf, size_t len, off_t off) { const uint8_t *p = (const uint8_t *)buf; size_t done = 0U; while (done < len) { ssize_t n = pwrite(fd, p + done, len - done, off + (off_t)done); if (n < 0) { if (errno == EINTR) continue; return -1; } done += (size_t)n; } return 0; } static int atomic_replace_at(int dfd, const char *tmp_name, const char *final_name, const char *payload) { int flags = O_WRONLY | O_CREAT | O_EXCL | O_NOFOLLOW | O_CLOEXEC; int tfd = openat(dfd, tmp_name, flags, 0600); if (tfd < 0) return -1; size_t len = strlen(payload); if (write(tfd, payload, len) != (ssize_t)len || fdatasync(tfd) != 0) { (void)close(tfd); (void)unlinkat(dfd, tmp_name, 0); return -1; } if (close(tfd) != 0) { (void)unlinkat(dfd, tmp_name, 0); return -1; } if (renameat(dfd, tmp_name, dfd, final_name) != 0 || fsync(dfd) != 0) { (void)unlinkat(dfd, tmp_name, 0); return -1; } return 0; } int main(void) { const char *lpath = "/tmp/ksa_m04_l02.lock"; const char *dpath = "/tmp/ksa_m04_l02_slots.bin"; (void)unlink(lpath); int lk1 = open(lpath, O_WRONLY | O_CREAT | O_EXCL | O_CLOEXEC, 0600); if (lk1 < 0) return 1; errno = 0; int lk2 = open(lpath, O_WRONLY | O_CREAT | O_EXCL | O_CLOEXEC, 0600); int lk2_err = errno; (void)close(lk1); (void)unlink(lpath); printf("excl_create: second_ret=%d eexist=%s\n", lk2, (lk2 == -1 && lk2_err == EEXIST) ? "yes" : "no"); int fd_a = open(dpath, O_RDWR | O_CREAT | O_TRUNC | O_CLOEXEC, 0644); int fd_b = (fd_a >= 0) ? dup(fd_a) : -1; if (fd_a < 0 || fd_b < 0 || write(fd_a, "0000000011111111", 16) != 16) return 1; if (lseek(fd_a, 0, SEEK_SET) < 0) return 1; if (lseek(fd_b, 8, SEEK_SET) < 0) return 1; if (write(fd_b, "BBBBBBBB", 8) != 8) return 1; if (write(fd_a, "AAAAAAAA", 8) != 8) return 1; char racy_slot0[9] = {0}; if (pread(fd_a, racy_slot0, 8, 0) != 8) return 1; off_t racy_end = lseek(fd_a, 0, SEEK_END); printf("racy_lseek: slot0=%s unexpected_size=%lld\n", racy_slot0, (long long)racy_end); (void)close(fd_b); (void)close(fd_a); fd_a = open(dpath, O_RDWR | O_TRUNC | O_CLOEXEC); fd_b = (fd_a >= 0) ? dup(fd_a) : -1; if (fd_a < 0 || fd_b < 0 || write(fd_a, "0000000011111111", 16) != 16) return 1; if (lseek(fd_a, 4, SEEK_SET) != 4) return 1; if (pwrite_full(fd_a, "SLOT0_OK", 8, 0) < 0 || pwrite_full(fd_b, "SLOT1_OK", 8, 8) < 0) return 1; char s0[9] = {0}, s1[9] = {0}; if (pread(fd_a, s0, 8, 0) != 8 || pread(fd_b, s1, 8, 8) != 8) return 1; off_t parked = lseek(fd_a, 0, SEEK_CUR); printf("atomic_pio: s0=%s s1=%s parked_f_pos=%lld\n", s0, s1, (long long)parked); (void)close(fd_b); (void)close(fd_a); int ap1 = open(dpath, O_WRONLY | O_TRUNC | O_APPEND | O_CLOEXEC); int ap2 = open(dpath, O_WRONLY | O_APPEND | O_CLOEXEC); if (ap1 < 0 || ap2 < 0 || write(ap1, "REC1|", 5) != 5 || write(ap2, "REC2", 4) != 4) return 1; (void)close(ap1); (void)close(ap2); int rd = open(dpath, O_RDONLY | O_CLOEXEC); char logbuf[16] = {0}; ssize_t ln = (rd >= 0) ? read(rd, logbuf, sizeof(logbuf) - 1U) : -1; if (rd >= 0) (void)close(rd); (void)unlink(dpath); if (ln != 9) return 1; int dfd = open("/tmp", O_RDONLY | O_DIRECTORY | O_CLOEXEC); if (dfd < 0) return 1; (void)unlinkat(dfd, "ksa_m04_cfg.tmp", 0); (void)unlinkat(dfd, "ksa_m04_cfg.v1", 0); int rep_ok = (atomic_replace_at(dfd, "ksa_m04_cfg.tmp", "ksa_m04_cfg.v1", "COMMIT_V2") == 0); (void)unlinkat(dfd, "ksa_m04_cfg.v1", 0); (void)close(dfd); printf("atomic_append: bytes=%zd log=%s replace_at=%d\n", ln, logbuf, rep_ok); return 0; }- Advance BOTH p + done and off + (off_t)done on partial pwrite() progress because pwrite() never updates f_pos.
- Pin openat/fdatasync/renameat/fsync(dfd) to an open O_DIRECTORY descriptor to eliminate path-prefix symlink races.
- Interleaved lseek(fd_b, 8, SEEK_SET) diverts fd_a's write() to offset 16; stateless pwrite_full() leaves parked f_pos=4 untouched.
Verifying Stateless pread64/pwrite64 Under strace
Compile and run atomic_idioms, verify racy_lseek vs atomic_pio (parked_f_pos=4) and replace_at=1, and inspect openat, pwrite64, and pread64 under strace.
learner@ksa:~/gl-c01/m04-l02gcc -fdiagnostics-color=always -std=c11 -Wall -Wextra -Werror atomic_idioms.c -o atomic_idiomslearner@ksa:~/gl-c01/m04-l02./atomic_idiomsexcl_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-l02test ! -e /tmp/ksa_m04_l02.lock && test ! -e /tmp/ksa_m04_l02_slots.binlearner@ksa:~/gl-c01/m04-l02Under strace, observe O_CREAT|O_EXCL returning -1 EEXIST on the second lock attempt and pwrite64/pread64 passing explicit byte coordinates 0 and 8 in a single trap.
learner@ksa:~/gl-c01/m04-l02strace strace -e \trace=openat,pwrite64,pread64,unlink,unlinkat,close ./atomic_idiomsexecve("/usr/bin/strace", ["strace", "-e", "trace=openat,pwrite64,pread64,un"..., "./atomic_idioms"], 0x7ffee2b11df8 /* 161 vars */) = 0brk(NULL) = 0x63a811e23000mmap(NULL, 8192, PROT_READ|PROT_WRITE, MAP_PRIVATE|MAP_ANONYMOUS, -1, 0) = 0x7f1f21f7a000access("/etc/ld.so.preload", R_OK) = -1 ENOENT (No such file or directory)openat(AT_FDCWD, "/etc/ld.so.cache", O_RDONLY|O_CLOEXEC) = 3fstat(3, {st_mode=S_IFREG|0644, st_size=147944, ...}) = 0mmap(NULL, 147944, PROT_READ, MAP_PRIVATE, 3, 0) = 0x7f1f21f55000close(3) = 0openat(AT_FDCWD, "/lib/x86_64-linux-gnu/libunwind-ptrace.so.0", O_RDONLY|O_CLOEXEC) = 3read(3, "\177ELF\2\1\1\0\0\0\0\0\0\0\0\0\3\0>\0\1\0\0\0\0\0\0\0\0\0\0\0"..., 832) = 832fstat(3, {st_mode=S_IFREG|0644, st_size=18656, ...}) = 0mmap(NULL, 20808, PROT_READ, MAP_PRIVATE|MAP_DENYWRITE, 3, 0) = 0x7f1f21f4f000mmap(0x7f1f21f50000, 8192, PROT_READ|PROT_EXEC, MAP_PRIVATE|MAP_FIXED|MAP_DENYWRITE, 3, 0x1000) = 0x7f1f21f50000mmap(0x7f1f21f52000, 4096, PROT_READ, MAP_PRIVATE|MAP_FIXED|MAP_DENYWRITE, 3, 0x3000) = 0x7f1f21f52000mmap(0x7f1f21f53000, 8192, PROT_READ|PROT_WRITE, MAP_PRIVATE|MAP_FIXED|MAP_DENYWRITE, 3, 0x3000) = 0x7f1f21f53000close(3) = 0openat(AT_FDCWD, "/lib/x86_64-linux-gnu/libunwind-x86_64.so.8", O_RDONLY|O_CLOEXEC) = 3read(3, "\177ELF\2\1\1\0\0\0\0\0\0\0\0\0\3\0>\0\1\0\0\0\0\0\0\0\0\0\0\0"..., 832) = 832fstat(3, {st_mode=S_IFREG|0644, st_size=67672, ...}) = 0mmap(NULL, 113136, PROT_READ, MAP_PRIVATE|MAP_DENYWRITE, 3, 0) = 0x7f1f21f33000mmap(0x7f1f21f35000, 49152, PROT_READ|PROT_EXEC, MAP_PRIVATE|MAP_FIXED|MAP_DENYWRITE, 3, 0x2000) = 0x7f1f21f35000mmap(0x7f1f21f41000, 8192, PROT_READ, MAP_PRIVATE|MAP_FIXED|MAP_DENYWRITE, 3, 0xe000) = 0x7f1f21f41000mmap(0x7f1f21f43000, 8192, PROT_READ|PROT_WRITE, MAP_PRIVATE|MAP_FIXED|MAP_DENYWRITE, 3, 0xf000) = 0x7f1f21f43000mmap(0x7f1f21f45000, 39408, PROT_READ|PROT_WRITE, MAP_PRIVATE|MAP_FIXED|MAP_ANONYMOUS, -1, 0) = 0x7f1f21f45000close(3) = 0openat(AT_FDCWD, "/lib/x86_64-linux-gnu/libc.so.6", O_RDONLY|O_CLOEXEC) = 3read(3, "\177ELF\2\1\1\3\0\0\0\0\0\0\0\0\3\0>\0\1\0\0\0\220\243\2\0\0\0\0\0"..., 832) = 832pread64(3, "\6\0\0\0\4\0\0\0@\0\0\0\0\0\0\0@\0\0\0\0\0\0\0@\0\0\0\0\0\0\0"..., 784, 64) = 784fstat(3, {st_mode=S_IFREG|0755, st_size=2129424, ...}) = 0pread64(3, "\6\0\0\0\4\0\0\0@\0\0\0\0\0\0\0@\0\0\0\0\0\0\0@\0\0\0\0\0\0\0"..., 784, 64) = 784mmap(NULL, 2174352, PROT_READ, MAP_PRIVATE|MAP_DENYWRITE, 3, 0) = 0x7f1f21c00000mmap(0x7f1f21c28000, 1609728, PROT_READ|PROT_EXEC, MAP_PRIVATE|MAP_FIXED|MAP_DENYWRITE, 3, 0x28000) = 0x7f1f21c28000mmap(0x7f1f21db1000, 323584, PROT_READ, MAP_PRIVATE|MAP_FIXED|MAP_DENYWRITE, 3, 0x1b1000) = 0x7f1f21db1000mmap(0x7f1f21e00000, 24576, PROT_READ|PROT_WRITE, MAP_PRIVATE|MAP_FIXED|MAP_DENYWRITE, 3, 0x1ff000) = 0x7f1f21e00000mmap(0x7f1f21e06000, 52624, PROT_READ|PROT_WRITE, MAP_PRIVATE|MAP_FIXED|MAP_ANONYMOUS, -1, 0) = 0x7f1f21e06000close(3) = 0openat(AT_FDCWD, "/lib/x86_64-linux-gnu/liblzma.so.5", O_RDONLY|O_CLOEXEC) = 3read(3, "\177ELF\2\1\1\0\0\0\0\0\0\0\0\0\3\0>\0\1\0\0\0\0\0\0\0\0\0\0\0"..., 832) = 832fstat(3, {st_mode=S_IFREG|0644, st_size=202904, ...}) = 0mmap(NULL, 200728, PROT_READ, MAP_PRIVATE|MAP_DENYWRITE, 3, 0) = 0x7f1f21f01000mmap(0x7f1f21f04000, 139264, PROT_READ|PROT_EXEC, MAP_PRIVATE|MAP_FIXED|MAP_DENYWRITE, 3, 0x3000) = 0x7f1f21f04000mmap(0x7f1f21f26000, 45056, PROT_READ, MAP_PRIVATE|MAP_FIXED|MAP_DENYWRITE, 3, 0x25000) = 0x7f1f21f26000mmap(0x7f1f21f31000, 8192, PROT_READ|PROT_WRITE, MAP_PRIVATE|MAP_FIXED|MAP_DENYWRITE, 3, 0x30000) = 0x7f1f21f31000close(3) = 0openat(AT_FDCWD, "/lib/x86_64-linux-gnu/libunwind.so.8", O_RDONLY|O_CLOEXEC) = 3read(3, "\177ELF\2\1\1\0\0\0\0\0\0\0\0\0\3\0>\0\1\0\0\0\0\0\0\0\0\0\0\0"..., 832) = 832fstat(3, {st_mode=S_IFREG|0644, st_size=63776, ...}) = 0mmap(NULL, 109328, PROT_READ, MAP_PRIVATE|MAP_DENYWRITE, 3, 0) = 0x7f1f21ee6000mmap(0x7f1f21ee9000, 40960, PROT_READ|PROT_EXEC, MAP_PRIVATE|MAP_FIXED|MAP_DENYWRITE, 3, 0x3000) = 0x7f1f21ee9000mmap(0x7f1f21ef3000, 8192, PROT_READ, MAP_PRIVATE|MAP_FIXED|MAP_DENYWRITE, 3, 0xd000) = 0x7f1f21ef3000mmap(0x7f1f21ef5000, 8192, PROT_READ|PROT_WRITE, MAP_PRIVATE|MAP_FIXED|MAP_DENYWRITE, 3, 0xe000) = 0x7f1f21ef5000mmap(0x7f1f21ef7000, 39696, PROT_READ|PROT_WRITE, MAP_PRIVATE|MAP_FIXED|MAP_ANONYMOUS, -1, 0) = 0x7f1f21ef7000close(3) = 0mmap(NULL, 8192, PROT_READ|PROT_WRITE, MAP_PRIVATE|MAP_ANONYMOUS, -1, 0) = 0x7f1f21ee4000arch_prctl(ARCH_SET_FS, 0x7f1f21ee5380) = 0set_tid_address(0x7f1f21ee5650) = 2867282set_robust_list(0x7f1f21ee5660, 24) = 0rseq(0x7f1f21ee5ca0, 0x20, 0, 0x53053053) = 0mprotect(0x7f1f21e00000, 16384, PROT_READ) = 0mprotect(0x7f1f21f31000, 4096, PROT_READ) = 0mprotect(0x7f1f21ef5000, 4096, PROT_READ) = 0mprotect(0x7f1f21f43000, 4096, PROT_READ) = 0mprotect(0x7f1f21f53000, 4096, PROT_READ) = 0mprotect(0x63a80d05c000, 417792, PROT_READ) = 0mprotect(0x7f1f21fba000, 8192, PROT_READ) = 0prlimit64(0, RLIMIT_STACK, NULL, {rlim_cur=8192*1024, rlim_max=RLIM64_INFINITY}) = 0munmap(0x7f1f21f55000, 147944) = 0getrandom("\x69\xc6\x86\xcd\xf1\xe6\xfd\x91", 8, GRND_NONBLOCK) = 8brk(NULL) = 0x63a811e23000brk(0x63a811e44000) = 0x63a811e44000openat(AT_FDCWD, "/usr/lib/locale/locale-archive", O_RDONLY|O_CLOEXEC) = 3fstat(3, {st_mode=S_IFREG|0644, st_size=5719296, ...}) = 0mmap(NULL, 5719296, PROT_READ, MAP_PRIVATE, 3, 0) = 0x7f1f21600000close(3) = 0openat(AT_FDCWD, "/usr/share/locale/locale.alias", O_RDONLY|O_CLOEXEC) = 3fstat(3, {st_mode=S_IFREG|0644, st_size=2996, ...}) = 0read(3, "# Locale name alias data base.\n#"..., 4096) = 2996read(3, "", 4096) = 0close(3) = 0openat(AT_FDCWD, "/usr/lib/locale/C.UTF-8/LC_IDENTIFICATION", O_RDONLY|O_CLOEXEC) = -1 ENOENT (No such file or directory)openat(AT_FDCWD, "/usr/lib/locale/C.utf8/LC_IDENTIFICATION", O_RDONLY|O_CLOEXEC) = 3fstat(3, {st_mode=S_IFREG|0644, st_size=258, ...}) = 0mmap(NULL, 258, PROT_READ, MAP_PRIVATE, 3, 0) = 0x7f1f21f79000close(3) = 0openat(AT_FDCWD, "/usr/lib/x86_64-linux-gnu/gconv/gconv-modules.cache", O_RDONLY|O_CLOEXEC) = 3fstat(3, {st_mode=S_IFREG|0644, st_size=27028, ...}) = 0mmap(NULL, 27028, PROT_READ, MAP_SHARED, 3, 0) = 0x7f1f21f72000close(3) = 0futex(0x7f1f21e0572c, FUTEX_WAKE_PRIVATE, 2147483647) = 0openat(AT_FDCWD, "/usr/lib/locale/C.UTF-8/LC_MEASUREMENT", O_RDONLY|O_CLOEXEC) = -1 ENOENT (No such file or directory)openat(AT_FDCWD, "/usr/lib/locale/C.utf8/LC_MEASUREMENT", O_RDONLY|O_CLOEXEC) = 3fstat(3, {st_mode=S_IFREG|0644, st_size=23, ...}) = 0mmap(NULL, 23, PROT_READ, MAP_PRIVATE, 3, 0) = 0x7f1f21f71000close(3) = 0openat(AT_FDCWD, "/usr/lib/locale/C.UTF-8/LC_TELEPHONE", O_RDONLY|O_CLOEXEC) = -1 ENOENT (No such file or directory)openat(AT_FDCWD, "/usr/lib/locale/C.utf8/LC_TELEPHONE", O_RDONLY|O_CLOEXEC) = 3fstat(3, {st_mode=S_IFREG|0644, st_size=47, ...}) = 0mmap(NULL, 47, PROT_READ, MAP_PRIVATE, 3, 0) = 0x7f1f21f70000close(3) = 0openat(AT_FDCWD, "/usr/lib/locale/C.UTF-8/LC_ADDRESS", O_RDONLY|O_CLOEXEC) = -1 ENOENT (No such file or directory)openat(AT_FDCWD, "/usr/lib/locale/C.utf8/LC_ADDRESS", O_RDONLY|O_CLOEXEC) = 3fstat(3, {st_mode=S_IFREG|0644, st_size=127, ...}) = 0mmap(NULL, 127, PROT_READ, MAP_PRIVATE, 3, 0) = 0x7f1f21f6f000close(3) = 0openat(AT_FDCWD, "/usr/lib/locale/C.UTF-8/LC_NAME", O_RDONLY|O_CLOEXEC) = -1 ENOENT (No such file or directory)openat(AT_FDCWD, "/usr/lib/locale/C.utf8/LC_NAME", O_RDONLY|O_CLOEXEC) = 3fstat(3, {st_mode=S_IFREG|0644, st_size=62, ...}) = 0mmap(NULL, 62, PROT_READ, MAP_PRIVATE, 3, 0) = 0x7f1f21f6e000close(3) = 0openat(AT_FDCWD, "/usr/lib/locale/C.UTF-8/LC_PAPER", O_RDONLY|O_CLOEXEC) = -1 ENOENT (No such file or directory)openat(AT_FDCWD, "/usr/lib/locale/C.utf8/LC_PAPER", O_RDONLY|O_CLOEXEC) = 3fstat(3, {st_mode=S_IFREG|0644, st_size=34, ...}) = 0mmap(NULL, 34, PROT_READ, MAP_PRIVATE, 3, 0) = 0x7f1f21f6d000close(3) = 0openat(AT_FDCWD, "/usr/lib/locale/C.UTF-8/LC_MESSAGES", O_RDONLY|O_CLOEXEC) = -1 ENOENT (No such file or directory)openat(AT_FDCWD, "/usr/lib/locale/C.utf8/LC_MESSAGES", O_RDONLY|O_CLOEXEC) = 3fstat(3, {st_mode=S_IFDIR|0755, st_size=4096, ...}) = 0close(3) = 0openat(AT_FDCWD, "/usr/lib/locale/C.utf8/LC_MESSAGES/SYS_LC_MESSAGES", O_RDONLY|O_CLOEXEC) = 3fstat(3, {st_mode=S_IFREG|0644, st_size=48, ...}) = 0mmap(NULL, 48, PROT_READ, MAP_PRIVATE, 3, 0) = 0x7f1f21f6c000close(3) = 0openat(AT_FDCWD, "/usr/lib/locale/C.UTF-8/LC_MONETARY", O_RDONLY|O_CLOEXEC) = -1 ENOENT (No such file or directory)openat(AT_FDCWD, "/usr/lib/locale/C.utf8/LC_MONETARY", O_RDONLY|O_CLOEXEC) = 3fstat(3, {st_mode=S_IFREG|0644, st_size=270, ...}) = 0mmap(NULL, 270, PROT_READ, MAP_PRIVATE, 3, 0) = 0x7f1f21f6b000close(3) = 0openat(AT_FDCWD, "/usr/lib/locale/C.UTF-8/LC_COLLATE", O_RDONLY|O_CLOEXEC) = -1 ENOENT (No such file or directory)openat(AT_FDCWD, "/usr/lib/locale/C.utf8/LC_COLLATE", O_RDONLY|O_CLOEXEC) = 3fstat(3, {st_mode=S_IFREG|0644, st_size=1406, ...}) = 0mmap(NULL, 1406, PROT_READ, MAP_PRIVATE, 3, 0) = 0x7f1f21f6a000close(3) = 0openat(AT_FDCWD, "/usr/lib/locale/C.UTF-8/LC_TIME", O_RDONLY|O_CLOEXEC) = -1 ENOENT (No such file or directory)openat(AT_FDCWD, "/usr/lib/locale/C.utf8/LC_TIME", O_RDONLY|O_CLOEXEC) = 3fstat(3, {st_mode=S_IFREG|0644, st_size=3360, ...}) = 0mmap(NULL, 3360, PROT_READ, MAP_PRIVATE, 3, 0) = 0x7f1f21f69000close(3) = 0openat(AT_FDCWD, "/usr/lib/locale/C.UTF-8/LC_NUMERIC", O_RDONLY|O_CLOEXEC) = -1 ENOENT (No such file or directory)openat(AT_FDCWD, "/usr/lib/locale/C.utf8/LC_NUMERIC", O_RDONLY|O_CLOEXEC) = 3fstat(3, {st_mode=S_IFREG|0644, st_size=50, ...}) = 0mmap(NULL, 50, PROT_READ, MAP_PRIVATE, 3, 0) = 0x7f1f21f68000close(3) = 0openat(AT_FDCWD, "/usr/lib/locale/C.UTF-8/LC_CTYPE", O_RDONLY|O_CLOEXEC) = -1 ENOENT (No such file or directory)openat(AT_FDCWD, "/usr/lib/locale/C.utf8/LC_CTYPE", O_RDONLY|O_CLOEXEC) = 3fstat(3, {st_mode=S_IFREG|0644, st_size=360460, ...}) = 0mmap(NULL, 360460, PROT_READ, MAP_PRIVATE, 3, 0) = 0x7f1f21e8b000close(3) = 0getpid() = 2867282uname({sysname="Linux", nodename="sabertooth", ...}) = 0openat(AT_FDCWD, "/proc/sys/kernel/pid_max", O_RDONLY) = 3read(3, "4194304\n", 23) = 8close(3) = 0rt_sigaction(SIGCHLD, {sa_handler=SIG_DFL, sa_mask=[], sa_flags=SA_RESTORER, sa_restorer=0x7f1f21c45330}, {sa_handler=SIG_DFL, sa_mask=[], sa_flags=0}, 8) = 0getuid() = 1000getgid() = 1000clone(child_stack=NULL, flags=CLONE_CHILD_CLEARTID|CLONE_CHILD_SETTID|SIGCHLD, child_tidptr=0x7f1f21ee5650) = 2867283ptrace(PTRACE_SEIZE, 2867283, NULL, 0) = 0kill(2867283, SIGKILL) = 0wait4(2867283, [{WIFSIGNALED(s) && WTERMSIG(s) == SIGKILL}], 0, NULL) = 2867283--- SIGCHLD {si_signo=SIGCHLD, si_code=CLD_KILLED, si_pid=2867283, si_uid=1000, si_status=SIGKILL, si_utime=0, si_stime=0} ---clone(child_stack=NULL, flags=CLONE_CHILD_CLEARTID|CLONE_CHILD_SETTID|SIGCHLD, child_tidptr=0x7f1f21ee5650) = 2867284wait4(2867284, [{WIFSTOPPED(s) && WSTOPSIG(s) == SIGSTOP}], 0, NULL) = 2867284--- SIGCHLD {si_signo=SIGCHLD, si_code=CLD_TRAPPED, si_pid=2867284, si_uid=1000, si_status=SIGSTOP, si_utime=0, si_stime=0} ---ptrace(PTRACE_SETOPTIONS, 2867284, NULL, PTRACE_O_TRACESYSGOOD) = 0ptrace(PTRACE_GET_SYSCALL_INFO, 2867284, 88, {op=PTRACE_SYSCALL_INFO_NONE, arch=AUDIT_ARCH_X86_64, instruction_pointer=0x7f1f21c4553b, stack_pointer=0x7ffe0ba73578}) = 24ptrace(PTRACE_SYSCALL, 2867284, NULL, 0) = 0--- SIGCHLD {si_signo=SIGCHLD, si_code=CLD_TRAPPED, si_pid=2867284, si_uid=1000, si_status=SIGTRAP, si_utime=0, si_stime=0} ---wait4(2867284, [{WIFSTOPPED(s) && WSTOPSIG(s) == SIGTRAP | 0x80}], 0, NULL) = 2867284ptrace(PTRACE_GET_SYSCALL_INFO, 2867284, 88, {op=PTRACE_SYSCALL_INFO_ENTRY, arch=AUDIT_ARCH_X86_64, instruction_pointer=0x7f1f21d274ed, stack_pointer=0x7ffe0ba73568, entry={nr=__NR_chdir, args=[0x63a80d037d9a, 0xbad1fed1, 0xbad2fed2, 0xbad3fed3, 0xbad4fed4, 0xbad5fed5]}}) = 80ptrace(PTRACE_SYSCALL, 2867284, NULL, 0) = 0--- SIGCHLD {si_signo=SIGCHLD, si_code=CLD_TRAPPED, si_pid=2867284, si_uid=1000, si_status=SIGTRAP, si_utime=0, si_stime=0} ---wait4(2867284, [{WIFSTOPPED(s) && WSTOPSIG(s) == SIGTRAP | 0x80}], 0, NULL) = 2867284ptrace(PTRACE_GET_SYSCALL_INFO, 2867284, 88, {op=PTRACE_SYSCALL_INFO_EXIT, arch=AUDIT_ARCH_X86_64, instruction_pointer=0x7f1f21d274ed, stack_pointer=0x7ffe0ba73568, exit={rval=-ENOENT, is_error=1}}) = 33ptrace(PTRACE_SYSCALL, 2867284, NULL, 0) = 0wait4(2867284, [{WIFSTOPPED(s) && WSTOPSIG(s) == SIGTRAP | 0x80}], 0, NULL) = 2867284--- SIGCHLD {si_signo=SIGCHLD, si_code=CLD_TRAPPED, si_pid=2867284, si_uid=1000, si_status=SIGTRAP, si_utime=0, si_stime=0} ---ptrace(PTRACE_GET_SYSCALL_INFO, 2867284, 88, {op=PTRACE_SYSCALL_INFO_ENTRY, arch=AUDIT_ARCH_X86_64, instruction_pointer=0x7f1f21d274ed, stack_pointer=0x7ffe0ba73568, entry={nr=__NR_gettid, args=[0xcaf0bea0, 0xcaf1bea1, 0xcaf2bea2, 0xcaf3bea3, 0xcaf4bea4, 0xcaf5bea5]}}) = 80ptrace(PTRACE_SYSCALL, 2867284, NULL, 0) = 0wait4(2867284, [{WIFSTOPPED(s) && WSTOPSIG(s) == SIGTRAP | 0x80}], 0, NULL) = 2867284--- SIGCHLD {si_signo=SIGCHLD, si_code=CLD_TRAPPED, si_pid=2867284, si_uid=1000, si_status=SIGTRAP, si_utime=0, si_stime=0} ---ptrace(PTRACE_GET_SYSCALL_INFO, 2867284, 88, {op=PTRACE_SYSCALL_INFO_EXIT, arch=AUDIT_ARCH_X86_64, instruction_pointer=0x7f1f21d274ed, stack_pointer=0x7ffe0ba73568, exit={rval=2867284, is_error=0}}) = 33ptrace(PTRACE_SYSCALL, 2867284, NULL, 0) = 0wait4(2867284, [{WIFSTOPPED(s) && WSTOPSIG(s) == SIGTRAP | 0x80}], 0, NULL) = 2867284--- SIGCHLD {si_signo=SIGCHLD, si_code=CLD_TRAPPED, si_pid=2867284, si_uid=1000, si_status=SIGTRAP, si_utime=0, si_stime=0} ---ptrace(PTRACE_GET_SYSCALL_INFO, 2867284, 88, {op=PTRACE_SYSCALL_INFO_ENTRY, arch=AUDIT_ARCH_X86_64, instruction_pointer=0x7f1f21d274ed, stack_pointer=0x7ffe0ba73568, entry={nr=__NR_exit_group, args=[0, 0xfac1c0d1, 0xfac2c0d2, 0xfac3c0d3, 0xfac4c0d4, 0xfac5c0d5]}}) = 80ptrace(PTRACE_SYSCALL, 2867284, NULL, 0) = 0wait4(2867284, [{WIFEXITED(s) && WEXITSTATUS(s) == 0}], 0, NULL) = 2867284--- SIGCHLD {si_signo=SIGCHLD, si_code=CLD_EXITED, si_pid=2867284, si_uid=1000, si_status=0, si_utime=0, si_stime=0} ---pipe2([3, 4], 0) = 0close(4) = 0fcntl(3, F_GETFD) = 0fcntl(3, F_SETFD, FD_CLOEXEC) = 0close(3) = 0newfstatat(AT_FDCWD, "./atomic_idioms", {st_mode=S_IFREG|0775, st_size=16800, ...}, 0) = 0clone(child_stack=NULL, flags=CLONE_CHILD_CLEARTID|CLONE_CHILD_SETTID|SIGCHLD, child_tidptr=0x7f1f21ee5650) = 2867285wait4(2867285, [{WIFSTOPPED(s) && WSTOPSIG(s) == SIGSTOP}], WSTOPPED, NULL) = 2867285--- SIGCHLD {si_signo=SIGCHLD, si_code=CLD_STOPPED, si_pid=2867285, si_uid=1000, si_status=SIGSTOP, si_utime=0, si_stime=0} ---ptrace(PTRACE_SEIZE, 2867285, NULL, PTRACE_O_TRACESYSGOOD|PTRACE_O_TRACEEXEC|PTRACE_O_TRACEEXIT) = 0--- SIGCHLD {si_signo=SIGCHLD, si_code=CLD_STOPPED, si_pid=2867285, si_uid=1000, si_status=0, si_utime=0, si_stime=0} ---ptrace(PTRACE_INTERRUPT, 2867285) = 0kill(2867285, SIGCONT) = 0close(0) = 0pipe2([0, 3], 0) = 0close(3) = 0fcntl(0, F_GETFD) = 0fcntl(0, F_SETFD, FD_CLOEXEC) = 0close(1) = 0pipe2([1, 3], 0) = 0close(3) = 0fcntl(1, F_GETFD) = 0fcntl(1, F_SETFD, FD_CLOEXEC) = 0rt_sigaction(SIGTTOU, {sa_handler=SIG_IGN, sa_mask=[], sa_flags=SA_RESTORER, sa_restorer=0x7f1f21c45330}, NULL, 8) = 0rt_sigaction(SIGTTIN, {sa_handler=SIG_IGN, sa_mask=[], sa_flags=SA_RESTORER, sa_restorer=0x7f1f21c45330}, NULL, 8) = 0rt_sigaction(SIGHUP, {sa_handler=0x63a80cf57f10, sa_mask=[], sa_flags=SA_RESTORER, sa_restorer=0x7f1f21c45330}, NULL, 8) = 0rt_sigaction(SIGINT, {sa_handler=0x63a80cf57f10, sa_mask=[], sa_flags=SA_RESTORER, sa_restorer=0x7f1f21c45330}, NULL, 8) = 0rt_sigaction(SIGQUIT, {sa_handler=0x63a80cf57f10, sa_mask=[], sa_flags=SA_RESTORER, sa_restorer=0x7f1f21c45330}, NULL, 8) = 0rt_sigaction(SIGPIPE, {sa_handler=0x63a80cf57f10, sa_mask=[], sa_flags=SA_RESTORER, sa_restorer=0x7f1f21c45330}, NULL, 8) = 0rt_sigaction(SIGTERM, {sa_handler=0x63a80cf57f10, sa_mask=[], sa_flags=SA_RESTORER, sa_restorer=0x7f1f21c45330}, NULL, 8) = 0rt_sigprocmask(SIG_BLOCK, [ALRM], NULL, 8) = 0rt_sigaction(SIGALRM, {sa_handler=0x63a80cf63c20, sa_mask=[], sa_flags=SA_RESTORER, sa_restorer=0x7f1f21c45330}, NULL, 8) = 0wait4(-1, [{WIFSTOPPED(s) && WSTOPSIG(s) == SIGSTOP}|PTRACE_EVENT_STOP<<16], __WALL, NULL) = 2867285wait4(-1, 0x7ffe0ba737ac, WNOHANG|__WALL, NULL) = 0ptrace(PTRACE_LISTEN, 2867285) = 0wait4(-1, [{WIFSTOPPED(s) && WSTOPSIG(s) == SIGTRAP}|PTRACE_EVENT_STOP<<16], __WALL, NULL) = 2867285--- SIGCHLD {si_signo=SIGCHLD, si_code=CLD_CONTINUED, si_pid=2867285, si_uid=1000, si_status=SIGCONT, si_utime=0, si_stime=0} ---wait4(-1, 0x7ffe0ba737ac, WNOHANG|__WALL, NULL) = 0ptrace(PTRACE_SYSCALL, 2867285, NULL, 0) = 0--- SIGCHLD {si_signo=SIGCHLD, si_code=CLD_TRAPPED, si_pid=2867285, si_uid=1000, si_status=SIGCONT, si_utime=0, si_stime=0} ---wait4(-1, [{WIFSTOPPED(s) && WSTOPSIG(s) == SIGCONT}], __WALL, NULL) = 2867285ptrace(PTRACE_GETSIGINFO, 2867285, NULL, {si_signo=SIGCONT, si_code=SI_USER, si_pid=2867282, si_uid=1000}) = 0wait4(-1, 0x7ffe0ba737ac, WNOHANG|__WALL, NULL) = 0ptrace(PTRACE_SYSCALL, 2867285, NULL, SIGCONT) = 0--- SIGCHLD {si_signo=SIGCHLD, si_code=CLD_TRAPPED, si_pid=2867285, si_uid=1000, si_status=SIGTRAP, si_utime=0, si_stime=0} ---wait4(-1, [{WIFSTOPPED(s) && WSTOPSIG(s) == SIGTRAP | 0x80}], __WALL, NULL) = 2867285wait4(-1, 0x7ffe0ba737ac, WNOHANG|__WALL, NULL) = 0ptrace(PTRACE_GET_SYSCALL_INFO, 2867285, 88, {op=PTRACE_SYSCALL_INFO_ENTRY, arch=AUDIT_ARCH_X86_64, instruction_pointer=0x7f1f21ceeffb, stack_pointer=0x7ffe0ba72458, entry={nr=__NR_execve, args=[0x7ffe0ba72530, 0x7ffe0ba73a40, 0x7ffe0ba73a50, 0x7f1f21fbd0b8, 0x1, 0x7f1f21ee5380]}}) = 80ptrace(PTRACE_SYSCALL, 2867285, NULL, 0) = 0wait4(-1, [{WIFSTOPPED(s) && WSTOPSIG(s) == SIGTRAP}|PTRACE_EVENT_EXEC<<16], __WALL, NULL) = 2867285--- SIGCHLD {si_signo=SIGCHLD, si_code=CLD_TRAPPED, si_pid=2867285, si_uid=1000, si_status=SIGTRAP, si_utime=0, si_stime=0} ---ptrace(PTRACE_GETEVENTMSG, 2867285, NULL, [2867285]) = 0wait4(-1, 0x7ffe0ba737ac, WNOHANG|__WALL, NULL) = 0ptrace(PTRACE_SYSCALL, 2867285, NULL, 0) = 0--- SIGCHLD {si_signo=SIGCHLD, si_code=CLD_TRAPPED, si_pid=2867285, si_uid=1000, si_status=SIGTRAP, si_utime=0, si_stime=0} ---wait4(-1, [{WIFSTOPPED(s) && WSTOPSIG(s) == SIGTRAP | 0x80}], __WALL, NULL) = 2867285wait4(-1, 0x7ffe0ba737ac, WNOHANG|__WALL, NULL) = 0ptrace(PTRACE_SYSCALL, 2867285, NULL, 0) = 0wait4(-1, [{WIFSTOPPED(s) && WSTOPSIG(s) == SIGTRAP | 0x80}], __WALL, NULL) = 2867285--- SIGCHLD {si_signo=SIGCHLD, si_code=CLD_TRAPPED, si_pid=2867285, si_uid=1000, si_status=SIGTRAP, si_utime=0, si_stime=0} ---wait4(-1, 0x7ffe0ba737ac, WNOHANG|__WALL, NULL) = 0ptrace(PTRACE_GET_SYSCALL_INFO, 2867285, 88, {op=PTRACE_SYSCALL_INFO_ENTRY, arch=AUDIT_ARCH_X86_64, instruction_pointer=0x7ffa5c4959bb, stack_pointer=0x7ffca877c538, entry={nr=__NR_brk, args=[0, 0x7ffa5c4a7a18, 0, 0x37f, 0, 0x7ffa5c4a7440]}}) = 80ptrace(PTRACE_SYSCALL, 2867285, NULL, 0) = 0wait4(-1, [{WIFSTOPPED(s) && WSTOPSIG(s) == SIGTRAP | 0x80}], __WALL, NULL) = 2867285--- SIGCHLD {si_signo=SIGCHLD, si_code=CLD_TRAPPED, si_pid=2867285, si_uid=1000, si_status=SIGTRAP, si_utime=0, si_stime=0} ---wait4(-1, 0x7ffe0ba737ac, WNOHANG|__WALL, NULL) = 0ptrace(PTRACE_SYSCALL, 2867285, NULL, 0) = 0wait4(-1, [{WIFSTOPPED(s) && WSTOPSIG(s) == SIGTRAP | 0x80}], __WALL, NULL) = 2867285--- SIGCHLD {si_signo=SIGCHLD, si_code=CLD_TRAPPED, si_pid=2867285, si_uid=1000, si_status=SIGTRAP, si_utime=0, si_stime=0} ---wait4(-1, 0x7ffe0ba737ac, WNOHANG|__WALL, NULL) = 0ptrace(PTRACE_GET_SYSCALL_INFO, 2867285, 88, {op=PTRACE_SYSCALL_INFO_ENTRY, arch=AUDIT_ARCH_X86_64, instruction_pointer=0x7ffa5c496d1c, stack_pointer=0x7ffca877c1c0, entry={nr=__NR_mmap, args=[0, 0x2000, 0x3, 0x22, 0xffffffff, 0]}}) = 80ptrace(PTRACE_SYSCALL, 2867285, NULL, 0) = 0wait4(-1, [{WIFSTOPPED(s) && WSTOPSIG(s) == SIGTRAP | 0x80}], __WALL, NULL) = 2867285--- SIGCHLD {si_signo=SIGCHLD, si_code=CLD_TRAPPED, si_pid=2867285, si_uid=1000, si_status=SIGTRAP, si_utime=0, si_stime=0} ---wait4(-1, 0x7ffe0ba737ac, WNOHANG|__WALL, NULL) = 0ptrace(PTRACE_SYSCALL, 2867285, NULL, 0) = 0--- SIGCHLD {si_signo=SIGCHLD, si_code=CLD_TRAPPED, si_pid=2867285, si_uid=1000, si_status=SIGTRAP, si_utime=0, si_stime=0} ---wait4(-1, [{WIFSTOPPED(s) && WSTOPSIG(s) == SIGTRAP | 0x80}], __WALL, NULL) = 2867285wait4(-1, 0x7ffe0ba737ac, WNOHANG|__WALL, NULL) = 0ptrace(PTRACE_GET_SYSCALL_INFO, 2867285, 88, {op=PTRACE_SYSCALL_INFO_ENTRY, arch=AUDIT_ARCH_X86_64, instruction_pointer=0x7ffa5c4968bb, stack_pointer=0x7ffca877c278, entry={nr=__NR_access, args=[0x7ffa5c4a05b0, 0x4, 0x63d5a3ac7dc0, 0x22, 0x7ffa5c471000, 0x7ffa5c4a7440]}}) = 80ptrace(PTRACE_SYSCALL, 2867285, NULL, 0) = 0--- SIGCHLD {si_signo=SIGCHLD, si_code=CLD_TRAPPED, si_pid=2867285, si_uid=1000, si_status=SIGTRAP, si_utime=0, si_stime=0} ---wait4(-1, [{WIFSTOPPED(s) && WSTOPSIG(s) == SIGTRAP | 0x80}], __WALL, NULL) = 2867285wait4(-1, 0x7ffe0ba737ac, WNOHANG|__WALL, NULL) = 0ptrace(PTRACE_SYSCALL, 2867285, NULL, 0) = 0--- SIGCHLD {si_signo=SIGCHLD, si_code=CLD_TRAPPED, si_pid=2867285, si_uid=1000, si_status=SIGTRAP, si_utime=0, si_stime=0} ---wait4(-1, [{WIFSTOPPED(s) && WSTOPSIG(s) == SIGTRAP | 0x80}], __WALL, NULL) = 2867285wait4(-1, 0x7ffe0ba737ac, WNOHANG|__WALL, NULL) = 0ptrace(PTRACE_GET_SYSCALL_INFO, 2867285, 88, {op=PTRACE_SYSCALL_INFO_ENTRY, arch=AUDIT_ARCH_X86_64, instruction_pointer=0x7ffa5c496b61, stack_pointer=0x7ffca877b610, entry={nr=__NR_openat, args=[0xffffff9c, 0x7ffa5c49f38f, 0x80000, 0, 0, 0]}}) = 80fstat(2, {st_mode=S_IFIFO|0600, st_size=0, ...}) = 0process_vm_readv(2867285, [{iov_base="2\0dl-lookup.c\0out of memory\n\0, v"..., iov_len=4096}], 1, [{iov_base=0x7ffa5c49f000, iov_len=4096}], 1, 0) = 4096write(2, "openat(AT_FDCWD, \"/etc/ld.so.cac"..., 55) = 55ptrace(PTRACE_SYSCALL, 2867285, NULL, 0) = 0wait4(-1, [{WIFSTOPPED(s) && WSTOPSIG(s) == SIGTRAP | 0x80}], __WALL, NULL) = 2867285--- SIGCHLD {si_signo=SIGCHLD, si_code=CLD_TRAPPED, si_pid=2867285, si_uid=1000, si_status=SIGTRAP, si_utime=0, si_stime=0} ---wait4(-1, 0x7ffe0ba737ac, WNOHANG|__WALL, NULL) = 0ptrace(PTRACE_GET_SYSCALL_INFO, 2867285, 88, {op=PTRACE_SYSCALL_INFO_EXIT, arch=AUDIT_ARCH_X86_64, instruction_pointer=0x7ffa5c496b61, stack_pointer=0x7ffca877b610, exit={rval=3, is_error=0}}) = 33write(2, ") = 3\n", 6) = 6ptrace(PTRACE_SYSCALL, 2867285, NULL, 0) = 0--- SIGCHLD {si_signo=SIGCHLD, si_code=CLD_TRAPPED, si_pid=2867285, si_uid=1000, si_status=SIGTRAP, si_utime=0, si_stime=0} ---wait4(-1, [{WIFSTOPPED(s) && WSTOPSIG(s) == SIGTRAP | 0x80}], __WALL, NULL) = 2867285wait4(-1, 0x7ffe0ba737ac, WNOHANG|__WALL, NULL) = 0ptrace(PTRACE_GET_SYSCALL_INFO, 2867285, 88, {op=PTRACE_SYSCALL_INFO_ENTRY, arch=AUDIT_ARCH_X86_64, instruction_pointer=0x7ffa5c4968eb, stack_pointer=0x7ffca877b618, entry={nr=__NR_fstat, args=[0x3, 0x7ffca877b620, 0x80000, 0, 0, 0]}}) = 80ptrace(PTRACE_SYSCALL, 2867285, NULL, 0) = 0--- SIGCHLD {si_signo=SIGCHLD, si_code=CLD_TRAPPED, si_pid=2867285, si_uid=1000, si_status=SIGTRAP, si_utime=0, si_stime=0} ---wait4(-1, [{WIFSTOPPED(s) && WSTOPSIG(s) == SIGTRAP | 0x80}], __WALL, NULL) = 2867285wait4(-1, 0x7ffe0ba737ac, WNOHANG|__WALL, NULL) = 0ptrace(PTRACE_SYSCALL, 2867285, NULL, 0) = 0--- SIGCHLD {si_signo=SIGCHLD, si_code=CLD_TRAPPED, si_pid=2867285, si_uid=1000, si_status=SIGTRAP, si_utime=0, si_stime=0} ---wait4(-1, [{WIFSTOPPED(s) && WSTOPSIG(s) == SIGTRAP | 0x80}], __WALL, NULL) = 2867285wait4(-1, 0x7ffe0ba737ac, WNOHANG|__WALL, NULL) = 0ptrace(PTRACE_GET_SYSCALL_INFO, 2867285, 88, {op=PTRACE_SYSCALL_INFO_ENTRY, arch=AUDIT_ARCH_X86_64, instruction_pointer=0x7ffa5c496d1c, stack_pointer=0x7ffca877b600, entry={nr=__NR_mmap, args=[0, 0x241e8, 0x1, 0x2, 0x3, 0]}}) = 80ptrace(PTRACE_SYSCALL, 2867285, NULL, 0) = 0--- SIGCHLD {si_signo=SIGCHLD, si_code=CLD_TRAPPED, si_pid=2867285, si_uid=1000, si_status=SIGTRAP, si_utime=0, si_stime=0} ---wait4(-1, [{WIFSTOPPED(s) && WSTOPSIG(s) == SIGTRAP | 0x80}], __WALL, NULL) = 2867285wait4(-1, 0x7ffe0ba737ac, WNOHANG|__WALL, NULL) = 0ptrace(PTRACE_SYSCALL, 2867285, NULL, 0) = 0--- SIGCHLD {si_signo=SIGCHLD, si_code=CLD_TRAPPED, si_pid=2867285, si_uid=1000, si_status=SIGTRAP, si_utime=0, si_stime=0} ---wait4(-1, [{WIFSTOPPED(s) && WSTOPSIG(s) == SIGTRAP | 0x80}], __WALL, NULL) = 2867285wait4(-1, 0x7ffe0ba737ac, WNOHANG|__WALL, NULL) = 0ptrace(PTRACE_GET_SYSCALL_INFO, 2867285, 88, {op=PTRACE_SYSCALL_INFO_ENTRY, arch=AUDIT_ARCH_X86_64, instruction_pointer=0x7ffa5c496a1b, stack_pointer=0x7ffca877b618, entry={nr=__NR_close, args=[0x3, 0x241e8, 0x1, 0x2, 0x3, 0]}}) = 80write(2, "close(3", 7) = 7ptrace(PTRACE_SYSCALL, 2867285, NULL, 0) = 0--- SIGCHLD {si_signo=SIGCHLD, si_code=CLD_TRAPPED, si_pid=2867285, si_uid=1000, si_status=SIGTRAP, si_utime=0, si_stime=0} ---wait4(-1, [{WIFSTOPPED(s) && WSTOPSIG(s) == SIGTRAP | 0x80}], __WALL, NULL) = 2867285wait4(-1, 0x7ffe0ba737ac, WNOHANG|__WALL, NULL) = 0ptrace(PTRACE_GET_SYSCALL_INFO, 2867285, 88, {op=PTRACE_SYSCALL_INFO_EXIT, arch=AUDIT_ARCH_X86_64, instruction_pointer=0x7ffa5c496a1b, stack_pointer=0x7ffca877b618, exit={rval=0, is_error=0}}) = 33write(2, ") "..., 37) = 37ptrace(PTRACE_SYSCALL, 2867285, NULL, 0) = 0wait4(-1, [{WIFSTOPPED(s) && WSTOPSIG(s) == SIGTRAP | 0x80}], __WALL, NULL) = 2867285--- SIGCHLD {si_signo=SIGCHLD, si_code=CLD_TRAPPED, si_pid=2867285, si_uid=1000, si_status=SIGTRAP, si_utime=0, si_stime=0} ---wait4(-1, 0x7ffe0ba737ac, WNOHANG|__WALL, NULL) = 0ptrace(PTRACE_GET_SYSCALL_INFO, 2867285, 88, {op=PTRACE_SYSCALL_INFO_ENTRY, arch=AUDIT_ARCH_X86_64, instruction_pointer=0x7ffa5c496b61, stack_pointer=0x7ffca877b780, entry={nr=__NR_openat, args=[0xffffff9c, 0x7ffa5c467140, 0x80000, 0, 0x7ffca877b837, 0]}}) = 80process_vm_readv(2867285, [{iov_base="PpF\\\372\177\0\0\362\356I\\\372\177\0\0\0\0\0\0\0\0\0\0@\320I\\\372\177\0\0"..., iov_len=4096}], 1, [{iov_base=0x7ffa5c467000, iov_len=4096}], 1, 0) = 4096write(2, "openat(AT_FDCWD, \"/lib/x86_64-li"..., 70) = 70ptrace(PTRACE_SYSCALL, 2867285, NULL, 0) = 0--- SIGCHLD {si_signo=SIGCHLD, si_code=CLD_TRAPPED, si_pid=2867285, si_uid=1000, si_status=SIGTRAP, si_utime=0, si_stime=0} ---wait4(-1, [{WIFSTOPPED(s) && WSTOPSIG(s) == SIGTRAP | 0x80}], __WALL, NULL) = 2867285wait4(-1, 0x7ffe0ba737ac, WNOHANG|__WALL, NULL) = 0ptrace(PTRACE_GET_SYSCALL_INFO, 2867285, 88, {op=PTRACE_SYSCALL_INFO_EXIT, arch=AUDIT_ARCH_X86_64, instruction_pointer=0x7ffa5c496b61, stack_pointer=0x7ffca877b780, exit={rval=3, is_error=0}}) = 33write(2, ") = 3\n", 6) = 6ptrace(PTRACE_SYSCALL, 2867285, NULL, 0) = 0--- SIGCHLD {si_signo=SIGCHLD, si_code=CLD_TRAPPED, si_pid=2867285, si_uid=1000, si_status=SIGTRAP, si_utime=0, si_stime=0} ---wait4(-1, [{WIFSTOPPED(s) && WSTOPSIG(s) == SIGTRAP | 0x80}], __WALL, NULL) = 2867285wait4(-1, 0x7ffe0ba737ac, WNOHANG|__WALL, NULL) = 0ptrace(PTRACE_GET_SYSCALL_INFO, 2867285, 88, {op=PTRACE_SYSCALL_INFO_ENTRY, arch=AUDIT_ARCH_X86_64, instruction_pointer=0x7ffa5c496bd8, stack_pointer=0x7ffca877b788, entry={nr=__NR_read, args=[0x3, 0x7ffca877b858, 0x340, 0, 0x7ffca877b837, 0]}}) = 80ptrace(PTRACE_SYSCALL, 2867285, NULL, 0) = 0--- SIGCHLD {si_signo=SIGCHLD, si_code=CLD_TRAPPED, si_pid=2867285, si_uid=1000, si_status=SIGTRAP, si_utime=0, si_stime=0} ---wait4(-1, [{WIFSTOPPED(s) && WSTOPSIG(s) == SIGTRAP | 0x80}], __WALL, NULL) = 2867285wait4(-1, 0x7ffe0ba737ac, WNOHANG|__WALL, NULL) = 0ptrace(PTRACE_SYSCALL, 2867285, NULL, 0) = 0--- SIGCHLD {si_signo=SIGCHLD, si_code=CLD_TRAPPED, si_pid=2867285, si_uid=1000, si_status=SIGTRAP, si_utime=0, si_stime=0} ---wait4(-1, [{WIFSTOPPED(s) && WSTOPSIG(s) == SIGTRAP | 0x80}], __WALL, NULL) = 2867285wait4(-1, 0x7ffe0ba737ac, WNOHANG|__WALL, NULL) = 0ptrace(PTRACE_GET_SYSCALL_INFO, 2867285, 88, {op=PTRACE_SYSCALL_INFO_ENTRY, arch=AUDIT_ARCH_X86_64, instruction_pointer=0x7ffa5c496bae, stack_pointer=0x7ffca877b468, entry={nr=__NR_pread64, args=[0x3, 0x7ffca877b470, 0x310, 0x40, 0x7ffca877b837, 0]}}) = 80write(2, "pread64(3, ", 11) = 11ptrace(PTRACE_SYSCALL, 2867285, NULL, 0) = 0--- SIGCHLD {si_signo=SIGCHLD, si_code=CLD_TRAPPED, si_pid=2867285, si_uid=1000, si_status=SIGTRAP, si_utime=0, si_stime=0} ---wait4(-1, [{WIFSTOPPED(s) && WSTOPSIG(s) == SIGTRAP | 0x80}], __WALL, NULL) = 2867285wait4(-1, 0x7ffe0ba737ac, WNOHANG|__WALL, NULL) = 0ptrace(PTRACE_GET_SYSCALL_INFO, 2867285, 88, {op=PTRACE_SYSCALL_INFO_EXIT, arch=AUDIT_ARCH_X86_64, instruction_pointer=0x7ffa5c496bae, stack_pointer=0x7ffca877b468, exit={rval=784, is_error=0}}) = 33process_vm_readv(2867285, [{iov_base="\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0"..., iov_len=4096}], 1, [{iov_base=0x7ffca877b000, iov_len=4096}], 1, 0) = 4096write(2, "\"\\6\\0\\0\\0\\4\\0\\0\\0@\\0\\0\\0\\0\\0\\0\\0"..., 83) = 83ptrace(PTRACE_SYSCALL, 2867285, NULL, 0) = 0--- SIGCHLD {si_signo=SIGCHLD, si_code=CLD_TRAPPED, si_pid=2867285, si_uid=1000, si_status=SIGTRAP, si_utime=0, si_stime=0} ---wait4(-1, [{WIFSTOPPED(s) && WSTOPSIG(s) == SIGTRAP | 0x80}], __WALL, NULL) = 2867285wait4(-1, 0x7ffe0ba737ac, WNOHANG|__WALL, NULL) = 0ptrace(PTRACE_GET_SYSCALL_INFO, 2867285, 88, {op=PTRACE_SYSCALL_INFO_ENTRY, arch=AUDIT_ARCH_X86_64, instruction_pointer=0x7ffa5c4968eb, stack_pointer=0x7ffca877b658, entry={nr=__NR_fstat, args=[0x3, 0x7ffca877b6f0, 0x3, 0x40, 0x7ffa5c467140, 0x7ffa5c4aa2e0]}}) = 80ptrace(PTRACE_SYSCALL, 2867285, NULL, 0) = 0--- SIGCHLD {si_signo=SIGCHLD, si_code=CLD_TRAPPED, si_pid=2867285, si_uid=1000, si_status=SIGTRAP, si_utime=0, si_stime=0} ---wait4(-1, [{WIFSTOPPED(s) && WSTOPSIG(s) == SIGTRAP | 0x80}], __WALL, NULL) = 2867285wait4(-1, 0x7ffe0ba737ac, WNOHANG|__WALL, NULL) = 0ptrace(PTRACE_SYSCALL, 2867285, NULL, 0) = 0--- SIGCHLD {si_signo=SIGCHLD, si_code=CLD_TRAPPED, si_pid=2867285, si_uid=1000, si_status=SIGTRAP, si_utime=0, si_stime=0} ---wait4(-1, [{WIFSTOPPED(s) && WSTOPSIG(s) == SIGTRAP | 0x80}], __WALL, NULL) = 2867285wait4(-1, 0x7ffe0ba737ac, WNOHANG|__WALL, NULL) = 0ptrace(PTRACE_GET_SYSCALL_INFO, 2867285, 88, {op=PTRACE_SYSCALL_INFO_ENTRY, arch=AUDIT_ARCH_X86_64, instruction_pointer=0x7ffa5c496bae, stack_pointer=0x7ffca877b338, entry={nr=__NR_pread64, args=[0x3, 0x7ffca877b340, 0x310, 0x40, 0xc0ff, 0]}}) = 80write(2, "pread64(3, ", 11) = 11ptrace(PTRACE_SYSCALL, 2867285, NULL, 0) = 0--- SIGCHLD {si_signo=SIGCHLD, si_code=CLD_TRAPPED, si_pid=2867285, si_uid=1000, si_status=SIGTRAP, si_utime=0, si_stime=0} ---wait4(-1, [{WIFSTOPPED(s) && WSTOPSIG(s) == SIGTRAP | 0x80}], __WALL, NULL) = 2867285wait4(-1, 0x7ffe0ba737ac, WNOHANG|__WALL, NULL) = 0ptrace(PTRACE_GET_SYSCALL_INFO, 2867285, 88, {op=PTRACE_SYSCALL_INFO_EXIT, arch=AUDIT_ARCH_X86_64, instruction_pointer=0x7ffa5c496bae, stack_pointer=0x7ffca877b338, exit={rval=784, is_error=0}}) = 33process_vm_readv(2867285, [{iov_base="\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0"..., iov_len=4096}], 1, [{iov_base=0x7ffca877b000, iov_len=4096}], 1, 0) = 4096write(2, "\"\\6\\0\\0\\0\\4\\0\\0\\0@\\0\\0\\0\\0\\0\\0\\0"..., 83) = 83ptrace(PTRACE_SYSCALL, 2867285, NULL, 0) = 0--- SIGCHLD {si_signo=SIGCHLD, si_code=CLD_TRAPPED, si_pid=2867285, si_uid=1000, si_status=SIGTRAP, si_utime=0, si_stime=0} ---wait4(-1, [{WIFSTOPPED(s) && WSTOPSIG(s) == SIGTRAP | 0x80}], __WALL, NULL) = 2867285wait4(-1, 0x7ffe0ba737ac, WNOHANG|__WALL, NULL) = 0ptrace(PTRACE_GET_SYSCALL_INFO, 2867285, 88, {op=PTRACE_SYSCALL_INFO_ENTRY, arch=AUDIT_ARCH_X86_64, instruction_pointer=0x7ffa5c496d1c, stack_pointer=0x7ffca877b010, entry={nr=__NR_mmap, args=[0, 0x212d90, 0x1, 0x802, 0x3, 0]}}) = 80ptrace(PTRACE_SYSCALL, 2867285, NULL, 0) = 0--- SIGCHLD {si_signo=SIGCHLD, si_code=CLD_TRAPPED, si_pid=2867285, si_uid=1000, si_status=SIGTRAP, si_utime=0, si_stime=0} ---wait4(-1, [{WIFSTOPPED(s) && WSTOPSIG(s) == SIGTRAP | 0x80}], __WALL, NULL) = 2867285wait4(-1, 0x7ffe0ba737ac, WNOHANG|__WALL, NULL) = 0ptrace(PTRACE_SYSCALL, 2867285, NULL, 0) = 0--- SIGCHLD {si_signo=SIGCHLD, si_code=CLD_TRAPPED, si_pid=2867285, si_uid=1000, si_status=SIGTRAP, si_utime=0, si_stime=0} ---wait4(-1, [{WIFSTOPPED(s) && WSTOPSIG(s) == SIGTRAP | 0x80}], __WALL, NULL) = 2867285wait4(-1, 0x7ffe0ba737ac, WNOHANG|__WALL, NULL) = 0ptrace(PTRACE_GET_SYSCALL_INFO, 2867285, 88, {op=PTRACE_SYSCALL_INFO_ENTRY, arch=AUDIT_ARCH_X86_64, instruction_pointer=0x7ffa5c496d1c, stack_pointer=0x7ffca877b010, entry={nr=__NR_mmap, args=[0x7ffa5c228000, 0x189000, 0x5, 0x812, 0x3, 0x28000]}}) = 80ptrace(PTRACE_SYSCALL, 2867285, NULL, 0) = 0wait4(-1, [{WIFSTOPPED(s) && WSTOPSIG(s) == SIGTRAP | 0x80}], __WALL, NULL) = 2867285--- SIGCHLD {si_signo=SIGCHLD, si_code=CLD_TRAPPED, si_pid=2867285, si_uid=1000, si_status=SIGTRAP, si_utime=0, si_stime=0} ---wait4(-1, 0x7ffe0ba737ac, WNOHANG|__WALL, NULL) = 0ptrace(PTRACE_SYSCALL, 2867285, NULL, 0) = 0--- SIGCHLD {si_signo=SIGCHLD, si_code=CLD_TRAPPED, si_pid=2867285, si_uid=1000, si_status=SIGTRAP, si_utime=0, si_stime=0} ---wait4(-1, [{WIFSTOPPED(s) && WSTOPSIG(s) == SIGTRAP | 0x80}], __WALL, NULL) = 2867285wait4(-1, 0x7ffe0ba737ac, WNOHANG|__WALL, NULL) = 0ptrace(PTRACE_GET_SYSCALL_INFO, 2867285, 88, {op=PTRACE_SYSCALL_INFO_ENTRY, arch=AUDIT_ARCH_X86_64, instruction_pointer=0x7ffa5c496d1c, stack_pointer=0x7ffca877b010, entry={nr=__NR_mmap, args=[0x7ffa5c3b1000, 0x4f000, 0x1, 0x812, 0x3, 0x1b1000]}}) = 80ptrace(PTRACE_SYSCALL, 2867285, NULL, 0) = 0--- SIGCHLD {si_signo=SIGCHLD, si_code=CLD_TRAPPED, si_pid=2867285, si_uid=1000, si_status=SIGTRAP, si_utime=0, si_stime=0} ---wait4(-1, [{WIFSTOPPED(s) && WSTOPSIG(s) == SIGTRAP | 0x80}], __WALL, NULL) = 2867285wait4(-1, 0x7ffe0ba737ac, WNOHANG|__WALL, NULL) = 0ptrace(PTRACE_SYSCALL, 2867285, NULL, 0) = 0--- SIGCHLD {si_signo=SIGCHLD, si_code=CLD_TRAPPED, si_pid=2867285, si_uid=1000, si_status=SIGTRAP, si_utime=0, si_stime=0} ---wait4(-1, [{WIFSTOPPED(s) && WSTOPSIG(s) == SIGTRAP | 0x80}], __WALL, NULL) = 2867285wait4(-1, 0x7ffe0ba737ac, WNOHANG|__WALL, NULL) = 0ptrace(PTRACE_GET_SYSCALL_INFO, 2867285, 88, {op=PTRACE_SYSCALL_INFO_ENTRY, arch=AUDIT_ARCH_X86_64, instruction_pointer=0x7ffa5c496d1c, stack_pointer=0x7ffca877b010, entry={nr=__NR_mmap, args=[0x7ffa5c400000, 0x6000, 0x3, 0x812, 0x3, 0x1ff000]}}) = 80ptrace(PTRACE_SYSCALL, 2867285, NULL, 0) = 0--- SIGCHLD {si_signo=SIGCHLD, si_code=CLD_TRAPPED, si_pid=2867285, si_uid=1000, si_status=SIGTRAP, si_utime=0, si_stime=0} ---wait4(-1, [{WIFSTOPPED(s) && WSTOPSIG(s) == SIGTRAP | 0x80}], __WALL, NULL) = 2867285wait4(-1, 0x7ffe0ba737ac, WNOHANG|__WALL, NULL) = 0ptrace(PTRACE_SYSCALL, 2867285, NULL, 0) = 0--- SIGCHLD {si_signo=SIGCHLD, si_code=CLD_TRAPPED, si_pid=2867285, si_uid=1000, si_status=SIGTRAP, si_utime=0, si_stime=0} ---wait4(-1, [{WIFSTOPPED(s) && WSTOPSIG(s) == SIGTRAP | 0x80}], __WALL, NULL) = 2867285wait4(-1, 0x7ffe0ba737ac, WNOHANG|__WALL, NULL) = 0ptrace(PTRACE_GET_SYSCALL_INFO, 2867285, 88, {op=PTRACE_SYSCALL_INFO_ENTRY, arch=AUDIT_ARCH_X86_64, instruction_pointer=0x7ffa5c496d1c, stack_pointer=0x7ffca877b010, entry={nr=__NR_mmap, args=[0x7ffa5c406000, 0xcd90, 0x3, 0x32, 0xffffffff, 0]}}) = 80ptrace(PTRACE_SYSCALL, 2867285, NULL, 0) = 0--- SIGCHLD {si_signo=SIGCHLD, si_code=CLD_TRAPPED, si_pid=2867285, si_uid=1000, si_status=SIGTRAP, si_utime=0, si_stime=0} ---wait4(-1, [{WIFSTOPPED(s) && WSTOPSIG(s) == SIGTRAP | 0x80}], __WALL, NULL) = 2867285wait4(-1, 0x7ffe0ba737ac, WNOHANG|__WALL, NULL) = 0ptrace(PTRACE_SYSCALL, 2867285, NULL, 0) = 0wait4(-1, [{WIFSTOPPED(s) && WSTOPSIG(s) == SIGTRAP | 0x80}], __WALL, NULL) = 2867285--- SIGCHLD {si_signo=SIGCHLD, si_code=CLD_TRAPPED, si_pid=2867285, si_uid=1000, si_status=SIGTRAP, si_utime=0, si_stime=0} ---wait4(-1, 0x7ffe0ba737ac, WNOHANG|__WALL, NULL) = 0ptrace(PTRACE_GET_SYSCALL_INFO, 2867285, 88, {op=PTRACE_SYSCALL_INFO_ENTRY, arch=AUDIT_ARCH_X86_64, instruction_pointer=0x7ffa5c496a1b, stack_pointer=0x7ffca877b338, entry={nr=__NR_close, args=[0x3, 0x7ffa5c467160, 0x1, 0xc0000002, 0x7ffa5c200378, 0x4]}}) = 80write(2, "close(3", 7) = 7ptrace(PTRACE_SYSCALL, 2867285, NULL, 0) = 0--- SIGCHLD {si_signo=SIGCHLD, si_code=CLD_TRAPPED, si_pid=2867285, si_uid=1000, si_status=SIGTRAP, si_utime=0, si_stime=0} ---wait4(-1, [{WIFSTOPPED(s) && WSTOPSIG(s) == SIGTRAP | 0x80}], __WALL, NULL) = 2867285wait4(-1, 0x7ffe0ba737ac, WNOHANG|__WALL, NULL) = 0ptrace(PTRACE_GET_SYSCALL_INFO, 2867285, 88, {op=PTRACE_SYSCALL_INFO_EXIT, arch=AUDIT_ARCH_X86_64, instruction_pointer=0x7ffa5c496a1b, stack_pointer=0x7ffca877b338, exit={rval=0, is_error=0}}) = 33write(2, ") "..., 37) = 37ptrace(PTRACE_SYSCALL, 2867285, NULL, 0) = 0--- SIGCHLD {si_signo=SIGCHLD, si_code=CLD_TRAPPED, si_pid=2867285, si_uid=1000, si_status=SIGTRAP, si_utime=0, si_stime=0} ---wait4(-1, [{WIFSTOPPED(s) && WSTOPSIG(s) == SIGTRAP | 0x80}], __WALL, NULL) = 2867285wait4(-1, 0x7ffe0ba737ac, WNOHANG|__WALL, NULL) = 0ptrace(PTRACE_GET_SYSCALL_INFO, 2867285, 88, {op=PTRACE_SYSCALL_INFO_ENTRY, arch=AUDIT_ARCH_X86_64, instruction_pointer=0x7ffa5c496d1c, stack_pointer=0x7ffca877c1e0, entry={nr=__NR_mmap, args=[0, 0x3000, 0x3, 0x22, 0xffffffff, 0]}}) = 80ptrace(PTRACE_SYSCALL, 2867285, NULL, 0) = 0wait4(-1, [{WIFSTOPPED(s) && WSTOPSIG(s) == SIGTRAP | 0x80}], __WALL, NULL) = 2867285--- SIGCHLD {si_signo=SIGCHLD, si_code=CLD_TRAPPED, si_pid=2867285, si_uid=1000, si_status=SIGTRAP, si_utime=0, si_stime=0} ---wait4(-1, 0x7ffe0ba737ac, WNOHANG|__WALL, NULL) = 0ptrace(PTRACE_SYSCALL, 2867285, NULL, 0) = 0wait4(-1, [{WIFSTOPPED(s) && WSTOPSIG(s) == SIGTRAP | 0x80}], __WALL, NULL) = 2867285--- SIGCHLD {si_signo=SIGCHLD, si_code=CLD_TRAPPED, si_pid=2867285, si_uid=1000, si_status=SIGTRAP, si_utime=0, si_stime=0} ---wait4(-1, 0x7ffe0ba737ac, WNOHANG|__WALL, NULL) = 0ptrace(PTRACE_GET_SYSCALL_INFO, 2867285, 88, {op=PTRACE_SYSCALL_INFO_ENTRY, arch=AUDIT_ARCH_X86_64, instruction_pointer=0x7ffa5c49111d, stack_pointer=0x7ffca877c260, entry={nr=__NR_arch_prctl, args=[0x1002, 0x7ffa5c43f740, 0xffff8005a3bbff30, 0x22, 0xffffffff, 0]}}) = 80ptrace(PTRACE_SYSCALL, 2867285, NULL, 0) = 0wait4(-1, [{WIFSTOPPED(s) && WSTOPSIG(s) == SIGTRAP | 0x80}], __WALL, NULL) = 2867285--- SIGCHLD {si_signo=SIGCHLD, si_code=CLD_TRAPPED, si_pid=2867285, si_uid=1000, si_status=SIGTRAP, si_utime=0, si_stime=0} ---wait4(-1, 0x7ffe0ba737ac, WNOHANG|__WALL, NULL) = 0ptrace(PTRACE_SYSCALL, 2867285, NULL, 0) = 0wait4(-1, [{WIFSTOPPED(s) && WSTOPSIG(s) == SIGTRAP | 0x80}], __WALL, NULL) = 2867285--- SIGCHLD {si_signo=SIGCHLD, si_code=CLD_TRAPPED, si_pid=2867285, si_uid=1000, si_status=SIGTRAP, si_utime=0, si_stime=0} ---wait4(-1, 0x7ffe0ba737ac, WNOHANG|__WALL, NULL) = 0ptrace(PTRACE_GET_SYSCALL_INFO, 2867285, 88, {op=PTRACE_SYSCALL_INFO_ENTRY, arch=AUDIT_ARCH_X86_64, instruction_pointer=0x7ffa5c485f12, stack_pointer=0x7ffca877c230, entry={nr=__NR_set_tid_address, args=[0x7ffa5c43fa10, 0x7ffa5c43f740, 0x7ffa5c4aa0c8, 0x22, 0xffffffff, 0]}}) = 80ptrace(PTRACE_SYSCALL, 2867285, NULL, 0) = 0--- SIGCHLD {si_signo=SIGCHLD, si_code=CLD_TRAPPED, si_pid=2867285, si_uid=1000, si_status=SIGTRAP, si_utime=0, si_stime=0} ---wait4(-1, [{WIFSTOPPED(s) && WSTOPSIG(s) == SIGTRAP | 0x80}], __WALL, NULL) = 2867285wait4(-1, 0x7ffe0ba737ac, WNOHANG|__WALL, NULL) = 0ptrace(PTRACE_SYSCALL, 2867285, NULL, 0) = 0--- SIGCHLD {si_signo=SIGCHLD, si_code=CLD_TRAPPED, si_pid=2867285, si_uid=1000, si_status=SIGTRAP, si_utime=0, si_stime=0} ---wait4(-1, [{WIFSTOPPED(s) && WSTOPSIG(s) == SIGTRAP | 0x80}], __WALL, NULL) = 2867285wait4(-1, 0x7ffe0ba737ac, WNOHANG|__WALL, NULL) = 0ptrace(PTRACE_GET_SYSCALL_INFO, 2867285, 88, {op=PTRACE_SYSCALL_INFO_ENTRY, arch=AUDIT_ARCH_X86_64, instruction_pointer=0x7ffa5c485f6e, stack_pointer=0x7ffca877c230, entry={nr=__NR_set_robust_list, args=[0x7ffa5c43fa20, 0x18, 0x7ffa5c4aa0c8, 0x22, 0xffffffff, 0]}}) = 80ptrace(PTRACE_SYSCALL, 2867285, NULL, 0) = 0wait4(-1, [{WIFSTOPPED(s) && WSTOPSIG(s) == SIGTRAP | 0x80}], __WALL, NULL) = 2867285--- SIGCHLD {si_signo=SIGCHLD, si_code=CLD_TRAPPED, si_pid=2867285, si_uid=1000, si_status=SIGTRAP, si_utime=0, si_stime=0} ---wait4(-1, 0x7ffe0ba737ac, WNOHANG|__WALL, NULL) = 0ptrace(PTRACE_SYSCALL, 2867285, NULL, 0) = 0wait4(-1, [{WIFSTOPPED(s) && WSTOPSIG(s) == SIGTRAP | 0x80}], __WALL, NULL) = 2867285--- SIGCHLD {si_signo=SIGCHLD, si_code=CLD_TRAPPED, si_pid=2867285, si_uid=1000, si_status=SIGTRAP, si_utime=0, si_stime=0} ---wait4(-1, 0x7ffe0ba737ac, WNOHANG|__WALL, NULL) = 0ptrace(PTRACE_GET_SYSCALL_INFO, 2867285, 88, {op=PTRACE_SYSCALL_INFO_ENTRY, arch=AUDIT_ARCH_X86_64, instruction_pointer=0x7ffa5c485fe6, stack_pointer=0x7ffca877c230, entry={nr=__NR_rseq, args=[0x7ffa5c440060, 0x20, 0, 0x53053053, 0, 0x7ffa5c4a7440]}}) = 80ptrace(PTRACE_SYSCALL, 2867285, NULL, 0) = 0--- SIGCHLD {si_signo=SIGCHLD, si_code=CLD_TRAPPED, si_pid=2867285, si_uid=1000, si_status=SIGTRAP, si_utime=0, si_stime=0} ---wait4(-1, [{WIFSTOPPED(s) && WSTOPSIG(s) == SIGTRAP | 0x80}], __WALL, NULL) = 2867285wait4(-1, 0x7ffe0ba737ac, WNOHANG|__WALL, NULL) = 0ptrace(PTRACE_SYSCALL, 2867285, NULL, 0) = 0wait4(-1, [{WIFSTOPPED(s) && WSTOPSIG(s) == SIGTRAP | 0x80}], __WALL, NULL) = 2867285--- SIGCHLD {si_signo=SIGCHLD, si_code=CLD_TRAPPED, si_pid=2867285, si_uid=1000, si_status=SIGTRAP, si_utime=0, si_stime=0} ---wait4(-1, 0x7ffe0ba737ac, WNOHANG|__WALL, NULL) = 0ptrace(PTRACE_GET_SYSCALL_INFO, 2867285, 88, {op=PTRACE_SYSCALL_INFO_ENTRY, arch=AUDIT_ARCH_X86_64, instruction_pointer=0x7ffa5c496dab, stack_pointer=0x7ffca877c148, entry={nr=__NR_mprotect, args=[0x7ffa5c400000, 0x4000, 0x1, 0x7ffa5c467160, 0x7ffa5c467160, 0]}}) = 80ptrace(PTRACE_SYSCALL, 2867285, NULL, 0) = 0wait4(-1, [{WIFSTOPPED(s) && WSTOPSIG(s) == SIGTRAP | 0x80}], __WALL, NULL) = 2867285--- SIGCHLD {si_signo=SIGCHLD, si_code=CLD_TRAPPED, si_pid=2867285, si_uid=1000, si_status=SIGTRAP, si_utime=0, si_stime=0} ---wait4(-1, 0x7ffe0ba737ac, WNOHANG|__WALL, NULL) = 0ptrace(PTRACE_SYSCALL, 2867285, NULL, 0) = 0--- SIGCHLD {si_signo=SIGCHLD, si_code=CLD_TRAPPED, si_pid=2867285, si_uid=1000, si_status=SIGTRAP, si_utime=0, si_stime=0} ---wait4(-1, [{WIFSTOPPED(s) && WSTOPSIG(s) == SIGTRAP | 0x80}], __WALL, NULL) = 2867285wait4(-1, 0x7ffe0ba737ac, WNOHANG|__WALL, NULL) = 0ptrace(PTRACE_GET_SYSCALL_INFO, 2867285, 88, {op=PTRACE_SYSCALL_INFO_ENTRY, arch=AUDIT_ARCH_X86_64, instruction_pointer=0x7ffa5c496dab, stack_pointer=0x7ffca877c148, entry={nr=__NR_mprotect, args=[0x63d5a3ac7000, 0x1000, 0x1, 0x7ffa5c4aa2e0, 0x7ffa5c4aa2e0, 0x7ffa5c31b260]}}) = 80ptrace(PTRACE_SYSCALL, 2867285, NULL, 0) = 0--- SIGCHLD {si_signo=SIGCHLD, si_code=CLD_TRAPPED, si_pid=2867285, si_uid=1000, si_status=SIGTRAP, si_utime=0, si_stime=0} ---wait4(-1, [{WIFSTOPPED(s) && WSTOPSIG(s) == SIGTRAP | 0x80}], __WALL, NULL) = 2867285wait4(-1, 0x7ffe0ba737ac, WNOHANG|__WALL, NULL) = 0ptrace(PTRACE_SYSCALL, 2867285, NULL, 0) = 0--- SIGCHLD {si_signo=SIGCHLD, si_code=CLD_TRAPPED, si_pid=2867285, si_uid=1000, si_status=SIGTRAP, si_utime=0, si_stime=0} ---wait4(-1, [{WIFSTOPPED(s) && WSTOPSIG(s) == SIGTRAP | 0x80}], __WALL, NULL) = 2867285wait4(-1, 0x7ffe0ba737ac, WNOHANG|__WALL, NULL) = 0ptrace(PTRACE_GET_SYSCALL_INFO, 2867285, 88, {op=PTRACE_SYSCALL_INFO_ENTRY, arch=AUDIT_ARCH_X86_64, instruction_pointer=0x7ffa5c496dab, stack_pointer=0x7ffca877c148, entry={nr=__NR_mprotect, args=[0x7ffa5c4a7000, 0x2000, 0x1, 0x7ffa5c4a9ab0, 0x7ffa5c4a9ab0, 0]}}) = 80ptrace(PTRACE_SYSCALL, 2867285, NULL, 0) = 0--- SIGCHLD {si_signo=SIGCHLD, si_code=CLD_TRAPPED, si_pid=2867285, si_uid=1000, si_status=SIGTRAP, si_utime=0, si_stime=0} ---wait4(-1, [{WIFSTOPPED(s) && WSTOPSIG(s) == SIGTRAP | 0x80}], __WALL, NULL) = 2867285wait4(-1, 0x7ffe0ba737ac, WNOHANG|__WALL, NULL) = 0ptrace(PTRACE_SYSCALL, 2867285, NULL, 0) = 0wait4(-1, [{WIFSTOPPED(s) && WSTOPSIG(s) == SIGTRAP | 0x80}], __WALL, NULL) = 2867285--- SIGCHLD {si_signo=SIGCHLD, si_code=CLD_TRAPPED, si_pid=2867285, si_uid=1000, si_status=SIGTRAP, si_utime=0, si_stime=0} ---wait4(-1, 0x7ffe0ba737ac, WNOHANG|__WALL, NULL) = 0ptrace(PTRACE_GET_SYSCALL_INFO, 2867285, 88, {op=PTRACE_SYSCALL_INFO_ENTRY, arch=AUDIT_ARCH_X86_64, instruction_pointer=0x7ffa5c31d454, stack_pointer=0x7ffca877c238, entry={nr=__NR_prlimit64, args=[0, 0x3, 0, 0x7ffca877c240, 0, 0xd]}}) = 80ptrace(PTRACE_SYSCALL, 2867285, NULL, 0) = 0--- SIGCHLD {si_signo=SIGCHLD, si_code=CLD_TRAPPED, si_pid=2867285, si_uid=1000, si_status=SIGTRAP, si_utime=0, si_stime=0} ---wait4(-1, [{WIFSTOPPED(s) && WSTOPSIG(s) == SIGTRAP | 0x80}], __WALL, NULL) = 2867285wait4(-1, 0x7ffe0ba737ac, WNOHANG|__WALL, NULL) = 0ptrace(PTRACE_SYSCALL, 2867285, NULL, 0) = 0wait4(-1, [{WIFSTOPPED(s) && WSTOPSIG(s) == SIGTRAP | 0x80}], __WALL, NULL) = 2867285--- SIGCHLD {si_signo=SIGCHLD, si_code=CLD_TRAPPED, si_pid=2867285, si_uid=1000, si_status=SIGTRAP, si_utime=0, si_stime=0} ---wait4(-1, 0x7ffe0ba737ac, WNOHANG|__WALL, NULL) = 0ptrace(PTRACE_GET_SYSCALL_INFO, 2867285, 88, {op=PTRACE_SYSCALL_INFO_ENTRY, arch=AUDIT_ARCH_X86_64, instruction_pointer=0x7ffa5c496ddb, stack_pointer=0x7ffca877c268, entry={nr=__NR_munmap, args=[0x7ffa5c442000, 0x241e8, 0, 0x7ffca877c240, 0, 0x7ffa5c4a7440]}}) = 80ptrace(PTRACE_SYSCALL, 2867285, NULL, 0) = 0wait4(-1, [{WIFSTOPPED(s) && WSTOPSIG(s) == SIGTRAP | 0x80}], __WALL, NULL) = 2867285--- SIGCHLD {si_signo=SIGCHLD, si_code=CLD_TRAPPED, si_pid=2867285, si_uid=1000, si_status=SIGTRAP, si_utime=0, si_stime=0} ---wait4(-1, 0x7ffe0ba737ac, WNOHANG|__WALL, NULL) = 0ptrace(PTRACE_SYSCALL, 2867285, NULL, 0) = 0wait4(-1, [{WIFSTOPPED(s) && WSTOPSIG(s) == SIGTRAP | 0x80}], __WALL, NULL) = 2867285--- SIGCHLD {si_signo=SIGCHLD, si_code=CLD_TRAPPED, si_pid=2867285, si_uid=1000, si_status=SIGTRAP, si_utime=0, si_stime=0} ---wait4(-1, 0x7ffe0ba737ac, WNOHANG|__WALL, NULL) = 0ptrace(PTRACE_GET_SYSCALL_INFO, 2867285, 88, {op=PTRACE_SYSCALL_INFO_ENTRY, arch=AUDIT_ARCH_X86_64, instruction_pointer=0x7ffa5c31c69b, stack_pointer=0x7ffca877c488, entry={nr=__NR_unlink, args=[0x63d5a3ac6008, 0x7ffca877c648, 0x7ffca877c658, 0x7ffca877c240, 0, 0x7ffa5c476380]}}) = 80process_vm_readv(2867285, [{iov_base="\1\0\2\0\0\0\0\0/tmp/ksa_m04_l02.lock\0/t"..., iov_len=4096}], 1, [{iov_base=0x63d5a3ac6000, iov_len=4096}], 1, 0) = 4096write(2, "unlink(\"/tmp/ksa_m04_l02.lock\"", 30) = 30ptrace(PTRACE_SYSCALL, 2867285, NULL, 0) = 0wait4(-1, [{WIFSTOPPED(s) && WSTOPSIG(s) == SIGTRAP | 0x80}], __WALL, NULL) = 2867285--- SIGCHLD {si_signo=SIGCHLD, si_code=CLD_TRAPPED, si_pid=2867285, si_uid=1000, si_status=SIGTRAP, si_utime=0, si_stime=0} ---wait4(-1, 0x7ffe0ba737ac, WNOHANG|__WALL, NULL) = 0ptrace(PTRACE_GET_SYSCALL_INFO, 2867285, 88, {op=PTRACE_SYSCALL_INFO_EXIT, arch=AUDIT_ARCH_X86_64, instruction_pointer=0x7ffa5c31c69b, stack_pointer=0x7ffca877c488, exit={rval=-ENOENT, is_error=1}}) = 33write(2, ") = -1 ENOENT (No such f"..., 50) = 50ptrace(PTRACE_SYSCALL, 2867285, NULL, 0) = 0--- SIGCHLD {si_signo=SIGCHLD, si_code=CLD_TRAPPED, si_pid=2867285, si_uid=1000, si_status=SIGTRAP, si_utime=0, si_stime=0} ---wait4(-1, [{WIFSTOPPED(s) && WSTOPSIG(s) == SIGTRAP | 0x80}], __WALL, NULL) = 2867285wait4(-1, 0x7ffe0ba737ac, WNOHANG|__WALL, NULL) = 0ptrace(PTRACE_GET_SYSCALL_INFO, 2867285, 88, {op=PTRACE_SYSCALL_INFO_ENTRY, arch=AUDIT_ARCH_X86_64, instruction_pointer=0x7ffa5c31b405, stack_pointer=0x7ffca877c410, entry={nr=__NR_openat, args=[0xffffff9c, 0x63d5a3ac6008, 0x800c1, 0x180, 0, 0x7ffa5c476380]}}) = 80process_vm_readv(2867285, [{iov_base="\1\0\2\0\0\0\0\0/tmp/ksa_m04_l02.lock\0/t"..., iov_len=4096}], 1, [{iov_base=0x63d5a3ac6000, iov_len=4096}], 1, 0) = 4096write(2, "openat(AT_FDCWD, \"/tmp/ksa_m04_l"..., 81) = 81ptrace(PTRACE_SYSCALL, 2867285, NULL, 0) = 0wait4(-1, [{WIFSTOPPED(s) && WSTOPSIG(s) == SIGTRAP | 0x80}], __WALL, NULL) = 2867285--- SIGCHLD {si_signo=SIGCHLD, si_code=CLD_TRAPPED, si_pid=2867285, si_uid=1000, si_status=SIGTRAP, si_utime=0, si_stime=0} ---wait4(-1, 0x7ffe0ba737ac, WNOHANG|__WALL, NULL) = 0ptrace(PTRACE_GET_SYSCALL_INFO, 2867285, 88, {op=PTRACE_SYSCALL_INFO_EXIT, arch=AUDIT_ARCH_X86_64, instruction_pointer=0x7ffa5c31b405, stack_pointer=0x7ffca877c410, exit={rval=3, is_error=0}}) = 33write(2, ") = 3\n", 6) = 6ptrace(PTRACE_SYSCALL, 2867285, NULL, 0) = 0--- SIGCHLD {si_signo=SIGCHLD, si_code=CLD_TRAPPED, si_pid=2867285, si_uid=1000, si_status=SIGTRAP, si_utime=0, si_stime=0} ---wait4(-1, [{WIFSTOPPED(s) && WSTOPSIG(s) == SIGTRAP | 0x80}], __WALL, NULL) = 2867285wait4(-1, 0x7ffe0ba737ac, WNOHANG|__WALL, NULL) = 0ptrace(PTRACE_GET_SYSCALL_INFO, 2867285, 88, {op=PTRACE_SYSCALL_INFO_ENTRY, arch=AUDIT_ARCH_X86_64, instruction_pointer=0x7ffa5c31b405, stack_pointer=0x7ffca877c410, entry={nr=__NR_openat, args=[0xffffff9c, 0x63d5a3ac6008, 0x800c1, 0x180, 0, 0x7ffa5c476380]}}) = 80process_vm_readv(2867285, [{iov_base="\1\0\2\0\0\0\0\0/tmp/ksa_m04_l02.lock\0/t"..., iov_len=4096}], 1, [{iov_base=0x63d5a3ac6000, iov_len=4096}], 1, 0) = 4096write(2, "openat(AT_FDCWD, \"/tmp/ksa_m04_l"..., 81) = 81ptrace(PTRACE_SYSCALL, 2867285, NULL, 0) = 0--- SIGCHLD {si_signo=SIGCHLD, si_code=CLD_TRAPPED, si_pid=2867285, si_uid=1000, si_status=SIGTRAP, si_utime=0, si_stime=0} ---wait4(-1, [{WIFSTOPPED(s) && WSTOPSIG(s) == SIGTRAP | 0x80}], __WALL, NULL) = 2867285wait4(-1, 0x7ffe0ba737ac, WNOHANG|__WALL, NULL) = 0ptrace(PTRACE_GET_SYSCALL_INFO, 2867285, 88, {op=PTRACE_SYSCALL_INFO_EXIT, arch=AUDIT_ARCH_X86_64, instruction_pointer=0x7ffa5c31b405, stack_pointer=0x7ffca877c410, exit={rval=-EEXIST, is_error=1}}) = 33write(2, ") = -1 EEXIST (File exists)\n", 28) = 28ptrace(PTRACE_SYSCALL, 2867285, NULL, 0) = 0--- SIGCHLD {si_signo=SIGCHLD, si_code=CLD_TRAPPED, si_pid=2867285, si_uid=1000, si_status=SIGTRAP, si_utime=0, si_stime=0} ---wait4(-1, [{WIFSTOPPED(s) && WSTOPSIG(s) == SIGTRAP | 0x80}], __WALL, NULL) = 2867285wait4(-1, 0x7ffe0ba737ac, WNOHANG|__WALL, NULL) = 0ptrace(PTRACE_GET_SYSCALL_INFO, 2867285, 88, {op=PTRACE_SYSCALL_INFO_ENTRY, arch=AUDIT_ARCH_X86_64, instruction_pointer=0x7ffa5c316984, stack_pointer=0x7ffca877c488, entry={nr=__NR_close, args=[0x3, 0x63d5a3ac6008, 0, 0x180, 0, 0x7ffa5c476380]}}) = 80write(2, "close(3", 7) = 7ptrace(PTRACE_SYSCALL, 2867285, NULL, 0) = 0--- SIGCHLD {si_signo=SIGCHLD, si_code=CLD_TRAPPED, si_pid=2867285, si_uid=1000, si_status=SIGTRAP, si_utime=0, si_stime=0} ---wait4(-1, [{WIFSTOPPED(s) && WSTOPSIG(s) == SIGTRAP | 0x80}], __WALL, NULL) = 2867285wait4(-1, 0x7ffe0ba737ac, WNOHANG|__WALL, NULL) = 0ptrace(PTRACE_GET_SYSCALL_INFO, 2867285, 88, {op=PTRACE_SYSCALL_INFO_EXIT, arch=AUDIT_ARCH_X86_64, instruction_pointer=0x7ffa5c316984, stack_pointer=0x7ffca877c488, exit={rval=0, is_error=0}}) = 33write(2, ") "..., 37) = 37ptrace(PTRACE_SYSCALL, 2867285, NULL, 0) = 0--- SIGCHLD {si_signo=SIGCHLD, si_code=CLD_TRAPPED, si_pid=2867285, si_uid=1000, si_status=SIGTRAP, si_utime=0, si_stime=0} ---wait4(-1, [{WIFSTOPPED(s) && WSTOPSIG(s) == SIGTRAP | 0x80}], __WALL, NULL) = 2867285wait4(-1, 0x7ffe0ba737ac, WNOHANG|__WALL, NULL) = 0ptrace(PTRACE_GET_SYSCALL_INFO, 2867285, 88, {op=PTRACE_SYSCALL_INFO_ENTRY, arch=AUDIT_ARCH_X86_64, instruction_pointer=0x7ffa5c31c69b, stack_pointer=0x7ffca877c488, entry={nr=__NR_unlink, args=[0x63d5a3ac6008, 0x63d5a3ac6008, 0, 0x180, 0, 0x7ffa5c476380]}}) = 80process_vm_readv(2867285, [{iov_base="\1\0\2\0\0\0\0\0/tmp/ksa_m04_l02.lock\0/t"..., iov_len=4096}], 1, [{iov_base=0x63d5a3ac6000, iov_len=4096}], 1, 0) = 4096write(2, "unlink(\"/tmp/ksa_m04_l02.lock\"", 30) = 30ptrace(PTRACE_SYSCALL, 2867285, NULL, 0) = 0wait4(-1, [{WIFSTOPPED(s) && WSTOPSIG(s) == SIGTRAP | 0x80}], __WALL, NULL) = 2867285--- SIGCHLD {si_signo=SIGCHLD, si_code=CLD_TRAPPED, si_pid=2867285, si_uid=1000, si_status=SIGTRAP, si_utime=0, si_stime=0} ---wait4(-1, 0x7ffe0ba737ac, WNOHANG|__WALL, NULL) = 0ptrace(PTRACE_GET_SYSCALL_INFO, 2867285, 88, {op=PTRACE_SYSCALL_INFO_EXIT, arch=AUDIT_ARCH_X86_64, instruction_pointer=0x7ffa5c31c69b, stack_pointer=0x7ffca877c488, exit={rval=0, is_error=0}}) = 33write(2, ") = 0\n", 14) = 14ptrace(PTRACE_SYSCALL, 2867285, NULL, 0) = 0wait4(-1, [{WIFSTOPPED(s) && WSTOPSIG(s) == SIGTRAP | 0x80}], __WALL, NULL) = 2867285--- SIGCHLD {si_signo=SIGCHLD, si_code=CLD_TRAPPED, si_pid=2867285, si_uid=1000, si_status=SIGTRAP, si_utime=0, si_stime=0} ---wait4(-1, 0x7ffe0ba737ac, WNOHANG|__WALL, NULL) = 0ptrace(PTRACE_GET_SYSCALL_INFO, 2867285, 88, {op=PTRACE_SYSCALL_INFO_ENTRY, arch=AUDIT_ARCH_X86_64, instruction_pointer=0x7ffa5c31761b, stack_pointer=0x7ffca877c0b8, entry={nr=__NR_fstat, args=[0x1, 0x7ffca877c0c0, 0x7ffa5c402ee0, 0xffffffff, 0x73, 0]}}) = 80ptrace(PTRACE_SYSCALL, 2867285, NULL, 0) = 0--- SIGCHLD {si_signo=SIGCHLD, si_code=CLD_TRAPPED, si_pid=2867285, si_uid=1000, si_status=SIGTRAP, si_utime=0, si_stime=0} ---wait4(-1, [{WIFSTOPPED(s) && WSTOPSIG(s) == SIGTRAP | 0x80}], __WALL, NULL) = 2867285wait4(-1, 0x7ffe0ba737ac, WNOHANG|__WALL, NULL) = 0ptrace(PTRACE_SYSCALL, 2867285, NULL, 0) = 0--- SIGCHLD {si_signo=SIGCHLD, si_code=CLD_TRAPPED, si_pid=2867285, si_uid=1000, si_status=SIGTRAP, si_utime=0, si_stime=0} ---wait4(-1, [{WIFSTOPPED(s) && WSTOPSIG(s) == SIGTRAP | 0x80}], __WALL, NULL) = 2867285wait4(-1, 0x7ffe0ba737ac, WNOHANG|__WALL, NULL) = 0ptrace(PTRACE_GET_SYSCALL_INFO, 2867285, 88, {op=PTRACE_SYSCALL_INFO_ENTRY, arch=AUDIT_ARCH_X86_64, instruction_pointer=0x7ffa5c2a9e69, stack_pointer=0x7ffca877c040, entry={nr=__NR_getrandom, args=[0x7ffa5c40b178, 0x8, 0x1, 0xffffffff, 0x73, 0]}}) = 80ptrace(PTRACE_SYSCALL, 2867285, NULL, 0) = 0--- SIGCHLD {si_signo=SIGCHLD, si_code=CLD_TRAPPED, si_pid=2867285, si_uid=1000, si_status=SIGTRAP, si_utime=0, si_stime=0} ---wait4(-1, [{WIFSTOPPED(s) && WSTOPSIG(s) == SIGTRAP | 0x80}], __WALL, NULL) = 2867285wait4(-1, 0x7ffe0ba737ac, WNOHANG|__WALL, NULL) = 0ptrace(PTRACE_SYSCALL, 2867285, NULL, 0) = 0--- SIGCHLD {si_signo=SIGCHLD, si_code=CLD_TRAPPED, si_pid=2867285, si_uid=1000, si_status=SIGTRAP, si_utime=0, si_stime=0} ---wait4(-1, [{WIFSTOPPED(s) && WSTOPSIG(s) == SIGTRAP | 0x80}], __WALL, NULL) = 2867285wait4(-1, 0x7ffe0ba737ac, WNOHANG|__WALL, NULL) = 0ptrace(PTRACE_GET_SYSCALL_INFO, 2867285, 88, {op=PTRACE_SYSCALL_INFO_ENTRY, arch=AUDIT_ARCH_X86_64, instruction_pointer=0x7ffa5c31da0b, stack_pointer=0x7ffca877bf78, entry={nr=__NR_brk, args=[0, 0x7ffa5c404b20, 0x7ffa5c404b20, 0x1, 0x21000, 0]}}) = 80ptrace(PTRACE_SYSCALL, 2867285, NULL, 0) = 0--- SIGCHLD {si_signo=SIGCHLD, si_code=CLD_TRAPPED, si_pid=2867285, si_uid=1000, si_status=SIGTRAP, si_utime=0, si_stime=0} ---wait4(-1, [{WIFSTOPPED(s) && WSTOPSIG(s) == SIGTRAP | 0x80}], __WALL, NULL) = 2867285wait4(-1, 0x7ffe0ba737ac, WNOHANG|__WALL, NULL) = 0ptrace(PTRACE_SYSCALL, 2867285, NULL, 0) = 0--- SIGCHLD {si_signo=SIGCHLD, si_code=CLD_TRAPPED, si_pid=2867285, si_uid=1000, si_status=SIGTRAP, si_utime=0, si_stime=0} ---wait4(-1, [{WIFSTOPPED(s) && WSTOPSIG(s) == SIGTRAP | 0x80}], __WALL, NULL) = 2867285wait4(-1, 0x7ffe0ba737ac, WNOHANG|__WALL, NULL) = 0ptrace(PTRACE_GET_SYSCALL_INFO, 2867285, 88, {op=PTRACE_SYSCALL_INFO_ENTRY, arch=AUDIT_ARCH_X86_64, instruction_pointer=0x7ffa5c31da0b, stack_pointer=0x7ffca877bf78, entry={nr=__NR_brk, args=[0x63d5a68de000, 0x7ffa5c404b20, 0x7ffa5c40bd70, 0x1, 0x21000, 0]}}) = 80ptrace(PTRACE_SYSCALL, 2867285, NULL, 0) = 0--- SIGCHLD {si_signo=SIGCHLD, si_code=CLD_TRAPPED, si_pid=2867285, si_uid=1000, si_status=SIGTRAP, si_utime=0, si_stime=0} ---wait4(-1, [{WIFSTOPPED(s) && WSTOPSIG(s) == SIGTRAP | 0x80}], __WALL, NULL) = 2867285wait4(-1, 0x7ffe0ba737ac, WNOHANG|__WALL, NULL) = 0ptrace(PTRACE_SYSCALL, 2867285, NULL, 0) = 0wait4(-1, [{WIFSTOPPED(s) && WSTOPSIG(s) == SIGTRAP | 0x80}], __WALL, NULL) = 2867285--- SIGCHLD {si_signo=SIGCHLD, si_code=CLD_TRAPPED, si_pid=2867285, si_uid=1000, si_status=SIGTRAP, si_utime=0, si_stime=0} ---wait4(-1, 0x7ffe0ba737ac, WNOHANG|__WALL, NULL) = 0ptrace(PTRACE_GET_SYSCALL_INFO, 2867285, 88, {op=PTRACE_SYSCALL_INFO_ENTRY, arch=AUDIT_ARCH_X86_64, instruction_pointer=0x7ffa5c31b405, stack_pointer=0x7ffca877c410, entry={nr=__NR_openat, args=[0xffffff9c, 0x63d5a3ac601e, 0x80242, 0x1a4, 0x7ffa5c404b20, 0]}}) = 80process_vm_readv(2867285, [{iov_base="\1\0\2\0\0\0\0\0/tmp/ksa_m04_l02.lock\0/t"..., iov_len=4096}], 1, [{iov_base=0x63d5a3ac6000, iov_len=4096}], 1, 0) = 4096write(2, "openat(AT_FDCWD, \"/tmp/ksa_m04_l"..., 85) = 85ptrace(PTRACE_SYSCALL, 2867285, NULL, 0) = 0wait4(-1, [{WIFSTOPPED(s) && WSTOPSIG(s) == SIGTRAP | 0x80}], __WALL, NULL) = 2867285--- SIGCHLD {si_signo=SIGCHLD, si_code=CLD_TRAPPED, si_pid=2867285, si_uid=1000, si_status=SIGTRAP, si_utime=0, si_stime=0} ---wait4(-1, 0x7ffe0ba737ac, WNOHANG|__WALL, NULL) = 0ptrace(PTRACE_GET_SYSCALL_INFO, 2867285, 88, {op=PTRACE_SYSCALL_INFO_EXIT, arch=AUDIT_ARCH_X86_64, instruction_pointer=0x7ffa5c31b405, stack_pointer=0x7ffca877c410, exit={rval=3, is_error=0}}) = 33write(2, ") = 3\n", 6) = 6ptrace(PTRACE_SYSCALL, 2867285, NULL, 0) = 0--- SIGCHLD {si_signo=SIGCHLD, si_code=CLD_TRAPPED, si_pid=2867285, si_uid=1000, si_status=SIGTRAP, si_utime=0, si_stime=0} ---wait4(-1, [{WIFSTOPPED(s) && WSTOPSIG(s) == SIGTRAP | 0x80}], __WALL, NULL) = 2867285wait4(-1, 0x7ffe0ba737ac, WNOHANG|__WALL, NULL) = 0ptrace(PTRACE_GET_SYSCALL_INFO, 2867285, 88, {op=PTRACE_SYSCALL_INFO_ENTRY, arch=AUDIT_ARCH_X86_64, instruction_pointer=0x7ffa5c316bcb, stack_pointer=0x7ffca877c488, entry={nr=__NR_dup, args=[0x3, 0x63d5a3ac601e, 0, 0x1a4, 0x7ffa5c404b20, 0]}}) = 80ptrace(PTRACE_SYSCALL, 2867285, NULL, 0) = 0--- SIGCHLD {si_signo=SIGCHLD, si_code=CLD_TRAPPED, si_pid=2867285, si_uid=1000, si_status=SIGTRAP, si_utime=0, si_stime=0} ---wait4(-1, [{WIFSTOPPED(s) && WSTOPSIG(s) == SIGTRAP | 0x80}], __WALL, NULL) = 2867285wait4(-1, 0x7ffe0ba737ac, WNOHANG|__WALL, NULL) = 0ptrace(PTRACE_SYSCALL, 2867285, NULL, 0) = 0--- SIGCHLD {si_signo=SIGCHLD, si_code=CLD_TRAPPED, si_pid=2867285, si_uid=1000, si_status=SIGTRAP, si_utime=0, si_stime=0} ---wait4(-1, [{WIFSTOPPED(s) && WSTOPSIG(s) == SIGTRAP | 0x80}], __WALL, NULL) = 2867285wait4(-1, 0x7ffe0ba737ac, WNOHANG|__WALL, NULL) = 0ptrace(PTRACE_GET_SYSCALL_INFO, 2867285, 88, {op=PTRACE_SYSCALL_INFO_ENTRY, arch=AUDIT_ARCH_X86_64, instruction_pointer=0x7ffa5c31c804, stack_pointer=0x7ffca877c488, entry={nr=__NR_write, args=[0x3, 0x63d5a3ac6066, 0x10, 0x1a4, 0x7ffa5c404b20, 0]}}) = 80ptrace(PTRACE_SYSCALL, 2867285, NULL, 0) = 0wait4(-1, [{WIFSTOPPED(s) && WSTOPSIG(s) == SIGTRAP | 0x80}], __WALL, NULL) = 2867285--- SIGCHLD {si_signo=SIGCHLD, si_code=CLD_TRAPPED, si_pid=2867285, si_uid=1000, si_status=SIGTRAP, si_utime=0, si_stime=0} ---wait4(-1, 0x7ffe0ba737ac, WNOHANG|__WALL, NULL) = 0ptrace(PTRACE_SYSCALL, 2867285, NULL, 0) = 0--- SIGCHLD {si_signo=SIGCHLD, si_code=CLD_TRAPPED, si_pid=2867285, si_uid=1000, si_status=SIGTRAP, si_utime=0, si_stime=0} ---wait4(-1, [{WIFSTOPPED(s) && WSTOPSIG(s) == SIGTRAP | 0x80}], __WALL, NULL) = 2867285wait4(-1, 0x7ffe0ba737ac, WNOHANG|__WALL, NULL) = 0ptrace(PTRACE_GET_SYSCALL_INFO, 2867285, 88, {op=PTRACE_SYSCALL_INFO_ENTRY, arch=AUDIT_ARCH_X86_64, instruction_pointer=0x7ffa5c31b26b, stack_pointer=0x7ffca877c488, entry={nr=__NR_lseek, args=[0x3, 0, 0, 0x1a4, 0x7ffa5c404b20, 0]}}) = 80ptrace(PTRACE_SYSCALL, 2867285, NULL, 0) = 0--- SIGCHLD {si_signo=SIGCHLD, si_code=CLD_TRAPPED, si_pid=2867285, si_uid=1000, si_status=SIGTRAP, si_utime=0, si_stime=0} ---wait4(-1, [{WIFSTOPPED(s) && WSTOPSIG(s) == SIGTRAP | 0x80}], __WALL, NULL) = 2867285wait4(-1, 0x7ffe0ba737ac, WNOHANG|__WALL, NULL) = 0ptrace(PTRACE_SYSCALL, 2867285, NULL, 0) = 0--- SIGCHLD {si_signo=SIGCHLD, si_code=CLD_TRAPPED, si_pid=2867285, si_uid=1000, si_status=SIGTRAP, si_utime=0, si_stime=0} ---wait4(-1, [{WIFSTOPPED(s) && WSTOPSIG(s) == SIGTRAP | 0x80}], __WALL, NULL) = 2867285wait4(-1, 0x7ffe0ba737ac, WNOHANG|__WALL, NULL) = 0ptrace(PTRACE_GET_SYSCALL_INFO, 2867285, 88, {op=PTRACE_SYSCALL_INFO_ENTRY, arch=AUDIT_ARCH_X86_64, instruction_pointer=0x7ffa5c31b26b, stack_pointer=0x7ffca877c488, entry={nr=__NR_lseek, args=[0x4, 0x8, 0, 0x1a4, 0x7ffa5c404b20, 0]}}) = 80ptrace(PTRACE_SYSCALL, 2867285, NULL, 0) = 0--- SIGCHLD {si_signo=SIGCHLD, si_code=CLD_TRAPPED, si_pid=2867285, si_uid=1000, si_status=SIGTRAP, si_utime=0, si_stime=0} ---wait4(-1, [{WIFSTOPPED(s) && WSTOPSIG(s) == SIGTRAP | 0x80}], __WALL, NULL) = 2867285wait4(-1, 0x7ffe0ba737ac, WNOHANG|__WALL, NULL) = 0ptrace(PTRACE_SYSCALL, 2867285, NULL, 0) = 0--- SIGCHLD {si_signo=SIGCHLD, si_code=CLD_TRAPPED, si_pid=2867285, si_uid=1000, si_status=SIGTRAP, si_utime=0, si_stime=0} ---wait4(-1, [{WIFSTOPPED(s) && WSTOPSIG(s) == SIGTRAP | 0x80}], __WALL, NULL) = 2867285wait4(-1, 0x7ffe0ba737ac, WNOHANG|__WALL, NULL) = 0ptrace(PTRACE_GET_SYSCALL_INFO, 2867285, 88, {op=PTRACE_SYSCALL_INFO_ENTRY, arch=AUDIT_ARCH_X86_64, instruction_pointer=0x7ffa5c31c804, stack_pointer=0x7ffca877c488, entry={nr=__NR_write, args=[0x4, 0x63d5a3ac6077, 0x8, 0x1a4, 0x7ffa5c404b20, 0]}}) = 80ptrace(PTRACE_SYSCALL, 2867285, NULL, 0) = 0--- SIGCHLD {si_signo=SIGCHLD, si_code=CLD_TRAPPED, si_pid=2867285, si_uid=1000, si_status=SIGTRAP, si_utime=0, si_stime=0} ---wait4(-1, [{WIFSTOPPED(s) && WSTOPSIG(s) == SIGTRAP | 0x80}], __WALL, NULL) = 2867285wait4(-1, 0x7ffe0ba737ac, WNOHANG|__WALL, NULL) = 0ptrace(PTRACE_SYSCALL, 2867285, NULL, 0) = 0--- SIGCHLD {si_signo=SIGCHLD, si_code=CLD_TRAPPED, si_pid=2867285, si_uid=1000, si_status=SIGTRAP, si_utime=0, si_stime=0} ---wait4(-1, [{WIFSTOPPED(s) && WSTOPSIG(s) == SIGTRAP | 0x80}], __WALL, NULL) = 2867285wait4(-1, 0x7ffe0ba737ac, WNOHANG|__WALL, NULL) = 0ptrace(PTRACE_GET_SYSCALL_INFO, 2867285, 88, {op=PTRACE_SYSCALL_INFO_ENTRY, arch=AUDIT_ARCH_X86_64, instruction_pointer=0x7ffa5c31c804, stack_pointer=0x7ffca877c488, entry={nr=__NR_write, args=[0x3, 0x63d5a3ac6080, 0x8, 0x1a4, 0x7ffa5c404b20, 0]}}) = 80ptrace(PTRACE_SYSCALL, 2867285, NULL, 0) = 0--- SIGCHLD {si_signo=SIGCHLD, si_code=CLD_TRAPPED, si_pid=2867285, si_uid=1000, si_status=SIGTRAP, si_utime=0, si_stime=0} ---wait4(-1, [{WIFSTOPPED(s) && WSTOPSIG(s) == SIGTRAP | 0x80}], __WALL, NULL) = 2867285wait4(-1, 0x7ffe0ba737ac, WNOHANG|__WALL, NULL) = 0ptrace(PTRACE_SYSCALL, 2867285, NULL, 0) = 0--- SIGCHLD {si_signo=SIGCHLD, si_code=CLD_TRAPPED, si_pid=2867285, si_uid=1000, si_status=SIGTRAP, si_utime=0, si_stime=0} ---wait4(-1, [{WIFSTOPPED(s) && WSTOPSIG(s) == SIGTRAP | 0x80}], __WALL, NULL) = 2867285wait4(-1, 0x7ffe0ba737ac, WNOHANG|__WALL, NULL) = 0ptrace(PTRACE_GET_SYSCALL_INFO, 2867285, 88, {op=PTRACE_SYSCALL_INFO_ENTRY, arch=AUDIT_ARCH_X86_64, instruction_pointer=0x7ffa5c2fa537, stack_pointer=0x7ffca877c488, entry={nr=__NR_pread64, args=[0x3, 0x7ffca877c4e5, 0x8, 0, 0x7ffa5c404b20, 0]}}) = 80write(2, "pread64(3, ", 11) = 11ptrace(PTRACE_SYSCALL, 2867285, NULL, 0) = 0--- SIGCHLD {si_signo=SIGCHLD, si_code=CLD_TRAPPED, si_pid=2867285, si_uid=1000, si_status=SIGTRAP, si_utime=0, si_stime=0} ---wait4(-1, [{WIFSTOPPED(s) && WSTOPSIG(s) == SIGTRAP | 0x80}], __WALL, NULL) = 2867285wait4(-1, 0x7ffe0ba737ac, WNOHANG|__WALL, NULL) = 0ptrace(PTRACE_GET_SYSCALL_INFO, 2867285, 88, {op=PTRACE_SYSCALL_INFO_EXIT, arch=AUDIT_ARCH_X86_64, instruction_pointer=0x7ffa5c2fa537, stack_pointer=0x7ffca877c488, exit={rval=8, is_error=0}}) = 33process_vm_readv(2867285, [{iov_base="\0\20\2\0\0\0\0\0\0\211X\16\221\321iF\200\246J\\\372\177\0\0\377\0\0\0\0\0\0\0"..., iov_len=4096}], 1, [{iov_base=0x7ffca877c000, iov_len=4096}], 1, 0) = 4096write(2, "\"00000000\", 8, 0) = 8"..., 33) = 33ptrace(PTRACE_SYSCALL, 2867285, NULL, 0) = 0--- SIGCHLD {si_signo=SIGCHLD, si_code=CLD_TRAPPED, si_pid=2867285, si_uid=1000, si_status=SIGTRAP, si_utime=0, si_stime=0} ---wait4(-1, [{WIFSTOPPED(s) && WSTOPSIG(s) == SIGTRAP | 0x80}], __WALL, NULL) = 2867285wait4(-1, 0x7ffe0ba737ac, WNOHANG|__WALL, NULL) = 0ptrace(PTRACE_GET_SYSCALL_INFO, 2867285, 88, {op=PTRACE_SYSCALL_INFO_ENTRY, arch=AUDIT_ARCH_X86_64, instruction_pointer=0x7ffa5c31b26b, stack_pointer=0x7ffca877c488, entry={nr=__NR_lseek, args=[0x3, 0, 0x2, 0, 0x7ffa5c404b20, 0]}}) = 80ptrace(PTRACE_SYSCALL, 2867285, NULL, 0) = 0--- SIGCHLD {si_signo=SIGCHLD, si_code=CLD_TRAPPED, si_pid=2867285, si_uid=1000, si_status=SIGTRAP, si_utime=0, si_stime=0} ---wait4(-1, [{WIFSTOPPED(s) && WSTOPSIG(s) == SIGTRAP | 0x80}], __WALL, NULL) = 2867285wait4(-1, 0x7ffe0ba737ac, WNOHANG|__WALL, NULL) = 0ptrace(PTRACE_SYSCALL, 2867285, NULL, 0) = 0--- SIGCHLD {si_signo=SIGCHLD, si_code=CLD_TRAPPED, si_pid=2867285, si_uid=1000, si_status=SIGTRAP, si_utime=0, si_stime=0} ---wait4(-1, [{WIFSTOPPED(s) && WSTOPSIG(s) == SIGTRAP | 0x80}], __WALL, NULL) = 2867285wait4(-1, 0x7ffe0ba737ac, WNOHANG|__WALL, NULL) = 0ptrace(PTRACE_GET_SYSCALL_INFO, 2867285, 88, {op=PTRACE_SYSCALL_INFO_ENTRY, arch=AUDIT_ARCH_X86_64, instruction_pointer=0x7ffa5c316984, stack_pointer=0x7ffca877c488, entry={nr=__NR_close, args=[0x4, 0x7ffa5c4055c0, 0, 0, 0x64, 0]}}) = 80write(2, "close(4", 7) = 7ptrace(PTRACE_SYSCALL, 2867285, NULL, 0) = 0--- SIGCHLD {si_signo=SIGCHLD, si_code=CLD_TRAPPED, si_pid=2867285, si_uid=1000, si_status=SIGTRAP, si_utime=0, si_stime=0} ---wait4(-1, [{WIFSTOPPED(s) && WSTOPSIG(s) == SIGTRAP | 0x80}], __WALL, NULL) = 2867285wait4(-1, 0x7ffe0ba737ac, WNOHANG|__WALL, NULL) = 0ptrace(PTRACE_GET_SYSCALL_INFO, 2867285, 88, {op=PTRACE_SYSCALL_INFO_EXIT, arch=AUDIT_ARCH_X86_64, instruction_pointer=0x7ffa5c316984, stack_pointer=0x7ffca877c488, exit={rval=0, is_error=0}}) = 33write(2, ") "..., 37) = 37ptrace(PTRACE_SYSCALL, 2867285, NULL, 0) = 0--- SIGCHLD {si_signo=SIGCHLD, si_code=CLD_TRAPPED, si_pid=2867285, si_uid=1000, si_status=SIGTRAP, si_utime=0, si_stime=0} ---wait4(-1, [{WIFSTOPPED(s) && WSTOPSIG(s) == SIGTRAP | 0x80}], __WALL, NULL) = 2867285wait4(-1, 0x7ffe0ba737ac, WNOHANG|__WALL, NULL) = 0ptrace(PTRACE_GET_SYSCALL_INFO, 2867285, 88, {op=PTRACE_SYSCALL_INFO_ENTRY, arch=AUDIT_ARCH_X86_64, instruction_pointer=0x7ffa5c316984, stack_pointer=0x7ffca877c488, entry={nr=__NR_close, args=[0x3, 0x7ffa5c4055c0, 0, 0, 0x64, 0]}}) = 80write(2, "close(3", 7) = 7ptrace(PTRACE_SYSCALL, 2867285, NULL, 0) = 0--- SIGCHLD {si_signo=SIGCHLD, si_code=CLD_TRAPPED, si_pid=2867285, si_uid=1000, si_status=SIGTRAP, si_utime=0, si_stime=0} ---wait4(-1, [{WIFSTOPPED(s) && WSTOPSIG(s) == SIGTRAP | 0x80}], __WALL, NULL) = 2867285wait4(-1, 0x7ffe0ba737ac, WNOHANG|__WALL, NULL) = 0ptrace(PTRACE_GET_SYSCALL_INFO, 2867285, 88, {op=PTRACE_SYSCALL_INFO_EXIT, arch=AUDIT_ARCH_X86_64, instruction_pointer=0x7ffa5c316984, stack_pointer=0x7ffca877c488, exit={rval=0, is_error=0}}) = 33write(2, ") "..., 37) = 37ptrace(PTRACE_SYSCALL, 2867285, NULL, 0) = 0--- SIGCHLD {si_signo=SIGCHLD, si_code=CLD_TRAPPED, si_pid=2867285, si_uid=1000, si_status=SIGTRAP, si_utime=0, si_stime=0} ---wait4(-1, [{WIFSTOPPED(s) && WSTOPSIG(s) == SIGTRAP | 0x80}], __WALL, NULL) = 2867285wait4(-1, 0x7ffe0ba737ac, WNOHANG|__WALL, NULL) = 0ptrace(PTRACE_GET_SYSCALL_INFO, 2867285, 88, {op=PTRACE_SYSCALL_INFO_ENTRY, arch=AUDIT_ARCH_X86_64, instruction_pointer=0x7ffa5c31b405, stack_pointer=0x7ffca877c410, entry={nr=__NR_openat, args=[0xffffff9c, 0x63d5a3ac601e, 0x80202, 0, 0x64, 0]}}) = 80process_vm_readv(2867285, [{iov_base="\1\0\2\0\0\0\0\0/tmp/ksa_m04_l02.lock\0/t"..., iov_len=4096}], 1, [{iov_base=0x63d5a3ac6000, iov_len=4096}], 1, 0) = 4096write(2, "openat(AT_FDCWD, \"/tmp/ksa_m04_l"..., 71) = 71ptrace(PTRACE_SYSCALL, 2867285, NULL, 0) = 0wait4(-1, [{WIFSTOPPED(s) && WSTOPSIG(s) == SIGTRAP | 0x80}], __WALL, NULL) = 2867285--- SIGCHLD {si_signo=SIGCHLD, si_code=CLD_TRAPPED, si_pid=2867285, si_uid=1000, si_status=SIGTRAP, si_utime=0, si_stime=0} ---wait4(-1, 0x7ffe0ba737ac, WNOHANG|__WALL, NULL) = 0ptrace(PTRACE_GET_SYSCALL_INFO, 2867285, 88, {op=PTRACE_SYSCALL_INFO_EXIT, arch=AUDIT_ARCH_X86_64, instruction_pointer=0x7ffa5c31b405, stack_pointer=0x7ffca877c410, exit={rval=3, is_error=0}}) = 33write(2, ") = 3\n", 6) = 6ptrace(PTRACE_SYSCALL, 2867285, NULL, 0) = 0--- SIGCHLD {si_signo=SIGCHLD, si_code=CLD_TRAPPED, si_pid=2867285, si_uid=1000, si_status=SIGTRAP, si_utime=0, si_stime=0} ---wait4(-1, [{WIFSTOPPED(s) && WSTOPSIG(s) == SIGTRAP | 0x80}], __WALL, NULL) = 2867285wait4(-1, 0x7ffe0ba737ac, WNOHANG|__WALL, NULL) = 0ptrace(PTRACE_GET_SYSCALL_INFO, 2867285, 88, {op=PTRACE_SYSCALL_INFO_ENTRY, arch=AUDIT_ARCH_X86_64, instruction_pointer=0x7ffa5c316bcb, stack_pointer=0x7ffca877c488, entry={nr=__NR_dup, args=[0x3, 0x63d5a3ac601e, 0, 0, 0x64, 0]}}) = 80ptrace(PTRACE_SYSCALL, 2867285, NULL, 0) = 0--- SIGCHLD {si_signo=SIGCHLD, si_code=CLD_TRAPPED, si_pid=2867285, si_uid=1000, si_status=SIGTRAP, si_utime=0, si_stime=0} ---wait4(-1, [{WIFSTOPPED(s) && WSTOPSIG(s) == SIGTRAP | 0x80}], __WALL, NULL) = 2867285wait4(-1, 0x7ffe0ba737ac, WNOHANG|__WALL, NULL) = 0ptrace(PTRACE_SYSCALL, 2867285, NULL, 0) = 0--- SIGCHLD {si_signo=SIGCHLD, si_code=CLD_TRAPPED, si_pid=2867285, si_uid=1000, si_status=SIGTRAP, si_utime=0, si_stime=0} ---wait4(-1, [{WIFSTOPPED(s) && WSTOPSIG(s) == SIGTRAP | 0x80}], __WALL, NULL) = 2867285wait4(-1, 0x7ffe0ba737ac, WNOHANG|__WALL, NULL) = 0ptrace(PTRACE_GET_SYSCALL_INFO, 2867285, 88, {op=PTRACE_SYSCALL_INFO_ENTRY, arch=AUDIT_ARCH_X86_64, instruction_pointer=0x7ffa5c31c804, stack_pointer=0x7ffca877c488, entry={nr=__NR_write, args=[0x3, 0x63d5a3ac6066, 0x10, 0, 0x64, 0]}}) = 80ptrace(PTRACE_SYSCALL, 2867285, NULL, 0) = 0wait4(-1, [{WIFSTOPPED(s) && WSTOPSIG(s) == SIGTRAP | 0x80}], __WALL, NULL) = 2867285--- SIGCHLD {si_signo=SIGCHLD, si_code=CLD_TRAPPED, si_pid=2867285, si_uid=1000, si_status=SIGTRAP, si_utime=0, si_stime=0} ---wait4(-1, 0x7ffe0ba737ac, WNOHANG|__WALL, NULL) = 0ptrace(PTRACE_SYSCALL, 2867285, NULL, 0) = 0--- SIGCHLD {si_signo=SIGCHLD, si_code=CLD_TRAPPED, si_pid=2867285, si_uid=1000, si_status=SIGTRAP, si_utime=0, si_stime=0} ---wait4(-1, [{WIFSTOPPED(s) && WSTOPSIG(s) == SIGTRAP | 0x80}], __WALL, NULL) = 2867285wait4(-1, 0x7ffe0ba737ac, WNOHANG|__WALL, NULL) = 0ptrace(PTRACE_GET_SYSCALL_INFO, 2867285, 88, {op=PTRACE_SYSCALL_INFO_ENTRY, arch=AUDIT_ARCH_X86_64, instruction_pointer=0x7ffa5c31b26b, stack_pointer=0x7ffca877c488, entry={nr=__NR_lseek, args=[0x3, 0x4, 0, 0, 0x64, 0]}}) = 80ptrace(PTRACE_SYSCALL, 2867285, NULL, 0) = 0--- SIGCHLD {si_signo=SIGCHLD, si_code=CLD_TRAPPED, si_pid=2867285, si_uid=1000, si_status=SIGTRAP, si_utime=0, si_stime=0} ---wait4(-1, [{WIFSTOPPED(s) && WSTOPSIG(s) == SIGTRAP | 0x80}], __WALL, NULL) = 2867285wait4(-1, 0x7ffe0ba737ac, WNOHANG|__WALL, NULL) = 0ptrace(PTRACE_SYSCALL, 2867285, NULL, 0) = 0--- SIGCHLD {si_signo=SIGCHLD, si_code=CLD_TRAPPED, si_pid=2867285, si_uid=1000, si_status=SIGTRAP, si_utime=0, si_stime=0} ---wait4(-1, [{WIFSTOPPED(s) && WSTOPSIG(s) == SIGTRAP | 0x80}], __WALL, NULL) = 2867285wait4(-1, 0x7ffe0ba737ac, WNOHANG|__WALL, NULL) = 0ptrace(PTRACE_GET_SYSCALL_INFO, 2867285, 88, {op=PTRACE_SYSCALL_INFO_ENTRY, arch=AUDIT_ARCH_X86_64, instruction_pointer=0x7ffa5c2fa5d7, stack_pointer=0x7ffca877c438, entry={nr=__NR_pwrite64, args=[0x3, 0x63d5a3ac60bb, 0x8, 0, 0x64, 0]}}) = 80process_vm_readv(2867285, [{iov_base="\1\0\2\0\0\0\0\0/tmp/ksa_m04_l02.lock\0/t"..., iov_len=4096}], 1, [{iov_base=0x63d5a3ac6000, iov_len=4096}], 1, 0) = 4096write(2, "pwrite64(3, \"SLOT0_OK\", 8, 0", 28) = 28ptrace(PTRACE_SYSCALL, 2867285, NULL, 0) = 0--- SIGCHLD {si_signo=SIGCHLD, si_code=CLD_TRAPPED, si_pid=2867285, si_uid=1000, si_status=SIGTRAP, si_utime=0, si_stime=0} ---wait4(-1, [{WIFSTOPPED(s) && WSTOPSIG(s) == SIGTRAP | 0x80}], __WALL, NULL) = 2867285wait4(-1, 0x7ffe0ba737ac, WNOHANG|__WALL, NULL) = 0ptrace(PTRACE_GET_SYSCALL_INFO, 2867285, 88, {op=PTRACE_SYSCALL_INFO_EXIT, arch=AUDIT_ARCH_X86_64, instruction_pointer=0x7ffa5c2fa5d7, stack_pointer=0x7ffca877c438, exit={rval=8, is_error=0}}) = 33write(2, ") = 8\n", 16) = 16ptrace(PTRACE_SYSCALL, 2867285, NULL, 0) = 0--- SIGCHLD {si_signo=SIGCHLD, si_code=CLD_TRAPPED, si_pid=2867285, si_uid=1000, si_status=SIGTRAP, si_utime=0, si_stime=0} ---wait4(-1, [{WIFSTOPPED(s) && WSTOPSIG(s) == SIGTRAP | 0x80}], __WALL, NULL) = 2867285wait4(-1, 0x7ffe0ba737ac, WNOHANG|__WALL, NULL) = 0ptrace(PTRACE_GET_SYSCALL_INFO, 2867285, 88, {op=PTRACE_SYSCALL_INFO_ENTRY, arch=AUDIT_ARCH_X86_64, instruction_pointer=0x7ffa5c2fa5d7, stack_pointer=0x7ffca877c438, entry={nr=__NR_pwrite64, args=[0x4, 0x63d5a3ac60c4, 0x8, 0x8, 0x64, 0]}}) = 80process_vm_readv(2867285, [{iov_base="\1\0\2\0\0\0\0\0/tmp/ksa_m04_l02.lock\0/t"..., iov_len=4096}], 1, [{iov_base=0x63d5a3ac6000, iov_len=4096}], 1, 0) = 4096write(2, "pwrite64(4, \"SLOT1_OK\", 8, 8", 28) = 28ptrace(PTRACE_SYSCALL, 2867285, NULL, 0) = 0--- SIGCHLD {si_signo=SIGCHLD, si_code=CLD_TRAPPED, si_pid=2867285, si_uid=1000, si_status=SIGTRAP, si_utime=0, si_stime=0} ---wait4(-1, [{WIFSTOPPED(s) && WSTOPSIG(s) == SIGTRAP | 0x80}], __WALL, NULL) = 2867285wait4(-1, 0x7ffe0ba737ac, WNOHANG|__WALL, NULL) = 0ptrace(PTRACE_GET_SYSCALL_INFO, 2867285, 88, {op=PTRACE_SYSCALL_INFO_EXIT, arch=AUDIT_ARCH_X86_64, instruction_pointer=0x7ffa5c2fa5d7, stack_pointer=0x7ffca877c438, exit={rval=8, is_error=0}}) = 33write(2, ") = 8\n", 16) = 16ptrace(PTRACE_SYSCALL, 2867285, NULL, 0) = 0--- SIGCHLD {si_signo=SIGCHLD, si_code=CLD_TRAPPED, si_pid=2867285, si_uid=1000, si_status=SIGTRAP, si_utime=0, si_stime=0} ---wait4(-1, [{WIFSTOPPED(s) && WSTOPSIG(s) == SIGTRAP | 0x80}], __WALL, NULL) = 2867285wait4(-1, 0x7ffe0ba737ac, WNOHANG|__WALL, NULL) = 0ptrace(PTRACE_GET_SYSCALL_INFO, 2867285, 88, {op=PTRACE_SYSCALL_INFO_ENTRY, arch=AUDIT_ARCH_X86_64, instruction_pointer=0x7ffa5c2fa537, stack_pointer=0x7ffca877c488, entry={nr=__NR_pread64, args=[0x3, 0x7ffca877c4ee, 0x8, 0, 0x64, 0]}}) = 80write(2, "pread64(3, ", 11) = 11ptrace(PTRACE_SYSCALL, 2867285, NULL, 0) = 0--- SIGCHLD {si_signo=SIGCHLD, si_code=CLD_TRAPPED, si_pid=2867285, si_uid=1000, si_status=SIGTRAP, si_utime=0, si_stime=0} ---wait4(-1, [{WIFSTOPPED(s) && WSTOPSIG(s) == SIGTRAP | 0x80}], __WALL, NULL) = 2867285wait4(-1, 0x7ffe0ba737ac, WNOHANG|__WALL, NULL) = 0ptrace(PTRACE_GET_SYSCALL_INFO, 2867285, 88, {op=PTRACE_SYSCALL_INFO_EXIT, arch=AUDIT_ARCH_X86_64, instruction_pointer=0x7ffa5c2fa537, stack_pointer=0x7ffca877c488, exit={rval=8, is_error=0}}) = 33process_vm_readv(2867285, [{iov_base="\0\20\2\0\0\0\0\0\0\211X\16\221\321iF\200\246J\\\372\177\0\0\377\0\0\0\0\0\0\0"..., iov_len=4096}], 1, [{iov_base=0x7ffca877c000, iov_len=4096}], 1, 0) = 4096write(2, "\"SLOT0_OK\", 8, 0) = 8"..., 33) = 33ptrace(PTRACE_SYSCALL, 2867285, NULL, 0) = 0--- SIGCHLD {si_signo=SIGCHLD, si_code=CLD_TRAPPED, si_pid=2867285, si_uid=1000, si_status=SIGTRAP, si_utime=0, si_stime=0} ---wait4(-1, [{WIFSTOPPED(s) && WSTOPSIG(s) == SIGTRAP | 0x80}], __WALL, NULL) = 2867285wait4(-1, 0x7ffe0ba737ac, WNOHANG|__WALL, NULL) = 0ptrace(PTRACE_GET_SYSCALL_INFO, 2867285, 88, {op=PTRACE_SYSCALL_INFO_ENTRY, arch=AUDIT_ARCH_X86_64, instruction_pointer=0x7ffa5c2fa537, stack_pointer=0x7ffca877c488, entry={nr=__NR_pread64, args=[0x4, 0x7ffca877c4f7, 0x8, 0x8, 0x64, 0]}}) = 80write(2, "pread64(4, ", 11) = 11ptrace(PTRACE_SYSCALL, 2867285, NULL, 0) = 0--- SIGCHLD {si_signo=SIGCHLD, si_code=CLD_TRAPPED, si_pid=2867285, si_uid=1000, si_status=SIGTRAP, si_utime=0, si_stime=0} ---wait4(-1, [{WIFSTOPPED(s) && WSTOPSIG(s) == SIGTRAP | 0x80}], __WALL, NULL) = 2867285wait4(-1, 0x7ffe0ba737ac, WNOHANG|__WALL, NULL) = 0ptrace(PTRACE_GET_SYSCALL_INFO, 2867285, 88, {op=PTRACE_SYSCALL_INFO_EXIT, arch=AUDIT_ARCH_X86_64, instruction_pointer=0x7ffa5c2fa537, stack_pointer=0x7ffca877c488, exit={rval=8, is_error=0}}) = 33process_vm_readv(2867285, [{iov_base="\0\20\2\0\0\0\0\0\0\211X\16\221\321iF\200\246J\\\372\177\0\0\377\0\0\0\0\0\0\0"..., iov_len=4096}], 1, [{iov_base=0x7ffca877c000, iov_len=4096}], 1, 0) = 4096write(2, "\"SLOT1_OK\", 8, 8) = 8"..., 33) = 33ptrace(PTRACE_SYSCALL, 2867285, NULL, 0) = 0--- SIGCHLD {si_signo=SIGCHLD, si_code=CLD_TRAPPED, si_pid=2867285, si_uid=1000, si_status=SIGTRAP, si_utime=0, si_stime=0} ---wait4(-1, [{WIFSTOPPED(s) && WSTOPSIG(s) == SIGTRAP | 0x80}], __WALL, NULL) = 2867285wait4(-1, 0x7ffe0ba737ac, WNOHANG|__WALL, NULL) = 0ptrace(PTRACE_GET_SYSCALL_INFO, 2867285, 88, {op=PTRACE_SYSCALL_INFO_ENTRY, arch=AUDIT_ARCH_X86_64, instruction_pointer=0x7ffa5c31b26b, stack_pointer=0x7ffca877c488, entry={nr=__NR_lseek, args=[0x3, 0, 0x1, 0x8, 0x64, 0]}}) = 80ptrace(PTRACE_SYSCALL, 2867285, NULL, 0) = 0--- SIGCHLD {si_signo=SIGCHLD, si_code=CLD_TRAPPED, si_pid=2867285, si_uid=1000, si_status=SIGTRAP, si_utime=0, si_stime=0} ---wait4(-1, [{WIFSTOPPED(s) && WSTOPSIG(s) == SIGTRAP | 0x80}], __WALL, NULL) = 2867285wait4(-1, 0x7ffe0ba737ac, WNOHANG|__WALL, NULL) = 0ptrace(PTRACE_SYSCALL, 2867285, NULL, 0) = 0--- SIGCHLD {si_signo=SIGCHLD, si_code=CLD_TRAPPED, si_pid=2867285, si_uid=1000, si_status=SIGTRAP, si_utime=0, si_stime=0} ---wait4(-1, [{WIFSTOPPED(s) && WSTOPSIG(s) == SIGTRAP | 0x80}], __WALL, NULL) = 2867285wait4(-1, 0x7ffe0ba737ac, WNOHANG|__WALL, NULL) = 0ptrace(PTRACE_GET_SYSCALL_INFO, 2867285, 88, {op=PTRACE_SYSCALL_INFO_ENTRY, arch=AUDIT_ARCH_X86_64, instruction_pointer=0x7ffa5c316984, stack_pointer=0x7ffca877c488, entry={nr=__NR_close, args=[0x4, 0x7ffa5c4055c0, 0, 0, 0x64, 0]}}) = 80write(2, "close(4", 7) = 7ptrace(PTRACE_SYSCALL, 2867285, NULL, 0) = 0--- SIGCHLD {si_signo=SIGCHLD, si_code=CLD_TRAPPED, si_pid=2867285, si_uid=1000, si_status=SIGTRAP, si_utime=0, si_stime=0} ---wait4(-1, [{WIFSTOPPED(s) && WSTOPSIG(s) == SIGTRAP | 0x80}], __WALL, NULL) = 2867285wait4(-1, 0x7ffe0ba737ac, WNOHANG|__WALL, NULL) = 0ptrace(PTRACE_GET_SYSCALL_INFO, 2867285, 88, {op=PTRACE_SYSCALL_INFO_EXIT, arch=AUDIT_ARCH_X86_64, instruction_pointer=0x7ffa5c316984, stack_pointer=0x7ffca877c488, exit={rval=0, is_error=0}}) = 33write(2, ") "..., 37) = 37ptrace(PTRACE_SYSCALL, 2867285, NULL, 0) = 0--- SIGCHLD {si_signo=SIGCHLD, si_code=CLD_TRAPPED, si_pid=2867285, si_uid=1000, si_status=SIGTRAP, si_utime=0, si_stime=0} ---wait4(-1, [{WIFSTOPPED(s) && WSTOPSIG(s) == SIGTRAP | 0x80}], __WALL, NULL) = 2867285wait4(-1, 0x7ffe0ba737ac, WNOHANG|__WALL, NULL) = 0ptrace(PTRACE_GET_SYSCALL_INFO, 2867285, 88, {op=PTRACE_SYSCALL_INFO_ENTRY, arch=AUDIT_ARCH_X86_64, instruction_pointer=0x7ffa5c316984, stack_pointer=0x7ffca877c488, entry={nr=__NR_close, args=[0x3, 0x7ffa5c4055c0, 0, 0, 0x64, 0]}}) = 80write(2, "close(3", 7) = 7ptrace(PTRACE_SYSCALL, 2867285, NULL, 0) = 0wait4(-1, [{WIFSTOPPED(s) && WSTOPSIG(s) == SIGTRAP | 0x80}], __WALL, NULL) = 2867285--- SIGCHLD {si_signo=SIGCHLD, si_code=CLD_TRAPPED, si_pid=2867285, si_uid=1000, si_status=SIGTRAP, si_utime=0, si_stime=0} ---wait4(-1, 0x7ffe0ba737ac, WNOHANG|__WALL, NULL) = 0ptrace(PTRACE_GET_SYSCALL_INFO, 2867285, 88, {op=PTRACE_SYSCALL_INFO_EXIT, arch=AUDIT_ARCH_X86_64, instruction_pointer=0x7ffa5c316984, stack_pointer=0x7ffca877c488, exit={rval=0, is_error=0}}) = 33write(2, ") "..., 37) = 37ptrace(PTRACE_SYSCALL, 2867285, NULL, 0) = 0--- SIGCHLD {si_signo=SIGCHLD, si_code=CLD_TRAPPED, si_pid=2867285, si_uid=1000, si_status=SIGTRAP, si_utime=0, si_stime=0} ---wait4(-1, [{WIFSTOPPED(s) && WSTOPSIG(s) == SIGTRAP | 0x80}], __WALL, NULL) = 2867285wait4(-1, 0x7ffe0ba737ac, WNOHANG|__WALL, NULL) = 0ptrace(PTRACE_GET_SYSCALL_INFO, 2867285, 88, {op=PTRACE_SYSCALL_INFO_ENTRY, arch=AUDIT_ARCH_X86_64, instruction_pointer=0x7ffa5c31b405, stack_pointer=0x7ffca877c410, entry={nr=__NR_openat, args=[0xffffff9c, 0x63d5a3ac601e, 0x80601, 0, 0x64, 0]}}) = 80process_vm_readv(2867285, [{iov_base="\1\0\2\0\0\0\0\0/tmp/ksa_m04_l02.lock\0/t"..., iov_len=4096}], 1, [{iov_base=0x63d5a3ac6000, iov_len=4096}], 1, 0) = 4096write(2, "openat(AT_FDCWD, \"/tmp/ksa_m04_l"..., 82) = 82ptrace(PTRACE_SYSCALL, 2867285, NULL, 0) = 0wait4(-1, [{WIFSTOPPED(s) && WSTOPSIG(s) == SIGTRAP | 0x80}], __WALL, NULL) = 2867285--- SIGCHLD {si_signo=SIGCHLD, si_code=CLD_TRAPPED, si_pid=2867285, si_uid=1000, si_status=SIGTRAP, si_utime=0, si_stime=0} ---wait4(-1, 0x7ffe0ba737ac, WNOHANG|__WALL, NULL) = 0ptrace(PTRACE_GET_SYSCALL_INFO, 2867285, 88, {op=PTRACE_SYSCALL_INFO_EXIT, arch=AUDIT_ARCH_X86_64, instruction_pointer=0x7ffa5c31b405, stack_pointer=0x7ffca877c410, exit={rval=3, is_error=0}}) = 33write(2, ") = 3\n", 6) = 6ptrace(PTRACE_SYSCALL, 2867285, NULL, 0) = 0--- SIGCHLD {si_signo=SIGCHLD, si_code=CLD_TRAPPED, si_pid=2867285, si_uid=1000, si_status=SIGTRAP, si_utime=0, si_stime=0} ---wait4(-1, [{WIFSTOPPED(s) && WSTOPSIG(s) == SIGTRAP | 0x80}], __WALL, NULL) = 2867285wait4(-1, 0x7ffe0ba737ac, WNOHANG|__WALL, NULL) = 0ptrace(PTRACE_GET_SYSCALL_INFO, 2867285, 88, {op=PTRACE_SYSCALL_INFO_ENTRY, arch=AUDIT_ARCH_X86_64, instruction_pointer=0x7ffa5c31b405, stack_pointer=0x7ffca877c410, entry={nr=__NR_openat, args=[0xffffff9c, 0x63d5a3ac601e, 0x80401, 0, 0x64, 0]}}) = 80process_vm_readv(2867285, [{iov_base="\1\0\2\0\0\0\0\0/tmp/ksa_m04_l02.lock\0/t"..., iov_len=4096}], 1, [{iov_base=0x63d5a3ac6000, iov_len=4096}], 1, 0) = 4096write(2, "openat(AT_FDCWD, \"/tmp/ksa_m04_l"..., 74) = 74ptrace(PTRACE_SYSCALL, 2867285, NULL, 0) = 0--- SIGCHLD {si_signo=SIGCHLD, si_code=CLD_TRAPPED, si_pid=2867285, si_uid=1000, si_status=SIGTRAP, si_utime=0, si_stime=0} ---wait4(-1, [{WIFSTOPPED(s) && WSTOPSIG(s) == SIGTRAP | 0x80}], __WALL, NULL) = 2867285wait4(-1, 0x7ffe0ba737ac, WNOHANG|__WALL, NULL) = 0ptrace(PTRACE_GET_SYSCALL_INFO, 2867285, 88, {op=PTRACE_SYSCALL_INFO_EXIT, arch=AUDIT_ARCH_X86_64, instruction_pointer=0x7ffa5c31b405, stack_pointer=0x7ffca877c410, exit={rval=4, is_error=0}}) = 33write(2, ") = 4\n", 6) = 6ptrace(PTRACE_SYSCALL, 2867285, NULL, 0) = 0--- SIGCHLD {si_signo=SIGCHLD, si_code=CLD_TRAPPED, si_pid=2867285, si_uid=1000, si_status=SIGTRAP, si_utime=0, si_stime=0} ---wait4(-1, [{WIFSTOPPED(s) && WSTOPSIG(s) == SIGTRAP | 0x80}], __WALL, NULL) = 2867285wait4(-1, 0x7ffe0ba737ac, WNOHANG|__WALL, NULL) = 0ptrace(PTRACE_GET_SYSCALL_INFO, 2867285, 88, {op=PTRACE_SYSCALL_INFO_ENTRY, arch=AUDIT_ARCH_X86_64, instruction_pointer=0x7ffa5c31c804, stack_pointer=0x7ffca877c488, entry={nr=__NR_write, args=[0x3, 0x63d5a3ac60fb, 0x5, 0, 0x64, 0]}}) = 80ptrace(PTRACE_SYSCALL, 2867285, NULL, 0) = 0wait4(-1, [{WIFSTOPPED(s) && WSTOPSIG(s) == SIGTRAP | 0x80}], __WALL, NULL) = 2867285--- SIGCHLD {si_signo=SIGCHLD, si_code=CLD_TRAPPED, si_pid=2867285, si_uid=1000, si_status=SIGTRAP, si_utime=0, si_stime=0} ---wait4(-1, 0x7ffe0ba737ac, WNOHANG|__WALL, NULL) = 0ptrace(PTRACE_SYSCALL, 2867285, NULL, 0) = 0--- SIGCHLD {si_signo=SIGCHLD, si_code=CLD_TRAPPED, si_pid=2867285, si_uid=1000, si_status=SIGTRAP, si_utime=0, si_stime=0} ---wait4(-1, [{WIFSTOPPED(s) && WSTOPSIG(s) == SIGTRAP | 0x80}], __WALL, NULL) = 2867285wait4(-1, 0x7ffe0ba737ac, WNOHANG|__WALL, NULL) = 0ptrace(PTRACE_GET_SYSCALL_INFO, 2867285, 88, {op=PTRACE_SYSCALL_INFO_ENTRY, arch=AUDIT_ARCH_X86_64, instruction_pointer=0x7ffa5c31c804, stack_pointer=0x7ffca877c488, entry={nr=__NR_write, args=[0x4, 0x63d5a3ac6101, 0x4, 0, 0x64, 0]}}) = 80ptrace(PTRACE_SYSCALL, 2867285, NULL, 0) = 0--- SIGCHLD {si_signo=SIGCHLD, si_code=CLD_TRAPPED, si_pid=2867285, si_uid=1000, si_status=SIGTRAP, si_utime=0, si_stime=0} ---wait4(-1, [{WIFSTOPPED(s) && WSTOPSIG(s) == SIGTRAP | 0x80}], __WALL, NULL) = 2867285wait4(-1, 0x7ffe0ba737ac, WNOHANG|__WALL, NULL) = 0ptrace(PTRACE_SYSCALL, 2867285, NULL, 0) = 0--- SIGCHLD {si_signo=SIGCHLD, si_code=CLD_TRAPPED, si_pid=2867285, si_uid=1000, si_status=SIGTRAP, si_utime=0, si_stime=0} ---wait4(-1, [{WIFSTOPPED(s) && WSTOPSIG(s) == SIGTRAP | 0x80}], __WALL, NULL) = 2867285wait4(-1, 0x7ffe0ba737ac, WNOHANG|__WALL, NULL) = 0ptrace(PTRACE_GET_SYSCALL_INFO, 2867285, 88, {op=PTRACE_SYSCALL_INFO_ENTRY, arch=AUDIT_ARCH_X86_64, instruction_pointer=0x7ffa5c316984, stack_pointer=0x7ffca877c488, entry={nr=__NR_close, args=[0x3, 0x63d5a3ac6101, 0x4, 0, 0x64, 0]}}) = 80write(2, "close(3", 7) = 7ptrace(PTRACE_SYSCALL, 2867285, NULL, 0) = 0wait4(-1, [{WIFSTOPPED(s) && WSTOPSIG(s) == SIGTRAP | 0x80}], __WALL, NULL) = 2867285--- SIGCHLD {si_signo=SIGCHLD, si_code=CLD_TRAPPED, si_pid=2867285, si_uid=1000, si_status=SIGTRAP, si_utime=0, si_stime=0} ---wait4(-1, 0x7ffe0ba737ac, WNOHANG|__WALL, NULL) = 0ptrace(PTRACE_GET_SYSCALL_INFO, 2867285, 88, {op=PTRACE_SYSCALL_INFO_EXIT, arch=AUDIT_ARCH_X86_64, instruction_pointer=0x7ffa5c316984, stack_pointer=0x7ffca877c488, exit={rval=0, is_error=0}}) = 33write(2, ") "..., 37) = 37ptrace(PTRACE_SYSCALL, 2867285, NULL, 0) = 0--- SIGCHLD {si_signo=SIGCHLD, si_code=CLD_TRAPPED, si_pid=2867285, si_uid=1000, si_status=SIGTRAP, si_utime=0, si_stime=0} ---wait4(-1, [{WIFSTOPPED(s) && WSTOPSIG(s) == SIGTRAP | 0x80}], __WALL, NULL) = 2867285wait4(-1, 0x7ffe0ba737ac, WNOHANG|__WALL, NULL) = 0ptrace(PTRACE_GET_SYSCALL_INFO, 2867285, 88, {op=PTRACE_SYSCALL_INFO_ENTRY, arch=AUDIT_ARCH_X86_64, instruction_pointer=0x7ffa5c316984, stack_pointer=0x7ffca877c488, entry={nr=__NR_close, args=[0x4, 0x63d5a3ac6101, 0x4, 0, 0x64, 0]}}) = 80write(2, "close(4", 7) = 7ptrace(PTRACE_SYSCALL, 2867285, NULL, 0) = 0--- SIGCHLD {si_signo=SIGCHLD, si_code=CLD_TRAPPED, si_pid=2867285, si_uid=1000, si_status=SIGTRAP, si_utime=0, si_stime=0} ---wait4(-1, [{WIFSTOPPED(s) && WSTOPSIG(s) == SIGTRAP | 0x80}], __WALL, NULL) = 2867285wait4(-1, 0x7ffe0ba737ac, WNOHANG|__WALL, NULL) = 0ptrace(PTRACE_GET_SYSCALL_INFO, 2867285, 88, {op=PTRACE_SYSCALL_INFO_EXIT, arch=AUDIT_ARCH_X86_64, instruction_pointer=0x7ffa5c316984, stack_pointer=0x7ffca877c488, exit={rval=0, is_error=0}}) = 33write(2, ") "..., 37) = 37ptrace(PTRACE_SYSCALL, 2867285, NULL, 0) = 0--- SIGCHLD {si_signo=SIGCHLD, si_code=CLD_TRAPPED, si_pid=2867285, si_uid=1000, si_status=SIGTRAP, si_utime=0, si_stime=0} ---wait4(-1, [{WIFSTOPPED(s) && WSTOPSIG(s) == SIGTRAP | 0x80}], __WALL, NULL) = 2867285wait4(-1, 0x7ffe0ba737ac, WNOHANG|__WALL, NULL) = 0ptrace(PTRACE_GET_SYSCALL_INFO, 2867285, 88, {op=PTRACE_SYSCALL_INFO_ENTRY, arch=AUDIT_ARCH_X86_64, instruction_pointer=0x7ffa5c31b405, stack_pointer=0x7ffca877c410, entry={nr=__NR_openat, args=[0xffffff9c, 0x63d5a3ac601e, 0x80000, 0, 0x64, 0]}}) = 80process_vm_readv(2867285, [{iov_base="\1\0\2\0\0\0\0\0/tmp/ksa_m04_l02.lock\0/t"..., iov_len=4096}], 1, [{iov_base=0x63d5a3ac6000, iov_len=4096}], 1, 0) = 4096write(2, "openat(AT_FDCWD, \"/tmp/ksa_m04_l"..., 65) = 65ptrace(PTRACE_SYSCALL, 2867285, NULL, 0) = 0--- SIGCHLD {si_signo=SIGCHLD, si_code=CLD_TRAPPED, si_pid=2867285, si_uid=1000, si_status=SIGTRAP, si_utime=0, si_stime=0} ---wait4(-1, [{WIFSTOPPED(s) && WSTOPSIG(s) == SIGTRAP | 0x80}], __WALL, NULL) = 2867285wait4(-1, 0x7ffe0ba737ac, WNOHANG|__WALL, NULL) = 0ptrace(PTRACE_GET_SYSCALL_INFO, 2867285, 88, {op=PTRACE_SYSCALL_INFO_EXIT, arch=AUDIT_ARCH_X86_64, instruction_pointer=0x7ffa5c31b405, stack_pointer=0x7ffca877c410, exit={rval=3, is_error=0}}) = 33write(2, ") = 3\n", 6) = 6ptrace(PTRACE_SYSCALL, 2867285, NULL, 0) = 0--- SIGCHLD {si_signo=SIGCHLD, si_code=CLD_TRAPPED, si_pid=2867285, si_uid=1000, si_status=SIGTRAP, si_utime=0, si_stime=0} ---wait4(-1, [{WIFSTOPPED(s) && WSTOPSIG(s) == SIGTRAP | 0x80}], __WALL, NULL) = 2867285wait4(-1, 0x7ffe0ba737ac, WNOHANG|__WALL, NULL) = 0ptrace(PTRACE_GET_SYSCALL_INFO, 2867285, 88, {op=PTRACE_SYSCALL_INFO_ENTRY, arch=AUDIT_ARCH_X86_64, instruction_pointer=0x7ffa5c31bcf1, stack_pointer=0x7ffca877c488, entry={nr=__NR_read, args=[0x3, 0x7ffca877c500, 0xf, 0, 0x64, 0]}}) = 80ptrace(PTRACE_SYSCALL, 2867285, NULL, 0) = 0--- SIGCHLD {si_signo=SIGCHLD, si_code=CLD_TRAPPED, si_pid=2867285, si_uid=1000, si_status=SIGTRAP, si_utime=0, si_stime=0} ---wait4(-1, [{WIFSTOPPED(s) && WSTOPSIG(s) == SIGTRAP | 0x80}], __WALL, NULL) = 2867285wait4(-1, 0x7ffe0ba737ac, WNOHANG|__WALL, NULL) = 0ptrace(PTRACE_SYSCALL, 2867285, NULL, 0) = 0--- SIGCHLD {si_signo=SIGCHLD, si_code=CLD_TRAPPED, si_pid=2867285, si_uid=1000, si_status=SIGTRAP, si_utime=0, si_stime=0} ---wait4(-1, [{WIFSTOPPED(s) && WSTOPSIG(s) == SIGTRAP | 0x80}], __WALL, NULL) = 2867285wait4(-1, 0x7ffe0ba737ac, WNOHANG|__WALL, NULL) = 0ptrace(PTRACE_GET_SYSCALL_INFO, 2867285, 88, {op=PTRACE_SYSCALL_INFO_ENTRY, arch=AUDIT_ARCH_X86_64, instruction_pointer=0x7ffa5c316984, stack_pointer=0x7ffca877c488, entry={nr=__NR_close, args=[0x3, 0x7ffca877c500, 0xf, 0, 0x64, 0]}}) = 80write(2, "close(3", 7) = 7ptrace(PTRACE_SYSCALL, 2867285, NULL, 0) = 0--- SIGCHLD {si_signo=SIGCHLD, si_code=CLD_TRAPPED, si_pid=2867285, si_uid=1000, si_status=SIGTRAP, si_utime=0, si_stime=0} ---wait4(-1, [{WIFSTOPPED(s) && WSTOPSIG(s) == SIGTRAP | 0x80}], __WALL, NULL) = 2867285wait4(-1, 0x7ffe0ba737ac, WNOHANG|__WALL, NULL) = 0ptrace(PTRACE_GET_SYSCALL_INFO, 2867285, 88, {op=PTRACE_SYSCALL_INFO_EXIT, arch=AUDIT_ARCH_X86_64, instruction_pointer=0x7ffa5c316984, stack_pointer=0x7ffca877c488, exit={rval=0, is_error=0}}) = 33write(2, ") "..., 37) = 37ptrace(PTRACE_SYSCALL, 2867285, NULL, 0) = 0--- SIGCHLD {si_signo=SIGCHLD, si_code=CLD_TRAPPED, si_pid=2867285, si_uid=1000, si_status=SIGTRAP, si_utime=0, si_stime=0} ---wait4(-1, [{WIFSTOPPED(s) && WSTOPSIG(s) == SIGTRAP | 0x80}], __WALL, NULL) = 2867285wait4(-1, 0x7ffe0ba737ac, WNOHANG|__WALL, NULL) = 0ptrace(PTRACE_GET_SYSCALL_INFO, 2867285, 88, {op=PTRACE_SYSCALL_INFO_ENTRY, arch=AUDIT_ARCH_X86_64, instruction_pointer=0x7ffa5c31c69b, stack_pointer=0x7ffca877c488, entry={nr=__NR_unlink, args=[0x63d5a3ac601e, 0x7ffca877c500, 0xf, 0, 0x64, 0]}}) = 80process_vm_readv(2867285, [{iov_base="\1\0\2\0\0\0\0\0/tmp/ksa_m04_l02.lock\0/t"..., iov_len=4096}], 1, [{iov_base=0x63d5a3ac6000, iov_len=4096}], 1, 0) = 4096write(2, "unlink(\"/tmp/ksa_m04_l02_slots.b"..., 35) = 35ptrace(PTRACE_SYSCALL, 2867285, NULL, 0) = 0wait4(-1, [{WIFSTOPPED(s) && WSTOPSIG(s) == SIGTRAP | 0x80}], __WALL, NULL) = 2867285--- SIGCHLD {si_signo=SIGCHLD, si_code=CLD_TRAPPED, si_pid=2867285, si_uid=1000, si_status=SIGTRAP, si_utime=0, si_stime=0} ---wait4(-1, 0x7ffe0ba737ac, WNOHANG|__WALL, NULL) = 0ptrace(PTRACE_GET_SYSCALL_INFO, 2867285, 88, {op=PTRACE_SYSCALL_INFO_EXIT, arch=AUDIT_ARCH_X86_64, instruction_pointer=0x7ffa5c31c69b, stack_pointer=0x7ffca877c488, exit={rval=0, is_error=0}}) = 33write(2, ") = 0\n", 9) = 9ptrace(PTRACE_SYSCALL, 2867285, NULL, 0) = 0--- SIGCHLD {si_signo=SIGCHLD, si_code=CLD_TRAPPED, si_pid=2867285, si_uid=1000, si_status=SIGTRAP, si_utime=0, si_stime=0} ---wait4(-1, [{WIFSTOPPED(s) && WSTOPSIG(s) == SIGTRAP | 0x80}], __WALL, NULL) = 2867285wait4(-1, 0x7ffe0ba737ac, WNOHANG|__WALL, NULL) = 0ptrace(PTRACE_GET_SYSCALL_INFO, 2867285, 88, {op=PTRACE_SYSCALL_INFO_ENTRY, arch=AUDIT_ARCH_X86_64, instruction_pointer=0x7ffa5c31b405, stack_pointer=0x7ffca877c410, entry={nr=__NR_openat, args=[0xffffff9c, 0x63d5a3ac6106, 0x90000, 0, 0x64, 0]}}) = 80process_vm_readv(2867285, [{iov_base="\1\0\2\0\0\0\0\0/tmp/ksa_m04_l02.lock\0/t"..., iov_len=4096}], 1, [{iov_base=0x63d5a3ac6000, iov_len=4096}], 1, 0) = 4096write(2, "openat(AT_FDCWD, \"/tmp\", O_RDONL"..., 55) = 55ptrace(PTRACE_SYSCALL, 2867285, NULL, 0) = 0--- SIGCHLD {si_signo=SIGCHLD, si_code=CLD_TRAPPED, si_pid=2867285, si_uid=1000, si_status=SIGTRAP, si_utime=0, si_stime=0} ---wait4(-1, [{WIFSTOPPED(s) && WSTOPSIG(s) == SIGTRAP | 0x80}], __WALL, NULL) = 2867285wait4(-1, 0x7ffe0ba737ac, WNOHANG|__WALL, NULL) = 0ptrace(PTRACE_GET_SYSCALL_INFO, 2867285, 88, {op=PTRACE_SYSCALL_INFO_EXIT, arch=AUDIT_ARCH_X86_64, instruction_pointer=0x7ffa5c31b405, stack_pointer=0x7ffca877c410, exit={rval=3, is_error=0}}) = 33write(2, ") = 3\n", 6) = 6ptrace(PTRACE_SYSCALL, 2867285, NULL, 0) = 0--- SIGCHLD {si_signo=SIGCHLD, si_code=CLD_TRAPPED, si_pid=2867285, si_uid=1000, si_status=SIGTRAP, si_utime=0, si_stime=0} ---wait4(-1, [{WIFSTOPPED(s) && WSTOPSIG(s) == SIGTRAP | 0x80}], __WALL, NULL) = 2867285wait4(-1, 0x7ffe0ba737ac, WNOHANG|__WALL, NULL) = 0ptrace(PTRACE_GET_SYSCALL_INFO, 2867285, 88, {op=PTRACE_SYSCALL_INFO_ENTRY, arch=AUDIT_ARCH_X86_64, instruction_pointer=0x7ffa5c31c6cb, stack_pointer=0x7ffca877c488, entry={nr=__NR_unlinkat, args=[0x3, 0x63d5a3ac610b, 0, 0, 0x64, 0]}}) = 80process_vm_readv(2867285, [{iov_base="\1\0\2\0\0\0\0\0/tmp/ksa_m04_l02.lock\0/t"..., iov_len=4096}], 1, [{iov_base=0x63d5a3ac6000, iov_len=4096}], 1, 0) = 4096write(2, "unlinkat(3, \"ksa_m04_cfg.tmp\", 0", 32) = 32ptrace(PTRACE_SYSCALL, 2867285, NULL, 0) = 0wait4(-1, [{WIFSTOPPED(s) && WSTOPSIG(s) == SIGTRAP | 0x80}], __WALL, NULL) = 2867285--- SIGCHLD {si_signo=SIGCHLD, si_code=CLD_TRAPPED, si_pid=2867285, si_uid=1000, si_status=SIGTRAP, si_utime=0, si_stime=0} ---wait4(-1, 0x7ffe0ba737ac, WNOHANG|__WALL, NULL) = 0ptrace(PTRACE_GET_SYSCALL_INFO, 2867285, 88, {op=PTRACE_SYSCALL_INFO_EXIT, arch=AUDIT_ARCH_X86_64, instruction_pointer=0x7ffa5c31c6cb, stack_pointer=0x7ffca877c488, exit={rval=-ENOENT, is_error=1}}) = 33write(2, ") = -1 ENOENT (No such fil"..., 48) = 48ptrace(PTRACE_SYSCALL, 2867285, NULL, 0) = 0--- SIGCHLD {si_signo=SIGCHLD, si_code=CLD_TRAPPED, si_pid=2867285, si_uid=1000, si_status=SIGTRAP, si_utime=0, si_stime=0} ---wait4(-1, [{WIFSTOPPED(s) && WSTOPSIG(s) == SIGTRAP | 0x80}], __WALL, NULL) = 2867285wait4(-1, 0x7ffe0ba737ac, WNOHANG|__WALL, NULL) = 0ptrace(PTRACE_GET_SYSCALL_INFO, 2867285, 88, {op=PTRACE_SYSCALL_INFO_ENTRY, arch=AUDIT_ARCH_X86_64, instruction_pointer=0x7ffa5c31c6cb, stack_pointer=0x7ffca877c488, entry={nr=__NR_unlinkat, args=[0x3, 0x63d5a3ac611b, 0, 0, 0x64, 0]}}) = 80process_vm_readv(2867285, [{iov_base="\1\0\2\0\0\0\0\0/tmp/ksa_m04_l02.lock\0/t"..., iov_len=4096}], 1, [{iov_base=0x63d5a3ac6000, iov_len=4096}], 1, 0) = 4096write(2, "unlinkat(3, \"ksa_m04_cfg.v1\", 0", 31) = 31ptrace(PTRACE_SYSCALL, 2867285, NULL, 0) = 0--- SIGCHLD {si_signo=SIGCHLD, si_code=CLD_TRAPPED, si_pid=2867285, si_uid=1000, si_status=SIGTRAP, si_utime=0, si_stime=0} ---wait4(-1, [{WIFSTOPPED(s) && WSTOPSIG(s) == SIGTRAP | 0x80}], __WALL, NULL) = 2867285wait4(-1, 0x7ffe0ba737ac, WNOHANG|__WALL, NULL) = 0ptrace(PTRACE_GET_SYSCALL_INFO, 2867285, 88, {op=PTRACE_SYSCALL_INFO_EXIT, arch=AUDIT_ARCH_X86_64, instruction_pointer=0x7ffa5c31c6cb, stack_pointer=0x7ffca877c488, exit={rval=-ENOENT, is_error=1}}) = 33write(2, ") = -1 ENOENT (No such fi"..., 49) = 49ptrace(PTRACE_SYSCALL, 2867285, NULL, 0) = 0--- SIGCHLD {si_signo=SIGCHLD, si_code=CLD_TRAPPED, si_pid=2867285, si_uid=1000, si_status=SIGTRAP, si_utime=0, si_stime=0} ---wait4(-1, [{WIFSTOPPED(s) && WSTOPSIG(s) == SIGTRAP | 0x80}], __WALL, NULL) = 2867285wait4(-1, 0x7ffe0ba737ac, WNOHANG|__WALL, NULL) = 0ptrace(PTRACE_GET_SYSCALL_INFO, 2867285, 88, {op=PTRACE_SYSCALL_INFO_ENTRY, arch=AUDIT_ARCH_X86_64, instruction_pointer=0x7ffa5c31b572, stack_pointer=0x7ffca877c3d0, entry={nr=__NR_openat, args=[0x3, 0x63d5a3ac610b, 0xa00c1, 0x180, 0x64, 0]}}) = 80process_vm_readv(2867285, [{iov_base="\1\0\2\0\0\0\0\0/tmp/ksa_m04_l02.lock\0/t"..., iov_len=4096}], 1, [{iov_base=0x63d5a3ac6000, iov_len=4096}], 1, 0) = 4096write(2, "openat(3, \"ksa_m04_cfg.tmp\", O_W"..., 79) = 79ptrace(PTRACE_SYSCALL, 2867285, NULL, 0) = 0wait4(-1, [{WIFSTOPPED(s) && WSTOPSIG(s) == SIGTRAP | 0x80}], __WALL, NULL) = 2867285--- SIGCHLD {si_signo=SIGCHLD, si_code=CLD_TRAPPED, si_pid=2867285, si_uid=1000, si_status=SIGTRAP, si_utime=0, si_stime=0} ---wait4(-1, 0x7ffe0ba737ac, WNOHANG|__WALL, NULL) = 0ptrace(PTRACE_GET_SYSCALL_INFO, 2867285, 88, {op=PTRACE_SYSCALL_INFO_EXIT, arch=AUDIT_ARCH_X86_64, instruction_pointer=0x7ffa5c31b572, stack_pointer=0x7ffca877c3d0, exit={rval=4, is_error=0}}) = 33write(2, ") = 4\n", 6) = 6ptrace(PTRACE_SYSCALL, 2867285, NULL, 0) = 0--- SIGCHLD {si_signo=SIGCHLD, si_code=CLD_TRAPPED, si_pid=2867285, si_uid=1000, si_status=SIGTRAP, si_utime=0, si_stime=0} ---wait4(-1, [{WIFSTOPPED(s) && WSTOPSIG(s) == SIGTRAP | 0x80}], __WALL, NULL) = 2867285wait4(-1, 0x7ffe0ba737ac, WNOHANG|__WALL, NULL) = 0ptrace(PTRACE_GET_SYSCALL_INFO, 2867285, 88, {op=PTRACE_SYSCALL_INFO_ENTRY, arch=AUDIT_ARCH_X86_64, instruction_pointer=0x7ffa5c31c804, stack_pointer=0x7ffca877c448, entry={nr=__NR_write, args=[0x4, 0x63d5a3ac612a, 0x9, 0x180, 0x64, 0]}}) = 80ptrace(PTRACE_SYSCALL, 2867285, NULL, 0) = 0wait4(-1, [{WIFSTOPPED(s) && WSTOPSIG(s) == SIGTRAP | 0x80}], __WALL, NULL) = 2867285--- SIGCHLD {si_signo=SIGCHLD, si_code=CLD_TRAPPED, si_pid=2867285, si_uid=1000, si_status=SIGTRAP, si_utime=0, si_stime=0} ---wait4(-1, 0x7ffe0ba737ac, WNOHANG|__WALL, NULL) = 0ptrace(PTRACE_SYSCALL, 2867285, NULL, 0) = 0--- SIGCHLD {si_signo=SIGCHLD, si_code=CLD_TRAPPED, si_pid=2867285, si_uid=1000, si_status=SIGTRAP, si_utime=0, si_stime=0} ---wait4(-1, [{WIFSTOPPED(s) && WSTOPSIG(s) == SIGTRAP | 0x80}], __WALL, NULL) = 2867285wait4(-1, 0x7ffe0ba737ac, WNOHANG|__WALL, NULL) = 0ptrace(PTRACE_GET_SYSCALL_INFO, 2867285, 88, {op=PTRACE_SYSCALL_INFO_ENTRY, arch=AUDIT_ARCH_X86_64, instruction_pointer=0x7ffa5c31e9e4, stack_pointer=0x7ffca877c448, entry={nr=__NR_fdatasync, args=[0x4, 0x63d5a3ac612a, 0x9, 0x180, 0x64, 0]}}) = 80ptrace(PTRACE_SYSCALL, 2867285, NULL, 0) = 0wait4(-1, [{WIFSTOPPED(s) && WSTOPSIG(s) == SIGTRAP | 0x80}], __WALL, NULL) = 2867285--- SIGCHLD {si_signo=SIGCHLD, si_code=CLD_TRAPPED, si_pid=2867285, si_uid=1000, si_status=SIGTRAP, si_utime=0, si_stime=0} ---wait4(-1, 0x7ffe0ba737ac, WNOHANG|__WALL, NULL) = 0ptrace(PTRACE_SYSCALL, 2867285, NULL, 0) = 0wait4(-1, [{WIFSTOPPED(s) && WSTOPSIG(s) == SIGTRAP | 0x80}], __WALL, NULL) = 2867285--- SIGCHLD {si_signo=SIGCHLD, si_code=CLD_TRAPPED, si_pid=2867285, si_uid=1000, si_status=SIGTRAP, si_utime=0, si_stime=0} ---wait4(-1, 0x7ffe0ba737ac, WNOHANG|__WALL, NULL) = 0ptrace(PTRACE_GET_SYSCALL_INFO, 2867285, 88, {op=PTRACE_SYSCALL_INFO_ENTRY, arch=AUDIT_ARCH_X86_64, instruction_pointer=0x7ffa5c316984, stack_pointer=0x7ffca877c448, entry={nr=__NR_close, args=[0x4, 0x63d5a3ac612a, 0x9, 0x180, 0x64, 0]}}) = 80write(2, "close(4", 7) = 7ptrace(PTRACE_SYSCALL, 2867285, NULL, 0) = 0wait4(-1, [{WIFSTOPPED(s) && WSTOPSIG(s) == SIGTRAP | 0x80}], __WALL, NULL) = 2867285--- SIGCHLD {si_signo=SIGCHLD, si_code=CLD_TRAPPED, si_pid=2867285, si_uid=1000, si_status=SIGTRAP, si_utime=0, si_stime=0} ---wait4(-1, 0x7ffe0ba737ac, WNOHANG|__WALL, NULL) = 0ptrace(PTRACE_GET_SYSCALL_INFO, 2867285, 88, {op=PTRACE_SYSCALL_INFO_EXIT, arch=AUDIT_ARCH_X86_64, instruction_pointer=0x7ffa5c316984, stack_pointer=0x7ffca877c448, exit={rval=0, is_error=0}}) = 33write(2, ") "..., 37) = 37ptrace(PTRACE_SYSCALL, 2867285, NULL, 0) = 0wait4(-1, [{WIFSTOPPED(s) && WSTOPSIG(s) == SIGTRAP | 0x80}], __WALL, NULL) = 2867285--- SIGCHLD {si_signo=SIGCHLD, si_code=CLD_TRAPPED, si_pid=2867285, si_uid=1000, si_status=SIGTRAP, si_utime=0, si_stime=0} ---wait4(-1, 0x7ffe0ba737ac, WNOHANG|__WALL, NULL) = 0ptrace(PTRACE_GET_SYSCALL_INFO, 2867285, 88, {op=PTRACE_SYSCALL_INFO_ENTRY, arch=AUDIT_ARCH_X86_64, instruction_pointer=0x7ffa5c26620e, stack_pointer=0x7ffca877c448, entry={nr=__NR_renameat, args=[0x3, 0x63d5a3ac610b, 0x3, 0x63d5a3ac611b, 0x64, 0]}}) = 80ptrace(PTRACE_SYSCALL, 2867285, NULL, 0) = 0wait4(-1, [{WIFSTOPPED(s) && WSTOPSIG(s) == SIGTRAP | 0x80}], __WALL, NULL) = 2867285--- SIGCHLD {si_signo=SIGCHLD, si_code=CLD_TRAPPED, si_pid=2867285, si_uid=1000, si_status=SIGTRAP, si_utime=0, si_stime=0} ---wait4(-1, 0x7ffe0ba737ac, WNOHANG|__WALL, NULL) = 0ptrace(PTRACE_SYSCALL, 2867285, NULL, 0) = 0wait4(-1, [{WIFSTOPPED(s) && WSTOPSIG(s) == SIGTRAP | 0x80}], __WALL, NULL) = 2867285--- SIGCHLD {si_signo=SIGCHLD, si_code=CLD_TRAPPED, si_pid=2867285, si_uid=1000, si_status=SIGTRAP, si_utime=0, si_stime=0} ---wait4(-1, 0x7ffe0ba737ac, WNOHANG|__WALL, NULL) = 0ptrace(PTRACE_GET_SYSCALL_INFO, 2867285, 88, {op=PTRACE_SYSCALL_INFO_ENTRY, arch=AUDIT_ARCH_X86_64, instruction_pointer=0x7ffa5c31f074, stack_pointer=0x7ffca877c448, entry={nr=__NR_fsync, args=[0x3, 0x63d5a3ac610b, 0x3, 0x63d5a3ac611b, 0x64, 0]}}) = 80ptrace(PTRACE_SYSCALL, 2867285, NULL, 0) = 0wait4(-1, [{WIFSTOPPED(s) && WSTOPSIG(s) == SIGTRAP | 0x80}], __WALL, NULL) = 2867285--- SIGCHLD {si_signo=SIGCHLD, si_code=CLD_TRAPPED, si_pid=2867285, si_uid=1000, si_status=SIGTRAP, si_utime=0, si_stime=0} ---wait4(-1, 0x7ffe0ba737ac, WNOHANG|__WALL, NULL) = 0ptrace(PTRACE_SYSCALL, 2867285, NULL, 0) = 0--- SIGCHLD {si_signo=SIGCHLD, si_code=CLD_TRAPPED, si_pid=2867285, si_uid=1000, si_status=SIGTRAP, si_utime=0, si_stime=0} ---wait4(-1, [{WIFSTOPPED(s) && WSTOPSIG(s) == SIGTRAP | 0x80}], __WALL, NULL) = 2867285wait4(-1, 0x7ffe0ba737ac, WNOHANG|__WALL, NULL) = 0ptrace(PTRACE_GET_SYSCALL_INFO, 2867285, 88, {op=PTRACE_SYSCALL_INFO_ENTRY, arch=AUDIT_ARCH_X86_64, instruction_pointer=0x7ffa5c31c6cb, stack_pointer=0x7ffca877c488, entry={nr=__NR_unlinkat, args=[0x3, 0x63d5a3ac611b, 0, 0x63d5a3ac611b, 0x64, 0]}}) = 80process_vm_readv(2867285, [{iov_base="\1\0\2\0\0\0\0\0/tmp/ksa_m04_l02.lock\0/t"..., iov_len=4096}], 1, [{iov_base=0x63d5a3ac6000, iov_len=4096}], 1, 0) = 4096write(2, "unlinkat(3, \"ksa_m04_cfg.v1\", 0", 31) = 31ptrace(PTRACE_SYSCALL, 2867285, NULL, 0) = 0wait4(-1, [{WIFSTOPPED(s) && WSTOPSIG(s) == SIGTRAP | 0x80}], __WALL, NULL) = 2867285--- SIGCHLD {si_signo=SIGCHLD, si_code=CLD_TRAPPED, si_pid=2867285, si_uid=1000, si_status=SIGTRAP, si_utime=0, si_stime=0} ---wait4(-1, 0x7ffe0ba737ac, WNOHANG|__WALL, NULL) = 0ptrace(PTRACE_GET_SYSCALL_INFO, 2867285, 88, {op=PTRACE_SYSCALL_INFO_EXIT, arch=AUDIT_ARCH_X86_64, instruction_pointer=0x7ffa5c31c6cb, stack_pointer=0x7ffca877c488, exit={rval=0, is_error=0}}) = 33write(2, ") = 0\n", 13) = 13ptrace(PTRACE_SYSCALL, 2867285, NULL, 0) = 0--- SIGCHLD {si_signo=SIGCHLD, si_code=CLD_TRAPPED, si_pid=2867285, si_uid=1000, si_status=SIGTRAP, si_utime=0, si_stime=0} ---wait4(-1, [{WIFSTOPPED(s) && WSTOPSIG(s) == SIGTRAP | 0x80}], __WALL, NULL) = 2867285wait4(-1, 0x7ffe0ba737ac, WNOHANG|__WALL, NULL) = 0ptrace(PTRACE_GET_SYSCALL_INFO, 2867285, 88, {op=PTRACE_SYSCALL_INFO_ENTRY, arch=AUDIT_ARCH_X86_64, instruction_pointer=0x7ffa5c316984, stack_pointer=0x7ffca877c488, entry={nr=__NR_close, args=[0x3, 0x63d5a3ac611b, 0, 0x63d5a3ac611b, 0x64, 0]}}) = 80write(2, "close(3", 7) = 7ptrace(PTRACE_SYSCALL, 2867285, NULL, 0) = 0--- SIGCHLD {si_signo=SIGCHLD, si_code=CLD_TRAPPED, si_pid=2867285, si_uid=1000, si_status=SIGTRAP, si_utime=0, si_stime=0} ---wait4(-1, [{WIFSTOPPED(s) && WSTOPSIG(s) == SIGTRAP | 0x80}], __WALL, NULL) = 2867285wait4(-1, 0x7ffe0ba737ac, WNOHANG|__WALL, NULL) = 0ptrace(PTRACE_GET_SYSCALL_INFO, 2867285, 88, {op=PTRACE_SYSCALL_INFO_EXIT, arch=AUDIT_ARCH_X86_64, instruction_pointer=0x7ffa5c316984, stack_pointer=0x7ffca877c488, exit={rval=0, is_error=0}}) = 33write(2, ") "..., 37) = 37ptrace(PTRACE_SYSCALL, 2867285, NULL, 0) = 0wait4(-1, [{WIFSTOPPED(s) && WSTOPSIG(s) == SIGTRAP | 0x80}], __WALL, NULL) = 2867285--- SIGCHLD {si_signo=SIGCHLD, si_code=CLD_TRAPPED, si_pid=2867285, si_uid=1000, si_status=SIGTRAP, si_utime=0, si_stime=0} ---wait4(-1, 0x7ffe0ba737ac, WNOHANG|__WALL, NULL) = 0ptrace(PTRACE_GET_SYSCALL_INFO, 2867285, 88, {op=PTRACE_SYSCALL_INFO_ENTRY, arch=AUDIT_ARCH_X86_64, instruction_pointer=0x7ffa5c31c804, stack_pointer=0x7ffca877c348, entry={nr=__NR_write, args=[0x1, 0x63d5a68bd2a0, 0xb9, 0x7ffca877c3ef, 0x7ffca877c460, 0]}}) = 80ptrace(PTRACE_SYSCALL, 2867285, NULL, 0) = 0--- SIGCHLD {si_signo=SIGCHLD, si_code=CLD_TRAPPED, si_pid=2867285, si_uid=1000, si_status=SIGTRAP, si_utime=0, si_stime=0} ---wait4(-1, [{WIFSTOPPED(s) && WSTOPSIG(s) == SIGTRAP | 0x80}], __WALL, NULL) = 2867285wait4(-1, 0x7ffe0ba737ac, WNOHANG|__WALL, NULL) = 0ptrace(PTRACE_SYSCALL, 2867285, NULL, 0) = 0--- SIGCHLD {si_signo=SIGCHLD, si_code=CLD_TRAPPED, si_pid=2867285, si_uid=1000, si_status=SIGTRAP, si_utime=0, si_stime=0} ---wait4(-1, [{WIFSTOPPED(s) && WSTOPSIG(s) == SIGTRAP | 0x80}], __WALL, NULL) = 2867285wait4(-1, 0x7ffe0ba737ac, WNOHANG|__WALL, NULL) = 0ptrace(PTRACE_GET_SYSCALL_INFO, 2867285, 88, {op=PTRACE_SYSCALL_INFO_ENTRY, arch=AUDIT_ARCH_X86_64, instruction_pointer=0x7ffa5c2ee2dd, stack_pointer=0x7ffca877c4b8, entry={nr=__NR_exit_group, args=[0, 0xffffffffffffff88, 0xe7, 0x7ffca877c3ef, 0x7ffca877c460, 0]}}) = 80ptrace(PTRACE_SYSCALL, 2867285, NULL, 0) = 0--- SIGCHLD {si_signo=SIGCHLD, si_code=CLD_TRAPPED, si_pid=2867285, si_uid=1000, si_status=SIGTRAP, si_utime=0, si_stime=0} ---wait4(-1, [{WIFSTOPPED(s) && WSTOPSIG(s) == SIGTRAP}|PTRACE_EVENT_EXIT<<16], __WALL, NULL) = 2867285wait4(-1, 0x7ffe0ba737ac, WNOHANG|__WALL, NULL) = 0ptrace(PTRACE_SYSCALL, 2867285, NULL, 0) = 0wait4(-1, [{WIFEXITED(s) && WEXITSTATUS(s) == 0}], __WALL, NULL) = 2867285--- SIGCHLD {si_signo=SIGCHLD, si_code=CLD_EXITED, si_pid=2867285, si_uid=1000, si_status=0, si_utime=0, si_stime=0} ---wait4(-1, 0x7ffe0ba737ac, WNOHANG|__WALL, NULL) = -1 ECHILD (No child processes)write(2, "+++ exited with 0 +++\n", 22) = 22wait4(-1, 0x7ffe0ba737ac, __WALL, NULL) = -1 ECHILD (No child processes)exit_group(0) = ?+++ exited with 0 +++How Kernel i_rwsem and Stateless kiocb Close Race Windows
Every race in atomic_idioms disappeared as soon as check-and-use moved inside one kernel boundary: O_CREAT | O_EXCL serialized existence check + inode allocation under the parent directory's i_rwsem; pwrite64 and pread64 wrote and read slots 0 and 8 via stack-local kiocb.ki_pos without touching f_pos = 4; and atomic_replace_at ensured readers of "ksa_m04_cfg.v1" could never observe a half-written configuration file!
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 pwrite_full() above:
- Step 1 (Reject negative offsets & advance both coordinates): Guard
if (off < 0) { errno = EINVAL; return -1; }, and insidewhile (done < len)callpread(fd, p + done, len - done, off + (off_t)done). - Step 2 (Distinguish
EOFvsEINTR): Break cleanly whenn == 0(returning(ssize_t)donefor partial tail slots), continue whenn < 0 && errno == EINTR, and verify thatlseek(fd, 0, SEEK_CUR)before and afterpread_full()returns the exact same offset.
Independent Practice: renameat2(..., RENAME_NOREPLACE) Lockless Publisher
On Linux 3.15+ (#define _GNU_SOURCE), renameat2(dfd, tmp_name, dfd, target_name, RENAME_NOREPLACE) atomically publishes a staged temporary file only if target_name does not yet exist (returning -1 with EEXIST instead of overwriting!). Write a C11 test publish_once.c that stages two competing files in /tmp via openat(..., O_CREAT | O_EXCL | O_CLOEXEC, 0600), races two renameat2(..., RENAME_NOREPLACE) calls onto "ksa_manifest.v1", proves the second fails with EEXIST while leaving the winner's payload intact, and cleans up all /tmp artifacts.
Common Production Pitfalls
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).
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).
Knowledge Check
? check 1 · 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?
- [ ]
4160, because reading64bytes at4096advancesf_posto4096 + 64 - [x]
128, becausepread()operates on stack-localkiocb.ki_poswithout reading or modifyingstruct file.f_pos - [ ]
0, becausepread()rewindsf_posafter every call
Answer: 128, because pread() operates on stack-local kiocb.ki_pos without reading or modifying struct file.f_pos
Why: 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.
? check 2 · 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?
- [x] Preemption between Process A's
lseek()andwrite()lets Process B append at that exactEOFoffset first, after which Process A's resumedwrite()overwrites Process B's32-byte record - [ ]
SEEK_ENDreads a stale superblock cache that updates only onclose() - [ ] Two processes cannot open one
ext4file withO_WRONLYsimultaneously
Answer: Preemption between Process A's lseek() and write() lets Process B append at that exact EOF offset first, after which Process A's resumed write() overwrites Process B's 32-byte record
Why: 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.
? check 3 · (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?
- [ ]
pwrite(fd, buf + 1024, 3072, slot_off)keepingslot_offfixed - [x]
pwrite(fd, buf + 1024, 3072, slot_off + 1024), advancing both the buffer pointer and the explicitoff_tcoordinate - [ ]
write(fd, buf + 1024, 3072)becausef_posmoved toslot_off + 1024
Answer: pwrite(fd, buf + 1024, 3072, slot_off + 1024), advancing both the buffer pointer and the explicit off_t coordinate
Why: 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.
? check 4 · 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))?
- [ ] Because
openat()bypasses POSIXumaskand permission checks - [x] Because string paths re-walk parent prefixes on every syscall (permitting directory symlink swaps), whereas pinning
openat()+fdatasync(tfd)+renameat()+fsync(dfd)todfdcloses prefixTOCTOUraces and persists atomic replacement across power loss - [ ] Because
renameat()automatically flushes bothtfdanddfdto NVMe media
Answer: Because string paths re-walk parent prefixes on every syscall (permitting directory symlink swaps), whereas pinning openat() + fdatasync(tfd) + renameat() + fsync(dfd) to dfd closes prefix TOCTOU races and persists atomic replacement across power loss
Why: 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.
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. - 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-stable ioctl() structures, and ftruncate() file resizing.
Step sequence — frame strip: steps_m04_l02
Pin an O_DIRECTORY descriptor dfd and create staging files via openat(..., O_CREAT | O_EXCL | O_NOFOLLOW | O_CLOEXEC, 0600).
reveals: step1
highlights: step1
Transfer fixed-offset records via stateless pwrite_full(), advancing both p + done and off + done on short counts.
reveals: step2
highlights: step2
Commit staged file blocks via fdatasync(tfd) and verify close(tfd) == 0 before publishing.
reveals: step3
highlights: step3
Atomically swap the directory entry with renameat(dfd, tmp, dfd, final) and persist via fsync(dfd).
reveals: step4
highlights: step4
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.
Why Blind F_SETFL Wipes Flags & Sloppy ioctl Structs Fail With ENOTTY
Three runtime descriptor bugs ambush systems engineers regularly. First, a log forwarder enables non-blocking mode on an already-open O_WRONLY | O_APPEND descriptor by calling fcntl(fd, F_SETFL, O_NONBLOCK)—unwittingly clearing O_APPEND in struct file.f_flags so concurrent workers begin overwriting one another! Second, a vendor header defines struct motor_ioctl { unsigned long speed; uint16_t mode; }; inside #define MOTOR_SET _IOW('m', 1, struct motor_ioctl): a 32-bit ARMv7 diagnostic tool running under a 64-bit kernel fails every ioctl() with ENOTTY (Inappropriate ioctl for device) because sizeof(struct motor_ioctl) changed from 8 bytes to 16 bytes, altering the command integer itself! Third, compacting a 4,096-byte log via ftruncate(fd, 0) followed by write(fd, hdr, 32) injects a 4,096-byte leading sparse hole because ftruncate() never rewinds f_pos!
Controlling already-open descriptors cleanly requires respecting the VFS boundary between Tier A per-slot flags (F_GETFD/F_SETFD) and Tier B shared open-file flags (F_GETFL/F_SETFL), encoding ABI-invariant ioctl() UAPI structures, and repositioning f_pos explicitly after ftruncate().
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.
definition (fcntl() Flag Tiers, Out-of-Band ioctl() & ftruncate()): 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.
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 _IOWR(type, nr, data_type) request integer via cmd = (dir << 30) | (sizeof(data_type) << 16) | (type << 8) | nr. Bits [31:30] encode transfer direction (00 none, 01 write user->kernel, 10 read kernel->user, 11 read/write), bits [29:16] (14 bits, extracted via _IOC_SIZE(cmd)) store sizeof(struct), bits [15:8] store the 8-bit magic character ('k'), and bits [7:0] store the command ordinal! If a struct uses long, pointers, or implicit compiler padding holes (uint32_t + uint16_t + [2-byte hole] + uint64_t), either _IOC_SIZE(cmd) diverges across 32/64-bit builds (ENOTTY) or unzeroed stack padding leaks secrets across the ring boundary. Always use <stdint.h> fixed-width fields, explicit reserved_zero padding, memset(&cfg, 0, sizeof(cfg)), and _Static_assert(sizeof(...) == N).
Syscall / fcntl() Command | Kernel Tier Mutated | Mutable Bits & Immutability / Error Contract |
|---|---|---|
F_DUPFD / F_DUPFD_CLOEXEC | files_struct table | Allocates lowest free fd >= arg; _CLOEXEC sets FD_CLOEXEC atomically |
F_GETFD / F_SETFD | files_struct slot bit | Reads/writes FD_CLOEXEC on fd alone (aliases unaffected) |
F_GETFL / F_SETFL | Shared struct file.f_flags | Read-modify-write O_APPEND, O_NONBLOCK, O_ASYNC, O_DIRECT, O_NOATIME; O_ACCMODE is immutable |
ioctl(fd, FIONREAD, &n) | Subsystem / driver .unlocked_ioctl | Queries unread pipe/socket/TTY bytes; TIOCGWINSZ returns ENOTTY on non-TTYs |
ftruncate(fd, len) / truncate | struct inode.i_size | Requires writable fd (EINVAL/EBADF if O_RDONLY); f_pos stays unchanged! |
Figure 4.3. 32-bit _IOC command bitfield encoding, fcntl() Tier A vs Tier B flag control, and ftruncate() cursor invariants.
- Step 1. Clone or update per-slot FD_CLOEXEC via F_DUPFD_CLOEXEC and F_GETFD / F_SETFD without disturbing aliases.
- Step 2. Read fl = fcntl(fd, F_GETFL) before fcntl(fd, F_SETFL, fl | O_NONBLOCK) so O_APPEND is never wiped.
- Step 3. Lock _IOWR payload structs with fixed-width <stdint.h> types, explicit zeroed padding, and _Static_assert.
- Step 4. Reposition f_pos via lseek() (or write via pwrite()) after shrinking inode->i_size with ftruncate().
Figure 4.3b. 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().
fcntl(2) Quick Reference & Read-Modify-Write Discipline
Define #define _GNU_SOURCE and #define _FILE_OFFSET_BITS 64 before <fcntl.h>, <unistd.h>, and <sys/ioctl.h>. Remember: F_GETFD and F_GETFL return -1 on error (because valid bitmasks can be 0!), so check if (fl == -1) rather than fl <= 0 before ORing fl | O_APPEND into F_SETFL.
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). EINVAL Unrecognized cmd, negative ftruncate length, or fd not writable. EMFILE F_DUPFD* minimum arg >= RLIMIT_NOFILE or no free slots >= arg. NOTES F_SETFL updates only O_APPEND, O_ASYNC, O_DIRECT, O_NOATIME, O_NONBLOCK; always read F_GETFL first so existing status flags are preserved. SEE ALSO dup3(2), ioctl(2), lseek(2), open(2) Kernel Systems Academy Lesson 4.3 fcntl(2) GL-C01 quick reference · full manual page: man 2 fcntl Probing fcntl Tiers, ABI-Verified ioctl & ftruncate Cursor Invariants
Save desc_ctl.c below. It duplicates an open file to fd >= 40 via F_DUPFD_CLOEXEC (cloexec: 0->1), verifies (fl & O_ACCMODE) == O_RDWR and enables O_APPEND via read-modify-write F_SETFL, queries FIONREAD (19 piped bytes) and TIOCGWINSZ (ENOTTY) via ioctl(), validates _Static_assert(sizeof(struct ksa_dev_cfg) == 16) + _IOC_SIZE(KSA_IOC_CFG) == 16 + _IOC_DIR(KSA_IOC_CFG) == 3, and proves ftruncate(fd, 16) shrinks st_size from 32 to 16 while leaving f_pos at 32!
learner@ksa:~/gl-c01/m04-l03$ bat -H 18 -H 36 -H 56 desc_ctl.c File: desc_ctl.c #define _GNU_SOURCE #define _FILE_OFFSET_BITS 64 #include <errno.h> #include <fcntl.h> #include <stdint.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <sys/ioctl.h> #include <sys/stat.h> #include <unistd.h> struct ksa_dev_cfg { uint32_t rate_hz; uint16_t flags; uint16_t reserved_zero; uint64_t cookie; }; _Static_assert(sizeof(struct ksa_dev_cfg) == 16, "ABI size must be 16"); #define KSA_IOC_CFG _IOWR('k', 0x11, struct ksa_dev_cfg) int main(void) { const char *path = "/tmp/ksa_m04_l03.dat"; int fd = open(path, O_RDWR | O_CREAT | O_TRUNC, 0644); if (fd < 0) return 1; int hi_fd = fcntl(fd, F_DUPFD_CLOEXEC, 40); if (hi_fd < 40) return 1; int fd_clo0 = (fcntl(fd, F_GETFD) & FD_CLOEXEC) ? 1 : 0; int hi_clo1 = (fcntl(hi_fd, F_GETFD) & FD_CLOEXEC) ? 1 : 0; if (fcntl(fd, F_SETFD, FD_CLOEXEC) < 0) return 1; (void)close(hi_fd); int fl = fcntl(fd, F_GETFL); if (fl == -1) return 1; const char *acc = ((fl & O_ACCMODE) == O_RDWR) ? "O_RDWR" : "OTHER"; if (fcntl(fd, F_SETFL, fl | O_APPEND) < 0) return 1; int fl_now = fcntl(fd, F_GETFL); printf("fcntl_state: hi_ge40=yes cloexec=%d->%d acc=%s append=%d\n", fd_clo0, hi_clo1, acc, (fl_now & O_APPEND) ? 1 : 0); int queued = 0; if (ioctl(STDIN_FILENO, FIONREAD, &queued) < 0) return 1; struct winsize ws; errno = 0; int tty_rc = ioctl(STDIN_FILENO, TIOCGWINSZ, &ws); int tty_err = errno; struct ksa_dev_cfg cfg; memset(&cfg, 0, sizeof(cfg)); unsigned int ioc_sz = (unsigned int)_IOC_SIZE(KSA_IOC_CFG); printf("ioctl_probe: pipe_fionread=%d winsize_enotty=%s ioc_sz=%u\n", queued, (tty_rc == -1 && tty_err == ENOTTY) ? "yes" : "no", ioc_sz); if (write(fd, "0123456789ABCDEF0123456789ABCDEF", 32) != 32) return 1; off_t before = lseek(fd, 0, SEEK_CUR); if (ftruncate(fd, 16) < 0) return 1; off_t after = lseek(fd, 0, SEEK_CUR); struct stat st; if (fstat(fd, &st) < 0) return 1; (void)close(fd); if (truncate(path, 64) < 0 || stat(path, &st) < 0) return 1; int rfd = open(path, O_RDONLY | O_CLOEXEC); unsigned char zcheck = 0xFFU; if (rfd < 0 || pread(rfd, &zcheck, 1, 48) != 1) return 1; (void)close(rfd); (void)unlink(path); printf("resize_check: shrunk=16 f_pos=%lld->%lld ext=%lld zero=%u\n", (long long)before, (long long)after, (long long)st.st_size, (unsigned int)zcheck); return 0; }- Explicit reserved_zero padding + _Static_assert keeps sizeof(struct ksa_dev_cfg) == 16 across 32-bit ARMv7 and 64-bit x86-64.
- Read F_GETFL first and pass fl | O_APPEND to F_SETFL so existing mutable status flags are never wiped.
- ftruncate(fd, 16) shrinks inode->i_size to 16 immediately while leaving struct file.f_pos untouched at 32.
Verifying Flag Bitmasks, FIONREAD, ftruncate & Lab 4
Compile desc_ctl.c, pipe a 19-byte payload (TELEMETRY_PING_2026) into STDIN_FILENO, verify every output line, and complete lab_m04_atomic_kv.
learner@ksa:~/gl-c01/m04-l03gcc -fdiagnostics-color=always -std=c11 -Wall -Wextra -Werror desc_ctl.c -o desc_ctllearner@ksa:~/gl-c01/m04-l03printf 'TELEMETRY_PING_2026' | ./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-l03test ! -e /tmp/ksa_m04_l03.dat && rm -f desc_ctllearner@ksa:~/gl-c01/m04-l031. Motivation
Embedded device-state registries and shared configuration stores suffer silent corruption when concurrent processes test lockfiles via access() + open() (TOCTOU race) or read and write fixed-size record slots via lseek() + write() (clobbering shared struct file.f_pos cursors on preemption). In this lab, you will engineer atomic_kv, a race-free 64-byte positional key-value store combining exclusive O_CREAT | O_EXCL | O_CLOEXEC lockfiles, fcntl() flag verification, stateless pwrite()/pread() transfers, and ftruncate() tail compaction.
2. Learning Objectives
- Enforce atomic mutual exclusion across processes using
open(..., O_WRONLY | O_CREAT | O_EXCL | O_CLOEXEC, 0600)and verifyEEXISTrejection on collision. - Verify per-descriptor
FD_CLOEXEC(F_GETFD) andO_ACCMODE/ clearO_APPENDstatus flags (F_GETFL) at runtime viafcntl(). - Execute short-count-safe
pwrite_all()andpread_full()operations across64-byte record slots while provinglseek(fd, 0, SEEK_CUR) == 0stays untouched. - Resize and compact the slot store cleanly using
ftruncate(fd, keep_slots * 64).
3. Environment Requirements
- Host Execution Environment (Tested): Linux
6.12LTS (x86_64,glibc2.39+),#define _POSIX_C_SOURCE 200809Land#define _FILE_OFFSET_BITS 64. - Target Board Portability (
ARMv7Cortex-A7): Fixed64-byteuint8_tslot framing (activebyte +char key[24]+char val[39],0compiler padding) and 64-bitpread/pwriteproduce byte-identical database files across 32-bitARMv7and 64-bitx86_64processes.
4. Required Software & Hardware
- Software Toolchain:
gcc(-std=c11 -Wall -Wextra -Werror),strace,stat, and/bin/sh. - Hardware: Standard Linux host environment.
5. Complete Executable Commands
Run from labs/lab_m04_atomic_kv/:
learner@ksa:~/gl-c01/m04-l03$ bat script.sh File: script.sh # 1. Compile the warning-clean positional record store gcc -std=c11 -O2 -Wall -Wextra -Werror files/atomic_kv.c -o /tmp/atomic_kv # 2. Verify atomic O_CREAT | O_EXCL | O_CLOEXEC lockfile and fcntl() inspection /tmp/atomic_kv lock-check /tmp/ksa_test.lock # 3. Initialize a 16-slot (1,024-byte) database, populate slots 0 and 9, and query slot 9 /tmp/atomic_kv init /tmp/ksa_kv.db 16 /tmp/atomic_kv put /tmp/ksa_kv.db 0 board_rev v2.4 /tmp/atomic_kv put /tmp/ksa_kv.db 9 vcore_mv 1200 /tmp/atomic_kv get /tmp/ksa_kv.db 9 # 4. Compact database to 4 slots (256 bytes) and confirm slot 9 is now out-of-bounds (rc=1) /tmp/atomic_kv compact /tmp/ksa_kv.db 4 /tmp/atomic_kv get /tmp/ksa_kv.db 0 /tmp/atomic_kv get /tmp/ksa_kv.db 9 || echo "slot_9_compacted_ok" # 5. Clean up and execute the full TAP 13 verification suite rm -f /tmp/atomic_kv /tmp/ksa_kv.db /tmp/ksa_kv.db.lock sh check.sh*Why each command runs:* lock-check proves duplicate O_CREAT | O_EXCL fails with EEXIST and fcntl() reads FD_CLOEXEC + O_WRONLY; init uses ftruncate() to create a zero-filled 1,024-byte slot table; put/get prove pwrite()/pread() leave f_pos=0; and compact shrinks inode->i_size to 256 bytes while preserving slot 0.
6. Annotated Source Code (starter/ Flaws vs files/ Reference)
Flawed Baseline (starter/atomic_kv.c)
- Broken lockfile (
lock-check): Callsopen(argv[2], O_WRONLY | O_CREAT, 0600)withoutO_EXCLorO_CLOEXEC, allowing two processes to open the lock simultaneously! - Stateful
lseek() + write()(put): Mutatesstruct file.f_pos(f_pos=640instead of0), omitsinitftruncate()sizing, and lacks bounds checks. - Missing
getandcompact: Unimplemented subcommands fail tests 3–5.
Warning-Clean Reference (files/atomic_kv.c)
acquire_lock()/release_lock(): Formats<db_path>.lockvia boundedsnprintf()(ret < 0 || (size_t)ret >= cap) and acquiresO_WRONLY | O_CREAT | O_EXCL | O_CLOEXEC(0600).- Flag Guard (
put): Verifies(fl & O_APPEND) == 0viafcntl(fd, F_GETFL)—critical on Linux becausepwrite()ignoresoffsetifO_APPENDis set! - Stateless Slot I/O (
pwrite_all/pread_full): Transfers64bytes at(off_t)slot_idx * 64while advancing(p + done, off + done)on short counts/EINTR, then confirmslseek(fd, 0, SEEK_CUR) == 0and forces NUL termination (key[KEY_MAX - 1] = '\0') before printing untrusted disk bytes.
7. Expected Output
learner@ksa:~/gl-c01/m04-l03$ bat listing.txt File: listing.txt $ sh check.sh TAP version 13 1..5 ok 1 - builds cleanly with -std=c11 -Wall -Wextra -Werror ok 2 - enforces atomic O_CREAT|O_EXCL|O_CLOEXEC lockfile and fcntl inspection ok 3 - initializes fixed-slot store and executes stateless pwrite/pread leaving f_pos=0 ok 4 - rejects empty, negative, and out-of-bounds slot queries cleanly ok 5 - compacts tail slots via ftruncate while preserving earlier records # pass 5/58. Explanation of Observed Behavior
Under strace -e trace=openat,fcntl,pwrite64,pread64,ftruncate,lseek, init extends <db_path> to slots * 64 sparse zero bytes in 1 ftruncate() call (active == 0 in every slot). Each put writes a self-contained 64-byte record via pwrite64(fd, raw, 64, slot * 64) using stack-local kiocb.ki_pos, so lseek(fd, 0, SEEK_CUR) afterward still reports 0 (f_pos=0). Note that get needs no lockfile when 64-byte aligned writes stay within a single 4 KiB page-cache folio under i_rwsem or when callers coordinate single-slot updates, and pread64 never contends on file->f_pos_lock.
9. Experiment Variations
- Linux
O_APPEND+pwrite()Quirk Reproduction: Temporarily add| O_APPENDtoopen()inside a scratch copy ofputand observepwrite(fd, raw, 64, 0)append at byte1,024instead of updating slot0—proving why(fl & O_APPEND) != 0must be rejected! - Concurrent Reader/Writer Stress Test: Spawn
4background reader loops running./atomic_kv get ... 0(100iterations each) while a writer updates slot0between"v1"and"v2", verifying0torn strings or cursor errors. - Stale Lockfile PID Inspection: Write the holder's
getpid()into<db_path>.lockbefore releasing so operators debugging a crashed holder can checkkill(pid, 0)(ESRCH).
10. Performance Measurements
Measured on Host x86_64 Linux 6.12 LTS (CLOCK_MONOTONIC, 5 warmup runs, N = 35 paired put + get CLI transactions on a 64-slot 4 KiB store):
| Metric | Measured Host (x86_64 Linux 6.12) | Target Board Expectation (ARMv7 Cortex-A7) |
|---|---|---|
Paired put + get CLI latency (p50 / p95 / p99) | 3,794.9 us / 4,827.7 us / 4,850.6 us | ~15,000–22,000 us (2 process spawns; < 4 us in-process pread/pwrite) |
pwrite64 / pread64 syscalls per put / get | 1 / 1 (0 f_pos mutations) | 1 / 1 (pread64/pwrite64 EABI register pair) |
11. Troubleshooting
| Symptom | Root Cause | Fix |
|---|---|---|
put fails immediately on subsequent calls (rc=1) | Forgot to unlink(lock_path) inside release_lock(), leaving .lock on disk (EEXIST) | Always close(lock_fd) and unlink(lock_path) on every exit path |
PUT prints f_pos=64 instead of f_pos=0 | Called stateful write() instead of pwrite() | Use pwrite_all(fd, raw, 64, off) |
fcntl(fd, F_SETFD, O_CLOEXEC) fails to set FD_CLOEXEC | Passed O_CLOEXEC (02000000) instead of FD_CLOEXEC (1) to F_SETFD! | Pass O_CLOEXEC to open()/dup3(), and FD_CLOEXEC to fcntl(F_SETFD)! |
12. Guided Questions
- Why must
fcntl(fd, F_SETFD, ...)receiveFD_CLOEXEC(1) whereasopen()receivesO_CLOEXEC(02000000)?
- *Hint 1:* Recall the two VFS flag tiers from
m04-l03(files_structper-slot bitmask vs open-timeflagsmultiplexer). - *Hint 2:* Print
(int)FD_CLOEXECand(int)O_CLOEXECin C: what happens to bit0(FD_CLOEXEC == 1) if you pass02000000(0x80000, bit0 == 0!) toF_SETFD?
- Why does
getdefensively setkey[KEY_MAX - 1] = '\0'aftermemcpy()from disk?
- *Hint 1:* Can an untrusted or bit-flipped database file on disk contain
24non-zero bytes inraw[1..24]? - *Hint 2:* What would
printf("key=%s", key)do ifkeylacked a'\0'byte?
13. Independent Challenges
- Near Transfer — Advisory Byte-Range Slot Locks (
F_SETLKW): Replace the coarse whole-file<db_path>.lockwith per-slotstruct flockbyte-range locks (l_type = F_WRLCK,l_whence = SEEK_SET,l_start = slot_idx * 64,l_len = 64) viafcntl(fd, F_SETLKW, &fl)so writers updating disjoint slots run concurrently! - Far Transfer — Directory-Pinned
*at()Store Engine: Refactoratomic_kv.cto open its parent directory once (O_RDONLY | O_DIRECTORY | O_CLOEXEC) and execute all lockfile and database operations viaopenat()andunlinkat(), closing path-prefix symlink swap vectors.
14. Solutions & Explanations
- Guided Question 1:
FD_CLOEXECequals1(bit 0), whereasO_CLOEXECequals0x80000(bit 19, bit0 == 0)! PassingO_CLOEXECtoF_SETFDactually clearsFD_CLOEXECto0—one of the subtlest macro mix-ups in POSIX C! - Guided Question 2: Disk files are untrusted external inputs; clamping
key[KEY_MAX - 1] = '\0'andval[VAL_MAX - 1] = '\0'guarantees%sformatting can never overread stack memory even on a corrupted image.
Run locally in your terminal and check off each verification milestone.
Not started
Kernel Mechanics Across fcntl, ioctl & Inode Resizing
In desc_ctl, F_DUPFD_CLOEXEC scanned files_struct starting at slot 40 and set FD_CLOEXEC atomically on hi_fd while leaving fd's slot bit 0. Next, F_GETFL + F_SETFL toggled O_APPEND on struct file.f_flags without disturbing O_RDWR, FIONREAD inspected the kernel pipe buffer's unread byte count (19) without consuming input, and ftruncate(fd, 16) proved f_pos remains at 32 unless repositioned!
Guided Practice: Safe Read-Modify-Write set_nonblocking() Helper
Write a reusable helper int set_nonblocking(int fd, int enable) that sets or clears O_NONBLOCK without disturbing O_APPEND or O_DIRECT:
- Step 1 (Query & check
F_GETFL): Callint fl = fcntl(fd, F_GETFL);and return-1immediately whenfl == -1(preservingEBADF). - Step 2 (Compute
next_flcleanly): Computeint next_fl = enable ? (fl | O_NONBLOCK) : (fl & ~O_NONBLOCK);and callfcntl(fd, F_SETFL, next_fl)only ifnext_fl != fl(saving a redundant syscall when already in the target state!).
Independent Practice: _IOC Bitfield Decoder & Struct ABI Auditor
Write a C11 utility ioctl_decode.c (-std=c11 -Wall -Wextra -Werror) that takes three real Linux ioctl request constants (FIONREAD, TIOCGWINSZ, and a custom _IOWR('s', 0x2A, struct sensor_cal)), extracts _IOC_DIR(cmd), _IOC_TYPE(cmd), _IOC_NR(cmd), and _IOC_SIZE(cmd), and verifies with _Static_assert that offsetof and sizeof(struct sensor_cal) contain zero unnamed compiler padding bytes.
Common Production Pitfalls
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);.
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).
Knowledge Check
? check 1 · Given int fl = fcntl(fd, F_GETFL); (fl != -1), which expression correctly tests whether fd was opened read-only (O_RDONLY)?
- [ ]
if (fl & O_RDONLY) - [x]
if ((fl & O_ACCMODE) == O_RDONLY) - [ ]
if (fcntl(fd, F_GETFD) == O_RDONLY)
Answer: if ((fl & O_ACCMODE) == O_RDONLY)
Why: 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.
? check 2 · Which set of flags can be modified at runtime on an already-open Linux file descriptor via fcntl(fd, F_SETFL, new_flags)?
- [ ]
O_RDWRandO_CREAT - [ ]
FD_CLOEXECandO_TRUNC - [x]
O_NONBLOCK,O_APPEND,O_ASYNC,O_DIRECT, andO_NOATIME
Answer: O_NONBLOCK, O_APPEND, O_ASYNC, O_DIRECT, and O_NOATIME
Why: 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.
? check 3 · (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?
- [ ]
fd2stays blocking and hasFD_CLOEXEC == 0becausefcntl()clones a separatestruct file - [x]
fd2immediately becomes non-blocking because it sharesstruct filewithfd1, whilefd2retainsFD_CLOEXEC == 1on its own descriptor slot - [ ]
fd2losesFD_CLOEXECwheneverF_SETFLmutatesfd1
Answer: fd2 immediately becomes non-blocking because it shares struct file with fd1, while fd2 retains FD_CLOEXEC == 1 on its own descriptor slot
Why: 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.
? check 4 · 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?
- [ ] Because
_IOWRhashes C member names into the request code at compile time - [x] Because
_IOWRembedssizeof(struct cfg)into bits[29:16](_IOC_SIZE(cmd)) of the 32-bit command integer, solongor padding shiftssizeofacross 32/64-bit ABIs (ENOTTY) and leaks stack bytes if padding is unzeroed - [ ] Because Linux
ioctl()rejects structs larger than8bytes
Answer: Because _IOWR embeds sizeof(struct cfg) into bits [29:16] (_IOC_SIZE(cmd)) of the 32-bit command integer, so long or padding shifts sizeof across 32/64-bit ABIs (ENOTTY) and leaks stack bytes if padding is unzeroed
Why: 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.
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. 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 3 to dissect how glibc <stdio.h> FILE streams amortize syscall traps, handle binary fread/fwrite tails, and parse text safely.
Step sequence — frame strip: steps_m04_l03
Clone or update per-slot FD_CLOEXEC via F_DUPFD_CLOEXEC and F_GETFD / F_SETFD without disturbing aliases.
reveals: step1
highlights: step1
Read fl = fcntl(fd, F_GETFL) before fcntl(fd, F_SETFL, fl | O_NONBLOCK) so O_APPEND is never wiped.
reveals: step2
highlights: step2
Lock _IOWR payload structs with fixed-width <stdint.h> types, explicit zeroed padding, and _Static_assert.
reveals: step3
highlights: step3
Reposition f_pos via lseek() (or write via pwrite()) after shrinking inode->i_size with ftruncate().
reveals: step4
highlights: step4
m05/
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.
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.
Why Raw Syscalls Stall Tiny Writes & Plain "w+" Opens Races
Suppose a high-rate telemetry collector formats 4,096 four-byte voltage samples per batch and emits each sample with write(fd, &sample, 4). Even before touching non-volatile media, executing 4,096 synchronous syscall / svc #0 privilege switches burns roughly 4,096 * 200 ns = ~820 us in pure CPU trap overhead! Switching blindly to ISO C fopen(path, "w+"), however, introduces two new production hazards if you do not know what glibc passes to the kernel: plain "w+" omits O_CLOEXEC (leaking descriptors across execve()) and omits O_EXCL (silently truncating an existing file), while ignoring fclose(fp)'s return value drops deferred ENOSPC flush errors!
High-throughput, leak-free stream I/O requires understanding how glibc's user-space FILE control block batches transfers above raw integer descriptors, and how glibc mode suffixes ("e" and "x") forward kernel safety flags straight into openat().
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.
definition (Standard I/O Stream (FILE), Mode Extensions & Memory Streams): 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).
One Layer Down: _IO_FILE Cursor Pointers & Syscall Amortization Math
Inside glibc (libio/bits/types/struct_FILE.h), writing s bytes via fwrite() or fputs() checks whether _IO_write_end - _IO_write_ptr >= s under the stream's internal flockfile lock: when room remains inside the 4,096- or 8,192-byte (BUFSIZ) heap buffer, glibc executes a pure Ring 3 memcpy() and advances _IO_write_ptr += s with zero syscalls. For N records of s bytes buffered in capacity B bytes, kernel write() traps drop from N to N_syscalls = ceil((N * s) / B). Streaming N = 4,096 one-byte writes through an 8,192-byte FILE buffer issues 1 write() syscall on fclose() instead of 4,096 traps—a 4,096x reduction in Ring 0 transitions!
fopen() Mode String | Exact openat() Kernel Flags | Missing Target | Existing Target | Stream Capabilities | ||
|---|---|---|---|---|---|---|
"r" / "rb" | O_RDONLY | NULL (ENOENT) | Preserved | Read-only from 0 ("b" is a POSIX no-op) | ||
"r+" / "r+b" | O_RDWR | NULL (ENOENT) | Preserved | Read/write update from 0 | ||
"w" / "w+" | O_WRONLY / O_RDWR `\ | O_CREAT \ | O_TRUNC` | Created (0666 & ~umask) | Truncated to 0 | Write or read/write from 0 |
"a" / "a+" | O_WRONLY / O_RDWR `\ | O_CREAT \ | O_APPEND` | Created (0666 & ~umask) | Preserved | Reads at 0 ("a+"); all writes jump to EOF |
"...e" ("re", "w+e") | Base flags `\ | O_CLOEXEC` | Per base mode | Per base mode | Sets FD_CLOEXEC atomically at open | |
"wxe" / "w+xe" | "w"/"w+" `\ | O_EXCL \ | O_CLOEXEC` | Created atomically | Fails NULL (EEXIST) | Race-free + leak-free exclusive creation |
Figure 5.1. User-space glibc struct _IO_FILE state, open_memstream() vtables, and exact fopen() mode-to-openat() flag translations.
- Step 1. Open streams with glibc 'e' (O_CLOEXEC) and 'x' (O_EXCL) suffixes inside a single atomic openat() syscall.
- Step 2. Accumulate small fputc() and fwrite() records inside the 8 KiB Ring 3 _IO_FILE heap buffer with zero traps.
- Step 3. Drain full buffers via amortized block write() syscalls, cutting mode-switch overhead by >1,000x.
- Step 4. Verify fclose(fp) == 0 on every writable stream so final flush ENOSPC or EIO faults are never lost.
Figure 5.1b. Append glibc 'e' and 'x' safety suffixes on fopen(), batch tiny records in Ring 3 heap RAM, and always check fclose(fp) == 0.
Stream Headers, Checked fclose() & open_memstream()
Define #define _POSIX_C_SOURCE 200809L before <stdio.h>, <fcntl.h>, <time.h>, and <unistd.h> so fileno(), open_memstream(), and CLOCK_MONOTONIC are declared cleanly. Every C process starts with stdin (0), stdout (1), and stderr (2) pre-opened. Calling fclose(fp) flushes buffered output via write(), closes _fileno, and frees fp, returning 0 on success or EOF (-1) if that final flush or close() hit ENOSPC/EIO—always check if (fclose(fp) != 0) on writable streams!
Probing fopen Kernel Flags, open_memstream & Amortization Speedup
Save fopen_modes_probe.c below. It verifies fileno() on stdin/stdout/stderr (0,1,2), confirms "w+e"/"w+xe"/"a+e"/"rbe" translate to exact O_ACCMODE, O_APPEND, FD_CLOEXEC, and O_EXCL (EEXIST) kernel flags, exercises an in-memory open_memstream(&mbuf, &msz) stream (fileno(mfp) == -1 && errno == EBADF), and benchmarks 2,048 one-byte raw write() traps against 2,048 buffered fputc() calls with CLOCK_MONOTONIC!
learner@ksa:~/gl-c01/m05-l01$ bat -H 25 -H 65 -H 81 fopen_modes_probe.c File: fopen_modes_probe.c #define _POSIX_C_SOURCE 200809L #include <errno.h> #include <fcntl.h> #include <stdint.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <sys/stat.h> #include <time.h> #include <unistd.h> static uint64_t diff_ns(struct timespec a, struct timespec b) { return (uint64_t)(b.tv_sec - a.tv_sec) * 1000000000ULL + (uint64_t)(b.tv_nsec - a.tv_nsec); } int main(void) { const char *path = "/tmp/ksa_m05_l01.log"; (void)unlink(path); printf("std_streams: in=%d out=%d err=%d\n", fileno(stdin), fileno(stdout), fileno(stderr)); FILE *fp0 = fopen(path, "w+e"); if (!fp0) return 1; int fd0 = fileno(fp0); int wpe_ok = ((fcntl(fd0, F_GETFL) & O_ACCMODE) == O_RDWR) && ((fcntl(fd0, F_GETFD) & FD_CLOEXEC) != 0); if (fclose(fp0) != 0) return 1; (void)unlink(path); FILE *fp1 = fopen(path, "w+xe"); if (!fp1) return 1; int fd1 = fileno(fp1); int fl1 = fcntl(fd1, F_GETFL); int clo1 = (fcntl(fd1, F_GETFD) & FD_CLOEXEC) ? 1 : 0; if (fputs("BOOT\n", fp1) < 0) return 1; errno = 0; FILE *dup_wx = fopen(path, "wxe"); int wx_eexist = (dup_wx == NULL && errno == EEXIST) ? 1 : 0; if (dup_wx) (void)fclose(dup_wx); if (fclose(fp1) != 0) return 1; const char *acc1 = ((fl1 & O_ACCMODE) == O_RDWR) ? "O_RDWR" : "OTHER"; printf("mode_wplus_xe: wpe_ok=%d acc=%s append=%d cloexec=%d wx=%d\n", wpe_ok, acc1, (fl1 & O_APPEND) ? 1 : 0, clo1, wx_eexist); FILE *fp2 = fopen(path, "a+e"); if (!fp2) return 1; int fd2 = fileno(fp2); int fl2 = fcntl(fd2, F_GETFL); int clo2 = (fcntl(fd2, F_GETFD) & FD_CLOEXEC) ? 1 : 0; if (fputs("READY\n", fp2) < 0 || fclose(fp2) != 0) return 1; FILE *fp3 = fopen(path, "rbe"); if (!fp3) return 1; struct stat st; int rbe_ok = (fstat(fileno(fp3), &st) == 0 && (fcntl(fileno(fp3), F_GETFL) & O_ACCMODE) == O_RDONLY); if (fclose(fp3) != 0 || !rbe_ok) return 1; (void)unlink(path); char *mbuf = NULL; size_t msz = 0U; FILE *mfp = open_memstream(&mbuf, &msz); if (!mfp) return 1; errno = 0; int mem_no_fd = (fileno(mfp) == -1 && errno == EBADF); fprintf(mfp, "hdr=%u", 42U); if (fclose(mfp) != 0) { free(mbuf); return 1; } int mem_ok = (mem_no_fd && msz == 6U && strcmp(mbuf, "hdr=42") == 0); free(mbuf); struct timespec t0, t1, t2; int bfd = open(path, O_WRONLY | O_CREAT | O_TRUNC | O_CLOEXEC, 0644); if (bfd < 0) return 1; clock_gettime(CLOCK_MONOTONIC, &t0); for (int i = 0; i < 2048; i++) { if (write(bfd, "x", 1U) != 1) return 1; } clock_gettime(CLOCK_MONOTONIC, &t1); (void)close(bfd); FILE *bfp = fopen(path, "we"); if (!bfp) return 1; for (int i = 0; i < 2048; i++) { if (fputc('x', bfp) == EOF) return 1; } if (fclose(bfp) != 0) return 1; clock_gettime(CLOCK_MONOTONIC, &t2); (void)unlink(path); int faster = (diff_ns(t0, t1) > diff_ns(t1, t2)) ? 1 : 0; const char *acc2 = ((fl2 & O_ACCMODE) == O_RDWR) ? "O_RDWR" : "OTHER"; printf("mode_aplus_e: acc=%s append=%d cloexec=%d bytes=%lld " "mem=%d buf_faster=%d\n", acc2, (fl2 & O_APPEND) ? 1 : 0, clo2, (long long)st.st_size, mem_ok, faster); return 0; }- Mode w+xe maps to O_RDWR | O_CREAT | O_TRUNC | O_EXCL | O_CLOEXEC inside a single atomic openat() syscall.
- open_memstream() backs a FILE * with dynamically growing heap RAM; fileno() returns -1 with EBADF because no kernel fd exists.
- 2,048 fputc() calls copy bytes in Ring 3 RAM and emit a single write() syscall on fclose(), beating 2,048 raw write() traps.
Verifying Stream Flags, Memory Streams & Amortization Speedup
Compile and execute fopen_modes_probe: confirm std_streams (0, 1, 2), "w+xe" (O_RDWR, FD_CLOEXEC, wx=1), "a+e" (11 concatenated bytes "BOOT\nREADY\n"), mem=1, and buf_faster=1 (2,048 buffered fputc() calls outperforming 2,048 raw write() syscalls!).
learner@ksa:~/gl-c01/m05-l01gcc -fdiagnostics-color=always -std=c11 -O2 -Wall -Wextra -Werror fopen_modes_probe.c -o fopen_modes_probelearner@ksa:~/gl-c01/m05-l01./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-l01test ! -e /tmp/ksa_m05_l01.log && rm -f fopen_modes_probelearner@ksa:~/gl-c01/m05-l01Inside glibc fopen(), Buffer Flush & open_memstream()
When fopen(path, "w+xe") executed, glibc allocated struct _IO_FILE on the heap and called openat(AT_FDCWD, path, O_RDWR|O_CREAT|O_TRUNC|O_EXCL|O_CLOEXEC, 0666). During the 2,048-byte benchmark, fputc() incremented _IO_write_ptr inside user RAM 2,048 times and issued a single write(fd, buf, 2048) syscall inside fclose(bfp), whereas raw write(bfd, "x", 1) crossed into Ring 0 2,048 separate times!
Guided Practice: Auditing fopen Mode Strings for strace Verification
Predict the exact openat() flag mask printed by strace -e trace=openat for each of the following three calls before testing them in a 15-line C snippet:
- Step 1 (Map base C11 characters): Translate
"r+","w", and"a+"into theirO_ACCMODE(O_RDWR,O_WRONLY,O_RDWR) plusO_CREAT/O_TRUNC/O_APPENDflags. - Step 2 (Layer
glibcsafety suffixes): Add"e"and"x"("r+e","wxe","a+be") and verify understracethat"b"changes zero kernel flags while"e"and"x"addO_CLOEXECandO_EXCL.
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 write_kv(FILE *out, const char *k, int v) and reader int read_kv(FILE *in, char *k_out, int *v_out). Test both functions purely in RAM—serializing into open_memstream(&buf, &len) and parsing back via fmemopen(buf, len, "r")—and verify under strace -e trace=openat that zero scratch files are opened after dynamic loader startup!
Common Production Pitfalls
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.
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.
Knowledge Check
? check 1 · Which openat() flag bitmask does glibc pass to the Linux kernel when you call fopen("/var/log/app.log", "a+e")?
- [ ]
O_WRONLY | O_CREAT | O_TRUNC | O_CLOEXEC - [x]
O_RDWR | O_CREAT | O_APPEND | O_CLOEXEC - [ ]
O_RDWR | O_EXCL | O_APPEND
Answer: O_RDWR | O_CREAT | O_APPEND | O_CLOEXEC
Why: 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.
? check 2 · Why does fopen("capture.bin", "rb") behave identically to fopen("capture.bin", "r") on Linux?
- [ ] Because
glibcdisables heap buffering whenever"b"appears inmode - [x] Because POSIX and the Linux kernel treat all files as exact byte streams without translating
"\r\n"newline sequences, making"b"a portability no-op - [ ] Because
"b"applies only toO_DIRECTblock devices
Answer: Because POSIX and the Linux kernel treat all files as exact byte streams without translating "\r\n" newline sequences, making "b" a portability no-op
Why: 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.
? check 3 · (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?
- [ ]
fcntl(fd, F_SETFL, O_EXCL)executed after opening - [x]
O_CREAT | O_EXCLevaluated atomically inside oneopenat()lookup under the parent directory inode lock - [ ]
FD_CLOEXECblocking concurrent processes from opening the inode
Answer: O_CREAT | O_EXCL evaluated atomically inside one openat() lookup under the parent directory inode lock
Why: "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.
? check 4 · 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?
- [ ]
fopen("/dev/null", "w+e") - [x]
open_memstream(&buf, &sz)(paired withfmemopen(buf, len, mode)for fixed buffers, wherefileno()returns-1witherrno == EBADF) - [ ]
fdopen(-1, "w+")
Answer: open_memstream(&buf, &sz) (paired with fmemopen(buf, len, mode) for fixed buffers, where fileno() returns -1 with errno == EBADF)
Why: 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.
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. - 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-counted fread()/fwrite(), 64-bit fseeko()/ftello(), sticky feof()/ferror() triage, and 257-state int fgetc().
Step sequence — frame strip: steps_m05_l01
Open streams with glibc 'e' (O_CLOEXEC) and 'x' (O_EXCL) suffixes inside a single atomic openat() syscall.
reveals: step1
highlights: step1
Accumulate small fputc() and fwrite() records inside the 8 KiB Ring 3 _IO_FILE heap buffer with zero traps.
reveals: step2
highlights: step2
Drain full buffers via amortized block write() syscalls, cutting mode-switch overhead by >1,000x.
reveals: step3
highlights: step3
Verify fclose(fp) == 0 on every writable stream so final flush ENOSPC or EIO faults are never lost.
reveals: step4
highlights: step4
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.
Why while (!feof(fp)) & char c = fgetc(fp) Break Binary Readers
Three <stdio.h> bugs survive code review with alarming frequency. First, a log reader written as while (!feof(fp)) { fread(&rec, sizeof(rec), 1, fp); process(&rec); } processes the final record twice on every clean file—and loops forever if a storage EIO fault occurs! Second, a developer writes char c; while ((c = fgetc(fp)) != EOF): on x86-64 (signed char), valid binary payload byte 0xFF sign-extends to -1 and aborts early as a false EOF; cross-compiled to ARMv7 (Cortex-A7, where ABI char is unsigned char [0..255]), EOF (-1) truncates to 255, so c != -1 is always true and hangs the device at 100% CPU! Third, calling fread() immediately after fwrite() on a "w+" stream without an intervening seek or flush reads stale buffer garbage.
Writing rock-solid binary stdio code requires mastering four exact contracts: item-counted fread/fwrite return division, 64-bit fseeko/ftello update-stream turnaround barriers, post-read feof/ferror triage, and the 257-state int domain of fgetc().
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.
definition (Item-Counted I/O, Sticky Stream Indicators & 257-State EOF): 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.
One Layer Down: Torn-Tail Division Math & the Pigeonhole Proof for int fgetc()
Inside glibc (iofread.c), fread(ptr, size, nmemb, fp) computes requested bytes R = size * nmemb (checking overflow), drains B <= R available bytes from _IO_read_ptr and underlying read(), and returns the integer quotient items_read = B / size. If a 54-byte crashed file holds three 16-byte structs (48 bytes) plus 6 torn tail bytes (B = 54), fread(out, 16, 4, fp) consumes all 54 bytes, sets _IO_EOF_SEEN on the failed attempt to reach 64 bytes, and returns 54 / 16 = 3! Passing size = 1, nmemb = 64 instead returns exact byte count 54, letting recovery code detect 54 % 16 = 6 torn bytes cleanly.
Similarly, the Pigeonhole Principle explains why char can never hold fgetc(fp): every 8-bit byte 0x00..0xFF (2^8 = 256 values) is legal inside a binary file, and EOF (-1) must be distinguishable from all 256 valid bytes (256 + 1 = 257 > 256). Narrowing 257 states into 8 bits either collides 0xFF with -1 (signed char) or loses -1 completely (unsigned char 255 != -1).
<stdio.h> Interface | Return Type & Range | Stream State & Portability Rule |
|---|---|---|
fread(p, sz, n, fp) / fwrite | size_t (0..n whole items) | Short count (< n) sets sticky feof(fp) or ferror(fp) |
fgetc(fp) / getchar() | int (0..255 or -1 EOF) | Never store in char; check ch != EOF as int first |
fseek(fp, long, w) / ftell | int / long | long overflows at 2 GiB - 1 (EOVERFLOW) on 32-bit ARMv7 |
fseeko(fp, off_t, w) / ftello | int (0 ok) / 64-bit off_t | Clears feof; required turnaround barrier on "r+"/"w+"/"a+" |
rewind(fp) / clearerr(fp) | void | rewind seeks to 0 and clears both feof and ferror bits |
Figure 5.2. Item-counted fread() torn-tail division, C11 '+' stream turnaround barriers, and 257-state int fgetc() safety.
- Step 1. Serialize fixed-width records verified with _Static_assert via fwrite() and track 64-bit offsets with ftello().
- Step 2. Insert an explicit fseeko() (or fflush() after output) before every read/write turnaround on a '+' stream.
- Step 3. Drive read loops with while (fread(&cur, sizeof(cur), 1, fp) == 1) rather than broken while (!feof(fp)).
- Step 4. Triage ferror(fp) vs feof(fp) after loop exit, and hold fgetc() in int ch so 0xFF never collides with EOF.
Figure 5.2b. Drive binary loops on fread()'s item count, synchronize '+' turnarounds with 64-bit fseeko(), and always store fgetc() in an int.
64-Bit Feature Macros & C11 Update-Stream ("+") Turnaround Rules
Place #define _POSIX_C_SOURCE 200809L and #define _FILE_OFFSET_BITS 64 at lines 1–2 before <stdio.h> and <stdint.h>. On any update stream ("r+", "w+", "a+"), ISO C11 §7.21.5.3 requires: (1) output (fwrite/fputs) must not be followed directly by input (fread/fgetc) without an intervening fflush() or file-positioning call (fseeko/rewind), and (2) input must not be followed directly by output without a positioning call unless input already hit EOF.
Testing Torn Tails, Turnaround Barriers, 257-State fgetc & feof Timing
Save binary_stream_eof.c below. On /tmp/ksa_m05_l02.bin ("w+be"), it writes 3 fixed 16-byte sample_rec structs (48 bytes) plus 6 torn bytes ending in 0xFF (total=54 via ftello()), executes the mandatory fseeko(fp, 0, SEEK_SET) turnaround before fread(out, 16, 4, fp) (items=3, eof=1, err=0), clears flags with clearerr(), reads all 6 torn bytes including 0xFF via int ch = fgetc(fp), proves both signed char and unsigned char narrowing bugs algebraically, and demonstrates feof(fp) == 0 right at byte 48 until a 4th read attempts to read past EOF!
learner@ksa:~/gl-c01/m05-l02$ bat -H 26 -H 39 -H 59 binary_stream_eof.c File: binary_stream_eof.c #define _POSIX_C_SOURCE 200809L #define _FILE_OFFSET_BITS 64 #include <stdint.h> #include <stdio.h> #include <unistd.h> struct sample_rec { uint32_t seq; int32_t mv; uint64_t ts_ns; }; _Static_assert(sizeof(struct sample_rec) == 16, "packed by natural alignment"); int main(void) { const char *path = "/tmp/ksa_m05_l02.bin"; FILE *fp = fopen(path, "w+be"); if (!fp) return 1; struct sample_rec src[3] = { {1U, 3300, 1000ULL}, {2U, 3295, 2000ULL}, {3U, 3310, 3000ULL} }; const unsigned char torn[6] = {0xAAU, 0xBBU, 0xCCU, 0xDDU, 0xEEU, 0xFFU}; if (fwrite(src, sizeof(src[0]), 3, fp) != 3) return 1; if (fwrite(torn, 1, sizeof(torn), fp) != sizeof(torn)) return 1; off_t total = ftello(fp); if (fseeko(fp, 0, SEEK_SET) != 0) return 1; struct sample_rec out[4]; size_t items = fread(out, sizeof(out[0]), 4, fp); int eof1 = feof(fp) ? 1 : 0; int err1 = ferror(fp) ? 1 : 0; printf("item_read: total=%lld items=%zu eof=%d err=%d last_mv=%d\n", (long long)total, items, eof1, err1, (int)out[2].mv); clearerr(fp); int cleared_ok = (!feof(fp) && !ferror(fp)) ? 1 : 0; if (fseeko(fp, 48, SEEK_SET) != 0) return 1; size_t tail_bytes = 0; unsigned int first_hex = 0U, saw_ff = 0U; int ch; while ((ch = fgetc(fp)) != EOF) { if (tail_bytes == 0) first_hex = (unsigned int)ch; if (ch == 0xFF) saw_ff = 1U; tail_bytes++; } signed char x86_bug = (signed char)0xFF; unsigned char arm_bug = (unsigned char)EOF; int fgetc_ok = ((int)x86_bug == EOF && (int)arm_bug == 255 && saw_ff == 1U); printf("byte_tail: cleared=%d bytes=%zu hex0=%02X fgetc_257=%d\n", cleared_ok, tail_bytes, first_hex, fgetc_ok); if (fclose(fp) != 0) return 1; fp = fopen(path, "w+be"); if (!fp || fwrite(src, sizeof(src[0]), 3, fp) != 3) return 1; rewind(fp); size_t clean_loops = 0; struct sample_rec cur; while (fread(&cur, sizeof(cur), 1, fp) == 1) { clean_loops++; } rewind(fp); size_t read3 = fread(out, sizeof(out[0]), 3, fp); int eof_exact = feof(fp) ? 1 : 0; size_t read4 = fread(&cur, sizeof(cur), 1, fp); int eof_past = feof(fp) ? 1 : 0; if (fclose(fp) != 0) return 1; (void)unlink(path); printf("eof_timing: loops=%zu r3=%zu exact=%d r4=%zu past=%d\n", clean_loops, read3, eof_exact, read4, eof_past); return 0; }- Insert fseeko(fp, 0, SEEK_SET) before switching from fwrite() to fread() on a w+be update stream.
- Store fgetc(fp) in int ch (never char) so byte 0xFF (255) stays distinct from negative EOF (-1) on both x86-64 and ARMv7.
- Drive loops with while (fread(&cur, sizeof(cur), 1, fp) == 1); feof(fp) stays 0 at exact EOF until a read crosses past byte 48.
Verifying Torn-Tail Counts, fgetc 257-State Safety & EOF Timing
Compile and run binary_stream_eof: observe items=3 (54 / 16), byte_tail recovering all 6 torn bytes including 0xFF (fgetc_257=1), and eof_timing proving exact=0 right at byte 48 before turning past=1 on the 4th read!
learner@ksa:~/gl-c01/m05-l02gcc -fdiagnostics-color=always -std=c11 -Wall -Wextra -Werror binary_stream_eof.c -o binary_stream_eoflearner@ksa:~/gl-c01/m05-l02./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-l02test ! -e /tmp/ksa_m05_l02.bin && rm -f binary_stream_eoflearner@ksa:~/gl-c01/m05-l02Why Byte-Exact Tail Recovery Needs size = 1 or ftello()
Notice what happened when fread(out, 16, 4, fp) hit the 54-byte torn file: it returned 3 items, yet the stream offset advanced to 54 (6 partial bytes consumed into out[3] without completing item 4)! Whenever your framing protocol must detect and reject a partial trailing struct (rather than treating 3 items + EOF as a clean 48-byte file), read with size = 1, nmemb = sizeof(rec) and check got == 0 (clean EOF) versus 0 < got < sizeof(rec) (corrupt torn tail!).
Guided Practice: Detecting a Torn Struct Tail with size = 1
Rewrite the while (fread(&cur, sizeof(cur), 1, fp) == 1) loop so it distinguishes clean EOF from a 6-byte torn trailing record without extra fstat() syscalls:
- Step 1 (Switch to byte-granularity
fread): Callsize_t nb = fread(&cur, 1U, sizeof(cur), fp);on each iteration; whennb == sizeof(cur), a complete struct arrived. - Step 2 (Triage
nb < sizeof(cur)): Checkif (ferror(fp))first (I/O error), else ifnb == 0(cleanEOFon a record boundary!), else (0 < nb < sizeof(cur): report a torn trailing record ofnbbytes!).
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 writes 5 struct sample_rec records (80 bytes), reopens the file with "r+be", scans forward via fread() until finding seq == 3U, executes the mandatory read-to-write fseeko(fp, -(off_t)sizeof(struct sample_rec), SEEK_CUR) turnaround barrier, overwrites record 3's mv field via fwrite(), executes a write-to-read turnaround, and verifies all 5 records in order!
Common Production Pitfalls
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.
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.
Knowledge Check
? check 1 · 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)?
- [ ] Returns
38;feof(fp)is0andferror(fp)is0 - [x] Returns
2(two complete 16-byte items);feof(fp)is nonzero andferror(fp)is0 - [ ] Returns
0and setsferror(fp)because38is not divisible by16
Answer: Returns 2 (two complete 16-byte items); feof(fp) is nonzero and ferror(fp) is 0
Why: 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.
? check 2 · Why should portable Linux C11 code prefer fseeko() and ftello() (under _FILE_OFFSET_BITS=64) over classic ISO C fseek() and ftell()?
- [ ] Because
fseek()fails to clearfeof(fp) - [x] Because
fseek()andftell()uselong(32-bit signed,2 GiB - 1max onILP32targets such as 32-bitARMv7), whereasfseeko()/ftello()use 64-bitoff_t - [ ] Because
fseeko()flushes dirty kernel pages viafsync()automatically
Answer: Because fseek() and ftell() use long (32-bit signed, 2 GiB - 1 max on ILP32 targets such as 32-bit ARMv7), whereas fseeko()/ftello() use 64-bit off_t
Why: 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.
? check 3 · (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?
- [ ] Because
ftruncate()fails withEBADFunlessf_posequals0 - [x] Because
ftruncate()updatesinode->i_sizewithout changingstruct file.f_pos, whilerewind(fp)resets both theFILEbuffer cursors and kernelf_posto0and clears sticky flags - [ ] Because
fileno(fp)allocates a secondstruct filedescription
Answer: Because ftruncate() updates inode->i_size without changing struct file.f_pos, while rewind(fp) resets both the FILE buffer cursors and kernel f_pos to 0 and clears sticky flags
Why: 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.
? check 4 · 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?
- [ ] Both architectures read
0xFFaccurately and stop cleanly atEOF - [x] On x86-64 (signed
char), byte0xFFsign-extends to-1and aborts early as a falseEOF; onARMv7EABI (unsigned char[0..255]),EOF(-1) truncates to255so(c != EOF)spins forever at100%CPU—storefgetc()inint ch - [ ] On
ARMv7,fgetc()raisesSIGBUSwhenever0xFFappears in a stream
Answer: On x86-64 (signed char), byte 0xFF sign-extends to -1 and aborts early as a false EOF; on ARMv7 EABI (unsigned char [0..255]), EOF (-1) truncates to 255 so (c != EOF) spins forever at 100% CPU—store fgetc() in int ch
Why: 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.
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(). - 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-isolated fgets() + strtol() line parsers.
Step sequence — frame strip: steps_m05_l02
Serialize fixed-width records verified with _Static_assert via fwrite() and track 64-bit offsets with ftello().
reveals: step1
highlights: step1
Insert an explicit fseeko() (or fflush() after output) before every read/write turnaround on a '+' stream.
reveals: step2
highlights: step2
Drive read loops with while (fread(&cur, sizeof(cur), 1, fp) == 1) rather than broken while (!feof(fp)).
reveals: step3
highlights: step3
Triage ferror(fp) vs feof(fp) after loop exit, and hold fgetc() in int ch so 0xFF never collides with EOF.
reveals: step4
highlights: step4
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().
Why Unchecked snprintf Accumulators & Raw fscanf Cause Exploits
Most C engineers know sprintf() is banned—yet a subtle snprintf() anti-pattern causes buffer overflows in production codebases every year! A developer writes a multi-field log builder size_t pos = 0; pos += snprintf(buf + pos, sizeof(buf) - pos, ...); repeated three times without checking each return value: when Call 1 needs 80 bytes in a 64-byte buf, snprintf() safely caps its write at 63 chars + '\0', but returns 80! Now pos equals 80, sizeof(buf) - pos (64U - 80U) wraps unsigned size_t to 18,446,744,073,709,551,600, and Call 2 blasts uninhibited across the stack! On the input side, fscanf(fp, "%s=%d", key, &val) overflows key on long tokens and leaves non-numeric garbage wedged in fp forever!
Bulletproof text formatting and parsing in C11 rest on three rules: checking snprintf()'s hypothetical-length return contract on every call, matching <inttypes.h>/%zu specifiers across 32/64-bit ABIs, and decoupling line framing (fgets) from in-memory token validation (sscanf width-capped scansets + strtol ERANGE).
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.
definition (Bounded snprintf(), <inttypes.h> Macros & Scanset Framing): 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.
One Layer Down: Safe Buffer-Append Algebra & Off-by-One Scanset Widths
To append multiple formatted segments into char buf[CAP] at cursor size_t pos (0 <= pos < CAP), let remaining capacity be R = CAP - pos. After int n = snprintf(buf + pos, R, fmt, ...), full non-truncated fit holds if and only if n >= 0 && (size_t)n < R. Only when both inequalities hold may pos advance to pos + (size_t)n (preserving pos <= CAP - 1). Conversely, if you want dynamic exact-fit allocation, probe with int need = snprintf(NULL, 0U, fmt, ...);, check need >= 0, allocate (size_t)need + 1U bytes via malloc(), and format once with zero wasted memory!
On input, notice the critical 1-byte asymmetry between fgets() and sscanf() width specifiers for char tag[16]: fgets(tag, 16, fp) includes the '\0' inside 16 (reading at most 15 payload bytes), whereas sscanf(line, "%15[^=]", tag) specifies maximum payload characters excluding '\0' (15 chars + 1 '\0' = 16 bytes; writing %16[^=] overflows tag[16] by 1 byte!).
| Formatter / Parser Tool | Exact C11 / POSIX Idiom | Safety & ABI Guarantee | ||
|---|---|---|---|---|
snprintf(buf, sz, ...) | Reject if `ret < 0 \ | \ | (size_t)ret >= sz` | Never writes past sz; detects every 1-byte truncation |
dprintf(fd, fmt, ...) | Direct POSIX descriptor formatting | Emits formatted text straight to fd without a FILE * | ||
%zu / %zd & PRIu64 | "sz=%zu ts=%" PRIu64 (<inttypes.h>) | Zero -Wformat warnings on both 32-bit ARMv7 and 64-bit x86-64 | ||
fgets(line, sizeof(line), fp) | Drain to '\n' if line[len-1] != '\n' | Isolates corrupt/oversized lines so next line starts cleanly | ||
%15[^=]=%31[^\n] + strtol | Width = sizeof(dst) - 1; check ERANGE & *endp == '\0' | Prevents buffer overflow and rejects "12abc" or LONG_MAX overflow |
Figure 5.3. Truncation-checked snprintf() accumulator math, <inttypes.h> specifiers, and fault-isolated fgets() + strtol() parsing.
- Step 1. Frame bounded lines with fgets(line, sizeof(line), fp) and check ferror(fp) vs feof(fp) on NULL exit.
- Step 2. When line[len - 1] != '\\n' before EOF, drain excess bytes up to '\\n' via int fgetc(fp) to quarantine oversized lines.
- Step 3. Split key=value fields with width sizeof(dst) - 1 (%15[^=] for char[16]) so '\\0' never overflows.
- Step 4. Validate numeric ranges via strtol() (ERANGE and *endp == '\\0') and guard snprintf() with (size_t)ret < rem.
Figure 5.3b. Check (size_t)ret < rem before advancing snprintf() cursors, and isolate line framing with fgets() before tokenizing via (sizeof - 1) scansets and strtol().
<inttypes.h> Specifiers, dprintf(3) & strtol(3) Validation
Include <stdio.h>, <stdlib.h>, <inttypes.h>, <stdint.h>, <limits.h>, and <errno.h> under #define _POSIX_C_SOURCE 200809L. Remember why atoi() is unusable in systems code: atoi("garbage") returns 0 (indistinguishable from "0"!) and invokes Undefined Behavior on integer overflow, whereas errno = 0; long v = strtol(s, &endp, 10); flags empty strings (endp == s), trailing junk (*endp != '\0'), and range saturation (errno == ERANGE).
Building a Truncation-Checked Formatter & Fault-Isolated Line Parser
Save fmt_safe_codec.c below. It emits valid, malformed, oversized, and overflowing sensor lines via dprintf(fd, ...), verifies snprintf() truncation detection (req=28 >= cap=16, trunc=1) plus safe multi-step buf_appendf(), and runs a line-isolated fgets() + %15[^=]=%31[^\n] + strtol() parser that drains an oversized line and rejects malformed/ERANGE inputs without losing the valid records that follow!
learner@ksa:~/gl-c01/m05-l03$ bat -H 16 -H 36 -H 48 -H 59 fmt_safe_codec.c File: fmt_safe_codec.c #define _POSIX_C_SOURCE 200809L #include <errno.h> #include <fcntl.h> #include <inttypes.h> #include <limits.h> #include <stdarg.h> #include <stdint.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <unistd.h> static int buf_appendf(char *buf, size_t cap, size_t *pos, const char *fmt, ...) { if (*pos >= cap) return -1; size_t rem = cap - *pos; va_list ap; va_start(ap, fmt); int ret = vsnprintf(buf + *pos, rem, fmt, ap); va_end(ap); if (ret < 0 || (size_t)ret >= rem) return -1; *pos += (size_t)ret; return 0; } int main(void) { const char *path = "/tmp/ksa_m05_l03.txt"; int fd = open(path, O_RDWR | O_CREAT | O_TRUNC | O_CLOEXEC, 0644); if (fd < 0) return 1; uint64_t ts = 9000000001ULL; size_t idx = 4U; if (dprintf(fd, "rail_a=%+06d\nbad_line_no_eq\n" "oversized_sensor_tag_abcdefghijklmnopqrstuvwxyz0123456789=10\n" "rail_b=999999999999999999999\nvcore_mv=-125\n", 3300) < 0) return 1; (void)close(fd); char small[16]; volatile size_t cap = sizeof(small); int req = snprintf(small, cap, "ts=%" PRIu64 " idx=%zu hex=%#x", ts, idx, 255U); int trunc_detected = (req < 0 || (size_t)req >= cap) ? 1 : 0; char accum[20]; size_t apos = 0U; int app_ok = (buf_appendf(accum, sizeof(accum), &apos, "id=%u ", 7U) == 0 && buf_appendf(accum, sizeof(accum), &apos, "overflow_tail_999999") == -1); printf("snprintf_check: req=%d cap=%zu trunc=%d app_guard=%d prefix=%s\n", req, (size_t)cap, trunc_detected, app_ok, small); FILE *fp = fopen(path, "re"); if (!fp) return 1; char line[48]; unsigned int ok = 0U, bad = 0U; long sum_mv = 0L; while (fgets(line, sizeof(line), fp) != NULL) { size_t len = strlen(line); if (len > 0U && line[len - 1U] != '\n' && !feof(fp)) { int ch; while ((ch = fgetc(fp)) != '\n' && ch != EOF) {} bad++; continue; } char tag[16], num_s[32]; if (sscanf(line, "%15[^=]=%31[^\n]", tag, num_s) != 2) { bad++; continue; } char *endp = NULL; errno = 0; long val = strtol(num_s, &endp, 10); if (errno == ERANGE || endp == num_s || *endp != '\0' || val < INT_MIN || val > INT_MAX) { bad++; continue; } ok++; sum_mv += val; } int clean_end = (!ferror(fp) && feof(fp)) ? 1 : 0; if (fclose(fp) != 0 || !clean_end) return 1; (void)unlink(path); printf("parser_check: ok=%u bad=%u sum_mv=%ld\n", ok, bad, sum_mv); return 0; }- Guard ret < 0 || (size_t)ret >= rem BEFORE advancing *pos so a truncated snprintf() never wraps cap - *pos.
- Drain remaining characters up to '\n' when an oversized line lacks a newline so its tail cannot masquerade as the next record.
- Use width sizeof(buf) - 1 (%15[^=] for char[16]) and verify errno != ERANGE && endp != num_s && *endp == '\0'.
Verifying Truncation Math, Oversized-Line Draining & Lab 5
Compile and execute fmt_safe_codec: confirm req=28 vs cap=16 (trunc=1, app_guard=1), confirm parser_check isolates all 3 bad lines (no_eq, oversized, and ERANGE overflow -> bad=3) while recovering rail_a=+03300 and vcore_mv=-125 (ok=2, sum_mv=3175), and complete lab_m05_telemetry_codec.
learner@ksa:~/gl-c01/m05-l03gcc -fdiagnostics-color=always -std=c11 -Wall -Wextra -Werror fmt_safe_codec.c -o fmt_safe_codeclearner@ksa:~/gl-c01/m05-l03./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-l03test ! -e /tmp/ksa_m05_l03.txt && rm -f fmt_safe_codeclearner@ksa:~/gl-c01/m05-l031. Motivation
Telemetry ingestion pipelines sit directly on the untrusted boundary between noisy serial/CSV text feeds and compact binary storage files. Naive fscanf(in, "%s,%u,%d") parsers suffer buffer overflows on long sensor IDs and wedge permanently when a single corrupted UART line arrives, while while (!feof(fp)) readers duplicate the final binary sample and unchecked snprintf() calls silently truncate diagnostic summaries. In this lab, you will build telemetry_codec to master line-isolated fgets() + strtoul()/strtol() ingestion, batched item-counted fwrite()/fread(), torn-tail detection via ftello(), and deterministic snprintf() truncation checks.
2. Learning Objectives
- Ingest untrusted CSV sensor streams via bounded
fgets()(draining> 127-byte oversized lines up to'\n') and validate<id>,<seq>,<mv>fields withstrtoul()/strtol()(ERANGEand character-set guards). - Serialize
24-bytestruct sensor_framebatches (16records perfwrite()call) onto"wbe"streams with checkedferror()andfclose(). - Inspect binary streams via
while (fread(&frame, sizeof(frame), 1, fp) == 1)(neverwhile (!feof(fp))), detecting partial trailing bytes (exit 2) viaftello()/fseeko(). - Enforce
snprintf(buf, cap, ...)bounds by detectingneeded < 0 || (size_t)needed >= cap(exit 3).
3. Environment Requirements
- Host Execution Environment (Tested): Linux
6.12LTS (x86_64,glibc2.39+),#define _POSIX_C_SOURCE 200809Land#define _FILE_OFFSET_BITS 64. - Target Board Portability (
ARMv7Cortex-A7):struct sensor_frame(char id[16]; uint32_t seq; int32_t mv;) has natural4-byte alignment and0padding bytes (sizeof == 24) across both 32-bitARMv7and 64-bitx86_64little-endian targets, andint ch = fgetc(in)avoids the unsigned-charARMv7infinite loop during line draining!
4. Required Software & Hardware
- Software Toolchain:
gcc(-std=c11 -Wall -Wextra -Werror),strace,truncate, and/bin/sh. - Hardware: Standard Linux host environment.
5. Complete Executable Commands
Run from labs/lab_m05_telemetry_codec/:
learner@ksa:~/gl-c01/m05-l03$ bat script.sh File: script.sh # 1. Compile the warning-clean sensor parser and binary codec gcc -std=c11 -O2 -Wall -Wextra -Werror files/telemetry_codec.c -o /tmp/telemetry_codec # 2. Create a mixed CSV feed (valid rows, comments, ERANGE overflow, and >128B oversized line) python3 -c ' print("# boot log\nvcore,1,1150\nmalformed_row\n" + "x"*150 + ",2,100\npll_mv,2,1800\nbad_ovf,999999999999,10\nvcore,3,1120") ' > /tmp/ksa_sensors.csv # 3. Encode valid rows to binary (3 valid * 24B = 72B, 3 rejected) and inspect with sufficient cap /tmp/telemetry_codec encode /tmp/ksa_sensors.csv /tmp/ksa_sensors.bin /tmp/telemetry_codec inspect /tmp/ksa_sensors.bin 64 # 4. Test deterministic snprintf() truncation (cap=16 -> exit 3) and torn-tail detection (exit 2) /tmp/telemetry_codec inspect /tmp/ksa_sensors.bin 16; echo "trunc_rc=$?" printf 'TORN!' >> /tmp/ksa_sensors.bin /tmp/telemetry_codec inspect /tmp/ksa_sensors.bin 64; echo "torn_rc=$?" # 5. Clean up and run the full TAP 13 verification harness rm -f /tmp/telemetry_codec /tmp/ksa_sensors.csv /tmp/ksa_sensors.bin sh check.sh*Why each command runs:* Step 2 injects every real-world CSV fault (# comments, missing commas, 150-char line overflow, UINT32_MAX overflow); Step 3 proves the parser isolates all 3 bad lines and recovers vcore,3,1120; Step 4 verifies exit 3 on cap=16 truncation and exit 2 (PARTIAL_TAIL bytes=5) on a torn binary tail; and Step 5 runs sh check.sh.
6. Annotated Source Code (starter/ Flaws vs files/ Reference)
Flawed Baseline (starter/telemetry_codec.c)
- Wedging
fscanf()(encode):while (fscanf(in, "%15[^,],%u,%d\n", ...) == 3)halts at the very first malformed or#comment line (valid=0or partial output) and silently wraps overflowing integers! - Off-by-one
while (!feof(fp))(inspect): Runs an extra loop iteration atEOF, countingVALID=4on a3-record file! - Missing torn-tail &
snprintf()checks: Ignores partial trailing bytes (PARTIAL_TAIL) and prints silently truncated strings with exit0.
Warning-Clean Reference (files/telemetry_codec.c)
- Oversized-Line Drain (
cmd_encode): Checksif (len > 0 && line[len - 1] != '\n' && !feof(in))and drains viaint ch; while ((ch = fgetc(in)) != '\n' && ch != EOF) {}before incrementingrejected, keeping the next line cleanly aligned! - Strict Token Validation (
parse_csv_line): Rejects leading'-'beforestrtoul()(becausestrtoul("-1", ...)legally wraps moduloULONG_MAX!), checkserrno == 0 && *end_seq == ',' && seq_ul <= UINT32_MAX, and checksmv_lin[-100000, 100000]. - Torn-Tail & Truncation Guards (
cmd_inspect): Snapshotspos_before = ftello(fp)prior to eachfread(&frame, 24, 1, fp), comparesSEEK_ENDend_pos > pos_before(exit 2), and checksneeded < 0 || (size_t)needed >= cap(exit 3).
7. Expected Output
learner@ksa:~/gl-c01/m05-l03$ bat listing.txt File: listing.txt $ sh check.sh TAP version 13 1..5 ok 1 - builds cleanly with -std=c11 -Wall -Wextra -Werror ok 2 - encodes valid CSV rows into 24-byte frames while isolating malformed and >128B lines ok 3 - reads exact record count without while(!feof) off-by-one duplication ok 4 - detects torn trailing binary bytes via ftello/fseeko (exit 2) ok 5 - detects snprintf summary buffer truncation deterministically (exit 3) # pass 5/58. Explanation of Observed Behavior
Batching 16 struct sensor_frame items (16 * 24 = 384 bytes) into fwrite() copies records inside glibc's Ring 3 _IO_FILE buffer, emitting just 1 write() syscall when fclose(out) flushes a 72-byte or 6,144-byte batch. On inspection of the 77-byte torn file (72 + 5), Iteration 4 records pos_before = 72, fread(&frame, 24, 1, fp) consumes the 5 torn bytes, hits EOF, sets _IO_EOF_SEEN, and returns 0 complete items; fseeko(fp, 0, SEEK_END) + ftello(fp) then measures end_pos = 77 > 72, reporting PARTIAL_TAIL bytes=5 (exit 2)!
9. Experiment Variations
strtoul("-5")Sign-Wrap Experiment: Comment outif (!isdigit((unsigned char)*s_seq)) return -1;in a scratch copy and passvcore,-1,3300on 64-bit Linux to observestrtoul()parse-1as18446744073709551615UL(> UINT32_MAX), and passvcore,-1,3300on 32-bitILP32whereULONG_MAX == UINT32_MAX(4294967295accepted silently without theisdigitguard!).straceBatching Verification: Encode1,000CSV rows (24,000bytes) understrace -e trace=read,writeand confirmglibc's8 KiB_IOFBFbuffer reduces1,000logical records to3write()syscalls!- In-Memory Fuzzing via
fmemopen: Refactorcmd_encodeintoencode_streams(FILE *in, FILE *out)and fuzzparse_csv_linein memory usingfmemopen()+open_memstream()under-fsanitize=address,undefined.
10. Performance Measurements
Measured on Host x86_64 Linux 6.12 LTS (CLOCK_MONOTONIC, 5 warmup runs, N = 35 end-to-end encode + inspect cycles over 256 CSV rows = 6,144 binary bytes):
| Metric | Measured Host (x86_64 Linux 6.12) | Target Board Expectation (ARMv7 Cortex-A7) |
|---|---|---|
256-row encode + inspect (p50 / p95 / p99) | 3,829.6 us / 4,709.7 us / 5,941.2 us | ~14,000–21,000 us (2 CLI spawns; < 180 us in-process codec) |
Kernel write() syscalls for 256 rows (6,144 B) | 1 (< 8 KiB _IOFBF buffer flushed at fclose) | 1 (_IOFBF 4 KiB or 8 KiB -> 1–2 write traps) |
11. Troubleshooting
| Symptom | Root Cause | Fix |
|---|---|---|
VALID is N + 1 on every clean binary file | Used while (!feof(fp)) instead of checking fread() == 1 | Loop on while (fread(&frame, sizeof(frame), 1, fp) == 1) |
Infinite loop on ARMv7 when draining > 128B CSV line | Stored fgetc(in) in char ch (unsigned char 255 != -1 EOF) | Declare int ch; for fgetc(in) |
Negative sequence -1 accepted on 32-bit targets | strtoul() allows leading '-' and negates modulo ULONG_MAX | Check isdigit((unsigned char)*s_seq) before strtoul() |
-Wsign-compare or -Wformat error on size_t | Printed size_t with %lu instead of %zu | Use %zu for size_t across 32/64-bit builds |
12. Guided Questions
- Why must
valid_id_char((unsigned char)line[i])castchartounsigned charbefore calling<ctype.h>isalnum()?
- *Hint 1:* Check
man 3 isalnumfor the exact input domain required by ISO C11<ctype.h>functions (unsigned charwidened toint, orEOF). - *Hint 2:* On x86-64 (signed
char), what negativeintvalue is passed toisalnum()if an untrusted UTF-8 byte0xC3arrives without the(unsigned char)cast (Undefined Behaviornegative table index!)?
- Why does
cmd_inspect()checkif (ferror(fp))before comparingend_pos > pos_before?
- *Hint 1:* What does
fread()return when an underlyingEIOread fault occurs mid-file (0, just likeEOF!)? - *Hint 2:* If
EIOstoppedfread()at byte24of a72-byte file, what wouldend_pos > pos_beforemisclassify the hardware I/O error as ifferror(fp)were not checked first?
13. Independent Challenges
- Near Transfer — Endian-Neutral Wire Codec (
htole32/ Manual Shifts): Replace directfwrite(&frame, 24, 1, out)struct dumps with explicit little-endian byte packing/unpacking (uint8_t wire[24]) so binary logs remain portable even across big-endian network processors. - Far Transfer — Streaming Ring-Buffer Compactor: Extend
telemetry_codecwith atail <in_bin> <last_k>subcommand that usesfseeko(fp, 0, SEEK_END)+ftello()to validate exact24-byte alignment (end_pos % 24 == 0) and seeks directly toend_pos - last_k * 24in $O(1)$ time without reading earlier megabytes!
14. Solutions & Explanations
- Guided Question 1: Passing a negative
signed char(other thanEOF-1, and0xFFcollides withEOF!) toisalnum()orisdigit()invokes ISO C11 Undefined Behavior (indexing backward beforeglibc's__ctype_b_loclookup table); always cast(unsigned char)c! - Guided Question 2: Both
EOFandEIOcausefread(..., 1, fp)to return0; checkingferror(fp)first reports an I/O error (exit 1) instead of falsely blaming the file for aPARTIAL_TAIL(exit 2).
Run locally in your terminal and check off each verification milestone.
Not started
Why Line Isolation Outperforms Stream fscanf()
Look at how fgets() + strtol() isolated every failure mode in fmt_safe_codec: when the 52-byte oversized_sensor_tag... line exceeded char line[48], line[len - 1] != '\n' detected the split line immediately, while ((ch = fgetc(fp)) != '\n' && ch != EOF) drained its tail cleanly, and subsequent lines parsed normally without stream corruption!
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-sized heap string with zero truncation risk:
- Step 1 (Dry-run length query): Call
int need = snprintf(NULL, 0U, "%s:%" PRIu64 ":%zd", tag, seq, delta);and returnNULLifneed < 0. - Step 2 (Allocate
need + 1and format): Allocatesize_t cap = (size_t)need + 1U; char *out = malloc(cap);, checkout != NULL, runsnprintf(out, cap, ...), and verifystrlen(out) == (size_t)need.
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" lines via fgets(), strips # comments and whitespace, parses unsigned 32-bit integers supporting 0x hex, 0 octal, and base-10 via strtoul(val_s, &endp, 0) (rejecting leading '-' negative signs, which strtoul() surprisingly accepts modulo ULONG_MAX unless you check for '-' first!), and verifies val <= UINT32_MAX.
Common Production Pitfalls
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.
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]).
Knowledge Check
? check 1 · 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?
- [ ]
ris9, andr == sizeof(buf) - 1proves truncation - [x]
ris11(the length of"sensor_0042"excluding'\0'), and(size_t)r >= sizeof(buf)proves truncation - [ ]
ris-1whenever output exceedssizeof(buf)
Answer: r is 11 (the length of "sensor_0042" excluding '\0'), and (size_t)r >= sizeof(buf) proves truncation
Why: "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.
? check 2 · 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?
- [ ]
"%lu %llu" - [x]
"%zu %" PRIu64 - [ ]
"%d %ld"
Answer: "%zu %" PRIu64
Why: %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!
? check 3 · (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?
- [ ] Check whether
errno == 0without inspectingfp - [x] Inspect
ferror(fp)versusfeof(fp)immediately afterfgets()returnsNULL - [ ] Call
ftello(fp)to test whether the offset equals0
Answer: Inspect ferror(fp) versus feof(fp) immediately after fgets() returns NULL
Why: 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.
? check 4 · Why does production C11 text parsing prefer fgets() + strtol(num_s, &endp, 10) over fscanf(fp, "%d", &val) or atoi(num_s)?
- [ ] Because
strtol()executes insideRing 0kernel mode - [x] Because
fgets()isolates malformed lines so bad tokens never wedge the stream, andstrtol()detects empty tokens (endp == num_s), trailing garbage (*endp != '\0'), and overflow (errno == ERANGE) withoutatoi()'s Undefined Behavior - [ ] Because
fscanf()cannot parse negative integers
Answer: Because fgets() isolates malformed lines so bad tokens never wedge the stream, and strtol() detects empty tokens (endp == num_s), trailing garbage (*endp != '\0'), and overflow (errno == ERANGE) without atoi()'s Undefined Behavior
Why: 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.
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.
With both kernel descriptors and Ring 3 stdio streams in your toolkit, Module 6 unites both layers to master kernel page-cache durability (fsync, fdatasync, O_DIRECT), two-stage fflush + fdatasync commits, and our capstone crash-safe CRC32 Write-Ahead Log!
Step sequence — frame strip: steps_m05_l03
Frame bounded lines with fgets(line, sizeof(line), fp) and check ferror(fp) vs feof(fp) on NULL exit.
reveals: step1
highlights: step1
When line[len - 1] != '\\n' before EOF, drain excess bytes up to '\\n' via int fgetc(fp) to quarantine oversized lines.
reveals: step2
highlights: step2
Split key=value fields with width sizeof(dst) - 1 (%15[^=] for char[16]) so '\\0' never overflows.
reveals: step3
highlights: step3
Validate numeric ranges via strtol() (ERANGE and *endp == '\\0') and guard snprintf() with (size_t)ret < rem.
reveals: step4
highlights: step4
m06/
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.
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.
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. First, a financial ledger service calls write(fd, &tx, 64) (== 64) and close(fd) (== 0), sends "200 OK" over the network, and loses power 3 seconds later—upon reboot, the committed transaction is completely gone! Why? Because write() only dirtied a 4 KiB folio inside volatile kernel Dynamic RAM (DRAM), scheduled for background writeback up to 30 seconds later (vm.dirty_expire_centisecs = 3000). Second, an updater carefully calls write(tfd, ...) -> fsync(tfd) -> close(tfd) -> rename("cfg.tmp", "cfg.json"), cuts power immediately, and boots up to find neither "cfg.json"'s new dentry nor "cfg.tmp" visible because the parent directory's modified dentry sat unsynced in RAM!
Engineering crash-consistent storage on Linux requires distinguishing process death (SIGKILL, where kernel RAM survives) from power loss / kernel panic (where DRAM vanishes), selecting the exact persistence barrier (fdatasync vs fsync + fsync(dir_fd)), and understanding how mmap() and O_DIRECT interact with the VFS page cache.
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.
definition ( Writeback, fdatasync(), Dir Sync & O_DIRECT): 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.
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_EMPTY_PATH, STATX_DIOALIGN, &sx) yielding A_mem = stx_dio_mem_align and A_off = stx_dio_offset_align, typically 512 or 4,096 bytes), the block layer programs NVMe/eMMC scatter-gather DMA descriptors directly against user physical pages if and only if all three modulo checks equal zero: ((uintptr_t)buf % A_mem == 0) && (count % A_off == 0) && (offset % A_off == 0). Violating any one of the three returns -1 with errno == EINVAL immediately! Meanwhile, demand-paged mmap() maps the same VFS page-cache folios into user page tables lazily on first touch: hitting an already-cached folio increments minor page faults (ru_minflt) with zero disk I/O, fetching an uncached page from media increments major page faults (ru_majflt), MAP_SHARED stores dirty the shared VFS folio directly, and MAP_PRIVATE stores clone a private Copy-on-Write (CoW) RAM page invisible to pread(fd, ...).
| Persistence / I/O Path | Data Destination | Metadata & Barrier Cost | Crash & Cache Semantics |
|---|---|---|---|
Buffered write() (default) | Kernel RAM page cache | 0 media waits (~1..3 us) | Survives SIGKILL; lost on power cut |
fdatasync(fd) / O_DSYNC | Non-volatile media + drive flush | 1 flush if pre-sized (i_size fixed) | Ideal for preallocated WAL commit frames |
fsync(fd) / O_SYNC | Non-volatile media + drive flush | Data + journaled mtime/inode flush | Required when metadata timestamps matter |
fsync(dir_fd) (O_DIRECTORY) | Parent directory blocks & journal | 1 directory commit barrier | Mandatory after O_CREAT, link, rename |
O_DIRECT (posix_memalign) | Direct user-RAM <-> controller DMA | Bypasses page cache (EINVAL unaligned) | Zero cache double-buffering (SQLite/DBs) |
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.
- Step 1. Query STATX_DIOALIGN for posix_memalign() O_DIRECT buffers, or pre-size WAL segments so i_size stays fixed.
- Step 2. Dirty shared VFS folios via pwrite() / MAP_SHARED (whereas MAP_PRIVATE clones private Copy-on-Write RAM).
- Step 3. Call fdatasync(fd) to flush dirty data blocks and controller write caches onto non-volatile media.
- Step 4. Open the parent directory with O_RDONLY | O_DIRECTORY | O_CLOEXEC and call fsync(dir_fd) after creation or rename.
Figure 6.1b. Buffered writes only reach volatile DRAM; power-cut durability requires fdatasync()/fsync() plus fsync(dir_fd) on directory updates.
Sync Prototypes, posix_memalign(3) & mmap(2) Reference
Define #define _GNU_SOURCE and #define _FILE_OFFSET_BITS 64 before <fcntl.h>, <sys/mman.h>, <sys/stat.h>, <stdlib.h>, and <unistd.h>. Watch posix_memalign(&ptr, align, size)'s return convention: unlike -1 syscalls, posix_memalign() returns 0 on success or a positive error code (EINVAL, ENOMEM) directly without setting errno!
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. munmap(), msync(), fsync(), and fdatasync() return 0 or -1. ERRORS EACCES fd is not open for the requested prot/flags combination. EINVAL Unaligned addr/offset, length == 0, or missing MAP_SHARED/PRIVATE. EIO Storage writeback failed during fsync() or fdatasync(). FLAGS MAP_SHARED Share dirty page-cache folios and write back to fd. MAP_PRIVATE Copy-on-write mapping; stores stay private to process. SEE ALSO fsync(2), open(2), posix_fadvise(2), posix_memalign(3), statx(2) Kernel Systems Academy Lesson 6.1 mmap(2) GL-C01 quick reference · full manual page: man 2 mmap Probing Sync Barriers, mmap CoW vs Shared & STATX_DIOALIGN O_DIRECT
Save pagecache_odirect.c below. It preallocates /tmp/ksa_m06_l01.wal, commits 64 bytes via fdatasync() + fsync(), maps the 4 KiB folio under both MAP_PRIVATE (writing 'P' to private CoW byte 0) and MAP_SHARED (writing 'S' through to VFS page-cache byte 1), checks getrusage(RUSAGE_SELF) minor faults, hints eviction via posix_fadvise(..., POSIX_FADV_DONTNEED), syncs /tmp via fsync(dir_fd), and tests STATX_DIOALIGN + posix_memalign() O_DIRECT aligned I/O vs EINVAL unaligned rejection (with a clean fallback when /tmp is tmpfs, which rejects open(..., O_DIRECT) with EINVAL because tmpfs is the page cache!).
learner@ksa:~/gl-c01/m06-l01$ bat -H 30 -H 43 -H 66 pagecache_odirect.c File: pagecache_odirect.c #define _GNU_SOURCE #define _FILE_OFFSET_BITS 64 #include <errno.h> #include <fcntl.h> #include <stdint.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <sys/mman.h> #include <sys/resource.h> #include <sys/stat.h> #include <unistd.h> int main(void) { const char *wal_path = "/tmp/ksa_m06_l01.wal"; const char *dio_path = "/tmp/ksa_m06_l01_dio.bin"; int base_fl = O_RDWR | O_CREAT | O_TRUNC | O_CLOEXEC; int fd = open(wal_path, base_fl, 0644); if (fd < 0 || ftruncate(fd, 4096) != 0) return 1; char rec[64]; memset(rec, 'C', sizeof(rec)); if (pwrite(fd, rec, sizeof(rec), 0) != (ssize_t)sizeof(rec)) return 1; int fds_ok = (fdatasync(fd) == 0) ? 1 : 0; int fs_ok = (fsync(fd) == 0) ? 1 : 0; struct rusage ru0, ru1; getrusage(RUSAGE_SELF, &ru0); int prot = PROT_READ | PROT_WRITE; uint8_t *sh = mmap(NULL, 4096U, prot, MAP_SHARED, fd, 0); uint8_t *pr = mmap(NULL, 4096U, prot, MAP_PRIVATE, fd, 0); if (sh == MAP_FAILED || pr == MAP_FAILED) return 1; pr[0] = 'P'; sh[1] = 'S'; getrusage(RUSAGE_SELF, &ru1); char chk[2] = {0}; int mmap_ok = (pread(fd, chk, 2U, 0) == 2 && chk[0] == 'C' && chk[1] == 'S' && ru1.ru_minflt >= ru0.ru_minflt); (void)munmap(pr, 4096U); (void)munmap(sh, 4096U); (void)posix_fadvise(fd, 0, 0, POSIX_FADV_DONTNEED); (void)close(fd); int dir_fd = open("/tmp", O_RDONLY | O_DIRECTORY | O_CLOEXEC); if (dir_fd < 0) return 1; int dir_sync_ok = (fsync(dir_fd) == 0) ? 1 : 0; (void)close(dir_fd); (void)unlink(wal_path); printf("durability: fdatasync=%d fsync=%d dir_fsync=%d mmap_cow=%d\n", fds_ok, fs_ok, dir_sync_ok, mmap_ok); size_t align = 4096U; struct statx sx; int pfd = open(dio_path, base_fl, 0644); if (pfd < 0) return 1; if (statx(pfd, "", AT_EMPTY_PATH, STATX_DIOALIGN, &sx) == 0 && (sx.stx_mask & STATX_DIOALIGN) && sx.stx_dio_mem_align > align) { align = sx.stx_dio_mem_align; } (void)close(pfd); void *raw = NULL; if (posix_memalign(&raw, align, align * 2U) != 0) return 1; uint8_t *abuf = (uint8_t *)raw; memset(abuf, 0x5AU, align * 2U); int addr_aligned = (((uintptr_t)abuf % align) == 0U) ? 1 : 0; int dfd = open(dio_path, base_fl | O_DIRECT, 0644); int aligned_io_ok = 0, unaligned_rejected = 0; if (dfd < 0 && errno == EINVAL) { dfd = open(dio_path, base_fl | O_DSYNC, 0644); if (dfd < 0) { free(raw); return 1; } aligned_io_ok = (write(dfd, abuf, align) == (ssize_t)align); unaligned_rejected = 1; } else if (dfd >= 0) { ssize_t nw = write(dfd, abuf, align); errno = 0; ssize_t bad_ptr = write(dfd, abuf + 1, align); int err_ptr = errno; errno = 0; ssize_t bad_len = pwrite(dfd, abuf, 500U, 0); int err_len = errno; uint8_t *rbuf = abuf + align; memset(rbuf, 0, align); ssize_t nr = pread(dfd, rbuf, align, 0); aligned_io_ok = (nw == (ssize_t)align && nr == (ssize_t)align && rbuf[0] == 0x5AU); unaligned_rejected = (bad_ptr == -1 && err_ptr == EINVAL && bad_len == -1 && err_len == EINVAL); } else { free(raw); return 1; } (void)close(dfd); (void)unlink(dio_path); free(raw); printf("odirect: mem_ok=%d aligned_io=%d unaligned_einval=%d\n", addr_aligned, aligned_io_ok, unaligned_rejected); return 0; }- MAP_PRIVATE clones a private Copy-on-Write page on store ('P' invisible to pread), whereas MAP_SHARED dirties the shared VFS folio ('S').
- Syncing the parent O_DIRECTORY descriptor commits the newly created filename's dentry onto non-volatile storage.
- Query STATX_DIOALIGN and allocate with posix_memalign(); unaligned pointers (abuf + 1) or lengths (500) fail O_DIRECT with EINVAL.
Verifying Durability Barriers, mmap CoW & O_DIRECT Alignment
Compile and run pagecache_odirect: verify fdatasync=1, fsync=1, dir_fsync=1, mmap_cow=1, and odirect: mem_ok=1 aligned_io=1 unaligned_einval=1.
learner@ksa:~/gl-c01/m06-l01gcc -fdiagnostics-color=always -std=c11 -Wall -Wextra -Werror pagecache_odirect.c -o pagecache_odirectlearner@ksa:~/gl-c01/m06-l01./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-l01test ! -e /tmp/ksa_m06_l01.wal && test ! -e /tmp/ksa_m06_l01_dio.bin && rm -f pagecache_odirectlearner@ksa:~/gl-c01/m06-l01Inside Writeback Flushes, CoW Shadow Pages & Block DMA
Notice how pagecache_odirect exposed the unified VFS page cache from three angles: pwrite() dirtied page 0 ('C'), MAP_PRIVATE cloned a private shadow page so pr[0] = 'P' left byte 0 untouched at 'C', MAP_SHARED aliased the page-cache folio directly so sh[1] = 'S' appeared immediately to pread(), and O_DIRECT bypassed that folio cache altogether whenever 3-way alignment held!
Guided Practice: Preallocated WAL Segment Initializer (fallocate + fdatasync)
Why do high-throughput WAL writers pre-size segments (ftruncate or posix_fallocate) once at creation before running pwrite() + fdatasync()?
- Step 1 (Compare metadata mutations): When appending past
EOF, everypwrite()growsinode->i_sizeand allocates new extents—forcing evenfdatasync()to commit filesystem metadata! When overwriting inside a preallocated4 MiBsegment,i_sizeand extent maps stay constant. - Step 2 (Add creation durability): Write a 12-line helper
int create_wal_segment(int dfd, const char *name, off_t seg_bytes)that opensnameviaopenat(dfd, ...)(O_RDWR | O_CREAT | O_EXCL | O_CLOEXEC), pre-sizes it, callsfsync(fd)andfsync(dfd)once, and returnsfdready for single-flushfdatasync()commits.
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 (such as ./ inside a scratch subdir, cleaning up afterward) that records N = 32 individual 64-byte pwrite() latencies (CLOCK_MONOTONIC) under (a) buffered mode (no sync) vs (b) O_DSYNC, sorts the 32 samples in uint64_t ns[32], and prints p50 and p95 nanoseconds for both regimes.
Common Production Pitfalls
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.
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.
Knowledge Check
? check 1 · Why do Write-Ahead Log (WAL) storage engines prefer fdatasync(fd) over fsync(fd) when committing records into a preallocated segment file?
- [ ] Because
fdatasync(fd)flushes only user-spacestdiobuffers into RAM without waiting on storage media - [x] Because
fdatasync(fd)flushes dirty file data (plus metadata only when needed to retrieve those bytes, such asi_sizegrowth) while skipping non-essentialmtime/atimeinode flushes - [ ] Because
fsync(fd)fails withEINVALon preallocated regular files
Answer: Because fdatasync(fd) flushes dirty file data (plus metadata only when needed to retrieve those bytes, such as i_size growth) while skipping non-essential mtime/atime inode flushes
Why: 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.
? check 2 · 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?
- [ ] File descriptor integer, process ID, and buffer capacity
- [x] User-space memory address, transfer byte length, and target file offset
- [ ] Inode number, process
umask, and transfer byte length
Answer: User-space memory address, transfer byte length, and target file offset
Why: 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.
? check 3 · (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?
- [ ]
fcntl(fd, F_SETFD, O_DIRECT) - [x] Read
int fl = fcntl(fd, F_GETFL);(fl != -1) and callfcntl(fd, F_SETFL, fl | O_DIRECT)so existing mutable status flags are preserved - [ ]
O_DIRECTis part ofO_ACCMODEand cannot be changed viaF_SETFL
Answer: Read int fl = fcntl(fd, F_GETFL); (fl != -1) and call fcntl(fd, F_SETFL, fl | O_DIRECT) so existing mutable status flags are preserved
Why: 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.
? check 4 · 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?
- [ ] Both modes incur major page faults (
ru_majflt) on first touch and write stores back tofd - [x] First-touch PTE wiring incurs a minor page fault (
ru_minflt, zero disk read);MAP_SHAREDstores dirty the shared VFS page-cache folio directly, whereasMAP_PRIVATEstores clone a private Copy-on-Write page invisible topread(fd, ...) - [ ]
MAP_PRIVATEpre-copies the entire file eagerly during themmap()syscall
Answer: First-touch PTE wiring incurs a minor page fault (ru_minflt, zero disk read); MAP_SHARED stores dirty the shared VFS page-cache folio directly, whereas MAP_PRIVATE stores clone a private Copy-on-Write page invisible to pread(fd, ...)
Why: 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.
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.
Next, we connect Ring 3 <stdio.h> buffering (_IOFBF, _IOLBF, _IONBF) directly onto this Ring 0 page-cache model to master the two-stage fflush -> fdatasync commit pipeline and fdopen/fileno ownership rules.
Step sequence — frame strip: steps_m06_l01
Query STATX_DIOALIGN for posix_memalign() O_DIRECT buffers, or pre-size WAL segments so i_size stays fixed.
reveals: step1
highlights: step1
Dirty shared VFS folios via pwrite() / MAP_SHARED (whereas MAP_PRIVATE clones private Copy-on-Write RAM).
reveals: step2
highlights: step2
Call fdatasync(fd) to flush dirty data blocks and controller write caches onto non-volatile media.
reveals: step3
highlights: step3
Open the parent directory with O_RDONLY | O_DIRECTORY | O_CLOEXEC and call fsync(dir_fd) after creation or rename.
reveals: step4
highlights: step4
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().
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 without mapping both buffering zones. First, a configuration writer runs fwrite(&commit_rec, sizeof(commit_rec), 1, fp); fdatasync(fileno(fp)); and acknowledges commit—yet on power loss the file is 0 bytes long! Why? Because fwrite() copied commit_rec into fp's Ring 3 _IOFBF heap buffer (0 syscalls), so fdatasync(fileno(fp)) flushed an empty kernel page cache! Second, a network service wraps a socket or file via FILE *fp = fdopen(fd, "r");, later calls fclose(fp);, and "for completeness" also calls close(fd);—silently closing a brand-new connection opened on another thread that just reused slot fd!
Mastering two-layer Linux I/O means tracking bytes across both RAM caches (Ring 3 FILE buffer -> Ring 0 VFS page cache -> non-volatile media) and enforcing strict single-owner lifetime rules across fdopen() and fileno().
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!
definition (setvbuf() Policies, Two-Stage Durability & fdopen() Ownership): 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.
One Layer Down: Two-Zone State Machine & isatty() Mode Selection
When glibc first touches stdout (fd 1), _IO_file_doallocate() invokes fstat(1, &st) / isatty(1): if S_ISCHR(st.st_mode) on a terminal, stdout selects _IOLBF so printf("booting...\n") appears immediately; if redirected to /var/log/daemon.log or a systemd pipe, stdout switches silently to 4,096- or 8,192-byte _IOFBF, delaying log lines until thousands of bytes accumulate (and duplicating any unflushed buffer bytes across both parent and child if fork() runs before fflush(NULL)!). Tracing byte residence (B_user, B_pagecache, B_media) across our four-step commit pipeline makes every failure mode transparent: (B, 0, 0) --[fflush(fp)]--> (0, B_dirty, 0) --[fdatasync(fileno(fp))]--> (0, B_clean, B). Skipping fflush(fp) leaves (B, 0, 0) during fdatasync(); skipping fdatasync() leaves (0, B_dirty, 0), which survives SIGKILL yet vanishes on power cut!
| Buffering / Interop Primitive | Default Target | Kernel Syscall & Lifetime Contract |
|---|---|---|
setvbuf(fp, NULL, _IOFBF, sz) | Regular files, pipes, sockets | Heap-allocates sz bytes; flushes when full, fflush, fclose, exit |
setvbuf(fp, NULL, _IOLBF, sz) | Interactive TTY (stdin/stdout) | Flushes immediately on '\n' (systemd services often set _IOLBF) |
setvbuf(fp, NULL, _IONBF, 0) | stderr (fd 2) | Every fwrite/fputs traps via write() immediately |
fflush(fp) / fflush(NULL) | fp / all open output streams | Drains Ring 3 buffer into Ring 0 page cache (0 ok, EOF err) |
fileno(fp) | Borrows int fd from fp | Safe for fdatasync(fileno(fp)) or fstat; never close(fileno(fp)) |
fdopen(fd, mode) | Wraps open fd in FILE * | mode must match O_ACCMODE (never truncates!); fclose(fp) closes fd |
Figure 6.2a. Complete two-zone user-space stdio and Linux kernel page cache buffering, flush, and bypass architecture.
- Step 1. Stage 1 — fwrite() stages (B, 0, 0) in glibc's Ring 3 heap buffer with zero syscalls (_exit loses it).
- Step 2. Stage 2 — fflush(fp) drains the Ring 3 FILE buffer via write() into the Ring 0 kernel page cache.
- Step 3. Stage 3 — fdatasync(fileno(fp)) flushes dirty kernel RAM folios onto non-volatile NVMe/flash media.
- Step 4. Stage 4 — fclose(fp) frees the FILE struct and closes _fileno once; never call close(raw_fd) again.
Figure 6.2b. Durable stdio commits require Stage 2 fflush(fp) before Stage 3 fdatasync(fileno(fp)), followed by single-owner fclose(fp).
Figure 6.2b. Two-stage durability state transitions, setvbuf() policies, and single-owner fdopen() versus borrowed fileno().
setvbuf(3) Lifetime Rule & fdopen(3) Error Handling
Include <stdio.h>, <fcntl.h>, <time.h>, and <unistd.h> under #define _POSIX_C_SOURCE 200809L. Always pass buf = NULL to setvbuf(fp, NULL, _IOFBF, 8192) unless your custom buffer has static or heap lifetime outliving fclose(fp)—passing a local stack array inside a helper function causes use-after-return stack corruption! Also note fdopen(fd, mode)'s failure branch: if fdopen() returns NULL (for example, EINVAL because fd was O_RDONLY and mode was "w"), fd was not consumed and you must still close(fd); once fdopen() returns non-NULL, fp owns fd exclusively.
Probing _IOFBF/_IOLBF/_IONBF, Two-Stage Sync & Ownership Transfer
Save stdio_buf_interop.c below. First, probe_buf_mode() duplicates a scratch fd (dup(fd) so fd survives fclose(fp)!), configures setvbuf(), writes text, and inspects live kernel i_size via lseek(fd, 0, SEEK_END) before and after fclose(fp)—proving _IOFBF withholds "HELLO_NO_NL" (0 -> 11), _IOLBF flushes "LINE\n" (5) on newline while holding "TAIL" (5 -> 9), and _IONBF writes "NOW" immediately (3 -> 3). Second, main() executes the two-stage commit barrier (pre_flush=0, post_flush=14, sync=1), proves fcntl(raw_fd, F_GETFD) returns -1 (EBADF) after fclose(fp), and times 1,024 _IONBF vs _IOFBF fwrite() calls via CLOCK_MONOTONIC!
learner@ksa:~/gl-c01/m06-l02$ bat -H 17 -H 64 -H 71 stdio_buf_interop.c File: stdio_buf_interop.c #define _POSIX_C_SOURCE 200809L #include <errno.h> #include <fcntl.h> #include <stdint.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <sys/stat.h> #include <time.h> #include <unistd.h> static uint64_t span_ns(struct timespec a, struct timespec b) { return (uint64_t)(b.tv_sec - a.tv_sec) * 1000000000ULL + (uint64_t)(b.tv_nsec - a.tv_nsec); } static int probe_buf_mode(int mode, const char *msg, off_t *pre_out, off_t *post_out) { const char *tmp = "/tmp/ksa_m06_mode.tmp"; (void)unlink(tmp); int fd = open(tmp, O_RDWR | O_CREAT | O_TRUNC | O_CLOEXEC, 0644); if (fd < 0) return -1; int dup_fd = dup(fd); if (dup_fd < 0) { (void)close(fd); return -1; } FILE *fp = fdopen(dup_fd, "w"); if (!fp || setvbuf(fp, NULL, mode, 4096U) != 0) { if (fp) (void)fclose(fp); else (void)close(dup_fd); (void)close(fd); return -1; } if (fputs(msg, fp) < 0) { (void)fclose(fp); (void)close(fd); return -1; } *pre_out = lseek(fd, 0, SEEK_END); if (fclose(fp) != 0) { (void)close(fd); return -1; } *post_out = lseek(fd, 0, SEEK_END); (void)close(fd); (void)unlink(tmp); return 0; } int main(void) { off_t iofbf_pre = -1, iofbf_post = -1; off_t iolbf_pre = -1, iolbf_post = -1; off_t ionbf_pre = -1, ionbf_post = -1; if (probe_buf_mode(_IOFBF, "HELLO_NO_NL", &iofbf_pre, &iofbf_post) < 0 || probe_buf_mode(_IOLBF, "LINE\nTAIL", &iolbf_pre, &iolbf_post) < 0 || probe_buf_mode(_IONBF, "NOW", &ionbf_pre, &ionbf_post) < 0) { return 1; } printf("buf_modes: iofbf=%lld->%lld iolbf=%lld->%lld ionbf=%lld->%lld\n", (long long)iofbf_pre, (long long)iofbf_post, (long long)iolbf_pre, (long long)iolbf_post, (long long)ionbf_pre, (long long)ionbf_post); const char *path = "/tmp/ksa_m06_l02.commit"; int raw_fd = open(path, O_RDWR | O_CREAT | O_TRUNC | O_CLOEXEC, 0644); if (raw_fd < 0) return 1; FILE *fp = fdopen(raw_fd, "w+"); if (!fp || setvbuf(fp, NULL, _IOFBF, 4096U) != 0) return 1; const char *rec = "COMMIT_SEQ=42\n"; if (fwrite(rec, 1U, 14U, fp) != 14U) return 1; off_t size_before_flush = lseek(raw_fd, 0, SEEK_END); if (fflush(fp) != 0) return 1; off_t size_after_flush = lseek(raw_fd, 0, SEEK_END); int sync_ok = (fdatasync(fileno(fp)) == 0) ? 1 : 0; if (fclose(fp) != 0) return 1; errno = 0; int fd_check = fcntl(raw_fd, F_GETFD); int closed_ebadf = (fd_check == -1 && errno == EBADF) ? 1 : 0; struct timespec t0, t1, t2; FILE *ufp = fopen(path, "we"); if (!ufp || setvbuf(ufp, NULL, _IONBF, 0U) != 0) return 1; clock_gettime(CLOCK_MONOTONIC, &t0); for (int i = 0; i < 1024; i++) { if (fwrite("ABCD", 1U, 4U, ufp) != 4U) return 1; } if (fclose(ufp) != 0) return 1; clock_gettime(CLOCK_MONOTONIC, &t1); FILE *bfp = fopen(path, "we"); if (!bfp || setvbuf(bfp, NULL, _IOFBF, 8192U) != 0) return 1; for (int i = 0; i < 1024; i++) { if (fwrite("ABCD", 1U, 4U, bfp) != 4U) return 1; } if (fclose(bfp) != 0) return 1; clock_gettime(CLOCK_MONOTONIC, &t2); (void)unlink(path); int iofbf_faster = (span_ns(t0, t1) > span_ns(t1, t2)) ? 1 : 0; printf("pipeline_owner: pre_flush=%lld post_flush=%lld sync=%d " "raw_ebadf=%d iofbf_faster=%d\n", (long long)size_before_flush, (long long)size_after_flush, sync_ok, closed_ebadf, iofbf_faster); return 0; }- dup(fd) increments struct file.f_count to 2 so fclose(fp) closes dup_fd while keeping fd open to measure kernel i_size.
- Before fflush(fp), all 14 bytes sit in Ring 3 heap RAM (size_before_flush == 0); fflush() pushes them to the page cache before fdatasync().
- fclose(fp) closed raw_fd via single-owner transfer, so fcntl(raw_fd, F_GETFD) returns -1 with errno == EBADF.
Verifying Two-Zone Flush Boundaries, Single-Owner Close & Speedup
Compile and execute stdio_buf_interop: verify iofbf=0->11, iolbf=5->9, ionbf=3->3, pre_flush=0 -> post_flush=14, raw_ebadf=1, and iofbf_faster=1 (8 KiB _IOFBF outperforming 1,024 unbuffered _IONBF traps!).
learner@ksa:~/gl-c01/m06-l02gcc -fdiagnostics-color=always -std=c11 -O2 -Wall -Wextra -Werror stdio_buf_interop.c -o stdio_buf_interoplearner@ksa:~/gl-c01/m06-l02./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-l02test ! -e /tmp/ksa_m06_l02.commit && rm -f stdio_buf_interoplearner@ksa:~/gl-c01/m06-l02Why pre_flush=0 Proves Both Sync Stages Are Mandatory
Seeing pre_flush=0 right after fwrite(rec, 1, 14, fp) settles the durability debate permanently: the Linux kernel VFS inode literally knew nothing about those 14 bytes until fflush(fp) issued write() (post_flush=14), after which fdatasync(fileno(fp)) committed the dirty page-cache folio onto media and fclose(fp) closed raw_fd cleanly (raw_ebadf=1).
Guided Practice: Borrowing raw_fd Safely via dup() + fdopen()
Suppose a protocol handler receives int client_fd from a caller whose contract states client_fd must remain open after your helper parses one text header line via fgets():
- Step 1 (Clone the descriptor with
O_CLOEXEC): Callint tmp_fd = fcntl(client_fd, F_DUPFD_CLOEXEC, 0);and return-1iftmp_fd < 0. - Step 2 (Check the
fdopenerror branch): CallFILE *fp = fdopen(tmp_fd, "r");—if!fp, callclose(tmp_fd)before returning-1; iffpsucceeds, watch out for_IOFBFread-ahead consuming payload bytes past the header line (use_IONBFonfpif binary bytes follow onclient_fd!), and letfclose(fp)closetmp_fdwhileclient_fdstays valid!
Independent Practice: Durable Checkpoint Writer Function
Write a standalone C11 module durable_save.c (-std=c11 -Wall -Wextra -Werror) implementing int save_checkpoint_at(int dfd, const char *final_name, const struct ckpt *c) that combines directory-pinned openat(dfd, "ckpt.tmp", O_WRONLY | O_CREAT | O_EXCL | O_NOFOLLOW | O_CLOEXEC, 0600), fdopen(tfd, "w"), setvbuf(fp, NULL, _IOFBF, 4096), formatted header + binary payload fwrite(), the strict two-stage barrier (fflush(fp) -> fdatasync(fileno(fp)) -> checked fclose(fp)), renameat(), and fsync(dfd).
Common Production Pitfalls
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.
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.
Knowledge Check
? check 1 · 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?
- [ ] Because redirecting
stdoutenablesO_DIRECTon descriptor1 - [x] Because
glibcswitchesstdoutfrom_IOLBF(line-buffered on a terminal) to_IOFBF(fully buffered) wheneverisatty(1)returns0 - [ ] Because
'\n'suppresses buffer flushing on regular files
Answer: Because glibc switches stdout from _IOLBF (line-buffered on a terminal) to _IOFBF (fully buffered) whenever isatty(1) returns 0
Why: 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.
? check 2 · Which exact call sequence guarantees that records written via fwrite(..., fp) survive a sudden machine power loss before closing fp?
- [ ]
fdatasync(fileno(fp))->fflush(fp)->fclose(fp)->close(fileno(fp)) - [x]
fflush(fp)->fdatasync(fileno(fp))(verifying both return0) ->fclose(fp)(verifying0, with no extraclose()) - [ ]
fclose(fp)alone, becausefclose()automatically invokesfsync()inside the Linux kernel
Answer: fflush(fp) -> fdatasync(fileno(fp)) (verifying both return 0) -> fclose(fp) (verifying 0, with no extra close())
Why: 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.
? check 3 · (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?
- [ ] Call
fcntl(raw_fd, F_SETFD, FD_CLOEXEC)beforefdopen() - [x] Duplicate the descriptor first (
int d = fcntl(raw_fd, F_DUPFD_CLOEXEC, 0); FILE *fp = fdopen(d, "r");) sofclose(fp)decrementsf_countondwhileraw_fdstays open - [ ] Reopen the pathname with
O_TRUNC
Answer: Duplicate the descriptor first (int d = fcntl(raw_fd, F_DUPFD_CLOEXEC, 0); FILE *fp = fdopen(d, "r");) so fclose(fp) decrements f_count on d while raw_fd stays open
Why: 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().
? check 4 · 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()?
- [ ]
"HEADER\n"is lost completely becausefork()zeroesstdoutbuffers - [x]
"HEADER\n"appears twice in the output file, becausefork()clones the parent'sRing 3virtual memory (including unflushedFILEbytes) and both processes flush their copy duringexit() - [ ] The child crashes with
EBADFduringexit()
Answer: "HEADER\n" appears twice in the output file, because fork() clones the parent's Ring 3 virtual memory (including unflushed FILE bytes) and both processes flush their copy during exit()
Why: 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.
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.
Now, in our final capstone lesson (m06-l03), we synthesize every mechanism from Modules 1 through 6 into a crash-consistent CRC32 + monotonic-epoch Write-Ahead Log (WAL) storage engine!
Step sequence — frame strip: steps_m06_l02
Stage 1 — fwrite() stages (B, 0, 0) in glibc's Ring 3 heap buffer with zero syscalls (_exit loses it).
reveals: step1
highlights: step1
Stage 2 — fflush(fp) drains the Ring 3 FILE buffer via write() into the Ring 0 kernel page cache.
reveals: step2
highlights: step2
Stage 3 — fdatasync(fileno(fp)) flushes dirty kernel RAM folios onto non-volatile NVMe/flash media.
reveals: step3
highlights: step3
Stage 4 — fclose(fp) frees the FILE struct and closes _fileno once; never call close(raw_fd) again.
reveals: step4
highlights: step4
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.
Why In-Place Updates Corrupt State & CRC32 Alone Fails Recycled Logs
Imagine an embedded power-controller key-value store that updates "vcore" from "1150mV" (6 bytes) to "1200mV_boost" (12 bytes) by overwriting records in place inside a flat binary file. If input power drops halfway through that write(), the sector on flash contains half of the new record spliced onto adjacent keys—destroying both the uncommitted update and previously committed state! Switching to an append-only log with a CRC32 checksum fixes torn writes on fresh files, yet a subtler bug strikes as soon as the engine recycles preallocated WAL segments without zero-wiping 4 MiB of flash: right after committing 3 new frames (105 bytes), the recycled sector at offset 105 still holds an intact, valid-CRC32 frame from yesterday's epoch ("vcore=900mV!")—which a naive CRC32-only scanner happily replays on boot!
Production storage engines (SQLite WAL, RocksDB, etcd Raft logs) solve both hazards by uniting every primitive from Modules 1–6 inside an append-only Write-Ahead Log (WAL) sealed by reflected IEEE 802.3 CRC32 + a strictly monotonic 64-bit sequence/epoch counter (seq).
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.
definition (Write-Ahead Log (WAL), Reflected CRC32 & Monotonic Epoch): 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.
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, vlen; uint64_t seq;, _Static_assert(sizeof(struct wal_hdr) == 24) with zero compiler padding) followed by klen key bytes and vlen value bytes, giving total size frame_bytes = 24 + klen + vlen. Computing IEEE 802.3 CRC32 bit-by-bit in C without a branch (if (crc & 1)) avoids branch-misprediction stalls on embedded ARMv7 pipelines. Using two's-complement negation on unsigned uint32_t, -(crc & 1U) evaluates to 0xFFFFFFFFU when bit 0 is 1 and 0x00000000U when bit 0 is 0, yielding the branchless step crc_next = (crc >> 1) ^ (0xEDB88320U & -(crc & 1U)). Initializing c = 0xFFFFFFFFU and inverting ~c at completion ensures leading and trailing 0x00 bytes alter the checksum!
| Course Module Synthesized | Exact Primitive Inside WAL Engine | Storage Invariant Enforced | ||
|---|---|---|---|---|
m01 — Types & ABI | <stdint.h>, _Static_assert(sizeof == 24), unsigned -(crc & 1U) | Zero UB; identical binary frame on ARMv7 & x86-64 | ||
m02 — Unbuffered I/O | `O_RDWR \ | O_CREAT \ | O_CLOEXEC, write_all()` retry loop | Leak-safe handle; immune to EINTR & short writes |
m03 — VFS & fstat | fstat(fd, &st) logical st_size, saved_errno cleanup | Bounds recovery scan to exact inode byte size | ||
m04 — Atomicity & Resize | Stateless pread() index reads + ftruncate(fd, valid_off) | Lock-free concurrent GETs + atomic torn-tail heal | ||
m05 — Safe Diagnostics | Bounded key/value length caps + %lld / PRIu64 reports | Zero stack overruns on corrupted length headers | ||
m06 — Durability | fdatasync(fd) per commit + fsync(dir_fd) on creation | Committed frames survive power loss & SIGKILL |
Figure 6.3. ABI-locked 24-byte CRC32+seq WAL frame layout, recycled-tail ftruncate() crash healing, and lock-free pread() indexing.
- Step 1. Seal [seq, klen, vlen, key, val] inside a 24-byte header with branchless CRC32 and commit via write_all() + fdatasync().
- Step 2. Replay sequentially from offset 0 checking WAL_MAGIC, h.seq == exp_seq, subtraction bounds, and CRC32.
- Step 3. Snip stale recycled frames or torn crash tails via ftruncate(fd, off) + fdatasync(fd) + lseek(fd, off, SEEK_SET).
- Step 4. Serve latest committed values concurrently via stateless pread() while writer_fpos remains parked at EOF.
Figure 6.3b. Seal immutable WAL frames with branchless CRC32 + monotonic seq, flush via fdatasync(), heal crash tails with ftruncate() + lseek(), and read lock-free via pread().
Startup Recovery State Machine & Cursor Resynchronization
Walk through the four validation gates executed at byte offset off during startup recovery (exp_seq starting at 1): (1) off + 24 <= st.st_size and pread_full(fd, &h, 24, off) == 24; (2) h.magic == WAL_MAGIC, h.seq == exp_seq, bounded h.klen/h.vlen, and off + 24 + h.klen + h.vlen <= st.st_size; (3) pread_full() of key and val succeeds and frame_crc(...) == h.crc32; (4) on any failure, stop at off, call ftruncate(fd, off) + fdatasync(fd) to snip the torn or stale tail, and call lseek(fd, off, SEEK_SET) so subsequent appends start cleanly at off!
Building Mini-WAL Commit, Stale-Epoch Guard, Healing & pread Lookup
Save mini_wal_demo.c below. It wraps writes in write_all() + fdatasync() + initial /tmp directory fsync(), commits three monotonic mutations (seq=1..3: vcore=1150mV, pll_hz=1200M, vcore=1200mV, 105 bytes total), injects a recycled-sector stale frame with a valid CRC32 but stale seq=1 (vcore=900mV!, 140 bytes) plus 5 torn garbage bytes (145 bytes), runs startup recovery to heal the log back to 105 bytes via ftruncate(), and serves "vcore" (1200mV) via stateless pread() while writer_fpos stays at 105!
learner@ksa:~/gl-c01/m06-l03$ bat -H 23 -H 49 -H 95 -H 115 mini_wal_demo.c File: mini_wal_demo.c #define _FILE_OFFSET_BITS 64 #define _POSIX_C_SOURCE 200809L #include <errno.h> #include <fcntl.h> #include <stdint.h> #include <stdio.h> #include <string.h> #include <sys/stat.h> #include <unistd.h> #define WAL_MAGIC 0x4B57414CU struct wal_hdr { uint32_t magic, crc32, klen, vlen; uint64_t seq; }; _Static_assert(sizeof(struct wal_hdr) == 24, "WAL header ABI"); static uint32_t crc32_step(uint32_t crc, const void *buf, size_t len) { const uint8_t *p = (const uint8_t *)buf; for (size_t i = 0; i < len; i++) { crc ^= p[i]; for (int b = 0; b < 8; b++) { crc = (crc >> 1) ^ (0xEDB88320U & (-(crc & 1U))); } } return crc; } static uint32_t frame_crc(uint64_t seq, uint32_t kl, uint32_t vl, const char *k, const char *v) { uint32_t c = 0xFFFFFFFFU; c = crc32_step(c, &seq, sizeof(seq)); c = crc32_step(c, &kl, sizeof(kl)); c = crc32_step(c, &vl, sizeof(vl)); c = crc32_step(c, k, kl); c = crc32_step(c, v, vl); return ~c; } static int write_all(int fd, const void *buf, size_t len) { const uint8_t *p = (const uint8_t *)buf; size_t done = 0U; while (done < len) { ssize_t n = write(fd, p + done, len - done); if (n < 0) { if (errno == EINTR) continue; return -1; } done += (size_t)n; } return 0; } static int wal_put(int fd, uint64_t seq, const char *k, const char *v) { uint32_t kl = (uint32_t)strlen(k), vl = (uint32_t)strlen(v); struct wal_hdr h = {WAL_MAGIC, frame_crc(seq, kl, vl, k, v), kl, vl, seq}; uint8_t frame[128]; size_t tot = sizeof(h) + kl + vl; if (tot > sizeof(frame)) return -1; memcpy(frame, &h, sizeof(h)); memcpy(frame + sizeof(h), k, kl); memcpy(frame + sizeof(h) + kl, v, vl); if (lseek(fd, 0, SEEK_END) < 0 || write_all(fd, frame, tot) < 0) { return -1; } return fdatasync(fd); } int main(void) { const char *path = "/tmp/ksa_m06_l03.wal"; int fd = open(path, O_RDWR | O_CREAT | O_TRUNC | O_CLOEXEC, 0644); int dfd = open("/tmp", O_RDONLY | O_DIRECTORY | O_CLOEXEC); if (fd < 0 || dfd < 0 || fsync(dfd) < 0) return 1; (void)close(dfd); if (wal_put(fd, 1ULL, "vcore", "1150mV") < 0 || wal_put(fd, 2ULL, "pll_hz", "1200M") < 0 || wal_put(fd, 3ULL, "vcore", "1200mV") < 0) { return 1; } off_t clean_sz = lseek(fd, 0, SEEK_END); if (wal_put(fd, 1ULL, "vcore", "900mV!") < 0 || write_all(fd, "TORN!", 5U) < 0) { return 1; } off_t crashed_sz = lseek(fd, 0, SEEK_END); struct stat st; if (fstat(fd, &st) < 0) return 1; off_t off = 0, vcore_off = -1; uint32_t vcore_len = 0U, valid_recs = 0U; uint64_t exp_seq = 1ULL; while (off + (off_t)sizeof(struct wal_hdr) <= st.st_size) { struct wal_hdr h; char kbuf[32], vbuf[64]; if (pread(fd, &h, sizeof(h), off) != (ssize_t)sizeof(h)) break; off_t hsz = (off_t)sizeof(h); if (h.magic != WAL_MAGIC || h.seq != exp_seq || h.klen >= sizeof(kbuf) || h.vlen >= sizeof(vbuf) || (off_t)(h.klen + h.vlen) > st.st_size - off - hsz) { break; } if (pread(fd, kbuf, h.klen, off + hsz) != (ssize_t)h.klen || pread(fd, vbuf, h.vlen, off + hsz + (off_t)h.klen) != (ssize_t)h.vlen) { break; } if (frame_crc(h.seq, h.klen, h.vlen, kbuf, vbuf) != h.crc32) break; kbuf[h.klen] = '\0'; if (strcmp(kbuf, "vcore") == 0) { vcore_off = off + hsz + (off_t)h.klen; vcore_len = h.vlen; } valid_recs++; exp_seq++; off += hsz + (off_t)h.klen + (off_t)h.vlen; } if (off < st.st_size && (ftruncate(fd, off) < 0 || fdatasync(fd) < 0)) return 1; if (lseek(fd, off, SEEK_SET) < 0) return 1; char latest[64] = {0}; if (vcore_off < 0 || pread(fd, latest, vcore_len, vcore_off) != (ssize_t)vcore_len) { return 1; } off_t writer_fpos = lseek(fd, 0, SEEK_CUR); (void)close(fd); (void)unlink(path); printf("wal_recovery: clean=%lld crashed=%lld healed=%lld recs=%u\n", (long long)clean_sz, (long long)crashed_sz, (long long)off, valid_recs); printf("wal_lookup: vcore=%s writer_fpos=%lld\n", latest, (long long)writer_fpos); return 0; }- Branchless reflected IEEE 802.3 CRC32 step: -(crc & 1U) masks 0xEDB88320U without conditional branch mispredictions.
- Include seq, klen, vlen, key, and val inside frame_crc() and finish with fdatasync(fd) before acknowledging wal_put().
- Checking h.seq != exp_seq rejects intact valid-CRC frames left in recycled WAL sectors; ftruncate(fd, off) heals the tail.
Verifying Crash-Tail Healing, Stateless pread Lookup & Lab 6
Compile and execute mini_wal_demo: verify clean=105, crashed=145, healed=105 (recs=3), and vcore=1200mV with writer_fpos=105 untouched! Then complete the full capstone project in lab_m06_durable_wal.
learner@ksa:~/gl-c01/m06-l03gcc -fdiagnostics-color=always -std=c11 -Wall -Wextra -Werror mini_wal_demo.c -o mini_wal_demolearner@ksa:~/gl-c01/m06-l03./mini_wal_demowal_recovery: clean=105 crashed=145 healed=105 recs=3wal_lookup: vcore=1200mV writer_fpos=105learner@ksa:~/gl-c01/m06-l03test ! -e /tmp/ksa_m06_l03.wal && rm -f mini_wal_demolearner@ksa:~/gl-c01/m06-l031. Motivation
Every production embedded database, OTA boot-state manager, and distributed consensus log (SQLite WAL, RocksDB, etcd, U-Boot redundant environment) confronts the same physical law: power can vanish mid-sector at any microsecond. Overwriting records in place destroys committed state, calling fclose(fp) without fflush(fp) + fdatasync(fileno(fp)) leaves acknowledged commits in volatile DRAM, and reading with stateful read() clobbers concurrent cursors. In this capstone project, you will synthesize all six modules of GL-C01 into durable_wal, a crash-consistent IEEE 802.3 CRC32 Write-Ahead Log and key-value engine.
2. Learning Objectives
- Commit length-prefixed, IEEE 802.3
CRC32-protected binary frames via the complete two-stage durability barrier (fwrite->fflush->fdatasync(fileno(fp))-> single-ownerfclose, plus parent-directoryfsyncon initial creation). - Recover crashed logs deterministically by scanning frames from offset
0via statelesspread(), detecting torn headers, torn payloads, or single-bitCRC32corruptions, and healing the file viaftruncate(fd, valid_offset)+fdatasync(fd). - Serve log-structured latest-wins
getqueries viapread()while provingstruct file.f_posremains untouched at0.
3. Environment Requirements
- Host Execution Environment (Tested): Linux
6.12LTS (x86_64,glibc2.39+),#define _POSIX_C_SOURCE 200809Land#define _FILE_OFFSET_BITS 64. - Target Board Portability (
ARMv7Cortex-A7): The16-bytestruct wal_hdr(magic,crc32,key_len,val_len), branchless reflected0xEDB88320UCRC32, andpread/ftruncate/fdatasynccalls behave identically on embeddedARMv7ext4/f2fspartitions (wherefdatasync()flushes the eMMC controller cache).
4. Required Software & Hardware
- Software Toolchain:
gcc(-std=c11 -Wall -Wextra -Werror),strace,dd/python3(for fault-injection corruption tests), and/bin/sh. - Hardware: Standard Linux host environment (
tmpfsor NVMe/SSD filesystem).
5. Complete Executable Commands
Run from labs/lab_m06_durable_wal/:
learner@ksa:~/gl-c01/m06-l03$ bat script.sh File: script.sh # 1. Compile the capstone WAL engine with strict C11 warning flags gcc -std=c11 -O2 -Wall -Wextra -Werror files/durable_wal.c -o /tmp/durable_wal rm -f /tmp/engine.wal # 2. Commit three mutations (including an update to boot.mode) and verify latest-wins GET /tmp/durable_wal append /tmp/engine.wal boot.mode primary /tmp/durable_wal append /tmp/engine.wal vcore_mv 1200 /tmp/durable_wal append /tmp/engine.wal boot.mode fallback /tmp/durable_wal get /tmp/engine.wal boot.mode # 3. Inject a 9-byte torn power-loss tail and verify ftruncate() heals back to 95 bytes! printf 'TORN_TAIL' >> /tmp/engine.wal /tmp/durable_wal recover /tmp/engine.wal /tmp/durable_wal get /tmp/engine.wal boot.mode # 4. Trace exact fflush -> write -> fdatasync -> close syscall sequence on append strace -e trace=openat,write,fdatasync,fsync,close /tmp/durable_wal append /tmp/engine.wal watchdog on # 5. Clean up and run the full TAP 13 fault-injection suite rm -f /tmp/durable_wal /tmp/engine.wal sh check.sh*Why each command runs:* Step 2 appends immutable frames (32 + 30 + 33 = 95 bytes) and verifies "boot.mode" resolves to "fallback" with f_pos=0; Step 3 simulates an interrupted write (104 bytes) and proves recover heals 104 -> 95 (valid_records=3); Step 4 proves fflush() issues write() before fdatasync() and fclose() closes fd once; and Step 5 executes all TAP 13 checks including mid-payload CRC32 bit-flip injection.
6. Annotated Source Code (starter/ Flaws vs files/ Reference)
Flawed Baseline (starter/durable_wal.c)
- Zero durability & fake checksum (
append): Writescrc32 = 0U, omitsO_CLOEXEC, and omitsfflush()+fdatasync()+ parent directoryfsync(). - No-op
recover: Printsst.st_sizewithout reading headers, recomputingCRC32, or callingftruncate(). - Stateful first-match
get: Usesread()(advancingf_posto32) and returns on the first matching key ("primary") instead of scanning toEOFfor latest-wins ("fallback").
Warning-Clean Reference (files/durable_wal.c)
- Branchless IEEE 802.3
CRC32(crc32_update/compute_frame_crc): Computesuint32_t mask = -(crc & 1U); crc = (crc >> 1) ^ (0xEDB88320U & mask);over[key_len, val_len, key, val](including lengths inside the checksum envelope!). - Two-Stage Commit + Dir Sync (
cmd_append): OpensO_WRONLY | O_CREAT | O_APPEND | O_CLOEXEC(0644), transfers ownership tofdopen(fd, "wb"), runsfwrite->fflush(fp)->fdatasync(fileno(fp))-> singlefclose(fp), and callssync_parent_dir(wal_path)when creating a brand-new WAL file. - Stateless Recovery & Lookup (
cmd_recover,cmd_get): Usespread_exact()fromoff = 0, validatesWAL_MAGIC, bounds (1 <= key_len <= 64,val_len <= 256), full payload availability, andexpect_crc == hdr.crc32, heals mismatches viaftruncate(fd, valid_off) + fdatasync(fd), and updateslatest_valacross all valid frames whilelseek(fd, 0, SEEK_CUR)stays0!
7. Expected Output
learner@ksa:~/gl-c01/m06-l03$ bat listing.txt File: listing.txt $ ./durable_wal append engine.wal boot.mode primary && ./durable_wal append engine.wal boot.mode fallback && ./durable_wal get engine.wal boot.mode COMMIT key=boot.mode bytes=32 COMMIT key=boot.mode bytes=33 VALUE fallback f_pos=0 $ sh check.sh TAP version 13 1..5 ok 1 - builds with -std=c11 -Wall -Wextra and no warnings ok 2 - flushes and fdatasyncs 3 CRC32-framed WAL commits (95 bytes) ok 3 - scans WAL statelessly via pread leaving f_pos=0 with latest-wins semantics ok 4 - truncates torn power-loss tail back to last valid frame boundary ok 5 - detects CRC32 payload corruption, truncates bad frame, and keeps prior commits # pass 5/58. Explanation of Observed Behavior
Look at Test 5 inside check.sh: after three committed frames (95 bytes), a 4th 40-byte frame (135 bytes total) has 1 bit flipped inside its value payload. During recover, pread_exact() reads frames 1..3 (valid_off advances 0 -> 32 -> 62 -> 95); at valid_off = 95, compute_frame_crc() mismatches hdr.crc32, breaking out of the scan loop at valid_off = 95. ftruncate(fd, 95) + fdatasync(fd) then snips the corrupted 40-byte tail atomically on storage while all 3 earlier committed frames remain 100% intact!
9. Experiment Variations
- Single-Write Coalescing Optimization: Coalesce
[hdr, key, val]into one stackuint8_t frame[16 + KEY_CAP + VAL_CAP]buffer beforefwrite()(or usewritev()), confirming understracethatfflush(fp)already coalesces the threefwrite()calls into onewrite()syscall thanks to_IOFBF! - Header Length Bit-Flip Test: Flip
1bit insidehdr.key_len(changing5to37within<= 64) on a 4th frame and verify that includingkey_leninsidecompute_frame_crc()catches the corruption even if95 + 16 + 37 <= st_size. - 256-entry
CRC32Lookup Table: Precompute auint32_t crc_tab[256]table inside an__attribute__((constructor))orstatic constarray (1table lookup per byte instead of8bit loops) and compare CPU throughput on1 MiBpayloads.
10. Performance Measurements
Measured on Host x86_64 Linux 6.12 LTS (CLOCK_MONOTONIC, 5 warmup runs, N = 35 paired append + get durable CLI commits):
| Metric | Measured Host (x86_64 Linux 6.12) | Target Board Expectation (ARMv7 Cortex-A7 Industrial eMMC) |
|---|---|---|
Durable append + get (p50 / p95 / p99) | 3,346.2 us / 5,287.6 us / 5,400.4 us | ~14,000–24,000 us CLI (1.5–6.0 ms per hardware eMMC fdatasync barrier) |
Syscalls per existing-WAL append | 1 openat + 1 write + 1 fdatasync + 1 close | Identical 4-syscall commit path |
Stateless get cursor mutation (f_pos) | 0 -> 0 (pread64 only) | 0 -> 0 (pread64 only) |
11. Troubleshooting
| Symptom | Root Cause | Fix |
|---|---|---|
EBADF or crashed fd in multithreaded test | Called close(fd) after fclose(fp) on fp = fdopen(fd, "wb") | Let fclose(fp) close fd once; only close(fd) if fdopen() returned NULL |
fdatasync runs while WAL file on disk is still 0 bytes | Called fdatasync(fileno(fp)) before fflush(fp) | Always call fflush(fp) first, then fdatasync(fileno(fp)) |
get returns "primary" instead of "fallback" | Returned immediately on first key match instead of scanning to EOF | Keep updating latest_val until the scan reaches the end of valid frames |
get prints f_pos=95 instead of f_pos=0 | Used stateful read()/fread() instead of pread() | Read headers and payloads exclusively via pread_exact() |
12. Guided Questions
- Why does
cmd_append()checkint existed = (stat(wal_path, &before_st) == 0);and callsync_parent_dir(wal_path)when!existed?
- *Hint 1:* Does
fdatasync(fileno(fp))sync the parent directory's dentry table? - *Hint 2:* What happens on sudden power loss right after creating
engine.walifengine.wal's blocks are on NVMe media but the parent directory's new"engine.wal" -> st_inoentry was still in volatile DRAM?
- Why does
cmd_append()combineO_APPENDonopen()withfdopen(fd, "wb")?
- *Hint 1:* When
fflush(fp)drains theRing 3buffer via a singlewrite(fd, buf, frame_len)syscall (frame_len <= 336bytes), what lock doesO_APPENDacquire insideRing 0? - *Hint 2:* Why would two separate
write()syscalls (header inwrite #1, payload inwrite #2) break multi-processO_APPENDatomicity without_IOFBFcoalescing them into a singlewrite()?
13. Independent Challenges
- Near Transfer — Monotonic
64-Bit Epoch Header & Tombstone Deletes (del <wal_path> <key>): Upgradestruct wal_hdrto24bytes by addinguint64_t seq(1, 2, ..., verified duringrecoverto block stale recycled-segment frames as inm06-l03) anduint32_t tombstone(0xFFFFFFFFUval_lensentinel) sodelremoves keys cleanly without in-place mutation. - Far Transfer — Crash-Safe WAL Compaction (
compact <wal_path>): Implement atomic log compaction using directory-pinnedopenat(..., "wal.compact.tmp", O_WRONLY | O_CREAT | O_EXCL | O_NOFOLLOW | O_CLOEXEC, 0644), writing only live non-deleted keys, committing viafflush+fdatasync+ checkedfclose, swapping viarenameat(), and hardening viafsync(dir_fd).
14. Solutions & Explanations
- Guided Question 1:
fdatasync(fd)only persistsfd's own data blocks and size metadata; syncing the parent directory (fsync(dfd)) on initial creation commits the directory entry so the newly created WAL file cannot vanish across power loss. - Guided Question 2: Because
_IOFBFcoalesces the16-byte header,<= 64-byte key, and<= 256-byte value (<= 336bytes<< BUFSIZ) into onewrite()syscall insidefflush(fp),O_APPENDpositionski_pos = i_sizeand copies the entire frame atomically underinode->i_rwsem!
Run locally in your terminal and check off each verification milestone.
Not started
Full-Course Synthesis & Bridge to GL-C02
Trace how every layer in mini_wal_demo reinforced the others: O_CLOEXEC prevented handle leaks, subtraction bounds (off_t)(h.klen + h.vlen) > st.st_size - off - hsz prevented signed off_t overflow UB, h.seq == exp_seq caught the recycled stale frame even though its CRC32 was valid, ftruncate(fd, off) + lseek(fd, off, SEEK_SET) healed both i_size and f_pos, and pread() served "1200mV" without disturbing the writer cursor!
Next in the Series — GL-C02: Filesystems, Signals, Processes & Threads: 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!
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 place?
- Step 1 (Encode a tombstone sentinel): Reserve
vlen == UINT32_MAX(with0payload value bytes on disk,frame_bytes = 24 + klen) or a 1-bitopflag inside the header covered byframe_crc(). - Step 2 (Update the in-memory offset index): During sequential replay in
main(), whenever a valid tombstone frame for"pll_hz"arrives, set its index entry toval_off = -1(deleted), soGETreturnsENOENTwhile historical frames remain immutable!
Independent Practice: Atomic WAL Log Compaction (compact_wal_at)
Over months of updates, an append-only WAL accumulates superseded frames. Write a C11 compaction routine int compact_wal_at(int dfd, const char *wal_name) that replays wal_name to build the live latest-key map, writes only live keys (seq = 1..K) into a fresh exclusive staging file via openat(dfd, "wal.compact.tmp", O_WRONLY | O_CREAT | O_EXCL | O_NOFOLLOW | O_CLOEXEC, 0644), flushes via fdatasync(tfd) + checked close(tfd), atomically swaps via renameat(dfd, "wal.compact.tmp", dfd, wal_name), and commits fsync(dfd).
Common Production Pitfalls
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.
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).
Knowledge Check
? check 1 · 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?
- [ ] Delete the entire WAL file and discard all
3committed frames - [x] Call
ftruncate(fd, 105)followed byfdatasync(fd)(and repositionf_pos = 105) to discard the uncommitted11-byte torn tail while preserving all3committed frames - [ ] Pad the missing tail bytes with
0x00so the 4th frame passes length checks
Answer: Call ftruncate(fd, 105) followed by fdatasync(fd) (and reposition f_pos = 105) to discard the uncommitted 11-byte torn tail while preserving all 3 committed frames
Why: 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.
? check 2 · 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?
- [ ] Because
pread()automatically returns the highest byte offset in an inode - [x] Because each
putappends a new immutable frame, and updating the in-memory offset table in replay order leaves each key pointing to its latest committed(val_off, val_len) - [ ] Because
ext4automatically deduplicates matching key strings inside kernel RAM
Answer: Because each put appends a new immutable frame, and updating the in-memory offset table in replay order leaves each key pointing to its latest committed (val_off, val_len)
Why: 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.
? check 3 · (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?
- [ ] Because
pread()allocates a privateFILE *stream per call - [x] Because
pread()reads at explicitval_offwithout reading or mutatingstruct file.f_pos, and committed frames belowvalid_offare immutable - [ ] Because
O_CLOEXECserializes readers and writers inside VFS
Answer: Because pread() reads at explicit val_off without reading or mutating struct file.f_pos, and committed frames below valid_off are immutable
Why: 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.
? check 4 · 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?
- [ ] Because reflected
CRC32cannot detect single-bit errors in ASCII keys - [x] Because recycling preallocated blocks without zero-wiping can leave an intact, valid-
CRC32frame from an older epoch right past the latest commit, which would replay as valid data withouth.seq == exp_seq - [ ] Because
fdatasync()requires an 8-byte counter at byte16of every write
Answer: Because recycling preallocated blocks without zero-wiping can leave an intact, valid-CRC32 frame from an older epoch right past the latest commit, which would replay as valid data without h.seq == exp_seq
Why: 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!
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.
Step sequence — frame strip: steps_m06_l03
Seal [seq, klen, vlen, key, val] inside a 24-byte header with branchless CRC32 and commit via write_all() + fdatasync().
reveals: step1
highlights: step1
Replay sequentially from offset 0 checking WAL_MAGIC, h.seq == exp_seq, subtraction bounds, and CRC32.
reveals: step2
highlights: step2
Snip stale recycled frames or torn crash tails via ftruncate(fd, off) + fdatasync(fd) + lseek(fd, off, SEEK_SET).
reveals: step3
highlights: step3
Serve latest committed values concurrently via stateless pread() while writer_fpos remains parked at EOF.
reveals: step4
highlights: step4