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

    This article presents a practical, tool-agnostic workflow for using large language models (LLMs) to take over legacy code and get it running in a real environment. Drawing on a firmware graphics project built on the UEFI environment, where graphics are provided through the Graphics Output Protocol and debugging is done over serial output, it shows why maintenance is harder than generation. The process starts with a static review that produces a verifiable issue checklist, then fixes two representative failures: a stale pointer after a mode switch and a mismatched protocol identifier. A second pass covers frame rate, input latency, resource management, failure diagnosability, and testability. The article closes with four hard rules for human-AI collaboration: evidence first, small validated steps, explicit interface contracts, and a standardized definition of done.

    1. Why Taking Over Existing Code Is Harder Than Generating It

    The barrier to having an LLM write code is dropping fast, but the real cost is not in generation—it is in maintenance. A project produced by automated tooling often looks well structured: clean directory layering, reasonable module boundaries, and acceptable naming. Once it runs in a real environment, however, the problems surface all at once—incomplete environment dependencies, wrong platform API call ordering, missing error handling, and chaotic resource lifecycle management.

    This article follows one practical case: taking over a legacy project and making it actually run. It abstracts a collaboration method that is independent of any specific tool. The original scenario is a firmware-level graphics program: the target platform is a UEFI environment, graphics capabilities are exposed through the Graphics Output Protocol, and debug output goes over a serial port. This kind of environment demands far more from AI collaboration than ordinary business code, because there is no exception stack trace to rely on. Failures typically show up as an immediate reboot or a blank screen.

    2. Round One: From “Not Running” to “Running”

    2.1 Start With a Static Review and Build a Verifiable Issue List

    The first step in taking over an unfamiliar project is not to modify code, but to review it. An effective prompt should ask the model to walk through the project module by module: entry point, main loop, business logic, rendering layer, input handling, and resource allocation and release paths. The output of the review must be a checklist that can be verified item by item, not a vague statement that “the code quality is poor.”

    A solid checklist usually contains four categories:

    • Incorrect platform API usage: wrong handle acquisition, wrong protocol identifiers, unmet preconditions;
    • Lifecycle defects: pointers invalidated before use, overwritten buffers, handles never closed;
    • Missing robustness: unchecked return values, unhandled boundary conditions, no fallback on failure paths;
    • Insufficient observability: missing logs and stage markers, so the fault domain cannot be narrowed down.

    The key principle is that every item on the list must be confirmed or disproved by a single run. That is how you turn “the AI’s guess” into “engineering evidence.”

    2.2 Failure One: A Pointer Invalidated by Call Ordering

    The first run was highly representative: the program started, printed the marker for the beginning of the main loop, and then exited immediately. No crash dump, no error code—just a silent death.

    On a platform without stack traces, the way forward is to add observability: insert serial prints at key stages, split the execution path into segments, and determine which segment the failure occurs in. The logs showed the anomaly appeared right after the graphics protocol initialization call.

    The root cause was a classic lifecycle problem: the pointer obtained when querying mode information pointed to memory owned internally by the protocol. After switching modes, that memory region was no longer guaranteed to be valid, and continuing to use it became a wild pointer access. The fix is equally general—do not reuse an old “view” after a state change; instead, re-fetch the currently valid buffer information once the state is settled.

    1. /* Bad: reusing the old pointer after a mode switch */
    2. info = query_mode_info(gop, mode);
    3. set_mode(gop, mode);
    4. draw_pixel(info->frame_buffer, ...); /* info may already be invalid */
    5. /* Good: re-fetch after the state change */
    6. set_mode(gop, mode);
    7. info = query_mode_info(gop, mode); /* get the current valid view */
    8. if (info == NULL || info->frame_buffer == NULL) {
    9. log("frame buffer unavailable");
    10. return NOT_READY;
    11. }

    This pattern generalizes into a rule: any chain of “query first, change state, then use” must re-validate the handle and pointer.

    2.3 Failure Two: Wrong Protocol Identifier

    The program no longer exited, but the screen produced no output. This kind of “runs fine, result missing” problem usually points to a capability negotiation failure: the requested protocol identifier did not match the one actually available on the platform, so handle acquisition failed—and the failure branch was silently ignored.

    There are two fixes. First, use a protocol identifier that matches the runtime environment. Second, handle acquisition failure explicitly and log it, so the problem is not swallowed.

    1. status = locate_protocol(&expected_guid, NULL, (void **)&gop);
    2. if (status != SUCCESS || gop == NULL) {
    3. log("gop locate failed, status=%r", status);
    4. return status; /* failures must be visible */
    5. }

    3. Round Two: Refinement and Optimization

    Getting it to run is only the starting point. Reasonable goals for the second round include:

    1. Frame rate and input latency: decouple rendering from the main loop, update logic with a fixed time step, and avoid tying logic speed to refresh rate;
    2. Resource management: release every allocation in pairs, reclaim on exception paths too, and avoid handle exhaustion after long runtimes;
    3. Diagnosable failures: define clear log levels and error codes for each stage, forming a searchable fault dictionary;
    4. Testability: separate pure logic (collision, line clearing, scoring) from platform-dependent code, so core logic can be unit tested in an ordinary environment.

    A sketch of the main loop structure:

    1. while (running) {
    2. poll_input(&input);
    3. if (tick_due(&accumulator, FRAME_MS)) {
    4. update(&state);
    5. accumulator -= FRAME_MS;
    6. }
    7. render(&state);
    8. }

    4. Methodology: Four Hard Rules for Human-AI Collaboration

    • Evidence first: every conclusion must be backed by logs, return values, or a minimal reproduction;
    • Small validated steps: fix one class of problem at a time and run immediately after each change, avoiding multiple variables changing at once;
    • Contract-based interfaces: before calling a platform API, make its preconditions, invalidation conditions, and error returns explicit;
    • Standardized acceptance: define done as “boots, is interactive, runs stably for a long time, and failures are visible.”

    5. Conclusion

    The value of having an LLM take over legacy code is not writing a perfect implementation in one shot. It is turning scattered failure symptoms into a structured issue list and closing each item in a verifiable way. For a team, what is worth preserving is the review template, the logging conventions, and the acceptance checklist. Once these are in place, collaboration efficiency improves steadily regardless of which AI coding tool or general cloud capability (such as log services, monitoring and alerting, or container platforms) you use.