#!/usr/bin/env python3 # SPDX-License-Identifier: MIT """Compare an unchanged stdio probe across pinned libc/linkage arms. Place fwrite-error-indicator.c beside this runner. Supply the unmodified upstream musl-1.2.5.tar.gz with --musl-archive. No download or system installation is made. Builds and binaries exist only in a private temporary directory. Output is JSON. """ import argparse from datetime import datetime, timezone import hashlib import json import os from pathlib import Path import platform import shutil import subprocess import sys import tarfile import tempfile MUSL_SHA256 = "a9a118bbe84d8764da0ea0d28b3ab3fae8477fc7e4085d90102b8596fc7c75e4" PROBE_SHA256 = "f8d632f6f508e08c379ea81e66a4dfb1b7866116f96b0ba452f20e99fd04eb62" def sha256(path): return hashlib.sha256(Path(path).read_bytes()).hexdigest() def run(command, cwd=None, timeout=60, env=None): return subprocess.run(command, cwd=cwd, env=env, check=True, capture_output=True, text=True, timeout=timeout) def repeat_count(value): try: value = int(value) except ValueError as error: raise argparse.ArgumentTypeError("repeats must be 1 to 20") from error if not 1 <= value <= 20: raise argparse.ArgumentTypeError("repeats must be 1 to 20") return value def signature(cases): return cases def main(): parser = argparse.ArgumentParser(description=__doc__) parser.add_argument("--musl-archive", required=True, type=Path) parser.add_argument("--repeats", type=repeat_count, default=5) args = parser.parse_args() if platform.system() != "Linux" or not Path("/dev/full").exists(): parser.error("Linux with /dev/full is required") for name in ("gcc", "make", "readelf"): if shutil.which(name) is None: parser.error(name + " is required") if sha256(args.musl_archive) != MUSL_SHA256: parser.error("musl archive hash does not match pinned upstream 1.2.5") probe = Path(__file__).with_name("fwrite-error-indicator.c").resolve() if PROBE_SHA256 and sha256(probe) != PROBE_SHA256: parser.error("probe differs from the previously published experiment") compiler = shutil.which("gcc") flags = ["-std=c11", "-Wall", "-Wextra", "-Werror"] env = os.environ.copy() for key in ("LD_PRELOAD", "LD_LIBRARY_PATH", "LIBRARY_PATH", "CPATH", "C_INCLUDE_PATH", "GCC_EXEC_PREFIX", "COMPILER_PATH"): env.pop(key, None) env["LC_ALL"] = "C" arms = [] with tempfile.TemporaryDirectory(prefix="hesela-stdio-libc-") as tmp: root = Path(tmp) with tarfile.open(args.musl_archive) as archive: archive.extractall(root, filter="data") musl = root / "musl-1.2.5" prefix = root / "musl-install" if (musl / "VERSION").read_text().strip() != "1.2.5": raise ValueError("unexpected musl version") reviewed = {name: sha256(musl / name) for name in ( "src/stdio/fwrite.c", "src/stdio/__stdio_write.c", "src/stdio/fflush.c", "COPYRIGHT")} configuration = ["./configure", "--disable-shared", "--prefix=" + str(prefix), "--syslibdir=" + str(prefix / "lib"), "CC=" + compiler] build_logs = {} for label, command in (("configure", configuration), ("make", ["make", "-j2"]), ("install", ["make", "install"])): result = run(command, cwd=musl, timeout=300, env=env) build_logs[label] = { "stdout_sha256": hashlib.sha256(result.stdout.encode()).hexdigest(), "stderr_sha256": hashlib.sha256(result.stderr.encode()).hexdigest(), } identity = root / "glibc-identity.c" identity.write_text('#include \n#include \n' 'int main(void) { puts(gnu_get_libc_version()); return 0; }\n') targets = [ ("glibc-dynamic", compiler, [], None), ("glibc-static", compiler, ["-static"], Path(run([compiler, "-print-file-name=libc.a"], env=env).stdout.strip()).resolve()), ("musl-1.2.5-static", str(prefix / "bin/musl-gcc"), ["-static"], prefix / "lib/libc.a"), ] for label, cc, link_flags, library in targets: binary = root / label link_map = root / (label + ".map") run([cc, *flags, *link_flags, str(probe), "-Wl,-Map=" + str(link_map), "-o", str(binary)], env=env) headers = run(["readelf", "-lW", str(binary)], env=env).stdout dynamic = run(["readelf", "-dW", str(binary)], env=env).stdout has_interpreter = "INTERP" in headers has_needed = "(NEEDED)" in dynamic if bool(link_flags) and (has_interpreter or has_needed): raise ValueError("static arm unexpectedly uses a dynamic dependency") if not link_flags and not (has_interpreter and has_needed): raise ValueError("dynamic control did not link dynamically") if library and str(library) not in link_map.read_text(): # GNU link maps can preserve a noncanonical compiler search path. loads = [line.split()[1] for line in link_map.read_text().splitlines() if line.startswith("LOAD ") and len(line.split()) == 2] if not any(Path(path).resolve() == library.resolve() for path in loads): raise ValueError("expected static libc archive absent from linker map") if label.startswith("glibc"): id_binary = root / (label + "-identity") run([cc, *flags, *link_flags, str(identity), "-o", str(id_binary)], env=env) libc_version = run([str(id_binary)], env=env).stdout.strip() else: libc_version = "1.2.5" observations = [] for repetition in range(1, args.repeats + 1): measured = json.loads(run([str(binary)], timeout=10, env=env).stdout) observations.append({"repeat": repetition, **measured}) arms.append({ "id": label, "libc_version": libc_version, "linkage": "static" if link_flags else "dynamic", "compile_flags": flags + link_flags, "binary_sha256": sha256(binary), "static_archive_sha256": sha256(library) if library else None, "linkage_verified": {"has_interpreter": has_interpreter, "has_needed_entry": has_needed, "expected_archive_in_map": True if library else None}, "runs": observations, "repeatable": all(signature(r["cases"]) == signature(observations[0]["cases"]) for r in observations), }) result = { "schema_version": 1, "experiment": "fwrite-cross-libc", "evidence_type": "deterministic-api-observation", "generated_at_utc": datetime.now(timezone.utc).isoformat().replace("+00:00", "Z"), "license": "MIT for Hesela runner and probe; observations are factual output", "environment": {"os": platform.system(), "kernel_release": platform.release(), "architecture": platform.machine(), "python": platform.python_version(), "compiler": run([compiler, "--version"], env=env).stdout.splitlines()[0]}, "method": { "repeat_count": args.repeats, "cases_per_arm_per_repeat": 3, "fresh_process_per_arm_per_repeat": True, "fresh_stream_per_case": True, "unchanged_probe": True, "single_threaded": True, "controlled_error_sink": "/dev/full", "payload_hex": "420a", "buffered_seed_hex": "41", "unbuffered_seed": None, "item_size": 1, "requested_items": 2, "supplied_buffer_bytes": 4096, "errno_convention": "Reset immediately before each measured call and captured immediately after; not a standalone success test.", "sequence": "setvbuf; optional seed; ferror; fwrite; ferror; fflush; ferror; clearerr; ferror; fclose", }, "sources_sha256": {probe.name: sha256(probe), Path(__file__).name: sha256(__file__)}, "musl_build": { "version": "1.2.5", "source_url": "https://musl.libc.org/releases/musl-1.2.5.tar.gz", "archive_sha256": MUSL_SHA256, "reviewed_sources_sha256": reviewed, "configure": ["--disable-shared", "--prefix=/musl-install", "--syslibdir=/musl-install/lib", "CC="], "parallel_jobs": 2, "logs_sha256": build_logs, "patched": False, "system_installation": False, }, "arms": arms, "summary": {"total_observations": len(arms) * 3 * args.repeats, "all_arms_repeatable": all(a["repeatable"] for a in arms), "temporary_directory_removed": not Path(tmp).exists()}, "limitations": [ "Version-pinned Linux API observations, not a libc conformance verdict or a latest-version survey.", "No filesystem exhaustion, delayed writeback, power loss, durability or recovery protocol tested.", "No partial-item write or concurrent output tested; repetitions are not incident-frequency samples.", "Buffered cases include a seed byte; unbuffered control does not.", "clearerr clears stream status, not evidence of prior output failure.", "Static and dynamic glibc arms control linkage; other versions, platforms and buffer states may differ.", ], } print(json.dumps(result, indent=2)) return 0 if __name__ == "__main__": try: sys.exit(main()) except (OSError, ValueError, subprocess.SubprocessError) as error: print("fwrite-cross-libc: " + str(error), file=sys.stderr) if isinstance(error, subprocess.CalledProcessError): print(error.stderr[-4000:], file=sys.stderr) sys.exit(1)