Lab 4: Race-Free Positional Record Store

45 minfree previewLinux 6.12C11glibc 2.39← module 4

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.

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

learner@ksa: ~/gl-c01/lab-m04
learner@ksa:~/gl-c01/lab-m04ls -lastarter/atomic_kv.clearner@ksa:~/gl-c01/lab-m04
starter: starter/atomic_kv.c
learner@ksa: ~/gl-c01/lab-m04
learner@ksa:~/gl-c01/lab-m04$ bat starter/atomic_kv.c File: starter/atomic_kv.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 <unistd.h>        enum { SLOT_BYTES = 64, KEY_MAX = 24, VAL_MAX = 39 };        struct slot_rec {        uint8_t active;        char key[KEY_MAX];        char val[VAL_MAX];    };        /*     * STARTER BASELINE (contains intentional systems bugs):     * 1. lock-check omits O_EXCL and O_CLOEXEC, failing duplicate-lock and fcntl checks.     * 2. put uses lseek() + write() instead of stateless pwrite(), mutating f_pos.     * 3. get and compact are not yet implemented.     */    int main(int argc, char **argv) {        if (argc < 3) {            return 2;        }        const char *cmd = argv[1];            if (strcmp(cmd, "lock-check") == 0 && argc == 3) {            int fd1 = open(argv[2], O_WRONLY | O_CREAT, 0600);            int fd2 = open(argv[2], O_WRONLY | O_CREAT, 0600);            if (fd1 >= 0) close(fd1);            if (fd2 >= 0) close(fd2);            unlink(argv[2]);            printf("LOCK_EXCL broken_duplicate_open_succeeded\n");            return 0;        }            if (strcmp(cmd, "init") == 0 && argc == 4) {            int fd = open(argv[2], O_RDWR | O_CREAT | O_TRUNC, 0644);            if (fd < 0) return 1;            close(fd);            printf("INIT slots=0 bytes=0\n");            return 0;        }            if (strcmp(cmd, "put") == 0 && argc == 6) {            long idx = strtol(argv[3], NULL, 10);            int fd = open(argv[2], O_RDWR);            if (fd < 0) return 1;            struct slot_rec rec;            memset(&rec, 0, sizeof(rec));            rec.active = 1U;            snprintf(rec.key, sizeof(rec.key), "%s", argv[4]);            snprintf(rec.val, sizeof(rec.val), "%s", argv[5]);            lseek(fd, (off_t)idx * SLOT_BYTES, SEEK_SET);            if (write(fd, &rec, sizeof(rec)) != (ssize_t)sizeof(rec)) {                close(fd);                return 1;            }            off_t cur = lseek(fd, 0, SEEK_CUR);            close(fd);            printf("PUT slot=%ld f_pos=%lld\n", idx, (long long)cur);            return 0;        }            fprintf(stderr, "unimplemented subcommand: %s\n", cmd);        return 1;    }

step 2/15 · 2. learning objectives

  1. Enforce atomic mutual exclusion across processes using open(..., O_WRONLY | O_CREAT | O_EXCL | O_CLOEXEC, 0600) and verify EEXIST rejection on collision.
  2. Verify per-descriptor FD_CLOEXEC (F_GETFD) and O_ACCMODE / clear O_APPEND status flags (F_GETFL) at runtime via fcntl().
  3. Execute short-count-safe pwrite_all() and pread_full() operations across 64-byte record slots while proving lseek(fd, 0, SEEK_CUR) == 0 stays untouched.
  4. Resize and compact the slot store cleanly using ftruncate(fd, keep_slots * 64).

step 3/15 · 3. environment requirements

  • Host Execution Environment (Tested): Linux 6.12 LTS (x86_64, glibc 2.39+), #define _POSIX_C_SOURCE 200809L and #define _FILE_OFFSET_BITS 64.
  • Target Board Portability (ARMv7 Cortex-A7): Fixed 64-byte uint8_t slot framing (active byte + char key[24] + char val[39], 0 compiler padding) and 64-bit pread/pwrite produce byte-identical database files across 32-bit ARMv7 and 64-bit x86_64 processes.

step 4/15 · 4. required software & hardware

  • Software Toolchain: gcc (-std=c11 -Wall -Wextra -Werror), strace, stat, and /bin/sh.
  • Hardware: Standard Linux host environment.

step 5/15 · 5. complete executable commands

Run from labs/lab_m04_atomic_kv/:

