UEFI GOP Troubleshooting Guide: Memory Ownership and Protocol Validation

    A practical guide to debugging the UEFI Graphics Output Protocol in EDK2 with QEMU and OVMF. It explains memory ownership, the correct QueryMode and SetMode sequence, framebuffer handling, GUID and status-code checks, serial logging, and a verification workflow for AI-assisted troubleshooting. Examples should be adjusted to match the actual headers and firmware versions in use.

    This guide uses EDK2 with QEMU and OVMF as its reference environment. Firmware implementations may differ, so adjust the examples to match the headers and versions in your build.

    The Graphics Output Protocol (EFI_GRAPHICS_OUTPUT_PROTOCOL, or GOP) is provided by firmware. The Gop pointer returned by LocateProtocol, along with the structure referenced by Gop->Mode, is owned by the firmware. The caller may read this data but must not release it.

    The Info structure returned by QueryMode is different. Firmware allocates it with AllocatePool and passes it to the caller. The caller must release it with FreePool after use.

    SetMode changes the mode state maintained by the firmware. It does not release Info. Its purpose is to update the framebuffer base address, framebuffer size, resolution, and other mode-related information used afterward.

    These two types of memory have different ownership rules and invalidation times. Treating them as the same object is a common source of incorrect debugging conclusions.

    A complete graphics initialization sequence should generally follow these steps:

    1. Locate GOP with LocateProtocol, then check both the status code and the returned pointer.
    2. Call QueryMode as needed to enumerate available modes. Release Info after each call.
    3. Switch to the target mode with SetMode and check the return status.
    4. After SetMode succeeds, read the framebuffer information and resolution from Gop->Mode.
    5. Render through Blt or by writing directly to the framebuffer.

    The following implementation covers the first four steps. Header paths and function names follow the EDK2 MdePkg conventions.

    1. #include <Uefi.h>
    2. #include <Library/UefiBootServicesTableLib.h>
    3. #include <Library/MemoryAllocationLib.h>
    4. #include <Library/DebugLib.h>
    5. #include <Protocol/GraphicsOutput.h>
    6. STATIC
    7. VOID
    8. ReleaseModeInfo (
    9. IN OUT EFI_GRAPHICS_OUTPUT_MODE_INFORMATION **Info
    10. )
    11. {
    12. if (*Info != NULL) {
    13. FreePool (*Info);
    14. *Info = NULL;
    15. }
    16. }
    17. EFI_STATUS
    18. InitGraphics (
    19. OUT EFI_GRAPHICS_OUTPUT_PROTOCOL **OutGop,
    20. IN UINT32 TargetMode
    21. )
    22. {
    23. EFI_STATUS Status;
    24. EFI_GRAPHICS_OUTPUT_PROTOCOL *Gop;
    25. EFI_GRAPHICS_OUTPUT_MODE_INFORMATION *Info;
    26. UINTN SizeOfInfo;
    27. UINT32 Mode;
    28. // Step 1: Locate GOP
    29. Status = gBS->LocateProtocol (
    30. &gEfiGraphicsOutputProtocolGuid,
    31. NULL,
    32. (VOID **)&Gop
    33. );
    34. if (EFI_ERROR (Status) || (Gop == NULL)) {
    35. DEBUG ((DEBUG_ERROR, "[GOP] LocateProtocol failed: %r\n", Status));
    36. return EFI_ERROR (Status) ? Status : EFI_NOT_FOUND;
    37. }
    38. // Step 2: Enumerate modes if needed and release Info after each use
    39. for (Mode = 0; Mode < Gop->Mode->MaxMode; Mode++) {
    40. Info = NULL;
    41. SizeOfInfo = 0;
    42. Status = Gop->QueryMode (Gop, Mode, &SizeOfInfo, &Info);
    43. if (EFI_ERROR (Status)) {
    44. DEBUG ((DEBUG_ERROR, "[GOP] QueryMode(%d) failed: %r\n", Mode, Status));
    45. ReleaseModeInfo (&Info);
    46. continue;
    47. }
    48. DEBUG ((
    49. DEBUG_INFO,
    50. "[GOP] mode=%d resolution=%dx%d\n",
    51. Mode,
    52. Info->HorizontalResolution,
    53. Info->VerticalResolution
    54. ));
    55. ReleaseModeInfo (&Info);
    56. }
    57. // Step 3: Switch to the target mode
    58. Status = Gop->SetMode (Gop, TargetMode);
    59. if (EFI_ERROR (Status)) {
    60. DEBUG ((DEBUG_ERROR, "[GOP] SetMode(%d) failed: %r\n", TargetMode, Status));
    61. return Status;
    62. }
    63. // Step 4: Read framebuffer information after SetMode succeeds
    64. DEBUG ((
    65. DEBUG_INFO,
    66. "[GOP] base=0x%Lx size=0x%Lx\n",
    67. (UINT64)Gop->Mode->FrameBufferBase,
    68. (UINT64)Gop->Mode->FrameBufferSize
    69. ));
    70. *OutGop = Gop;
    71. return EFI_SUCCESS;
    72. }

    Two details are easy to miss.

    First, when QueryMode fails, Info may still be NULL. Check the pointer before releasing it. Under the UEFI specification, calling FreePool with a NULL pointer returns EFI_INVALID_PARAMETER, so a null check is required.

    Second, every EFI_STATUS must be checked. Failure paths should log the error and return or otherwise handle it explicitly. Do not continue execution as if the operation succeeded.

    3. Where to Read Framebuffer Information Before and After SetMode

    The framebuffer base address, FrameBufferBase, and framebuffer size, FrameBufferSize, are mode-dependent. They commonly change when the graphics mode changes.

    Therefore, values read before SetMode describe the previous mode. If those values are cached and later used for rendering, the program may write to an address or range that no longer corresponds to the active mode.

    The correct approach is to read the fields in Gop->Mode only after SetMode returns EFI_SUCCESS.

    1. Status = Gop->SetMode (Gop, TargetMode);
    2. if (EFI_ERROR (Status)) {
    3. // Do not read framebuffer fields after failure.
    4. return Status;
    5. }
    6. UINT64 Base = (UINT64)Gop->Mode->FrameBufferBase;
    7. UINT64 Size = (UINT64)Gop->Mode->FrameBufferSize;

    If SetMode fails, the fields in Gop->Mode may retain their old values or may be in an indeterminate state. Do not use them for rendering after a failure. You can return the error, or restore the previous mode and read the values again after the recovery succeeds.

    For rendering, Blt is generally preferable. Firmware handles address calculations and pixel-format conversion, making it less error-prone than writing directly to the framebuffer. The following example fills the entire screen with one color.

    1. EFI_STATUS
    2. FillScreen (
    3. IN EFI_GRAPHICS_OUTPUT_PROTOCOL *Gop,
    4. IN EFI_GRAPHICS_OUTPUT_BLT_PIXEL *Color
    5. )
    6. {
    7. return Gop->Blt (
    8. Gop,
    9. Color,
    10. EfiBltVideoFill,
    11. 0, 0,
    12. 0, 0,
    13. Gop->Mode->Info->HorizontalResolution,
    14. Gop->Mode->Info->VerticalResolution,
    15. 0
    16. );
    17. }

    4. QueryMode and Info: Who Allocates and Who Frees It?

    Each successful call to QueryMode allocates a new Info structure. The caller should release it immediately after use.

    The rules are:

    1. Every successful QueryMode call must have one corresponding FreePool call.
    2. Set the pointer to NULL immediately after freeing it to prevent accidental reuse.
    3. Do not retain an Info pointer across multiple calls. Copy the required fields into caller-owned variables before releasing it.

    A common incorrect pattern is to save every mode’s Info pointer in a loop and use the pointers after the loop, or to access Info->HorizontalResolution after releasing Info. Both cases access freed memory.

    The following pattern is safe:

    1. Status = Gop->QueryMode (Gop, Mode, &SizeOfInfo, &Info);
    2. if (!EFI_ERROR (Status)) {
    3. UINT32 Width = Info->HorizontalResolution;
    4. UINT32 Height = Info->VerticalResolution;
    5. ReleaseModeInfo (&Info); // Do not access Info after this point
    6. // Continue processing with Width and Height
    7. }

    Gop->Mode->Info and the Info returned by QueryMode are different memory blocks. The former is owned by the firmware and must not be passed to FreePool. Confusing these two structures can result in freeing memory that the caller does not own.

    5. GUID Matching and Status-Code Troubleshooting

    LocateProtocol searches for a protocol instance by GUID. In EDK2, the GOP GUID variable is named gEfiGraphicsOutputProtocolGuid and is declared in MdePkg/Include/Protocol/GraphicsOutput.h.

    Common GUID-related problems include:

    • Missing or inconsistent headers: The correct header may not be included, or the project may use an outdated definition from another codebase. Compilation usually exposes this problem, although a same-named macro or variable can sometimes hide it.
    • Missing protocol declaration in the module INF: The protocol consumed by the module should be declared in the [Protocols] section of the module’s .inf file. If it is missing, the build or link process may fail.
    • Firmware provides only the older protocol: Older firmware may provide EFI_UGA_DRAW_PROTOCOL without a GOP instance. In that case, LocateProtocol returns EFI_NOT_FOUND for GOP. The code must either fall back to UGA or clearly report the environment limitation.

    The following table summarizes common status codes:

    Call Status code Common meaning
    LocateProtocol EFI_NOT_FOUND No instance of the protocol exists, or the GUID or firmware support is incorrect
    QueryMode EFI_INVALID_PARAMETER The mode number is greater than or equal to MaxMode, or an argument is NULL
    QueryMode EFI_DEVICE_ERROR The device cannot return mode information
    SetMode EFI_UNSUPPORTED The current device does not support the requested mode
    SetMode EFI_DEVICE_ERROR The device failed to switch modes

    When EFI_NOT_FOUND appears, check the GUID and firmware environment before changing the rendering code.

    6. Serial Logging Template

    A UEFI environment may not provide a full debugger, so serial logs are one of the most reliable ways to observe execution. Use a consistent format and print one line for every important call, including the module name, step, status code, and key parameters.

    A useful format is:

    1. [Module][Step] status: parameter list

    In EDK2, the DEBUG macro can be used for logging. %r formats an EFI_STATUS as a readable name, %d is used for integers, and %Lx is used for 64-bit hexadecimal values. In a DEBUG build, the output is routed through the serial configuration used by DebugLib. When running under QEMU, -serial stdio can display serial output directly in the terminal.

    A complete log might look like this:

    1. [GOP][Locate] status: Success
    2. [GOP][Query] mode=0 resolution=1024x768 status: Success
    3. [GOP][Query] mode=1 resolution=1280x720 status: Success
    4. [GOP][Set] mode=1 status: Success
    5. [GOP][Set] base=0x80000000 size=0x00300000
    6. [GOP][Blt] status: Success

    These values are examples only. Actual output depends on the firmware and available modes.

    With consistent logging, the failure location is easier to identify. If the log stops before [GOP][Set], the mode-switch call may have failed or hung. If [GOP][Blt] fails, check the Blt parameters and confirm that framebuffer data was read at the correct time.

    7. AI-Assisted Troubleshooting: A Two-Pass Workflow and Checklist

    AI tools can help inspect code, map the call chain, and identify suspicious locations. Their conclusions must be reviewed manually and should not be treated as authoritative without verification.

    A two-pass workflow is useful:

    Pass one: make the program run correctly. Provide the code, complete serial logs, returned EFI_STATUS values, call sequence, and firmware or OVMF version. Ask the AI to map the call chain and identify where each memory block is allocated and released. Require every conclusion to include a code line reference and supporting evidence, such as a relevant UEFI specification requirement or header declaration. Fix one issue at a time and validate it immediately.

    Pass two: refine the implementation. After the program runs reliably, review performance, error propagation, and code structure.

    Do not provide private keys, signing keys, proprietary firmware images, or unpublished source code to an AI tool. Remove sensitive material before sharing debugging data.

    After each change, verify the following:

    • Every LocateProtocol call checks both Status and whether the returned pointer is NULL.
    • Every successful QueryMode call has a corresponding ReleaseModeInfo or FreePool.
    • No code accesses Info after it has been released.
    • The framebuffer base and size are read only after SetMode succeeds.
    • The code does not use new-mode framebuffer fields after SetMode fails.
    • Every important step has a corresponding status message in the log.
    • The module’s [Protocols] section declares the protocols it consumes.
    • Function signatures and status-code meanings are checked against the headers and the UEFI specification.

    Each item can be verified through code review or log inspection. AI-generated recommendations should be accepted only after they pass the same verification process.

    8. Summary

    • GOP is owned by the firmware. The caller may read Gop and Gop->Mode, but must not release them.
    • The caller owns the Info returned by QueryMode and must call FreePool after each use, then clear the pointer.
    • Read the framebuffer base and size only after SetMode succeeds. Do not use them after a failed mode switch.
    • Check every EFI_STATUS, log failures, and handle them explicitly.
    • Use a consistent serial-log format so that every step can be traced.
    • Validate AI-assisted troubleshooting conclusions against the UEFI specification, headers, source code, and runtime logs.