Fixing a Crashing UEFI Graphics Application with an AI Coding Assistant: From Black Screen to Stable GOP Rendering
This article walks through a real rescue of a UEFI graphics game that would not run on real hardware or in emulation. Using an AI coding assistant alongside serial logs and target-machine verification, it shows how to fix two fatal defects — a crash caused by reusing a stale graphics mode structure after SetMode, and a black screen caused by locating the wrong protocol GUID — and then harden the program for stable, performant rendering. It covers EDK2/QEMU/OVMF toolchain setup, the checklist to give an AI for static review, correct Graphics Output Protocol frame buffer handling and QueryMode buffer lifetimes, pixel format and PixelsPerScanLine pitfalls, optimization options such as dirty rectangles, double buffering and Blt, and a reusable "hypothesis — verify — correct" workflow for firmware and kernel-mode debugging.
1. What Is a UEFI Graphics Application, and Why Is It So Hard to Write and Debug?
A UEFI graphics program, in short, is an executable that runs in the motherboard firmware environment before the operating system starts. Using the Graphics Output Protocol (GOP) that UEFI exposes, developers can drive the screen directly, read key presses, and build small games like Breakout or Tetris. That makes these projects a classic test of skill for embedded and firmware developers.
Where is the difficulty? Mainly in three areas:
- No operating system underneath you. Memory management, graphics output, and input handling are all your responsibility; a single wild pointer can reboot the machine outright.
- Almost no debugging facilities. In most cases you depend on serial logs — textbook black-box debugging.
- Extremely low fault tolerance. A mistake anywhere in pointer lifetimes, protocol addressing, or return-code handling does not produce an error dialog; it produces a hang or a crash.
In recent years, LLM-powered coding assistants have become a practical tool for developers facing hard problems. They can review code quickly, narrow down suspicious logic, and suggest fixes. But the real-world situation is often this: you are handed someone else’s code, it reads cleanly and looks well structured, yet on real hardware it either fails to compile or crashes the moment it starts. How much can AI actually help here?
This article follows a real rescue attempt: using an AI coding assistant to progressively fix an unrunnable UEFI graphics mini-game. The whole process follows one principle: the AI proposes hypotheses and repair directions, serial logs supply evidence, and the real machine or the emulator delivers the final verdict.
⚠️ Risk warning
Experiments at the UEFI and firmware level can cause the following problems: the system failing to boot, data loss, or in the case of mistaken flashing or accidental modification of firmware variables, damage to the device.
- Before you begin: validate on a virtual machine (for example QEMU + OVMF) or a dedicated test machine first. Back up important data and record your current BIOS version and settings.
- For real-hardware validation: prefer platforms with recovery features such as BIOS Flashback or a dual BIOS, and have serial logging tools and a rollback plan ready. Debugging unverified firmware code on your primary or production machine is not recommended.
2. Setting Up the Toolchain: Building Your Judging Panel First
Before debugging starts, get the validation environment in place. The table below is a starting point; adjust it to your own platform and versions:
| Stage | Recommended tools | Purpose |
|---|---|---|
| Build | EDK2 (EDK II build framework) + GCC5 toolchain | Build the UEFI application and produce a loadable .efi file |
| Emulated run | QEMU + OVMF firmware image | Fast repeated validation, with serial logs printed straight to the terminal |
| Real-hardware run | UEFI Shell or a boot entry on a USB stick + serial logging | Final verdict; some motherboards can emit logs over USB-to-serial adapters or an on-board debug header |
| Version control | Git history for every change | Guarantees “one problem changed at a time” and makes rollback trivial |
EDK2 and OVMF move quickly, so record the versions or commit hashes you used to keep results reproducible. Also, if nothing appears on screen long after SetMode, try adding a short delay after SetMode succeeds (for example gBS->Stall()). Some firmware needs time for the display path to settle after a mode change; measure the actual delay on your target platform.
3. Round 1: Static Review with AI and Two Fatal Defects
3.1 Have the AI Review First, Instead of Writing New Code
You have a structurally complete UEFI game project (entry point, main loop, game logic, rendering, and input modules all present), but it either fails to build or crashes on launch. The instruction to give the AI at this point is not “write me a new version.” It is:
You are a senior UEFI firmware development engineer. Review the following code (EDK2-based; target platforms are QEMU/OVMF and an XX model motherboard; UEFI specification 2.x). Perform static analysis only — do not rewrite the code. Check the items in the checklist below one by one and output a Markdown table with these columns: index | file:line | risk level (high/medium/low) | cause | suggested fix | verification method. Focus on: the entry signature, whether the old ModeInfo is reused after SetMode, the lifetime of the QueryMode buffer, the GUID and return codes of LocateProtocol, memory deallocation, and serial log checkpoints. Mark anything you cannot confirm as “requires real-hardware verification.”
| Check item | What to check | Typical symptom |
|---|---|---|
| Entry signature | An EDK2 application entry should be EFI_STATUS EFIAPI UefiMain(EFI_HANDLE ImageHandle, EFI_SYSTEM_TABLE *SystemTable), not int main() |
Build failure, or immediate exit after loading |
| Mode selection (SetMode) | Is the mode number taken from an enumeration query rather than hard-coded? Is the return value checked? | On-screen resolution does not match expectations |
| Mode query (QueryMode) | Is ModeInfo reused across SetMode? Is SizeOfInfo initialized? Is the buffer freed in pairs? | Crash on startup, bad addresses |
| Protocol location (LocateProtocol) | Does the GUID correspond to the graphics output protocol? Is the return status checked? Was it mistaken for the EDID protocol? | Black screen with no error reported |
| Error-code handling | Is EFI_ERROR(Status) checked after every Boot Services call? |
Runs while broken, then crashes randomly later |
| Memory deallocation | Does every AllocatePool/AllocateZeroPool have a matching FreePool? | Memory grows continuously after repeatedly creating and destroying objects |
| Serial log checkpoints | Are key stages instrumented: entry → protocol location → SetMode → buffer acquisition → first frame drawn → main loop? | Once it fails, you cannot tell which step it stopped at |
The AI will usually produce a dozen or more “suspicions” very quickly. Stay calm here: do not treat the AI’s judgement as final. In firmware development, the environment itself is the most honest judge, and every single item should be verified in the emulator or on real hardware.
3.2 Defect One: The Program Crashes Immediately on Launch
Symptom: The program prints “entering the game main loop” over serial and then exits right away — the classic crash-on-start case.
Verification: Have the AI add numbered, status-code-bearing logs at the key checkpoints — entry, protocol location, mode selection, first-frame drawing — then watch the serial output to see which step is the last one to complete. The result: no output appeared after the GOP SetMode call, so the crash point is in the render initialization stage.
Further inspection showed that the rendering module saved the ModeInformation pointer obtained before SetMode into a global variable, and after switching modes it kept reading frame buffer information from it:
// Broken: reusing the old ModeInfo after SetModeStatus = GraphicsOutput->SetMode(GraphicsOutput, DesiredMode);FrameBufferBase = ModeInfo->FrameBufferBase; // ModeInfo was obtained before SetMode
After re-reviewing the code with the AI and checking the EDK2 sources, there are actually two problems here:
- Lifetime problem: The ModeInformation structure is owned by the firmware driver. After a mode switch, the memory it points to may be re-laid out or invalidated, so reading it is a use of a dangling pointer.
- Field ownership problem:
EFI_GRAPHICS_OUTPUT_MODE_INFORMATIONhas noFrameBufferBasefield at all. The frame buffer base address and size live in theEFI_GRAPHICS_OUTPUT_PROTOCOL_MODEstructure — that is,GraphicsOutput->Mode->FrameBufferBaseand->FrameBufferSize.
The fix: after SetMode succeeds, read the current frame buffer information through GraphicsOutput->Mode. In an EDK2 environment this is the most direct approach, with the clearest lifetime:
// Correct: read frame buffer info from the GOP mode block after SetMode succeedsEFI_GRAPHICS_OUTPUT_PROTOCOL *GraphicsOutput;EFI_STATUS Status;UINT8 *FrameBuffer;Status = gBS->LocateProtocol(&gEfiGraphicsOutputProtocolGuid, NULL,(VOID **)&GraphicsOutput);if (EFI_ERROR(Status) || GraphicsOutput == NULL) {// Always handle the error and return first; never continue with a NULL pointerreturn Status;}Status = GraphicsOutput->SetMode(GraphicsOutput, DesiredMode);if (EFI_ERROR(Status)) {return Status; // SetMode fails if the mode is unsupported; fall back to a default mode or abort}// After SetMode succeeds, GraphicsOutput->Mode is maintained by the GOP driver,// and its contents always match the active modeFrameBuffer = (UINT8 *)(UINTN)GraphicsOutput->Mode->FrameBufferBase;// Verify the pixel format before drawing (BGR 32-bit is used here as an example;// other formats need their own conversion)// Many platforms support PixelBlueGreenRedReserved8BitPerPixel, where 0x00FFFFFF is whiteif (GraphicsOutput->Mode->Info->PixelFormat !=PixelBlueGreenRedReserved8BitPerPixel) {return EFI_UNSUPPORTED; // Adjust the drawing logic per pixel format, or fail explicitly}
If you really do need to call QueryMode — for example to enumerate every supported mode, or to query a mode that is not currently active — here is the complete form. The lifetime of the mode information buffer works as follows:
- SizeOfInfo: initialize to 0 before the call.
- ModeInformation: allocated by the driver and, per the UEFI specification (2.x), to be released with FreePool after use.
- Platform-specific implementations: a few implementations return a pointer to internal driver data. In that case, follow the actual convention of the driver source matching your EDK2 version, and do not free blindly.
- Reuse across SetMode: whichever form you use, do not save the mode information pointer and reuse it across SetMode.
// When you need to enumerate or query other modes: full QueryMode usageUINTN SizeOfInfo = 0; // Must be initialized before the callEFI_GRAPHICS_OUTPUT_MODE_INFORMATION *ModeInfo = NULL;// 1. Query the required buffer size with SizeOfInfo=0 and ModeInfo=NULLStatus = GraphicsOutput->QueryMode(GraphicsOutput, DesiredMode,&SizeOfInfo, NULL);if (Status == EFI_BUFFER_TOO_SMALL && SizeOfInfo > 0) {// 2. Allocate a buffer of the reported sizeStatus = gBS->AllocatePool(EfiBootServicesData, SizeOfInfo,(VOID **)&ModeInfo);if (EFI_ERROR(Status)) {return Status;}// 3. Query again to retrieve the details of that modeStatus = GraphicsOutput->QueryMode(GraphicsOutput, DesiredMode,&SizeOfInfo, &ModeInfo);if (EFI_ERROR(Status)) {gBS->FreePool(ModeInfo);return Status;}// 4. Read resolution, PixelsPerScanLine, pixel format, etc. from ModeInfo here// The frame buffer base address and size should still come from GraphicsOutput->Mode// 5. Free it when done to avoid a memory leakgBS->FreePool(ModeInfo);}
After the fix and a rerun, the program no longer crashed and entered the main loop normally. The lesson from this round is typical: in a kernel-mode environment where resource lifetimes are already fuzzy, “reusing an old pointer” is one of the most easily overlooked and most fatal classes of bug. And that is exactly the kind of problem an AI is good at catching through static review.
3.3 Defect Two: It Runs, but Nothing Appears on Screen
Symptom: The program no longer crashes and the serial log keeps flowing, but the screen stays pitch black and the graphical interface never appears. This “alive but invisible” class of problem is equally common in firmware development.
Verification: Feeding the symptom set “it runs, logs look normal, screen is black” back to the AI shifts its attention to how the graphics output protocol is obtained. Inspection revealed that the code used the GUID of an EDID-related (display capability description) protocol instead of the graphics output protocol’s own GUID. The handle that LocateProtocol returned is therefore nothing like the expected GOP interface, and every subsequent frame buffer operation fails.
UEFI addresses its services by protocol GUID (globally unique identifier), and firmware contains more than one display-related GUID: some identify the graphics output protocol itself, some identify EDID-related protocols, and there is also the legacy UGA drawing protocol. Pick the wrong one and you get back a handle that is not what you expected.
// When locating the graphics output protocol, use the graphics output protocol's own GUIDStatus = gBS->LocateProtocol(&gEfiGraphicsOutputProtocolGuid, // the correct protocol GUIDNULL,(VOID **)&GraphicsOutput);if (EFI_ERROR(Status)) {// If the protocol is not found, report the error explicitly and stop;// do not continue executingreturn Status;}
There is also an implicit best practice here: every LocateProtocol call must have its return status checked. In a firmware environment, a protocol can fail to resolve because the platform does not support it or the driver has not been loaded. Ignoring the error code merely postpones the problem until it surfaces as a crash, which massively increases the cost of investigation.
You can additionally have the AI list every GUID used in the project and check each one against the definitions in the EDK2 headers (for example under MdePkg/Include/Protocol/). This step is also well suited to handing over to the AI. After correcting the GUID and adding the missing error checks, the graphical interface finally rendered properly. At this point the program had moved from “does not run at all” to “does run.”
4. Round 2: From “It Runs” to “It Runs Stably and Well”
The first round’s only goal was “it runs.” The second round shifts to refinement and optimization. In an environment like UEFI, where resources are constrained and fault tolerance is minimal, refinement matters far more than in ordinary application development. It usually centers on four lines of work:
- Robustness hardening: add return-code checks to every protocol call and memory allocation, turning “silent failure” into “explicit error” and preventing the program from running while broken.
- Performance optimization: reading and writing the frame buffer pixel by pixel at a given resolution gets expensive fast as resolution grows, so the amount of data written needs targeted reduction.
- Resource management: verify that dynamically allocated memory is released promptly and that long-running sessions do not leak.
- Observability: add instrumentation such as frame rate statistics and key timing measurements to the serial log so maintainers can see at a glance where the program is stuck.
In this phase the coding assistant can act as a “code refactoring advisor” and a “performance bottleneck analyst”: removing duplicated code without changing behavior, or proposing optimization approaches for a specific hot function.
A comparison of common graphics optimization options:
| Approach | How it works | When it applies | Main cost | Verification metric |
|---|---|---|---|---|
| Dirty rectangles | Redraw only the regions that changed | Few moving elements, localized changes (for example only the ball and paddle move) | Coordinate mapping is complex and easy to get incomplete | Pixels written per frame, visual artifacts left behind |
| Double buffering | Draw a complete frame in a memory buffer, then blit it to the frame buffer as a whole | Frequent full-screen refreshes, no tearing allowed | One extra frame worth of memory | Frame time, presence of tearing |
| Character/sprite caching | Pre-render glyphs and patterns into pixel buffers and reuse them | Lots of text, repeated primitives | Extra cost during the pre-generation stage | First-frame time, per-frame time |
| Blt instead of direct writes | Submit a buffer via BltBufferToVideo |
Frame buffer unavailable, or cross-platform compatibility is needed | Fixed overhead per call | Target platform compatibility list, frame rate |
Note this: performance changes must be quantified and validated on the target real hardware. Behavior in QEMU says nothing definitive about real hardware, and whether an AI-proposed optimization actually helps must be settled by measured data, not by whether the code “looks more elegant.”
5. FAQ: High-Frequency Failure Symptoms in UEFI GOP Debugging
| Problem | First things to check | Key notes |
|---|---|---|
| The graphics program shows a black screen but the main loop is running | Frame buffer address, pixel format, mode number | After SetMode succeeds, verify GraphicsOutput->Mode->FrameBufferBase and the pixel format |
| LocateProtocol returns EFI_NOT_FOUND | Whether the GUID is correct, whether the driver is loaded | Check with the drivers and devices commands in the UEFI Shell; GOP is normally provided directly by the firmware |
| Screen shows corrupted graphics, skewed rows, or a tilted image | Row stride and pixel format | Compute the row offset with Mode->Info->PixelsPerScanLine; do not substitute the display width |
| Nothing refreshes after SetMode | Whether mode information is re-read, whether a redraw happens | SetMode typically clears the screen and resets the frame buffer, so you must re-acquire the address and redraw everything |
| No response after the program loads | Entry signature, file format, console output | The entry must be UefiMain and follow the EFIAPI calling convention; run it directly in the UEFI Shell and watch the output |
6. Methodology: Making AI Serve Low-Level Debugging
Abstracting the process above yields a workflow for AI-assisted debugging in firmware and kernel-mode development scenarios:
- Review before writing: given existing code, first have the assistant produce a structured review and an issue list, then work through fixes one at a time instead of rewriting from the start.
- Log-driven, verified on real hardware: the AI proposes hypotheses and investigation directions, serial logs supply the facts, and the real machine delivers the verdict. All three are indispensable.
- Focus on high-risk patterns: pointer lifetimes, protocol addressing (GUIDs), error-code checks, and call ordering are the four categories that keep recurring in firmware development, and they should be the priority for both AI review and manual inspection.
- Small steps, each one verifiable: change one problem at a time and run a validation immediately, so that stacking multiple changes cannot leave you unable to tell which one introduced the new fault.
- Judge optimizations by measurement: whether to adopt the AI’s refactoring and optimization suggestions should be decided by quantitative results on real hardware.
6.1 Long-Tail Q&A: Common Questions About AI-Assisted UEFI Graphics Debugging
- What is the order of investigation for a black screen? Verify layer by layer: is serial output present → did LocateProtocol succeed → did SetMode succeed → frame buffer address and pixel format → the actual writes.
- How do you handle a LocateProtocol failure? Check whether the GUID corresponds to the graphics output protocol, use the
driversanddevicescommands to confirm the driver is loaded, and check the return code. - Why does the frame buffer become invalid? The most common cause is reusing an old pointer across SetMode; switching to the valid address for the current mode resolves it.
- How do you refresh the screen after SetMode? First check the SetMode return status, then re-acquire the frame buffer address from
GraphicsOutput->Mode, then redraw everything. - What does this apply to? The workflow targets UEFI applications in an EDK2 environment, using the QEMU/OVMF emulator and serial logging; behavior may differ on other firmware frameworks or platforms and should be verified against their respective interface documentation.
During debugging, keep an “hypothesis — verification — correction” record table to build up a chain of evidence. It makes backtracking easy, and it is also convenient to hand the organized record back to the AI for a retrospective:
| # | Symptom | Hypothesis | Verification method | Evidence (log/result) | Correction and conclusion |
|---|---|---|---|---|---|
| 1 | Exits immediately after printing the main-loop log | Old ModeInfo was reused after SetMode | Serial log + code walkthrough | Log stops after SetMode | Read from Mode->FrameBufferBase instead; no more crash |
| 2 | Main loop runs normally but the screen is black | Wrong GUID used when locating GOP | Code walkthrough + logs | Protocol location fails | Switched to gEfiGraphicsOutputProtocolGuid; display works |
If you want to roll this workflow out to a team, you can hook build/compile, version control, and log retention into a CI pipeline that compiles automatically on merge and archives serial logs from each run centrally. That both speeds up verification and leaves a traceable record for retrospectives.
It is worth adding that tasks with this kind of barrier to entry demand more from the developer’s own low-level knowledge: you must be able to judge whether the explanation the AI gives actually holds up, and correct it promptly when it is wrong. An AI coding tool is more like an “amplifier” — what it amplifies is the developer’s own capability and judgement, not a replacement for them.
7. Conclusion
Back to the original question: when an unrunnable UEFI graphics program is placed in front of us, how much can an AI coding assistant really help? The answer is that it can significantly accelerate code review, defect localization, and repair attempts, freeing the developer from a large amount of mechanical investigation work — but the actual technical judgement, environment validation, and final decision remain in the hands of a developer who understands the low level.
From “does not run” to “runs stably and runs well,” the essence of that path is combining the AI’s generative capability with the developer’s deep understanding of the system into a “hypothesis — verify — correct” loop. Whether you are dealing with Breakout inside firmware, an operating system kernel, or a complex enterprise system, this methodology of “the AI proposes hypotheses, the environment judges, and the human signs off” is worth serious practice for any developer who cares about engineering quality.
