Lab 5: Bounded stdio Sensor Log Parser & Binary Codec
Map glibc FILE streams and fopen mode strings to kernel openat flags, serialize fixed binary records safely with fread/fwrite/fseeko and feof/ferror triage, and construct truncation-safe snprintf and fgets/strtol codecs.
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
Telemetry ingestion pipelines sit directly on the untrusted boundary between noisy serial/CSV text feeds and compact binary storage files. Naive fscanf(in, "%s,%u,%d") parsers suffer buffer overflows on long sensor IDs and wedge permanently when a single corrupted UART line arrives, while while (!feof(fp)) readers duplicate the final binary sample and unchecked snprintf() calls silently truncate diagnostic summaries. In this lab, you will build telemetry_codec to master line-isolated fgets() + strtoul()/strtol() ingestion, batched item-counted fwrite()/fread(), torn-tail detection via ftello(), and deterministic snprintf() truncation checks.
learner@ksa:~/gl-c01/lab-m05ls -lastarter/telemetry_codec.clearner@ksa:~/gl-c01/lab-m05starter: starter/telemetry_codec.c
learner@ksa:~/gl-c01/lab-m05$ bat starter/telemetry_codec.c File: starter/telemetry_codec.c #define _POSIX_C_SOURCE 200809L #include <stdint.h> #include <stdio.h> #include <stdlib.h> #include <string.h> struct sensor_frame { char id[16]; uint32_t seq; int32_t mv; }; /* * STARTER BASELINE (contains intentional stdio bugs): * 1. encode uses fscanf() without line draining, wedging on malformed/oversized lines. * 2. inspect loops on while (!feof(fp)), counting a phantom extra record at EOF, * and ignores partial-tail structs and snprintf() truncation detection. */ int main(int argc, char **argv) { if (argc != 4) return 2; if (strcmp(argv[1], "encode") == 0) { FILE *in = fopen(argv[2], "r"); FILE *out = fopen(argv[3], "wb"); if (!in || !out) return 1; struct sensor_frame f; size_t valid = 0; while (fscanf(in, "%15[^,],%u,%d\n", f.id, &f.seq, &f.mv) == 3) { fwrite(&f, sizeof(f), 1, out); valid++; } fclose(in); fclose(out); printf("ENCODE valid=%zu rejected=0 bytes=%zu\n", valid, valid * sizeof(f)); return 0; } if (strcmp(argv[1], "inspect") == 0) { FILE *fp = fopen(argv[2], "rb"); if (!fp) return 1; size_t cap = (size_t)strtoul(argv[3], NULL, 10); if (cap == 0) return 1; struct sensor_frame f; memset(&f, 0, sizeof(f)); size_t count = 0; int32_t min_mv = 0, max_mv = 0; /* BUG: classic off-by-one while (!feof(fp)) loop */ while (!feof(fp)) { (void)fread(&f, sizeof(f), 1, fp); if (count == 0 || f.mv < min_mv) min_mv = f.mv; if (count == 0 || f.mv > max_mv) max_mv = f.mv; count++; } char *buf = calloc(cap, 1); if (!buf) { fclose(fp); return 1; } snprintf(buf, cap, "VALID=%zu MIN_MV=%d MAX_MV=%d EOF_CLEAN=1", count, min_mv, max_mv); printf("%s\n", buf); free(buf); fclose(fp); return 0; } return 2; }step 2/15 · 2. learning objectives
- Ingest untrusted CSV sensor streams via bounded
fgets()(draining> 127-byte oversized lines up to'\n') and validate<id>,<seq>,<mv>fields withstrtoul()/strtol()(ERANGEand character-set guards). - Serialize
24-bytestruct sensor_framebatches (16records perfwrite()call) onto"wbe"streams with checkedferror()andfclose(). - Inspect binary streams via
while (fread(&frame, sizeof(frame), 1, fp) == 1)(neverwhile (!feof(fp))), detecting partial trailing bytes (exit 2) viaftello()/fseeko(). - Enforce
snprintf(buf, cap, ...)bounds by detectingneeded < 0 || (size_t)needed >= cap(exit 3).
step 3/15 · 3. environment requirements
- Host Execution Environment (Tested): Linux
6.12LTS (x86_64,glibc2.39+),#define _POSIX_C_SOURCE 200809Land#define _FILE_OFFSET_BITS 64. - Target Board Portability (
ARMv7Cortex-A7):struct sensor_frame(char id[16]; uint32_t seq; int32_t mv;) has natural4-byte alignment and0padding bytes (sizeof == 24) across both 32-bitARMv7and 64-bitx86_64little-endian targets, andint ch = fgetc(in)avoids the unsigned-charARMv7infinite loop during line draining!
step 4/15 · 4. required software & hardware
- Software Toolchain:
gcc(-std=c11 -Wall -Wextra -Werror),strace,truncate, and/bin/sh. - Hardware: Standard Linux host environment.
step 5/15 · 5. complete executable commands
Run from labs/lab_m05_telemetry_codec/:
learner@ksa:~/gl-c01/lab-m05$ bat script.sh File: script.sh # 1. Compile the warning-clean sensor parser and binary codec gcc -std=c11 -O2 -Wall -Wextra -Werror files/telemetry_codec.c -o /tmp/telemetry_codec # 2. Create a mixed CSV feed (valid rows, comments, ERANGE overflow, and >128B oversized line) python3 -c ' print("# boot log\nvcore,1,1150\nmalformed_row\n" + "x"*150 + ",2,100\npll_mv,2,1800\nbad_ovf,999999999999,10\nvcore,3,1120") ' > /tmp/ksa_sensors.csv # 3. Encode valid rows to binary (3 valid * 24B = 72B, 3 rejected) and inspect with sufficient cap /tmp/telemetry_codec encode /tmp/ksa_sensors.csv /tmp/ksa_sensors.bin /tmp/telemetry_codec inspect /tmp/ksa_sensors.bin 64 # 4. Test deterministic snprintf() truncation (cap=16 -> exit 3) and torn-tail detection (exit 2) /tmp/telemetry_codec inspect /tmp/ksa_sensors.bin 16; echo "trunc_rc=$?" printf 'TORN!' >> /tmp/ksa_sensors.bin /tmp/telemetry_codec inspect /tmp/ksa_sensors.bin 64; echo "torn_rc=$?" # 5. Clean up and run the full TAP 13 verification harness rm -f /tmp/telemetry_codec /tmp/ksa_sensors.csv /tmp/ksa_sensors.bin sh check.sh*Why each command runs:* Step 2 injects every real-world CSV fault (# comments, missing commas, 150-char line overflow, UINT32_MAX overflow); Step 3 proves the parser isolates all 3 bad lines and recovers vcore,3,1120; Step 4 verifies exit 3 on cap=16 truncation and exit 2 (PARTIAL_TAIL bytes=5) on a torn binary tail; and Step 5 runs sh check.sh.
step 6/15 · 6. annotated source code (`starter/` flaws vs `files/` reference)
Flawed Baseline (starter/telemetry_codec.c)
- Wedging
fscanf()(encode):while (fscanf(in, "%15[^,],%u,%d\n", ...) == 3)halts at the very first malformed or#comment line (valid=0or partial output) and silently wraps overflowing integers! - Off-by-one
while (!feof(fp))(inspect): Runs an extra loop iteration atEOF, countingVALID=4on a3-record file! - Missing torn-tail &
snprintf()checks: Ignores partial trailing bytes (PARTIAL_TAIL) and prints silently truncated strings with exit0.
Warning-Clean Reference (files/telemetry_codec.c)
- Oversized-Line Drain (
cmd_encode): Checksif (len > 0 && line[len - 1] != '\n' && !feof(in))and drains viaint ch; while ((ch = fgetc(in)) != '\n' && ch != EOF) {}before incrementingrejected, keeping the next line cleanly aligned! - Strict Token Validation (
parse_csv_line): Rejects leading'-'beforestrtoul()(becausestrtoul("-1", ...)legally wraps moduloULONG_MAX!), checkserrno == 0 && *end_seq == ',' && seq_ul <= UINT32_MAX, and checksmv_lin[-100000, 100000]. - Torn-Tail & Truncation Guards (
cmd_inspect): Snapshotspos_before = ftello(fp)prior to eachfread(&frame, 24, 1, fp), comparesSEEK_ENDend_pos > pos_before(exit 2), and checksneeded < 0 || (size_t)needed >= cap(exit 3).
step 7/15 · 7. expected output
learner@ksa:~/gl-c01/lab-m05$ 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 - encodes valid CSV rows into 24-byte frames while isolating malformed and >128B lines ok 3 - reads exact record count without while(!feof) off-by-one duplication ok 4 - detects torn trailing binary bytes via ftello/fseeko (exit 2) ok 5 - detects snprintf summary buffer truncation deterministically (exit 3) # pass 5/5step 8/15 · 8. explanation of observed behavior
Batching 16 struct sensor_frame items (16 * 24 = 384 bytes) into fwrite() copies records inside glibc's Ring 3 _IO_FILE buffer, emitting just 1 write() syscall when fclose(out) flushes a 72-byte or 6,144-byte batch. On inspection of the 77-byte torn file (72 + 5), Iteration 4 records pos_before = 72, fread(&frame, 24, 1, fp) consumes the 5 torn bytes, hits EOF, sets _IO_EOF_SEEN, and returns 0 complete items; fseeko(fp, 0, SEEK_END) + ftello(fp) then measures end_pos = 77 > 72, reporting PARTIAL_TAIL bytes=5 (exit 2)!
step 9/15 · 9. experiment variations
strtoul("-5")Sign-Wrap Experiment: Comment outif (!isdigit((unsigned char)*s_seq)) return -1;in a scratch copy and passvcore,-1,3300on 64-bit Linux to observestrtoul()parse-1as18446744073709551615UL(> UINT32_MAX), and passvcore,-1,3300on 32-bitILP32whereULONG_MAX == UINT32_MAX(4294967295accepted silently without theisdigitguard!).straceBatching Verification: Encode1,000CSV rows (24,000bytes) understrace -e trace=read,writeand confirmglibc's8 KiB_IOFBFbuffer reduces1,000logical records to3write()syscalls!- In-Memory Fuzzing via
fmemopen: Refactorcmd_encodeintoencode_streams(FILE *in, FILE *out)and fuzzparse_csv_linein memory usingfmemopen()+open_memstream()under-fsanitize=address,undefined.
step 10/15 · 10. performance measurements
Measured on Host x86_64 Linux 6.12 LTS (CLOCK_MONOTONIC, 5 warmup runs, N = 35 end-to-end encode + inspect cycles over 256 CSV rows = 6,144 binary bytes):
| Metric | Measured Host (x86_64 Linux 6.12) | Target Board Expectation (ARMv7 Cortex-A7) |
|---|---|---|
256-row encode + inspect (p50 / p95 / p99) | 3,829.6 us / 4,709.7 us / 5,941.2 us | ~14,000–21,000 us (2 CLI spawns; < 180 us in-process codec) |
Kernel write() syscalls for 256 rows (6,144 B) | 1 (< 8 KiB _IOFBF buffer flushed at fclose) | 1 (_IOFBF 4 KiB or 8 KiB -> 1–2 write traps) |
step 11/15 · 11. troubleshooting
| Symptom | Root Cause | Fix |
|---|---|---|
VALID is N + 1 on every clean binary file | Used while (!feof(fp)) instead of checking fread() == 1 | Loop on while (fread(&frame, sizeof(frame), 1, fp) == 1) |
Infinite loop on ARMv7 when draining > 128B CSV line | Stored fgetc(in) in char ch (unsigned char 255 != -1 EOF) | Declare int ch; for fgetc(in) |
Negative sequence -1 accepted on 32-bit targets | strtoul() allows leading '-' and negates modulo ULONG_MAX | Check isdigit((unsigned char)*s_seq) before strtoul() |
-Wsign-compare or -Wformat error on size_t | Printed size_t with %lu instead of %zu | Use %zu for size_t across 32/64-bit builds |
step 12/15 · 12. guided questions
- Why must
valid_id_char((unsigned char)line[i])castchartounsigned charbefore calling<ctype.h>isalnum()?
- *Hint 1:* Check
man 3 isalnumfor the exact input domain required by ISO C11<ctype.h>functions (unsigned charwidened toint, orEOF). - *Hint 2:* On x86-64 (signed
char), what negativeintvalue is passed toisalnum()if an untrusted UTF-8 byte0xC3arrives without the(unsigned char)cast (Undefined Behaviornegative table index!)?
- Why does
cmd_inspect()checkif (ferror(fp))before comparingend_pos > pos_before?
- *Hint 1:* What does
fread()return when an underlyingEIOread fault occurs mid-file (0, just likeEOF!)? - *Hint 2:* If
EIOstoppedfread()at byte24of a72-byte file, what wouldend_pos > pos_beforemisclassify the hardware I/O error as ifferror(fp)were not checked first?
step 13/15 · 13. independent challenges
- Near Transfer — Endian-Neutral Wire Codec (
htole32/ Manual Shifts): Replace directfwrite(&frame, 24, 1, out)struct dumps with explicit little-endian byte packing/unpacking (uint8_t wire[24]) so binary logs remain portable even across big-endian network processors. - Far Transfer — Streaming Ring-Buffer Compactor: Extend
telemetry_codecwith atail <in_bin> <last_k>subcommand that usesfseeko(fp, 0, SEEK_END)+ftello()to validate exact24-byte alignment (end_pos % 24 == 0) and seeks directly toend_pos - last_k * 24in $O(1)$ time without reading earlier megabytes!
step 14/15 · 14. solutions & explanations
- Guided Question 1: Passing a negative
signed char(other thanEOF-1, and0xFFcollides withEOF!) toisalnum()orisdigit()invokes ISO C11 Undefined Behavior (indexing backward beforeglibc's__ctype_b_loclookup table); always cast(unsigned char)c! - Guided Question 2: Both
EOFandEIOcausefread(..., 1, fp)to return0; checkingferror(fp)first reports an I/O error (exit 1) instead of falsely blaming the file for aPARTIAL_TAIL(exit 2).
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-m05./telemetry_codec encode sensors.csv sensors.bin && ./telemetry_codec inspect sensors.bin 64learner@ksa:~/gl-c01/lab-m05ENCODE valid=4 rejected=0 bytes=96VALID=4 MIN_MV=-120 MAX_MV=12050 EOF_CLEAN=1Progressive hints & solution
hint 1
Compare starter/telemetry_codec.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
warning: Reveal the reference solution files? Running ./check.sh against your own attempt first builds stronger retention.
solution: files/telemetry_codec.c
learner@ksa:~/gl-c01/lab-m05$ bat files/telemetry_codec.c File: files/telemetry_codec.c #define _POSIX_C_SOURCE 200809L #include <ctype.h> #include <errno.h> #include <limits.h> #include <stdint.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <sys/types.h> enum { LINE_CAP = 128, BATCH_CAP = 16 }; struct sensor_frame { char id[16]; uint32_t seq; int32_t mv; }; static int valid_id_char(unsigned char c) { return isalnum(c) || c == '_' || c == '.' || c == '-'; } static int parse_csv_line(const char *line, struct sensor_frame *out) { const char *c1 = strchr(line, ','); if (!c1) return -1; size_t id_len = (size_t)(c1 - line); if (id_len == 0 || id_len >= sizeof(out->id)) return -1; for (size_t i = 0; i < id_len; i++) { if (!valid_id_char((unsigned char)line[i])) return -1; } const char *s_seq = c1 + 1; if (!isdigit((unsigned char)*s_seq)) return -1; errno = 0; char *end_seq = NULL; unsigned long seq_ul = strtoul(s_seq, &end_seq, 10); if (errno != 0 || end_seq == s_seq || *end_seq != ',' || seq_ul > UINT32_MAX) { return -1; } const char *s_mv = end_seq + 1; if (*s_mv != '-' && *s_mv != '+' && !isdigit((unsigned char)*s_mv)) return -1; errno = 0; char *end_mv = NULL; long mv_l = strtol(s_mv, &end_mv, 10); if (errno != 0 || end_mv == s_mv || *end_mv != '\0') return -1; if (mv_l < -100000L || mv_l > 100000L) return -1; memset(out, 0, sizeof(*out)); memcpy(out->id, line, id_len); out->seq = (uint32_t)seq_ul; out->mv = (int32_t)mv_l; return 0; } static int cmd_encode(const char *in_path, const char *out_path) { FILE *in = fopen(in_path, "re"); if (!in) return 1; FILE *out = fopen(out_path, "wbe"); if (!out) { fclose(in); return 1; } char line[LINE_CAP]; struct sensor_frame batch[BATCH_CAP]; size_t bcount = 0; size_t valid = 0; size_t rejected = 0; while (fgets(line, (int)sizeof(line), in) != NULL) { size_t len = strlen(line); if (len > 0 && line[len - 1] != '\n' && !feof(in)) { int ch; while ((ch = fgetc(in)) != '\n' && ch != EOF) { /* drain oversized line cleanly */ } rejected++; continue; } while (len > 0 && (line[len - 1] == '\n' || line[len - 1] == '\r')) { line[--len] = '\0'; } if (len == 0 || line[0] == '#') continue; struct sensor_frame frame; if (parse_csv_line(line, &frame) < 0) { rejected++; continue; } batch[bcount++] = frame; valid++; if (bcount == BATCH_CAP) { if (fwrite(batch, sizeof(batch[0]), bcount, out) != bcount) { fclose(in); fclose(out); return 1; } bcount = 0; } } if (ferror(in)) { fclose(in); fclose(out); return 1; } if (bcount > 0 && fwrite(batch, sizeof(batch[0]), bcount, out) != bcount) { fclose(in); fclose(out); return 1; } if (fclose(in) != 0 || fclose(out) != 0) return 1; printf("ENCODE valid=%zu rejected=%zu bytes=%zu\n", valid, rejected, valid * sizeof(struct sensor_frame)); return 0; } static int cmd_inspect(const char *bin_path, const char *cap_str) { errno = 0; char *end = NULL; unsigned long cap_ul = strtoul(cap_str, &end, 10); if (errno != 0 || end == cap_str || *end != '\0' || cap_ul == 0 || cap_ul > 65536UL) { return 1; } size_t cap = (size_t)cap_ul; FILE *fp = fopen(bin_path, "rbe"); if (!fp) return 1; size_t count = 0; int32_t min_mv = 0; int32_t max_mv = 0; off_t pos_before = 0; for (;;) { pos_before = ftello(fp); if (pos_before < 0) { fclose(fp); return 1; } struct sensor_frame frame; size_t got = fread(&frame, sizeof(frame), 1, fp); if (got == 1) { if (count == 0 || frame.mv < min_mv) min_mv = frame.mv; if (count == 0 || frame.mv > max_mv) max_mv = frame.mv; count++; continue; } break; } if (ferror(fp)) { fclose(fp); return 1; } int eof_clean = feof(fp) ? 1 : 0; if (fseeko(fp, 0, SEEK_END) < 0) { fclose(fp); return 1; } off_t end_pos = ftello(fp); fclose(fp); if (end_pos < 0) return 1; if (end_pos > pos_before) { printf("PARTIAL_TAIL bytes=%lld\n", (long long)(end_pos - pos_before)); return 2; } char *buf = malloc(cap); if (!buf) return 1; int needed = snprintf(buf, cap, "VALID=%zu MIN_MV=%d MAX_MV=%d EOF_CLEAN=%d", count, min_mv, max_mv, eof_clean); if (needed < 0 || (size_t)needed >= cap) { free(buf); printf("TRUNCATED needed=%d cap=%zu\n", needed, cap); return 3; } printf("%s\n", buf); free(buf); return 0; } int main(int argc, char **argv) { if (argc != 4) return 2; if (strcmp(argv[1], "encode") == 0) { return cmd_encode(argv[2], argv[3]); } if (strcmp(argv[1], "inspect") == 0) { return cmd_inspect(argv[2], argv[3]); } return 2; }Run the check
From labs/lab_m05_telemetry_codec/, run ./check.sh. A complete solution emits TAP version 13 with every test point marked ok and exits 0:
learner@ksa:~/gl-c01/lab-m05./check.shTAP version 131..5ok 1 - builds with -std=c11 -Wall -Wextra and no warningsok 2 - encodes 4 valid CSV records to 96 bytes and drains oversized linesok 3 - reads exact binary item count without while(!feof) off-by-one bugok 4 - detects snprintf truncation (ret >= cap) and exits with status 3ok 5 - detects 7-byte partial trailing struct at EOF and exits with status 2# 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-m05./check.shTAP version 131..5ok 1 - builds with -std=c11 -Wall -Wextra and no warningsnot ok 2 - encodes 4 valid CSV records to 96 bytes and drains oversized lines --- message: 'encode output= ENCODE valid=0 rejected=0 bytes=0 bytes=0, expected ENCODE valid=4 rejected=4 bytes=96' hint: 'drain remainder of long fgets() lines lacking \n and validate numeric fields via strtoul/strtol endptr' ...not ok 3 - reads exact binary item count without while(!feof) off-by-one bug --- message: 'inspect output= VALID=1 MIN_MV=0 MAX_MV=0 EOF_CLEAN=1 , expected VALID=4 MIN_MV=-120 MAX_MV=12050 EOF_CLEAN=1' hint: 'loop on while (fread(&rec, sizeof(rec), 1, fp) == 1) instead of while (!feof(fp))' ...not ok 4 - detects snprintf truncation (ret >= cap) and exits with status 3 --- message: 'rc=0 out= VALID=1 MIN_MV= , expected rc=3 and TRUNCATED needed=44 cap=16' hint: 'check int n = snprintf(buf, cap, ...); if ((size_t)n >= cap) report needed=n+1 and exit 3' ...not ok 5 - detects 7-byte partial trailing struct at EOF and exits with status 2 --- message: 'rc=0 out= VALID=1 MIN_MV=0 MAX_MV=0 EOF_CLEAN=1 , expected rc=2 and PARTIAL_TAIL bytes=7' hint: 'compare ftello(fp) after item loop against total file size to detect trailing partial bytes' ...# 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-m05$ 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_m05.XXXXXX")" trap 'rm -rf "$WORK"' EXIT BUILT=0 if [ ! -f files/telemetry_codec.c ]; then tap_not_ok 1 "builds with -std=c11 -Wall -Wextra and no warnings" \ "missing files/telemetry_codec.c" \ "place your implementation in files/telemetry_codec.c" elif gcc -std=c11 -Wall -Wextra -Werror files/telemetry_codec.c -o "$WORK/telemetry_codec" 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/telemetry_codec.c" fi LONG_ID="$(awk 'BEGIN{for(i=0;i<180;i++) printf "X"}')" cat > "$WORK/sensors.csv" <<EOF # Telemetry batch header vrm.core,101,850 bad line without commas ${LONG_ID},102,900 temp.die,103,-120 vrm.soc,104,1125 overflow_id_longer_than_15_chars,105,500 rail.aux,not_a_num,3300 psu.in,106,12050 EOF ENC_OUT="" BIN_BYTES=0 if [ "$BUILT" -eq 1 ]; then ENC_OUT="$(timeout 3 "$WORK/telemetry_codec" encode "$WORK/sensors.csv" "$WORK/sensors.bin" 2>/dev/null || true)" [ -f "$WORK/sensors.bin" ] && BIN_BYTES="$(wc -c < "$WORK/sensors.bin" | tr -d ' ')" fi if [ "$ENC_OUT" = "ENCODE valid=4 rejected=4 bytes=96" ] && [ "$BIN_BYTES" = "96" ]; then tap_ok 2 "encodes 4 valid CSV records to 96 bytes and drains oversized lines" else tap_not_ok 2 "encodes 4 valid CSV records to 96 bytes and drains oversized lines" \ "encode output='${ENC_OUT:-empty}' bytes=${BIN_BYTES}, expected 'ENCODE valid=4 rejected=4 bytes=96'" \ "drain remainder of long fgets() lines lacking '\\n' and validate numeric fields via strtoul/strtol endptr" fi INSP_OUT="" if [ "$BUILT" -eq 1 ] && [ -f "$WORK/sensors.bin" ]; then INSP_OUT="$(timeout 3 "$WORK/telemetry_codec" inspect "$WORK/sensors.bin" 64 2>/dev/null || true)" fi if [ "$INSP_OUT" = "VALID=4 MIN_MV=-120 MAX_MV=12050 EOF_CLEAN=1" ]; then tap_ok 3 "reads exact binary item count without while(!feof) off-by-one bug" else tap_not_ok 3 "reads exact binary item count without while(!feof) off-by-one bug" \ "inspect output='${INSP_OUT:-empty}', expected 'VALID=4 MIN_MV=-120 MAX_MV=12050 EOF_CLEAN=1'" \ "loop on while (fread(&rec, sizeof(rec), 1, fp) == 1) instead of while (!feof(fp))" fi TRUNC_OUT="" TRUNC_RC=0 if [ "$BUILT" -eq 1 ] && [ -f "$WORK/sensors.bin" ]; then TRUNC_OUT="$(timeout 3 "$WORK/telemetry_codec" inspect "$WORK/sensors.bin" 16 2>/dev/null)" TRUNC_RC=$? fi if [ "$TRUNC_RC" -eq 3 ] && [ "$TRUNC_OUT" = "TRUNCATED needed=44 cap=16" ]; then tap_ok 4 "detects snprintf truncation (ret >= cap) and exits with status 3" else tap_not_ok 4 "detects snprintf truncation (ret >= cap) and exits with status 3" \ "rc=${TRUNC_RC} out='${TRUNC_OUT:-empty}', expected rc=3 and 'TRUNCATED needed=44 cap=16'" \ "check int n = snprintf(buf, cap, ...); if ((size_t)n >= cap) report needed=n+1 and exit 3" fi TORN_OUT="" TORN_RC=0 if [ "$BUILT" -eq 1 ] && [ -f "$WORK/sensors.bin" ]; then cp "$WORK/sensors.bin" "$WORK/torn.bin" printf 'TORN999' >> "$WORK/torn.bin" TORN_OUT="$(timeout 3 "$WORK/telemetry_codec" inspect "$WORK/torn.bin" 64 2>/dev/null)" TORN_RC=$? fi if [ "$TORN_RC" -eq 2 ] && [ "$TORN_OUT" = "PARTIAL_TAIL bytes=7" ]; then tap_ok 5 "detects 7-byte partial trailing struct at EOF and exits with status 2" else tap_not_ok 5 "detects 7-byte partial trailing struct at EOF and exits with status 2" \ "rc=${TORN_RC} out='${TORN_OUT:-empty}', expected rc=2 and 'PARTIAL_TAIL bytes=7'" \ "compare ftello(fp) after item loop against total file size to detect trailing partial bytes" 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_m05_telemetry_codec/ so relative paths to files/ resolve directly.