Spaces:
Sleeping

File size: 3,698 Bytes
a70359d
a0d90c4
 
223bac6
a0d90c4
 
 
 
 
 
 
 
 
223bac6
a70359d
8d598a4
223bac6
 
a0d90c4
223bac6
 
 
 
a70359d
 
 
 
 
 
8d598a4
a0d90c4
223bac6
 
a70359d
 
223bac6
 
a0d90c4
8d598a4
a0d90c4
 
 
223bac6
 
a0d90c4
 
223bac6
8d598a4
a0d90c4
 
 
 
 
 
223bac6
a0d90c4
 
8d598a4
223bac6
a0d90c4
 
223bac6
a0d90c4
223bac6
a70359d
a0d90c4
 
 
 
 
 
 
 
 
 
a70359d
 
a0d90c4
 
 
 
 
 
 
 
 
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
import os
import shutil
import sys
from functools import partial
from pathlib import Path
from tempfile import TemporaryDirectory
from time import monotonic

from runner import ROOT, lift, read_preview, require_outputs, run_command

TOOL = ROOT / "ccs"


def stages(work, log, deadline, *, binary=None, entries=()):
    env = dict(os.environ, LD_LIBRARY_PATH=str(TOOL))
    yield "Lifting the binary to assembly…", ()
    name = lift(TOOL, work, log, deadline, ["--GNASM"], env=env, binary=binary, entries=entries)
    run = partial(run_command, deadline=deadline, limit_output=binary is not None)
    nasm = work / "nasm"
    assembly = nasm / f"{name}.asm"
    mapping = nasm / f"{name}.map"
    obj = f"{name}.o"
    theory = f"PCode_{name}"
    require_outputs(assembly, nasm / "__gmon_start__.c")
    _, opening, annotations = assembly.read_text().partition("\n%ifdef COMMENT\n")
    addresses, closing, _ = annotations.partition("\n%endif")
    if not (opening and addresses and closing):
        raise RuntimeError("FoxDec did not emit the address mapping in the NASM output.")
    mapping.write_text(addresses + "\n")
    yield "Assembling and linking the lifted program…", ()

    run(["nasm", "-felf64", "-g", "-F", "dwarf", "-o", obj, assembly.name], nasm, log)
    run(["gcc", "-c", "__gmon_start__.c", "-o", "__gmon_start__.o"], nasm, log)
    # Keep the end-of-data label distinct from the stderr copy relocation.
    (nasm / "layout.ld").write_text("SECTIONS { . = ALIGN(32); } INSERT BEFORE .data;\n")
    run(["gcc", "-g", "-m64", "-nostartfiles", "-fgnu-tm", "-Wl,-T,layout.ld",
         "-o", "a.out", obj, "__gmon_start__.o"], nasm, log)
    require_outputs(nasm / "a.out")
    yield "Generating the certificate with Ghidra…", ()

    certificate = work / "certificate"
    certificate.mkdir()
    run([TOOL / "bin/certgen", f"../{name}", "../nasm/a.out", f"../nasm/{mapping.name}"], certificate, log)
    blocks = sorted(certificate.glob(f"{theory}_*_*.thy"))
    if not blocks:
        raise RuntimeError("The generator produced no block theories.")
    require_outputs(certificate / f"{theory}.thy", certificate / f"{theory}_mapping.thy", *blocks)
    yield "Preparing Isabelle verification…", ()

    shutil.copyfile(TOOL / "PCode.thy", certificate / "PCode.thy")
    (certificate / "ROOT").write_text(
        'session FoxDec_Certificate = HOL +\n'
        '  options [document = false, quick_and_dirty = false]\n'
        '  sessions "HOL-Library" "HOL-Eisbach" Word_Lib\n'
        f'  theories {theory}\n'
    )
    verification = work / "verification.log"
    yield "Checking the certificate with Isabelle (this may take several minutes)…", ()
    run(
        ["/opt/Isabelle2023/bin/isabelle", "build", "-c", "-v", "-o", "threads=2",
         "-d", "/opt/Word_Lib", "-D", ".", "FoxDec_Certificate"],
        certificate, verification,
    )
    yield f"Isabelle2023 verified {theory}.thy", [
        verification,
        assembly, mapping, *sorted(certificate.glob("*.thy")),
        certificate / "ROOT", log,
    ]


def main(timeout):
    start = monotonic()
    with TemporaryDirectory(prefix="foxdec-ccs-") as directory:
        work = Path(directory)
        try:
            for stage, _ in stages(work, work / "run.log", start + float(timeout)):
                print(f"{monotonic() - start:.1f}s · {stage}", flush=True)
            print(read_preview(work / "verification.log", tail=True))
        except (RuntimeError, TimeoutError, OSError):
            for log in ("run.log", "verification.log"):
                print(read_preview(work / log, tail=True), file=sys.stderr)
            raise


if __name__ == "__main__":
    main(*sys.argv[1:])