# UEFI Graphics Application Debugging with AI Assistance: A Practical Guide

    This guide walks through debugging UEFI/BIOS-level graphics applications, from setting up a reproducible QEMU + OVMF environment and building a minimal Graphics Output Protocol (GOP) example, to diagnosing the most common failure modes: stale mode information after `SetMode`, protocol GUID usage or linking errors, black screens, and firmware-stage crashes. It also shows how to use AI coding tools for structured code review and defect inference while keeping validation and architectural decisions in the developer's hands. You will find serial logging templates, `EFI_STATUS` interpretation tables, an observability-first log checkpoint table, a pre-flight risk checklist, and guidance on moving from "it compiles" to "it runs" to "it is optimized."

    1. Why Firmware-Level Graphics Development Is Hard

    When you develop graphics programs on top of an operating system, you can rely on mature graphics libraries, windowing systems, memory management, and debuggers. Once you drop down into a firmware environment such as UEFI/BIOS, most of that infrastructure simply does not exist. You are left facing boot services directly, protocol interfaces, frame buffers, and a very limited set of debugging options. In particular, graphics capability at the firmware stage is usually exposed through the Graphics Output Protocol (GOP), so a program has to locate the protocol, set a mode, and write into the frame buffer to draw anything.

    Many developers run into the same questions: What do I do when GOP location fails? How do I diagnose a black screen after SetMode? What should I actually log over the serial port? The root cause of these problems is rarely mysterious. It is that the firmware environment lacks high-level abstractions, so failures surface as a black screen, an unexpected exit, a hang, or a serial error message. As a result, firmware graphics development is not only about writing code. It is about building observability, reproducibility, and small-step verification into your process.

    Memory boundaries deserve special attention as well. During the UEFI boot services phase, you can request memory with AllocatePool or AllocatePages. Once ExitBootServices has been called, however, boot services are no longer available. At that point you cannot keep relying on LocateProtocol, SetMode, AllocatePool, AllocatePages, or other boot services for protocol location, mode switching, or ordinary memory allocation. If you genuinely need to access the frame buffer after exiting boot services, save the necessary addresses and parameters beforehand and add basic bounds checks, so you never call a boot service interface that has already been invalidated at runtime.

    AI coding tools are a good fit for the repetitive analysis work in this scenario: module review, defect inference, code replacement, and comment backfilling. The developer, however, should keep ownership of problem definition, result verification, and architectural decisions.

    2. Minimal Reproducible Environment: Get It Running Before You Debug It

    Before you start chasing bugs, put together a UEFI graphics application environment that is reproducible, recoverable, and rollback-friendly. In firmware debugging, the environment itself is more likely to cause unpredictable problems than your code is.

    A reasonable minimum environment includes:

    1. EDK2 build environment — used to compile UEFI applications, confirming that parameters such as UEFI_ARCH, TARGET, and TOOL_CHAIN are correct.
    2. UEFI Shell — used to load and run the generated .efi application.
    3. OVMF/QEMU virtual machine — used to emulate a UEFI firmware environment instead of debugging on production hardware.
    4. Serial output — redirect UEFI debug information to a serial port so you can observe the boot process, protocol state, and your own log messages.
    5. Version records — record the EDK2 version, OVMF firmware version, QEMU version, serial configuration, and build flags.

    A simplified example project might look like this:

    1. SampleApp/
    2. ├── SampleApp.c
    3. ├── SampleApp.inf
    4. ├── SampleApp.dec
    5. └── BuildOutput/

    Here, SampleApp.c holds the main flow, and SampleApp.inf declares the module type, source files, and library dependencies. If the project uses protocol GUIDs, make sure the relevant protocol package is included as well, otherwise you may hit undefined symbols or a runtime location failure.

    When debugging in a virtual machine, create snapshots of the disk and firmware state. If your program hangs the platform or corrupts the configuration, you can recover quickly. Be much more careful with real hardware: firmware-level errors can affect boot, display, and subsequent maintenance, so repeatedly trialing unverified code on production machines is not advisable.

    Below is a minimal QEMU + OVMF command example. Replace the OVMF firmware path and adjust BuildOutput to match your EDK2 build output location:

    1. qemu-system-x86_64 \
    2. -machine q35,accel=kvm:tcg \
    3. -m 2048 \
    4. -pflash /usr/share/OVMF/OVMF_CODE.fd \
    5. -drive if=pflash,file=OVMF_VARS.fd,format=raw,snapshot=on \
    6. -drive file=fat:rw:./BuildOutput/Build/SampleApp/DEBUG_GCC5/X64,format=raw \
    7. -serial file:uefi-serial.log \
    8. -device isa-debugcon,iobase=0x402,chardev=debugcon \
    9. -chardev file,id=debugcon,path=uefi-debug.log \
    10. -display none

    This command covers at least three key points: loading the OVMF firmware through -pflash, exposing the build output directory to the UEFI Shell via file=fat:rw:..., and collecting logs through -serial file:uefi-serial.log together with isa-debugcon. Setting snapshot=on prevents firmware variables or disk state from being corrupted accidentally. If you also want all guest disk writes to stay out of persistent storage, append -snapshot.

    3. Minimal GOP Example: From Protocol Location to Actual Drawing

    To build a minimal graphics application in UEFI, you typically need to do three things: locate the Graphics Output Protocol, set a display mode, read the frame buffer information for the current mode, and write at least one verifiable block of pixels. Otherwise the application stops at “the protocol was located” and never closes the loop from protocol location to actual drawing.

    The code below has been cleaned up with proper types, error checks, and a minimal drawing routine.

    1. #include <Uefi.h>
    2. #include <Library/UefiBootServicesTableLib.h>
    3. #include <Library/DebugLib.h>
    4. #include <Protocol/GraphicsOutput.h>
    5. EFI_STATUS
    6. EFIAPI
    7. UefiMain (
    8. IN EFI_HANDLE ImageHandle,
    9. IN EFI_SYSTEM_TABLE *SystemTable
    10. )
    11. {
    12. EFI_STATUS Status;
    13. EFI_GRAPHICS_OUTPUT_PROTOCOL *Gop;
    14. UINT32 ModeNumber;
    15. UINTN SizeOfInfo;
    16. EFI_GRAPHICS_OUTPUT_MODE_INFORMATION *Info;
    17. EFI_PHYSICAL_ADDRESS FrameBufferBase;
    18. UINT32 PixelsPerScanLine;
    19. volatile UINT32 *Pixels;
    20. UINTN FillWidth;
    21. UINTN FillHeight;
    22. UINTN Row;
    23. UINTN Column;
    24. Gop = NULL;
    25. ModeNumber = 0;
    26. SizeOfInfo = 0;
    27. Info = NULL;
    28. FrameBufferBase = 0;
    29. PixelsPerScanLine = 0;
    30. Status = gBS->LocateProtocol (
    31. &gEfiGraphicsOutputProtocolGuid,
    32. NULL,
    33. (VOID **)&Gop
    34. );
    35. if (EFI_ERROR (Status) || Gop == NULL) {
    36. DEBUG ((DEBUG_ERROR, "LOCATE GOP FAILED: %r, Gop=%p\n", Status, Gop));
    37. return Status;
    38. }
    39. if (Gop->Mode == NULL || Gop->Mode->Info == NULL) {
    40. DEBUG ((DEBUG_ERROR, "GOP MODE INFO IS NULL\n"));
    41. return EFI_NOT_READY;
    42. }
    43. ModeNumber = Gop->Mode->Mode;
    44. DEBUG ((DEBUG_INFO, "CURRENT MODE: MODE=%d\n", ModeNumber));
    45. Status = Gop->SetMode (Gop, ModeNumber);
    46. if (EFI_ERROR (Status)) {
    47. DEBUG ((DEBUG_ERROR, "SET MODE FAILED: MODE=%d STATUS=%r\n",
    48. ModeNumber, Status));
    49. return Status;
    50. }
    51. Status = Gop->QueryMode (Gop, ModeNumber, &SizeOfInfo, &Info);
    52. if (EFI_ERROR (Status) || Info == NULL) {
    53. DEBUG ((DEBUG_ERROR, "QUERY MODE FAILED: MODE=%d STATUS=%r\n",
    54. ModeNumber, Status));
    55. if (Info != NULL) {
    56. FreePool (Info);
    57. }
    58. return Status;
    59. }
    60. FrameBufferBase = Info->FrameBufferBase;
    61. PixelsPerScanLine = Info->PixelsPerScanLine;
    62. DEBUG ((DEBUG_INFO,
    63. "QUERY MODE OK: MODE=%d SIZE=%u FB_BASE=0x%llx PIXELS=%u\n",
    64. ModeNumber,
    65. (UINT32)SizeOfInfo,
    66. (UINT64)FrameBufferBase,
    67. PixelsPerScanLine));
    68. if (Info->PixelFormat != PixelRedGreenBlueReserved8BitPerColor) {
    69. DEBUG ((DEBUG_ERROR,
    70. "PIXEL FORMAT NOT SUPPORTED FOR MINIMAL DIRECT WRITE\n"));
    71. FreePool (Info);
    72. return EFI_UNSUPPORTED;
    73. }
    74. Pixels = (volatile UINT32 *)(UINTN)FrameBufferBase;
    75. FillWidth = (UINTN)Info->HorizontalResolution / 2;
    76. FillHeight = (UINTN)Info->VerticalResolution / 4;
    77. if (FillWidth > (UINTN)PixelsPerScanLine) {
    78. FillWidth = (UINTN)PixelsPerScanLine;
    79. }
    80. for (Row = 0; Row < FillHeight; Row++) {
    81. for (Column = 0; Column < FillWidth; Column++) {
    82. Pixels[Row * (UINTN)PixelsPerScanLine + Column] = 0x0000FF00;
    83. }
    84. }
    85. DEBUG ((DEBUG_INFO, "DRAW MINIMAL RECTANGLE DONE\n"));
    86. FreePool (Info);
    87. return EFI_SUCCESS;
    88. }

    This code illustrates several important points.

    First, the frame buffer base address must be held in a type wide enough for it. EFI_PHYSICAL_ADDRESS is used here to avoid truncation of high addresses that would occur with a 32-bit UINT32. Log output should also use a 64-bit-safe format, for example FB_BASE=0x%llx, with an explicit cast to (UINT64)FrameBufferBase. If your project uses portable macros such as ULLFMT, make sure the printed width matches a 64-bit unsigned type. PixelsPerScanLine is a 32-bit unsigned value and can be printed with %u.

    Second, LocateProtocol must have both its return value and the Gop pointer checked. Even when the status looks normal, avoid passing a null pointer further down the flow.

    Third, both SetMode and QueryMode need an EFI_ERROR check. In firmware protocols, mode-setting failures, nonexistent mode numbers, and unavailable frame buffers are all reported as status codes. If you skip the check, the program may continue into the drawing path and end up showing a black screen or exiting abnormally.

    Fourth, two easily confused pointers must be kept distinct. Gop->Mode->Info is the entry to the mode information maintained inside the protocol instance and should generally not be released by the caller with FreePool; it may become invalid after SetMode. The Info returned by QueryMode is a mode information buffer obtained by the caller through the protocol, and it must be released with FreePool after use. If you call QueryMode before SetMode and keep using that Info afterwards, it may no longer reflect the current state. The recommended sequence is therefore to call QueryMode again after SetMode and copy the fields you need into local variables.

    Fifth, the minimal drawing example assumes the current mode uses a 32-bit pixel format, PixelRedGreenBlueReserved8BitPerColor. If the firmware actually reports a different pixel format, you have to recompute the write pattern based on bits per pixel, channel ordering, and stride. Writing directly through UINT32 is only valid for the simple scenario shown in this example.

    4. Round One: From “It Compiles” to “It Runs”

    Problem 1: Using Stale Mode Information After SetMode

    The program prints a single log line and exits immediately, or nothing ever appears on screen. After adding serial debug output, the fault turns out to happen right after the protocol calls. Looking closer at the code reveals that the original version obtained the mode information pointer before SetMode, while SetMode updates the current mode and frame buffer information. Continuing to use the old mode information leads to a dangling or unreliable pointer access.

    The distinction is worth repeating: Gop->Mode->Info is protocol-internal information that must not be freed, but it may no longer be the valid current information after SetMode. The Info returned by QueryMode can and must be released with FreePool, but if it was obtained before SetMode it may be inconsistent with the latest mode state. The safer approach is to set the mode first, query the current mode second, and then copy the frame buffer fields.

    The incorrect and correct orderings compare as follows:

    Incorrect sequence Correct sequence Reason and result
    Calling QueryMode before SetMode and holding the Info pointer for a long time Calling QueryMode again after SetMode The old Info may not reflect the latest state
    Continuing to dereference the old Info after SetMode Copying FrameBufferBase and PixelsPerScanLine from the new Info May read a wrong address or trigger a fault
    Not distinguishing the internal pointer from the queried buffer Explicitly not freeing Gop->Mode->Info and freeing the Info returned by QueryMode Avoids incorrect frees or incorrect retention

    Serial logging can print:

    1. CURRENT MODE: MODE=%d
    2. SET MODE: MODE=%d STATUS=%r
    3. QUERY MODE: MODE=%d STATUS=%r
    4. FB BASE: 0x%llx
    5. PIXELS: %u

    This quickly confirms whether the mode was set successfully, whether the mode information was re-queried, and whether the frame buffer is valid.

    Problem 2: Incorrect Protocol GUID Usage or Linking

    The program no longer crashes, but the graphical output never appears. After reviewing the reported runtime behavior, the tool narrows the problem down to the protocol location step. In UEFI, the Graphics Output Protocol is identified by gEfiGraphicsOutputProtocolGuid. That GUID normally comes from an EDK2 header, such as Protocol/GraphicsOutput.h. If the header is not included, the protocol package is not linked, the wrong GUID is used, or the project architecture does not match, LocateProtocol will fail to obtain the Graphics Output Protocol.

    It is better to describe this as “incorrect protocol GUID usage or linking” rather than “protocol GUID misconfiguration”. When troubleshooting, check the LocateProtocol return value and whether Gop is null first, instead of immediately suspecting the drawing logic.

    1. Status = gBS->LocateProtocol (
    2. &gEfiGraphicsOutputProtocolGuid,
    3. NULL,
    4. (VOID **)&Gop
    5. );
    6. if (EFI_ERROR (Status) || Gop == NULL) {
    7. DEBUG ((DEBUG_ERROR, "GOP Locate failed: %r, Gop=%p\n", Status, Gop));
    8. return Status;
    9. }

    If location fails, check the following in order:

    1. Whether the correct protocol header is included;
    2. Whether the protocol package is linked correctly in the project;
    3. Whether the GUID in use is gEfiGraphicsOutputProtocolGuid;
    4. Whether the current firmware installs the Graphics Output Protocol at all;
    5. Whether the application runs in a suitable boot services phase;
    6. Whether the compiled architecture matches the UEFI firmware architecture.

    Common EFI_STATUS return values can help point the investigation in the right direction:

    Return value Common meaning Where to look
    EFI_SUCCESS Operation succeeded Continue checking mode setup and frame buffer
    EFI_NOT_FOUND Protocol or device not found Check whether the firmware installs GOP and whether the GUID is correct
    EFI_UNSUPPORTED The platform does not support this operation or mode Check the mode number, graphics capability, and firmware configuration
    EFI_INVALID_PARAMETER Invalid parameter Check pointers, the GUID, and mode parameters
    EFI_OUT_OF_RESOURCES Out of resources Check memory or protocol instance state

    Serial logs should at minimum include LOCATE GOP, STATUS, the Gop address, and the subsequent SET MODE status. Only once protocol location is proven to succeed do mode setting and frame buffer access become meaningful.

    5. Handing Legacy Code Over to AI Coding Tools

    This case study started from a Tetris implementation that had been generated by AI but never ran successfully. It spanned multiple files with an entry point, main loop, game logic, rendering, and input handling — structurally fairly complete, but it would neither compile nor run. Throwing it away seemed wasteful, and rewriting it from scratch would take too long, so the more sensible option was to have an AI coding tool take over the code.

    The first step is not to start editing. It is to have the tool perform a systematic review. The review instruction should be explicit and focused. For example:

    1. Review this UEFI graphics application code. The goal is to diagnose why it fails
    2. to compile, fails to run, shows a black screen, crashes, or hangs.
    3. Please output:
    4. 1. A reproducible serial log template;
    5. 2. Minimal verification steps;
    6. 3. A list of issues ordered by severity;
    7. 4. A suggested fix for each issue;
    8. 5. Risk points related to GOP location, SetMode, QueryMode, and frame buffer access;
    9. 6. One minimal, rollback-friendly fix patch.
    10. Please distinguish between "protocol-internal pointers" and "pointers returned by
    11. QueryMode that must be released with FreePool".

    The tool can then analyze module by module and produce an issue list — wrong protocol call order, incorrect mode information caching, wrong GUID usage, unchecked pointers, missing serial logging, and so on. The real value here is converting the developer’s mental burden of reading every line of source into a verifiable to-do list. You do not have to accept the conclusions blindly; you confirm each item against the logs and the build results.

    6. Debugging Methodology: Observability First and a Risk Checklist

    Both cases above point to a single firmware debugging principle: observability first. In an environment without a GUI, without a stack trace, and without an OS-level debugger, serial output is almost your only window. Emitting checkpoints at key stages turns an opaque crash into a sequence of locatable steps.

    At minimum, log the following points:

    1. LOCATE GOP: STATUS=%r GOP=%p
    2. CURRENT MODE: MODE=%d
    3. SET MODE: MODE=%d STATUS=%r
    4. QUERY MODE: MODE=%d STATUS=%r SIZE=%u
    5. FB BASE: 0x%llx
    6. PIXELS: %u
    7. ENTER LOOP

    If conditions allow, also record the pixel format, frame buffer dimensions, color depth, and bytes per scan line. For graphics applications, the frame buffer base address and the number of pixels per scan line matter especially. Many drawing anomalies are not caused by a bad drawing algorithm at all, but by an incorrect stride calculation or a wrong assumption about resolution.

    This can be organized into a troubleshooting table:

    Log checkpoint What to check Common failure cause
    LOCATE GOP Whether Status is EFI_SUCCESS and Gop is non-null Wrong GUID, protocol not installed, architecture mismatch
    CURRENT MODE Whether the current mode number is reasonable Gop->Mode or Gop->Mode->Info is null
    SET MODE Whether the mode was set successfully Mode does not exist, firmware does not support it, bad parameters
    QUERY MODE Whether the query succeeded and SizeOfInfo is reasonable Invalid mode, insufficient memory, abnormal protocol state
    FB BASE Whether the base address is a valid, non-zero address Mode not set, frame buffer unavailable
    PIXELS Whether pixels per scan line is greater than zero Wrong mode information or a failed query

    Firmware debugging carries additional risk. Faulty code can hang the platform, corrupt the display, break boot, and on real hardware even compromise later recovery. Debug in a recoverable environment or virtual machine such as QEMU + OVMF. Do not repeatedly run unvalidated graphics applications on production devices or in unbacked-up environments.

    A minimum checklist can include:

    1. Are you running in a recoverable environment or virtual machine?
    2. Have you recorded the UEFI firmware version, EDK2 version, and OVMF version?
    3. Have you recorded the serial output, baud rate, and log level?
    4. Have you recorded the ModeNumber?
    5. Have you recorded the frame buffer base address, dimensions, stride, and pixel format?
    6. Have you rebuilt and re-verified after every change?
    7. Have you avoided debugging directly on production hardware?
    8. Have you kept a rollback snapshot or the original source version?

    When working with AI tools, an iterative “small steps, fast cycles” rhythm works best:

    • Solve only one class of problem per round, and rebuild, run, and verify immediately after each change.
    • Feed back the complete, real information: serial logs, compile errors, and runtime state.
    • Keep a verifying mindset toward every change the tool suggests.
    • Low-level changes involving memory, timing, and protocols must be confirmed by the developer using actual runtime results.

    7. Round Two: From “It Runs” to “It Is Optimized”

    The goal of the first round is usually just to get the program running. Once the application enters the main loop, can read the frame buffer, and can display a basic image, you can move on to a second round focused on optimization.

    Round two can include:

    1. Optimizing the render refresh strategy to avoid screen tearing;
    2. Reducing unnecessary full-screen redraws;
    3. Improving input response latency;
    4. Refactoring scattered drawing logic;
    5. Filling in boundary conditions and error returns;
    6. Adding clearer serial logs and error codes;
    7. Decoupling hardware-specific operations from game logic.

    The emphasis at this stage is quality and maintainability. Let the tool do local, small-scope refactoring first, with clear comments. Avoid one large sweeping change, which tends to introduce regressions that are hard to localize.

    For instance, the drawing flow can be split into stages:

    1. Initialize graphics
    2. Enter main loop
    3. Handle input
    4. Update game state
    5. Compute the region that needs drawing
    6. Write to the frame buffer
    7. Swap or refresh the display

    If double buffering is available, screen tearing can be reduced further. Without double buffering, you can still improve the experience by limiting the refresh rate, reducing the redrawn area, and optimizing how pixels are written.

    8. Practical Advice for Developers

    Bringing AI coding tools into firmware-level development is essentially outsourcing repetitive analysis work, while the human keeps initiative over problem definition, result verification, and architectural decisions. To make this collaboration model work well, three points matter:

    1. Make instructions specific. Review and modification instructions should state the module scope and the dimensions to focus on, rather than staying vague. For example: “check protocol location only” or “analyze pointer lifetime after SetMode only”.

    2. Close the feedback loop. Drive each iteration with real runtime information — serial logs, return values, build results — rather than relying on the tool’s subjective judgment alone.

    3. Keep the human in control. Be especially careful with low-level changes involving memory, timing, and protocols. The tool improves throughput, but final confirmation of correctness remains the developer’s responsibility.

    Firmware development has a high entry barrier. Once AI tools take over the repetitive work of code review and defect inference, developers can concentrate their effort on architecture design, problem localization, and verification — the areas that genuinely test their skill. That is the more valuable way to apply AI-assisted development to low-level work.