Decompiling and Reverse-Engineering Binaries with LLMs: From Ghidra to Clean C and RustLongread · digest for October 11
Conceptual illustration of binary reverse engineering: transforming assembly opcodes into clean C and Rust code through Ghidra analysis and neural networks.
Longread7 sections≈ 7 min

Decompiling and Reverse-Engineering Binaries with LLMs: From Ghidra to Clean C and Rust

Every engineer who has opened a disassembler knows that sinking feeling of hitting a wall. You stare at endless listings of mov and lea instructions and calls to functions like func_004018A0. Decompilers translate opcodes into C-like pseudocode, but a mess of untyped void* pointers, uVar1 variables, and bloated conditionals looks nothing like readable source code.

For decades, reverse engineering remained a slow, delicate, and expensive craft. Recovering the source code of a small utility or console game took months of manual effort. Now, specialized models like LLM4Decompile and reasoning agents are changing the field. Combining the NSA's Ghidra analyzer with language models creates a closed loop that turns binary dumps into clean, type-safe C or Rust code.

The Fog of Decompilation: Why Classic Static Analysis Stalls Halfway

To see why this matters, remember that aggressive compiler optimizations (-O2, -O3) strip away metadata ruthlessly:

  1. Erased types and structs: Objects flatten into raw register offsets like *(int*)(ESI + 0x18). The decompiler sees a memory read, but has no idea whether it's a user profile field or a graphics buffer width.
  2. Function inlining and loop unrolling: Clean helper calls dissolve inside the caller, turning into huge monolithic blocks of instructions.
  3. Scrambled control flow: Neat switch and if-else statements collapse into jump tables and a maze of jmp instructions.

Classic decompilers recover only the control flow and rough arithmetic. Until recently, only a human could figure out what the code actually meant.

Two Years Shrunk to 84 Days: A Real-World Binary Breakthrough

A striking example comes from the retro-engineering community. Reverse engineer Chris Lewis spent nearly two years painstakingly decompiling the Nintendo 64 game Snowboard Kids, logging thousands of hours comparing assembly listings and raw bytes.

When the same process was repeated using agentic LLM loops, reconstruction time dropped to 84 days—nearly nine times faster. Security researchers estimate that as models improve, recovering standard binary modules is shrinking to just days.

In this setup, the model acts as a pattern-recognition expert. Spotting scattered bit shifts and XOR operations, it recognizes an AES encryption routine or a CRC32 checksum and replaces a hundred lines of messy pseudocode with one clean function.

Architecture of the Verifiable Loop: The Compiler as an Unbiased Judge

The biggest danger of trusting neural networks in systems programming is silent hallucination. The solution is a Verifiable Feedback Loop, where the model spars continuously with a compiler:

  • Step 1: Ghidra extracts raw pseudocode from the target binary;
  • Step 2: The LLM analyzes the pseudocode, recovers data types, assigns meaningful variable names, and writes Rust code;
  • Step 3: The compiler (rustc) tries to build the code. Any syntax or borrow-checker errors go straight back into the model's context;
  • Step 4: A test harness runs both the original and recompiled binaries on identical inputs, comparing memory dumps and STDOUT;
  • Step 5: The loop repeats until behavior is functionally identical.

Infographic of the verifiable reverse-engineering loop: a closed cycle of Ghidra decompilation, LLM code generation, rustc compiler checks, and output testing.

Headless Pseudocode Extraction: Automating Ghidra Without a GUI

To build an automated pipeline, you skip manual GUI clicks. Instead, you use Ghidra's analyzeHeadless CLI tool with a Java decompilation script (DecompileExport.java):

import ghidra.app.script.GhidraScript;
import ghidra.app.decompiler.*;
import ghidra.program.model.listing.*;
import java.io.PrintWriter;

