Practical Implementation of LLM-Driven Reverse Rewriting for Legacy Software
Can large language models (LLMs) rewrite legacy software from scratch? The answer is yes, but not through "one-prompt magic." This article explores the practical implementation of LLM-driven reverse rewriting for legacy systems where source code is lost or documentation is incomplete. By embedding LLMs into a verifiable, auditable, and continuously integrated engineering pipeline, teams can leverage code agents for repetitive tasks while relying on automated tests and human review for convergence. Covering format reverse engineering, milestone planning, agent collaboration, and compliance, this guide provides a pragmatic roadmap for modernizing legacy software safely and efficiently.
I. The Conclusion First: Real Cases Exist, But Not “One-Prompt to Full Product”
“Are there any practical application cases for powerful models?” If we focus the question on legacy software rewriting, the answer is: Yes, and an operable prototype path already exists. However, it does not mean letting the model write a complete product based on intuition, nor does it replace architects, testers, and legal reviewers. A more accurate description is embedding LLMs into an engineering pipeline that is verifiable, auditable, and supports continuous integration. Code agents handle a large volume of repetitive but critical R&D work, while automated testing and human review converge the results.
This approach is particularly suitable for three scenarios:
- Original source code is missing or documentation is incomplete, but the running program, resource packages, and test samples can be legally studied.
- Private protocols, legacy file formats, and historical interfaces require compatibility, making traditional reverse engineering and manually written parsers extremely costly.
- Legacy systems must be modernized incrementally without a one-time downtime rewrite, requiring parallel evolution of a “compatibility layer + new engine.”
Boundaries must be clarified first: experiments are only conducted on proprietary software, authorized software, or binaries legally allowed for compatibility research. Copying or distributing copyrighted resources and code is prohibited. When third-party licenses are involved, compliance audits must be performed. Models cannot replace legal judgment, nor can they be tools to bypass license or copyright restrictions.
II. An Anonymized Pilot: Rewriting Legacy Software with Lost Source Code
Consider a typical project: an old real-time strategy (RTS) software where the original source code is unobtainable, resource formats are highly privatized, and the community still has compatibility needs. The team aims to build a proof-of-concept prototype in two weeks. The goal is not to release a complete replacement immediately, but to verify three things:
- Can we quickly identify and parse the main resource formats?
- Can we establish a runnable core gameplay loop and basic UI?
- Can automated testing maintain quality during high-frequency iterations?
The team divides the work into three phases:
- Pre-prototype phase: Ensure resource packages can be opened, the UI shell can launch, and logging and error handling are functional.
- Core prototype phase: Implement combat rules, deterministic replay, save file reading, and key interactions.
- Integration prototype phase: Complete online synchronization, exception recovery, performance baselines, and form a demonstrable version.
In an intensive trial, code agents can generate numerous small commits daily. R&D personnel no longer read every line of generated code; instead, they focus on acceptance results, test reports, resource parsing success rates, replay consistency, build repeatability, and compliance alerts. This rhythm sounds aggressive, but the premise is: all changes enter automated gating, and any commit that fails to meet acceptance criteria cannot be merged into the main branch.
III. Overall Technical Approach: Models Must Be “Engineering-Surrounded”
The overall architecture can be summarized in the following chain:
Requirements and acceptance use cases -> Sample and asset inventory -> Binary and format reconnaissance -> Self-built format specifications -> Parsers and compatibility layers -> Core engine and gameplay simulation -> UI, resource pipeline, and networking -> Automated verification and compliance audit
LLMs are best suited for “generating hypotheses, writing initial drafts, supplementing tests, and explaining failures.” What truly determines project success is the engineering system surrounding the model:
- Specification first: Each task provides input samples, behavior constraints, error handling, and acceptance use cases to prevent the model from freewheeling.
- Clean implementation: Specifications, implementation, and testing should ideally be handled by different roles or separate sessions, avoiding “writing, reviewing, and judging correctness all by oneself.”
- Evidence chain: Key constants, field layouts, and compatibility behaviors must be traceable to sample experiments, documentation, or human confirmation, not solely based on the model’s statements.
- Automated acceptance: Format parsing requires golden samples, corrupted samples, and randomly mutated samples; gameplay logic requires consistency replays; networking requires disconnection reconnection and state verification.
IV. Format Reverse Engineering: Turning “Magic Constants” into Verifiable Knowledge
The most troublesome part of legacy software is often not the business logic, but various private formats: archives, images, audio, video containers, maps, animations, configuration tables, and index files. They typically lack public specifications, have ambiguous field boundaries, and may even have version differences.
The value of LLMs here is not “guessing the right answer directly,” but significantly shortening the experimental loop:
- Summarize possible structural features based on hex samples.
- Generate parser skeletons and boundary checks.
- Generate hypotheses and test cases for each field.
- Read failure logs and propose the next round of probing strategies.
- Document stabilized behaviors into self-built format specifications and regression tests.
However, one phenomenon must be guarded against: the model might have “memorized” certain constants or algorithms from public implementations in its training data. The code it writes may seem original but could carry license or copyright risks. Engineering-wise, model output should be treated as a hypothesis to be verified, not a trusted specification. The correct approach is:
- Every key constant must be supported by sample experiments or public documentation.
- Separate the “specification compiler” from the “code implementer” to enforce clean implementation.
- Introduce code similarity detection and license scanning.
- Prohibit the direct introduction of implementations with incompatible licenses.
- Flag constants with unexplainable origins as risks; it is better to redo the experiment than to bring them into production.
Pseudocode illustration:
function parseAsset(bytes):require bytes length is sufficientmagic = readHeader(bytes)require magic belongs to known sample set, otherwise return recoverable errorfields = decode field by field based on self-built specificationperform boundary validation on indices, offsets, and lengthsprovide fail-safe for truncated files and malicious length inputsresult = buildAsset(fields)assert roundTrip(result) == legal sample structurereturn result
Note that the primary goal of the parser is “stable, diagnosable, and fuzz-testable,” not to cover all formats in one go. The faster the model generates code, the more stringent the error handling must be; otherwise, high-frequency iterations will amplify hidden defects.
V. Milestone Breakdown: Structuring a Two-Week Proof of Concept
A reusable pilot rhythm can be designed as follows:
Days 1-2: Compliance and Reconnaissance.
Confirm the authorization scope, establish a sample inventory, version matrix, and target deliverables. The model assists in organizing resource directories, identifying file header features, and generating an initial parser task list. Humans determine “what not to touch, what must be verified, and how to roll back on failure.”
Days 3-5: Pre-prototype.
The goal is to open resources, render a basic UI, and display logs. Each parser is paired with golden samples, corrupted samples, and minimal regression tests. This phase does not pursue gameplay; it only validates the toolchain and feedback speed.
Days 6-9: Core Prototype.
Implement deterministic time steps, input command queues, map reading, basic combat rules, save/load, and replay. Abstract the legacy program’s behavior into “comparable observation points”: does the same input produce the same state, do the same resources render consistently, and is the sequence of key events stable?
Days 10-12: Integration and Networking.
If the goal is multiplayer, you must adhere to “separation of simulation and rendering, fixed time steps, deterministic random numbers, and command synchronization.” The model can generate sync checks, reconnection logic, log comparisons, and exception injection tests, but the synchronization strategy still needs to be designed by senior engineers.
Days 13-14: Demo and Retrospective.
Output a runnable demo, test reports, license audit results, a risk list, and recommendations for the next phase. Evaluation metrics should not only look at “how much code was generated,” but rather: sample parsing success rate, corrupted input safety, build repeatability, replay consistency, number of license alerts, and average cost per valid change.
VI. Agent Collaboration: Reducing “Self-Serving Correctness” Through Role Division
The biggest risk of high-frequency code generation is not slow writing, but errors being massively duplicated. It is recommended to split agents into different roles:
- Planner: Breaks milestones into small tasks, providing boundaries and dependencies.
- Implementer: Writes code strictly according to specifications, accompanied by tests.
- Reviewer: Checks architecture, exception handling, license, and similarity risks.
- Tester: Supplements negative cases, fuzz tests, and regression comparisons.
- Archivist: Updates self-built specifications, change logs, and evidence chains.
Each task should have an acceptance template similar to the following:
Task scope: Implement reading for a specific resource index tableInput samples: A set of legal samples + a set of truncated/malformed samplesAcceptance criteria:1. All legal samples can be parsed stably;2. Illegal inputs must not crash and must return locatable errors;3. No incompatible license dependencies introduced;4. New regression tests added and all passed;5. Key fields have documented evidence sources.Human decision point: If field semantics cannot be verified, do not fabricate them.
Without this template, the model will easily continue stacking features after it “looks like it runs,” eventually forming an unmaintainable black box. High-frequency commits must be paired with mandatory gating, automatic rollbacks, and small incremental changes; otherwise, the faster the generation speed, the faster the technical debt accumulates.
VII. Rewriting Architecture: Compatibility First, Modernization Second
There are usually two routes for rewriting legacy software: a one-time rebuild, or “compatibility layer + progressive replacement.” For projects with lost source code, the latter carries lower risk. Key designs include:
- Separation of parsing and business layers: Private format parsing is isolated as a module for easy replacement and fuzz testing.
- Data-driven: Maps, units, rules, and UI configurations are made data-centric to reduce hardcoding.
- Separation of simulation and rendering: The core simulation maintains fixed time steps; rendering and input only consume state.
- Deterministic design: Random numbers, floating-point behavior, and event sequences are traceable, facilitating replay and network verification.
- Compatibility layer: First ensure old resources are readable and old behaviors are comparable, then gradually migrate to modern formats.
- Secure defaults: All binary inputs are processed within sandbox-like boundaries, limiting memory, file length, and recursion depth.
The networking part, in particular, cannot rely solely on the model to “write a network module.” You need to define the sync model, add state verification, detect desynchronization, record command logs, and prepare for reconnection and malicious client protection. The model can accelerate boilerplate code, but protocol design and failure models must be defined by humans.
VIII. Quality, Compliance, and Security: Three Non-Negotiable Baselines
First, license and copyright compliance.
Do not ignore dependency reviews just because the model “writes fast.” Static linking, secondary distribution, and resource asset usage must all be vetted. For outputs suspected of being highly similar to existing implementations, similarity detection and clean rewrites should be performed; all third-party dependencies enter a Software Bill of Materials (SBOM), recording version, license, purpose, and distribution method.
Second, clean implementation and evidence chain.
Models might reproduce algorithms and constants from training data, so source review is mandatory. It is recommended to separate “observe behavior - compile specification - independent implementation - comparative testing.” Record sample hashes, experimental conclusions, and reviewers for each key compatibility point to avoid unexplainable issues during future maintenance.
Third, security testing and privacy boundaries.
Parsers are typical attack surfaces; boundary checks, fuzz testing, timeouts, and memory limits should be added. When sensitive data is involved, do not upload un-desensitized code, keys, or customer assets to unauthorized services. Model-generated code must also undergo dependency vulnerability scanning, permission checks, and supply chain audits.
IX. Capabilities and Limitations: What Models Can Accelerate vs. Replace
From practice, LLMs excel at:
- Rapidly generating parsers, serialization code, test skeletons, and migration adapter layers.
- Proposing experimental hypotheses based on failure logs.
- Filling in large amounts of repetitive code under clear specifications.
- Organizing scattered observations into documentation and regression use cases.
However, they cannot reliably replace the following:
- System architecture trade-offs and long-term evolution roadmaps.
- Final semantic judgments of private formats.
- Legal responsibility judgments regarding licenses and copyrights.
- Network synchronization, performance optimization, and high-risk security design.
- Proof of source for “model-memorized” content.
Therefore, whether it is worth introducing a model does not depend on “code generation speed” itself, but on whether the team can establish a verification oracle: having samples, golden tests, replays, audits, and failure rollbacks. As long as the verification loop is strong enough, the stronger the model, the greater the benefit; if the verification loop is missing, the stronger the model, the greater the risk.
X. Conclusion
Returning to the initial question: Are there practical application cases for LLM-driven reverse rewriting of legacy software? Yes, but its correct form is a pilot engineering project of “auditable code agents + high-frequency integration + clean implementation + automated verification.” It can advance format reconnaissance, parser skeletons, UI shells, test supplementation, and prototype networking to a demonstrable state within weeks; it can also generate a massive amount of seemingly correct code, so it must be backed by engineering disciplines.
For enterprises, the most pragmatic approach is not to rewrite the entire system at once, but to select a module with clear boundaries, sufficient samples, and legal research viability for validation: for example, a private file format, a legacy protocol adaptation layer, or a compatibility shell for an old UI. First prove that the format can be parsed, behaviors can be regressed, licenses can be audited, and costs can be measured, then discuss expanding the scope. This way, LLMs bring not “magic generation,” but an engineering capability that tangibly shortens feedback cycles and improves the efficiency of legacy system modernization.
