Lab 1: Symlink-Safe Directory Auditor & Atomic Manifest

50 minfree previewLinux 6.12C11glibc 2.39← module 1

Inspect Linux's seven VFS file types and struct stat inode fields via stat/fstat/lstat, manage UID/GID ownership, mode bits, special bits, and nanosecond utimensat/futimens timestamps without TOCTOU races, and build symlink-safe directory scanners with crash-atomic rename() updates.

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

Backup agents, firmware OTA verifiers, and container layer scanners fail catastrophically in production when written with naive filesystem calls: inspecting entries with stat() follows ln -s .. loop symbolic links into infinite recursion, reading symlinks with readlink() without explicit NUL termination leaks stack garbage, omitting errno = 0 before readdir() hides disk I/O errors, and rewriting manifest.txt in place with O_TRUNC wipes hard-linked manifest.prev rollback snapshots and leaves torn files on power loss. In this studio lab, you will build a static C11 library (libtreeaudit.a) and CLI (tree_auditor) that eliminate all four defects.

learner@ksa: ~/gl-c02/lab-m01
learner@ksa:~/gl-c02/lab-m01ls -lastarter/Makefilestarter/tree_auditor.cstarter/treeaudit.cstarter/treeaudit.hlearner@ksa:~/gl-c02/lab-m01
starter: starter/Makefile
learner@ksa: ~/gl-c02/lab-m01
learner@ksa:~/gl-c02/lab-m01$ bat starter/Makefile File: starter/Makefile    CC ?= gcc    CFLAGS := -O0        all: tree_auditor        # BUGGY STARTER:    # 1. Missing -std=c11 -Wall -Wextra -Werror    # 2. Does not build static archive libtreeaudit.a via ar rcs    tree_auditor: treeaudit.c tree_auditor.c    	$(CC) $(CFLAGS) treeaudit.c tree_auditor.c -o tree_auditor        clean:    	rm -f *.o tree_auditor
starter: starter/tree_auditor.c
learner@ksa: ~/gl-c02/lab-m01
learner@ksa:~/gl-c02/lab-m01$ bat starter/tree_auditor.c File: starter/tree_auditor.c    #include "treeaudit.h"    #include <stdio.h>    #include <stdlib.h>        int main(int argc, char *argv[]) {        if (argc < 3) {            return EXIT_FAILURE;        }        struct tree_stats st;        if (treeaudit_scan_dir(argv[1], &st) == -1) {            return EXIT_FAILURE;        }        if (treeaudit_write_manifest_atomic(argv[2], &st) == -1) {            return EXIT_FAILURE;        }        printf("reg=%u\n", st.reg_files);        return EXIT_SUCCESS;    }
starter: starter/treeaudit.c
learner@ksa: ~/gl-c02/lab-m01
learner@ksa:~/gl-c02/lab-m01$ bat starter/treeaudit.c File: starter/treeaudit.c    #define _XOPEN_SOURCE 700    #include "treeaudit.h"    #include <dirent.h>    #include <fcntl.h>    #include <stdio.h>    #include <string.h>    #include <sys/stat.h>    #include <unistd.h>        /* BUGGY STARTER:     * 1. Calls stat() instead of lstat(), following symlink loops and failing on dangling links!     * 2. Does not zero errno before readdir() and forgets to skip "." and ".."!     * 3. Overwrites manifest_path in place with O_TRUNC instead of staging .tmp + rename()!     */    int treeaudit_scan_dir(const char *root_path, struct tree_stats *out_stats) {        memset(out_stats, 0, sizeof(*out_stats));        DIR *dp = opendir(root_path);        if (dp == NULL) {            return -1;        }        struct dirent *de;        while ((de = readdir(dp)) != NULL) {            char child[512];            snprintf(child, sizeof(child), "%s/%s", root_path, de->d_name);            struct stat st;            if (stat(child, &st) == -1) {                closedir(dp);                return -1;            }            if (S_ISREG(st.st_mode)) {                out_stats->reg_files++;                out_stats->total_reg_bytes += (unsigned long long)st.st_size;            }        }        closedir(dp);        return 0;    }        int treeaudit_write_manifest_atomic(const char *manifest_path, const struct tree_stats *st) {        int fd = open(manifest_path, O_WRONLY | O_CREAT | O_TRUNC, 0644);        if (fd == -1) {            return -1;        }        char buf[128];        int n = snprintf(buf, sizeof(buf), "reg=%u\n", st->reg_files);        (void)write(fd, buf, (size_t)n);        close(fd);        return 0;    }
starter: starter/treeaudit.h
learner@ksa: ~/gl-c02/lab-m01
learner@ksa:~/gl-c02/lab-m01$ bat starter/treeaudit.h File: starter/treeaudit.h    #ifndef KSA_TREEAUDIT_H    #define KSA_TREEAUDIT_H        struct tree_stats {        unsigned int reg_files;        unsigned int dirs;        unsigned int symlinks;        unsigned int dangling_links;        unsigned int hardlinked_files;        unsigned long long total_reg_bytes;    };        int treeaudit_scan_dir(const char *root_path, struct tree_stats *out_stats);    int treeaudit_write_manifest_atomic(const char *manifest_path, const struct tree_stats *st);        #endif

