Debugging Legacy Code with LLMs: A Practical Playbook

    This article presents a practical workflow for using large language models to debug and repair legacy or AI-generated code. Instead of regenerating code from scratch, the approach focuses on diagnosis under existing constraints through layered acceptance criteria (runnable, displayable, interactive), static review before fixes, observability design, and a repeatable loop of review, reproduction, isolation, minimal fix, regression, and refactoring. Two representative firmware graphics failures—stale framebuffer information after mode changes and incorrect protocol identifiers—are used to illustrate root-cause analysis and concrete fixes. The article also covers state lifecycle awareness, input debouncing, rendering optimization, and a final acceptance checklist that teams can reuse.

    1. Why Legacy Code Is Harder Than Generating from Scratch

    In real development, model-generated code rarely reaches a deliverable state on the first attempt. A more common scenario is that an engineering skeleton produced by an AI coding tool is kept, but it fails to run because of environment differences, protocol misunderstandings, or state management defects. Taking over this kind of code is not “generating it again.” It is diagnosis and repair under existing constraints.

    In the original practice, the task was to implement a small Chinese-language graphical game in a firmware environment. The difficulty was not the game logic itself, but the low-level graphics output protocol, framebuffer lifecycle, input event loop, and runtime initialization. If any assumption about state does not hold, the program exits silently.

    2. Methodology Overview: Layered Convergence Instead of Fixing Everything at Once

    Break acceptance into three layers and converge layer by layer. This avoids mixing multiple faults in a single debugging session:

    1. L1 Runnable: The process does not crash and the main loop keeps running.
    2. L2 Displayable: The graphics protocol is acquired correctly, the framebuffer is valid, and the screen can refresh.
    3. L3 Interactive and Optimizable: Input responds correctly, logic is stable, and performance and structure are maintainable.

    Each layer needs a clear pass criterion. Otherwise, debugging degrades into repeated trial and error.

    3. Round 1, Step One: Start with Static Review

    The first instruction when taking over code should not be “fix this for me.” It should be “review this code and list possible problems and risk points.” The value of static review is to make hidden defects explicit and turn them into a checklist that can be verified.

    Review can be sliced by module:

    • Entry and initialization: protocol location, handle acquisition, mode-setting order;
    • Main loop: exit conditions, event pump, exception branches;
    • Game logic: state machine, collision detection, boundary handling;
    • Rendering module: framebuffer address source, resolution, and pixel format;
    • Input handling: key scanning, repeated triggering, focus issues.

    Illustrative review checklist (pseudocode):

    1. review(engine):
    2. check(init_order: [locate_protocol, query_mode, set_mode, re_query_framebuffer])
    3. check(framebuffer_lifetime)
    4. check(loop_exit_condition)
    5. check(input_debounce)
    6. report(severity, file, reason, suggested_fix)

    4. Typical Failure 1: Crash Caused by Invalid Framebuffer Information

    The symptom is representative: the program starts, prints the log that the main loop has begun, and then exits immediately with no graphical output.

    The way to locate it is to add observability: emit serial logs at key points and use the “last successful log” as the breakpoint clue. The logs showed that the exception happened after the graphics protocol call.

    The root cause was invalidated framebuffer information after a mode switch: the information structure obtained when querying the mode was no longer valid after the mode was set, and continuing to use it was effectively accessing a dangling pointer. The fix principle is to re-acquire derived data after a state change, rather than caching data across states.

    1. // Bad example: reuse across states
    2. mode_info = query_mode(gop, mode);
    3. set_mode(gop, mode);
    4. draw(mode_info->framebuffer); // Risk: the information may already be invalid
    5. // Good example: re-acquire after the state change
    6. set_mode(gop, mode);
    7. info = query_current_mode(gop);
    8. draw(info->framebuffer, info->width, info->height);

    Engineering recommendation: document the “validity period of handles/pointers” in comments and interface contracts. Make it explicit who is responsible for acquiring, who is responsible for releasing, and when it becomes invalid.

    5. Typical Failure 2: Missing Display Caused by an Incorrect Protocol Identifier

    The program no longer crashes, but the screen is blank. This kind of problem is usually not a logic error, but a mismatch between identifier constants and the specification, which causes protocol location to fail or returns the wrong instance.

    Recommended troubleshooting order:

    1. Confirm that the source of protocol identifiers is unified and that all references point to the same specification definition; forbid handwritten copies;
    2. Check how the return value of a failed location is handled; failure must be reported explicitly instead of continuing execution;
    3. Use a minimal sample to verify whether “initialize only and clear the screen” succeeds, narrowing the problem scope.
    1. status = locate_protocol(&protocol_guid, NULL, (void**)&gop);
    2. if (status != SUCCESS) {
    3. log("locate gop failed: %d", status); // Surface the problem immediately
    4. return status;
    5. }

    6. Observability Design: Make the Scene Understandable to Both AI and Humans

    The key to human-AI collaborative debugging is sharing the same “facts.” Fix three types of information:

    • Stage logs: initialization, mode setting, first-frame rendering, input events;
    • State snapshots: current mode, resolution, framebuffer address, error codes;
    • Minimal reproduction: strip unrelated modules and keep only the triggering path.

    With these three types of information, the fixes suggested by the model can be verified rather than guessed.

    7. Round 2: Refinement and Optimization

    After the program is runnable and displayable, move on to structural optimization:

    • State machine convergence: model game states explicitly and avoid scattered flags;
    • Resource lifecycle: unify acquisition and release paths and forbid repeated initialization;
    • Input debouncing and throttling: avoid uncontrollable repeated triggering caused by long presses;
    • Rendering optimization: dirty-rectangle refresh, double buffering, and avoiding full-screen redraws;
    • Portability: converge platform-specific calls into an adaptation layer to make it easier to migrate to container platforms or cloud simulation environments for regression.

    8. Collaboration Workflow and Acceptance Checklist

    Recommended collaboration loop: review → reproduce → isolate → minimal fix → regression → refactor. Solve only one layer of problems per round and keep a rollback-capable version.

    Example acceptance checklist:

    • No crashes and a stable main loop;
    • Graphics initialization failure returns a clear error code;
    • Derived data is re-acquired after state changes;
    • Input responds correctly with no repeated triggering;
    • Key paths have logs and state snapshots.

    9. Conclusion

    The benefit of having AI take over legacy code is not “writing it correctly on the first try.” It is turning review, isolation, repair, and regression into a repeatable process. For developers, what truly needs to be accumulated is layered acceptance criteria, observability design, and state lifecycle awareness. Combined with general cloud capabilities such as log services and monitoring alerts for regression and tracing, this kind of debugging can be upgraded from individual experience into a team asset.