Debugging Legacy Code with LLMs: A UEFI Graphics Program Case Study

    This article documents a hands-on debugging session in which a large language model took over a non-running legacy UEFI graphics program. It covers the firmware environment constraints that shape the debugging methodology, three concrete runtime failures and their fixes, a second pass focused on performance and robustness, and four practical rules for handing legacy code to an AI coding tool. Readers will also find acceptance criteria and engineering recommendations for making this workflow reproducible.

    1. Background: When One Model Has to Clean Up After Another

    An informal side-by-side experiment sparked a discussion: different AI coding tools were each asked to build a small graphical game in a firmware environment. One produced compiling, runnable output in about two and a half hours; the other spent nearly six hours still setting up the environment and delivered nothing executable. The most common objection in the comments was that the tasks differed, so the comparison was unfair. That objection is valid, but it also exposes a more interesting problem: legacy code that no longer runs is one of the most common situations in real engineering work.

    The code that was left behind was not worthless. It had seven files, clear separation of responsibilities, and well-defined module boundaries. Throwing it away would be a waste, and rewriting it would discard a usable structure. The more production-realistic option was to hand the mess to another model and have it diagnose and repair the code on top of the existing architecture. The hard part of this kind of work is not generation but localization: the code compiles, yet fails at runtime in very subtle ways.

    2. Environment Constraints Drive the Debugging Methodology

    A firmware graphics program runs under a few hard constraints that directly shape how you investigate failures:

    • No operating system as a safety net. There is no process isolation and no exception handler; a single invalid memory access means an immediate reboot or a silent exit.
    • Very tight resources during startup. Memory, stack, and temporary buffers are all constrained, and any redundant copy can trigger a failure.
    • Limited feedback channels. Typically you have only serial logs and screen output; without a graphical debugger, logs are your only camera.
    • Strong coupling between protocol states. The graphics output protocol, simple text output protocol, and file protocol have ordering dependencies, and a resource acquired in one step may already be invalid in the next.

    So the first step in taking over legacy code is not to change code but to establish observability: raise the serial log level, insert timestamped checkpoints in critical branches, and determine exactly which line the program reaches before it disappears.

    3. Round One: From Not Running to Running

    3.1 Review First, Type Later

    The first instruction should be extremely restrained: perform code review only, list suspicious points, and make no changes. Review module by module: entry point, main loop, game logic, rendering, input handling. A solid checklist looks roughly like this:

    Module Suspicious point Risk level
    Entry No rollback when protocol lookup fails High
    Rendering Mode info pointer reused across calls High
    Input Missing periodic reads, events pile up Medium
    Main loop No timeout exit condition Medium
    Logic Off-by-one in collision boundary check Low

    The value of this table is that it turns “mysterious crashes” into a list of verifiable hypotheses, each of which can be checked off as it is fixed.

    3.2 Failure One: Immediate Exit on Startup

    The log printed the main-loop startup message and then ended right away. After adding checkpoints, the failure was localized to just after the graphics output protocol call. The root cause was a classic use-after-invalidation: the mode information structure returned by the query is owned internally by the protocol, and after the mode is set, that memory is no longer valid. Reading it afterward is a wild pointer access.

    The repair principle is a single sentence: never reuse a pointer across a state change; re-query after the state switches.

    1. // Wrong: info is invalid after SetMode
    2. gop->QueryMode(gop, mode, &size, &info);
    3. gop->SetMode(gop, mode);
    4. frame = info->FrameBufferBase; // dangerous
    5. // Right: re-query after the state change
    6. gop->SetMode(gop, mode);
    7. gop->QueryMode(gop, mode, &size, &info);
    8. frame = info->FrameBufferBase;

    3.3 Failure Two: It Runs, but the Screen Is Black

    The program no longer exited, but the screen stayed blank. The cause was a wrong protocol identifier configuration: the firmware specification defines several similar identifiers for graphics-related protocols, and picking the wrong one means the graphics output protocol cannot be located correctly. The signature of this class of problem is “all the logic is right, nothing is on screen.” When investigating, verify identifiers and the protocol installation path first, rather than suspecting the rendering algorithm.

    3.4 Failure Three: Input Does Nothing

    Once the画面 appeared, key presses had no effect. A common cause is reading the input device only once during initialization, with no periodic polling in the main loop; once the event queue fills up, new events are dropped. The fix is to put input reading on a fixed cadence and to clear pending events before each frame begins.

    4. Round Two: Refinement and Optimization

    Running is only the starting point. The goal of the second round is to make the program deliverable:

    1. Stable frame rate. Decouple rendering from logic: advance logic in fixed steps and let rendering follow the display refresh, so that logic speed is not tied to frame rate and the feel does not drift.
    2. Resource discipline. Pre-allocate buffers and avoid repeated allocate/free cycles inside loops; this matters most during startup.
    3. Complete fault tolerance. Check the return value of every protocol call, print a readable error on failure, and exit safely instead of crashing silently.
    4. Portability. Consolidate platform-specific calls into a separate adaptation layer so the logic layer is unaware of concrete firmware interfaces, making it easier to move to different hardware.
    5. Keep observability. Retain toggleable log macros, disabled in production and enabled when troubleshooting.

    5. Methodology: Four Rules for Handing Code to a Model

    • Review before modifying. Have the model produce a list of problems and verification methods; a human confirms the priorities.
    • Verify in small steps. Change one hypothesis at a time and run immediately, so that changing multiple variables at once does not make attribution impossible.
    • Enforce observability. Debugging firmware without logs is flying blind; treat checkpoints as part of the fix.
    • Define acceptance up front. Compiles, starts, renders correctly, input works, and runs for ten minutes without rebooting: all five must pass before the work is done.

    6. Capability Boundaries and Engineering Recommendations

    To be objective, the difference in model performance between “generating from scratch” and “taking over and debugging” depends more on whether the task constraints are clear and the feedback is sufficient than on the sheer volume of code. For enterprises that want to put this capability into production, three things are worth setting up: first, use a container platform to pin down a reproducible build environment and eliminate environment differences that create false failures; second, use a logging service with monitoring and alerting to collect runtime checkpoints into a traceable chain; third, turn the review checklist and acceptance criteria into templates, with version archiving backed by object storage.

    In related work at Baidu AI Cloud, embedding AI coding tools into this kind of engineering pipeline usually produces more stable results than relying on model capability alone. Letting the model generate hypotheses and apply bulk changes, while people define constraints and perform final acceptance, is currently the more cost-effective division of labor.