Reverse Engineering Large Language Models in Practice: Rewriting a Classic Game with AI
This article presents a practical methodology for using AI coding tools to reverse engineer and rewrite a classic real-time strategy game whose original source code is lost. It emphasizes that any reverse engineering must be based on legal authorization, and covers compliance prerequisites, the capability boundaries of models as accelerators rather than evidence sources, a six-layer analysis pipeline, structured recovery from disassembly to readable pseudocode, quantifiable equivalence verification, and modern refactoring for maintainability. It also shows how the same evidence-first approach applies to health-check style audits of legacy systems. Readers will gain a reusable engineering framework for modernizing legacy systems.
1. Introduction: Starting from “Have the Model Rewrite an Old Game”
A recurring idea in technical communities goes like this: the source code of a classic real-time strategy game has long been lost, while today’s intelligent coding tools have significantly stronger code comprehension and generation capabilities. Naturally, a thought emerges—can a model first “understand” the executable, then “rewrite” its logic, and ultimately produce a maintainable, extensible modern version?
The idea itself is valuable, but it compresses a multi-stage engineering effort into a single slogan. A truly executable path must answer four questions: where the legal and licensing boundaries lie; how binary information can be structurally extracted; how the extracted semantics can be verified as equivalent; and how the rewritten architecture can balance performance and maintainability. This article uses “washing and bathing” as a metaphor—first “washing” old code into clear semantics, then “bathing” it in modern engineering structure—to lay out a methodology.
One thing must be stated upfront: any reverse engineering and rewriting must be built on legal authorization. If the target program’s copyright status is unclear, or its license agreement prohibits reverse engineering, the correct action is to stop. The alternative is to build a new program with “equivalent gameplay” based on public materials and independent design, rather than copying the original implementation and assets.
2. Compliance and Prerequisites: A Step You Cannot Skip
- Authorization confirmation: Confirm that you are the rights holder, have obtained written permission, or are in a jurisdiction that explicitly permits limited reverse engineering for interoperability purposes.
- Resource isolation: Place the sample under analysis in an isolated environment and prohibit network callback, to avoid any risk from outbound behavior in the sample.
- Asset separation: Code logic can be independently implemented based on analysis conclusions; binary assets such as art, audio, and fonts usually cannot be “rewritten” along with the logic and must be replaced with your own or clearly licensed materials.
- Traceable records: Every analysis conclusion must be backed by evidence (addresses, instructions, data references), forming a traceable chain of evidence rather than “the model says it is so.”
3. Capability Boundaries: The Model Is an Accelerator, Not a Source of Evidence
Intelligent coding tools excel at pattern recognition and code synthesis: given enough context, they can complete function skeletons, generate boilerplate code, and propose refactoring suggestions. But they do not possess the target program’s actual runtime state, nor do they inherently understand undocumented data structures. Treating model output as fact is a classic case of “mistaking representation for support.”
A more reliable positioning is this: the model is responsible for “proposing hypotheses and generating candidate implementations,” while the engineering pipeline is responsible for “verifying hypotheses.” The core question is not whether the model is confident, but whether there exists a reproducible means of verification.
4. Analysis Pipeline: Six Progressive Layers
- Static overview: Tally segment structure, import/export tables, strings, and resource directories to build a global map.
- Disassembly and deobfuscation: Obtain an instruction-level view; for packed or obfuscated samples, first unpack and recover control flow.
- Function boundaries and call graph: Identify function entries, reconstruct call relationships, and mark hot and critical paths.
- Type and structure recovery: Infer struct field offsets and alignment from access patterns, forming candidate type definitions.
- Semantic annotation and symbolic execution: Use symbolic execution to solve path constraints for complex branches, filling in semantics that are hard to determine statically.
- Dynamic verification: Run in a controlled environment, collect traces and state snapshots, and cross-check against static conclusions.
Illustrative pipeline pseudocode (used to express stage relationships, not a specific tool interface):
sample -> unpack/deobfuscate -> disassemble-> build_callgraph -> infer_types-> annotate_semantics(symbolic_exec)-> dynamic_trace -> evidence_store
5. From Disassembly to Readable Pseudocode: Structured Recovery
Disassembly output is a “linear instruction stream,” while what humans need is “structured semantics.” The key actions in recovery include:
- Control flow structuring: Map jumps and conditional branches to if/else, loops, and early returns, eliminating goto chains.
- Calling convention identification: Determine parameter register/stack layout and return value location to avoid parameter misalignment.
- Memory access classification: Distinguish global data, stack locals, and heap objects, and infer lifetimes.
- Constant and magic number interpretation: Give physical meaning in context (such as frame duration, unit caps).
Example (abstract illustration showing the mapping idea from “instruction fragment → structured pseudocode”):
; Abstract instruction fragmentcmp dword [ctx+0x10], 0jle .skipmov eax, [ctx+0x18]imul eax, 3add eax, [ctx+0x1C]mov [ctx+0x20], eax.skip:
/* Candidate implementation after structured recovery */if (ctx->field_10 > 0) {ctx->field_20 = ctx->field_18 * 3 + ctx->field_1C;}
At this point the field names are still placeholders and must be gradually replaced with semantic names based on evidence (access patterns, initialization paths, serialization formats).
6. Equivalence Verification: Can the Rewrite Be Trusted?
The credibility of a rewrite does not come from “looking similar,” but from quantifiable equivalence:
- Input-output equivalence: For the same input sequence, compare whether state transitions and outputs match (allowing floating-point tolerance and iteration order differences).
- Trace comparison: Record call sequences and branch hits on critical paths, and perform differential localization.
- Property testing: Define invariants (resource conservation, units not passing through each other, non-negative damage) and check them with randomized inputs.
- Regression baseline: Solidify the old version’s behavior in a controlled environment as a baseline, and run the baseline on every commit of the new implementation.
Illustrative property test:
for seed in range(N):rng = Random(seed)state = init_state(rng)for _ in range(1000):cmd = random_command(rng, state)old = step_old(state, cmd)new = step_new(state, cmd)assert close(old, new, tol=1e-6)assert invariants_hold(new)
7. Modern Refactoring: Turning “It Runs” into “It Is Maintainable”
Equivalence is only the baseline; the goal of refactoring is to give the codebase the ability to evolve over the long term:
- Layered architecture: Decouple the simulation core, rendering, input, and resource management, so the core does not depend on a specific platform.
- Data-oriented design: Replace implicit global state with contiguous memory layout and a clear ownership model, improving cache friendliness and testability.
- Deterministic simulation: Fix the timestep and pseudo-random seed to guarantee replay and multiplayer consistency.
- Observability: Build in logging, metrics, and tracing to turn “black-box behavior” into diagnosable signals.
- Asset pipeline: Convert original assets into your own formats and establish a repeatable build process.
Illustrative directory structure:
/sim # Pure logic, deterministic/render # Rendering backend abstraction/platform # Input, window, audio/assets # Own or licensed materials/tests # Equivalence and property tests
8. Common Pitfalls
- Treating model guesses as conclusions: An unsupported “it should be…” pollutes the entire chain.
- Premature optimization: First ensure semantic correctness, then do performance profiling and hotspot optimization.
- Ignoring undefined behavior: Compiler-dependent behavior relied upon by old code must be explicitly pinned down.
- Conflating assets with logic: Logic being rewritable does not mean assets can be copied.
- Missing baseline: Without an old-version baseline, equivalence is impossible to discuss.
9. Applying the Same Method to Health-Check Style Code Audits
The same “evidence-chain-first” approach also applies to health-check style audits of legacy systems. Many teams hold years of consecutive “build passing” reports yet cannot explain why production suddenly fails—because basic checks only cover compilation and unit tests, lacking deep probing of critical paths. The layered philosophy of early cancer screening is worth borrowing: a basic package screens for common chronic conditions, while targeted examinations reach deeper risks. Mapped to engineering:
- Basic layer: Compilation, static checks, unit tests.
- Advanced layer: Coverage and mutation testing, dependency and license compliance scanning.
- Specialized layer: Symbolic execution of critical paths, fuzzing, performance profiling, and memory model checks.
10. Conclusion
“Having intelligent coding tools rewrite an old game” is attractive because it compresses complex engineering into a single wish. But the actionable answer is always engineering-based: first solve authorization and isolation, then use the six-layer analysis to turn a binary into structured semantics, use equivalence and property testing to establish trust, and finally complete modernization with layered architecture and observability. The model can significantly accelerate hypothesis generation and code synthesis, but the real support remains evidence, verification, and constraints. Walk this chain through, and what you gain is not only a runnable rewritten version, but a methodology reusable for modernizing any legacy system.
