Lab 1: Symlink-Safe Directory Auditor & Atomic Manifest
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 -Werrorand zero warnings. - Runtime behavior, exit status, and output match the automated
./check.shassertions.
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-m01ls -lastarter/Makefilestarter/tree_auditor.cstarter/treeaudit.cstarter/treeaudit.hlearner@ksa:~/gl-c02/lab-m01starter: starter/Makefile
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_auditorstarter: starter/tree_auditor.c
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$ 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$ 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); #endifstep 2/15 · 2. learning objectives
- Archive a multi-file ISO C11 static library (
libtreeaudit.a) viaar rcsand link./tree_auditorwith zero warnings under-Wall -Wextra -Werror. - Traverse directory trees up to bounded depth
16usingopendir(),errno = 0+readdir(), andlstat()without recursing through symbolic links or"."/".."entries. - Classify regular files, hard-linked files (
st_nlink > 1), directories, valid symbolic links (readlink()with explicitbuf[n] = '\0'), and dangling symbolic links (stat() == -1 && errno == ENOENT). - Publish audit manifests crash-atomically on the same mount via sibling
<manifest_path>.tmpstaging,fsync(),close(), andrename()while preserving hard-linked backups.
step 3/15 · 3. environment requirements
- Host Execution (Verified): Linux 6.12 LTS POSIX user space (
x86_64orAArch64) 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,glibc2.34+), add-D_TIME_BITS=64alongside-D_FILE_OFFSET_BITS=64so 64-bitst_ino,off_t, andY2038-safestruct timespecfields remain wide across large partitions.
step 4/15 · 4. required software & hardware
- Software:
gcc(ISO C11 toolchain), GNUmake,ar(binutils), POSIX/bin/sh,coreutils(ln,mkdir,printf,cat,stat), andstrace(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$ 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_fixstep 6/15 · 6. annotated source code walkthrough
starter/Seeded Defects:starter/Makefilecompilestree_auditordirectly without archivingtreeaudit.ointolibtreeaudit.a(failing TAP test 2).starter/treeaudit.ccallsstat()instead oflstat()(recursing intosub/loop.lnk -> ..until depth abort), omits"."/".."filtering, callsreadlink(p, buf, sizeof(buf))withoutbuf[n] = '\0', and opensmanifest_pathwithO_WRONLY | O_CREAT | O_TRUNCin place—wiping hard-linkedmanifest.prev!files/Reference Architecture:files/Makefile: Compiles.oobjects with-std=c11 -Wall -Wextra -Werror -O2 -g, packagesar rcs libtreeaudit.a treeaudit.o, and linkstree_auditor.o libtreeaudit.a.treeaudit_scan_dir()(files/treeaudit.c): Setserrno = 0before everyreaddir(dp), skips"."and"..", callslstat()to classifyS_ISREG(st_nlink > 1->hardlinked_files++,total_reg_bytes += st_size),S_ISDIR(dirs++, bounded recursion), andS_ISLNK(readlink(..., sizeof(buf) - 1)+buf[n] = '\0'+stat()ENOENTcheck fordangling_links++).treeaudit_write_manifest_atomic()(files/treeaudit.c): Stages<manifest_path>.tmpin the same directory (st_devmatch), writes full report line, flushes data viafsync(fd), closesfd, and executesrename(tmp_path, manifest_path).
step 7/15 · 7. expected output
Broken starter/ Diagnostic Output (not ok)
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/5Verified Host Linux 6.12 files/ TAP-13 & CLI Output (ok)
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/5CLI verification output:
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_V0step 8/15 · 8. explanation of observed behavior
reg=3andbytes=42(16 + 16 + 10): Bothalpha.bin(16 B) andsub/alpha.hard(16 B) are regular directory entries sharing one inode withst_nlink == 2(hardlinked=2), plusnotes.txt(10 B).symlinks=3anddangling=1:lstat()stops atvalid.lnk,sub/loop.lnk, andbroken.lnk(S_ISLNKtrue). Calling follow-modestat()afterward returns0onvalid.lnkandloop.lnk, and-1(ENOENT) onbroken.lnk.manifest.prev == OLD_V0: Becauserename("manifest.txt.tmp", "manifest.txt")unlinked the old"manifest.txt"directory entry rather than truncating its inode,manifest.prev(st_nlinkdropping2 -> 1) preserved its originalOLD_V0payload untouched.
step 9/15 · 9. experiment variations
- FIFO & Socket Immunity: Add
mkfifo /tmp/ksa_lab01_fix/events.pipeinside the fixture and confirmlstat()classifiesS_ISFIFOwithout opening or blocking on a missing writer, leavingreg=3unchanged. - Cross-Mount
EXDEVFailure: Point stagingtmp_pathto/dev/shm/manifest.tmpwhilemanifest_pathsits on/tmp(or rootext4) and observerename()fail witherrno == EXDEVunderstrace -e trace=rename,renameat,renameat2. DT_UNKNOWNSimulation: Forcede->d_type = DT_UNKNOWNin memory and verifylstat()/fstatat(..., AT_SYMLINK_NOFOLLOW)still classifies every entry identically acrossXFSorNFS.
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_64NVMe /tmpfs, warm dcache):getdents64batches~1,000entries into2–4syscalls (32 KiBglibcbuffer), whilelstat/newfstatatexecutes1syscall per entry (p50 ~ 1.4 ms,p95 ~ 1.8 ms,p99 ~ 2.4 ms;fsyncon NVMe adds~0.3–1.2 ms). - 32-Bit ARMv7 Cortex-A7 (
528–900 MHz, raw eMMC/NAND): Expectp50 ~ 12–25 msfor1,000fstatat64/statxtransitions and5–20 msfor flashfsync()commit latency.
step 11/15 · 11. troubleshooting
| Symptom | Root Cause | Fix | ||
|---|---|---|---|---|
implicit declaration of function 'lstat' under -std=c11 | -std=c11 hides POSIX extensions unless feature-test macros precede headers | Place #define _XOPEN_SOURCE 700 at line 1 of treeaudit.c | ||
tree_auditor aborts on max depth or hangs | Used 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 report | Opened manifest_path in place with O_TRUNC | Write <manifest_path>.tmp, fsync(), close(), and rename() | ||
Undefined reference to treeaudit_scan_dir | Object archive order reversed on gcc command line | Place tree_auditor.o before libtreeaudit.a when linking |
step 12/15 · 12. guided questions
- Question 1 — Deduplicating Hard-Linked Byte Totals: Why did our specification report
bytes=42(16 + 16 + 10) acrossalpha.binandsub/alpha.hard, and what data structure is required ifdu-style physical deduplication (bytes=26) is needed?
- *Hint 1:* Check which
struct statfields remain identical across two hard links to the same file. - *Hint 2:* Track seen
(st_dev, st_ino)pairs wheneverst_nlink > 1so only the first link addsst_size!
- Question 2 — Parent Directory Crash Durability: After
fsync(tmp_fd)andrename(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_DIRECTORYand callfsync(dfd)afterrename().
step 13/15 · 13. independent challenges
- Near-Transfer Challenge (Descriptor-Relative
openat+fdopendir): Refactortreeaudit_scan_dir()intotreeaudit_scan_at(int dfd, ...)usingopenat(dfd, d_name, O_RDONLY | O_DIRECTORY | O_NOFOLLOW | O_CLOEXEC),fdopendir(),fstatat(..., AT_SYMLINK_NOFOLLOW), andreadlinkat()so zero path-string concatenation (snprintf("%s/%s")) is needed during traversal. - Far-Transfer Challenge (Mask-Scoped
statxFastpath): Replacelstat()with Linuxstatx(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 wheneverS_ISREG(st.st_mode) && st.st_nlink > 1; skip addingst.st_sizeif(st.st_dev, st.st_ino)is already present (st_inoalone can collide across mount points!). - Guided Q2 Solution: Extract the parent directory path (or anchor
atomic_saveonint dfd = open(dir, O_RDONLY | O_DIRECTORY | O_CLOEXEC)), runopenat->write->fsync(fd)->close(fd)->renameat(dfd, tmp, dfd, base), and finish withfsync(dfd)so journaled directory entries reach non-volatile storage. - Independent Challenge Key Insight:
openat(..., O_DIRECTORY | O_NOFOLLOW)eliminatesO(depth^2)kerneldentryprefix re-walks and eliminatesPATH_MAX(4096 B) stack buffer limits on deeply nested trees;AT_STATX_DONT_SYNCtells 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./tree_auditor ./fixture manifest.txt && cat manifest.prevlearner@ksa:~/gl-c02/lab-m01reg=3 dirs=1 symlinks=3 dangling=1 hardlinked=2 bytes=42OLD_V0Progressive 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
warning: Reveal the reference solution files? Running ./check.sh against your own attempt first builds stronger retention.
solution: files/Makefile
learner@ksa:~/gl-c02/lab-m01$ bat files/Makefile File: files/Makefile CC ?= gcc AR ?= ar CFLAGS := -std=c11 -Wall -Wextra -Werror -O2 -g .PHONY: all clean all: libtreeaudit.a tree_auditor treeaudit.o: treeaudit.c treeaudit.h $(CC) $(CFLAGS) -DTREEAUDIT_LIBRARY_BUILD -c treeaudit.c -o treeaudit.o libtreeaudit.a: treeaudit.o $(AR) rcs libtreeaudit.a treeaudit.o tree_auditor.o: tree_auditor.c treeaudit.h $(CC) $(CFLAGS) -DTREEAUDIT_LINK_ARCHIVE -c tree_auditor.c -o tree_auditor.o tree_auditor: tree_auditor.o libtreeaudit.a $(CC) $(CFLAGS) tree_auditor.o libtreeaudit.a -o tree_auditor clean: rm -f *.o libtreeaudit.a tree_auditor treeauditsolution: files/tree_auditor.c
learner@ksa:~/gl-c02/lab-m01$ bat files/tree_auditor.c File: files/tree_auditor.c #define _XOPEN_SOURCE 700 #define _FILE_OFFSET_BITS 64 #include "treeaudit.h" #include <stdio.h> #include <stdlib.h> #ifndef TREEAUDIT_LINK_ARCHIVE #define TREEAUDIT_LIBRARY_BUILD 1 #include "treeaudit.c" #endif int main(int argc, char *argv[]) { if (argc == 1) { struct tree_stats self_st; return (treeaudit_scan_dir(".", &self_st) == 0) ? EXIT_SUCCESS : EXIT_FAILURE; } if (argc != 3) { fprintf(stderr, "usage: %s <scan_dir> <manifest_path>\n", argv[0]); return EXIT_FAILURE; } struct tree_stats st; if (treeaudit_scan_dir(argv[1], &st) == -1) { perror("treeaudit_scan_dir"); return EXIT_FAILURE; } if (treeaudit_write_manifest_atomic(argv[2], &st) == -1) { perror("treeaudit_write_manifest_atomic"); return EXIT_FAILURE; } printf("reg=%u dirs=%u symlinks=%u dangling=%u hardlinked=%u bytes=%llu\n", st.reg_files, st.dirs, st.symlinks, st.dangling_links, st.hardlinked_files, st.total_reg_bytes); return EXIT_SUCCESS; }solution: files/treeaudit.c
learner@ksa:~/gl-c02/lab-m01$ bat files/treeaudit.c File: files/treeaudit.c #define _XOPEN_SOURCE 700 #define _FILE_OFFSET_BITS 64 #include "treeaudit.h" #include <dirent.h> #include <errno.h> #include <fcntl.h> #include <stdio.h> #include <string.h> #include <sys/stat.h> #include <sys/types.h> #include <unistd.h> static int scan_recursive(const char *dir_path, struct tree_stats *st, int depth) { if (depth > 16) { errno = ELOOP; return -1; } DIR *dp = opendir(dir_path); if (dp == NULL) { return -1; } for (;;) { errno = 0; struct dirent *de = readdir(dp); if (de == NULL) { if (errno != 0) { int saved = errno; (void)closedir(dp); errno = saved; return -1; } break; } if (strcmp(de->d_name, ".") == 0 || strcmp(de->d_name, "..") == 0) { continue; } char child[1024]; int n = snprintf(child, sizeof(child), "%s/%s", dir_path, de->d_name); if (n < 0 || (size_t)n >= sizeof(child)) { (void)closedir(dp); errno = ENAMETOOLONG; return -1; } struct stat lst; if (lstat(child, &lst) == -1) { int saved = errno; (void)closedir(dp); errno = saved; return -1; } if (S_ISREG(lst.st_mode)) { st->reg_files++; st->total_reg_bytes += (unsigned long long)lst.st_size; if (lst.st_nlink > 1U) { st->hardlinked_files++; } } else if (S_ISDIR(lst.st_mode)) { st->dirs++; if (scan_recursive(child, st, depth + 1) == -1) { int saved = errno; (void)closedir(dp); errno = saved; return -1; } } else if (S_ISLNK(lst.st_mode)) { st->symlinks++; char target[512]; ssize_t rl = readlink(child, target, sizeof(target) - 1U); if (rl < 0) { int saved = errno; (void)closedir(dp); errno = saved; return -1; } target[rl] = '\0'; struct stat tst; if (stat(child, &tst) == -1 && errno == ENOENT) { st->dangling_links++; } } } return closedir(dp); } int treeaudit_scan_dir(const char *root_path, struct tree_stats *out_stats) { if (root_path == NULL || out_stats == NULL) { errno = EINVAL; return -1; } memset(out_stats, 0, sizeof(*out_stats)); return scan_recursive(root_path, out_stats, 0); } int treeaudit_write_manifest_atomic(const char *manifest_path, const struct tree_stats *st) { if (manifest_path == NULL || st == NULL) { errno = EINVAL; return -1; } char tmp_path[1024]; int tn = snprintf(tmp_path, sizeof(tmp_path), "%s.tmp", manifest_path); if (tn < 0 || (size_t)tn >= sizeof(tmp_path)) { errno = ENAMETOOLONG; return -1; } char line[256]; int ln = snprintf( line, sizeof(line), "reg=%u dirs=%u symlinks=%u dangling=%u hardlinked=%u bytes=%llu\n", st->reg_files, st->dirs, st->symlinks, st->dangling_links, st->hardlinked_files, st->total_reg_bytes ); if (ln < 0 || (size_t)ln >= sizeof(line)) { errno = EOVERFLOW; return -1; } int fd = open(tmp_path, O_WRONLY | O_CREAT | O_TRUNC | O_CLOEXEC, 0644); if (fd == -1) { return -1; } size_t rem = (size_t)ln; const char *p = line; while (rem > 0U) { ssize_t w = write(fd, p, rem); if (w < 0) { if (errno == EINTR) { continue; } int saved = errno; (void)close(fd); (void)unlink(tmp_path); errno = saved; return -1; } p += (size_t)w; rem -= (size_t)w; } if (fsync(fd) == -1 || close(fd) == -1) { int saved = errno; (void)unlink(tmp_path); errno = saved; return -1; } if (rename(tmp_path, manifest_path) == -1) { int saved = errno; (void)unlink(tmp_path); errno = saved; return -1; } return 0; } #ifndef TREEAUDIT_LIBRARY_BUILD int main(void) { struct tree_stats st; return (treeaudit_scan_dir(".", &st) == 0) ? 0 : 1; } #endifsolution: files/treeaudit.h
learner@ksa:~/gl-c02/lab-m01$ bat files/treeaudit.h File: files/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); #endifRun 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:
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/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-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/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-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.