learner@ksa: ~/gl-c01/lab-m04
learner@ksa:~/gl-c01/lab-m04$ 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.

step 6/15 · 6. annotated source code (`starter/` flaws vs `files/` reference)

Flawed Baseline (starter/atomic_kv.c)

  1. Broken lockfile (lock-check): Calls open(argv[2], O_WRONLY | O_CREAT, 0600) without O_EXCL or O_CLOEXEC, allowing two processes to open the lock simultaneously!
  2. Stateful lseek() + write() (put): Mutates struct file.f_pos (f_pos=640 instead of 0), omits init ftruncate() sizing, and lacks bounds checks.
  3. Missing get and compact: Unimplemented subcommands fail tests 3–5.

Warning-Clean Reference (files/atomic_kv.c)

  • acquire_lock() / release_lock(): Formats <db_path>.lock via bounded snprintf() (ret < 0 || (size_t)ret >= cap) and acquires O_WRONLY | O_CREAT | O_EXCL | O_CLOEXEC (0600).
  • Flag Guard (put): Verifies (fl & O_APPEND) == 0 via fcntl(fd, F_GETFL)—critical on Linux because pwrite() ignores offset if O_APPEND is set!
  • Stateless Slot I/O (pwrite_all / pread_full): Transfers 64 bytes at (off_t)slot_idx * 64 while advancing (p + done, off + done) on short counts/EINTR, then confirms lseek(fd, 0, SEEK_CUR) == 0 and forces NUL termination (key[KEY_MAX - 1] = '\0') before printing untrusted disk bytes.

step 7/15 · 7. expected output

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

step 8/15 · 8. 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.

step 9/15 · 9. experiment variations

  1. Linux O_APPEND + pwrite() Quirk Reproduction: Temporarily add | O_APPEND to open() inside a scratch copy of put and observe pwrite(fd, raw, 64, 0) append at byte 1,024 instead of updating slot 0—proving why (fl & O_APPEND) != 0 must be rejected!
  2. Concurrent Reader/Writer Stress Test: Spawn 4 background reader loops running ./atomic_kv get ... 0 (100 iterations each) while a writer updates slot 0 between "v1" and "v2", verifying 0 torn strings or cursor errors.
  3. Stale Lockfile PID Inspection: Write the holder's getpid() into <db_path>.lock before releasing so operators debugging a crashed holder can check kill(pid, 0) (ESRCH).

step 10/15 · 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):

MetricMeasured 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 / get1 / 1 (0 f_pos mutations)1 / 1 (pread64/pwrite64 EABI register pair)

step 11/15 · 11. troubleshooting

SymptomRoot CauseFix
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=0Called stateful write() instead of pwrite()Use pwrite_all(fd, raw, 64, off)
fcntl(fd, F_SETFD, O_CLOEXEC) fails to set FD_CLOEXECPassed O_CLOEXEC (02000000) instead of FD_CLOEXEC (1) to F_SETFD!Pass O_CLOEXEC to open()/dup3(), and FD_CLOEXEC to fcntl(F_SETFD)!

step 12/15 · 12. guided questions

  1. Why must fcntl(fd, F_SETFD, ...) receive FD_CLOEXEC (1) whereas open() receives O_CLOEXEC (02000000)?
  • *Hint 1:* Recall the two VFS flag tiers from m04-l03 (files_struct per-slot bitmask vs open-time flags multiplexer).
  • *Hint 2:* Print (int)FD_CLOEXEC and (int)O_CLOEXEC in C: what happens to bit 0 (FD_CLOEXEC == 1) if you pass 02000000 (0x80000, bit 0 == 0!) to F_SETFD?
  1. Why does get defensively set key[KEY_MAX - 1] = '\0' after memcpy() from disk?
  • *Hint 1:* Can an untrusted or bit-flipped database file on disk contain 24 non-zero bytes in raw[1..24]?
  • *Hint 2:* What would printf("key=%s", key) do if key lacked a '\0' byte?

step 13/15 · 13. independent challenges

  1. Near Transfer — Advisory Byte-Range Slot Locks (F_SETLKW): Replace the coarse whole-file <db_path>.lock with per-slot struct flock byte-range locks (l_type = F_WRLCK, l_whence = SEEK_SET, l_start = slot_idx * 64, l_len = 64) via fcntl(fd, F_SETLKW, &fl) so writers updating disjoint slots run concurrently!
  2. Far Transfer — Directory-Pinned *at() Store Engine: Refactor atomic_kv.c to open its parent directory once (O_RDONLY | O_DIRECTORY | O_CLOEXEC) and execute all lockfile and database operations via openat() and unlinkat(), closing path-prefix symlink swap vectors.

