Spaces:
Sleeping

File size: 6,084 Bytes
f51c192
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
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)