File Offsets & lseek Slicing
Reading right after writing on an O_RDWR descriptor returns zero bytes unless you understand the shared kernel offset f_pos, while opening an O_TRUNC output file before validating input slice bounds destroys existing data on failure. You will master 64-bit lseek(), SEEK_DATA/SEEK_HOLE, signed off_t overflow guards, and all five POSIX slicing patterns.
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.
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-l03→ open standalone lab workbench
1. 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
Key takeaways
- 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
errnounwinding, and sparse extent holes.