Lab 3: Sparse Partition Image Builder & Hole Inspector

50 minfree previewLinux 6.12C11glibc 2.39← module 3

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 -Werror and zero warnings.
  • Runtime behavior, exit status, and output match the automated ./check.sh assertions.
step 1/15

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-m03
learner@ksa:~/gl-c01/lab-m03ls -lastarter/sparse_img.clearner@ksa:~/gl-c01/lab-m03
starter: starter/sparse_img.c
learner@ksa: ~/gl-c01/lab-m03
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

  1. Construct a 4 MiB (4,194,304-byte) sparse partition image using lseek(fd, 4194240, SEEK_SET) so unallocated interior extents consume 0 physical disk blocks.
  2. Measure and verify logical length (st.st_size == 4194304) against physical sector allocation ((long long)st.st_blocks * 512LL < 131072) via fstat(), while proving VFS synthesizes 0x00 bytes on reads inside the hole.
  3. Demonstrate O_RDWR | O_APPEND asymmetry by proving lseek(afd, 0, SEEK_SET) positions read() at byte 0 ("KSA_SPARSE_SB_V1") while forcing write() atomically to EOF (4194304 + tag_len).

step 3/15 · 3. environment requirements

  • Host Execution Environment (Tested): Linux 6.12 LTS (x86_64, glibc 2.39+) on sparse-capable POSIX filesystems (ext4, XFS, Btrfs, or tmpfs).
  • Target Board Portability (ARMv7 Cortex-A7): #define _FILE_OFFSET_BITS 64 ensures off_t and struct stat (fstat64) handle >= 2 GiB sparse images identically on 32-bit ARMv7 ext4/f2fs root partitions (note: VFAT boot 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
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)

  1. Physical zero-fill loop: Calls write(fd, zero, 4096) 1,024 times, allocating 4,194,304 physical bytes (8,192 512-byte sectors) and failing phys_bytes < 131072.
  2. Missing O_TRUNC & O_CLOEXEC: Re-running over an existing larger image leaves trailing garbage intact, and descriptors leak on execve().
  3. Missing trailer, hole verification, and O_APPEND proof: Never writes the superblock/trailer markers or tests O_RDWR | O_APPEND.

Warning-Clean Reference (files/sparse_img.c)

  • Sparse Construction: Opens <img_path> with O_RDWR | O_CREAT | O_TRUNC | O_CLOEXEC (0644), writes 64-byte "KSA_SPARSE_SB_V1" (0x5A-padded) at 0, calls lseek(fd, 4194240, SEEK_SET) across the unallocated [64 .. 4194239] gap, and writes 64-byte "KSA_SPARSE_TR_V1" (0xA5-padded) at 4194240.
  • Hole & Sector Verification: Queries fstat(fd, &st), computes phys_bytes = (long long)st.st_blocks * 512LL (8,192 bytes = two 4 KiB blocks!), seeks to 2097152 (2 MiB), pre-fills hole_buf with 0xFF, and proves read_full() overwrites all 64 bytes with VFS-synthesized 0x00.
  • O_APPEND Asymmetry Proof: Reopens with O_RDWR | O_APPEND | O_CLOEXEC, seeks to 0 to read "KSA_SPARSE_SB_V1", seeks to 0 again before write_all(afd, append_tag, tag_len), and verifies byte 0 stayed "KSA_SPARSE_SB_V1" while st_size grew to 4194304 + tag_len!

step 7/15 · 7. expected output

learner@ksa: ~/gl-c01/lab-m03
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/5

