Debugging Legacy Code with LLMs: A Practical Two-Round Workflow

    This article presents a practical workflow for using a large language model (LLM) to debug legacy code generated by automated tools that has never run successfully. Instead of asking the model to fix everything at once, the process splits the work into two rounds: first achieving a minimal runnable state, then refining for maintainability. It covers starting with a static review checklist, diagnosing a real failure where the program exits immediately after startup, and identifying the root cause as a framebuffer pointer invalidated across calls. It also includes a reusable collaboration checklist and a general rule for query-change-reuse call sequences. The method is platform-independent and focuses on engineering discipline rather than any specific tool.

    1. Where the Problem Comes From: A Handover, Not a Benchmark

    Many teams have faced a similar scenario: a project left behind by an AI coding tool contains seven source files. The modular structure looks reasonable and the directory layout is tidy, but the moment the environment changes, nothing runs. Typical legacy artifacts like this are “all form, no substance”: interface calls happen in the wrong order, resource lifecycles are unmanaged, and error branches are simply missing.

    This article does not compare specific tools. Instead, it frames the situation as a broader engineering problem: when you take over code that was generated by an automated tool and has never actually run successfully, how do you use an LLM to bring it back to a runnable state? The approach in the original material splits the task into two rounds: the first aims for “it runs,” and the second aims for “polish.” This rhythm is worth keeping because it compresses the unknown into the smallest possible scope and avoids introducing too many variables at once, which would make root-cause analysis impossible.

    2. Round 1: Start with Static Review and Build a Problem List

    The first instruction after taking over should not be “fix this for me,” but “review this code and list the problems that could cause failures.” The reason is that generative models, when unconstrained, tend to rewrite directly, and a rewrite throws away the only thing of value in the original project: its intended module structure.

    A solid review checklist usually covers the following dimensions:

    • Entry point and initialization order: failures in firmware-style programs are usually not logic errors but wrong initialization sequences.
    • Main loop structure: whether an exit condition is triggered prematurely, or whether the loop body is missing necessary blocking or yielding.
    • Graphics protocol call chain: the ordering among mode query, mode set, and framebuffer acquisition.
    • Input handling: whether key scanning is debounced and whether events are consumed.
    • Resource lifecycle: whether allocation, use, and release are paired, and whether pointers remain valid during use.

    Having the model output a checklist rather than a patch has a hidden benefit: a checklist can be rejected item by item by a human. In practice, the model’s “it will run after this fix” is often overly optimistic, and the real pass rate is usually around half. The checklist must therefore be treated as a set of hypotheses, not conclusions.

    3. The First Real Failure: It Starts, Then Exits Immediately

    After the changes, the program does enter a running state. It prints a log showing the main loop has started, and then the process ends. This “print and exit” behavior is very common in bare-metal and firmware environments. A recommended troubleshooting order is:

    1. Determine whether the exit is active or passive: is it a normal return because the loop condition was met, or an abnormal interruption of control flow?
    2. Add logs, not guesses: print return values, error codes, and buffer addresses of key calls to the serial port, narrowing the scope section by section.
    3. Bisect the problem: insert markers in the middle of the call chain to determine whether the exception occurs before or after the protocol call.

    Following this order quickly narrows the failure point to just after a mode query in the graphics protocol.

    4. Root Cause: A Framebuffer Pointer Invalidated Across Calls

    The typical root cause is a lifecycle mismatch: first query the current mode and obtain a pointer to a struct describing the framebuffer address and dimensions; then call the set-mode interface to switch resolution; after the switch completes, the previously obtained descriptive memory is invalid, and dereferencing it is a wild pointer access.

    A schematic of the wrong approach and the fix is shown below (expressing only the ordering, not a specific API):

    1. // Wrong: info is invalid after SetMode
    2. info = QueryMode(mode);
    3. SetMode(mode);
    4. framebuffer = info->buffer; // wild pointer
    5. // Correct: re-acquire after the switch
    6. SetMode(mode);
    7. info = QueryMode(mode); // query again
    8. framebuffer = info->buffer;

    A general rule can be drawn from this: for any three-stage “query-change-reuse” call sequence, the query result must be re-acquired after the change. This pattern applies to graphics, networking, files, and device handles. When asking the model to fix the code, also explicitly require it to add null checks and error-code checks; otherwise, you only move the crash point further down the line.

    5. Round 2: Four Things to Do in the Refinement Phase

    Once the code reaches a runnable state, the goal of the second round shifts from “does not crash” to “maintainable”:

    • Complete error handling: every return value needs a branch, with a locatable error code on failure.
    • Unify resource management: converge allocation and release into paired functions to avoid leaks from mid-way returns.
    • Decouple input and rendering: drive logic with a fixed time step, and let rendering only read state, avoiding logic speed being tied to the refresh rate.
    • Observability: keep a leveled logging switch and make serial output trimmable for on-site diagnosis.

    6. A Reusable Collaboration Workflow and Checklist

    Turning the above practices into a process can significantly reduce handover costs:

    1. Get the environment running before discussing features; pin and document dependency and toolchain versions.
    2. In the first round, allow only “minimal runnable changes”; forbid opportunistic refactoring.
    3. At the end of each round, commit a reproducible build artifact and logs.
    4. Close the loop on the review checklist item by item; mark unverified items as pending confirmation.
    5. For code involving pointers, handles, and buffers, enforce a “re-acquire after change” check.

    On the compute and toolchain side, this kind of long-chain debugging usually relies on a container platform to ensure environment consistency, plus logging services and monitoring alerts to capture serial output. The general capabilities of Baidu AI Cloud can serve as one hosting option, but the method itself is platform-independent.

    7. Conclusion

    The value of an LLM taking over legacy code is not writing a perfect implementation in one shot, but compressing the chain of “read code, list hypotheses, add logs, bisect, fix, regress” down to hours. What truly determines success is still engineering discipline: two-round progression, checklist closure, and lifecycle rules. Master this method, and legacy projects from any source can be reliably brought back to a controllable state.