Debugging Legacy Code with Large Language Models: A Practical Workflow
This article shares a practical approach to using large language models for debugging legacy code, especially in firmware and graphics development where runtime behavior is hard to inspect. It explains why structured, well-modularized code can still fail at runtime, then outlines a two-round iteration process with three layers of acceptance: process stability, correct graphics output, and input, frame rate, resource release, and error recovery. Each stage includes observable evidence such as serial logs, return status checks, and mode queries, along with concrete examples of pointer lifetime errors and graphics protocol identifier mistakes. The goal is to turn AI debugging into a verifiable engineering workflow rather than trial-and-error rewriting.
1. Background: Why Debugging Legacy Code Is Harder Than Generating It
In real development, the failure of AI-generated code is often not that the model cannot write it, but that the code does not run. One comparison showed a clear gap: the same type of model completed a small graphics game in 2.5 hours, compiled successfully on the first try, and ran correctly on the first launch. Another model spent nearly six hours on a similar task and still failed to set up the build environment. This shows that generative models can vary widely in strongly environment-dependent scenarios such as firmware graphics development.
A more useful question follows: if a codebase is well structured and clearly modular but still does not run, can a model help clean up the mess? Such legacy code usually has three characteristics:
- The module layout looks reasonable but hides runtime defects.
- Locating the problem depends on hardware and firmware, making static reading insufficient.
- Error information is sparse, with no operating-system-level exception stack.
The key to debugging is therefore not to have the model rewrite everything, but to build a verifiable feedback loop.
2. Methodology Overview: Two Rounds and Three Acceptance Layers
Split the task into two rounds. The first round aims to make the code run. The second round aims to make it run correctly and reliably. At the same time, apply three acceptance layers:
- Layer 1: The process does not crash and the main loop keeps running.
- Layer 2: The graphics output protocol works and the screen renders correctly.
- Layer 3: Input handling, frame rate, resource release, and error recovery behave as expected.
Every layer must have observable evidence, such as serial logs, return value checks, or mode query results, rather than relying on the impression that “nothing looks wrong.”
3. Round 1: From Not Running to Running Reliably
3.1 Start with a Read-Only Static Review
Before changing any line, have the model perform a read-only review and produce a structured issue list classified into three levels: “will certainly cause a crash,” “may cause display problems,” and “potential risk.” The review should cover the entry function, main loop, game logic update, render submission, input handling, and resource lifecycle. An example prompt:
Perform a static review only. Do not modify any files.Output an issue list ordered by severity. For each item, include: file and function, trigger condition, inferred root cause, and verification method.Focus on: pointer lifetime, protocol return values, order of mode information retrieval, and resource release paths.
The benefit is turning blind debugging into hypothesis-driven verification.
3.2 Issue 1: The Program Exits Immediately Due to a Pointer Lifetime Error
A typical symptom is that the program prints a loop-start log and then exits. Adding finer-grained serial logs can narrow the failure to a point after the graphics output protocol call. The root cause is usually the lifetime of the mode information structure: the information pointer returned by the mode query becomes invalid after the mode is set, and dereferencing it later triggers an exception.
The fix principle is to re-fetch at the point of use instead of holding the pointer long-term:
// Bad: holding the pointer across callsconst VOID *info = NULL;Status = gop->QueryMode(gop, mode, &size, &info);Status = gop->SetMode(gop, mode);use(info); // info may already be invalid// Good: query again after setting the modeStatus = gop->SetMode(gop, mode);UINTN size = 0;const VOID *info = NULL;Status = gop->QueryMode(gop, mode, &size, &info);use(info);
This type of issue is common in firmware and low-level development: read-only structures returned by interfaces are often valid only within a specific call window, and caching them across stages is a common anti-pattern.
3.3 Issue 2: The Program Runs but Shows Nothing Due to a Wrong Protocol Identifier
When Layer 2 acceptance fails, the process stays alive but the screen shows no output. A common root cause is an incorrect graphics output protocol identifier. The firmware specification defines several related identifiers; some are for global variables and some are for protocol installation. Mixing them leads to lookup failures or unusable handles.
A practical approach is to ask the model to produce three-step evidence: locate, open, and validate.
1) Locate the protocol using the graphics output protocol entry provided in the system table;2) Check the return status and confirm the handle is not null;3) Query the current mode and frame buffer information, and print the resolution and pixel format.
Also remind the model not to swallow return statuses. In low-level development, ignoring status codes turns deterministic failures into random ones and greatly increases troubleshooting cost.
4. Round 2: Refinement and Robustness
Once the code runs, focus on correctness:
- Rendering: unify pixel format and stride calculation to avoid image offset and skew.
- Input: apply edge detection and debouncing to key presses to avoid multiple responses from a single trigger.
- Timing: drive logic updates with a fixed time step and decouple rendering from logic.
- Resources: define buffer ownership clearly and release resources through a unified exit path.
- Observability: keep tiered logging switches for on-site diagnosis.
The acceptance checklist should be fixed as a table, with each item checked off and log snippets retained as delivery evidence.
5. Takeaways
Large language models are well suited to debugging tasks that are high-risk and strongly environment-dependent, but they must be constrained by a verifiable process: review before modifying, apply minimal fixes before optimization, and require evidence at every acceptance layer. If a team wants to productize this workflow, it can combine general capabilities such as container platforms, logging services, and monitoring alerts on Baidu AI Cloud to build a closed-loop pipeline of “code review, build, run, and log feedback,” turning AI debugging from an individual skill into a team engineering capability.