step 2/15 · 2. learning objectives

  1. Archive a multi-file ISO C11 static library (libtreeaudit.a) via ar rcs and link ./tree_auditor with zero warnings under -Wall -Wextra -Werror.
  2. Traverse directory trees up to bounded depth 16 using opendir(), errno = 0 + readdir(), and lstat() without recursing through symbolic links or "."/".." entries.
  3. Classify regular files, hard-linked files (st_nlink > 1), directories, valid symbolic links (readlink() with explicit buf[n] = '\0'), and dangling symbolic links (stat() == -1 && errno == ENOENT).
  4. Publish audit manifests crash-atomically on the same mount via sibling <manifest_path>.tmp staging, fsync(), close(), and rename() while preserving hard-linked backups.

step 3/15 · 3. environment requirements

  • Host Execution (Verified): Linux 6.12 LTS POSIX user space (x86_64 or AArch64) running in an isolated temporary directory (_XOPEN_SOURCE 700, _FILE_OFFSET_BITS 64). No root privileges required.
  • 32-Bit ARMv7 Target Cross-Compile Note: When targeting 32-bit ARMv7 Cortex-A7 (arm-linux-gnueabihf-gcc, glibc 2.34+), add -D_TIME_BITS=64 alongside -D_FILE_OFFSET_BITS=64 so 64-bit st_ino, off_t, and Y2038-safe struct timespec fields remain wide across large partitions.

step 4/15 · 4. required software & hardware

  • Software: gcc (ISO C11 toolchain), GNU make, ar (binutils), POSIX /bin/sh, coreutils (ln, mkdir, printf, cat, stat), and strace (optional syscall verification).
  • Hardware: Standard Linux development workstation or container; zero external boards required.

step 5/15 · 5. complete executable commands

Run each step from course_creator/courses/linux-c-proc-threads/labs/lab_m01_tree_auditor/:

learner@ksa: ~/gl-c02/lab-m01
learner@ksa:~/gl-c02/lab-m01$ bat script.sh File: script.sh    # 1. Run the TAP-13 harness against starter/ (optional sanity check) or verify files/:    #    check.sh compiles the workspace, checks ar t libtreeaudit.a, builds a symlink-loop fixture,    #    and verifies atomic rename() preservation of hard-linked manifest.prev.    sh check.sh        # 2. Build the multi-file library and CLI cleanly in files/ to verify strict C11 flags:    make -C files clean && make -C files        # 3. Inspect the static archive symbol index to confirm treeaudit.o is packaged inside libtreeaudit.a:    ar t files/libtreeaudit.a        # 4. Construct a local test fixture with a hard link, valid symlink, directory loop, and broken link:    rm -rf /tmp/ksa_lab01_fix && mkdir -p /tmp/ksa_lab01_fix/sub    printf '0123456789abcdef' > /tmp/ksa_lab01_fix/alpha.bin    ln /tmp/ksa_lab01_fix/alpha.bin /tmp/ksa_lab01_fix/sub/alpha.hard    printf '0123456789' > /tmp/ksa_lab01_fix/notes.txt    ln -s alpha.bin /tmp/ksa_lab01_fix/valid.lnk    ln -s .. /tmp/ksa_lab01_fix/sub/loop.lnk    ln -s missing /tmp/ksa_lab01_fix/broken.lnk    printf 'OLD_V0\n' > /tmp/ksa_lab01_fix/manifest.txt    ln /tmp/ksa_lab01_fix/manifest.txt /tmp/ksa_lab01_fix/manifest.prev        # 5. Execute tree_auditor and verify manifest.prev still holds OLD_V0 across atomic rename():    ./files/tree_auditor /tmp/ksa_lab01_fix /tmp/ksa_lab01_fix/manifest.txt    cat /tmp/ksa_lab01_fix/manifest.prev    rm -rf /tmp/ksa_lab01_fix

