Spaces:
Sleeping

File size: 4,989 Bytes
a0d90c4
 
 
223bac6
a0d90c4
223bac6
a0d90c4
 
 
 
 
223bac6
 
a0d90c4
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
223bac6
a0d90c4
 
223bac6
 
 
 
a0d90c4
223bac6
a0d90c4
 
 
 
 
 
 
 
 
 
 
 
223bac6
a0d90c4
 
 
 
 
 
 
 
223bac6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a0d90c4
 
223bac6
 
a0d90c4
223bac6
a0d90c4
 
223bac6
8d598a4
a0d90c4
223bac6
 
 
 
 
 
 
 
 
 
 
 
 
 
a0d90c4
 
 
 
 
 
 
 
 
 
a70359d
a0d90c4
 
 
a70359d
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
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]