public class DecompileExport extends GhidraScript {
    @Override
    public void run() throws Exception {
        DecompInterface decompiler = new DecompInterface();
        decompiler.openProgram(currentProgram);
        PrintWriter writer = new PrintWriter(getScriptArgs()[0]);

        FunctionManager funcManager = currentProgram.getFunctionManager();
        for (Function func : funcManager.getFunctions(true)) {
            DecompileResults results = decompiler.decompileFunction(func, 60, monitor);
            if (results.decompileCompleted()) {
                writer.println("// Function: " + func.getName());
                writer.println(results.getDecompiledFunction().getC());
            }
        }
        writer.close();
    }
}

You run the decompiler straight from the terminal without starting a graphical server:

# Extract pseudocode from the target_binary executable
/opt/ghidra/support/analyzeHeadless /tmp/ghidra_workspace ProjectTemp \
    -import ./target_binary \
    -postScript DecompileExport.java ./raw_decompiled.c \
    -deleteProject

Turning Pseudocode into Safe Rust: Pairing Python with the Compiler

A Python glue script sends a chunk of pseudocode to the language model, asks for a Rust rewrite, and immediately checks it with rustc:

import os
import subprocess
from openai import OpenAI

client = OpenAI(api_key=os.environ.get("OPENAI_API_KEY"))

def reconstruct_to_rust(raw_c_code: str) -> str:
    system_prompt = (
        "You are a systems reverse-engineering expert. Convert Ghidra pseudocode "
        "into idiomatic, type-safe Rust. Restore meaningful names and data structures. "
        "Return only a clean code block with no explanations."
    )
    response = client.chat.completions.create(
        model="gpt-4o",
        messages=[
            {"role": "system", "content": system_prompt},
            {"role": "user", "content": f"Pseudocode:\n```c\n{raw_c_code}\n```"}
        ],
        temperature=0.1
    )
    text = response.choices[0].message.content.strip()
    return text.removeprefix("```rust").removeprefix("```").removesuffix("```").strip()

def verify_compilation(rust_code: str, output_path: str = "./reconstructed.rs") -> bool:
    with open(output_path, "w", encoding="utf-8") as f:
        f.write(rust_code)
    proc = subprocess.run(["rustc", "--crate-type=lib", output_path], capture_output=True, text=True)
    if proc.returncode == 0:
        print("[SUCCESS] Rust code is valid and compiled.")
        return True
    print(f"[ERROR]: {proc.stderr}")
    return False

if __name__ == "__main__":
    with open("./raw_decompiled.c", "r", encoding="utf-8") as f:
        pseudocode = f.read()
    rust_code = reconstruct_to_rust(pseudocode)
    verify_compilation(rust_code)

Here, the compiler acts as a strict referee, catching borrow-checker errors or type mismatches right away.

Clean-Room Design: Legally Rebuilding Closed Software

Understanding how binaries work opens the door to legally rebuilding proprietary systems through clean-room design. Copyright law protects specific code expression, not functional protocols. The process splits engineers into two teams:

  1. Dirty Room (Analysis): Inspects the closed binary, decompiles functions, and writes a spec of protocols and structures.
  2. Clean Room (Development): Never sees the closed code and builds an independent implementation from scratch using only that spec.

Projects like PhotoCraft and FilmCraft use Rust codebases to rebuild proprietary media editors without infringing copyright.

Optimization Undercurrents: Inlining Limits and Architectural Verdict

Despite strong results, this method still faces engineering limits:

  • Aggressive inlining and vectorization: Code compiled with SIMD/AVX flags breaks into parallel register operations that even top LLMs struggle to interpret;
  • Protectors and obfuscators: Commercial packers like VMProtect and Denuvo still require manual de-virtualization first;
  • Environment isolation: Decompiling untrusted binaries must always happen inside disposable sandboxes with no network access.

Combining Ghidra with coding models strips closed software of its "permanent black box" status. Legacy libraries get a second life in safe Rust, and security teams gain a fast way to dissect incidents.

Want a deep diveVotes help us choose what to break down in detail. This material has 0 votes.
Sources · 2