Spaces:
Sleeping
Sleeping
Download app.py from ejschwartz/decompilai: direct link, hf CLI and curl.
- Browser
- Download file 6.08 kB
-
https://huggingface.co/spaces/ejschwartz/decompilai/resolve/main/app.py
- Command line
-
hf download hf://spaces/ejschwartz/decompilai/app.py
-
curl -L -o app.py https://huggingface.co/spaces/ejschwartz/decompilai/resolve/main/app.py
6.08 kB
| import json | |
| import os | |
| from pathlib import Path | |
| import signal | |
| import subprocess | |
| import sys | |
| import tempfile | |
| import gradio as gr | |
| UPSTREAM = Path(os.environ.get("DECOMPILAI_ROOT", "/opt/decompilai")) / "examples" | |
| LOCAL = Path(__file__).resolve().parent / "examples" | |
| DEFAULT = "clamp-bug" | |
| EXAMPLES = { | |
| DEFAULT: ("Clamp with an off-by-one error", UPSTREAM / "orig.c", UPSTREAM / "cand_bad.c"), | |
| "clamp-match": ("Matching clamp", UPSTREAM / "orig.c", UPSTREAM / "cand_ok.c"), | |
| "rotate": ("Rotate versus shift", LOCAL / "rotate.c", LOCAL / "shift.c"), | |
| "popcount": ("Population count", LOCAL / "popcount.c", LOCAL / "popcount_candidate.c"), | |
| "upper": ("Uppercase conversion (upper)", LOCAL / "upper.c", LOCAL / "upper_candidate.c"), | |
| "putchar": ("One-byte output (my_putchar_count)", LOCAL / "putchar.c", LOCAL / "putchar_candidate.c"), | |
| } | |
| VERDICTS = { | |
| "no_divergence_found": "No divergence found on the valid inputs tried.", | |
| "diverges": "The implementations diverge.", | |
| "no_compile": "The candidate failed to compile.", | |
| "error_original": "The original failed to compile.", | |
| "unsupported": "The checker could not analyze this function.", | |
| "inconclusive": "The check was inconclusive.", | |
| } | |
| def example_paths(example_id): | |
| if example_id not in EXAMPLES: | |
| raise ValueError("Choose a bundled example.") | |
| return EXAMPLES[example_id][1:] | |
| def load_example(example_id): | |
| return ( | |
| *(path.read_text() for path in example_paths(example_id)), | |
| "Ready to check.", | |
| None, | |
| None, | |
| ) | |
| def check_example(example_id, timeout=60): | |
| original, candidate = example_paths(example_id) | |
| command = [ | |
| sys.executable, "-m", "decompilai.check", | |
| "--orig", str(original), "--cand", str(candidate), "--func", "func0", | |
| "-n", "2000", "--seed", "1", "--corpus-seconds", "0", | |
| ] | |
| with tempfile.TemporaryDirectory(prefix="decompilai-job-") as work: | |
| with subprocess.Popen( | |
| command, stdout=subprocess.PIPE, text=True, start_new_session=True, | |
| env={**os.environ, "TMPDIR": work}, | |
| ) as process: | |
| try: | |
| output, _ = process.communicate(timeout=timeout) | |
| except subprocess.TimeoutExpired: | |
| try: | |
| os.killpg(process.pid, signal.SIGKILL) | |
| except ProcessLookupError: | |
| pass | |
| process.communicate() | |
| raise | |
| if process.returncode: | |
| raise subprocess.CalledProcessError(process.returncode, command) | |
| return json.loads(output) | |
| def summarize(result): | |
| labels = { | |
| "inputs": "Generated inputs", | |
| "valid_inputs": "Valid inputs", | |
| "compared": "Compared inputs", | |
| "diverging_inputs": "Diverging inputs", | |
| } | |
| lines = [VERDICTS.get(result["verdict"], result["verdict"])] | |
| lines.extend(f"{label}: {result[key]}" for key, label in labels.items() if key in result) | |
| if first := result.get("first"): | |
| lines.append(f"First divergence ({first['kind']}): {first.get('input', '')}") | |
| for side in ("original", "candidate"): | |
| observation = first.get(side, {}) | |
| lines.append(f"{side.title()}: {observation.get('status', '')} {observation.get('outputs', '')}".rstrip()) | |
| if stdout := observation.get("stdout_hex"): | |
| lines.append(f" Stdout (hex): {stdout}") | |
| lines.extend(str(result[key]) for key in ("reason", "detail") if result.get(key)) | |
| return "\n".join(lines) | |
| def run_check(example_id): | |
| yield gr.update(interactive=False), gr.update(interactive=False), "Checking…", None, None | |
| try: | |
| result = check_example(example_id) | |
| except ValueError: | |
| message = "Choose a bundled example." if example_id not in EXAMPLES else "The checker returned an unreadable result." | |
| except subprocess.TimeoutExpired: | |
| message = "The check exceeded its 60-second limit." | |
| except (OSError, subprocess.CalledProcessError): | |
| message = "The checker could not complete this run." | |
| else: | |
| # Gradio copies this file into its cache before advancing the generator. | |
| with tempfile.TemporaryDirectory(prefix="decompilai-report-") as directory: | |
| report = Path(directory) / f"{example_id}.json" | |
| report.write_text(json.dumps(result, indent=2) + "\n") | |
| yield gr.update(interactive=True), gr.update(interactive=True), summarize(result), result, str(report) | |
| return | |
| yield gr.update(interactive=True), gr.update(interactive=True), message, None, None | |
| def build_app(): | |
| original, candidate, status, _, _ = load_example(DEFAULT) | |
| with gr.Blocks(title="DecompilAI", delete_cache=(3600, 3600)) as demo: | |
| gr.Markdown( | |
| "# DecompilAI\n" | |
| "Compare the behavior of two C functions on generated inputs. " | |
| "Choose a bundled example to inspect its source and run the checker." | |
| ) | |
| with gr.Row(): | |
| example = gr.Dropdown( | |
| [(entry[0], key) for key, entry in EXAMPLES.items()], | |
| value=DEFAULT, label="Example", allow_custom_value=False, | |
| ) | |
| run = gr.Button("Check behavior", variant="primary") | |
| with gr.Row(): | |
| left = gr.Code(original, language="c", label="Original C", interactive=False, lines=12) | |
| right = gr.Code(candidate, language="c", label="Candidate C", interactive=False, lines=12) | |
| summary = gr.Textbox(status, label="Result", interactive=False, lines=4) | |
| report = gr.DownloadButton("Download JSON report") | |
| with gr.Accordion("Raw result", open=False): | |
| raw = gr.JSON() | |
| example.input(load_example, example, [left, right, summary, raw, report], api_visibility="private") | |
| run.click( | |
| run_check, example, [example, run, summary, raw, report], | |
| concurrency_limit=1, api_name="check_example", | |
| ) | |
| return demo.queue(max_size=16) | |
| if __name__ == "__main__": | |
| build_app().launch(server_name="0.0.0.0", server_port=7860) | |