Debugging Legacy Code with LLMs: A Practical Two-Round Approach

    This article walks through a practical workflow for using large language models to debug legacy code that looks complete but fails to run. It covers a first pass focused on static review and reachability, including two real defects involving stale framebuffer data after a display mode switch and mismatched protocol identifiers, followed by a second pass on resource handling, input, rendering, and observability. Readers will find reusable checklists and a repeatable engineering process for turning one-off fixes into stable delivery.

    1. Why Taking Over Legacy Code Is Harder Than Generating from Scratch

    In real development work, the scenario most often used to validate AI coding assistants is “generating a small program from scratch.” In actual engineering, however, a more common situation is different: the project already exists, the code was produced by different tools in different batches, and it looks structurally complete but does not run. The problem with this kind of legacy code is not that it cannot be written, but that it cannot run, and the defects are often spread across multiple layers such as the environment, protocols, and memory lifetime.

    In one typical engagement, an intelligent coding tool first performed a static review of the legacy project, then moved on to runtime debugging, and finally used two rounds of iteration to take an unrunnable project to a runnable and optimizable state. This shows that the value of a large model is not only producing code, but also taking on systematic troubleshooting and refactoring work.

    2. Round One: From “Looks the Part” to “Actually Runs”

    1. Start with a Code Review and Build a Defect List

    The first step in taking over a project is not to change code, but to have the model read through it module by module: entry function, main loop, business logic, rendering, and input handling. The review should focus on three categories of risk:

    • Lifetime issues: whether resource allocation and release are paired, and whether pointers are still used after they become invalid;
    • Interface contract issues: whether return values, output parameters, and handle validity are checked;
    • Environment dependency issues: whether compile macros, target platform, and protocol identifiers match the runtime environment.

    The value of the review is to turn “blind debugging” into “working through a checklist,” reducing repeated trial and error.

    2. Typical Defect One: Framebuffer Invalid After a Display Mode Switch

    The program entered the main loop after startup and then exited immediately. After adding serial log output, the anomaly was found to occur after a call to the graphics output protocol. The root cause was that the information structure obtained by querying the mode pointed to memory that had become invalid after the mode switch, and continuing to read it triggered the exception.

    The fix is to adjust the call order and the timing of data retrieval:

    1. // Switch the mode first, then query the current mode information again
    2. status = gGop->SetMode(gGop, target_mode);
    3. if (EFI_ERROR(status)) return status;
    4. status = gGop->QueryMode(gGop, target_mode, &info);
    5. if (EFI_ERROR(status)) return status;
    6. // Use the resolution and pixel format in info to initialize rendering

    The key point is that for any “query-change-use again” chain, you must confirm whether the data is still valid after the change; when necessary, query again instead of caching the old pointer.

    3. Typical Defect Two: Mismatched Protocol Identifier Causes the GUI Not to Appear

    When the program runs but shows no screen, this usually points to an incorrect protocol identifier configuration. In firmware development environments, there are several similar definitions for graphics output related identifiers, and choosing the wrong one prevents the protocol instance from being obtained correctly. The fix is to unify the source of the identifier and avoid hard-coding it in business code:

    1. #include <Guid/GraphicsOutput.h>
    2. status = gBS->LocateProtocol(&gEfiGraphicsOutputProtocolGuid, NULL, (VOID **)&gGop);

    It is also recommended to add capability probing at the startup stage: whether the resolution is supported and whether the pixel format is the expected type, to avoid building subsequent rendering logic on wrong assumptions.

    3. Round Two: Refinement, Optimization, and Stability Hardening

    Round one solved “can run”; round two solves “runs stably and for a long time.” It is recommended to proceed along four lines:

    1. Resources and error handling: every allocation has a corresponding release; check the return code of every external call and propagate it upward;
    2. Input and main loop: debounce input and throttle the frame rate to avoid busy waiting that occupies the processor;
    3. Rendering and layout: glyph caching and line-wrapping rules for non-monospaced characters such as Chinese, to avoid out-of-bounds drawing;
    4. Observability: tiered logging and instrumentation on critical paths, making it easy to trace back through the serial port or a log service.

    A skeletal main loop:

    1. while (running) {
    2. process_input(&running);
    3. update(&state, dt);
    4. render(&state);
    5. throttle_frame(60);
    6. }

    4. Methodology: Turning Occasional Success into Repeatable Delivery

    • Environment first: pin down the target platform, compile macros, and dependency versions to reduce “runs locally but not elsewhere”;
    • Review first: produce a defect list before making changes, and fix by priority;
    • Small-step verification: change only one category of problem at a time, and run verification immediately after each change;
    • Two-round iteration: round one for reachability, round two for robustness and performance;
    • Complete deliverables: archive the source code, build instructions, run logs, and known limitations together.

    5. Conclusion

    The key to a large model taking over legacy code is not “whether it can write it,” but whether it can complete review, localization, fixing, and verification through an engineering process. By treating lifetime, interface contracts, and environment consistency as core check items, combined with two rounds of iteration and observability work, a one-off “it runs” can be turned into stable delivery capability.