Debugging Legacy Code with Large Language Models: A Practical Walkthrough

    This article shares a practical experience of using a large language model to take over and debug legacy code that looked well-structured but failed to run. It walks through a two-round workflow: first establishing observability and turning vague failures into a checklist of testable hypotheses to reach a runnable state, then refining correctness, rendering performance, input handling, and robustness. Key lessons include re-querying resources after state changes, verifying protocol handle binding, checking return statuses, and validating in small steps. The article closes with a reusable handover process and common pitfalls to avoid.

    1. Background: Why Taking Over Broken Code Is Harder Than Generating from Scratch

    In real development work, the capability people most often expect from AI coding assistants is “generating a runnable project from scratch.” But in actual engineering, a more frequent scenario is the opposite: taking over code left behind by someone else (or by another model) that looks properly structured yet does not run.

    The original practice was fairly representative: an intelligent coding tool produced a modular bare-metal graphics program consisting of seven files, with clear separation between the entry point, main loop, game logic, rendering, and input handling. However, even setting up the build environment in a real environment proved difficult, and there was no runnable artifact in the end. A different large language model then took over and completed the fix in about two and a half hours, after which the program ran successfully.

    This contrast highlights an easily overlooked conclusion: there is a huge gap between code that “looks correct” and code that “runs correctly.” Modularity and naming conventions only solve maintainability; they cannot guarantee that runtime contracts (memory validity, protocol handles, mode-switch timing) hold. So the first principle when taking over legacy code is not to keep adding features, but to establish observability.

    2. Round One: From Not Running to Running

    2.1 Start with a Static Review and Produce a Problem List

    The first instruction after taking over should be to review, not to modify: have the model read through the entry point, main loop, logic, rendering, and input handling module by module, and output a candidate list of “issues that could prevent the program from running,” along with a clear fix order. The value of this step is that it breaks the vague “it doesn’t run” into a list of verifiable hypotheses and avoids blind trial and error.

    A practical review outline:

    • Startup path: does the entry point complete basic initialization, and are return values checked;
    • Resource acquisition: is the success status verified when acquiring handles/protocols;
    • Timing dependencies: are there objects that are used first and invalidated later;
    • Boundaries and branches: are there error branches that will inevitably be hit, or null pointer dereferences;
    • Observability: are there places where logs, serial output, or breakpoints can be inserted.

    2.2 Defect One: Frame Buffer Invalidation After Mode Switch

    After startup, the program printed a loop-start marker and then exited immediately—a classic “initialization passes, runtime crashes” case. After adding serial debug output, the crash was located to a call to the graphics output protocol.

    The root cause was a memory lifetime issue: a pointer in the information structure returned when querying the mode pointed to memory that was no longer valid after the mode was set (a common dangling/wild pointer problem in the industry). Setting the display mode reallocates or remaps the frame buffer, so the previously obtained address naturally becomes invalid.

    The fix is to query the frame buffer information again after the mode is set, then use the new address and dimensions:

    1. // Bad example: keep using the old pointer after the mode switch
    2. status = gop->QueryMode(gop, mode, &cols, &rows, &info);
    3. status = gop->SetMode(gop, mode);
    4. draw_pixel(info->FrameBufferBase, ...); // info is now invalid
    5. // Good example: re-fetch after SetMode
    6. status = gop->SetMode(gop, mode);
    7. status = gop->QueryMode(gop, mode, &cols, &rows, &info);
    8. if (EFI_ERROR(status) || info == NULL) { return status; }
    9. draw_pixel(info->FrameBufferBase, info->FrameBufferSize, ...);

    The general rule to extract: for any resource that follows a “query—change—use again” pattern, you must re-query after the change; do not assume that a cached address remains valid across mode switches.

    2.3 Defect Two: Incorrect Protocol Identifier Configuration

    Once the crash was resolved, the program could run continuously, but there was no output on the screen. After feeding back the runtime result, the model determined that the problem lay in the identifier configuration of the graphics output protocol: in the firmware environment there are multiple graphics-related protocol identifiers, and using the wrong one prevents the graphics output protocol from being located and bound correctly, which manifests as “runs normally but the screen is blank.”

    The key to the fix is to confirm that the referenced identifier matches the definition of the graphics output protocol in the firmware specification, and to print the status code when binding fails instead of silently continuing. The engineering lesson here is: for blank-screen problems, suspect handle binding first, not rendering logic.

    2.4 Round One Acceptance Criteria

    • The process no longer exits abnormally, and the main loop can keep running;
    • The current mode’s resolution and the frame buffer address and size are successfully obtained;
    • An expected initial image appears on screen (even just a solid-color fill);
    • Key paths all have status-code logs, so failures can be located.

    3. Round Two: Refinement, Optimization, and Stability

    Round one only ensures the program is “alive”; round two addresses “correct and smooth.” It is recommended to proceed along four lines:

    1. Input handling: key scanning needs debouncing and edge detection to avoid a single press being recognized multiple times; both pressed and released states must be handled.
    2. Rendering performance: per-pixel writes are expensive in a bare-metal environment and should be changed to row/block copies to reduce repeated computation; use dirty-rectangle updates for static backgrounds, redrawing only changed areas.
    3. Logic correctness: collision detection must cover boundaries and self-collision; random block generation should avoid unreproducible extreme sequences; scoring and line-clearing logic should have pure functions with boundaries that unit tests can cover.
    4. Robustness: the return status of all external calls must be checked; null pointers, out-of-bounds indices, and buffer sizes must be validated explicitly; error branches should output diagnosable information rather than returning directly.

    A schematic skeleton of the main loop:

    1. while (running) {
    2. if (g_system->Reset(g_system, FALSE) == EFI_SUCCESS) {
    3. handle_input(&g_state); // edge detection + state machine
    4. }
    5. if (g_state.dirty) {
    6. update_logic(&g_state); // pure logic, easy to test
    7. render(&g_state); // dirty rectangles + block copies
    8. g_state.dirty = FALSE;
    9. }
    10. g_boot->Stall(1000); // yield the CPU, avoid busy waiting
    11. }

    4. Methodology: A Reusable Handover Process

    • Observe first, modify later: code without logs and status codes is not debuggable, so the first step is always to add observability.
    • Turn assumptions into a checklist: convert “it doesn’t run” into numbered hypotheses, verify and check them off one by one, and avoid regressions.
    • Contracts first: make explicit each module’s external inputs, outputs, and lifetime promises, especially the validity period of resource pointers.
    • Validate in small steps: change only one class of problem at a time and run immediately after each change, to prevent multiple overlapping changes from making attribution impossible.
    • Two-round acceptance: round one checks runnability; round two checks correctness, performance, and robustness, with separate criteria.
    • Build regression cases: turn each fixed defect into a checklist item, forming a handover checklist.

    5. Common Pitfalls

    • Judging code quality by directory structure alone while ignoring runtime contracts;
    • Caching resource addresses assumed to remain valid across modes/states;
    • Ignoring return values, so failures are silently swallowed and appear as “normal running with no output”;
    • Starting with architectural refactoring instead of first making the program run;
    • Lacking observability and building debugging on guesswork.

    6. Conclusion

    What is truly worth attention in this practice of “one AI cleaning up after another” is not which tool wins, but that it validates a general engineering path: when facing legacy code, first establish observability, then eliminate runtime defects item by item with a checklist of hypotheses, and finally deliver stable results through refinement and two-round acceptance. When applying this in the cloud, you can combine container platforms to unify build environments, along with logging services and monitoring alerts to carry runtime diagnostic information, turning this kind of debugging from individual experience into a reusable standard process for the team.