step 6/15 · 6. annotated source code walkthrough

  • starter/ Seeded Defects:
  • starter/Makefile compiles tree_auditor directly without archiving treeaudit.o into libtreeaudit.a (failing TAP test 2).
  • starter/treeaudit.c calls stat() instead of lstat() (recursing into sub/loop.lnk -> .. until depth abort), omits "."/".." filtering, calls readlink(p, buf, sizeof(buf)) without buf[n] = '\0', and opens manifest_path with O_WRONLY | O_CREAT | O_TRUNC in place—wiping hard-linked manifest.prev!
  • files/ Reference Architecture:
  • files/Makefile: Compiles .o objects with -std=c11 -Wall -Wextra -Werror -O2 -g, packages ar rcs libtreeaudit.a treeaudit.o, and links tree_auditor.o libtreeaudit.a.
  • treeaudit_scan_dir() (files/treeaudit.c): Sets errno = 0 before every readdir(dp), skips "." and "..", calls lstat() to classify S_ISREG (st_nlink > 1 -> hardlinked_files++, total_reg_bytes += st_size), S_ISDIR (dirs++, bounded recursion), and S_ISLNK (readlink(..., sizeof(buf) - 1) + buf[n] = '\0' + stat() ENOENT check for dangling_links++).
  • treeaudit_write_manifest_atomic() (files/treeaudit.c): Stages <manifest_path>.tmp in the same directory (st_dev match), writes full report line, flushes data via fsync(fd), closes fd, and executes rename(tmp_path, manifest_path).

step 7/15 · 7. expected output

Broken starter/ Diagnostic Output (not ok)

learner@ksa: ~/gl-c02/lab-m01
learner@ksa:~/gl-c02/lab-m01$ bat listing.txt File: listing.txt    TAP version 13    1..5    ok 1 - builds with -std=c11 -Wall -Wextra and no warnings    not ok 2 - archives treeaudit.o into static library libtreeaudit.a    not ok 3 - audits tree across symlink cycles, dangling links, and hard links    not ok 4 - writes manifest.txt and leaves no temporary staging file behind    not ok 5 - replaces manifest atomically via rename() preserving hard-linked backup    # pass 1/5

Verified Host Linux 6.12 files/ TAP-13 & CLI Output (ok)

learner@ksa: ~/gl-c02/lab-m01
learner@ksa:~/gl-c02/lab-m01$ bat listing.txt File: listing.txt    TAP version 13    1..5    ok 1 - builds with -std=c11 -Wall -Wextra and no warnings    ok 2 - archives treeaudit.o into static library libtreeaudit.a    ok 3 - audits tree across symlink cycles, dangling links, and hard links    ok 4 - writes manifest.txt and leaves no temporary staging file behind    ok 5 - replaces manifest atomically via rename() preserving hard-linked backup    # pass 5/5

CLI verification output:

learner@ksa: ~/gl-c02/lab-m01
learner@ksa:~/gl-c02/lab-m01$ bat listing.txt File: listing.txt    reg=3 dirs=1 symlinks=3 dangling=1 hardlinked=2 bytes=42    OLD_V0

step 8/15 · 8. explanation of observed behavior

  • reg=3 and bytes=42 (16 + 16 + 10): Both alpha.bin (16 B) and sub/alpha.hard (16 B) are regular directory entries sharing one inode with st_nlink == 2 (hardlinked=2), plus notes.txt (10 B).
  • symlinks=3 and dangling=1: lstat() stops at valid.lnk, sub/loop.lnk, and broken.lnk (S_ISLNK true). Calling follow-mode stat() afterward returns 0 on valid.lnk and loop.lnk, and -1 (ENOENT) on broken.lnk.
  • manifest.prev == OLD_V0: Because rename("manifest.txt.tmp", "manifest.txt") unlinked the old "manifest.txt" directory entry rather than truncating its inode, manifest.prev (st_nlink dropping 2 -> 1) preserved its original OLD_V0 payload untouched.

