Debugging Legacy Code with LLMs: A Practical Guide
This article shares a practical workflow for using large language models to debug and repair legacy code. It covers a two-round, three-layer methodology: static review, dynamic observation, and root-cause verification. Through a firmware graphics demo case, it explains common failure patterns such as stale pointers after mode changes and protocol GUID mismatches, and provides a reusable troubleshooting checklist for reliable human-AI collaboration.
1. The Starting Point: Why Taking Over a Mess Is Harder Than Generating From Scratch
In real development work, generating a module from scratch and taking over an unknown, non-running piece of legacy code are tasks of completely different magnitudes. The former only requires the model to have coding ability. The latter additionally demands three capabilities: understanding someone else’s design intent, reproducing and explaining failure symptoms, and making minimal fixes without overturning the overall architecture.
The scenario in this practice is quite representative: a graphical mini-game for a firmware environment, split into seven modules. The structure looks well organized, but there is no way to set up a build environment and no runnable artifact. Discarding it would be a waste, and rewriting it would waste the existing structure, so the decision was made to bring in a large language model for “firefighting.” This type of task is generally referred to as legacy remediation in engineering. The difficulty lies not in writing new code, but in establishing a trustworthy causal chain.
2. Methodology Overview: Two Rounds and Three Layers
Break the entire process into two rounds and three layers:
- The first round targets “getting it to run,” solving only blocking issues without optimization;
- The second round targets “running correctly and stably,” handling logic errors, experience defects, and resource issues;
- The three-layer localization order is: static review layer (read the code to find suspicious points) → dynamic observation layer (add logs, check output order) → root-cause verification layer (propose hypotheses and make single-point changes to verify).
This order cannot be reversed. Making code changes without static review easily leads to “fix one thing, break another.” Trusting the model’s conclusions without dynamic observation easily leads to accepting plausible-sounding but non-reproducible explanations.
3. Round One: From Static Review to Runnable
3.1 Do a Code Review First, Not a Fix
The first instruction should be deliberately restrained, for example:
Please review this code, list the issues that could prevent it from running, ordered by severity, and do not modify anything yet.
The model then checks the entry function, main loop, game logic, rendering module, and input handling module by module, and outputs a prioritized list of issues. The value of this step is that it transforms the vague feeling of “not runnable” into several verifiable, concrete hypotheses. The review conclusions must be treated as hypotheses, not conclusions.
3.2 Symptom One: Immediate Exit on Startup and Memory Lifetime
After adding logs, a typical pattern appears: the loop-start marker is printed, and the process ends immediately, indicating the exception occurs after the graphics protocol call. Further localization points to the information pointer returned by the mode query becoming invalid after switching modes. This is a classic trap in firmware and low-level graphics programming: the query interface returns a pointer to an internal protocol buffer, and once SetMode is called, the internal buffer is reallocated, so the old pointer becomes a wild pointer.
The fix principle is also fixed: do not reuse the same pointer across a state change; the pointer must be re-obtained after the state change.
// Bad example: continuing to use the old pointer after switching modesinfo = gop->QueryMode(gop, mode, &size);gop->SetMode(gop, mode);frame = info->FrameBufferBase; // info may already be invalid// Good example: re-query after the state changegop->SetMode(gop, mode);info = gop->QueryMode(gop, mode, &size);frame = info->FrameBufferBase;
A safer approach here is to copy the frame buffer base address and size into local variables after re-querying, avoiding holding an external pointer for a long time.
3.3 Symptom Two: Protocol Identifier Misconfiguration Causing a Blank Screen
The process no longer exits, but there is no output on screen. This kind of “silent failure” usually comes from a protocol identifier (GUID) mismatch: multiple similar graphics-related identifiers exist in the underlying framework, and when the wrong one is referenced, the locate interface returns “not found,” while the caller often ignores the return value, so all subsequent calls operate on a null pointer.
There are two key points for the fix: first, verify that the identifier used is consistent with the definition in the framework version; second, all locate interfaces must check the return value and return early on error, for example:
status = locate_protocol(&g_protocol_guid, NULL, (void **)&gop);if (status != 0 || gop == NULL) {log_error("locate gop failed: %d", status);return status;}
4. A Reusable Troubleshooting Checklist
- Return values of all external interfaces must be checked, especially “locate/query” interfaces;
- Do not cache pointers across state-change cycles; copy values when necessary;
- Serial ports or logging services are the cheapest observation means; add logs before guessing at logic;
- Change only one variable at a time, verify immediately after the change, and form a traceable record;
- Have the model output a three-part explanation of “hypothesis — verification method — expected symptom,” rather than directly giving a patch;
- The build environment itself is also a source of failures; dependency and toolchain versions must be pinned and recorded.
5. Round Two: Refinement and Engineering
Once it runs, move on to refinement: use a fixed time step so speed does not drift with frame rate, apply edge detection to input to avoid repeated triggering, reduce full-screen redraws in rendering, unify error paths, and add reproducible test cases for randomness and boundary conditions. If cloud collaboration is involved, a container platform can be used to pin down the build environment, object storage can hold build artifacts, and logging services with monitoring and alerting can track exceptions. These all belong to general capability categories and are vendor-independent.
6. Conclusion
The benefit of having a large language model take over legacy code lies not in generating something correct in one shot, but in making the troubleshooting process conversational, observable, and traceable. What truly determines success or failure is the process: review first, then observe, then modify, combined with strict return-value checking and memory-lifetime awareness. Only by solidifying this workflow can the debugging efficiency of human-AI collaboration become stable, rather than depending on luck.
