#!/usr/bin/env python3 """Compile and observe bounded Linux descriptor operations in private temporary files. Usage: python3 run-descriptor-lifetime.py --repeats 5 > descriptor-lifetime.json This script emits actual API observations, not a durability or failure-rate study. """ import argparse from datetime import datetime, timezone import hashlib import json import platform from pathlib import Path import shutil import subprocess import sys import tempfile CASE_IDS = [ "duplicate-survives-close", "released-number-reused", "stale-close-closes-replacement", "dup2-replaces-and-shares-offset", "dup2-self-is-no-op", "dup2-invalid-source-preserves-target", "close-invalid-descriptor", ] LIMITATIONS = [ "Linux-only observations from one host and one recorded kernel; not a portability study.", "Repeated deterministic checks are not independent statistical samples or a failure-rate estimate.", "Single-threaded, deliberately ordered operations; no concurrent close or allocation race was tested.", "No EINTR, EIO or ENOSPC was injected or observed; all valid-descriptor close calls succeeded.", "The deliberate stale second close follows a successful close and descriptor reuse, not an error retry.", "dup2 replacement and shared offsets were observed; atomicity is an API guarantee, not proved by timing here.", "No fsync, power loss, crash recovery, persistence or device durability was tested.", "EBADF is observed separately from reading a deliberately closed replacement, dup2 with source -1 and close(-1); these are invalid-descriptor checks, not storage faults.", ] def bounded_repeats(value): try: result = int(value) except ValueError as exc: raise argparse.ArgumentTypeError("repeats must be an integer from 1 to 20") from exc if not 1 <= result <= 20: raise argparse.ArgumentTypeError("repeats must be an integer from 1 to 20") return result def main(): parser = argparse.ArgumentParser(description=__doc__) parser.add_argument("--repeats", type=bounded_repeats, default=5) args = parser.parse_args() if platform.system() != "Linux": parser.error("this observation runner supports Linux only") compiler = shutil.which("cc") if compiler is None: parser.error("a C compiler named cc is required") directory = Path(__file__).resolve().parent source = directory / "descriptor-lifetime.c" sources = { path.name: hashlib.sha256(path.read_bytes()).hexdigest() for path in (source, Path(__file__).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-descriptor-lifetime-") as temporary: root = Path(temporary) executable = root / "descriptor-lifetime" subprocess.run( [compiler, *flags, str(source), "-o", str(executable)], check=True, capture_output=True, text=True, timeout=30, ) for index in range(1, args.repeats + 1): trial_directory = root / f"repeat-{index}" trial_directory.mkdir(mode=0o700) process = subprocess.run( [str(executable), str(trial_directory)], check=True, capture_output=True, text=True, timeout=5, close_fds=True, ) observation = json.loads(process.stdout) if [case["id"] for case in observation["cases"]] != CASE_IDS: raise ValueError("unexpected case sequence from C harness") if not all(case["passed"] is True for case in observation["cases"]): raise ValueError("C harness reported a failed check") runs.append({"repeat": index, **observation}) payload = { "schema_version": 1, "experiment": "linux-descriptor-lifetime", "evidence_type": "deterministic-api-observation", "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": len(CASE_IDS), "sequence": CASE_IDS, "one_fresh_process_per_repeat": True, "temporary_files_only": True, "single_threaded": True, "randomization": "none; deterministic API sequence", "comparison": "checked syscall returns, byte contents, file identities, shared offsets and per-descriptor close-on-exec flags", }, "sources_sha256": sources, "references": [ "https://man7.org/linux/man-pages/man2/open.2.html", "https://man7.org/linux/man-pages/man2/dup.2.html", "https://man7.org/linux/man-pages/man2/close.2.html", ], "runs": runs, "summary": { "passed_cases": sum(case["passed"] for run in runs for case in run["cases"]), "total_cases": args.repeats * len(CASE_IDS), "all_passed": True, "temporary_directory_removed": not root.exists(), }, "limitations": LIMITATIONS, } print(json.dumps(payload, indent=2)) if __name__ == "__main__": try: main() except (OSError, ValueError, subprocess.SubprocessError) as error: print(f"descriptor-lifetime: {error}", file=sys.stderr) if isinstance(error, subprocess.CalledProcessError) and error.stderr: print(error.stderr, file=sys.stderr) sys.exit(1)