step 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

  1. Extent Enumeration (filefrag / SEEK_DATA): Run filefrag -v /tmp/ksa_part.img (or add lseek(fd, 0, SEEK_HOLE) / lseek(fd, 4096, SEEK_DATA)) to inspect the exact physical extent ranges [0..4095] and [4190208..4194303].
  2. Naive cp Inflation Test: Compare cp --sparse=never /tmp/ksa_part.img /tmp/dense.img (du -h jumps to 4.0M!) against cp --sparse=always /tmp/ksa_part.img /tmp/sparse_copy.img (du -h stays 12K!).
  3. Punching Holes Dynamically (fallocate): On Linux (#define _GNU_SOURCE), test fallocate(fd, FALLOC_FL_PUNCH_HOLE | FALLOC_FL_KEEP_SIZE, 0, 4096) to deallocate block 0 back into a sparse hole without changing st_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):

MetricSparse 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() syscalls2 (3 with --append-tag)1,0242 (3 with --append-tag)

step 11/15 · 11. troubleshooting

SymptomRoot CauseFix
phys_bytes equals 4194304 or 33554432Wrote literal zero buffers, or multiplied st_blocks * st_blksize (4096) instead of 512Use lseek() across holes and multiply st.st_blocks * 512LL
superblock_ok=0 after --append-tagOpened afd without O_APPEND, allowing lseek(0) + write() to clobber byte 0Pass `O_RDWR \O_APPEND \O_CLOEXEC`
EOVERFLOW on > 2 GiB sparse offsets on 32-bit buildsMissing #define _FILE_OFFSET_BITS 64 before #includePlace #define _FILE_OFFSET_BITS 64 on line 1

step 12/15 · 12. guided questions

  1. Why does lseek(fd, 4194304, SEEK_SET) followed immediately by close(fd) (with NO write()) leave st_size == 0 instead of 4194304?
  • *Hint 1:* Which kernel structure does lseek() mutate (struct file.f_pos vs struct inode.i_size)?
  • *Hint 2:* Which syscall resizes inode->i_size to 4194304 without writing trailing payload bytes if your image ends with a sparse hole?
  1. Why did appending an 8-byte tag at offset 4,194,304 increase phys_bytes by 4,096 bytes (8 st_blocks units) instead of 8 bytes?
  • *Hint 1:* Offset 4,194,304 (4 MiB) sits at exact 4 KiB block index 1024 (4194304 / 4096 == 1024).
  • *Hint 2:* What is the minimum physical allocation unit of an ext4 / tmpfs page-backed filesystem?

step 13/15 · 13. independent challenges

  1. Near Transfer — Multi-Partition GPT-Style Sparse Table Builder: Extend sparse_img.c to accept <boot_bin> and <rootfs_bin> payloads placed at 1 MiB (1,048,576) and 64 MiB (67,108,864) inside a 512 MiB logical image, verifying via SEEK_DATA/SEEK_HOLE that exactly the non-zero regions are allocated.
  2. Far Transfer — Sparse Archive Serializer (--pack / --unpack): Build a sparse-aware archiver that scans any sparse image with SEEK_DATA/SEEK_HOLE, emits compact [uint64_t offset, uint64_t length, data...] records, and reconstructs an identical sparse target (st_size and st_blocks * 512 preserved).

step 14/15 · 14. solutions & explanations

  • Guided Question 1: lseek() updates only struct file.f_pos in RAM without touching struct inode.i_size; only a subsequent write() past i_size (or an explicit ftruncate(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 byte 0 of block 1024 allocates that entire 4 KiB block (phys_bytes rises from 8,192 to 12,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
learner@ksa:~/gl-c01/lab-m03./sparse_img part.img && ./sparse_img part.img --append-tag AUDIT_01learner@ksa:~/gl-c01/lab-m03
expected output
logical_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=1

Progressive 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

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:

./check.sh — lab m03
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/5

On an incomplete starter tree, ./check.sh exits non-zero and marks the unmet assertion not ok with an indented YAML diagnostic block:

./check.sh — lab m03 (starter)
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/5

note: 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
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.

Progress is saved on this device.

search — fzf

0/0 ───────────────────────────────────────────

keyboard shortcuts — less

/
search
f
focus mode
[
previous
]
next
?
help
Esc
close

figure