Debugging Legacy Code with Large Language Models: A Practical Workflow

    This article walks through a practical method for using large language models to debug legacy code, based on a real repair effort on a firmware graphics program. It explains why taking over broken code is harder than generating from scratch, then breaks the work into two rounds: first static review, targeted logging, resource lifecycle checks, and small regression steps to get the code running; then structural cleanup, resource safety, observability, determinism, fallback paths, and regression checklists for maintainability. Readers will find reusable review checklists, code examples for stale pointer and protocol identifier mistakes, a main loop skeleton, and four core principles for AI-assisted debugging.

    1. Why Taking Over Broken Code Is Harder Than Generating From Scratch

    In real development work, the most common scenario for LLM-assisted programming is not writing a complete project from scratch. It is taking over code left behind by someone else, or by another model, that does not run. This kind of task is significantly harder, for three reasons.

    First, context is missing. The original designer’s intent, boundary conditions, and implicit assumptions were never written down, so the model has to infer them from the code alone.

    Second, failures are compound. When generating from scratch, problems usually concentrate on whether the program runs at all. Legacy code already has a complete structure, so the problems hide in the interactions between modules and surface as vague symptoms such as crashes, blank screens, or no response.

    Third, feedback signals are weak. In bare-metal or firmware environments especially, there is no mature debugger or logging system, and a crash often leaves behind a single line of output, making localization extremely costly.

    The core methodology for taking over legacy code should therefore be: build a global understanding through static review first, narrow the problem scope layer by layer using the run feedback from a minimal reproducible case, and only then move into optimization. The rest of this article uses the repair of a graphics program in a firmware environment as an example.

    2. Round 1: From “Does Not Run” to “Runs”

    2.1 Always Start With Static Review, Not With Running the Code

    After copying the legacy code unchanged into a clean new environment, the first instruction should ask the model to read through it and produce a problem list, not to compile and run it immediately. The reason is that running directly only yields a general failure symptom, while static review builds a module-level map.

    A qualified review checklist should cover these dimensions:

    • Entry point and lifecycle: whether the entry function is complete, and whether uninitialized global state exists;
    • Main loop structure: loop conditions, exit paths, and possible infinite blocking;
    • Coupling between business logic and rendering: whether logic updates and screen refreshes are incorrectly tied together;
    • Input handling: whether key states are debounced, and whether out-of-bounds indexing exists;
    • Resource acquisition order: whether buffers, modes, and handles are acquired and released in pairs.

    A sample review output structure could look like this:

    1. [Critical] Old frame buffer info pointer used after mode switch
    2. [Critical] Inconsistent references to graphics output protocol identifier constants
    3. [Medium] Main loop has no timeout exit condition
    4. [Minor] Key scanning is not debounced, repeated triggering possible

    The key lesson is to have the model produce a “list of verifiable hypotheses” first, where each hypothesis maps to an observable symptom. Every later run then verifies or refutes one of those hypotheses, which is far more efficient than blind trial and error.

    2.2 Failure One: Exits Immediately After Start, a Wild Pointer Problem

    The program compiles and starts, prints the log that the main loop has begun, and then exits immediately. This kind of “dies right after launch” symptom almost always points to a stale resource obtained during initialization.

    The localization path should be to add denser logging before and after key calls, treating serial output as the only available “breakpoint.” Once the anomaly is found to occur after mode-setting related calls, the display information structure obtained earlier should be checked for validity.

    The typical error pattern is: query the current display mode and save the returned info pointer, then switch modes, then use the old pointer to access fields such as resolution and frame buffer address. A mode switch reallocates or remaps memory, so the old pointer immediately becomes a wild pointer, and reading it triggers an exception.

    The repair principle is “whoever changes a resource must re-acquire it afterward”:

    1. // Bad: reuse old info after switching modes
    2. info = query_mode(handle, mode);
    3. set_mode(handle, mode);
    4. draw_pixel(info->frame_buffer, ...); // info is now invalid
    5. // Good: re-query after switching
    6. set_mode(handle, mode);
    7. info = query_mode(handle, mode);
    8. if (info == NULL) { return STATUS_INVALID_PARAMETER; }
    9. draw_pixel(info->frame_buffer, ...);

    Null pointer checks and status code checks should also be added, so that a “resource invalidated” problem does not turn into a silent error.

    2.3 Failure Two: Runs But the Screen Is Blank, a Protocol Identifier Configuration Error

    The second typical problem is that the program no longer crashes but never obtains a usable graphics output interface. Firmware specifications usually define multiple identifier constants for a group of related capabilities, each with different semantics: some correspond to an interface that is “currently installed,” others to one that is “installable/recommended to install.” Mixing them up causes a query to return “not found,” or returns an object that was not properly initialized.

    Key troubleshooting points:

    • Clarify the semantics of the required capability: an “existing instance” or one that “needs to be installed”;
    • Check whether the definitions of the globally unique identifiers come from a single source, avoiding separate declarations in multiple places;
    • Print the specific status code when a query fails, instead of a general error;
    • Verify interface availability with a minimal standalone sample, then integrate it back into the main program.

    The value of this kind of problem is the reminder that a constant reference the model produces may look reasonable but still be wrong, and must be cross-checked against the specification definition.

    2.4 Round 1 Summary: The General Pattern

    The goal of the first round is singular: runnable. The effective process can be fixed into four steps: produce hypotheses through static review, trade denser logging for observability, trace resource lifecycles in “initialization order,” and run a regression check immediately after each fix.

    3. Round 2: Refinement and Engineering

    Getting the code running is only the starting point. The second round of refinement should focus on maintainability and robustness, and can proceed in this order:

    1. Structural cleanup: split the three main lines of “logic update,” “rendering,” and “input,” so the main loop only handles scheduling and frame rate is not coupled to logic speed.
    2. Resource safety: acquire and release all handles and buffers in pairs, reclaim them on exception paths too, and introduce a unified status code check macro.
    3. Observability: grade the logs and keep a switchable debug channel, avoiding unconditional prints piled up just for troubleshooting.
    4. Determinism: fix the seed for random logic so defects are reproducible, and add debouncing and edge detection for key input.
    5. Boundaries and fallback: provide a clear fallback path when a resolution or mode is unsupported, instead of failing outright.
    6. Regression verification: build a minimal verification checklist and run the four paths of startup, rendering, input, and exit after every change.

    A sample main loop skeleton:

    1. while (running) {
    2. process_input(&input); // edge detection + debouncing
    3. update(&state, dt); // logic decoupled from frame rate
    4. if (state.game_over) break;
    5. render(&state); // confirm frame buffer is valid before rendering
    6. }

    4. Methodology: Four Principles for LLM-Assisted Debugging

    • Review before running: use static analysis to build global hypotheses, avoiding being led by a single symptom.
    • Turn the unobservable into the observable: logs and status codes are the most effective “breakpoints” in bare-metal environments.
    • Troubleshoot by lifecycle: initialization order, resource acquisition order, and release order are the high-incidence areas for firmware-class defects.
    • Small-step regression: change only one class of problem at a time and verify immediately, preventing multiple overlapping problems from making attribution difficult.

    As for horizontal comparisons between different models, they are actually of limited value. The more useful conclusion is that in real engineering, model capability must be measured within a system of “observability, context supply, and a verification loop.” For enterprise adoption, container platforms can unify build environments, while logging services and monitoring alerts accumulate runtime data, turning one-off troubleshooting experience into reusable team assets. Baidu AI Cloud provides general product category support for standardizing this kind of development process, helping teams bring AI-assisted debugging into a controllable, auditable engineering pipeline.