LLM-Assisted UEFI Debugging: A Practical Two-Stage Workflow
A two-stage workflow for using large language models to debug an existing UEFI graphics application: first resolve startup crashes, then refine protocol handling and validate regressions. The article covers Graphics Output Protocol discovery, memory ownership, mode changes, fallback behavior, and the review checks needed before merging model-generated patches.
Why Code That Compiles May Still Fail at Runtime
Low-level firmware development offers limited feedback. The runtime environment is constrained, debugging options are sparse, and a single mistake can leave a device unable to boot. Developers often have to reconcile specification requirements, serial logs, and actual hardware behavior.
In this environment, the most useful role for a large language model (LLM) is not to generate an entire program in one pass. A more practical approach is to use it for code review, testable hypotheses, and narrowly scoped debugging patches that progressively isolate problems in a controlled environment.
The example here involves an existing UEFI graphics application with a clear structure: an entry point, a main loop, rendering code, and input handling. On its first run, the application crashed immediately. Successful compilation established that its syntax and linking were broadly correct—not that its protocol calls, memory ownership, or hardware state transitions were valid.
A Two-Stage Repair Workflow
For this type of project, divide the work into two stages.
Stage 1: Get the application running. Review the code structure and critical call paths, add leveled logging, identify the first failure, and apply the smallest fix that can be verified.
Stage 2: Refine the implementation and run regression tests. Review Graphics Output Protocol acquisition, GUID matching, mode changes, fallback paths, resource release, exit cleanup, and boundary conditions. Turn these checks into a repeatable checklist.
Keeping changes small makes each iteration easier to diagnose. For every proposed patch, require the model to provide:
- The reason for the change.
- Its scope and likely impact.
- A verification method.
A developer or automated test process must validate these points before the patch is merged.
Stage 1: From Startup Crash to a Running Application
Begin with the entry point, protocol acquisition, mode queries, rendering initialization, and exit paths. Ask the model to check:
- Was the protocol acquired successfully?
- Are return values handled?
- When is mode information queried?
- Is a framebuffer address cached across a mode change?
- Can input polling block execution?
- Are allocated resources released on exit?
The result should be a prioritized issue list, not a vague statement that something “might be wrong.”
Next, add serial logging at key points: startup, protocol acquisition, mode query, mode setting, framebuffer acquisition, and entry into the main loop. The purpose is to identify the first failure point. In this case, execution stopped after a Graphics Output Protocol call, making that code the immediate focus.
Understand Protocol Memory Ownership
The critical issue was ownership of data returned or maintained by the protocol.
The QueryMode function of EFI_GRAPHICS_OUTPUT_PROTOCOL allocates a buffer, writes mode information into it, and returns it through the SizeOfInfo and Info parameters. The caller must release this buffer with FreePool after use. Info is valid only when QueryMode succeeds; a failure path must not free it as though it were a valid allocation.
SetMode changes the device’s current mode and updates the protocol’s internal Gop->Mode structure, including the mode number, Info pointer, FrameBufferBase, and FrameBufferSize. The caller may read this protocol-owned state but must not free it. After SetMode, previously saved mode data must not be reused.
A call can change the underlying state. Whether old data is still trustworthy matters more than whether its pointer appears valid.
The following example illustrates the call sequence only. Check production code against the UEFI implementation and specification version used by the project.
EFI_STATUSApplyGraphicsMode(EFI_GRAPHICS_OUTPUT_PROTOCOL *Gop, UINT32 Mode){EFI_STATUS Status;UINTN SizeOfInfo;EFI_GRAPHICS_OUTPUT_MODE_INFORMATION *Info = NULL;/* QueryMode allocates Info on success; the caller must free it.Info is not valid on failure. */Status = Gop->QueryMode(Gop, Mode, &SizeOfInfo, &Info);if (EFI_ERROR(Status)) {return Status;}if (Info->HorizontalResolution == 0 || Info->VerticalResolution == 0) {FreePool(Info);return EFI_UNSUPPORTED;}FreePool(Info);Info = NULL;Status = Gop->SetMode(Gop, Mode);if (EFI_ERROR(Status)) {return Status;}/* Read current protocol state after SetMode; do not reuse old data. */if (Gop->Mode == NULL || Gop->Mode->Info == NULL) {return EFI_DEVICE_ERROR;}/* Gop->Mode->Info is protocol-owned and must not be freed. */gFramebuffer = (UINT8 *)(UINTN)Gop->Mode->FrameBufferBase;gFramebufferSize = Gop->Mode->FrameBufferSize;gHorizontal = Gop->Mode->Info->HorizontalResolution;gVertical = Gop->Mode->Info->VerticalResolution;gPixelsPerLine = Gop->Mode->Info->PixelsPerScanLine;return EFI_SUCCESS;}
Three details matter:
- Release the buffer allocated by
QueryModeimmediately after use, then set the pointer toNULL. - After a successful
SetMode, read the framebuffer address, framebuffer size, and resolution again fromGop->Mode. - Check
Gop->Modeand itsInfopointer before dereferencing them.
During review, require the model to identify the owner of every pointer: protocol-internal state, a buffer allocated by QueryMode, or memory managed by the caller. Do not merge code with unclear ownership.
Stage 2: Refinement and Regression Testing
GUID Matching and Protocol Acquisition
An application may stop crashing yet still display no graphics. At that point, check both the protocol GUID and the handle used to acquire the protocol.
The standard Graphics Output Protocol GUID is declared in MdePkg’s GraphicsOutput.h as gEfiGraphicsOutputProtocolGuid. Reference the standard symbol rather than creating a duplicate GUID constant elsewhere. Firmware frameworks contain GUIDs with similar names but different purposes, making copy-and-paste mistakes easy.
GOP is normally installed on a graphics device handle, not the application’s own ImageHandle. Do not assume that calling HandleProtocol on ImageHandle will retrieve it.
For a system with a single display device, LocateProtocol can retrieve the first GOP instance:
EFI_STATUSGetGraphicsOutput(EFI_GRAPHICS_OUTPUT_PROTOCOL **GopOut){EFI_STATUS Status;EFI_GRAPHICS_OUTPUT_PROTOCOL *Gop = NULL;if (GopOut == NULL) {return EFI_INVALID_PARAMETER;}*GopOut = NULL;Status = gBS->LocateProtocol(&gEfiGraphicsOutputProtocolGuid, NULL, (VOID **)&Gop);if (EFI_ERROR(Status)) {DEBUG((DEBUG_ERROR, "GOP not found, guid=gEfiGraphicsOutputProtocolGuid, status=%r\n",Status));return EFI_UNSUPPORTED;}if (Gop == NULL) {return EFI_DEVICE_ERROR;}*GopOut = Gop;return EFI_SUCCESS;}
On systems with multiple display devices, the instance returned by LocateProtocol may not be the intended one. Use gBS->LocateHandleBuffer with ByProtocol to enumerate all handles that support GOP, then call gBS->HandleProtocol for each handle. Log each device handle during enumeration.
The handle array returned by LocateHandleBuffer is system-allocated and must be released with FreePool after use.
Logs should include the device handle, protocol name, and Status. A status code alone is often insufficient to identify the problem. For every protocol-acquisition change, require the model to explain:
- Which handle is used.
- Which GUID is passed.
- How the return value is evaluated.
Fallback Behavior
GOP may be unavailable on headless systems or some virtual machines. The application should not simply stop without any visible output.
A recommended approach is for GetGraphicsOutput to return EFI_UNSUPPORTED, allowing the caller to record a clear error and either continue in text mode through SimpleTextOutput or exit safely according to the application’s requirements.
Whichever path is chosen, record it in the serial log. Preserve enough detail to distinguish “the protocol is unavailable” from “the protocol exists, but an operation failed.”
Verify State After Mode Changes
The available modes, current mode number, framebuffer base address, and framebuffer size should be consistent.
After changing modes, read the current mode information again. Do not continue rendering with an old resolution or stale framebuffer parameters.
Regression Checklist
Test one hypothesis per change and retain both logs and version diffs. If a regression appears, this makes it easier to return to the last known-good version.
| Check | Expected result | Log anchor | Rollback point |
|---|---|---|---|
Release of buffers returned by QueryMode |
Every successful call has a corresponding FreePool; no leaks |
Buffer address before and after release | Previous mode-query function |
Refresh of Gop->Mode fields after SetMode |
Framebuffer address, size, and resolution match the new mode | Mode number, FrameBufferBase, and resolution |
Previous mode-setting function |
| Resource cleanup on failure paths | Every error branch returns to a clean state | Cleanup actions in error branches | Shared error-handling cleanup code |
| Behavior when protocol acquisition fails | A readable error is logged, EFI_UNSUPPORTED is returned, and the application does not crash |
Device handle, GUID name, and Status |
Previous GetGraphicsOutput function or corresponding commit |
| Cold boot | The graphical interface appears correctly after startup | Complete serial startup sequence | Last bootable image |
| Mode switching | Display dimensions and coordinates remain correct after the switch | Resolution before and after switching | Image from before the mode-switching change |
| Main-loop exit | Resources are released, and display and input state are restored | Exit-path logs | Previous exit function |
Engineering Boundaries for LLM-Assisted Development
An LLM can help review code and generate patches, but it cannot replace specification checks or engineering judgment. Generated code can still contain subtle errors, such as treating ImageHandle as a device handle or freeing protocol-owned memory.
Follow three rules:
- Build and test in an isolated environment. Use virtual firmware or a recoverable test device rather than experimenting directly on critical hardware.
- Define the context and constraints in the prompt. Specify the relevant code scope, prohibit invented interfaces, and require verification steps.
- Validate every conclusion. Check model-generated claims against the specification or the actual implementation.
Before merging generated code, review the following:
- Handle source: Is the protocol being acquired from the correct device handle rather than the application’s image handle?
- GUID reference: Does the code use the standard GUID definition without duplicating it elsewhere?
- Pointer ownership: Is it clear which memory must be released and which memory must not be freed?
- Failure handling: Do error paths leave the application in a clean state, with an appropriate fallback?
- Observability and regression coverage: Are the logs sufficient to locate failures, and does each change have a corresponding regression check?
LLMs become useful in low-level firmware development when their output is kept within a controlled cycle of review, patching, logging, and regression testing.
