Spaces:
Sleeping
Sleeping
File size: 16,921 Bytes
d3b7f65 a0d90c4 223bac6 8d598a4 a0d90c4 c2e30e3 a0d90c4 a70359d 8d598a4 31b9410 a0d90c4 223bac6 c2e30e3 a0d90c4 223bac6 31b9410 223bac6 c2e30e3 a0d90c4 c2e30e3 a0d90c4 83a9a5a 8d598a4 d3b7f65 8d598a4 83a9a5a 8d598a4 c2e30e3 8d598a4 c2e30e3 8d598a4 c2e30e3 8d598a4 a0d90c4 223bac6 f9afae4 223bac6 31b9410 c2e30e3 31b9410 f05dfe4 31b9410 f05dfe4 c2e30e3 f9afae4 223bac6 c2e30e3 31b9410 223bac6 8d598a4 31b9410 a0d90c4 223bac6 a0d90c4 c2e30e3 a70359d a0d90c4 223bac6 f9afae4 223bac6 31b9410 223bac6 31b9410 a70359d 8d598a4 a70359d 8d598a4 83a9a5a 8d598a4 a70359d 8d598a4 a0d90c4 a70359d 223bac6 a0d90c4 a70359d a0d90c4 8d598a4 a0d90c4 8d598a4 c2e30e3 8d598a4 c2e30e3 8d598a4 a0d90c4 223bac6 a0d90c4 8d598a4 31b9410 f05dfe4 8d598a4 a0d90c4 f05dfe4 c2e30e3 a0d90c4 31b9410 a0d90c4 223bac6 | 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 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 | import base64
import logging
import re
from queue import Empty, Queue
from threading import Thread
import subprocess
from html import escape
from pathlib import Path
from tempfile import TemporaryDirectory
from time import monotonic
import gradio as gr
from pygments import highlight
from pygments.formatters import HtmlFormatter
from pygments.lexers import CLexer, IsabelleLexer, NasmLexer
from ccs import stages as ccs_stages
from runner import DEADLINE, MAX_UPLOAD, pldi, read_preview, stage_upload
import sefm
from sefm import stages as sefm_stages
ARTIFACTS = {
"SEFM 2020 · C decompilation": ("wc", 120, sefm_stages,
"Decompiles x86-64 functions to C with the paper’s decompiler, then recompiles the C with `gcc`."),
"PLDI 2022 · SSM Construction": ("simple_local_array", DEADLINE, pldi,
"Builds a symbolic state machine for a binary and shows its assembly, graphs and diagnostics."),
"CCS 2024 · Verified lifting": ("wc", 480, ccs_stages,
"Lifts a binary to symbolized assembly, recompiles it and checks an equivalence certificate in Isabelle. "
"The example takes about four minutes."),
}
EXAMPLE = "Built-in example"
UPLOAD = "Upload a binary"
SOURCE = "Compile C source"
DISPLAY_LIMIT = 4 * 1024 * 1024
HIGHLIGHT_LIMIT = 1024 * 1024
LEXERS = {".c": CLexer, ".h": CLexer, ".asm": NasmLexer, ".thy": IsabelleLexer}
HIGHLIGHT_CSS = "\n".join(rule for style, scope in (("friendly", ".foxdec-results pre"), ("monokai", ".dark .foxdec-results pre"))
for rule in HtmlFormatter(style=style).get_token_style_defs(scope))
logger = logging.getLogger(__name__)
def prepare():
return gr.update(value="Queued", visible=True), "", gr.update(interactive=False)
def display_results(work, files):
groups = {name: [] for name in ("C code", "Functions", "Overview", "Assembly", "Graphs", "Certificate", "Diagnostics")}
functions = {}
for path in sorted(files):
name = path.relative_to(work).as_posix()
parts = path.relative_to(work).parts
if len(parts) >= 3 and parts[0] == "functions":
functions.setdefault(parts[1], []).append(path)
continue
group = ("C code" if name.endswith(".c") else
"Assembly" if name.endswith(".asm") else
"Graphs" if name.endswith(".dot") else
"Certificate" if name.startswith("certificate/") or name == "verification.log" else
"Diagnostics" if name.endswith((".log", ".err")) else "Overview")
groups[group].append((name, [path]))
groups["Functions"] = list(functions.items())
tabs, panels = [], []
for group_index, (group, entries) in enumerate((g, e) for g, e in groups.items() if e):
checked = " checked" if group_index == 0 else ""
tabs.append(f'<input type="radio" name="view" id="view-{group_index}"{checked}>'
f'<label for="view-{group_index}">{group} <span>{len(entries)}</span></label>')
choices, contents = [], []
for index, (name, paths) in enumerate(entries):
safe_name = escape(name)
selected = " checked" if index == 0 else ""
rendered_files = []
for path in paths:
with path.open("rb") as stream:
data = stream.read(DISPLAY_LIMIT + 1)
truncated = len(data) > DISPLAY_LIMIT
data = data[:DISPLAY_LIMIT]
text = data.decode(errors="replace")
lexer = LEXERS.get(path.suffix)
content = ((highlight(text, lexer(), HtmlFormatter(nowrap=True))
if lexer and len(data) <= HIGHLIGHT_LIMIT else escape(text)) or "No output.")
if truncated:
content += "\n[Display limit reached for this file]"
graph = ""
if path.suffix == ".dot" and not truncated:
try:
rendered = subprocess.run(["dot", "-Tpng"], input=data, capture_output=True,
timeout=2, check=True).stdout
encoded = base64.b64encode(rendered).decode("ascii")
graph = f'<div class="graph-scroll"><img alt="Graph: {safe_name}" src="data:image/png;base64,{encoded}"></div>'
except (OSError, subprocess.SubprocessError):
graph = "<p>Graph rendering unavailable. DOT source is shown below.</p>"
source = f'<pre>{content}</pre>' if not graph else f'<details><summary>DOT source</summary><pre>{content}</pre></details>'
heading = f'<h4>{escape(path.name)}</h4>' if len(paths) > 1 else ""
rendered_files.append(f'<section>{heading}{graph}{source}</section>')
ident = f"file-{group_index}-{index}"
choices.append(f'<input type="radio" name="files-{group_index}" id="{ident}"{selected}>'
f'<label for="{ident}">{safe_name}</label>')
contents.append(f'<article class="file-content file-{index}"><h3>{safe_name}</h3>{"".join(rendered_files)}</article>')
rules = ''.join(f'.files-{group_index}:has(#file-{group_index}-{i}:checked) .file-{i}{{display:block}}' for i in range(len(entries)))
single = " single" if len(entries) == 1 else ""
panels.append(f'<div class="panel panel-{group_index}"><div class="files files-{group_index}{single}">'
f'<aside>{"".join(choices)}</aside><main>{"".join(contents)}</main></div><style>{rules}</style></div>')
rules = ''.join(f'.workspace:has(#view-{i}:checked) .panel-{i}{{display:block}}' for i in range(len(panels)))
return f'<div class="foxdec-results"><h2>Results</h2><div class="workspace"><nav>{"".join(tabs)}</nav>{"".join(panels)}<style>{rules}</style></div></div>'
def entry_addresses(text, workflow):
values = re.split(r"[,\s]+", text.strip()) if text.strip() else []
if len(values) > 128 or any(not re.fullmatch(r"0[xX][0-9a-fA-F]{1,16}", value) for value in values):
raise ValueError("Enter up to 128 hexadecimal addresses such as 0x401000.")
entries = tuple(dict.fromkeys(int(value, 16) for value in values))
if any(not 0 < address < 2**63 for address in entries):
raise ValueError("Enter valid positive entry addresses.")
if workflow is pldi and len(entries) > 1:
raise ValueError("PLDI accepts one starting address.")
if workflow is sefm_stages and entries:
raise ValueError("SEFM takes its functions from the configuration file.")
return entries
def input_choices(artifact):
example_name, _, workflow, _ = ARTIFACTS[artifact]
return [(f"{EXAMPLE} · {example_name}", EXAMPLE), *([(SOURCE, SOURCE)] if workflow is sefm_stages else []), (UPLOAD, UPLOAD)]
def mode_controls(artifact, choice):
if ARTIFACTS[artifact][2] is not sefm_stages:
return *[gr.update(visible=choice == UPLOAD)] * 2, *[gr.update(visible=False)] * 3, gr.update()
config = {EXAMPLE: sefm.example_config, SOURCE: lambda: sefm.C_EXAMPLE_CONFIG, UPLOAD: lambda: sefm.CONFIG_TEMPLATE}[choice]()
return (gr.update(visible=True), gr.update(visible=choice == UPLOAD), gr.update(visible=choice == SOURCE, value=sefm.C_EXAMPLE),
gr.update(visible=choice == SOURCE, value=sefm.DEFAULT_CFLAGS),
gr.update(visible=True, open=choice == UPLOAD), gr.update(value=config))
def input_controls(artifact):
return (ARTIFACTS[artifact][3], gr.update(choices=input_choices(artifact), value=EXAMPLE), None,
gr.update(value="", visible=ARTIFACTS[artifact][2] is not sefm_stages), *mode_controls(artifact, EXAMPLE))
def updates(workflow):
queue = Queue()
def run():
try:
for item in workflow:
queue.put(("item", item))
except Exception as error:
queue.put(("error", error))
finally:
queue.put(("done", None))
Thread(target=run, daemon=True).start()
while True:
try:
kind, value = queue.get(timeout=2)
except Empty:
yield None
continue
if kind == "done":
return
if kind == "error":
raise value
yield value
def run_example(artifact, mode=EXAMPLE, upload=None, addresses="", source="", cflags="", config=""):
yield "Running", "", gr.update(interactive=False)
if artifact not in ARTIFACTS:
yield "Choose an available artifact.", "", gr.update(interactive=True)
return
started = monotonic()
_, budget, workflow, _ = ARTIFACTS[artifact]
deadline = started + budget
phases = []
with TemporaryDirectory(prefix="foxdec-job-") as directory:
work = Path(directory)
log = work / "run.log"
try:
arguments = {}
match mode:
case "Built-in example":
pass
case "Upload a binary" if upload:
entries = entry_addresses(addresses or "", workflow)
arguments = {"binary": stage_upload(upload, work, entries), "entries": entries}
case "Compile C source" if workflow is sefm_stages:
arguments = {"source": source or "", "cflags": cflags}
case _:
raise ValueError("Choose a built-in example or upload a binary.")
if workflow is sefm_stages:
arguments["config"] = config
files = ()
current = ""
def progress(action):
return "\n".join([*(f"✓ {step}" for step in phases),
f"▶ {action} · {monotonic() - started:.0f}s elapsed"])
for update in updates(workflow(work, log, deadline, **arguments)):
if update is None:
yield progress(current or "Starting analysis"), gr.update(), gr.update(interactive=False)
continue
phase, files = update
if phase and not files:
if current:
phases.append(current.rstrip("…"))
current = phase
if not files:
available = (sorted((work / "nasm").glob("*.asm"))
+ sorted((work / "certificate").glob("*.thy"))
+ [path for path in [work / "generated.c"] if path.is_file()])
verification = work / "verification.log"
if verification.is_file():
available.append(verification)
yield progress(current or "Starting analysis"), display_results(work, available) if available else gr.update(), gr.update(interactive=False)
if not files:
raise RuntimeError("The job produced no results.")
if current:
phases.append(current.rstrip("…"))
if phase:
phases.append(phase)
immediate = [path for path in files if path.suffix == ".asm"]
if immediate:
yield progress("Preparing graphs and other results…"), display_results(work, immediate), gr.update(interactive=False)
else:
yield progress("Preparing results…"), "", gr.update(interactive=False)
results = display_results(work, files)
if monotonic() >= deadline:
raise TimeoutError("The job reached its time limit.")
status = f"Completed in {monotonic() - started:.1f}s"
if phases and phases[-1].startswith("Analysis stopped."):
status = phases.pop()
except ValueError as error:
status, results = str(error), ""
except (OSError, RuntimeError) as error:
if isinstance(error, TimeoutError):
status = str(error)
else:
logger.exception("FoxDec job failed")
status = f"Failed. {error}"
diagnostics = (log, work / "simple_local_array.err", work / "verification.log")
message = "\n".join(filter(None, (read_preview(path, tail=True) for path in diagnostics)))
results = f'<div class="foxdec-results"><pre>{escape(message)}</pre></div>' if message else ""
yield "\n".join([*(f"✓ {step}" for step in phases), status]), results, gr.update(interactive=True)
with gr.Blocks(
title="FoxDec research artifacts",
css="""
.foxdec-results nav { display:flex; flex-wrap:wrap; gap:.4rem; border-bottom:1px solid var(--border-color-primary); }
.foxdec-results input { position:absolute; opacity:0; pointer-events:none; }
.foxdec-results label { display:block; cursor:pointer; padding:.65rem .9rem; border-radius:.4rem; overflow-wrap:anywhere; }
.foxdec-results input:checked + label { background:var(--background-fill-secondary); color:var(--link-text-color); font-weight:600; }
.foxdec-results input:focus-visible + label { outline:2px solid var(--link-text-color); }
.foxdec-results nav span { opacity:.65; font-size:.8em; }
.foxdec-results .panel, .foxdec-results .file-content { display:none; }
.foxdec-results .files { display:grid; grid-template-columns:minmax(12rem, 22%) minmax(0, 1fr); gap:1rem; margin-top:1rem; }
.foxdec-results aside { max-height:40rem; overflow:auto; border-right:1px solid var(--border-color-primary); }
.foxdec-results main { min-width:0; }
.foxdec-results .files.single { grid-template-columns:minmax(0, 1fr); }
.foxdec-results .files.single aside { display:none; }
.foxdec-results h3 { overflow-wrap:anywhere; }
.foxdec-results pre { max-height:40rem; overflow:auto; padding:1rem; border-radius:.5rem; background:var(--background-fill-secondary); white-space:pre; }
.graph-scroll { overflow:auto; background:white; padding:1rem; border-radius:.5rem; }
.graph-scroll img { max-width:none; height:auto; }
""" + HIGHLIGHT_CSS + """
@media(max-width:700px) { .foxdec-results .files { grid-template-columns:1fr; } .foxdec-results aside { max-height:12rem; border-right:0; border-bottom:1px solid var(--border-color-primary); } }
""",
analytics_enabled=False,
delete_cache=(60, 3600),
) as demo:
gr.Markdown("# FoxDec research artifacts\nAnalyze a Linux x86-64 binary, inspect the generated assembly and graphs, or verify a lifting certificate.")
first = next(iter(ARTIFACTS))
with gr.Row(equal_height=False):
with gr.Column(scale=1, min_width=320):
artifact = gr.Radio(list(ARTIFACTS), value=first, label="Artifact")
about = gr.Markdown(ARTIFACTS[first][3])
mode = gr.Radio(input_choices(first), value=EXAMPLE, label="Input")
run = gr.Button("Run analysis", variant="primary", size="lg")
status = gr.Textbox(label="Status", lines=4, max_lines=12, interactive=False, visible=False)
with gr.Column(scale=1, min_width=320) as inputs_column:
with gr.Column(visible=False) as upload_inputs:
upload = gr.File(label="Linux x86-64 ELF binary", type="filepath")
addresses = gr.Textbox(label="Entry addresses (optional)", placeholder="0x401000", visible=False)
source = gr.Code(label="C source (compiled with gcc, never run)", language="c", value=sefm.C_EXAMPLE, visible=False)
cflags = gr.Textbox(label="Compiler options", value=sefm.DEFAULT_CFLAGS, visible=False,
info="Optimization, code generation, warning and macro options. The paper’s tool expects x86-64 and no PIE.")
with gr.Accordion("Decompiler configuration", open=False) as config_panel:
config = gr.Textbox(show_label=False, lines=16, max_lines=16, show_copy_button=True,
value=sefm.example_config(),
info="Functions to decompile, their argument registers, and the C preamble.")
results = gr.HTML(value="<p>Run an analysis to see its results here.</p>")
with gr.Accordion("Artifact catalog", open=False):
gr.Markdown(Path(__file__).with_name("catalog.md").read_text())
mode_outputs = [inputs_column, upload_inputs, source, cflags, config_panel, config]
artifact.input(input_controls, artifact, [about, mode, upload, addresses, *mode_outputs], queue=False, api_name=False)
mode.input(mode_controls, [artifact, mode], mode_outputs, queue=False, api_name=False)
outputs = [status, results, run]
run.click(prepare, outputs=outputs, queue=False, api_name=False).then(
run_example, [artifact, mode, upload, addresses, source, cflags, config], outputs, concurrency_limit=1, api_name="run",
)
if __name__ == "__main__":
demo.queue().launch(server_name="0.0.0.0", server_port=7860, max_file_size=MAX_UPLOAD)
|