step 9/15 · 9. experiment variations

  1. FIFO & Socket Immunity: Add mkfifo /tmp/ksa_lab01_fix/events.pipe inside the fixture and confirm lstat() classifies S_ISFIFO without opening or blocking on a missing writer, leaving reg=3 unchanged.
  2. Cross-Mount EXDEV Failure: Point staging tmp_path to /dev/shm/manifest.tmp while manifest_path sits on /tmp (or root ext4) and observe rename() fail with errno == EXDEV under strace -e trace=rename,renameat,renameat2.
  3. DT_UNKNOWN Simulation: Force de->d_type = DT_UNKNOWN in memory and verify lstat() / fstatat(..., AT_SYMLINK_NOFOLLOW) still classifies every entry identically across XFS or NFS.

step 10/15 · 10. performance measurements

Benchmark tree_auditor over a 1,000-file synthetic tree using CLOCK_MONOTONIC (3 warm-up runs to populate VFS dentry cache, followed by N = 31 timed runs) and inspect syscall counts via strace -c ./files/tree_auditor /tmp/bench_tree /tmp/bench.manifest:

  • Host Linux 6.12 (x86_64 NVMe / tmpfs, warm dcache): getdents64 batches ~1,000 entries into 2–4 syscalls (32 KiB glibc buffer), while lstat/newfstatat executes 1 syscall per entry (p50 ~ 1.4 ms, p95 ~ 1.8 ms, p99 ~ 2.4 ms; fsync on NVMe adds ~0.3–1.2 ms).
  • 32-Bit ARMv7 Cortex-A7 (528–900 MHz, raw eMMC/NAND): Expect p50 ~ 12–25 ms for 1,000 fstatat64/statx transitions and 5–20 ms for flash fsync() commit latency.

step 11/15 · 11. troubleshooting

SymptomRoot CauseFix
implicit declaration of function 'lstat' under -std=c11-std=c11 hides POSIX extensions unless feature-test macros precede headersPlace #define _XOPEN_SOURCE 700 at line 1 of treeaudit.c
tree_auditor aborts on max depth or hangsUsed stat() instead of lstat(), or forgot to skip "." and ".."Switch entry probe to lstat() and skip `strcmp(d_name, ".") == 0 \\strcmp(d_name, "..") == 0`
manifest.prev overwritten with new reportOpened manifest_path in place with O_TRUNCWrite <manifest_path>.tmp, fsync(), close(), and rename()
Undefined reference to treeaudit_scan_dirObject archive order reversed on gcc command linePlace tree_auditor.o before libtreeaudit.a when linking

step 12/15 · 12. guided questions

  1. Question 1 — Deduplicating Hard-Linked Byte Totals: Why did our specification report bytes=42 (16 + 16 + 10) across alpha.bin and sub/alpha.hard, and what data structure is required if du-style physical deduplication (bytes=26) is needed?
  • *Hint 1:* Check which struct stat fields remain identical across two hard links to the same file.
  • *Hint 2:* Track seen (st_dev, st_ino) pairs whenever st_nlink > 1 so only the first link adds st_size!
  1. Question 2 — Parent Directory Crash Durability: After fsync(tmp_fd) and rename(tmp, dst) succeed, what single crash window remains before power loss, and how do you close it?
  • *Hint 1:* Recall Figure 1.3a—rename() mutates the parent directory's [d_ino, d_name] block in page cache.
  • *Hint 2:* Open the parent directory with O_RDONLY | O_DIRECTORY and call fsync(dfd) after rename().

