# Debugging UEFI Graphics Code with LLMs: From "Looks Right" to "Actually Runs"

    When you build graphics programs for the UEFI environment, the hard part is not writing the code, it is making the code actually run. There is no operating system, no runtime, and no third-party graphics library; failures rarely produce a stack trace or a dialog box, and the typical outcome is a black screen or a machine that reboots. This article walks through a real experiment in which large language models (LLMs) implemented UEFI graphics programs, then debugged and repaired code left behind by a different model. It covers a unified build setup, a two-round acceptance process, two concrete failure cases (stale frame buffer information after a mode switch, and the wrong graphics-related GUID), the polish work that followed, and a checklist of common UEFI graphics pitfalls. The focus is methodology, not a ranking of models: how to move UEFI graphics code from "looks correct" to "reliably runs" with AI in the loop.

    \section{1. Background and Motivation: From “It Compiles” to “It Runs”}

    Developing graphics programs for UEFI is hard for three reasons:

    • Unusual environment: there is no operating system, no runtime, and no third-party graphics library.
    • Failures are silent: a program that breaks usually produces no stack trace and no dialog box. The mild outcome is a black screen; the severe outcome is an immediate reboot.
    • Limited debugging tools: you mainly have serial logs and the firmware emulation environment inside a virtual machine.

    Here, a “graphics program” means one that draws directly into the frame buffer through the Graphics Output Protocol (GOP). Typical uses are boot-phase logos, boot menus, small games shown during boot, and hardware self-test screens.

    I had an LLM implement a Chinese-language brick-breaker (Breakout-style) game in a BIOS environment. After roughly two and a half hours of development, it compiled on the first attempt and entered the game loop on its first run.

    I then asked a different model to implement Tetris under the same constraints. Six hours later the program still would not run, and the build environment itself had not been set up. However, what the second model left behind included seven source files, with a clean separation between entry point, logic, rendering, and input, and an overall structure that followed conventions. Throwing that away felt wasteful, which led to a new idea: have the first model repair the code the second model left behind. You could call it “letting AI clean up after AI.”

    The value of this approach is not only about “which model is stronger”:

    • A single environment and a single task remove interfering variables.
    • It matches a real scenario: taking over legacy code of unknown origin that has never been validated.
    • It upgrades “generation” into a complete loop of review, diagnosis, repair, and verification.

    It is also worth being explicit: the two tasks are not a fair comparison. This article does not rank models. The point is the methodology, that is, how to move UEFI graphics code from “looks right” to “really runs” with AI participating.

    \section{2. Preparation: A Unified Environment and Clear Acceptance Criteria}

    \subsection{2.1 Unified Build Environment}

    One of the root causes of the previous failure was the build step. The two models very likely assumed different compilers and dependency versions, which produces the classic outcome: “the code is fine, but the environment will not come up.” For firmware projects, pin down four things:

    1. One compiler and one set of build tools, with version numbers recorded.
    2. One firmware runtime environment, that is, the same UEFI emulation environment or firmware in a VM, at the same resolution and pixel format.
    3. One source directory layout, so the model can understand module boundaries.
    4. One written constraints document, handed to the model together with the code:
    1. # Runtime constraints
    2. - No operating system and no standard library runtime; do not rely on the file system or the network
    3. - Graphics output is done only through the Graphics Output Protocol (GOP); the supported combinations of mode number and pixel format must be enumerated and confirmed during initialization
    4. - No graphics debugger; serial logs are the only stable output channel. Logs must carry a module prefix and a timestamp
    5. - An exit path is required: pressing a designated key ends the loop and returns to the upper-level UI

    \subsection{2.2 Two-Round Acceptance}

    Code acceptance was done in two rounds:

    • Round 1 (functional verification): the code compiles, starts, and the core gameplay runs, with no crashes and no black screens.
    • Round 2 (quality polish): smoothness, visual quality, memory usage, and code structure.

    The final acceptance criterion is a single one: the built executable runs stably in the target firmware environment. Whether the source is tidy and how long generation took are only process metrics.

    \section{3. Round 1: From “Compiles” to “Runs”}

    \subsection{3.1 First Step: Ask for a Review, Not a Fix}

    The first instruction to the model that took over was “review this code and identify potential problems.” The key is diagnose first, treat second. Telling the model to “just fix it” usually introduces new changes, and the problems pile up. The instruction should come with a module list and a required output format:

    1. You are a senior UEFI/BIOS graphics engineer. Review the source code below module by module,
    2. in this order: entry point -> main loop -> game logic -> rendering -> input.
    3. Produce a list of problems sorted by severity. For each item, include:
    4. 1. A description of the problem and the file/function where it lives;
    5. 2. Trigger conditions and consequences;
    6. 3. A suggested fix, stating the basis for it (a UEFI specification convention, or the specific code logic).
    7. Analysis only in this round; do not modify the code.

    A few minutes later, the model produced a problem list. At the time, it judged that “once these are fixed it should run.” That was not actually the case. Even so, the list was valuable: it turned “a black screen with no clue” into several concrete hypotheses that could be verified one at a time.

    \subsection{3.2 Problem 1: Crash Right After the Mode Switch - The Lifetime of Frame Buffer Information}

    Symptom: the program started and printed its initialization logs, then exited as soon as it entered the main game loop. Compared with the previous round, where the build environment could not even be set up, this counted as progress.

    Localization: I had the model add serial logs with module prefixes and ran it again:

    1. [init] start
    2. [init] locate gop ok
    3. [init] set mode ok, mode=160
    4. [loop] Starting Game Loop
    5. [render] clear screen ... <-- logs stop here

    The program exited on the first screen clear. Reading the code together with the log showed:

    1. During initialization, QueryMode was called, a mode information pointer was obtained, and that pointer was kept.
    2. SetMode was then called to switch resolution.
    3. The main loop kept reading the frame buffer base address and the number of pixels per scan line from the stored pointer.
    4. The first write to the screen touched an invalid address, which triggered exception handling and halted the machine.

    Root cause: the question is “when is the pointer still valid?” Per the general convention of the UEFI specification for the Graphics Output Protocol, mode information describes the frame buffer base address, pixels per scan line, horizontal and vertical resolution, and pixel format. The information pointer returned by QueryMode is owned by the driver, and how long it stays valid depends on the implementation. The common rule is that after a mode change, the data an older pointer refers to is no longer reliable, and dereferencing it is no better than dereferencing a wild pointer.

    Fix: re-query the mode information after the mode change, then draw. Example code:

    1. // Compute and set a mode from the physical resolution
    2. Status = SetModeByResolution(Gop, Width, Height, &ModeIndex);
    3. if (EFI_ERROR(Status)) {
    4. Log(L"[init] set mode by %dx%d failed: %r\n", Width, Height, Status);
    5. return Status;
    6. }
    7. // Re-query after the mode change; do not keep using the previous ModeInfo pointer
    8. UINTN InfoSize = 0;
    9. EFI_GRAPHICS_OUTPUT_MODE_INFORMATION *ModeInfo = NULL;
    10. Status = Gop->QueryMode(Gop, ModeIndex, &InfoSize, &ModeInfo);
    11. if (EFI_ERROR(Status) || ModeInfo == NULL) {
    12. Log(L"[init] query mode %d failed: %r\n", ModeIndex, Status);
    13. return EFI_DEVICE_ERROR;
    14. }
    15. Framebuffer = (UINT8 *)(UINTN)ModeInfo->FrameBufferBase;
    16. Stride = (UINTN)ModeInfo->PixelsPerScanLine; // pixels per scan line
    17. Log(L"[init] fb=0x%x stride=%d fmt=%d\n",
    18. ModeInfo->FrameBufferBase, Stride, ModeInfo->PixelFormat);

    If the program switches modes again later, the safer approach is to wrap this in an InitGraphics() function that sets the mode and fetches the frame buffer information together, so the two always update as a pair, and to validate them before every use.

    General takeaway: AI can “see” the code but tends to overlook the “contract”, that is, the conditions under which an interface’s return value is valid. When reviewing an AI-generated solution, specifically check two categories of code: pointers kept across a lifecycle boundary, and return values that are not null-checked.

    \subsection{3.3 Problem 2: No Graphics on Screen - The Wrong Graphics-Related GUID}

    Symptom: the program no longer crashed, the serial log kept printing game loop output, but nothing appeared on the screen.

    Localization: I asked the model to analyze the logs against the initialization code. It found the problem in the step that locates the Graphics Output Protocol: the GUID used in the code did not match the GUID that the Graphics Output Protocol is actually bound to in that firmware environment.

    Root cause: UEFI identifies and locates the services a driver provides through “protocol interface + GUID”, and a development environment contains several graphics-related GUIDs with similar names and different purposes:

    GUID type Purpose Typical consequence of misuse
    Protocol GUID Obtaining a protocol instance via LocateProtocol/HandleProtocol Used for locating modes, switching modes, and drawing; if it does not match, the call returns “not found”
    Variable GUID Organizing non-volatile variables, for example boot entries and boot order Used for protocol location, it returns “not found”
    Device path-related GUID Identifying device path node types Used for protocol location, it returns “not found”
    Image-related GUID Protocols or types for image resources such as boot logos and boot image options Mistaken for the Graphics Output Protocol, it fails to compile with a type mismatch

    Among these, settings such as the boot-phase display resolution are typically exposed by firmware as non-volatile variables. Reading such settings should use the corresponding variable interface, not the protocol location interface.

    Fix highlights:

    1. Determine the Graphics Output Protocol GUID from the definition in the protocol header, not from guesswork.
    2. Check the status code returned when location fails instead of dereferencing a null pointer.
    3. After a successful locate, call QueryMode first and print the information for the first mode to confirm the protocol is really usable before switching modes.
    1. // Use the protocol GUID defined by the protocol header, not a variable GUID or a device path-related GUID
    2. Status = gBS->LocateProtocol(&gGraphicsOutputProtocolGuid, NULL, (VOID **)&Gop);
    3. if (EFI_ERROR(Status) || Gop == NULL) {
    4. // Print the status code instead of dereferencing a null pointer
    5. Log(L"[init] locate gop failed: %r\n", Status);
    6. return Status;
    7. }
    8. // Confirm the protocol works before switching modes
    9. UINTN Size = 0;
    10. EFI_GRAPHICS_OUTPUT_MODE_INFORMATION *Info = NULL;
    11. Status = Gop->QueryMode(Gop, 0, &Size, &Info);
    12. Log(L"[init] gop ready, mode0: %dx%d stride=%d\n",
    13. Info ? Info->HorizontalResolution : 0,
    14. Info ? Info->VerticalResolution : 0,
    15. Info ? Info->PixelsPerScanLine : 0);

    Troubleshooting method: for any “not found” or “not supported” error, first write a minimal program that locates the protocol and queries modes on its own, confirm the basic path works, and only then run the full program.

    General takeaway: at the firmware level, many APIs are indexed by GUID, and similar names often carry very different semantics. This is a high-frequency source of AI mistakes. During code review, make “does the GUID in every protocol location call match its interface?” a mandatory check.

    \subsection{3.4 The Debug Loop: Three Stages Closing the Circuit}

    Looking back at the whole process, every problem was located with the same routine:

    1. Static review: the model reads the code and produces hypotheses about the problems.
    2. Log observation: print logs with module prefixes and timestamps at key points, turning a vague symptom such as “black screen” into a precise question such as “where does it stop”.
    3. Minimal verification: write a few lines of minimal code to test a single hypothesis in isolation, then merge it back into the main program once confirmed.

    These three stages repeat until the program reliably enters the game loop.

    \section{4. Round 2: Polishing Quality on Top of a Working Program}

    Getting the program to run was only the starting point. In the second round I focused on five areas:

    1. Chinese text rendering: confirm the line-break convention used in the firmware encoding, implement lookup from GB2312 double-byte characters into a 16x16 bitmap font, and allow Chinese and ASCII characters to be mixed on the same line, so prompts such as “Start” and “Score” display correctly.
    2. Off-screen buffer and frame synchronization: using the addressing rule “frame buffer base + pixels per scan line x y + x”, draw each frame into a memory buffer, then submit the completed frame to the screen in a single operation to avoid flicker and tearing; a fixed frame rate is driven by the firmware timer services.
    3. Input handling: read scan codes and Unicode characters through the key-reading services of the simple text input protocol. Some emulation environments do not support the arrow keys, so a fallback was needed: W/A/S/D control was added, along with Esc to exit.
    4. Resource management: the canvas, buffers, and font data are allocated once before the run, and during gameplay only object state is updated, avoiding repeated allocation and release.
    5. Code structure: rendering was decoupled from game rules. A state such as “game over”, for example, only needs to be rendered once and handled separately from the dynamic elements, so static content is not repainted every frame.

    There were setbacks along the way: some changes compiled but broke rendering. In those cases I had the model roll back to the last working version and validate that single change in isolation, rather than introducing problems from several changes at once.

    \section{5. Lessons Learned: Six Points for AI-Assisted Firmware Development}

    \subsection{5.1 Write the Constraints Document Clearly}

    The more explicit the information, the less the AI will “improvise.” Describe the runtime environment, the available interfaces, the serial log conventions, and the exit requirements in plain text. Constraints determine the outcome more than a request for “the optimal solution.”

    \subsection{5.2 Give the AI Observability}

    Placing logs at key points is like giving the AI a pair of eyes. Without logs, the model can only guess; with logs, it can make progress based on evidence. Logs should include a module prefix, status codes, and timestamps, and they must be emitted reliably in the serial emulation environment.

    \subsection{5.3 Let the AI Review and Diagnose; Humans Own the Contracts}

    Static review and root-cause analysis are worth leaning on fully. But AI tends to miss conventions such as pointer lifetime, who allocates and releases a returned buffer, and which data becomes invalid after a mode switch. Those judgments must be confirmed by the developer. In particular, any change related to real hardware or a production environment should be made only after thorough validation.

    \subsection{5.4 Change One Thing at a Time, and Keep a Known-Good Version}

    Firmware environments give slow feedback and are hard to diagnose. If several points are changed at once, you cannot tell which one caused the problem. After each round of changes, run at least two checks:

    • Does it compile?
    • Does it start without crashing?

    At the same time, keep a known-good version. Confirming that “the change actually helped” matters much more than “the change looks reasonable.”

    \subsection{5.5 “The Code Looks Right” Is Not “The Code Runs”}

    Reviewing the whole development process, code quality breaks down into several layers:

    Layer Characteristics Where it showed up here
    Structure Clear module boundaries, consistent naming The seven files left by the other model
    Compilation Builds successfully on the first try The first model’s initial build
    Runtime No crashes, no black screen, correct logic After the two fixes
    Quality Smooth, stable, controlled resource usage The Round 2 polish

    Evaluating in layers is what separates “seems like it will run” from “really runs stably.”

    \subsection{5.6 Cross-Validate with AI, Do Not Rely on a Single Path}

    Having different models and different approaches review each other is an efficient way to find errors. But cross-validation cannot replace the validation environment: the final verdict is always an actual test of the build artifact in the target environment.

    \section{6. A Checklist of Common UEFI Graphics Pitfalls}

    Category Typical problem How to handle it
    Mode and pixel format Wrong colors, likely a BGR layout or a pixel format with padding bits Handle RGB layout, BGR layout, and bit-mask formats separately per pixel format
    Frame buffer The whole image is offset, or rows drift apart, often because the resolution is not a multiple of 8 Compute addresses strictly as “frame buffer base + pixels per scan line x y + x”, and validate coordinate bounds
    Pointer lifetime A stale mode information pointer after a mode change causes a crash Re-query after a mode change; do not carry the pointer across stages
    Protocol location Nothing on screen, locate returns “not found” Verify the protocol GUID; check the status code
    Mode selection No display at all Prefer a mode that matches the physical resolution and supports direct drawing
    Boot protection Writes are blocked Check whether boot protection is enabled and whether writes are permitted at runtime
    Input No keyboard response Check how scan codes and Unicode characters are read; support multiple key paths
    Text rendering Garbled Chinese or wrong line breaks Pin down the line-break encoding convention and implement double-byte character lookup
    Memory Exhaustion after running for a long time Allocate resources once; avoid repeated allocation and release in loops
    Resource leaks Allocation without release Define who allocates and who releases, and always pair a release function with its matching allocation function
    Runtime-resident memory Memory still occupied after exit Request the memory the game needs with the correct memory type
    Exit path Cannot exit End the loop and release resources on the designated key instead of rebooting
    Build environment The build environment cannot be set up Pin compiler and dependency versions; use one directory layout
    Runtime environment Abnormal display Fix resolution, pixel format, and the firmware emulation environment

    \section{7. Conclusion}

    This exercise started with a game and ended with a process:

    1. Have the AI perform an overall review and produce hypotheses about the problems.
    2. Use serial logs to turn vague symptoms into concrete problems.
    3. Verify each hypothesis with minimal code.
    4. Then move on to quality and experience polish.

    Throughout, AI carried a large share of the repetitive work of finding problems and writing patches, while the judgments about “what counts as valid evidence” and “which conventions must be held” stayed with the human developer.