Lab 2: Byte-Exact Framed Slice Copier
Acquire and manage per-process file descriptors with exact open() flags and mode & ~umask permissions, build partial-count and EINTR-resilient read_full() and write_all() loops, and implement side-effect-safe lseek() byte-slicing tools.
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
File-extraction and firmware-slicing utilities fail dangerously in the field when they open output files with O_CREAT | O_TRUNC before checking whether the input descriptor is seekable or holds enough bytes—wiping an existing configuration or firmware backup to 0 bytes whenever a user accidentally passes a pipe (ESPIPE) or an out-of-range offset! Compounding that bug, single-shot read()/write() calls drop bytes on partial transfers, strlen() truncates binary slices at 0x00, and decimal 644 scrambles inode permissions. Here you will build framed_copy, a side-effect-safe, binary-exact POSIX slice extractor.
learner@ksa:~/gl-c01/lab-m02ls -lastarter/framed_copy.clearner@ksa:~/gl-c01/lab-m02starter: starter/framed_copy.c
learner@ksa:~/gl-c01/lab-m02$ bat starter/framed_copy.c File: starter/framed_copy.c #include <fcntl.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <unistd.h> /* BUGGY STARTER: * 1. Opens dst_path BEFORE validating src_path bounds or ESPIPE! * 2. Missing O_TRUNC and O_CLOEXEC; uses decimal 644 instead of octal 0644! * 3. Single unlooped read()/write() + strlen(buf) truncates at embedded 0x00! */ int main(int argc, char *argv[]) { if (argc != 5) { return 1; } off_t offset = atol(argv[3]); size_t length = (size_t)atol(argv[4]); int src_fd = open(argv[1], O_RDONLY); int dst_fd = open(argv[2], O_WRONLY | O_CREAT, 644); if (src_fd < 0 || dst_fd < 0) { return 1; } lseek(src_fd, offset, SEEK_SET); char buf[8192]; memset(buf, 0, sizeof(buf)); read(src_fd, buf, length); write(dst_fd, buf, strlen(buf)); close(src_fd); close(dst_fd); return 0; }step 2/15 · 2. learning objectives
- Implement
EINTR- and short-count-resilientwrite_all()andread_full()loops overuint8_tbuffers using signedssize_treturn checks. - Validate input seekability (
ESPIPE) and 64-bitoff_tslice bounds (offset <= src_sizeandlength <= src_size - offset) vialseek(src_fd, 0, SEEK_END)before opening or truncatingdst_path. - Enforce
O_CLOEXEC,O_TRUNC, octal0644(S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH) permissions, and checkedclose()error propagation (EIO).
step 3/15 · 3. environment requirements
- Host Execution Environment (Tested): Linux
6.12LTS (x86_64,glibc2.39+),#define _FILE_OFFSET_BITS 64and#define _POSIX_C_SOURCE 200809L. - Target Board Portability (
ARMv7Cortex-A7): Defining_FILE_OFFSET_BITS 64before all headers widensoff_tfrom 32-bitlong(2 GiB - 1ceiling onILP32ARMv7) to signed 64-bit, enabling identical multi-gigabyte partition slicing on 32-bit embedded targets.
step 4/15 · 4. required software & hardware
- Software Toolchain:
gcc(-std=c11 -Wall -Wextra -Werror),strace,cmp/sha256sum,stat, and/bin/sh. - Hardware: Standard Linux host environment (
0root privileges required).
step 5/15 · 5. complete executable commands
Run from labs/lab_m02_framed_copy/:
learner@ksa:~/gl-c01/lab-m02$ bat script.sh File: script.sh # 1. Compile the reference implementation with strict C11 and 64-bit off_t flags gcc -std=c11 -O2 -Wall -Wextra -Werror files/framed_copy.c -o /tmp/framed_copy # 2. Seed an 8 KiB binary file containing embedded 0x00 and 0xFF bytes dd if=/dev/urandom of=/tmp/ksa_src.bin bs=1024 count=8 status=none # 3. Extract exact 2048-byte window [500, 2548) and verify byte-for-byte identity /tmp/framed_copy /tmp/ksa_src.bin /tmp/ksa_dst.bin 500 2048 dd if=/tmp/ksa_src.bin bs=1 skip=500 count=2048 status=none | cmp -s - /tmp/ksa_dst.bin && echo "MATCH_OK" # 4. Verify side-effect safety: piped stdin fails with ESPIPE WITHOUT touching /tmp/ksa_dst.bin! printf 'pipe_bytes' | /tmp/framed_copy /dev/stdin /tmp/ksa_dst.bin 0 4 || stat -c 'preserved_bytes=%s mode=%a' /tmp/ksa_dst.bin # 5. Clean up scratch files and run the full TAP 13 test suite rm -f /tmp/framed_copy /tmp/ksa_src.bin /tmp/ksa_dst.bin sh check.sh*Why each command runs:* dd generates arbitrary binary bytes (including 0x00); cmp -s proves byte-exact extraction at offset 500; piping /dev/stdin triggers ESPIPE on lseek() to verify /tmp/ksa_dst.bin keeps preserved_bytes=2048 and mode=644; and sh check.sh runs all automated checks.
step 6/15 · 6. annotated source code (`starter/` flaws vs `files/` reference)
Flawed Baseline (starter/framed_copy.c)
- Destructive eager
open(): Opensdst_fdon line 20 before checking whethersrc_fdis seekable or long enough. - Decimal
644& missingO_TRUNC/O_CLOEXEC:open(argv[2], O_WRONLY | O_CREAT, 644)stamps sticky octal01204(--w----r-T) and leaves stale trailing bytes intact when overwriting larger files! - Unchecked
atol()&strlen(buf):atol()invokes UB on overflow, fixedchar buf[8192]overflows whenlength > 8192, andwrite(dst_fd, buf, strlen(buf))truncates at the first0x00byte.
Warning-Clean Reference (files/framed_copy.c)
- CLI Parsing (
main): Parses<offset>withstrtoll(errno == 0,*end == '\0',raw_off >= 0) and<length>withstrtoull(<= SIZE_MAX). - Precondition Ordering (
copy_slice): Openssrc_fd(O_RDONLY | O_CLOEXEC), queriessrc_size = lseek(src_fd, 0, SEEK_END)(aborting immediately onESPIPE!), validates subtraction boundsoffset <= src_size && (uintmax_t)(src_size - offset) >= (uintmax_t)length(zero signed-overflow risk), seekssrc_fdtooffset, and only then opensdst_fd(O_WRONLY | O_CREAT | O_TRUNC | O_CLOEXEC,0644). - Streaming Loop & Checked
close(): Streams4,096-byte chunks throughread_full()andwrite_all(), preserveserrnoacross error-pathclose()calls, and verifiesclose(dst_fd) == 0so deferred writebackEIOfaults are never masked.
step 7/15 · 7. expected output
learner@ksa:~/gl-c01/lab-m02$ bat listing.txt File: listing.txt $ sh check.sh TAP version 13 1..6 ok 1 - compiles cleanly with -std=c11 -Wall -Wextra -Werror ok 2 - copies binary slice with embedded 0x00 bytes and sets octal 0644 mode ok 3 - truncates pre-existing larger destination file via O_TRUNC ok 4 - rejects out-of-bounds slice without creating or modifying dst_path ok 5 - rejects non-seekable pipe input (ESPIPE) without touching dst_path ok 6 - handles 0-byte slice cleanly # pass 6/6step 8/15 · 8. explanation of observed behavior
When copy_slice() runs against a 64 KiB binary file for [4096, 36864) (32 KiB), lseek(src_fd, 0, SEEK_END) reads inode->i_size in kernel RAM (0 disk I/O), lseek(src_fd, 4096, SEEK_SET) positions src_fd's struct file.f_pos to 4096, open(dst_path, ... | O_TRUNC, 0644) resets any prior destination extents and masks 0644 & ~umask, and eight 4 KiB iterations transfer all 32,768 bytes without ever scanning for '\0'. When /dev/stdin is a pipe, lseek(src_fd, 0, SEEK_END) returns (off_t)-1 with errno == ESPIPE at line 62—returning -1 before line 83 ever touches dst_path.
step 9/15 · 9. experiment variations
- Chunk-Size Syscall Trade-Off: Change
uint8_t chunk[4096]tochunk[64]vschunk[65536]on a1 MiBslice and comparestrace -c -e trace=read,writesyscall counts (16,384calls vs256calls vs16calls). umaskSensitivity Test: Run(umask 0077 && ./framed_copy src.bin dst.bin 0 64 && stat -c '%a' dst.bin)to confirm the kernel computes0644 & ~0077 = 0600(rw-------).- Zero-Length Boundary: Run
./framed_copy src.bin empty.bin 2048 0at exactEOF(offset == src_size,length == 0) to confirm a valid0-byte file is created cleanly (copied=0).
step 10/15 · 10. performance measurements
Measured on Host x86_64 Linux 6.12 LTS (CLOCK_MONOTONIC, 5 warmup runs, N = 35 timed extractions of a 32 KiB slice from a 64 KiB file):
| Metric | Measured Host (x86_64 Linux 6.12) | Target Board Expectation (ARMv7 Cortex-A7 eMMC) |
|---|---|---|
32 KiB slice CLI latency (p50 / p95 / p99) | 2,950.3 us / 3,299.9 us / 3,608.9 us | ~11,000–18,000 us (page-cache warm; higher on cold eMMC read) |
Kernel lseek + read + write calls (32 KiB) | 2 + 8 + 8 (18 data-path syscalls) | 2 + 8 + 8 (_llseek on 32-bit ARMv7) |
step 11/15 · 11. troubleshooting
| Symptom | Root Cause | Fix | |||
|---|---|---|---|---|---|
Destination file shrinks to 0 bytes when offset is invalid | `open(dst_path, ... \ | O_TRUNC) executed before lseek(src_fd, 0, SEEK_END)` bounds check | Validate src_size and bounds before opening dst_path | ||
| Output file has trailing stale bytes from an earlier run | O_TRUNC omitted on open(dst_path, ...) | Include `O_WRONLY \ | O_CREAT \ | O_TRUNC \ | O_CLOEXEC` |
offset + length wraps negative on huge values | Signed off_t overflow Undefined Behavior | Check offset <= src_size first, then (uintmax_t)(src_size - offset) < length | |||
Permissions show --w----r-T (1204) | Passed decimal 644 instead of octal 0644 | Use 0644 or `S_IRUSR \ | S_IWUSR \ | S_IRGRP \ | S_IROTH` |
step 12/15 · 12. guided questions
- Why does
copy_slice()treatgot < (ssize_t)wantfromread_full()as an error (EIO) even though we already verifiedoffset + length <= src_size?
- *Hint 1:* Can another process concurrently call
ftruncate()onsrc_pathbetween yourSEEK_ENDcheck and yourread_full()loop? - *Hint 2:* What does
read_full()return ifsrc_pathshrinks mid-copy and hits prematureEOF(0)?
- Why do we save
int saved = errno;before callingclose(src_fd)on error branches?
- *Hint 1:* Check
m03-l02's rules on whetherclose()can modifyerrnoor leave callers guessing ifclose()itself hits an internal check. - *Hint 2:* Trace what
perror("copy_slice")inmain()prints iferrnowas overwritten during cleanup!
step 13/15 · 13. independent challenges
- Near Transfer — Atomic Staging Slice Extractor: Upgrade
copy_slice()so that instead of truncatingdst_pathin place (which leaves a partialdst_pathifSIGKILLhits mid-copy), it writes into<dst_path>.tmp.<pid>opened withO_CREAT | O_EXCL | O_CLOEXECand atomicallyrename()s ontodst_pathonly afterclose()succeeds! - Far Transfer — Zero-Copy Kernel
copy_file_range(2)Fastpath: On Linux4.5+(#define _GNU_SOURCE), replace the user-spaceread_full/write_all4 KiBbounce buffer withcopy_file_range(src_fd, &in_off, dst_fd, NULL, left, 0)(falling back toread_full/write_allonEXDEVcross-filesystem copies) and benchmark64 MiBthroughput (MiB/s) withCLOCK_MONOTONIC.
step 14/15 · 14. solutions & explanations
- Guided Question 1: Because Unix filesystems allow concurrent processes to truncate an open file without mandatory locking,
read_full()returning< wantdetects concurrent truncation (EIO) instead of silently writing fewer bytes thancopied=<length>promised. - Guided Question 2: Saving
errnobeforeclose()guaranteesperror("copy_slice")reports the exact root cause (ESPIPE,EINVAL,ENOSPC) rather than any side effect of cleanup. - Challenge 2 Key Idiom:
ssize_t n = copy_file_range(src_fd, NULL, dst_fd, NULL, left, 0);copies page-cache folios (or issues filesystem CoWreflinkclones onBtrfs/XFS) entirely insideRing 0with zero user-spacememcpy()traffic!
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-m02./framed_copy sample.bin slice.bin 16 24 && stat -c 'bytes=%s mode=%a' slice.bin && cat slice.bin && echolearner@ksa:~/gl-c01/lab-m02copied=24bytes=24 mode=644KSA_SLICE_PAYLOAD_24BYTEProgressive hints & solution
hint 1
Compare starter/framed_copy.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/framed_copy.c
learner@ksa:~/gl-c01/lab-m02$ bat files/framed_copy.c File: files/framed_copy.c #define _FILE_OFFSET_BITS 64 #define _POSIX_C_SOURCE 200809L #include <errno.h> #include <fcntl.h> #include <inttypes.h> #include <stdint.h> #include <stdio.h> #include <stdlib.h> #include <sys/stat.h> #include <sys/types.h> #include <unistd.h> int write_all(int fd, const void *buf, size_t count) { const uint8_t *p = (const uint8_t *)buf; size_t remaining = count; while (remaining > 0U) { ssize_t n = write(fd, p, remaining); if (n < 0) { if (errno == EINTR) { continue; } return -1; } p += (size_t)n; remaining -= (size_t)n; } return 0; } ssize_t read_full(int fd, void *buf, size_t count) { uint8_t *p = (uint8_t *)buf; size_t total = 0U; while (total < count) { ssize_t n = read(fd, p + total, count - total); if (n == 0) { break; } if (n < 0) { if (errno == EINTR) { continue; } return -1; } total += (size_t)n; } return (ssize_t)total; } int copy_slice(const char *src_path, const char *dst_path, off_t offset, size_t length) { if (offset < 0) { errno = EINVAL; return -1; } int src_fd = open(src_path, O_RDONLY | O_CLOEXEC); if (src_fd == -1) { return -1; } off_t src_size = lseek(src_fd, 0, SEEK_END); if (src_size == (off_t)-1) { int saved = errno; (void)close(src_fd); errno = saved; return -1; } if (offset > src_size || (uintmax_t)(src_size - offset) < (uintmax_t)length) { (void)close(src_fd); errno = EINVAL; return -1; } if (lseek(src_fd, offset, SEEK_SET) == (off_t)-1) { int saved = errno; (void)close(src_fd); errno = saved; return -1; } int dst_fd = open(dst_path, O_WRONLY | O_CREAT | O_TRUNC | O_CLOEXEC, S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH); if (dst_fd == -1) { int saved = errno; (void)close(src_fd); errno = saved; return -1; } uint8_t chunk[4096]; size_t left = length; while (left > 0U) { size_t want = (left < sizeof(chunk)) ? left : sizeof(chunk); ssize_t got = read_full(src_fd, chunk, want); if (got < 0 || (size_t)got != want) { int saved = (got < 0) ? errno : EIO; (void)close(dst_fd); (void)close(src_fd); errno = saved; return -1; } if (write_all(dst_fd, chunk, want) == -1) { int saved = errno; (void)close(dst_fd); (void)close(src_fd); errno = saved; return -1; } left -= want; } int rc = 0; int saved_err = 0; if (close(dst_fd) == -1) { rc = -1; saved_err = errno; } if (close(src_fd) == -1 && rc == 0) { rc = -1; saved_err = errno; } if (rc == -1) { errno = saved_err; } return rc; } int main(int argc, char *argv[]) { if (argc != 5) { fprintf(stderr, "Usage: %s <src_path> <dst_path> <offset> <length>\n", argv[0]); return EXIT_FAILURE; } char *end_off = NULL; errno = 0; long long raw_off = strtoll(argv[3], &end_off, 10); if (errno != 0 || end_off == argv[3] || *end_off != '\0' || raw_off < 0) { fprintf(stderr, "Invalid offset: %s\n", argv[3]); return EXIT_FAILURE; } char *end_len = NULL; errno = 0; unsigned long long raw_len = strtoull(argv[4], &end_len, 10); if (errno != 0 || end_len == argv[4] || *end_len != '\0' || raw_len > (unsigned long long)SIZE_MAX) { fprintf(stderr, "Invalid length: %s\n", argv[4]); return EXIT_FAILURE; } if (copy_slice(argv[1], argv[2], (off_t)raw_off, (size_t)raw_len) == -1) { perror("copy_slice"); return EXIT_FAILURE; } printf("copied=%zu\n", (size_t)raw_len); return EXIT_SUCCESS; }Run the check
From labs/lab_m02_framed_copy/, run ./check.sh. A complete solution emits TAP version 13 with every test point marked ok and exits 0:
learner@ksa:~/gl-c01/lab-m02./check.shTAP version 131..5ok 1 - builds with -std=c11 -Wall -Wextra and no warningsok 2 - opens descriptors with O_CLOEXEC and retries partial I/O on EINTRok 3 - extracts exact 5200-byte binary slice and truncates stale bytesok 4 - creates destination file with octal 0644 permissions under umask 0022ok 5 - rejects out-of-bounds offsets and pipes before creating destination# 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-m02./check.shTAP version 131..5ok 1 - builds with -std=c11 -Wall -Wextra and no warningsnot ok 2 - opens descriptors with O_CLOEXEC and retries partial I/O on EINTR --- message: 'files/framed_copy.c is missing O_CLOEXEC or EINTR retry loops' hint: 'pass O_CLOEXEC to every open() and retry read()/write() when errno == EINTR' ...not ok 3 - extracts exact 5200-byte binary slice and truncates stale bytes --- message: 'slice mismatch (output is 7000 bytes, expected 5200 binary-exact bytes)' hint: 'pass O_TRUNC on destination open() and loop read()/write() until length reaches 0' ...not ok 4 - creates destination file with octal 0644 permissions under umask 0022 --- message: 'created destination permissions are 1204, expected 644' hint: 'pass octal literal 0644 (not decimal 644) as the third argument to open()' ...not ok 5 - rejects out-of-bounds offsets and pipes before creating destination --- message: 'out-of-bounds offset+length succeeded instead of failing' hint: 'validate source size via lseek(SEEK_END) and seek to offset before opening dst_path' ...# 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-m02$ 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" SRC="files/framed_copy.c" WORKDIR="$(mktemp -d "${TMPDIR:-/tmp}/ksa_lab_m02.XXXXXX")" trap 'rm -rf "$WORKDIR"' EXIT BIN="$WORKDIR/framed_copy" BUILT=0 if [ ! -f "$SRC" ]; then tap_not_ok 1 "builds with -std=c11 -Wall -Wextra and no warnings" \ "missing source file $SRC" \ "place your implementation in files/framed_copy.c" elif gcc -std=c11 -Wall -Wextra -Werror "$SRC" -o "$BIN" 2>"$WORKDIR/cc.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 "$WORKDIR/cc.err")" \ "fix all C11 compiler warnings and errors in files/framed_copy.c" fi if [ -f "$SRC" ] && grep -q "O_CLOEXEC" "$SRC" && grep -q "EINTR" "$SRC"; then tap_ok 2 "opens descriptors with O_CLOEXEC and retries partial I/O on EINTR" else tap_not_ok 2 "opens descriptors with O_CLOEXEC and retries partial I/O on EINTR" \ "files/framed_copy.c is missing O_CLOEXEC or EINTR retry loops" \ "pass O_CLOEXEC to every open() and retry read()/write() when errno == EINTR" fi umask 0022 INFILE="$WORKDIR/input.bin" EXPFILE="$WORKDIR/expected.bin" OUTFILE="$WORKDIR/output.bin" python3 - "$INFILE" "$EXPFILE" <<'PY' import sys data = bytes(((i * 37) & 0xFF) if (i % 19 != 0) else 0x00 for i in range(8192)) open(sys.argv[1], "wb").write(data) open(sys.argv[2], "wb").write(data[1000:6200]) PY dd if=/dev/zero of="$OUTFILE" bs=1000 count=7 >/dev/null 2>&1 if [ "$BUILT" -eq 1 ] && timeout 3 "$BIN" "$INFILE" "$OUTFILE" 1000 5200 >"$WORKDIR/run.out" 2>"$WORKDIR/run.err" && cmp -s "$EXPFILE" "$OUTFILE"; then tap_ok 3 "extracts exact 5200-byte binary slice and truncates stale bytes" else ACTUAL_SZ=0 [ -f "$OUTFILE" ] && ACTUAL_SZ="$(wc -c < "$OUTFILE" | tr -d ' ')" tap_not_ok 3 "extracts exact 5200-byte binary slice and truncates stale bytes" \ "slice mismatch (output is ${ACTUAL_SZ} bytes, expected 5200 binary-exact bytes)" \ "pass O_TRUNC on destination open() and loop read()/write() until length reaches 0" fi rm -f "$OUTFILE" MODE="none" if [ "$BUILT" -eq 1 ] && timeout 3 "$BIN" "$INFILE" "$OUTFILE" 0 64 >/dev/null 2>&1 && [ -f "$OUTFILE" ]; then MODE="$(stat -c '%a' "$OUTFILE")" fi if [ "$MODE" = "644" ]; then tap_ok 4 "creates destination file with octal 0644 permissions under umask 0022" else tap_not_ok 4 "creates destination file with octal 0644 permissions under umask 0022" \ "created destination permissions are ${MODE}, expected 644" \ "pass octal literal 0644 (not decimal 644) as the third argument to open()" fi NOFILE="$WORKDIR/must_not_exist.bin" PIPE_NOFILE="$WORKDIR/pipe_must_not_exist.bin" BOUNDS_OK=1 if [ "$BUILT" -ne 1 ]; then BOUNDS_OK=0 REASON="framed_copy binary was not built" elif timeout 3 "$BIN" "$INFILE" "$NOFILE" 8000 512 >/dev/null 2>&1; then BOUNDS_OK=0 REASON="out-of-bounds offset+length succeeded instead of failing" elif [ -e "$NOFILE" ]; then BOUNDS_OK=0 REASON="out-of-bounds request created destination file before checking source bounds" elif printf 'pipe-stream-payload' | timeout 3 "$BIN" /dev/stdin "$PIPE_NOFILE" 0 4 >/dev/null 2>&1; then BOUNDS_OK=0 REASON="non-seekable pipe input succeeded instead of failing on lseek ESPIPE" elif [ -e "$PIPE_NOFILE" ]; then BOUNDS_OK=0 REASON="ESPIPE failure path created destination file before validating source seekability" fi if [ "$BOUNDS_OK" -eq 1 ]; then tap_ok 5 "rejects out-of-bounds offsets and pipes before creating destination" else tap_not_ok 5 "rejects out-of-bounds offsets and pipes before creating destination" \ "$REASON" \ "validate source size via lseek(SEEK_END) and seek to offset before opening dst_path" 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_m02_framed_copy/ so relative paths to files/ resolve directly.