Debugging Legacy Code with LLMs: A Practical Playbook for AI-Assisted Troubleshooting

    This article shares a practical workflow for using a large language model (LLM) to debug legacy code originally generated by another AI coding tool. Using a modular graphics demo that compiled cleanly but failed at runtime as the example, it walks through a two-round process: first moving from static review to a runnable program, then refining for maintainability. Key topics include structured code review prompts, crash localization through added observability, handling dangling handles across state changes, verifying display protocol identifiers and mode/resolution matching, and improving resource lifecycle, error handling, and logging. It closes with four hard rules for AI-assisted debugging—layered context, minimal reproduction, closed-loop verification, and traceable conclusions—plus common pitfalls to avoid.

    1. The Starting Point: Why “It Compiles” Doesn’t Mean “It Runs”

    In firmware and low-level graphics development, a common mistake is treating a clean build as the delivery standard. Compilation only checks syntax and types. Runtime issues—memory validity, protocol handle lifetimes, display mode matching—surface only in a real environment.

    This article follows a hands-on case: a small graphics game generated by an AI coding tool. It had seven files, a clear modular split, and a tidy directory structure. By all appearances, the code looked solid. But once copied into a new environment, it failed to launch the graphical interface and exited immediately on startup. We handed this legacy code to another LLM, with the goal of turning code that “looks correct” into a program that “actually runs.”

    The value of this exercise is not comparing tools. It is about building a method: when AI-generated code needs to be debugged by another AI, how should a human organize context and design a verification loop?

    2. Round One: From Static Review to a Runnable Program

    2.1 Review First, Don’t Modify Right Away

    The first instruction when taking over legacy code should be to review, not to change. Have the model walk through the code module by module: entry point, main loop, game logic, rendering, and input handling. The review output should be a checklist of concrete issues, not vague commentary.

    A reusable review prompt structure looks like this:

    1. Please review this code in the following order:
    2. 1) Whether entry point and dependency initialization are complete;
    3. 2) Whether the main loop's exit condition is reachable and unique;
    4. 3) Whether graphics output handles and mode information are used across their lifetime;
    5. 4) Whether input events are properly consumed;
    6. 5) Whether there is uninitialized memory, out-of-bounds access, or unreleased resources.
    7. Output format: issue list + impact + suggested fix location.

    The benefit is clear: it turns a vague “it won’t run” into several verifiable hypotheses.

    2.2 Crash Localization: Change One Variable at a Time

    After launch, the program printed a log showing the loop had started, then exited. The most effective move here is not guessing but adding observability: insert serial logs along the critical path to mark execution progress, narrowing the crash point to just after a specific call.

    The finding: a query for display mode returned an info pointer, but after the mode was set, the memory region that pointer referred to became invalid. Dereferencing it afterward triggered the fault. The fix was to adjust the sequence—re-fetch the frame buffer info after the mode is set, instead of reusing the old pointer.

    This abstracts into a general principle: treat any handle or pointer that crosses a state change as invalid, and re-acquire it. In firmware, graphics stacks, and device drivers, this kind of “dangling handle” is one of the most typical sources of runtime crashes.

    1. /* Bad: reusing an old pointer */
    2. QueryMode(&Info);
    3. SetMode(Mode);
    4. UseFrameBuffer(Info); /* Info may already be invalid */
    5. /* Good: re-acquire after the state change */
    6. QueryMode(&Info);
    7. SetMode(Mode);
    8. QueryMode(&Info); /* re-fetch valid info */
    9. UseFrameBuffer(Info);

    2.3 No GUI Appears: Identifier and Configuration Correctness

    Once the crash was fixed, the program no longer exited, but the screen stayed blank. This kind of “silent failure” usually comes from a configuration mismatch: the graphics output protocol has multiple related global identifier definitions, and picking the wrong one means the protocol instance can’t be located correctly, leaving the screen empty.

    The approach is to have the model output the source and definition location of each identifier it uses, then compare them one by one against the definitions in the current firmware spec. The key here is requiring sources, so the model doesn’t fabricate constants from memory.

    2.4 Output But No Picture: Mode and Resolution Matching

    A deeper typical problem: logs are normal, the loop is running, but there’s no valid picture on screen. The cause is often that the requested resolution or pixel format doesn’t match a mode the device actually supports. A suggested troubleshooting order:

    1. Enumerate the device’s supported mode list and print it;
    2. Confirm whether the effective mode matches the requested one;
    3. Verify pixel format, bits per pixel, and color depth assumptions;
    4. Check whether the render target buffer size is recalculated based on the effective mode.

    3. Round Two: Refinement and Optimization

    The goal of round one was “it runs.” The goal of round two is “it’s maintainable.” Suggested to proceed along four dimensions:

    • Resource lifecycle: release all acquired resources in pairs on the exit path, avoiding leaks on exception paths.
    • Error handling: replace “no return value check” with explicit error propagation, returning a locatable error code on failure.
    • Observability: add log levels, allow debug info to be turned off via a switch, and avoid flooding that affects performance judgment.
    • Structural convergence: extract duplicated initialization logic into a single entry point, reducing inconsistency from multiple edits.

    4. Methodology: Four Hard Rules for AI-Assisted Debugging

    1. Layer the context: give structure and responsibilities first, then specific files, then runtime logs. Avoid dumping everything at once, which scatters attention.
    2. Require a minimal reproduction: have the model produce the shortest reproducible path first, then discuss fixes, to avoid spinning on unrelated code.
    3. Close the verification loop: after each change, there must be a clear observation point (log, screen, return value). A change without an observation point is considered incomplete.
    4. Require traceable conclusions: when constants, protocols, or mode definitions are involved, require the model to cite sources, and adopt them only after human review.

    5. Common Pitfalls

    • Treating a clean build as a working feature;
    • Modifying multiple places at once, making attribution impossible;
    • Looking only at the final symptom, not the timing before and after a state change;
    • Letting the model “freestyle” a refactor and break the parts that already worked;
    • Lacking regression verification, fixing one problem and introducing two new ones.

    6. Conclusion

    Having an LLM take over code left behind by another tool is essentially an exercise in “context engineering + systematic troubleshooting.” What really determines success is not how nicely the model writes, but whether the human breaks the problem into small enough pieces and designs verification clearly enough.固化 the four steps—review, localize, fix, and regression—into a process, and AI can reliably clean up after us instead of creating new messes.