Debugging Legacy Code with Large Language Models: A Practical Methodology

    This article presents a practical methodology for using AI coding assistants to debug legacy code that compiles but fails at runtime. It covers a two-round workflow, from static review and minimal signal injection to reach a runnable state, then hardening for maintainability. Readers will find reusable review prompts, real failure patterns such as stale framebuffer pointers and incorrect protocol identifiers, code examples, and a four-step troubleshooting framework for driving AI toward stable convergence when context is incomplete.

    1. Why Taking Over Broken Code Is Harder Than Generating From Scratch

    In real development work, the most commonly validated scenario for AI coding assistants is generating a small working program from scratch. Real engineering, however, often demands the opposite: taking over code left behind by someone else (or another model) that looks well structured but does not run. This kind of task is significantly harder for three reasons.

    First, context is missing. The original design intent, environment assumptions, and dependency versions are undocumented, so the model can only infer them from the code itself. Second, the failure location is uncertain. A program that “compiles but exits immediately at runtime” may have its root cause anywhere in the initialization flow, memory lifetime, or protocol interaction. Third, the feedback chain is long. Low-level graphics programs often produce no standard output, so progress must be judged from indirect signals such as serial logs or screen display.

    The core of this article is therefore not “which model is stronger,” but a general troubleshooting methodology: how to let AI converge on a problem step by step through a closed loop of review, hypothesis, verification, and correction, even when information is incomplete.

    2. Round One: From “Does Not Run” to “Basically Runs”

    2.1 Start With Static Review and Build a Problem List

    The first instruction after taking over code should ask the model to read through it and output risk points, not modify it immediately. An effective review prompt can be organized like this:

    1. Review this code module by module: entry flow, main loop, business logic, rendering, input handling.
    2. Output: 1) points that may cause crashes; 2) lifecycle and resource management risks; 3) whether external interface calls are paired and parameters are valid.
    3. Give the list only. Do not change the code yet.

    The value here is turning “blind changes” into “verification with hypotheses.” The model’s list typically covers three high-frequency categories: pointers or handles used before initialization, incorrect ordering of resource acquisition and release, and unchecked return values from external protocol calls.

    2.2 Failure One: Immediate Exit on Startup, Traced to Invalid Framebuffer Information

    The program compiles and starts, prints the log showing it entered the main loop, and then exits immediately. This is a classic case of “a trap laid during initialization, triggered in the main loop.”

    The approach is to add logs and narrow the scope. Have the model insert serial output before and after key calls, and the crash point can quickly be narrowed to just after the display mode setting call. Further analysis reveals that the pointer to the information structure obtained when querying the display mode is no longer valid after the mode takes effect: that memory region has been reallocated or freed, and continuing to read it is a wild pointer access.

    The repair principle is one sentence: resource acquisition must be performed again in the stage where the resource is used; an old handle cannot be reused across stages.

    1. // Bad: reusing an old pointer across stages
    2. info = query_mode(handle, mode);
    3. set_mode(handle, mode);
    4. draw(info->frame_buffer, info->width, info->height); // info is now invalid
    5. // Good: re-acquire after the mode takes effect
    6. set_mode(handle, mode);
    7. info = query_mode(handle, mode); // query once more
    8. draw(info->frame_buffer, info->width, info->height);

    This class of problem is extremely common in graphics, networking, and file handle scenarios, and is worth adding to the team’s code review checklist.

    2.3 Failure Two: No More Crashes, but a Blank Screen

    The typical symptom of the second stage is a stable process with normal logs but no output on the screen. The problem has shifted from “memory correctness” to “incorrect interface identifier configuration”: the low layer defines multiple similar protocol identifiers, and using the wrong one causes the retrieved interface to be null or to behave abnormally, so the program never reaches the actual drawing branch.

    There are two steps to handle this. First, have the model list the definition locations and differences of all relevant identifiers in the current environment, and compare them one by one against the values actually used in the code. Second, validate the return status and check that the pointer is non-null immediately after acquiring the interface; on failure, print a clear error code instead of continuing.

    1. status = locate_protocol(&expected_guid, &gop);
    2. if (EFI_ERROR(status) || gop == NULL) {
    3. serial_printf("locate gop failed: %d\n", status);
    4. return status; // fail early, avoid a later null pointer
    5. }

    “Fail early, log, and never swallow errors” is a basic discipline in low-level development, and also the prerequisite for letting AI correct itself: the model can only see the signals you feed it.

    3. Round Two: Refinement and Maintainability

    Once the first round runs, do not rush to add features. Do a round of “runnability hardening” first:

    • Input handling: confirm that key scanning has debounce and repeat-trigger protection to avoid runaway movement speed;
    • Timing control: the main loop needs a fixed cadence to prevent logic from running too fast when rendering speed is bound to hardware refresh;
    • Resource management: every acquisition has a corresponding release path, including in exception branches;
    • Clearer state machine: model “start / in progress / pause / end” explicitly to reduce scattered boolean flags;
    • Observability: keep a leveled log switch for on-site diagnosis.

    A skeletal main loop is shown below:

    1. while (running) {
    2. tick = get_tick();
    3. if (tick - last >= FRAME_MS) {
    4. last = tick;
    5. handle_input();
    6. update_game(); // pure logic, does not touch hardware
    7. render(); // drawing only
    8. }
    9. }

    Decoupling “logic update” from “hardware drawing” is key to whether this kind of program can be maintained continuously by AI; the tighter the coupling, the higher the probability that each model change introduces a regression.

    4. A Reusable Four-Step Troubleshooting Method

    1. Freeze the scene: keep a copy of the original code so all changes can be rolled back, making it easy to compare “which step started to improve things.”
    2. Static review first: produce a problem list and hypotheses before acting, avoiding cascading changes.
    3. Minimal signal injection: use serial or logs to illuminate the execution path, verifying one hypothesis at a time.
    4. Two-round iteration: the first round only pursues runnability, the second handles robustness and structural optimization, avoiding mixed goals.

    5. Conclusion

    The real value of AI-assisted development is not only “generating fast,” but also taking over a chaotic scene and converging stably. In this practice, going from not runnable to runnable relied not on a stronger model, but on clearer constraints: explicit review instructions, observable runtime signals, strict resource lifecycle management, and round-by-round goal control. Once this workflow is fixed, a team can significantly improve troubleshooting efficiency and delivery certainty regardless of which class of intelligent coding tool or cloud development environment it uses.