Debugging Legacy Code with Large Language Models: A Practical Workflow

    This article walks through a practical workflow for using AI coding tools to debug and refine legacy low-level and firmware code. It covers static review before any edits, aligning static suspicion with runtime behavior through logging, fixing crashes caused by stale handles after state changes and blank screens caused by wrong protocol identifiers, then moving into hardening work such as input throttling, fixed-timestep timing, resource cleanup, bounds checks, and tiered logging. It closes with a reusable debugging loop and common pitfalls to avoid.

    1. Where the Problem Starts: Why Legacy Code Is Hard to Take Over

    In real engineering environments, the hardest task is often not writing a program from scratch, but taking over code someone else left behind that no longer runs. This kind of code usually has a few traits: the module breakdown looks reasonable and the naming is passable, but there are no executable verification records; the original author is gone, and the comments no longer reflect the real intent; and the runtime environment differs from the original development environment, so the “it runs on my machine” assumption breaks down completely.

    A typical scenario went like this: an AI coding tool first tried to build a simple low-level graphics game and spent hours without getting the build and runtime environment working, ultimately producing nothing runnable. It did leave behind seven source files, split into modules with separate entry point, main loop, game logic, rendering, and input handling — not a messy structure. Throwing it away would clearly be a waste, so a different AI coding tool with different strengths was brought in to clean up the mess and repair and optimize the same class of graphics program. The value of this process is not in ranking the two tools against each other, but in distilling a general-purpose troubleshooting path.

    It is worth stressing that with different tasks and different environments, a direct comparison is not fair; what is worth reusing is the method, not the conclusion.

    2. Round One: From “Doesn’t Run” to “Runs”

    2.1 Do a Static Review First, Don’t Rush to Change Code

    The first instruction when taking over legacy code should be: review this code and list the problems that might exist. Have the model read through each module one by one — entry function, main loop, game logic, rendering module, input handling — and produce a list of issues sorted by risk.

    The point of this step is to build a mental model. Before making any changes, a person (or a model) must first understand roughly how the code is organized and where things are most likely to go wrong. Common review findings include:

    • Resource acquisition and release that don’t match;
    • Pointers used without validation, or invalidated after a state transition;
    • Wrong choice of protocol/interface identifier constants;
    • Error codes ignored, with execution continuing after a failure;
    • Writing directly into an empty render buffer.

    Once the list is out, don’t trust it blindly — run the program once first, and align “static suspicion” with “actual observed behavior.”

    2.2 Symptom One: Exits Immediately on Startup

    On the first run, the program printed the log line for entering the main loop and then exited immediately. For this kind of “crash on startup” problem, the most effective approach is to add observability: send logs for the key steps over the serial port, annotating the return value of each step.

    The logs pinpointed the crash to just after the graphics output protocol call. Further analysis showed that the pointer obtained when querying mode information became invalid after the mode was set — switching modes rebuilds internal data structures, so the previously retrieved buffer information is no longer valid. The fix is straightforward: query the frame buffer information again after the mode is set, instead of reusing the old pointer.

    Illustrative code:

    1. // Wrong: reuse the info from before the mode switch
    2. ModeInfo = GetModeInfo(Mode);
    3. SetMode(Mode);
    4. WritePixel(ModeInfo->FrameBuffer, x, y, color); // wild pointer
    5. // Correct: re-query after the mode switch
    6. SetMode(Mode);
    7. ModeInfo = GetModeInfo(CurrentMode);
    8. if (ModeInfo == NULL || ModeInfo->FrameBuffer == NULL) {
    9. return STATUS_INVALID_PARAMETER;
    10. }
    11. WritePixel(ModeInfo->FrameBuffer, x, y, color);

    The general form of this lesson: any code that “first obtains a handle/description, then changes global state” should make you suspect the lifetime of that handle.

    2.3 Symptom Two: Runs but No Picture

    The program no longer exits, but nothing appears on screen. This kind of problem is usually in the “find the interface” step: in a firmware environment there are multiple identifier constants related to graphics output, and picking the wrong one means the graphics output protocol instance can’t be located correctly, so every call fails or returns null.

    The fix is to unify the source of the identifier and avoid hand-written constants: reference the constant defined in the public header file directly, and strictly check the return value of every step during initialization — on failure, print the error code and exit rather than continuing.

    1. Status = LocateProtocol(&GraphicsOutputId, NULL, &Gop);
    2. if (Status != SUCCESS) {
    3. LogError("locate gop failed: %d", Status);
    4. return Status;
    5. }

    2.4 Round One Summary

    Round one has a single goal: make it run. The method is a small-step loop of “review — run — add logs — minimal fix — run again,” changing only one thing per round so every change in behavior can be attributed.

    3. Round Two: Refinement and Optimization

    Once it runs, move into the refinement phase, shifting the focus from correctness to robustness and maintainability:

    1. Input handling: key bounce and repeated triggering need throttling, so a single press isn’t recognized as multiple consecutive presses.
    2. Timing control: drive the main loop with a fixed cadence so rendering speed doesn’t depend on machine performance.
    3. Resource management: define clear initialization and de-initialization paths, releasing acquired resources on exit.
    4. Bounds validation: range-check all external inputs (coordinates, mode numbers) before use.
    5. Tiered observability: separate debug logs from error logs so redundant output can be turned off in release builds.

    This phase is where AI coding tools show the most value: they can produce multiple candidate implementations in a short time for the developer to choose from, rather than starting from a blank page.

    4. Distilled Methodology: A Reusable Troubleshooting Loop

    Abstracting the process above yields a loop that applies to low-level and firmware development:

    • Static review: build a module map and a risk list first;
    • Baseline run: record the first observed symptom and the failure location;
    • Observability first: add logs before changing logic;
    • Minimal fix: change one variable at a time to keep results attributable;
    • Regression verification: re-run the full path after each fix;
    • Refinement and consolidation: write validation, logging, and resource management into the standards.

    5. Common Pitfalls

    • Rewriting from the start: the module breakdown of legacy code is often reusable, and rewriting costs more.
    • Ignoring return values: low-level interfaces don’t throw exceptions, they only return error codes.
    • Reusing old handles after a state transition: this is a frequent cause of crash-on-startup.
    • Guessing conclusions from symptoms: inference without log support tends to drift further in the wrong direction.

    6. Closing Thoughts

    “Having AI clean up after AI” sounds like a joke, but it reveals a serious engineering fact: the biggest payoff of AI coding tools is not generating perfect code in one shot, but compressing the review, locate, fix, and verify loop down to a very short cycle. For developers, what really needs to be mastered is the loop itself — tools will keep evolving, while the method transfers to any tech stack. Combined with general-purpose cloud container platforms, logging services, and monitoring and alerting capabilities, this loop can also be consolidated into reusable engineering standards for a team.