Debugging Legacy Code with Large Language Models: A Two-Round Practical Framework

    This article presents a practical framework for using AI coding tools to debug legacy firmware and low-level graphics code. It explains why legacy projects are hard to take over, then walks through a two-round iteration process—getting the code runnable first, then refining it—with a four-step loop of code review, runtime verification, defect localization, and fix regression. Real examples cover wild pointers after mode switches, mismatched protocol identifiers, and silent failures, along with a reusable checklist for teams.

    1. Why Legacy Code Is Hard to Take Over

    In firmware and low-level graphics development, there is often a full debugging cycle between “it compiles” and “it runs.” A representative case from the original practice: a graphics mini-game generated by an AI coding tool. The structure looked clean—split into entry point, main loop, game logic, rendering, and input handling—but in a new environment it either failed to launch the GUI or exited immediately after startup. Legacy code like this typically has three pain points:

    1. Missing context: The original author’s design intent, environment assumptions, and dependency versions were never documented.
    2. Tight environment coupling: Low-level graphics output depends on protocols and memory layouts provided by the firmware environment, so it breaks as soon as the environment changes.
    3. Silent failures: Low-level programs lack logging facilities, making crash points hard to locate; the only option is “drip-feed” debugging through serial output.

    So the first step in taking over legacy code is not to change code, but to establish observability.

    2. Methodology: A Two-Round Debugging Framework

    The practice uses a two-round approach that generalizes to most legacy projects:

    • Round 1: Make it runnable. The goal is stable startup, entering the main loop, and completing one rendered frame—not full functionality.
    • Round 2: Refine and optimize. Building on a runnable baseline, address interaction feel, rendering efficiency, and edge-case behavior.

    Each round is a four-step closed loop: code review → runtime verification → defect localization → fix and regression. The key is to leave a written issue list after every round, avoiding the “fix one thing, break three others” trap.

    3. Round 1: From Review to Runnable

    3.1 Code Review: Produce an Issue List First

    After copying the legacy code into a new project unchanged, the first instruction should be review, not modification. Have the AI coding tool inspect each module—entry function, main loop, game logic, rendering, and input handling—and output a structured issue list, for example:

    • Whether there are dangling references in the timing of resource acquisition and release;
    • Whether protocol/interface identifier constants match the target environment;
    • Whether cached buffer information becomes invalid after a mode switch;
    • Whether input events are consumed before initialization completes.

    The value of review is turning “unknown risks” into “checkable tasks,” so every subsequent fix can be regression-tested.

    3.2 Defect One: Immediate Exit and Wild Pointers

    The symptom: the program printed its startup message and exited immediately. After adding serial debug logs, the crash was localized to right after a graphics protocol call. Root cause: the information pointer obtained when querying the mode pointed to memory that became invalid after the mode switch—a wild pointer. Subsequent rendering kept using that pointer and triggered an exception.

    The fix follows the principle of “switch first, then re-fetch”:

    1. // Bad: keep using the old pointer after switching modes
    2. mode_info = query_mode(gop, mode);
    3. set_mode(gop, mode);
    4. framebuffer = mode_info->frame_buffer; // old memory may already be invalid
    5. // Good: re-fetch after the switch completes
    6. set_mode(gop, mode);
    7. mode_info = query_mode(gop, mode);
    8. framebuffer = mode_info->frame_buffer;

    The general lesson: pointers, handles, and caches that cross a state change must be treated as invalidated resources. Any “fetch first, use later, change state in between” pattern should be considered high-risk.

    3.3 Defect Two: Missing GUI Due to Identifier Mismatch

    The program no longer crashed, but the screen showed no output. Analyzing the runtime logs pointed to a misconfigured identifier constant for the graphics output protocol: the target environment had multiple similar protocol identifiers, and picking the wrong one meant no usable graphics output interface was obtained, so rendering commands had nowhere to land.

    Troubleshooting checklist:

    • Confirm the mapping between the identifier used and the target environment version, rather than reusing constants from the old project;
    • Validate at initialization whether the interface was acquired successfully, and print a clear error code on failure;
    • Chain “acquire interface → query mode → set mode → get framebuffer” into one logged path, so a failure at any step is visible.

    3.4 Round 1 Acceptance Criteria

    Round 1 is complete when: the program starts repeatedly without crashing, serial logs show the full initialization chain, and the program enters the main loop with periodic heartbeat output. Only then is it allowed to proceed to Round 2.

    4. Round 2: Refinement and Optimization

    Once runnable, optimize in order of payoff:

    1. Stability: Add handling for exception branches so null pointers and failed returns are not ignored;
    2. Observability: Turn temporary debug logs into leveled logs, collected via a logging service or serial output for long-term maintenance;
    3. Rendering and input: Reduce repeated per-frame computation and cache static resources; add debouncing and focus checks to input handling;
    4. Portability: Consolidate environment-specific constants and initialization logic into a separate adaptation layer to lower the cost of switching environments.

    5. Reusable Checklist

    • Review legacy code and write down an issue list before touching the keyboard;
    • Re-fetch all cached pointers after any state switch;
    • Verify protocol and identifier constants against the target environment, and log the entire initialization chain;
    • Proceed in two rounds: Round 1 only guarantees “it runs”; Round 2 is for optimization;
    • Isolate environment differences in an adaptation layer to improve portability;
    • General-purpose capabilities such as the container platform, logging service, and monitoring/alerting offered by Baidu AI Cloud can standardize build, runtime, and log collection, making the AI-assisted debugging process observable and traceable as well.

    6. Conclusion

    The real value of AI coding tools in taking over legacy projects is not how much code they generate at once, but executing the “review → verify → localize → fix” loop consistently. With the two-round iteration framework and awareness of common low-level graphics pitfalls, teams can turn uncontrollable “crash scenes” into a reproducible, measurable engineering process.