step 13/15 · 13. independent challenges

  • Near-Transfer Challenge (Descriptor-Relative openat + fdopendir): Refactor treeaudit_scan_dir() into treeaudit_scan_at(int dfd, ...) using openat(dfd, d_name, O_RDONLY | O_DIRECTORY | O_NOFOLLOW | O_CLOEXEC), fdopendir(), fstatat(..., AT_SYMLINK_NOFOLLOW), and readlinkat() so zero path-string concatenation (snprintf("%s/%s")) is needed during traversal.
  • Far-Transfer Challenge (Mask-Scoped statx Fastpath): Replace lstat() with Linux statx(dfd, d_name, AT_SYMLINK_NOFOLLOW | AT_STATX_DONT_SYNC, STATX_TYPE | STATX_NLINK | STATX_SIZE | STATX_INO, &sx) (#define _GNU_SOURCE) and measure RPC savings on a network/FUSE mount.

step 14/15 · 14. solutions & explanations

  • Guided Q1 Solution: Maintain an open-addressed hash table of struct { dev_t dev; ino_t ino; } keys inserted whenever S_ISREG(st.st_mode) && st.st_nlink > 1; skip adding st.st_size if (st.st_dev, st.st_ino) is already present (st_ino alone can collide across mount points!).
  • Guided Q2 Solution: Extract the parent directory path (or anchor atomic_save on int dfd = open(dir, O_RDONLY | O_DIRECTORY | O_CLOEXEC)), run openat -> write -> fsync(fd) -> close(fd) -> renameat(dfd, tmp, dfd, base), and finish with fsync(dfd) so journaled directory entries reach non-volatile storage.
  • Independent Challenge Key Insight: openat(..., O_DIRECTORY | O_NOFOLLOW) eliminates O(depth^2) kernel dentry prefix re-walks and eliminates PATH_MAX (4096 B) stack buffer limits on deeply nested trees; AT_STATX_DONT_SYNC tells distributed filesystems to return cached attributes without round-tripping to remote metadata servers.

step 15/15 · run verification and inspect output

Run the verification command and confirm the output matches the expected contract.

learner@ksa: ~/gl-c02/lab-m01
learner@ksa:~/gl-c02/lab-m01./tree_auditor ./fixture manifest.txt && cat manifest.prevlearner@ksa:~/gl-c02/lab-m01
expected output
reg=3 dirs=1 symlinks=3 dangling=1 hardlinked=2 bytes=42OLD_V0

Progressive hints & solution

hint 1

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

./check.sh — lab m01
learner@ksa:~/gl-c02/lab-m01./check.shTAP version 131..5ok 1 - builds with -std=c11 -Wall -Wextra and no warningsok 2 - archives treeaudit.o into static library libtreeaudit.aok 3 - audits tree across symlink cycles, dangling links, and hard linksok 4 - writes manifest.txt and leaves no temporary staging file behindok 5 - replaces manifest atomically via rename() preserving hard-linked backup# 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 m01 (starter)
learner@ksa:~/gl-c02/lab-m01./check.shTAP version 131..5ok 1 - builds with -std=c11 -Wall -Wextra and no warningsnot ok 2 - archives treeaudit.o into static library libtreeaudit.a  ---  message: 'Makefile did not build static archive libtreeaudit.a containing treeaudit.o'  hint: 'compile treeaudit.c with -c and archive via ar rcs libtreeaudit.a treeaudit.o'  ...not ok 3 - audits tree across symlink cycles, dangling links, and hard links  ---  message: 'tree_auditor rc=1 stdout= empty , expected reg=3 dirs=1 symlinks=3 dangling=1 hardlinked=2 bytes=42'  hint: 'inspect entries with lstat(), skip . and .. , NUL-terminate readlink(), and detect dangling targets'  ...not ok 4 - writes manifest.txt and leaves no temporary staging file behind  ---  message: 'manifest= OLD_V0 tmp_present=no'  hint: 'stage into sibling .tmp file, flush with fsync(), and replace target via rename()'  ...not ok 5 - replaces manifest atomically via rename() preserving hard-linked backup  ---  message: 'manifest.prev held OLD_V0 instead of OLD_V0'  hint: 'never open manifest.txt with O_TRUNC in place; write manifest.txt.tmp and call rename()'  ...# 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-c02/lab-m01
learner@ksa:~/gl-c02/lab-m01$ 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"        WORKDIR="$(mktemp -d "${TMPDIR:-/tmp}/ksa_lab_c02_m01.XXXXXX")"    trap 'rm -rf "$WORKDIR"' EXIT        MISSING=""    for req in files/Makefile files/treeaudit.h files/treeaudit.c files/tree_auditor.c; do        if [ ! -f "$req" ]; then            MISSING="$MISSING $req"        fi    done        BUILT=0    if [ -n "$MISSING" ]; then        tap_not_ok 1 "builds with -std=c11 -Wall -Wextra and no warnings" \            "missing required files:$MISSING" \            "keep Makefile, treeaudit.h, treeaudit.c, and tree_auditor.c inside files/"    else        cp -R files "$WORKDIR/build"        if ! make -C "$WORKDIR/build" clean >"$WORKDIR/make_clean.out" 2>&1; then            tap_not_ok 1 "builds with -std=c11 -Wall -Wextra and no warnings" \                "make clean failed in files/Makefile" \                "define a clean target removing *.o, libtreeaudit.a, and tree_auditor"        elif ! make -C "$WORKDIR/build" >"$WORKDIR/make.out" 2>"$WORKDIR/make.err"; then            tap_not_ok 1 "builds with -std=c11 -Wall -Wextra and no warnings" \                "make failed: $(cat "$WORKDIR/make.err")" \                "fix all C11 warnings and errors in files/"        else            [ -x "$WORKDIR/build/tree_auditor" ] && BUILT=1            if grep -q -- '-std=c11' files/Makefile && grep -q -- '-Wall' files/Makefile && grep -q -- '-Wextra' files/Makefile && [ "$BUILT" -eq 1 ]; then                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" \                    "Makefile built without strict -std=c11 -Wall -Wextra flags" \                    "set CFLAGS = -std=c11 -Wall -Wextra -Werror in files/Makefile"            fi        fi    fi        if [ -f "$WORKDIR/build/libtreeaudit.a" ] && ar t "$WORKDIR/build/libtreeaudit.a" 2>/dev/null | grep -q "treeaudit.o"; then        tap_ok 2 "archives treeaudit.o into static library libtreeaudit.a"    else        tap_not_ok 2 "archives treeaudit.o into static library libtreeaudit.a" \            "Makefile did not build static archive libtreeaudit.a containing treeaudit.o" \            "compile treeaudit.c with -c and archive via ar rcs libtreeaudit.a treeaudit.o"    fi        FIX="$WORKDIR/fixture"    mkdir -p "$FIX/sub"    printf "0123456789abcdef" >"$FIX/alpha.bin"    ln "$FIX/alpha.bin" "$FIX/sub/alpha.hard"    printf "0123456789" >"$FIX/notes.txt"    ln -s "alpha.bin" "$FIX/valid.lnk"    ln -s ".." "$FIX/sub/loop.lnk"    ln -s "does_not_exist" "$FIX/broken.lnk"        MANIFEST="$WORKDIR/manifest.txt"    PREV_LINK="$WORKDIR/manifest.prev"    printf "OLD_V0\n" >"$MANIFEST"    ln "$MANIFEST" "$PREV_LINK"        EXPECTED="reg=3 dirs=1 symlinks=3 dangling=1 hardlinked=2 bytes=42"    OUT=""    RUN_RC=1    if [ "$BUILT" -eq 1 ]; then        OUT="$(timeout 3 "$WORKDIR/build/tree_auditor" "$FIX" "$MANIFEST" 2>/dev/null)"        RUN_RC=$?    fi        if [ "$RUN_RC" -eq 0 ] && [ "$OUT" = "$EXPECTED" ]; then        tap_ok 3 "audits tree across symlink cycles, dangling links, and hard links"    else        tap_not_ok 3 "audits tree across symlink cycles, dangling links, and hard links" \            "tree_auditor rc=${RUN_RC} stdout='${OUT:-empty}', expected '${EXPECTED}'" \            "inspect entries with lstat(), skip '.' and '..', NUL-terminate readlink(), and detect dangling targets"    fi        FILE_CONTENT=""    [ -f "$MANIFEST" ] && FILE_CONTENT="$(tr -d '\r\n' < "$MANIFEST")"    if [ "$RUN_RC" -eq 0 ] && [ ! -e "$MANIFEST.tmp" ] && [ "$FILE_CONTENT" = "$EXPECTED" ]; then        tap_ok 4 "writes manifest.txt and leaves no temporary staging file behind"    else        tap_not_ok 4 "writes manifest.txt and leaves no temporary staging file behind" \            "manifest='${FILE_CONTENT:-empty}' tmp_present=$([ -e "$MANIFEST.tmp" ] && echo yes || echo no)" \            "stage into sibling .tmp file, flush with fsync(), and replace target via rename()"    fi        PREV_CONTENT=""    [ -f "$PREV_LINK" ] && PREV_CONTENT="$(tr -d '\r\n' < "$PREV_LINK")"    if [ "$RUN_RC" -eq 0 ] && [ "$FILE_CONTENT" = "$EXPECTED" ] && [ "$PREV_CONTENT" = "OLD_V0" ]; then        tap_ok 5 "replaces manifest atomically via rename() preserving hard-linked backup"    else        tap_not_ok 5 "replaces manifest atomically via rename() preserving hard-linked backup" \            "manifest.prev held '${PREV_CONTENT:-empty}' instead of 'OLD_V0'" \            "never open manifest.txt with O_TRUNC in place; write manifest.txt.tmp and call rename()"    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_m01_tree_auditor/ 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