#!/usr/bin/env python3 # SPDX-License-Identifier: MIT """Reproduce three bounded Linux/glibc fwrite error observations. Place fwrite-error-indicator.c beside this file. Run: python3 run-fwrite-error-indicator.py --repeats 5 > fwrite-error-indicator.json This writes only to /dev/full and compiler output in a private temporary directory. """ import argparse from datetime import datetime, timezone import hashlib import json from pathlib import Path import platform import shutil import subprocess import sys import tempfile def repeats(value): try: count = int(value) except ValueError as error: raise argparse.ArgumentTypeError("repeats must be 1 to 20") from error if not 1 <= count <= 20: raise argparse.ArgumentTypeError("repeats must be 1 to 20") return count def checks(cases): if [c.get("mode") for c in cases] != [ "line-buffered", "fully-buffered", "unbuffered" ]: raise ValueError("unexpected case order") results = [] for index, case in enumerate(cases): expected_count = 2 if index < 2 else 0 early_error = index != 1 results.append( case["error_before"] == 0 and case["returned_items"] == expected_count and bool(case["error_after_fwrite"]) == early_error and case["fwrite_errno_is_enospc"] == early_error and case["fflush_return"] == (-1 if index == 1 else 0) and case["fflush_errno_is_enospc"] == (index == 1) and case["error_after_fflush"] == 1 and case["error_after_clearerr"] == 0 and case["fclose_return"] == 0 and (index == 2 or (case["seed_return"] == ord("A") and case["seed_errno"] == 0)) ) return results def main(): parser = argparse.ArgumentParser(description=__doc__) parser.add_argument("--repeats", type=repeats, default=5) args = parser.parse_args() if platform.system() != "Linux": parser.error("Linux and /dev/full are required") compiler = shutil.which("cc") if compiler is None: parser.error("cc is required") source = Path(__file__).with_name("fwrite-error-indicator.c").resolve() flags = ["-std=c11", "-Wall", "-Wextra", "-Werror"] compiler_version = subprocess.run( [compiler, "--version"], check=True, capture_output=True, text=True, timeout=10 ).stdout.splitlines()[0] runs = [] with tempfile.TemporaryDirectory(prefix="hesela-fwrite-error-") as directory: binary = Path(directory) / "probe" subprocess.run([compiler, *flags, str(source), "-o", str(binary)], check=True, capture_output=True, text=True, timeout=30) for repetition in range(1, args.repeats + 1): execution = subprocess.run([str(binary)], check=True, capture_output=True, text=True, timeout=10) observation = json.loads(execution.stdout) for case, passed in zip(observation["cases"], checks(observation["cases"])): case["matches_recorded_behavior"] = passed runs.append({"repeat": repetition, **observation}) matched = sum(c["matches_recorded_behavior"] for r in runs for c in r["cases"]) payload = { "schema_version": 1, "experiment": "glibc-fwrite-error-indicator", "evidence_type": "deterministic-api-observation", "license": "MIT (Hesela harness and runner); observations are factual output", "generated_at_utc": datetime.now(timezone.utc).isoformat().replace("+00:00", "Z"), "environment": { "os": platform.system(), "kernel_release": platform.release(), "architecture": platform.machine(), "libc": list(platform.libc_ver()), "python": platform.python_version(), "compiler": compiler_version, "compile_flags": flags, }, "method": { "repeat_count": args.repeats, "cases_per_repeat": 3, "fresh_process_per_repeat": True, "fresh_stream_per_case": True, "single_threaded": True, "controlled_error_sink": "/dev/full", "payload_hex": "420a", "item_size": 1, "requested_items": 2, "buffered_seed_hex": "41", "unbuffered_seed": None, "supplied_buffer_bytes": 4096, "buffer_note": "4096 is the supplied array length, not an active buffer size in unbuffered mode.", "errno_convention": "Reset to zero before each measured call and captured immediately afterward; errno alone does not classify success or failure.", "sequence": "setvbuf; optional seed; ferror; fwrite; ferror; fflush; ferror; clearerr; ferror; fclose", "comparison": "Expected values describe this recorded glibc configuration, not a cross-libc conformance test.", }, "sources_sha256": { p.name: hashlib.sha256(p.read_bytes()).hexdigest() for p in (source, Path(__file__).resolve()) }, "references": [ "https://raw.githubusercontent.com/bminor/glibc/glibc-2.39/libio/iofwrite.c", "https://raw.githubusercontent.com/bminor/glibc/glibc-2.39/libio/fileops.c", "https://man7.org/linux/man-pages/man3/ferror.3.html", "https://man7.org/linux/man-pages/man4/full.4.html", ], "runs": runs, "summary": { "matching_cases": matched, "total_cases": 3 * args.repeats, "all_matched": matched == 3 * args.repeats, "temporary_directory_removed": not Path(directory).exists(), }, "limitations": [ "One Linux/glibc environment; exact return sequences are not universal API guarantees.", "No filesystem fullness, device error, delayed writeback, power loss or durability test.", "Repeats test repeatability, not independent samples or an incident frequency.", "The line-buffered and fully-buffered cases have a seed byte; the unbuffered control does not.", "No partial-item write, concurrent output or recovery protocol is tested.", "clearerr clears the indicator; it does not establish successful output or repair.", ], } print(json.dumps(payload, indent=2)) return 0 if payload["summary"]["all_matched"] else 1 if __name__ == "__main__": try: sys.exit(main()) except (OSError, ValueError, subprocess.SubprocessError) as error: print(f"fwrite-error-indicator: {error}", file=sys.stderr) if isinstance(error, subprocess.CalledProcessError) and error.stderr: print(error.stderr, file=sys.stderr) sys.exit(1)