Fixing UEFI Firmware Graphics Programs with AI: A Practical GOP Debugging Guide

    This article walks through how to use an AI coding assistant to repair a UEFI graphics program—for example, a simple Breakout or Tetris clone—that is structurally sound but won't compile or run. It covers the fundamentals of the Graphics Output Protocol (GOP), the most common failure patterns (black screen, crash after boot, no serial output, shifted or corrupted display), and a reproducible collaboration workflow where AI handles review, hypothesis generation, and fix drafts while the developer validates on real hardware, watches serial logs, and makes the final call. You will also find code examples for correct mode switching, GUID-based protocol location, safe frame buffer access, and drawing performance, plus a practical checklist for moving a broken program to a stable, verifiable, and optimizable state.

    Introduction: How AI Helps Fix Firmware Graphics Programs

    Developing graphics programs in a UEFI firmware environment is completely different from desktop development. There is no full operating system, no mature window system, and no high-level drawing libraries to rely on. Developers typically work directly with the Graphics Output Protocol (GOP), writing pixel data to the frame buffer. A single mistake in a mode parameter, a protocol GUID, or the lifetime handling of a pointer can lead to a black screen, a crash, no output at all, or even disruption of the subsequent boot process.

    This article centers on one typical task: taking a UEFI graphics program—such as a simple Breakout or Tetris clone—that has acceptable structure but cannot run as-is, and using an AI coding assistant to move it from “won’t compile, won’t run” to “compiles, boots, verifies, and can be optimized.” The focus is not on having AI generate perfect code in one shot, but on establishing a reproducible collaboration workflow: AI handles review, proposes hypotheses, and generates fix drafts; the developer handles on-device validation, serial log observation, and final decisions.

    1. Understanding the Key Points of UEFI GOP Graphics Development

    The most critical resource in UEFI graphics development is GOP. GOP typically provides current mode information, including resolution, pixel format, frame buffer address, frame buffer size, and the number of pixels per scan line (PixelsPerScanLine). Developers should pay close attention to the following objects:

    • EFI_GRAPHICS_OUTPUT_PROTOCOL: the graphics output protocol instance.
    • Mode->Info: the current mode information maintained by the protocol; the caller should generally not free this.
    • Mode->FrameBufferBase: the starting address of the current frame buffer.
    • Mode->FrameBufferSize: the size of the current frame buffer.
    • Mode->PixelsPerScanLine: the number of pixels per line, which is not necessarily equal to the horizontal resolution.
    • Information returned by QueryMode(): usually backed by allocated memory that the caller is responsible for freeing.

    Compared with ordinary application development, firmware graphics development has three difficulties. First, there is no operating system to fall back on, so errors are more direct. Second, pointer and memory lifetime constraints are stricter. Third, different motherboards and different firmware implementations may support GOP to varying degrees. For these reasons, AI suggestions should not be treated as final answers; they must be confirmed step by step through compilation, execution, serial logs, and validation on the target platform.

    Common Problems Quick Reference

    Symptom Common Cause Priority Check Points
    Completely black screen GOP not located, unsupported mode, incorrect frame buffer address LocateProtocol, SetMode, FrameBufferBase
    Crash right after boot Null pointer, invalid mode, incorrect memory free Whether Mode is null, MaxMode range, error branches
    No serial output Serial port not enabled, wrong baud rate, logging library not initialized Serial IO, DebugLib, baud rate, ConOut
    No graphics output but code looks fine Wrong GUID, protocol location failed Whether the standard gEfiGraphicsOutputProtocolGuid is used
    Shifted or corrupted display PixelsPerScanLine not used correctly, pixel format mismatch Line stride, bytes per pixel, alignment

    2. First Round: Get the Code Running

    2.1 Do a Structured Code Review with AI

    When fixing this kind of program, it is not advisable to run it immediately. Doing a static review with AI first can significantly reduce blind debugging time. You can use a prompt template like the following:

    1. Please review the following UEFI GOP graphics program code and output risk items in a table with these columns:
    2. risk level, containing function, trigger condition, root cause analysis, fix recommendation, verification method.
    3. Focus especially on:
    4. 1. Whether gBS, gST, and the GOP protocol are used correctly;
    5. 2. Whether mode information is incorrectly reused before and after SetMode;
    6. 3. Whether memory returned by QueryMode is properly freed;
    7. 4. Whether the GUID uses the standard graphics output protocol identifier;
    8. 5. Whether the frame buffer address, size, and line stride are validated;
    9. 6. Whether the error return paths are complete;
    10. 7. Whether the code may continue accessing a null pointer.

    The output of this review should be as specific as possible, rather than vaguely saying “the code has problems.” A high-quality result will usually list: which function may crash, under what conditions it crashes, how it should be fixed, and how to verify it via serial output or on real hardware.

    2.2 Common Error One: Old Mode Information Cannot Be Used Directly After SetMode

    A typical problem is that a program calls QueryMode() before switching modes, then continues using the previously obtained information after switching, assuming it represents the new current state. This is not rigorous.

    The key point to be clear about: SetMode() may change the current display mode. The old QueryMode() result does not necessarily represent the new current mode. If what you hold is Gop->Mode->Info, you should re-read the protocol’s current mode information after switching modes; if what you hold is a pointer returned by QueryMode(), you must manage it according to its allocation lifetime—typically calling FreePool() after use—and you must not assume it is suitable for the new current mode.

    The recommended approach is: first check the mode range, then call SetMode() and check the return status; after a successful mode switch, re-read the current frame buffer information, or call QueryMode() again to get the current mode information.

    1. #include <Uefi.h>
    2. #include <Protocol/GraphicsOutput.h>
    3. EFI_STATUS
    4. EFIAPI
    5. StartGraphics (
    6. VOID
    7. )
    8. {
    9. EFI_STATUS Status;
    10. EFI_GRAPHICS_OUTPUT_PROTOCOL *Gop;
    11. UINT32 Mode;
    12. Gop = NULL;
    13. Status = gBS->LocateProtocol (
    14. &gEfiGraphicsOutputProtocolGuid,
    15. NULL,
    16. (VOID **)&Gop
    17. );
    18. if (EFI_ERROR (Status) || Gop == NULL) {
    19. return EFI_NOT_FOUND;
    20. }
    21. if (Gop->Mode == NULL || Gop->Mode->MaxMode == 0) {
    22. return EFI_UNSUPPORTED;
    23. }
    24. Mode = Gop->Mode->Mode;
    25. if (Mode >= Gop->Mode->MaxMode) {
    26. Mode = 0;
    27. }
    28. Status = Gop->SetMode (Gop, Mode);
    29. if (EFI_ERROR (Status)) {
    30. return Status;
    31. }
    32. if (Gop->Mode->Info == NULL) {
    33. return EFI_PROTOCOL_ERROR;
    34. }
    35. // At this point we read the current mode information after a successful SetMode.
    36. // Mode->Info is maintained by the protocol and should generally not be freed manually.
    37. if (Gop->Mode->FrameBufferBase != 0 &&
    38. Gop->Mode->FrameBufferSize != 0 &&
    39. Gop->Mode->Info->PixelsPerScanLine != 0) {
    40. // You can continue drawing here.
    41. }
    42. return EFI_SUCCESS;
    43. }

    If the developer genuinely needs to obtain mode information explicitly, QueryMode() can be called again after a successful switch:

    1. EFI_STATUS Status;
    2. EFI_GRAPHICS_OUTPUT_PROTOCOL *Gop;
    3. EFI_GRAPHICS_OUTPUT_MODE_INFORMATION *Info;
    4. UINTN SizeOfInfo;
    5. Info = NULL;
    6. SizeOfInfo = 0;
    7. Status = Gop->QueryMode (
    8. Gop,
    9. Gop->Mode->Mode,
    10. &SizeOfInfo,
    11. &Info
    12. );
    13. if (!EFI_ERROR (Status) && Info != NULL) {
    14. // What we read here is the currently valid mode information.
    15. // It must be freed after use.
    16. FreePool (Info);
    17. }

    The core of this fix is not that “SetMode invalidates all pointers,” but rather: do not treat old state information as new state information directly. After any operation that changes state, you should re-confirm the current mode, frame buffer address, line stride, and pixel format.

    2.3 Common Error Two: Wrong GUID Location Causes “Program Runs Fine but Shows No Output”

    Another frequent problem is an incorrect GUID configuration. UEFI locates protocols by GUID. The standard GUID symbol for the graphics output protocol is typically:

    1. gEfiGraphicsOutputProtocolGuid

    In an EDK2 environment, you typically need to include:

    1. #include <Uefi.h>
    2. #include <Protocol/GraphicsOutput.h>

    The corresponding standard GUID is:

    1. {9042A9DE-23DC-4A38-96FB-7ADED080516A}

    If the developer uses some other graphics-related GUID, or manually enters an incorrect GUID, the program may still execute but cannot obtain the correct graphics output channel. The symptom is often: no error is reported, logs look normal, but the screen never shows anything.

    A minimal location example is as follows:

    1. #include <Uefi.h>
    2. #include <Protocol/GraphicsOutput.h>
    3. EFI_STATUS
    4. EFIAPI
    5. LocateGop (
    6. VOID
    7. )
    8. {
    9. EFI_STATUS Status;
    10. EFI_GRAPHICS_OUTPUT_PROTOCOL *Gop;
    11. Gop = NULL;
    12. Status = gBS->LocateProtocol (
    13. &gEfiGraphicsOutputProtocolGuid,
    14. NULL,
    15. (VOID **)&Gop
    16. );
    17. if (EFI_ERROR (Status) || Gop == NULL) {
    18. // It is recommended to output a serial log or DEBUG log here,
    19. // for example: DEBUG ((DEBUG_ERROR, "Locate GOP failed: %r\n", Status));
    20. return Status;
    21. }
    22. return EFI_SUCCESS;
    23. }

    The point to emphasize here: locating GOP is only the first step and does not mean the program already has full drawing capability. The developer still needs to check the current mode, frame buffer address, pixel format, and whether the mode switch succeeded. Different firmware may implement GOP capabilities differently, so any “location succeeded” result should still be followed by validation of the actual runtime behavior.

    3. Serial Logs: A Key Means of Firmware Debugging

    In firmware development, serial logs are a very effective observability tool. But the serial port is not available out of the box; certain preconditions must be met.

    3.1 Serial Debugging Preconditions

    You typically need to confirm the following:

    1. The firmware has the debug serial port enabled;
    2. The target platform has the Serial IO protocol installed;
    3. The underlying serial driver is working properly;
    4. DebugLib or the logging output library is correctly configured;
    5. The baud rate matches the serial tool, commonly 115200;
    6. The log output direction is correct, for example ConOut or a serial device;
    7. The physical serial connection is stable and the USB-to-serial driver works properly.

    In an EDK2 environment, if the program runs in the DXE phase, you typically need to confirm that gEfiSerialIoProtocolGuid can be located and that the debug serial port has been fully initialized. If the firmware only enables graphics output but not serial output, the developer may not see any logs at all.

    3.2 Log Troubleshooting Method

    If the program produces no serial output at all, check in the following order:

    • Check the serial cable, the USB-to-serial chip, and the serial tool on the host machine;
    • Confirm the baud rate, data bits, stop bits, and parity bits match;
    • Confirm whether the firmware outputs boot logs;
    • Confirm whether DebugLib has the corresponding log level enabled;
    • Confirm whether the program’s execution phase allows serial output;
    • Confirm whether output has been redirected to a graphical terminal or another output device;
    • Validate the basic serial link first in QEMU/OVMF.

    Once the serial port is available, it is recommended to insert logs at key points, such as protocol location, mode query, mode switch, frame buffer reading, entry into the main loop, and input reading. The log output should include variable values and status codes, not just print “started.”

    Example:

    1. DEBUG ((DEBUG_INFO, "GOP Mode = %d, MaxMode = %d\n",
    2. Gop->Mode->Mode, Gop->Mode->MaxMode));
    3. DEBUG ((DEBUG_INFO, "FrameBufferBase = 0x%llx\n",
    4. Gop->Mode->FrameBufferBase));
    5. DEBUG ((DEBUG_INFO, "FrameBufferSize = 0x%llx\n",
    6. Gop->Mode->FrameBufferSize));
    7. DEBUG ((DEBUG_INFO, "PixelsPerScanLine = %d\n",
    8. Gop->Mode->Info->PixelsPerScanLine));

    With serial logs, the developer can turn the hypotheses proposed by AI into a verifiable closed loop: first propose possible problems, then run the program, observe where the logs stop, and finally feed the logs back to AI so it can continue narrowing down the range.

    4. Second Round: From Running to Stable

    Once the program can boot and display something, you enter the optimization phase. AI can still help with analysis at this stage, but every suggestion must be validated. Firmware optimization cannot be judged solely by whether the code “looks better,” but by whether it genuinely reduces elapsed time, decreases crashes, and improves stability.

    4.1 Applicability Boundaries and Validation Criteria

    GOP behavior depends on the specific firmware implementation. Some platforms may support only a limited set of resolutions, and some platforms may impose special alignment requirements on the frame buffer address. Therefore, it is recommended to validate in the following environments:

    • QEMU or OVMF: for quickly validating logic and serial output;
    • Target virtual machine firmware: for validating behavior closer to a real environment;
    • A development board or test machine model: for final confirmation of compatibility.

    Note: modifying firmware variables, boot entries, serial configuration, or graphics modes can affect device boot. It is recommended to operate in a test or recoverable environment, and to avoid repeatedly making changes on critical production devices.

    4.2 Drawing Performance Optimization

    Drawing performance optimization can be approached from the following directions:

    • Use PixelsPerScanLine to compute the real line stride, rather than simply using the horizontal resolution;
    • Write consecutive pixels in batches, avoiding complex computation for every single pixel;
    • Minimize unnecessary function calls and branch checks;
    • For static backgrounds, prepare color values or simple patterns in advance;
    • Avoid frequently redrawing the entire screen; prefer redrawing only the changed regions;
    • If the platform supports it, consider a double-buffering or off-screen buffering strategy.

    A simple batch clear-screen example is as follows:

    1. EFI_STATUS
    2. ClearScreen (
    3. EFI_GRAPHICS_OUTPUT_PROTOCOL *Gop
    4. )
    5. {
    6. UINT32 *FrameBuffer;
    7. UINTN Index;
    8. UINTN PixelCount;
    9. if (Gop == NULL || Gop->Mode == NULL ||
    10. Gop->Mode->FrameBufferBase == 0 ||
    11. Gop->Mode->FrameBufferSize == 0) {
    12. return EFI_INVALID_PARAMETER;
    13. }
    14. FrameBuffer = (UINT32 *)Gop->Mode->FrameBufferBase;
    15. PixelCount = Gop->Mode->FrameBufferSize / sizeof (UINT32);
    16. for (Index = 0; Index < PixelCount; Index++) {
    17. FrameBuffer[Index] = 0x00000000;
    18. }
    19. return EFI_SUCCESS;
    20. }

    This example assumes 32 bits per pixel. In actual development, you must adjust the approach according to PixelFormat and the number of bytes per pixel. Under different pixel formats, the color layout may differ, so you cannot simply write values directly in RGB order.

    4.3 Input Handling and Stability

    If the graphics program includes keyboard input, note the following:

    • Whether input reading has a clear timing;
    • Whether key-repeat triggering exists;
    • Whether both scan codes and character codes are handled;
    • Whether the main loop blocks for too long;
    • Whether errors are ignored due to read failures;
    • Whether the display still refreshes normally when there is no input.

    AI can help analyze input logic, but real-hardware key behavior, keyboard controller differences, and firmware input protocol differences still require actual validation.

    4.4 Error Handling and Memory Management

    All external protocol calls should check the return status. In particular:

    • Whether LocateProtocol() succeeds;
    • Whether SetMode() succeeds;
    • Whether QueryMode() succeeds;
    • Whether Mode is null;
    • Whether Mode->Info is null;
    • Whether FrameBufferBase is valid;
    • Whether FrameBufferSize is reasonable;
    • Whether memory allocation failures are handled;
    • Whether memory is set to null immediately after being freed;
    • Whether there is a risk of double-free or of freeing memory owned by the protocol internally.

    One key principle: Mode->Info is usually maintained by the protocol, and the caller should not free it at will; the information returned by QueryMode() is usually the caller’s responsibility to free. The two must not be confused.

    5. Experience Checklist

    Finally, the whole process can be organized into an actionable checklist:

    1. Compile check: Confirm that header files, library dependencies, GUID symbols, and link configuration are correct.
    2. Mode check: Confirm that Mode exists, MaxMode is valid, and the target mode is within a legal range.
    3. State check: Re-read the current mode after SetMode(); do not reuse old state information.
    4. Pointer check: Distinguish between pointers owned internally by the protocol and pointers returned by QueryMode(), avoiding incorrect freeing or incorrect retention.
    5. GUID check: Use gEfiGraphicsOutputProtocolGuid and include the correct header.
    6. Log check: Confirm that serial debugging is enabled, the baud rate is correct, and key points output status codes.
    7. Drawing check: Use FrameBufferBase, FrameBufferSize, and PixelsPerScanLine; do not assume a fixed resolution.
    8. Error check: Every protocol call failure should either return or produce a diagnostic; do not continue drawing in an error state.
    9. Validation environment: Prefer validating in QEMU/OVMF or on a test machine first, then confirm on the target model.
    10. AI collaboration style: Have AI output risk level, cause, fix recommendation, and verification method, rather than just generating code.

    In summary, the value of an AI coding assistant in UEFI graphics development does not lie in guaranteeing success on the first try, but in helping the developer complete structured review, risk localization, and fix-draft generation more quickly. Firmware development still requires the developer to understand the underlying constraints—especially memory lifetime, protocol location, mode switching, and serial debugging. Treating AI as a reviewer and debugging partner, rather than the final arbiter, is what lets you reliably turn “broken code” into a firmware graphics program that runs, can be verified, and can be optimized.