Debugging Legacy UEFI Graphics Code with AI: A Two-Round Practical Method

    Using AI to debug legacy code tests its engineering ability, not just its generation ability. This article documents a hands-on experiment applying AI to a legacy UEFI firmware graphics project that won't build and crashes on startup. It presents a two-round convergence methodology that establishes observability through serial logs and a firmware VM before attempting any fix, then walks through concrete defect classes—dangling pointers after mode switches and mismatched graphics protocol GUIDs—before polishing input handling, rendering, timing, and maintainability. It closes with six reusable principles for handing legacy code to AI: build a feedback loop first, review before editing, change one variable at a time, let AI propose hypotheses while humans decide, switch diagnostic paths after two failed attempts, and verify model-recalled constants and interfaces against the spec.

    1. Why “taking over a mess” is more valuable than “rewriting from scratch”

    Using AI to generate a new project validates its generation capability. Handing it a legacy project that won’t compile and crashes on startup, then asking it to clean up, validates its engineering capability. The latter is closer to real work: most of the time, developers don’t face a blank canvas but code left by others—undocumented, only loosely conformant in structure, and crashing the moment it runs.

    The subject of this experiment was a graphics sample project in a firmware environment. It had three characteristics that made it a good test case:

    • The code isn’t bad: multiple source files, modular structure, and consistent naming—it “looks the part” on static inspection.
    • Completely unusable at runtime: heavy build-environment dependencies, with no baseline runnable version.
    • Extremely high debugging cost: no operating system, no conventional debugger experience, and no screenshot tools—the only observation channel is serial output.

    The third characteristic determined the whole methodology: in a bare-metal firmware environment, you must first give the AI a pair of eyes, or any reasoning is guesswork. This point recurs throughout what follows.

    2. Experiment design: a two-round convergence method

    To make the process reproducible and the conclusions comparable, I explicitly split the work into two rounds, each with a clear Definition of Done.

    Round Goal Definition of Done
    Round 1 Make the code “run” Build passes → startup does not exit → expected image appears on screen
    Round 2 Refine and optimize Correct input response, no visible flicker, edge cases don’t crash, maintainable structure

    The accompanying environment setup matters just as much, otherwise the AI’s suggestions can’t be verified:

    1. Isolated build environment: copy the legacy code unchanged into a fresh build environment, so that historical configuration doesn’t mask missing real dependencies.
    2. Establish a logging channel: use the serial port as the only stdout, so progress is observable at any stage.
    3. Introduce a firmware VM: boot repeatedly in a virtualized firmware environment, compressing the cost of “reboot once” from minutes to seconds.
    4. Traceable changes: put all modifications under version control, changing only one issue at a time, to make rollback and attribution easy.

    This setup isn’t formalism. The failure mode of AI code repair is usually not “thinking wrong,” but “changing a lot when only one thing was the cause”—once something reverts, you can no longer say which change did the work.

    3. Round 1: from unrunnable to on-screen

    3.1 The first step is review, not editing

    My first instruction was deliberately simple: please review this code, identify the issues that could prevent it from running, and explain the reasoning.

    The AI went module by module—entry point, main loop, game logic, rendering module, input handling—and after a few minutes produced an issue list covering initialization order, protocol pointer lifetime, missing return-code handling, and more. The value of this list is that it translated the vague symptom “won’t run” into several independently verifiable hypotheses.

    Two things are worth standardizing at the prompt level:

    • Ask it to give both “why I suspect this” and “how to verify it,” not just a conclusion.
    • Ask it to grade by severity (fatal / blocking / minor), so the human only decides rather than discussing every item.

    3.2 Defect one: dangling pointer after switching display mode

    After the first round of fixes, the program no longer stalled at the build stage. It started, printed the log marking the beginning of the main loop, then exited immediately—one step further than “completely unrunnable.”

    With finer-grained stage logs added, the problem was localized to the graphics protocol initialization: the call returned success, then it crashed immediately when accessing mode information. The root cause is a very typical lifetime error:

    1. /* Problematic: info points to data maintained internally by firmware */
    2. EFI_GRAPHICS_OUTPUT_PROTOCOL_MODE *Mode = Graphics->Mode;
    3. Graphics->SetMode(Graphics, TargetMode);
    4. /* After SetMode, the previously obtained mode info memory may be invalid */
    5. UseResolution(Mode->Info->HorizontalResolution);

    The mode information is reconstructed by firmware when switching modes, and the old pointer becomes invalid immediately after. The correct approach is to re-query after SetMode, and free it as soon as you’re done:

    1. UINT32 InfoSize = 0;
    2. EFI_GRAPHICS_OUTPUT_MODE_INFORMATION *Info = NULL;
    3. Graphics->SetMode(Graphics, TargetMode);
    4. Graphics->QueryMode(Graphics, Graphics->Mode->Mode, &InfoSize, &Info);
    5. if (Info == NULL) { return EFI_NOT_READY; }
    6. /* Use Info's resolution, pixel format, and pixels per scanline */
    7. DrawBackground(Graphics, Info);
    8. FreePool(Info); /* Key: ownership of the buffer returned by the query is the caller's */

    This class of defect appears very frequently in AI-generated graphics code, because “get the mode, switch the mode, then draw using the old mode” is intuitively coherent—only by checking pointer ownership against the spec do you find the flaw.

    3.3 Defect two: graphics protocol GUID mismatch causing the output device not to be found

    After it stopped crashing, the next symptom was a fully black screen. The logs showed that the call to locate the graphics output protocol didn’t return success.

    Firmware contains multiple display-related protocol identifiers with similar names but different responsibilities: some for graphics output, some for direct framebuffer access, and some for text output. Using the wrong identifier usually doesn’t crash—instead the locate call quietly returns “not found,” and this class of problem is the easiest to overlook.

    Recommended troubleshooting order:

    1. Print the return code itself to distinguish “not found,” “unsupported,” and “already uninstalled.”
    2. Confirm the device is connected: the controller may not yet be bound by a driver, so explicitly trigger the connection and then locate again.
    3. Verify the identifier definitions against the spec headers, rather than trusting constant names from the model’s memory.
    4. Degrade on locate failure, rather than dereferencing a null pointer and continuing.
    1. status = LocateProtocol(&GraphicsOutputGuid, NULL, (VOID **)&Graphics);
    2. if (status != EFI_SUCCESS) {
    3. Log(L"locate graphics protocol failed: %r\n", status);
    4. ConnectControllerIfNeeded(); /* Trigger driver binding, then retry */
    5. status = LocateProtocol(&GraphicsOutputGuid, NULL, (VOID **)&Graphics);
    6. if (status != EFI_SUCCESS) { return status; }
    7. }

    At this point, Round 1 met its Definition of Done: it builds, it starts, and the image is output correctly.

    4. Round 2: refining and optimizing

    Running is only the starting point. The goal of the second round was to make it “look like a program a human wrote.”

    4.1 Input handling

    Keyboard input in a bare-metal environment must handle the press and release semantics of scancodes; reading directly causes “one keypress to trigger multiple actions.” Key improvements:

    • Use the “press edge” as the event trigger condition, maintaining the previous frame’s key state.
    • Provide a controllable repeat interval for long presses, rather than relying on hardware repeat.
    • Route all keys through a unified mapping table, avoiding hardcoded values scattered through the logic.
    • Provide an explicit exit key, to facilitate automated testing.

    4.2 Rendering strategy

    The initial implementation refreshed the entire screen every frame, with obvious flicker. Optimization directions, ordered by cost-effectiveness:

    1. Partial redraw: update only the rectangular region that actually changed.
    2. Reduce full-screen fills: the background color doesn’t need to be redrawn every frame—check whether it’s really covered before drawing.
    3. Unify the pixel-write path: avoid some paths using block transfer and others writing the framebuffer directly, which leads to inconsistent pixel-format handling.
    4. Boundary clipping: clip all coordinates to range before writing, to prevent out-of-bounds writes from corrupting adjacent memory.

    4.3 Timing and the main loop

    Using busy-wait for delays makes input latency jitter severely. Switch to a fixed-step driver: record timestamps, advance the logic by the target frame interval, and do only the necessary work inside the loop body.

    4.4 Stability and maintainability

    • Check the return code of every memory allocation and protocol call, taking a degradation path on failure rather than continuing.
    • Collect magic numbers for size, speed, color, and so on into named constants.
    • Change the game state to an explicit state machine, avoiding flags that overwrite each other.
    • Grade logs, so they can be turned off during production runs.

    5. A reusable methodology: six principles for handing legacy code to AI

    1. Build the feedback loop first, then talk about fixes. If it can compile, can run, and can show logs—missing any one of these three, and the AI can only guess.
    2. Review before modifying. The first step should be an issue list with reasoning, not a patch.
    3. Change one variable at a time. Only when all changes are rollback-able is attribution clear.
    4. Let the AI own the hypotheses; the human owns the decisions. It is good at enumerating possibilities; you use the logs to eliminate them.
    5. After two consecutive ineffective attempts on the same problem, switch diagnostic paths: add logs, build a minimal reproduction, and strip out unrelated modules—rather than continuing to patch the same hypothesis.
    6. Verify the constants and interfaces it recalls from memory. The model confuses similarly named definitions, so anywhere that participates in protocol location, memory ownership, or pixel-format decisions, defer to the spec and headers.

    6. Conclusion

    After two rounds of iteration, this legacy project went from “completely unusable” to “runnable with a clear structure.” The real payoff isn’t the hours saved, but that the process itself exposed a class of high-frequency defect patterns: pointer lifetime, protocol identifier matching, missing return codes, and framebuffer out-of-bounds. These four kinds of problems recur in graphics, driver, and bare-metal development, and distilling them into a review checklist has more long-term value than any one-off code generation.

    For teams, a more pragmatic approach is to position the AI coding assistant as “an executor that can read context, enumerate hypotheses, but needs to be verified and constrained,” combined with a cloud-reproducible build environment, a unified logging service, and monitoring alerts, so that every change is observable and traceable. The strength of the tool sets the ceiling, but the quality of the feedback loop determines whether you can work stably near that ceiling.