UEFI Graphics Development with AI Coding Assistants: A Review and Debugging Practice
This article walks through developing UEFI graphics applications with the help of AI coding assistants, using a real-world Tetris project as the backdrop. It explains why UEFI graphics programs often fail with black screens or silent exits, and lays out a repeatable two-round engineering workflow: first make the program run, then make it maintainable. You will find a Run checklist and a Refine checklist, a minimal graphics output protocol location example, practical fixes for two common failures (mode information pointer invalidation and wrong protocol GUIDs), a guide to serial-port debugging when no logs appear, a troubleshooting checklist for black screens and protocol failures, and optimization guidance for resource management, frame pacing, input handling, and rendering correctness. It also shows how to prompt AI for verifiable, prioritized review output, making it easier to work through issues one by one.
Introduction: Why Do UEFI Graphics Applications Keep Showing a Black Screen or Failing Silently?
UEFI (Unified Extensible Firmware Interface) runs before the operating system is loaded. At this stage there is no mature high-level graphics library, no standard runtime, and no visual debugging environment of the kind developers rely on in a normal OS. Many tasks that look trivial at the OS level—drawing a square, responding to a key press, or keeping a stable game loop running—become a combined test of low-level protocols, the memory model, display modes, and input handling once you drop into the UEFI stage.
Common pain points in UEFI graphics development include: How do I troubleshoot a black UEFI graphics screen? What if the serial log produces no output? Why does protocol location fail? Why does the program not crash, yet nothing appears on the screen? These problems are rarely a single point of failure. They usually result from the combined effect of the environment, protocol selection, pointer lifetimes, return-value checks, and log observability.
This article is based on a real scenario: taking over a modular but non-functional UEFI Tetris project and using an AI coding assistant to perform a code review, locate faults, and carry out a second round of optimization. The goal is not to get the AI to “write it right the first time,” but to establish a reusable engineering workflow: First make the program run, then make it maintainable; first build observability, then apply precise fixes.
Development Environment and Reproducible Prerequisites: Don’t Skip This Step
Before discussing AI-assisted review, you must define the development, build, and runtime environment for your UEFI application. Otherwise, even code that looks correct may fail to reproduce the problem because of differences in the image, firmware, or logging channel.
A typical UEFI application development environment can include the following parts:
- Development framework: commonly EDK2, used with the UEFI build system to compile a module or standalone application.
- Target architecture: for example X64, IA32, or ARM, which must match the firmware environment.
- Runtime environment: this can be OVMF + QEMU, real hardware, or a virtual machine firmware.
- Debug output: common approaches include serial logging, OVMF debug logs, platform POST codes, or an emulator and debugger when conditions allow.
- Input and display: a graphics application depends on the Graphics Output Protocol, while an input application depends on the Simple Text Input Protocol or the Extended Input Protocol.
For AI-assisted development, environment details are critical. It helps to have the AI answer the following questions first:
- Can the current project already build a bootable UEFI application or driver?
- Is the runtime QEMU, OVMF, real hardware, or another firmware platform?
- Is serial logging already producing output? If there is no output, check image loading, firmware configuration, and serial initialization first.
- Has the graphics display already successfully entered the UEFI Graphics Output mode?
- Is the current problem a boot failure, a protocol location failure, a mode-setting failure, no input response, or a rendering anomaly?
The clearer these answers are, the less likely the AI-generated code and troubleshooting suggestions will drift away from reality.
Methodology: Two Iterations—Run First, Refine Second
For complex low-level development, the “get it right in one shot” mindset is a trap. A safer approach is to split the task into two rounds: Round one is Run, with the goal of getting it working; round two is Refine, with the goal of stability, performance, and maintainability.
Round One: Run Checklist
Round one focuses only on “can the program reach a debuggable state”:
- The application entry executes, and its exit status code is observable.
- Key protocol location returns
EFI_SUCCESS, and the interface pointer is non-null. - The Graphics Output Protocol is located using the correct
gEfiGraphicsOutputProtocolGuid. - The return value, dimensions, and mode information from
QueryModeare checked. - After
SetMode, the mode information is queried again, or the mode data that must be retained is copied. - At least one clear-screen or simple rectangle draw can complete.
- The keyboard input protocol can be located, and key events can be polled or waited on.
- Serial logs can output key fields, not just the word “success.”
- Every critical failure path has a log, avoiding silent failures.
Round Two: Refine Checklist
Round two focuses on quality and stability:
- Mode information is re-acquired after a state change, avoiding reliance on an old pointer.
- Frame interval control has an explicit target, such as 30 FPS or 60 FPS, rather than an unconstrained busy wait.
- Input debouncing has a verifiable threshold, such as 80–150 ms debouncing or confirmation across consecutive frames.
- Memory allocation and release occur in pairs, with resource counts matching before and after entering and exiting the game.
- Release paths for handles, events, protocol interfaces, and other resources are complete.
- Render coordinates, colors, resolution, pixel format, and row stride match the actual mode.
- Magic numbers are replaced with constants or macros, and module naming and comments are maintainable.
- Logs and configuration are sanitized before sharing to avoid leaking environment information.
This kind of checklist suits AI collaboration better than a vague “optimize it a bit.” Each step can be verified, and it makes it easy to roll back quickly when something fails.
Round One: From Legacy Code to a Running Program
Step One: Have the AI Perform a Structured Code Review
When facing unfamiliar code, jumping straight into debugging is often inefficient. A more effective approach is to have the AI perform a structured review first and output a verifiable list of issues.
You can prompt the AI as follows:
Please read through the current UEFI project and review it module by module:entry point, graphics output, main loop, input handling, and resource management.Do not make large code changes directly. Output a list of issues, and each fieldmust include: issue, file, function, reproduction condition, and fix priority.Focus on risks that could cause a black screen, startup exit, protocol locationfailure, invalid pointers, or unresponsive input.
The benefit of this output format is that a problem is no longer a vague “it might crash”—instead, it can be traced to a file, a function, a reproduction condition, and a priority. Engineers can verify each item by priority rather than facing a pile of changes with no clear cause.
A Minimal Protocol Location Example
In UEFI graphics development, the Graphics Output Protocol is usually located through the graphics output protocol GUID. A common constant in EDK2 is gEfiGraphicsOutputProtocolGuid. A minimal example looks like this:
#include <Uefi.h>#include <Library/UefiBootServicesTableLib.h>#include <Library/DebugLib.h>#include <Protocol/GraphicsOutput.h>extern EFI_GUID gEfiGraphicsOutputProtocolGuid;EFI_STATUSEFIAPIUefiMain (IN EFI_HANDLE ImageHandle,IN EFI_SYSTEM_TABLE *SystemTable){EFI_STATUS Status;EFI_HANDLE Handle;EFI_GRAPHICS_OUTPUT_PROTOCOL *Gop;Handle = NULL;Gop = NULL;Status = gBS->LocateProtocol (&gEfiGraphicsOutputProtocolGuid,NULL,(VOID **)&Gop);if (EFI_ERROR (Status) || Gop == NULL) {DEBUG ((EFI_D_ERROR, "Locate GOP failed: %r\n", Status));return Status;}DEBUG ((EFI_D_INFO, "GOP located successfully\n"));return EFI_SUCCESS;}
Although simple, this code embodies three important habits: use the real protocol GUID, check the return status, and check whether the interface pointer is null.
Problem 1: The Program Exits Immediately at Startup—The Mode Information Pointer May Be Invalid
After the first version started, it exited before the interface even appeared. This kind of problem is very common in UEFI graphics development, and a typical cause is improper handling of the mode information pointer’s lifetime.
When setting the display mode, the Graphics Output Protocol usually first queries the mode information, then switches to the target mode. QueryMode returns a mode information structure that includes the resolution, pixel format, frame buffer address, and more. The important point is: whether the pointer returned by QueryMode remains valid for a long time may depend on the firmware implementation, the protocol implementation, and the calling context. Once you call SetMode or another interface that changes the display state, continuing to use a previously cached pointer carries risk.
So rather than vaguely saying “the frame buffer pointer becomes invalid,” a more accurate statement is: after a state change, do not assume you can rely on old query results or cached pointers.
A schematic version of the wrong tendency looks like this:
UINTN Size;EFI_GRAPHICS_OUTPUT_MODE_INFORMATION *Info;Status = Gop->QueryMode (Gop, ModeNumber, &Size, &Info);if (EFI_ERROR (Status)) {return Status;}// If Info is saved here and SetMode is called afterward,// reusing the old Info is risky.ModeInfoBackup = Info;Status = Gop->SetMode (Gop, TargetModeNumber);if (EFI_ERROR (Status)) {return Status;}// Do not assume ModeInfoBackup is still valid.UseResolution (ModeInfoBackup->HorizontalResolution);
A safer approach is: when you need to retain the mode information for a long time, copy it first; or call QueryMode again after executing SetMode.
UINTN Size;EFI_GRAPHICS_OUTPUT_MODE_INFORMATION LocalInfo;// Query the target mode.Status = Gop->QueryMode (Gop, TargetModeNumber, &Size, &Info);if (EFI_ERROR (Status) || Info == NULL) {DEBUG ((EFI_D_ERROR, "QueryMode failed: %r\n", Status));return EFI_UNSUPPORTED;}// If you need to keep it, copy to a local variable.CopyMem (&LocalInfo, Info, Size);// Set the mode.Status = Gop->SetMode (Gop, TargetModeNumber);if (EFI_ERROR (Status)) {DEBUG ((EFI_D_ERROR, "SetMode failed: %r\n", Status));return Status;}// Query again after setting to confirm the current state.Status = Gop->QueryMode (Gop, TargetModeNumber, &Size, &Info);if (EFI_ERROR (Status) || Info == NULL) {DEBUG ((EFI_D_ERROR, "Re-QueryMode failed: %r\n", Status));return EFI_UNSUPPORTED;}UseResolution (Info->HorizontalResolution, Info->VerticalResolution);
The general principle for fixing this kind of problem is: for any call that crosses a point where system state may change—such as setting a mode, reconfiguring a protocol, or reinitializing a device—handles, pointers, and state information cached before that call should be re-acquired or copied.
Problem 2: The Graphics Interface Doesn’t Appear—A Protocol GUID Is Misconfigured
After fixing the crash, the program no longer exits, but the screen is still pitch black. At this point, the second typical trap is using the wrong GUID during protocol location.
In UEFI, different protocols have different GUIDs. The Graphics Output Protocol should use the GUID corresponding to the graphics output protocol, not the GUID of an input protocol, a display protocol, or some other graphics-related protocol. If the wrong GUID is passed during location, LocateProtocol may fail, the interface pointer is null, and subsequent drawing naturally cannot execute.
A common misconception is: as long as you call functions related to the Graphics Output Protocol, you should be able to display something. In reality, you must first complete protocol location, mode setting, and use of the frame buffer before display can work.
During troubleshooting, you can add logs like these:
DEBUG ((EFI_D_INFO, "Locate GOP status=%r handle=%p\n", Status, Handle));DEBUG ((EFI_D_INFO, "Gop pointer=%p\n", Gop));
If Status is not EFI_SUCCESS, or Gop is null, prioritize suspecting the following:
- Whether the correct protocol header definition was used for the protocol GUID.
- Whether the current firmware or runtime environment has already installed this protocol.
- Whether there is an unmet protocol dependency.
- Whether the correct registration handle or a null value was passed when calling
LocateProtocol. - Whether the current image has the permissions or phase conditions required to run.
For a “black screen but no crash” problem, you should also continue to check:
- Whether
SetModesucceeded. - Whether the current mode is supported by the firmware or display device.
- Whether the resolution, pixel format, and frame buffer address match the display device.
- Whether an effective clear-screen or first draw was performed.
- Whether there is a pixel offset, a color format error, or an incorrect stride calculation.
Serial Debugging: Turning “Guessing the Problem” into “Looking at Evidence”
At the UEFI stage, serial logging is usually one of the key observability methods. It is not the only method, but it is very effective in many bare-metal or firmware environments. What really determines debugging speed is often not how accurately the AI guesses, but whether the program leaves behind enough evidence.
What If the Serial Port Produces No Logs?
If there are no logs on the serial port, troubleshoot in the following order:
- Confirm the image is loaded and executed by the firmware. If the application is not loaded, no logs will appear.
- Confirm the build artifact type is correct. Is it an EFI application, a driver, or a module? Does it meet the target firmware’s loading requirements?
- Confirm the debug logging library is available. In an EDK2 environment, check whether the
DEBUGmacro links to a suitable DebugLib. - Confirm the serial port has been initialized. If you use a serial library, you must complete serial initialization first; if the platform has no serial port at an early stage, use a platform-supported POST code or another logging mechanism.
- Confirm the QEMU or OVMF log configuration. For example, QEMU serial redirection, OVMF debug log options, and log file paths.
- Confirm the serial parameters match. Do the baud rate, data bits, stop bits, and parity bits match the host terminal?
- Confirm the log level is not being filtered out. Some build configurations may output only ERROR-level messages, making INFO logs invisible.
Key Log Fields
In UEFI graphics development, logs should not just say “entered function.” It is more valuable to record key state:
Status: the return status of an interface call.Handle: the protocol or device handle.Mode: the current or target display mode number.Resolution: the horizontal and vertical resolution.PixelFormat: the pixel format.Stride: the number of pixels per row or the byte span.FrameBufferBase: the frame buffer address, logged only after confirming the context is valid.FrameBufferSize: the frame buffer size.
Example logs:
DEBUG ((EFI_D_INFO,"GOP status=%r handle=%p\n",Status,Handle));DEBUG ((EFI_D_INFO,"QueryMode mode=%u size=%u\n",TargetModeNumber,Size));DEBUG ((EFI_D_INFO,"SetMode status=%r mode=%u\n",Status,TargetModeNumber));DEBUG ((EFI_D_INFO,"Mode info %ux%u format=%u stride=%u\n",Info->HorizontalResolution,Info->VerticalResolution,Info->PixelFormat,Info->PixelsPerScanLine));
When the serial log shows the program stopping after a certain protocol call, the problem scope shrinks from “the entire initialization flow” to a specific code segment. Build observability first, then talk about precise fixes.
Common Troubleshooting: Black Screen, No Logs, Protocol Failures
How Do I Troubleshoot a Black UEFI Graphics Screen?
Check in the following order:
- Whether the Graphics Output Protocol was located successfully.
- Whether
SetModereturned success. - Whether the queried resolution matches the display device.
- Whether the pixel format is correct, for example RGB or BGR.
- Whether the frame buffer address comes from valid mode information.
- Whether a clear-screen or first draw was performed.
- Whether the draw coordinates are out of bounds.
- Whether the stride calculation matches the resolution.
- Whether there is an incorrect color value or a pixel offset.
- Whether the log shows continuous frame updates rather than only initialization logs.
How Do I Investigate a Black Screen That Doesn’t Crash?
This kind of problem is usually not a null-pointer crash but rather drawing to the wrong target. Focus on checking:
- Whether protocol location really succeeded.
- Whether the mode was set successfully.
- Whether the drawing writes to the correct buffer.
- Whether the wrong pixel format was used.
- Whether the color was written to the wrong offset.
- Whether the screen was actually refreshed in the main loop.
What If the Serial Port Produces No Logs?
Prioritize checking:
- Whether the image is loaded.
- Whether the build is a DEBUG version.
- Whether DebugLib is linked correctly.
- Whether the serial port is initialized.
- Whether the QEMU/OVMF/real-hardware serial configuration is correct.
- Whether the log level is being filtered.
- Whether the platform supports serial output at the current stage.
Round Two: Refinement and Optimization
Only after the code runs does the quality phase begin. The goal of the second round is not simply to “optimize the code,” but to move the program from “it runs” to “stable, fast, and clean.”
Resource and State Management
Resource management must be quantifiable:
- Memory allocated on each game entry is released on game exit.
- The state machine resets before each new game.
- The allocation count and release count are equal.
- Event handles, input handles, graphics protocol interfaces, and other resources are released correctly when no longer needed.
- After running for a long time, the log should not show a continuously growing unreleased count.
You can record this in the log:
EnterGame allocCount=%u freeCount=%uExitGame allocCount=%u freeCount=%u
If allocCount is still greater than freeCount after exit, there is a leak risk.
Main Loop and Frame Rate Control
The UEFI environment has no OS scheduler, so the main loop must control its own pacing. If the main loop busy-waits without limit, it may saturate the CPU, causing input latency or system instability.
You can set a target:
- Target 30 FPS: a frame interval of about 33.3 ms.
- Target 60 FPS: a frame interval of about 16.7 ms.
In the implementation, you can use a timer, an event, or a simple timestamp comparison to avoid fully spinning. You can log:
Frame interval avg=%u ms target=%u ms
If the average frame interval significantly exceeds the target, rendering or logic is taking too long; if the frame interval is 0 or the main loop spins at high frequency, throttling is missing.
Input Handling Robustness
Common keyboard input problems include key repeats, jitter, multi-key conflicts, and lost events. Recommendations:
- Set a debounce window for repeated key presses, for example 80–150 ms.
- For continuous-movement inputs, use “confirmation across consecutive frames” instead of a single scan.
- Log the key scan code and repeat count to help determine whether it is input jitter or a logic error.
- Avoid blocking on a single key press in the main loop unless the interaction model clearly requires it.
Example log:
Key scanCode=0x%02x repeat=%u debounceMs=%u
Rendering Correctness
Rendering problems are often related to assumptions about resolution. Do not hard-code a resolution in the code, such as 1024x768, unless you have confirmed the target mode. Instead, obtain the following from the QueryMode result:
- Horizontal resolution.
- Vertical resolution.
- Pixel format.
- Pixels per row or byte span.
- Frame buffer size.
When rendering, check:
- Whether coordinates are within the screen bounds.
- Whether the pixel index is calculated using the stride.
- Whether the color channel order matches the pixel format.
- Whether scaling and offsets are reasonable across different modes.
Readability and Maintainability
The second round should also address code with low maintainability:
- Replace magic numbers with constants, such as key codes, color values, and frame intervals.
- Add comments to key functions, explaining inputs, outputs, and side effects.
- Unify the error-handling style so that all key calls check their return status.
- Separate “debug output” from “formal logging” so that excessive logs don’t affect performance.
Verifiable Output from AI Review Prompts
To reduce vague suggestions from the AI, you can require table output. For example:
Please review the current project and output a Markdown table. The columns must include:issue, file, function, reproduction condition, and fix priority.Priorities are divided into P0, P1, and P2.P0 means startup failure or the program cannot run.P1 means abnormal functionality while the program still runs.P2 means maintainability, performance, or code quality issues.
This kind of result is easier for engineers to work through item by item, and it makes subsequent regression testing more straightforward.
Practical Takeaways: Put AI to Work in Key Engineering Steps
Looking back over the whole development process, several lessons can be distilled:
- Review first, debug later. Having the AI produce a structured understanding of the code first can turn troubleshooting from “aimless” into “targeted.”
- Prioritize observability. In UEFI and low-level environments, logs, return statuses, handles, and mode information are the foundational evidence for diagnosing problems.
- Watch out for implicit state invalidation. After a call that crosses a state change, cached pointers and handles need to be re-acquired or copied.
- Check every return value. Protocol location, mode queries, mode setting, memory allocation, and input event acquisition should all be checked for success and traced in the logs.
- AI is a collaborator, not someone who washes their hands of it. The AI can accelerate review, generate code, and propose hypotheses, but the final judgment of correctness, the design of observability methods, and the verification loop still rest with the engineer.
- Legacy code governance needs to move forward step by step. For code with low maintainability, first establish test paths and logging, then refactor incrementally, avoiding a one-time large-scale rewrite that leads to issues with no clear cause.
- Sanitize logs before sharing. Serial logs, configuration output, or debug information may contain device paths, environment variables, or internal addresses, so sensitive content should be removed before sharing externally.
Given a consistent test environment, hardware display, and firmware implementation, this “review—run—diagnose—optimize” methodology can significantly improve the efficiency and predictability of UEFI graphics development. When facing differences in real hardware, display devices, or firmware implementations, you still need to combine serial logs, platform documentation, and observed behavior for regression verification.
