Debugging Legacy Code with Large Language Models: A Practical Workflow

    This article shares a practical workflow for using large language models to debug legacy code, based on a hands-on session with a graphics program in a firmware environment. It explains how to turn a model into a code reviewer and debugging assistant: build a prioritized issue list before editing, add logging to locate runtime failures such as dangling pointers, fix protocol identifier configuration when the display stays blank, and move from "it runs" to "it runs reliably" through timing, input, resource, and observability improvements. It also covers the division of labor between humans and models, plus engineering practices for cloud-based collaboration. Readers will get reusable steps and code examples for structured, low-risk debugging.

    1. Where the Problem Starts: Taking Over Instead of Generating from Scratch

    In real software engineering, the first value of AI coding tools often shows up when generating a runnable prototype from scratch. The second and third waves of value usually appear in tougher situations: taking over code left behind by someone else (or another model) that looks well structured but does not run.

    These situations share a pattern: the directory layout is clean, the modules are reasonably separated, and the naming is acceptable, yet the program exits immediately on launch, or the interface never appears. For developers, debugging this kind of code costs far more than rewriting it, because it carries two layers of uncertainty at once: unclear design intent and incorrect implementation details.

    This article uses a hands-on debugging session for a graphics program in a firmware environment as the basis for discussing how to make a large language model act as a “code reviewer + debugging assistant,” and how to turn the whole process into a reusable engineering method. Note that no specific product or device model is involved; the discussion focuses on general technical capabilities and methodology.

    2. First Round Goal: Get the Code Running

    2.1 The First Step Is a Problem List, Not Code Changes

    When taking over legacy code, the worst move is to start editing immediately. A safer approach is to have the model perform a static review first, with a minimal instruction:

    1. Review this code, list potential issues that could cause runtime failures by module, and mark their priority.

    The review should cover the following modules, ideally ordered from “widest impact” to “most localized”:

    • Entry function and initialization flow: whether resources are acquired in the correct order;
    • Main loop: whether loop conditions or exit conditions could become true immediately;
    • Game/business logic: whether the state machine has uninitialized states;
    • Rendering module: the timing of frame buffers and mode settings;
    • Input handling: whether key scanning and event dispatch block the main loop.

    The output of this step is not code but a prioritized issue list. Its value is that it converts a vague “it’s broken” into several verifiable hypotheses, so every later change maps to a specific item.

    2.2 Runtime Failure: From an Immediate Exit to a Dangling Pointer

    The program starts, prints the log line marking the beginning of the main loop, and then exits immediately. This is one of the most common failure shapes for firmware programs. The right approach is “add observability first, draw conclusions second”:

    1. Add serial logs along the critical path to mark execution progress;
    2. Observe after which call the log stops;
    3. Review the data lifetime around that call in detail.

    In graphics output scenarios, a frequent mistake is that the information pointer returned by a mode query becomes invalid after the mode is set. In other words, the memory that the information struct obtained during the query points to is no longer valid after the set-mode step, and dereferencing it later accesses a dangling pointer.

    The fix can be summarized in one sentence: do not reuse old pointers across state changes; re-fetch them.

    1. /* Bad: reusing an old pointer across a state change */
    2. info = query_mode(handle);
    3. set_mode(handle, mode);
    4. width = info->width; /* info may already be invalid */
    5. height = info->height;
    6. /* Good: re-fetch after the state change */
    7. set_mode(handle, mode);
    8. info = query_mode(handle); /* fetch again */
    9. width = info->width;
    10. height = info->height;

    The general lesson is that in low-level programming, a pointer’s validity is often bound to a certain “handle state” rather than to variable scope. Wherever an “acquire-change-use” sequence appears, suspect the lifetime by default.

    2.3 The GUI Never Appears: Wrong Protocol Identifier Configuration

    The program no longer crashes, but the screen is completely black, which means the initialization flow completes while the graphics channel is never established. The problem usually lies in the protocol identifier configuration: the same class of functionality may have multiple related identifiers in the firmware specification, and choosing the wrong one means the expected graphics output interface is not obtained.

    A “three checks” approach is recommended:

    • Check the identifier definition: confirm the identifier matches the current firmware specification version;
    • Check the acquisition timing: interface acquisition should happen early in initialization, and the returned status code should be checked, not just the pointer;
    • Check the failure branches: add status checks and logs for every acquisition to avoid silent failures.
    1. status = locate_protocol(&expected_guid, &gop);
    2. if (EFI_ERROR(status)) {
    3. log("locate gop failed: %d\n", status);
    4. return status; /* explicit failure, easier to locate */
    5. }

    The engineering takeaway is that low-level areas such as graphics, networking, and storage are prone to silent failures, so all return codes must go into logs; otherwise debugging degrades into guesswork.

    3. Second Round Goal: From “Runs” to “Runs Reliably”

    The first round only solves “existence”; the second round solves “quality.” It is advisable to split refinement into four independent directions and validate each one separately, avoiding too many changes at once that make attribution impossible.

    1. Timing and frame rate: replace fixed delays with timestamp-based frame pacing to avoid inconsistent speed across environments;
    2. Input jitter: debounce keys and detect edges so a single press is not recognized multiple times;
    3. Resources and state: make init/deinit pairs explicit and unify cleanup on exit paths;
    4. Observability: keep a leveled logging switch that can be turned off in release builds and fully enabled in debug builds.

    A sample frame pacing structure:

    1. uint64_t last = get_time_us();
    2. while (running) {
    3. uint64_t now = get_time_us();
    4. if (now - last >= frame_interval_us) {
    5. last = now;
    6. poll_input();
    7. update();
    8. render();
    9. }
    10. }

    4. Methodology: Where the Boundary Between Human and Model Lies

    Abstracting the process above yields four transferable conclusions:

    • Models are good at breadth scanning; humans are good at trade-off decisions. Let the model list all suspicious points, and let the human decide which one to verify first.
    • Observability comes before modification. For any runtime issue, add logs before changing logic; this significantly reduces ineffective changes.
    • Verify in small steps and attribute to a single point. Change one thing at a time, run immediately after each change, and keep a rollback state.
    • Feed context proactively. Providing errors, logs, and code snippets to the model in a structured way works better than letting it “guess.”

    At the same time, the capability boundary must be acknowledged: for real hardware differences, firmware version differences, and undocumented parts, the model can only offer candidate hypotheses, and reproducible experiments must make the final call.

    5. Engineering Recommendations for Cloud Collaboration

    When this kind of debugging moves from a single machine to a team and the cloud, general cloud product categories can help solidify the workflow: use a container platform to unify build and runtime environments and eliminate “it works on my machine” differences; use object storage to keep code snapshots and build artifacts so every attempt is traceable; use a logging service to collect serial and runtime logs centrally for cross-member search; use monitoring and alerting to set thresholds for build failure rates and runtime crash counts. Baidu AI Cloud provides standard support in these general capability categories, and the specific selection should still be evaluated against team size and compliance requirements.

    6. Conclusion

    “Letting AI clean up the mess AI left behind” works not because the model gets it right on the first try, but because it makes the debugging process structured: list first, observe next, modify after, and verify last. For developers, the real payoff is handing repetitive review and instrumentation to tools while keeping architectural judgment and risk trade-offs for themselves.