Lab 1: Multi-File C11 Static Archive & Syscall Boundary Tracer
Onboard into the 4-course Linux Systems C series across Ring 3 / Ring 0 hardware boundaries, master the 4-stage GCC/Make C11 toolchain and POSIX boundary types, and trace glibc wrappers, CRT startup, and errno diagnostics under strace.
Prerequisites in this module
What ./check.sh verifies
- Clean C11 build with
-std=c11 -Wall -Wextra -Werrorand zero warnings. - Runtime behavior, exit status, and output match the automated
./check.shassertions.
step 1/15 · inspect starter files and specification
Embedded and infrastructure teams routinely ship corrupted binary packets or crash in production because a framing helper called strlen() on a payload containing 0x00 bytes, stored write()'s signed ssize_t -1 error in unsigned size_t (wrapping to SIZE_MAX), or compiled without -Wall -Wextra -Werror across separate translation units. In this studio laboratory, you will engineer a warning-clean multi-file ISO C11 static library (libsysbuf.a) and CLI boundary tracer (inspector) that strictly separates zero-syscall Ring 3 framing from EINTR-resilient Ring 0 write() transfers and errno validation.
learner@ksa:~/gl-c01/lab-m01ls -lastarter/Makefilestarter/inspector.cstarter/sysbuf.cstarter/sysbuf.hlearner@ksa:~/gl-c01/lab-m01starter: starter/Makefile
learner@ksa:~/gl-c01/lab-m01$ bat starter/Makefile File: starter/Makefile # Starter Makefile (BUGGY: missing C11/Werror flags and missing libsysbuf.a archive rule) CC = gcc all: $(CC) inspector.c sysbuf.c -o inspector clean: rm -f inspector *.ostarter: starter/inspector.c
learner@ksa:~/gl-c01/lab-m01$ bat starter/inspector.c File: starter/inspector.c #include "sysbuf.h" #include <stdio.h> #include <string.h> #include <unistd.h> /* BUGGY STARTER: * 1. Dereferences argv[1] without checking argc > 1! * 2. Ignores signed error return (-1) and errno on invalid descriptor -1! * 3. Issues multiple printf() calls instead of one framed write(STDOUT_FILENO, ...). */ int main(int argc, char *argv[]) { (void)argc; uint8_t payload[8] = {0x4BU, 0x00U, 0x53U, 0x00U, 0x41U, 0x01U, 0xFEU, 0x10U}; uint8_t frame[24]; sysbuf_encode_header(frame, 7U, payload, sizeof(payload)); if (strcmp(argv[1], "--raw") == 0) { sysbuf_write_all(STDOUT_FILENO, frame, sizeof(frame)); return 0; } printf("frame_bytes=%zu\n", sizeof(frame)); printf("done\n"); return 0; }starter: starter/sysbuf.c
learner@ksa:~/gl-c01/lab-m01$ bat starter/sysbuf.c File: starter/sysbuf.c #include "sysbuf.h" #include <string.h> #include <unistd.h> /* BUGGY STARTER: * 1. Uses strlen() on binary payload, stopping at the first 0x00 byte! * 2. Stores write() return value in unsigned size_t (-1 wraps to SIZE_MAX) * and ignores partial counts and EINTR! */ size_t sysbuf_encode_header(uint8_t dst[SYSBUF_HDR_SIZE], uint16_t channel, const uint8_t *payload, size_t payload_len) { (void)payload_len; size_t wrong_len = strlen((const char *)payload); memset(dst, 0, SYSBUF_HDR_SIZE); memcpy(dst, "KSB1", 4); dst[4] = (uint8_t)(channel >> 8); dst[5] = (uint8_t)(channel & 0xFFU); dst[7] = (uint8_t)wrong_len; return SYSBUF_HDR_SIZE; } int sysbuf_write_all(int fd, const void *buf, size_t count) { size_t n = (size_t)write(fd, buf, count); return (n == count) ? 0 : -1; }starter: starter/sysbuf.h
learner@ksa:~/gl-c01/lab-m01$ bat starter/sysbuf.h File: starter/sysbuf.h #ifndef KSA_SYSBUF_H #define KSA_SYSBUF_H #include <stddef.h> #include <stdint.h> #define SYSBUF_HDR_SIZE 16U size_t sysbuf_encode_header(uint8_t dst[SYSBUF_HDR_SIZE], uint16_t channel, const uint8_t *payload, size_t payload_len); int sysbuf_write_all(int fd, const void *buf, size_t count); #endifstep 2/15 · 2. learning objectives
- Build a multi-file ISO C11 static archive (
ar rcs libsysbuf.a sysbuf.o) and linked executable (inspector) using GNU Make with-std=c11 -Wall -Wextra -Werror -O2 -g. - Implement zero-syscall
Ring 3big-endian binary header encoding (sysbuf_encode_header) across payloads containing embedded0x00bytes withoutstrlen()truncation. - Implement a partial-count and
EINTR-safesysbuf_write_all()loop over signedssize_tand verify negative-descriptor-1(EBADF) diagnostics via thread-localerrno. - Verify under
stracethatRing 3framing, XOR checksumming, andsnprintf()formatting emit0kernelwritetraps prior to the single terminal flush.
step 3/15 · 3. environment requirements
- Host Execution Environment (Tested): POSIX-compliant Linux
6.12LTS (x86_64,glibc2.39+), executing insidelabs/lab_m01_toolchain_tracer/. - Target Board Portability (
ARMv7Cortex-A7): All C11 source files use<stdint.h>exact-width types (uint8_t,uint16_t), explicit big-endian shifts, andsize_t/ssize_t%zuformatting so the identical archive cross-compiles cleanly underarm-linux-gnueabihf-gccwith identical24-byte wire output.
step 4/15 · 4. required software & hardware
- Software Toolchain:
gcc(GCC11+with ISO C11 support), GNUmake, GNU Binutils (ar,nm,readelf),strace, and/bin/sh. - Hardware: Standard Linux host workstation or container (
0privileged/devnodes or root capabilities required).
step 5/15 · 5. complete executable commands
Run each command from labs/lab_m01_toolchain_tracer/ to observe the broken starter, build the static archive, inspect ELF symbols, and run the automated TAP 13 test harness:
learner@ksa:~/gl-c01/lab-m01$ bat script.sh File: script.sh # 1. Confirm starter/ fails check.sh deterministically (demonstrating the bugs to fix) cp starter/* files/ 2>/dev/null || true # (Note: coursec labs tests starter/ in a temp copy; inspect starter/ directly!) make -C files clean && make -C files # 2. Inspect archive members and global symbol table (.symtab) inside libsysbuf.a ar t files/libsysbuf.a nm -g files/libsysbuf.a # 3. Execute the CLI summary mode (verifies EBADF on fd=-1 and prints 1 formatted line) ./files/inspector # 4. Inspect exact raw binary frame bytes (24 bytes: 16-byte KSB1 header + 8-byte payload) ./files/inspector --raw | od -tx1 -An # 5. Count Ring 0 write() traps under strace (1 failed write(-1) + 1 stdout flush = 2) strace -e trace=write ./files/inspector 2>&1 >/dev/null | grep -c '^write(' # 6. Run the full TAP version 13 verification suite sh check.sh*Why each command runs:* make -C files compiles sysbuf.o and inspector.o separately before archiving libsysbuf.a via ar rcs and linking -L. -lsysbuf after inspector.o; nm -g confirms exported global symbols (T sysbuf_encode_header, T sysbuf_write_all); od -tx1 proves embedded 0x00 bytes survive intact; strace proves Ring 3 framing triggers zero kernel traps; and sh check.sh validates every contract end-to-end.
step 6/15 · 6. annotated source code (`starter/` flaws vs `files/` reference)
Flawed Baseline (starter/sysbuf.c & starter/Makefile)
- Missing strict compiler flags:
starter/Makefileomits-std=c11 -Wall -Wextra -Werrorand static-archive rules. - Binary
0x00truncation (starter/sysbuf.c):size_t wrong_len = strlen((const char *)payload);stops atpayload[1] == 0x00, encoding length1instead of8and skipping the XOR checksum (0x00instead of0xb6). - Unsigned
size_terror wrap (starter/sysbuf.c):size_t n = (size_t)write(fd, buf, count);wraps(ssize_t)-1toSIZE_MAXand fails to retry short writes orerrno == EINTR.
Warning-Clean Reference (files/sysbuf.c & files/inspector.c)
sysbuf_encode_header()(files/sysbuf.c): Zeroesdst[0..15], copies"KSB1", shiftschannelandpayload_leninto big-endian network order ((val >> 8U) & 0xFFU), iteratesfor (size_t i = 0; i < payload_len; i++)to computexor_sum(0xb6) andzero_count(2), and returns16with0syscalls.sysbuf_write_all()(files/sysbuf.c): Castsconst void *toconst uint8_t *, capturesssize_t written = write(fd, cursor, remaining), retries whenwritten < 0 && errno == EINTR, returns-1on fatal errors (EBADF), and advances(cursor += (size_t)written, remaining -= (size_t)written)untilremaining == 0U.main()(files/inspector.c): Checksargc > 1 && strcmp(argv[1], "--raw") == 0safely before touchingargv[1], testssysbuf_write_all(-1, ...)(bad_rc == -1 && errno == EBADF), formats a boundedsnprintf()line (ret < 0 || (size_t)ret >= sizeof(line)), and flushes once viasysbuf_write_all(STDOUT_FILENO, ...).
step 7/15 · 7. expected output
learner@ksa:~/gl-c01/lab-m01$ bat listing.txt File: listing.txt $ ./files/inspector frame_bytes=24 payload_bytes=8 null_bytes=2 checksum=0xb6 ebadf_ok=1 glibc=2.39 $ sh check.sh TAP version 13 1..5 ok 1 - builds libsysbuf.a and inspector cleanly with -std=c11 -Wall -Wextra -Werror ok 2 - archives sysbuf.o inside libsysbuf.a via ar ok 3 - preserves embedded 0x00 bytes, XOR checksum 0xb6, and EBADF errno handling ok 4 - emits exact 24-byte raw binary frame with KSB1 header and big-endian lengths ok 5 - executes pure Ring 3 framing with exactly 2 write() syscalls under strace # pass 5/5step 8/15 · 8. explanation of observed behavior
On payload {0x4B, 0x00, 0x53, 0x00, 0x41, 0x01, 0xFE, 0x10}, bitwise XOR evaluates $0x4B \oplus 0x00 \oplus 0x53 \oplus 0x00 \oplus 0x41 \oplus 0x01 \oplus 0xFE \oplus 0x10 = 0xB6$, while counting 0x00 bytes yields null_bytes=2. Under strace -e trace=write, sysbuf_encode_header() and snprintf() execute strictly inside Ring 3 stack RAM (0 trace lines). Calling write(-1, ...) traps into Ring 0, where VFS fdget_pos(-1) returns -EBADF (-9); glibc stores +9 in thread-local errno and returns -1 (ebadf_ok=1). Finally, sysbuf_write_all(STDOUT_FILENO, ...) flushes the entire line in 1 successful write(1, ...) syscall.
step 9/15 · 9. experiment variations
- Reversed Link-Order Experiment: Run
gcc -std=c11 files/inspector.o -Lfiles -lsysbuf -o /tmp/ok_binversusgcc -std=c11 -Lfiles -lsysbuf files/inspector.o -o /tmp/fail_bin(with-DSYSBUF_LINK_ARCHIVE) to observe GNUlddiscardlibsysbuf.abefore seeinginspector.o's unresolved symbols (undefined reference to 'sysbuf_encode_header'). - Link-Time
EINTRInjection (--wrap=write): Link a test wrapper with-Wl,--wrap=writethat returns-1witherrno = EINTRon every odd call and4bytes on every even call, confirmingsysbuf_write_all()still emits all24--rawbytes intact. - Sanitizer Verification: Rebuild with
CFLAGS="-std=c11 -Wall -Wextra -Werror -O1 -g -fsanitize=address,undefined"and verify zeroASanorUBSandiagnostics.
step 10/15 · 10. performance measurements
Measured on the Host x86_64 Linux 6.12 LTS build environment using CLOCK_MONOTONIC across 5 warmup runs and N = 35 timed end-to-end ./inspector executions:
| Metric | Measured Host (x86_64 Linux 6.12) | Target Board Expectation (ARMv7 Cortex-A7 @ 900 MHz) |
|---|---|---|
End-to-end ./inspector latency (p50 / p95 / p99) | 2,543.1 us / 2,869.9 us / 2,896.0 us | ~9,500–14,000 us (dominated by execve + ld-linux dynamic linking) |
In-process sysbuf_encode_header() (24 B, Ring 3) | < 15 ns (0 syscalls) | ~45–80 ns (0 svc #0 traps) |
Total write() syscalls (strace -c) | 2 (1 EBADF + 1 stdout) | 2 (identical ABI syscall count) |
step 11/15 · 11. troubleshooting
| Symptom | Root Cause | Fix |
|---|---|---|
undefined reference to 'sysbuf_encode_header' | -lsysbuf placed before inspector.o on the gcc link command line | Move -L. -lsysbuf after all .o object files that call it |
payload_bytes=8 yet checksum=0x4b and header[7]=1 | strlen() used instead of payload_len, stopping at payload[1] == 0x00 | Iterate for (size_t i = 0; i < payload_len; i++) over const uint8_t * |
implicit declaration of function under -std=c11 | #define _POSIX_C_SOURCE 200809L missing or placed below #include | Put #define _POSIX_C_SOURCE 200809L on line 1 of every .c file |
ebadf_ok=0 despite write(-1, ...) failing | An intervening printf() or helper ran before reading errno | Capture int saved_err = errno; immediately on the line after bad_rc = ... |
step 12/15 · 12. guided questions
- Why does
sysbuf_encode_header()accept(const uint8_t *payload, size_t payload_len)instead ofconst char *payload?
- *Hint 1:* Inspect bytes
1and3of the test payload{0x4B, 0x00, 0x53, 0x00, ...}and trace what C string functions treat0x00as. - *Hint 2:* Also recall from
m01-l02whether plaincharhas the same signedness onx86_64versusARMv7EABI when computing bitwise checksums!
- Why does
sysbuf.ccastconst void *buftoconst uint8_t *cursorinsidesysbuf_write_all()?
- *Hint 1:* What happens in strict ISO C11 (
-Wpointer-arith -Werror) if you writebuf += writtendirectly onconst void *buf? - *Hint 2:* Why is
const void *still preferred on the public parameter list ofsysbuf_write_all()?
step 13/15 · 13. independent challenges
- Near Transfer — Frame Decoder & Verifier (
sysbuf_decode_header): Addint sysbuf_decode_header(const uint8_t src[16], const uint8_t *payload, size_t cap, uint16_t *chan_out, size_t *len_out)tosysbuf.cthat validates"KSB1", reconstructs16-bit big-endianchannelandpayload_len, rejectspayload_len > cap(EINVAL), and verifies both the XOR checksum and0x00-byte count (Ebadmsg/EPROTOon mismatch). - Far Transfer — Shared Library (
libsysbuf.so) vs Static Archive (libsysbuf.a): ExtendMakefileto buildlibsysbuf.so(-fPIC -shared), compare.plt/.got.pltJUMP_SLOTentries inreadelf -rWbetween the statically archived and dynamically linkedinspectorbinaries, and measure startup overhead acrossN = 50runs.
step 14/15 · 14. solutions & explanations
- Guided Question 1: Binary protocols treat
0x00as an ordinary value rather than a terminator (strlen()stops at index1), anduint8_tguarantees unsigned[0..255]arithmetic across both signed-charx86_64and unsigned-charARMv7targets. - Guided Question 2: Standard C leaves
voidan incomplete type (sizeof(void)is invalid; GNU C treatsvoid * + 1as a non-standard extension rejected under-Wpedantic/-Werror), so internal byte stepping requiresconst uint8_t *, while keepingconst void *on the public signature allows callers to pass structs orchar *buffers without noisy pointer casts. - Challenge 1 Key Idiom: Reconstruct big-endian
uint16_tvia((uint16_t)src[6] << 8U) | (uint16_t)src[7](casting touint16_t/unsignedbefore shifting to avoid signed promotion surprises) and validatelen <= capbefore scanningpayload.
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-m01./inspector && ./inspector --raw | wc -clearner@ksa:~/gl-c01/lab-m01frame_bytes=24 payload_bytes=8 null_bytes=2 checksum=0xb6 ebadf_ok=1 glibc=2.3924Progressive 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-c01/lab-m01$ bat files/Makefile File: files/Makefile CC ?= gcc AR ?= ar CFLAGS := -std=c11 -Wall -Wextra -Werror -O2 -g .PHONY: all clean all: libsysbuf.a inspector sysbuf.o: sysbuf.c sysbuf.h $(CC) $(CFLAGS) -DSYSBUF_LIBRARY_BUILD -c sysbuf.c -o sysbuf.o libsysbuf.a: sysbuf.o $(AR) rcs libsysbuf.a sysbuf.o inspector.o: inspector.c sysbuf.h $(CC) $(CFLAGS) -DSYSBUF_LINK_ARCHIVE -c inspector.c -o inspector.o inspector: inspector.o libsysbuf.a $(CC) $(CFLAGS) inspector.o libsysbuf.a -o inspector clean: rm -f *.o libsysbuf.a inspector sysbufsolution: files/inspector.c
learner@ksa:~/gl-c01/lab-m01$ bat files/inspector.c File: files/inspector.c #define _POSIX_C_SOURCE 200809L #include "sysbuf.h" #include <errno.h> #include <gnu/libc-version.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <unistd.h> #ifndef SYSBUF_LINK_ARCHIVE #define SYSBUF_LIBRARY_BUILD 1 #include "sysbuf.c" #endif int main(int argc, char *argv[]) { const uint8_t payload[8] = {0x4BU, 0x00U, 0x53U, 0x00U, 0x41U, 0x01U, 0xFEU, 0x10U}; uint8_t frame[SYSBUF_HDR_SIZE + sizeof(payload)]; size_t hdr_len = sysbuf_encode_header(frame, 7U, payload, sizeof(payload)); memcpy(frame + hdr_len, payload, sizeof(payload)); size_t frame_len = hdr_len + sizeof(payload); if (argc > 1 && strcmp(argv[1], "--raw") == 0) { if (sysbuf_write_all(STDOUT_FILENO, frame, frame_len) == -1) { perror("sysbuf_write_all"); return EXIT_FAILURE; } return EXIT_SUCCESS; } errno = 0; int bad_rc = sysbuf_write_all(-1, frame, frame_len); int ebadf_ok = (bad_rc == -1 && errno == EBADF) ? 1 : 0; char line[160]; int len = snprintf( line, sizeof(line), "frame_bytes=%zu payload_bytes=%zu null_bytes=%u checksum=0x%02x ebadf_ok=%d glibc=%s\n", frame_len, sizeof(payload), (unsigned int)frame[9], (unsigned int)frame[8], ebadf_ok, gnu_get_libc_version() ); if (len < 0 || (size_t)len >= sizeof(line)) { return EXIT_FAILURE; } if (sysbuf_write_all(STDOUT_FILENO, line, (size_t)len) == -1) { return EXIT_FAILURE; } return ebadf_ok ? EXIT_SUCCESS : EXIT_FAILURE; }solution: files/sysbuf.c
learner@ksa:~/gl-c01/lab-m01$ bat files/sysbuf.c File: files/sysbuf.c #define _POSIX_C_SOURCE 200809L #include "sysbuf.h" #include <errno.h> #include <string.h> #include <sys/types.h> #include <unistd.h> size_t sysbuf_encode_header(uint8_t dst[SYSBUF_HDR_SIZE], uint16_t channel, const uint8_t *payload, size_t payload_len) { uint8_t xor_sum = 0U; uint8_t zero_count = 0U; memset(dst, 0, SYSBUF_HDR_SIZE); memcpy(dst, "KSB1", 4U); dst[4] = (uint8_t)((channel >> 8U) & 0xFFU); dst[5] = (uint8_t)(channel & 0xFFU); dst[6] = (uint8_t)((payload_len >> 8U) & 0xFFU); dst[7] = (uint8_t)(payload_len & 0xFFU); for (size_t i = 0; i < payload_len; i++) { xor_sum ^= payload[i]; if (payload[i] == 0x00U && zero_count < 255U) { zero_count++; } } dst[8] = xor_sum; dst[9] = zero_count; return SYSBUF_HDR_SIZE; } int sysbuf_write_all(int fd, const void *buf, size_t count) { const uint8_t *cursor = (const uint8_t *)buf; size_t remaining = count; while (remaining > 0U) { ssize_t written = write(fd, cursor, remaining); if (written < 0) { if (errno == EINTR) { continue; } return -1; } cursor += (size_t)written; remaining -= (size_t)written; } return 0; } #ifndef SYSBUF_LIBRARY_BUILD int main(void) { uint8_t hdr[SYSBUF_HDR_SIZE]; const uint8_t sample[2] = {0xAAU, 0x00U}; return (sysbuf_encode_header(hdr, 1U, sample, sizeof(sample)) == SYSBUF_HDR_SIZE) ? 0 : 1; } #endifsolution: files/sysbuf.h
learner@ksa:~/gl-c01/lab-m01$ bat files/sysbuf.h File: files/sysbuf.h #ifndef KSA_SYSBUF_H #define KSA_SYSBUF_H #include <stddef.h> #include <stdint.h> #define SYSBUF_HDR_SIZE 16U size_t sysbuf_encode_header(uint8_t dst[SYSBUF_HDR_SIZE], uint16_t channel, const uint8_t *payload, size_t payload_len); int sysbuf_write_all(int fd, const void *buf, size_t count); #endifRun the check
From labs/lab_m01_toolchain_tracer/, run ./check.sh. A complete solution emits TAP version 13 with every test point marked ok and exits 0:
learner@ksa:~/gl-c01/lab-m01./check.shTAP version 131..5ok 1 - builds with -std=c11 -Wall -Wextra and no warningsok 2 - archives sysbuf.o into static library libsysbuf.aok 3 - frames 24-byte binary packet preserving embedded NUL bytesok 4 - reports frame metrics, XOR checksum, and EBADF errno checkok 5 - emits stdout report in a single write(1, ...) system call# pass 5/5On an incomplete starter tree, ./check.sh exits non-zero and marks the unmet assertion not ok with an indented YAML diagnostic block:
learner@ksa:~/gl-c01/lab-m01./check.shTAP version 131..5not ok 1 - builds with -std=c11 -Wall -Wextra and no warnings --- message: 'Makefile built without strict -std=c11 -Wall -Wextra flags' hint: 'add CFLAGS = -std=c11 -Wall -Wextra -Werror to files/Makefile' ...not ok 2 - archives sysbuf.o into static library libsysbuf.a --- message: 'Makefile did not build static archive libsysbuf.a containing sysbuf.o' hint: 'compile sysbuf.c with -c and run ar rcs libsysbuf.a sysbuf.o' ...ok 3 - frames 24-byte binary packet preserving embedded NUL bytesnot ok 4 - reports frame metrics, XOR checksum, and EBADF errno check --- message: 'unexpected inspector stdout: empty' hint: 'check ssize_t write() return for -1 (EBADF) and format full metric line' ...not ok 5 - emits stdout report in a single write(1, ...) system call --- message: 'expected 1 write(1, ...) syscall for stdout report, observed 0' hint: 'format into a user-space buffer first and flush once via write(STDOUT_FILENO, ...)' ...# pass 1/5note: How to read TAP diagnostics: 1..N states the total test plan; each ok k confirms a passed check; not ok k pinpoints the failing check alongside message: (what went wrong) and hint: (where to look next) between --- and ....
inspect harness: check.sh
learner@ksa:~/gl-c01/lab-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_m01.XXXXXX")" trap 'rm -rf "$WORKDIR"' EXIT MISSING="" for req in files/Makefile files/sysbuf.h files/sysbuf.c files/inspector.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, sysbuf.h, sysbuf.c, and inspector.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 that removes *.o, libsysbuf.a, and inspector" 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 compiler errors under -std=c11 -Wall -Wextra -Werror" else [ -x "$WORKDIR/build/inspector" ] && 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" \ "add CFLAGS = -std=c11 -Wall -Wextra -Werror to files/Makefile" fi fi fi if [ -f "$WORKDIR/build/libsysbuf.a" ] && ar t "$WORKDIR/build/libsysbuf.a" 2>/dev/null | grep -q "sysbuf.o"; then tap_ok 2 "archives sysbuf.o into static library libsysbuf.a" else tap_not_ok 2 "archives sysbuf.o into static library libsysbuf.a" \ "Makefile did not build static archive libsysbuf.a containing sysbuf.o" \ "compile sysbuf.c with -c and run ar rcs libsysbuf.a sysbuf.o" fi OUTBIN="$WORKDIR/frame.bin" OUTTXT="" if [ "$BUILT" -eq 1 ]; then timeout 3 "$WORKDIR/build/inspector" --raw >"$OUTBIN" 2>/dev/null || true OUTTXT="$(timeout 3 "$WORKDIR/build/inspector" 2>/dev/null || true)" fi FSIZE=0 [ -f "$OUTBIN" ] && FSIZE="$(wc -c < "$OUTBIN" | tr -d ' ')" if [ "$BUILT" -eq 1 ] && [ "$FSIZE" = "24" ]; then tap_ok 3 "frames 24-byte binary packet preserving embedded NUL bytes" else tap_not_ok 3 "frames 24-byte binary packet preserving embedded NUL bytes" \ "binary output frame size is ${FSIZE} bytes, expected 24" \ "track explicit byte length with size_t instead of calling strlen() across 0x00 bytes" fi case "$OUTTXT" in *"frame_bytes=24 payload_bytes=8 null_bytes=2 checksum=0xb6 ebadf_ok=1 glibc="*) tap_ok 4 "reports frame metrics, XOR checksum, and EBADF errno check" ;; *) tap_not_ok 4 "reports frame metrics, XOR checksum, and EBADF errno check" \ "unexpected inspector stdout: ${OUTTXT:-empty}" \ "check ssize_t write() return for -1 (EBADF) and format full metric line" ;; esac if [ "$BUILT" -eq 1 ] && command -v strace >/dev/null 2>&1; then OK_WRITES="$(strace -e trace=write "$WORKDIR/build/inspector" 2>&1 >/dev/null | grep -c '^write(1,' || true)" if [ "$OK_WRITES" = "1" ]; then tap_ok 5 "emits stdout report in a single write(1, ...) system call" else tap_not_ok 5 "emits stdout report in a single write(1, ...) system call" \ "expected 1 write(1, ...) syscall for stdout report, observed ${OK_WRITES}" \ "format into a user-space buffer first and flush once via write(STDOUT_FILENO, ...)" fi elif [ "$BUILT" -eq 1 ]; then tap_ok 5 "emits stdout report in a single write(1, ...) system call" else tap_not_ok 5 "emits stdout report in a single write(1, ...) system call" \ "inspector executable was not built" \ "fix Makefile build so ./inspector can be traced under strace" 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_toolchain_tracer/ so relative paths to files/ resolve directly.