Lab 3: Sparse Partition Image Builder & Hole Inspector
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.
Prerequisites in this module
What ./check.sh verifies
- Clean C11 build with
-std=c11 -Wall -Wextra -Werrorand zero warnings. - Runtime behavior, exit status, and output match the automated
./check.shassertions.
step 1/15 · inspect starter files and specification
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.
learner@ksa:~/gl-c01/lab-m03ls -lastarter/sparse_img.clearner@ksa:~/gl-c01/lab-m03starter: starter/sparse_img.c
learner@ksa:~/gl-c01/lab-m03$ bat starter/sparse_img.c File: starter/sparse_img.c #include <fcntl.h> #include <stdio.h> #include <string.h> #include <unistd.h> /* BUGGY STARTER: * 1. Writes 4 MiB of physical zeros in a loop instead of lseek(), allocating full disk blocks! * 2. Missing O_TRUNC and O_CLOEXEC. * 3. Assumes lseek(fd, 0, SEEK_SET) lets write() overwrite offset 0 under O_APPEND. */ int main(int argc, char *argv[]) { if (argc < 2) { return 1; } int fd = open(argv[1], O_RDWR | O_CREAT, 0644); if (fd < 0) { return 1; } char zero[4096]; memset(zero, 0, sizeof(zero)); for (int i = 0; i < 1024; i++) { write(fd, zero, sizeof(zero)); } close(fd); return 0; }step 2/15 · 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).
step 3/15 · 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).
step 4/15 · 4. required software & hardware
- Software Toolchain:
gcc(-std=c11 -Wall -Wextra -Werror),stat,ls,du,strace, and/bin/sh. - Hardware: Standard Linux host environment.
step 5/15 · 5. complete executable commands
Run from labs/lab_m03_sparse_image/:
learner@ksa:~/gl-c01/lab-m03$ 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.
step 6/15 · 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!
step 7/15 · 7. expected output
learner@ksa:~/gl-c01/lab-m03$ 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/5step 8/15 · 8. 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.
step 9/15 · 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!
step 10/15 · 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) |
step 11/15 · 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 |
step 12/15 · 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?
step 13/15 · 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).
step 14/15 · 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).
step 15/15 · run verification and inspect output
Run the verification command and confirm the output matches the expected contract.
learner@ksa:~/gl-c01/lab-m03./sparse_img part.img && ./sparse_img part.img --append-tag AUDIT_01learner@ksa:~/gl-c01/lab-m03logical_size=4194304 phys_bytes=8192 hole_zero_ok=1 superblock_ok=1 append_eof_ok=1logical_size=4194312 phys_bytes=12288 hole_zero_ok=1 superblock_ok=1 append_eof_ok=1Progressive hints & solution
hint 1
Compare starter/sparse_img.c against the module lessons. Focus first on: Clean C11 build with -std=c11 -Wall -Wextra -Werror and zero warnings.
hint 2
Compile with -std=c11 -Wall -Wextra -Werror, check every system-call return value before touching output buffers, and verify cleanup on error paths.
solution
warning: Reveal the reference solution files? Running ./check.sh against your own attempt first builds stronger retention.
solution: files/sparse_img.c
learner@ksa:~/gl-c01/lab-m03$ bat files/sparse_img.c File: files/sparse_img.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> #define IMG_SIZE 4194304L #define BLOCK_META_SIZE 64U #define TRAILER_OFFSET (IMG_SIZE - (long)BLOCK_META_SIZE) #define HOLE_PROBE_OFFSET 2097152L 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(int argc, char *argv[]) { if (argc != 2 && argc != 4) { fprintf(stderr, "Usage: %s <img_path> [--append-tag <tag>]\n", argv[0]); return EXIT_FAILURE; } const char *img_path = argv[1]; const char *append_tag = NULL; if (argc == 4) { if (strcmp(argv[2], "--append-tag") != 0) { fprintf(stderr, "Unknown flag: %s\n", argv[2]); return EXIT_FAILURE; } append_tag = argv[3]; } int fd = open(img_path, O_RDWR | O_CREAT | O_TRUNC | O_CLOEXEC, S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH); if (fd == -1) { perror("open"); return EXIT_FAILURE; } uint8_t superblock[BLOCK_META_SIZE]; uint8_t trailer[BLOCK_META_SIZE]; memset(superblock, 0x5AU, sizeof(superblock)); memcpy(superblock, "KSA_SPARSE_SB_V1", 16U); memset(trailer, 0xA5U, sizeof(trailer)); memcpy(trailer, "KSA_SPARSE_TR_V1", 16U); if (write_all(fd, superblock, sizeof(superblock)) == -1) { perror("write superblock"); (void)close(fd); return EXIT_FAILURE; } if (lseek(fd, (off_t)TRAILER_OFFSET, SEEK_SET) == (off_t)-1) { perror("lseek trailer"); (void)close(fd); return EXIT_FAILURE; } if (write_all(fd, trailer, sizeof(trailer)) == -1) { perror("write trailer"); (void)close(fd); return EXIT_FAILURE; } struct stat st; if (fstat(fd, &st) == -1) { perror("fstat"); (void)close(fd); return EXIT_FAILURE; } if (lseek(fd, (off_t)HOLE_PROBE_OFFSET, SEEK_SET) == (off_t)-1) { perror("lseek hole"); (void)close(fd); return EXIT_FAILURE; } uint8_t hole_buf[BLOCK_META_SIZE]; memset(hole_buf, 0xFFU, sizeof(hole_buf)); ssize_t got = read_full(fd, hole_buf, sizeof(hole_buf)); if (got != (ssize_t)sizeof(hole_buf)) { fprintf(stderr, "short read inside sparse hole\n"); (void)close(fd); return EXIT_FAILURE; } int hole_zero_ok = 1; for (size_t i = 0; i < sizeof(hole_buf); i++) { if (hole_buf[i] != 0x00U) { hole_zero_ok = 0; break; } } if (close(fd) == -1) { perror("close"); return EXIT_FAILURE; } long long final_size = (long long)st.st_size; long long phys_bytes = (long long)st.st_blocks * 512LL; int superblock_ok = 1; int append_eof_ok = 1; if (append_tag != NULL) { size_t tag_len = strlen(append_tag); int afd = open(img_path, O_RDWR | O_APPEND | O_CLOEXEC); if (afd == -1) { perror("open O_APPEND"); return EXIT_FAILURE; } uint8_t check_sb[16]; if (lseek(afd, 0, SEEK_SET) == (off_t)-1 || read_full(afd, check_sb, sizeof(check_sb)) != (ssize_t)sizeof(check_sb)) { (void)close(afd); return EXIT_FAILURE; } superblock_ok = (memcmp(check_sb, "KSA_SPARSE_SB_V1", 16U) == 0) ? 1 : 0; /* Rewind f_pos to 0 before write: O_APPEND must still force write to EOF! */ if (lseek(afd, 0, SEEK_SET) == (off_t)-1 || write_all(afd, append_tag, tag_len) == -1) { (void)close(afd); return EXIT_FAILURE; } /* Confirm byte 0 was NOT overwritten and st_size grew by tag_len */ if (lseek(afd, 0, SEEK_SET) == (off_t)-1 || read_full(afd, check_sb, sizeof(check_sb)) != (ssize_t)sizeof(check_sb)) { (void)close(afd); return EXIT_FAILURE; } if (memcmp(check_sb, "KSA_SPARSE_SB_V1", 16U) != 0) { superblock_ok = 0; append_eof_ok = 0; } struct stat ast; if (fstat(afd, &ast) == -1) { (void)close(afd); return EXIT_FAILURE; } final_size = (long long)ast.st_size; phys_bytes = (long long)ast.st_blocks * 512LL; if (final_size != (long long)IMG_SIZE + (long long)tag_len) { append_eof_ok = 0; } if (close(afd) == -1) { perror("close O_APPEND"); return EXIT_FAILURE; } } if (!hole_zero_ok || !superblock_ok || !append_eof_ok || phys_bytes >= 131072LL) { fprintf(stderr, "verification failed: size=%lld phys=%lld hole_zero=%d sb=%d append=%d\n", final_size, phys_bytes, hole_zero_ok, superblock_ok, append_eof_ok); return EXIT_FAILURE; } printf("logical_size=%lld phys_bytes=%lld hole_zero_ok=%d superblock_ok=%d append_eof_ok=%d\n", final_size, phys_bytes, hole_zero_ok, superblock_ok, append_eof_ok); return EXIT_SUCCESS; }Run the check
From labs/lab_m03_sparse_image/, run ./check.sh. A complete solution emits TAP version 13 with every test point marked ok and exits 0:
learner@ksa:~/gl-c01/lab-m03./check.shTAP version 131..5ok 1 - builds with -std=c11 -Wall -Wextra and no warningsok 2 - truncates stale blocks and creates 4 MiB sparse image (< 128 KiB disk)ok 3 - writes superblock, reads VFS-zeroed hole at 2 MiB, and writes trailerok 4 - appends 8-byte AUDIT_01 tag at EOF under O_APPEND despite lseek(0)ok 5 - preserves offset-0 superblock intact across O_APPEND write# pass 5/5On an incomplete starter tree, ./check.sh exits non-zero and marks the unmet assertion not ok with an indented YAML diagnostic block:
learner@ksa:~/gl-c01/lab-m03./check.shTAP version 131..5ok 1 - builds with -std=c11 -Wall -Wextra and no warningsnot ok 2 - truncates stale blocks and creates 4 MiB sparse image (< 128 KiB disk) --- message: 'st_size=5242880 physical_bytes=5242880 (expected st_size=4194304 and physical < 131072)' hint: 'open with O_TRUNC and jump across the unallocated region via lseek() instead of writing zeros' ...not ok 3 - writes superblock, reads VFS-zeroed hole at 2 MiB, and writes trailer --- message: 'superblock at offset 0 mismatch: b \x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00' hint: 'verify hole readback at 2 MiB and print logical_size=4194304 ... hole_zero_ok=1 superblock_ok=1' ...not ok 4 - appends 8-byte AUDIT_01 tag at EOF under O_APPEND despite lseek(0) --- message: 'unexpected --append-tag output: empty' hint: 'verify that O_APPEND ignores lseek(fd, 0, SEEK_SET) on write() and advances size to 4194312' ...not ok 5 - preserves offset-0 superblock intact across O_APPEND write --- message: 'superblock after append was (tail= )' hint: 'open descriptor with O_WRONLY | O_APPEND | O_CLOEXEC so byte 0 is never overwritten' ...# pass 1/5note: How to read TAP diagnostics: 1..N states the total test plan; each ok k confirms a passed check; not ok k pinpoints the failing check alongside message: (what went wrong) and hint: (where to look next) between --- and ....
inspect harness: check.sh
learner@ksa:~/gl-c01/lab-m03$ bat check.sh File: check.sh #!/bin/sh set -u PASS=0 TOTAL=5 tap_ok() { PASS=$((PASS + 1)) printf 'ok %s - %s\n' "$1" "$2" } tap_not_ok() { msg=$(printf '%s' "$3" | tr "\n\r'" " " | sed "s/ */ /g; s/^ //; s/ \$//") hnt=$(printf '%s' "$4" | tr "\n\r'" " " | sed "s/ */ /g; s/^ //; s/ \$//") printf 'not ok %s - %s\n' "$1" "$2" printf ' ---\n' printf " message: '%s'\n" "$msg" printf " hint: '%s'\n" "$hnt" printf ' ...\n' } printf 'TAP version 13\n' printf '1..%s\n' "$TOTAL" SRC="files/sparse_img.c" WORKDIR="$(mktemp -d "${TMPDIR:-/tmp}/ksa_lab_m03.XXXXXX")" trap 'rm -rf "$WORKDIR"' EXIT BIN="$WORKDIR/sparse_img" BUILT=0 if [ ! -f "$SRC" ]; then tap_not_ok 1 "builds with -std=c11 -Wall -Wextra and no warnings" \ "missing source file $SRC" \ "place your implementation in files/sparse_img.c" elif gcc -std=c11 -Wall -Wextra -Werror "$SRC" -o "$BIN" 2>"$WORKDIR/cc.err"; then BUILT=1 tap_ok 1 "builds with -std=c11 -Wall -Wextra and no warnings" else tap_not_ok 1 "builds with -std=c11 -Wall -Wextra and no warnings" \ "gcc failed: $(cat "$WORKDIR/cc.err")" \ "fix all C11 warnings and errors in files/sparse_img.c" fi umask 0022 IMG="$WORKDIR/part.img" dd if=/dev/zero of="$IMG" bs=1048576 count=5 >/dev/null 2>&1 OUT1="" if [ "$BUILT" -eq 1 ]; then OUT1="$(timeout 3 "$BIN" "$IMG" 2>/dev/null || true)" fi SZ1="$(stat -c '%s' "$IMG" 2>/dev/null || echo 0)" BLOCKS1="$(stat -c '%b' "$IMG" 2>/dev/null || echo 99999)" PHYS1=$((BLOCKS1 * 512)) if [ "$BUILT" -eq 1 ] && [ "$SZ1" = "4194304" ] && [ "$PHYS1" -lt 131072 ] && grep -q "O_TRUNC" "$SRC" && grep -q "fstat" "$SRC"; then tap_ok 2 "truncates stale blocks and creates 4 MiB sparse image (< 128 KiB disk)" else tap_not_ok 2 "truncates stale blocks and creates 4 MiB sparse image (< 128 KiB disk)" \ "st_size=${SZ1} physical_bytes=${PHYS1} (expected st_size=4194304 and physical < 131072)" \ "open with O_TRUNC and jump across the unallocated region via lseek() instead of writing zeros" fi LAYOUT_ERR="$(python3 - "$IMG" <<'PY' import os, sys p = sys.argv[1] if not os.path.isfile(p) or os.path.getsize(p) < 4194304: print("image smaller than 4194304 bytes") sys.exit(0) with open(p, "rb") as f: sb = f.read(16) f.seek(2097152) hole = f.read(64) f.seek(4194240) tr = f.read(16) if sb != b"KSA_SPARSE_SB_V1": print(f"superblock at offset 0 mismatch: {sb!r}") elif hole != b"\x00" * 64: print("hole at 2 MiB did not read back as 64 zero bytes") elif tr != b"KSA_SPARSE_TR_V1": print(f"trailer at offset 4194240 mismatch: {tr!r}") PY )" case "$OUT1" in *"logical_size=4194304 "*hole_zero_ok=1*superblock_ok=1*) if [ -z "$LAYOUT_ERR" ]; then tap_ok 3 "writes superblock, reads VFS-zeroed hole at 2 MiB, and writes trailer" else tap_not_ok 3 "writes superblock, reads VFS-zeroed hole at 2 MiB, and writes trailer" \ "$LAYOUT_ERR" \ "write KSA_SPARSE_SB_V1 at 0 and KSA_SPARSE_TR_V1 at 4194240" fi ;; *) tap_not_ok 3 "writes superblock, reads VFS-zeroed hole at 2 MiB, and writes trailer" \ "${LAYOUT_ERR:-unexpected stdout: ${OUT1:-empty}}" \ "verify hole readback at 2 MiB and print logical_size=4194304 ... hole_zero_ok=1 superblock_ok=1" ;; esac OUT2="" if [ "$BUILT" -eq 1 ]; then OUT2="$(timeout 3 "$BIN" "$IMG" --append-tag "AUDIT_01" 2>/dev/null || true)" fi TAIL_TAG="$(python3 - "$IMG" <<'PY' import os, sys p = sys.argv[1] if os.path.isfile(p) and os.path.getsize(p) >= 4194312: with open(p, "rb") as f: f.seek(4194304) sys.stdout.write(f.read(8).decode("latin1")) PY )" case "$OUT2" in *"logical_size=4194312 "*append_eof_ok=1*) if [ "$TAIL_TAG" = "AUDIT_01" ]; then tap_ok 4 "appends 8-byte AUDIT_01 tag at EOF under O_APPEND despite lseek(0)" else tap_not_ok 4 "appends 8-byte AUDIT_01 tag at EOF under O_APPEND despite lseek(0)" \ "tail bytes at 4194304 were '${TAIL_TAG}', expected 'AUDIT_01'" \ "open with O_APPEND so kernel forces write() to current i_size (4194304)" fi ;; *) tap_not_ok 4 "appends 8-byte AUDIT_01 tag at EOF under O_APPEND despite lseek(0)" \ "unexpected --append-tag output: ${OUT2:-empty}" \ "verify that O_APPEND ignores lseek(fd, 0, SEEK_SET) on write() and advances size to 4194312" ;; esac SB_AFTER="$(python3 - "$IMG" <<'PY' import os, sys p = sys.argv[1] if os.path.isfile(p) and os.path.getsize(p) >= 16: with open(p, "rb") as f: sys.stdout.write(f.read(16).decode("latin1")) PY )" if [ "$BUILT" -eq 1 ] && [ "$SB_AFTER" = "KSA_SPARSE_SB_V1" ] && [ "$TAIL_TAG" = "AUDIT_01" ]; then tap_ok 5 "preserves offset-0 superblock intact across O_APPEND write" else tap_not_ok 5 "preserves offset-0 superblock intact across O_APPEND write" \ "superblock after append was '${SB_AFTER}' (tail='${TAIL_TAG}')" \ "open descriptor with O_WRONLY | O_APPEND | O_CLOEXEC so byte 0 is never overwritten" fi printf '# pass %s/%s\n' "$PASS" "$TOTAL" [ "$PASS" -eq "$TOTAL" ]Definition of done
Verification checklist
status: 0/3 checks verified
Troubleshooting
Compiler fails under -Werror on sign conversion or unused args
Use exact POSIX return types (ssize_t for read()/write(), size_t for byte counts) rather than relaxing flags.
./check.sh reports missing files in files/
Invoke ./check.sh from inside labs/lab_m03_sparse_image/ so relative paths to files/ resolve directly.