Spaces:
Sleeping
Sleeping
Commit ·
f51c192
0
Parent(s):
Build DecompilAI Gradio Space
Browse filesFiles changed (14)
- .dockerignoreAdded+6
- .gitignoreAdded+2
- DockerfileAdded+34
- README.mdAdded+39
- app.pyAdded+144
- examples/popcount.cAdded+6
- examples/popcount_candidate.cAdded+3
- examples/putchar.cAdded+6
- examples/putchar_candidate.cAdded+7
- examples/rotate.cAdded+3
- examples/shift.cAdded+3
- examples/upper.cAdded+9
- examples/upper_candidate.cAdded+12
- requirements.txtAdded+1
123456*!Dockerfile!requirements.txt!app.py!examples/!examples/*.c12__pycache__/.venv/12345678910111213141516171819202122232425262728293031323334# syntax=docker/dockerfile:1FROM ubuntu:24.04 AS upstreamRUN --mount=type=cache,target=/var/cache/apt,sharing=locked \ rm -f /etc/apt/apt.conf.d/docker-clean && apt-get update && apt-get install -y --no-install-recommends ca-certificates gitRUN --mount=type=secret,id=git_ca,target=/run/secrets/git_ca \ if [ -f /run/secrets/git_ca ]; then export GIT_SSL_CAINFO=/run/secrets/git_ca; fi \ && git init /opt/decompilai \ && git -C /opt/decompilai fetch --depth=1 https://github.com/Shreyas652/DecompilAI.git 69cba22981778b46ee672f550eb6a8bbaaae9213 \ && git -C /opt/decompilai checkout --detach FETCH_HEAD \ && rm -rf /opt/decompilai/.git
FROM ubuntu:24.04RUN --mount=type=cache,target=/var/cache/apt,sharing=locked \ rm -f /etc/apt/apt.conf.d/docker-clean && apt-get update && apt-get install -y --no-install-recommends \ ca-certificates clang-18 llvm-18 libclang-rt-18-dev gcc libc6-dev python3-venv \ && ln -s /usr/bin/clang-18 /usr/local/bin/clang \ && python3 -m venv /opt/venv \ && rm -rf /var/lib/apt/lists/*ENV PATH=/opt/venv/bin:$PATH \ PYTHONPATH=/opt/decompilai \ DECOMPILAI_ROOT=/opt/decompilai \ GRADIO_ANALYTICS_ENABLED=False \ VDEC_CACHE=/tmp/decompilai-cacheWORKDIR /opt/appCOPY requirements.txt .RUN --mount=type=cache,target=/root/.cache/pip pip install -r requirements.txtCOPY --from=upstream /opt/decompilai/decompilai /opt/decompilai/decompilaiCOPY --from=upstream /opt/decompilai/examples /opt/decompilai/examplesCOPY --from=upstream /opt/decompilai/LICENSE /opt/decompilai/NOTICE /opt/decompilai/COPY app.py .COPY examples examplesUSER ubuntuEXPOSE 7860CMD ["python", "app.py"]123456789101112131415161718192021222324252627282930313233343536373839---title: DecompilAIemoji: 🔍colorFrom: indigocolorTo: bluesdk: dockerapp_port: 7860fullWidth: true---
# DecompilAI
Select an example, inspect the original and candidate C, then click **Check behavior**. DecompilAI compares the functions on 2,000 generated inputs with seed 1. When it finds a difference, the result shows a counterexample and what each function did. The JSON report contains the full checker output. Agreement covers the valid inputs tried.
The clamp examples come from [DecompilAI](https://github.com/Shreyas652/DecompilAI), pinned at `69cba22981778b46ee672f550eb6a8bbaaae9213`. Rotate versus shift, population count, `upper`, and `my_putchar_count` are standalone C adaptations of cases from [Decompiler verifier](https://huggingface.co/spaces/ejschwartz/decompile-verify). The last two exercise in-place buffer writes and standard output, respectively.
## Run the workbench locally
```shdocker build --platform linux/amd64 -t decompilai-space .docker run --rm --platform linux/amd64 -p 127.0.0.1:7860:7860 decompilai-space```
Open <http://127.0.0.1:7860>. The same Dockerfile runs on Hugging Face CPU hardware without secrets.
If a local TLS proxy intercepts GitHub and the build fails certificate verification, add `--secret id=git_ca,src=/path/to/your/trusted-ca-bundle.pem` to the build command.
## Check your own C locally
Put `orig.c` and `cand.c` in a dedicated `inputs` directory. Define the same function name and signature in both files. DecompilAI compiles and executes both inputs, so run the checker in a separate container with networking disabled and mount only the inputs. [Upstream security guidance](https://github.com/Shreyas652/DecompilAI/blob/main/SECURITY.md)
```shdocker run --rm --platform linux/amd64 --network none \ --mount "type=bind,source=$PWD/inputs,target=/data,readonly" \ decompilai-space python -m decompilai.check \ --orig /data/orig.c --cand /data/cand.c --func func0```
See [DecompilAI usage](https://github.com/Shreyas652/DecompilAI/blob/main/docs/USAGE.md) for supported types, options, and result fields.123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144import jsonimport osfrom pathlib import Pathimport signalimport subprocessimport sysimport 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)123456int func0(unsigned int x) { int count = 0; for (; x; x >>= 1) count += x & 1u; return count;}123int func0(unsigned int x) { return __builtin_popcount(x);}123456#include <unistd.h>
int func0(char c) { write(STDOUT_FILENO, &c, 1); return 1;}1234567#include <unistd.h>
int func0(char c) { char buffer[4] = {c}; write(STDOUT_FILENO, buffer, 1); return 1;}123unsigned int func0(unsigned int x) { return (x << 1) | (x >> 31);}123unsigned int func0(unsigned int x) { return x << 1;}123456789#include <stddef.h>
void func0(char *s) { if (!s) return; for (; *s; ++s) if (*s >= 'a' && *s <= 'z') *s -= 'a' - 'A';}123456789101112#include <string.h>
void func0(char *s) { if (!s) return; for (size_t i = 0; ; ++i) { if (i >= strlen(s)) break; if (s[i] > 96 && s[i] <= 122) s[i] -= 32; }}1gradio==6.9.0.dockerignoreAdded+6
.gitignoreAdded+2
DockerfileAdded+34
README.mdAdded+39
app.pyAdded+144
examples/popcount.cAdded+6
examples/popcount_candidate.cAdded+3
examples/putchar.cAdded+6
examples/putchar_candidate.cAdded+7
examples/rotate.cAdded+3
examples/shift.cAdded+3
examples/upper.cAdded+9
examples/upper_candidate.cAdded+12
requirements.txtAdded+1