Debugging Legacy Code with Large Language Models: A Practical Methodology

    This article presents a practical, product-agnostic methodology for using large language models to debug legacy code, based on a firmware graphics program case study. It explains why taking over undocumented, non-running code is harder than generating new code, and walks through a two-round workflow: first establishing a minimal runnable loop through structured review, serial logging, and fixes for pointer lifetime and resource identifier issues; then improving stability, resource management, logic completeness, and portability. It also summarizes four guiding principles and common pitfalls to avoid.

    1. Background: Why Taking Over a Mess Is Harder Than Generating from Scratch

    In real development work, the most time-consuming task is often not writing a new module from a blank file, but taking over legacy code with an unknown origin, no documentation, and no ability to run. This kind of code usually has a few characteristics: the directory structure looks reasonable and the modules appear well separated, yet hidden defects sit along the critical paths; the original author has left, so the design intent cannot be confirmed; and the build and runtime environment must be reconstructed, where any missing step makes even “getting it to start” impossible.

    The value of AI coding tools on such tasks is not in generating perfect code in one shot, but in breaking a vague problem domain into verifiable small steps and giving actionable change suggestions at each step. This article uses a debugging session on a firmware graphics program as a sample and discusses a methodology that is independent of any specific product.

    2. First Round Goal: Make It Run, Not Make It Run Well

    The first principle of debugging legacy code is to establish a minimal runnable loop. Focusing on performance and appearance too early only expands the problem surface.

    2.1 Structured Review Before Blind Changes

    Before starting any modification, have the model perform a layered review of the code covering: the entry function, the main loop, business logic, the rendering module, and input handling. The output of the review should be a checkable list of issues, not a generic set of “code style suggestions.” A qualified list typically includes: suspicious null and dangling pointers, unchecked return values, mismatched resource allocation and release, wrong protocol call ordering, and inconsistent constant and identifier definitions.

    A sample review prompt can be organized like this:

    1. Perform a static review of the current project and output only a list of issues, sorted by severity.
    2. Each item should include: file and function, trigger condition, possible consequence, and suggested verification method.
    3. Do not modify the code.

    The point of this step is to turn “unknown” into a “known list,” so that every later change maps to one item on the list, avoiding repeated trial and error.

    2.2 Build Observability: Serial Logs Are the Cheapest Debugger

    Firmware and low-level graphics programs often have no conventional debugger available. In that case, the most economical approach is adding logs. Have the model insert timestamped output at key points, for example one line before and after protocol initialization, before and after mode setting, and at the entry and exit of each frame in the main loop. The goal of logging is not “more,” but being able to answer one question: after which line did the program lose control flow.

    A typical phenomenon seen in practice: after startup the program prints the log marking the beginning of the loop, then silently exits. This kind of “exit without any error message” usually points to interrupted control flow rather than a wrong logic branch.

    2.3 Memory Lifetime: Pointer Invalidation After a Mode Switch

    The root cause of the phenomenon above is that the lifetime of the memory a pointer refers to is shorter than the code that uses it. The information structure returned when the graphics output protocol queries a mode is often maintained internally by the protocol; once the interface for setting the mode is called, the internal buffer may be reallocated, and the pointer obtained earlier immediately becomes invalid. Continuing to use it reads reused memory, which shows up as random crashes or a garbled screen.

    The fix is “fetch after use state change,” moving the information retrieval to after the state change:

    1. // Bad example: fetch info first, then switch mode; the pointer becomes invalid
    2. const VOID *info = NULL;
    3. Status = gop->QueryMode(gop, mode, &size, &info);
    4. Status = gop->SetMode(gop, mode);
    5. Use(info); // Dangerous
    6. // Good example: re-fetch after the state change completes
    7. Status = gop->SetMode(gop, mode);
    8. UINTN size = 0;
    9. const VOID *info = NULL;
    10. Status = gop->QueryMode(gop, mode, &size, &info);
    11. Use(info);

    This type of defect makes up a large share of legacy code, because it hides a timing error behind an appearance of “correct logic.” It is hard to find by static reading and must rely on runtime observation.

    2.4 Inconsistent Resource Identifiers: Graphics Protocol Lookup Failure

    A second common problem is “the program runs but the UI does not appear.” When code locates a protocol instance through a global system table, the identifier used must exactly match the definition in the platform header files. Firmware specifications often contain several identifiers with similar names, pointing to different protocols or different purposes. Choosing the wrong one results in “the lookup succeeds but what you get is not what you wanted,” or simply a not-found return.

    An effective way to investigate this kind of problem is to have the model list all identifiers involved in the code, compare them one by one against the specification definitions, and clarify the semantics and usage scenario of each identifier, instead of guessing based on name similarity. After the fix, the return status code usually still needs to be verified, to avoid treating a failure as a success and continuing.

    3. Second Round Goal: From “Runs” to “Maintainable”

    After the first round passes, the code is often only “barely alive”: unstable frame rate, input latency, missing boundary checks, unreleased resources. The focus of the second round shifts to refinement.

    • Stability: add status code checks for all external calls, and route failures to a unified error handling path instead of continuing execution.
    • Resource management: keep allocation and release of resources such as the frame buffer, event queue, and input devices within the same lifetime, avoiding repeated initialization.
    • Logic completeness: fill in boundary conditions such as collision detection, boundary bouncing, scoring, and restart flow, which are exactly the parts most easily omitted in the prototype stage.
    • Portability: converge platform-related calls into a small number of adapter functions to reduce later migration cost.

    A practical acceptance order is: first get the main path working, then the boundary paths, and finally the exception paths (for example, a device that does not exist or a mode that is not supported). Only when all three paths pass is it truly deliverable.

    4. Methodology: Four Rules for Letting a Model Take Over Legacy Code

    1. Review first, act second. Turn problems into a list, map each change to one item, and form a traceable closed loop.
    2. Observe first, reason second. Guessing without logs and state output has a very low hit rate; observability is a prerequisite for low-level debugging.
    3. Focus on timing and lifetime, not just logic branches. Pointer invalidation, state not refreshed, and wrong initialization order are high-frequency areas in legacy code.
    4. Converge goals in rounds. The first round only solves “it runs”; the second round discusses optimization, avoiding mixed goals that cause repeated regressions.

    5. Common Pitfalls

    • Proposing a large number of changes at once, making it impossible to locate which one introduced a new problem.
    • Only telling the model to “fix it” without providing runtime output, leaving the model to infer from imagination.
    • Ignoring return value checks, treating failure as success, and pushing the problem to a later stage where it surfaces.
    • Optimizing rendering and data structures too early, adding variables while the program is not yet stable.

    6. Conclusion

    The real value of large language models on legacy code is turning “no idea where to start” into “a list that can be verified item by item,” and shrinking the problem domain with each iteration. For developers, what needs to be provided is a clear goal, observable runtime information, and explicit acceptance criteria. For platform providers, general capabilities such as a stable build environment, log services, and monitoring alerts can significantly reduce the communication cost of this kind of debugging. With the framework above, even facing a completely unfamiliar project, you can advance at a controlled pace to a runnable and maintainable state.