UEFI Firmware Development with AI Assistants: A Practical Debugging Walkthrough
This article walks through a real firmware development task where AI coding assistants were used to build and debug a modular UEFI graphics application. It explains why firmware development is unusually hard for AI (high constraints, tight hardware coupling, weak observability), then describes a two-round workflow: first get the code running, then refine it. Key technical takeaways include avoiding wild frame buffer pointers after SetMode, correctly locating the Graphics Output Protocol via its GUID, and building observability with serial logging. The article also covers common UEFI/BIOS graphics pitfalls, testable acceptance criteria, and lessons on how to divide work between human engineers and AI. Readers will learn practical debugging patterns for low-level firmware code and how to validate changes safely in QEMU/OVMF before touching target hardware.
Why Firmware-Level Development Is a Hard Problem for AI
UEFI (Unified Extensible Firmware Interface) and BIOS development differ fundamentally from application-level software development. There is no OS scheduler, no rich standard library, and no mature debugger attach capability. Code typically runs directly on bare metal or inside a firmware environment, where a single null pointer access or a wrong mode switch can reboot a device, black-screen it, or drop it into an unpredictable state.
Because of this, firmware development has three defining traits: high constraints, strong hardware coupling, and weak observability. Many errors do not surface as clean exceptions the way ordinary programs do. Instead they show up through serial logs, graphical glitches, device reboots, or even a silent “hang.” That is exactly what makes firmware a proving ground for the real capabilities of an AI coding assistant.
This article is based on a real task. First, a smart coding tool was used to generate a modular graphics application framework, but because of environment configuration issues and deviations in protocol call details, the code would not run. Then a different AI coding assistant took over the leftover code to perform review, root-cause analysis, fixing, and iterative optimization. The point here is not to oversell AI’s capabilities, but to summarize how humans and AI can reasonably divide work in low-level development.
Workflow Design: Two Rounds, Run First, Then Refine
Low-level tasks have long chains and dense failure points. If you ask an AI to simultaneously deliver architecture, rendering, input handling, performance, and stability from the start, you easily end up with results that “look complete but cannot actually run.” A more reliable approach is to split the work into two rounds:
Round 1 solves “can it run.” The goal is to move the program from not running at all to being able to boot, initialize, and enter the main loop.
Round 2 solves “does it run well.” Building on a working baseline, the goal is to eliminate out-of-bounds accesses, tune the refresh cadence, fill in missing input responses, and improve maintainability.
| Stage | Input | Start Condition | Exit Criteria | Output |
|---|---|---|---|---|
| Round 1: Run | Original code, target environment, serial logs | Program won’t run or exits abnormally after startup | No null pointers, no protocol lookup failures, can enter the main loop | Bootable version, issue list, serial logs |
| Round 2: Optimize | Working version, acceptance metrics, test tools | Round 1 passed | Frame rate, input, and boundary access meet the acceptance table | Stable version, test records, optimization notes |
The advantage of this layered approach is that each round has clear boundaries. Whether a problem lies in protocol lookup, mode setting, or rendering logic can be quickly determined from the logs. In this practice, the layered strategy helped reduce the problem to small, individually verifiable goals. However, the effectiveness depends on log quality, the verification environment, and task complexity, and should not be understood as guaranteed to work for every project.
Round 1: Get the Code Running First
Step 1: Have the AI Perform a Code Review First
The first instruction was deliberately kept simple: review this code and list potential problems, but do not modify anything yet. The value of this step is that it lets the model build an overall mental model of the codebase first.
The AI checked the entry function, main loop, game logic, rendering module, and input handling module by module, and produced a prioritized issue list. Compared with directly asking an AI to “fix it until it runs,” reviewing first is more reliable. It makes implicit design flaws explicit and provides a roadmap for the debugging that follows.
It is recommended to have the AI output a problem-cause-fix-verification mapping table:
| Problem | Possible Cause | Fix Direction | Verification |
|---|---|---|---|
| Crash right after startup | Stale frame buffer pointer | Re-fetch the frame buffer after SetMode | No serial errors, screen refreshes |
| GUI does not appear | Wrong GUID configuration | Use the correct protocol GUID and check the return code | LocateProtocol returns EFI_SUCCESS |
| Rendering anomalies | Out-of-bounds access or mode mismatch | Validate resolution and buffer size | Boundary tests pass |
| Input does not respond | Missing event handling | Complete the key event mapping | Key test matrix passes |
Problem 1: Program Crash and a Wild Frame Buffer Pointer
After the review, a trial run began. The program started but exited immediately after printing the initialization logs. Compared with the original code, this was already a step forward, but still short of “it runs.”
To improve observability, I had the AI add finer-grained debug output and continuously print execution progress over serial. The logs showed that the problem occurred right after the graphics output protocol call.
The root cause was a classic firmware trap: many developers first call QueryMode to query the display mode, then call SetMode to set the mode. QueryMode typically returns mode information used to understand the resolution, pixel format, and other descriptors; it should not be treated as a stable frame buffer handle that remains valid after a mode switch. Once SetMode is called, the graphics mode is reinitialized and any previously cached address or structure may become invalid. Continuing to access the old address means accessing invalid memory, which is what is commonly called a wild pointer.
The correct approach is not to reuse the old frame buffer information from before SetMode, but instead, after SetMode succeeds, to re-fetch the frame buffer base address and size from the current valid gop->Mode or a valid handle provided by the platform.
Sample code:
#include <Uefi.h>#include <Protocol/GraphicsOutput.h>EFI_STATUS Status;UINTN Size = 0;EFI_GRAPHICS_OUTPUT_MODE_INFORMATION *Info = NULL;UINT32 ModeIndex = 0;EFI_PHYSICAL_ADDRESS FrameBufferBase;UINTN FrameBufferSize;// QueryMode is typically used to query mode information, and should not serve as a// stable frame buffer reference after SetModeStatus = gop->QueryMode(gop, ModeIndex, &Size, &Info);if (EFI_ERROR(Status) || Info == NULL) {DEBUG((DEBUG_ERROR, "QueryMode failed: %r\n", Status));return EFI_ABORTED;}// Set the graphics mode; the return status must be checkedStatus = gop->SetMode(gop, ModeIndex);if (EFI_ERROR(Status)) {DEBUG((DEBUG_ERROR, "SetMode failed: %r\n", Status));return Status;}// After SetMode succeeds, obtain the frame buffer from the current valid mode structureif (gop->Mode == NULL || gop->Mode->FrameBufferBase == NULL) {DEBUG((DEBUG_ERROR, "FrameBufferBase is NULL after SetMode\n"));return EFI_DEVICE_ERROR;}FrameBufferBase = gop->Mode->FrameBufferBase;FrameBufferSize = gop->Mode->FrameBufferSize;DEBUG((DEBUG_INFO, "FrameBuffer base = 0x%lx, size = 0x%lx\n",FrameBufferBase, FrameBufferSize));// Draw using the valid frame bufferPaint(FrameBufferBase, FrameBufferSize);
There are three key checks here:
- Whether QueryMode succeeded and whether the returned structure is null.
- Whether SetMode succeeded; drawing must stop if it fails.
- Whether frame_buffer is null after SetMode, to avoid painting directly.
Low-level code cannot rely on the assumption that “it usually won’t be null.” The serial log should print the mode number, frame buffer base, frame buffer size, and return status so you can quickly tell whether the problem occurs during protocol lookup, mode setting, or drawing.
Problem 2: Wrong Graphics Output Protocol GUID Configuration
The program no longer crashed, but the graphical interface still would not appear. After feeding the symptom back to the model, it analyzed the runtime results further and pointed to a failed Graphics Output Protocol lookup.
In the UEFI ecosystem, protocols are typically addressed by GUID. The common identifier for the Graphics Output Protocol is:
#include <Protocol/GraphicsOutput.h>EFI_STATUS Status;EFI_GRAPHICS_OUTPUT_PROTOCOL *gop = NULL;Status = gBS->LocateProtocol(&EFI_GRAPHICS_OUTPUT_PROTOCOL_GUID,NULL,(VOID **)&gop);if (EFI_ERROR(Status) || gop == NULL) {DEBUG((DEBUG_ERROR, "LocateProtocol GOP failed: %r\n", Status));return Status;}
One point deserves special attention: across different SDKs, different EDK II versions, and different platform packages, header file paths, global variable names, and the way protocol instances are obtained may vary slightly. When using them, refer to the specific SDK documentation and confirm that the header version, protocol GUID definition, and calling convention are consistent.
Common mistakes include:
- Using a GUID that is close but incorrect.
- Not calling LocateProtocol and dereferencing an uninitialized pointer directly.
- Not checking the return status of LocateProtocol.
- Calling the graphics protocol at the wrong stage.
- Mistaking a platform-private variable for the standard GOP instance.
After correcting the GUID reference and checking the return code, the graphics path was restored and the program truly came “alive.”
Round 2: From Running to Usable
Round 1 solved “can it run”; Round 2 moves into “does it run well.” The tasks in this stage include: eliminating out-of-bounds accesses at logical boundaries, optimizing the render refresh cadence, filling in missing input responses, and cleaning up redundant repeated computations.
Compared with Round 1, Round 2 relies more heavily on deep code understanding and refactoring ability, and it requires the developer to provide clear acceptance criteria. Otherwise, the AI is prone to make changes that “look like optimizations but cannot actually be verified.”
Before Round 2 begins, it is recommended to establish an acceptance table:
| Acceptance Item | Suggested Criterion | Recording Method |
|---|---|---|
| Frame rate threshold | At the target resolution, no lower than a set frame rate, e.g., 30 FPS | Serial statistics or log instrumentation |
| Input combinations | Cover arrow keys, confirm key, cancel key, and key combinations | Key matrix records |
| Replay count | Replay each key combination at least 50 times | Test case table |
| Crash count | Crash count for any combination must be 0 | Serial logs and reboot count |
| Boundary memory access | Do not access addresses outside the frame buffer range | Address range check logs |
| Serial log level | At least three levels: ERROR, WARN, INFO | Log template |
| Test environment | Prefer QEMU/OVMF or an isolated dev board | Environment and firmware version records |
For example, the original goal of “no key combination may cause a crash” is vague. It can be rewritten as a testable criterion:
“In the test key matrix, trigger any two-key combination 50 times consecutively; there must be no reboot, hang, or rendering corruption; the crash count in the serial log is 0, and ERROR logs do not exceed a preset baseline.”
Such acceptance criteria are more suitable to hand to an AI to execute, and also easier for a human to review.
Common Mistakes and Precautions
In UEFI/BIOS graphics development, the following problems are especially common:
- Caching the frame buffer address before SetMode and continuing to access it after SetMode.
- Mistaking the mode information returned by QueryMode for a valid frame buffer handle after SetMode.
- Not checking the return status of QueryMode, SetMode, or LocateProtocol.
- Using an incorrect or approximate GUID to locate a protocol.
- Not accounting for the frame buffer size changing when the resolution changes.
- Missing serial logs, leaving problems to be guessed from device reboots or black screens.
- Repeatedly trial-and-erroring directly on target hardware, without first validating in QEMU, OVMF, or an isolated environment.
Low-level crashes can affect device state. It is recommended to first validate in QEMU or on an isolated dev board, and to prepare a rollback plan: keep the original firmware, back up critical variables, prepare serial output, and avoid running unverified graphics code directly on production devices.
Engineering Lessons for Using AI Assistants Well
Drawing on this practice, a few lessons are worth adopting:
First, split tasks into layers. Separate “getting it to run” from “refining it.” Do not ask the AI to complete framework design, protocol calls, graphics rendering, and performance optimization all at once. Doing only one type of goal per round makes convergence easier.
Second, review before modifying. Have the model produce an issue list first, then start changing code. This makes it easier to catch architectural problems, protocol misuse, and lifecycle issues, and it also makes it easier for a human to step in and gatekeep.
Third, proactively improve observability. The low-level environment lacks graphical debugging tools, and serial logs are often the only reliable probe. You should require the AI to print status at key points: protocol lookup results, mode setting results, frame buffer address, frame buffer size, and error return codes.
Fourth, have humans gatekeep hardware-related assumptions. Assumptions about frame buffer lifecycle, protocol GUIDs, memory alignment, display modes, and pixel formats depend heavily on the specific hardware and firmware implementation. They must be verified against the SDK documentation and platform manuals, and cannot be left entirely to the model to guess.
Fifth, iterate rather than doing everything in one shot. Complex goals should be broken into multiple rounds of small-step verification. Each round needs clear pass criteria, such as “no longer crashes,” “GOP located successfully,” “SetMode returns EFI_SUCCESS,” and “no crash in the input matrix.”
Sixth, prioritize risk. Low-level code errors can directly affect device boot, display, or firmware state. The verification order should be: run in an isolated environment first, then gradually transition to the target device; ensure recoverability first, then pursue performance optimization.
Conclusion
Firmware-level development is a proving ground for the true quality of an AI coding assistant. It has no standard library or runtime to fall back on, and every defect is amplified by the bare-metal environment. Looking at this practice of moving from “won’t run” to “runs,” AI coding assistants already offer clear value in code review, problem localization, fix suggestions, and log completion. But for the critical assumptions that are strongly tied to hardware, they still cannot do without the judgment and verification of human engineers.
The truly efficient paradigm is not to hand the entire task to an AI, but human-AI collaboration: the AI drives progress, reviews, localizes problems, and generates candidate solutions; humans set standards, verify boundaries, confirm hardware assumptions, and control risk. Understanding and making good use of this division of labor is the key to applying AI coding capabilities to hardcore scenarios such as UEFI and BIOS.