step 14/15 · 14. solutions & explanations

  • Guided Question 1: FD_CLOEXEC equals 1 (bit 0), whereas O_CLOEXEC equals 0x80000 (bit 19, bit 0 == 0)! Passing O_CLOEXEC to F_SETFD actually clears FD_CLOEXEC to 0—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' and val[VAL_MAX - 1] = '\0' guarantees %s formatting can never overread stack memory even on a corrupted image.

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-m04
learner@ksa:~/gl-c01/lab-m04./atomic_kv init store.db 6 && ./atomic_kv put store.db 4 psu.vout 12100mV && ./atomic_kv get store.db 4learner@ksa:~/gl-c01/lab-m04
expected output
INIT slots=6 bytes=384PUT slot=4 f_pos=0GET slot=4 key=psu.vout val=12100mV f_pos=0

Progressive hints & solution

hint 1

Compare starter/atomic_kv.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_m04_atomic_kv/, run ./check.sh. A complete solution emits TAP version 13 with every test point marked ok and exits 0:

./check.sh — lab m04
learner@ksa:~/gl-c01/lab-m04./check.shTAP version 131..5ok 1 - builds with -std=c11 -Wall -Wextra and no warningsok 2 - enforces O_CREAT|O_EXCL|O_CLOEXEC lockfile check and unlinks lockok 3 - zero-extends 6-slot store to 384 bytes via ftruncateok 4 - performs stateless pwrite/pread slot I/O leaving f_pos at 0ok 5 - compacts store to 128 bytes via ftruncate while preserving slot 1# 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 m04 (starter)
learner@ksa:~/gl-c01/lab-m04./check.shTAP version 131..5ok 1 - builds with -std=c11 -Wall -Wextra and no warningsnot ok 2 - enforces O_CREAT|O_EXCL|O_CLOEXEC lockfile check and unlinks lock  ---  message: 'lock-check returned LOCK_EXCL broken_duplicate_open_succeeded (stale lock exists: no)'  hint: 'open with O_WRONLY|O_CREAT|O_EXCL|O_CLOEXEC, inspect F_GETFD/F_GETFL via fcntl(), and unlink before exit'  ...not ok 3 - zero-extends 6-slot store to 384 bytes via ftruncate  ---  message: 'init output= INIT slots=0 bytes=0 size=0, expected INIT slots=6 bytes=384 and 384 bytes'  hint: 'call ftruncate(fd, slots * 64) to size the backing file cleanly'  ...not ok 4 - performs stateless pwrite/pread slot I/O leaving f_pos at 0  ---  message: 'put= PUT slot=4 f_pos=320 get= empty inactive_rejected=1'  hint: 'use pwrite()/pread() at slot*64 without mutating f_pos and exit non-zero on inactive slots'  ...not ok 5 - compacts store to 128 bytes via ftruncate while preserving slot 1  ---  message: 'compact= empty size=320 slot1= empty'  hint: 'shrink store.db to keep_slots * 64 via ftruncate() without altering earlier slots'  ...# 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-m04
learner@ksa:~/gl-c01/lab-m04$ 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"        WORK="$(mktemp -d "${TMPDIR:-/tmp}/ksa_lab_m04.XXXXXX")"    trap 'rm -rf "$WORK"' EXIT        BUILT=0    if [ ! -f files/atomic_kv.c ]; then        tap_not_ok 1 "builds with -std=c11 -Wall -Wextra and no warnings" \            "missing files/atomic_kv.c" \            "place your implementation in files/atomic_kv.c"    elif gcc -std=c11 -Wall -Wextra -Werror files/atomic_kv.c -o "$WORK/atomic_kv" 2>"$WORK/gcc.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 "$WORK/gcc.err")" \            "fix all C11 warnings and errors in files/atomic_kv.c"    fi        LOCK_OUT=""    if [ "$BUILT" -eq 1 ]; then        LOCK_OUT="$(timeout 3 "$WORK/atomic_kv" lock-check "$WORK/test.lock" 2>/dev/null || true)"    fi    if [ "$LOCK_OUT" = "LOCK_EXCL ok cloexec=1 mode=O_WRONLY" ] && [ ! -e "$WORK/test.lock" ]; then        tap_ok 2 "enforces O_CREAT|O_EXCL|O_CLOEXEC lockfile check and unlinks lock"    else        tap_not_ok 2 "enforces O_CREAT|O_EXCL|O_CLOEXEC lockfile check and unlinks lock" \            "lock-check returned '${LOCK_OUT:-empty}' (stale lock exists: $([ -e "$WORK/test.lock" ] && echo yes || echo no))" \            "open with O_WRONLY|O_CREAT|O_EXCL|O_CLOEXEC, inspect F_GETFD/F_GETFL via fcntl(), and unlink before exit"    fi        INIT_OUT=""    INIT_BYTES=0    if [ "$BUILT" -eq 1 ]; then        INIT_OUT="$(timeout 3 "$WORK/atomic_kv" init "$WORK/store.db" 6 2>/dev/null || true)"        [ -f "$WORK/store.db" ] && INIT_BYTES="$(wc -c < "$WORK/store.db" | tr -d ' ')"    fi    if [ "$INIT_OUT" = "INIT slots=6 bytes=384" ] && [ "$INIT_BYTES" = "384" ]; then        tap_ok 3 "zero-extends 6-slot store to 384 bytes via ftruncate"    else        tap_not_ok 3 "zero-extends 6-slot store to 384 bytes via ftruncate" \            "init output='${INIT_OUT:-empty}' size=${INIT_BYTES}, expected 'INIT slots=6 bytes=384' and 384 bytes" \            "call ftruncate(fd, slots * 64) to size the backing file cleanly"    fi        PUT_OUT=""    GET_OUT=""    INACTIVE_OK=0    if [ "$BUILT" -eq 1 ] && [ -f "$WORK/store.db" ]; then        PUT_OUT="$(timeout 3 "$WORK/atomic_kv" put "$WORK/store.db" 4 "psu.vout" "12100mV" 2>/dev/null || true)"        timeout 3 "$WORK/atomic_kv" put "$WORK/store.db" 1 "fan.tach" "4200rpm" >/dev/null 2>&1 || true        GET_OUT="$(timeout 3 "$WORK/atomic_kv" get "$WORK/store.db" 4 2>/dev/null || true)"        if ! timeout 3 "$WORK/atomic_kv" get "$WORK/store.db" 2 >/dev/null 2>&1; then            INACTIVE_OK=1        fi    fi        if [ "$PUT_OUT" = "PUT slot=4 f_pos=0" ] && [ "$GET_OUT" = "GET slot=4 key=psu.vout val=12100mV f_pos=0" ] && [ "$INACTIVE_OK" -eq 1 ]; then        tap_ok 4 "performs stateless pwrite/pread slot I/O leaving f_pos at 0"    else        tap_not_ok 4 "performs stateless pwrite/pread slot I/O leaving f_pos at 0" \            "put='${PUT_OUT:-empty}' get='${GET_OUT:-empty}' inactive_rejected=${INACTIVE_OK}" \            "use pwrite()/pread() at slot*64 without mutating f_pos and exit non-zero on inactive slots"    fi        COMP_OUT=""    COMP_BYTES=0    GET1_OUT=""    SLOT4_GONE=0    if [ "$BUILT" -eq 1 ] && [ -f "$WORK/store.db" ]; then        COMP_OUT="$(timeout 3 "$WORK/atomic_kv" compact "$WORK/store.db" 2 2>/dev/null || true)"        COMP_BYTES="$(wc -c < "$WORK/store.db" | tr -d ' ')"        if ! timeout 3 "$WORK/atomic_kv" get "$WORK/store.db" 4 >/dev/null 2>&1; then            SLOT4_GONE=1        fi        GET1_OUT="$(timeout 3 "$WORK/atomic_kv" get "$WORK/store.db" 1 2>/dev/null || true)"    fi        if [ "$COMP_OUT" = "COMPACT bytes=128" ] && [ "$COMP_BYTES" = "128" ] && [ "$SLOT4_GONE" -eq 1 ] && [ "$GET1_OUT" = "GET slot=1 key=fan.tach val=4200rpm f_pos=0" ]; then        tap_ok 5 "compacts store to 128 bytes via ftruncate while preserving slot 1"    else        tap_not_ok 5 "compacts store to 128 bytes via ftruncate while preserving slot 1" \            "compact='${COMP_OUT:-empty}' size=${COMP_BYTES} slot1='${GET1_OUT:-empty}'" \            "shrink store.db to keep_slots * 64 via ftruncate() without altering earlier slots"    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_m04_atomic_kv/ 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