Spaces:
Sleeping

foxdec / runner.py
ejschwartz's picture
Improve artifact workspace and remove quickstart
8d598a4
Raw History Blame Contribute Delete
4.99 kB
import os
import shutil
import signal
import struct
import subprocess
from contextlib import nullcontext
from pathlib import Path
from time import monotonic
ROOT = Path("/opt/foxdec")
DEADLINE = 300
MAX_UPLOAD = 16 * 1024 * 1024
MAX_OUTPUT_FILE = 8 * 1024 * 1024
def read_preview(path, *, tail=False):
if not path.is_file():
return ""
with path.open("rb") as stream:
size = stream.seek(0, os.SEEK_END)
stream.seek(max(0, size - 12_000) if tail else 0)
preview = stream.read(12_000).decode(errors="replace").strip()
if size <= 12_000:
return preview
return "…\n" + preview if tail else preview + "\n…"
class CommandError(RuntimeError):
def __init__(self, command, code):
super().__init__(f"{Path(command).name} exited with status {code}.")
self.code = code
def run_command(args, work, log, deadline, *, env=None, stdout=None, limit_output=False):
if monotonic() >= deadline:
raise TimeoutError("The job reached its time limit.")
command = Path(args[0]).name
if limit_output:
args = ["prlimit", f"--fsize={MAX_OUTPUT_FILE}", "--", *args]
with log.open("ab") as diagnostics, (stdout.open("wb") if stdout else nullcontext(diagnostics)) as output:
with subprocess.Popen(
args, cwd=work, env=env, stdout=output, stderr=diagnostics,
stdin=subprocess.DEVNULL, start_new_session=True,
) as process:
try:
code = process.wait(timeout=max(0, deadline - monotonic()))
except subprocess.TimeoutExpired:
raise TimeoutError("The job reached its time limit.") from None
finally:
try:
os.killpg(process.pid, signal.SIGKILL)
except ProcessLookupError:
pass
if code:
raise CommandError(command, code)
def require_outputs(*paths):
for path in paths:
if not path.is_file() or not path.stat().st_size:
raise RuntimeError(f"Expected output was missing or empty: {path.name}.")
def stage_upload(source, work, entries):
with Path(source).open("rb") as stream:
data = stream.read(MAX_UPLOAD + 1)
if len(data) > MAX_UPLOAD:
raise ValueError("Choose a binary no larger than 16 MiB.")
if len(data) < 64 or data[:7] != b"\x7fELF\x02\x01\x01":
raise ValueError("Choose a 64-bit little-endian Linux ELF binary.")
kind, machine, version, entry = struct.unpack_from("<HHIQ", data, 16)
if machine != 62 or version != 1 or kind not in (2, 3):
raise ValueError("Choose an x86-64 ELF executable or shared object.")
if not (entry or entries):
raise ValueError("This ELF file has no entry point. Enter a starting address.")
binary = work / "uploaded"
binary.write_bytes(data)
return binary
def lift(tool, work, log, deadline, options, *, env=None, binary=None, entries=()):
if binary is None:
binary = work / "wc"
for name in ("wc", "wc.entry"):
shutil.copyfile(tool / "binary" / name, work / name)
custom = False
else:
custom = True
if entries:
binary.with_suffix(".entry").write_text("".join(f"{address:#x}\n" for address in entries))
run_command(
[tool / "bin/foxdec-exe", "-c", tool / "config/config.dhall", "-d",
"./", "-n", binary.name, "-i", "BINARY", *options],
work, log, deadline, env=env, limit_output=custom,
)
return binary.name
def pldi(work, log, deadline, *, binary=None, entries=()):
yield "Constructing the state-space model…", ()
tool = ROOT / "pldi"
if binary is not None:
analysis = work / "analysis.txt"
args = [tool / "bin/construct-ssm", binary.name, *map(str, entries)]
try:
run_command(args, work, log, deadline, stdout=analysis, limit_output=True)
except CommandError as error:
if not analysis.stat().st_size:
raise
yield f"Analysis stopped. {error}", [analysis, log]
else:
require_outputs(analysis)
yield "", [analysis, log]
return
shutil.copytree(tool / "example", work, dirs_exist_ok=True)
env = dict(os.environ, PATH=f"{tool / 'bin'}:{os.environ['PATH']}")
analysis, diagnostics = (work / f"simple_local_array.{ext}" for ext in ("out", "err"))
note = ""
try:
run_command(["make"], work, log, deadline, env=env)
except CommandError as error:
expected = "construct-ssm: Don't know where to return: val == 64varRSP00, pred =="
if error.code != 2 or not read_preview(diagnostics).startswith(expected):
raise
note = "Reproduced the release’s unresolved return diagnostic."
require_outputs(analysis)
if not diagnostics.is_file():
raise RuntimeError("The PLDI example produced no diagnostics file.")
yield note, [analysis, diagnostics, log]