AI-Assisted Firmware Debugging: Two Iterations from Startup Crash to Stable UEFI Operation
AI can quickly walk through legacy firmware code and produce fix hypotheses, but observability, acceptance, and rollback must stay in human hands. Using a UEFI graphics application that "looks fine" as the example, this article lays out a two-iteration method for getting from compile failures and startup crashes to stable operation. You'll get a problem-localization path, reference fix code, reusable AI prompt templates, an acceptance checklist, and guidance on the risk boundaries and compliance considerations of firmware-layer changes.
AI can quickly walk through legacy firmware code and produce fix hypotheses, but observability, acceptance, and rollback must stay in human hands. This article uses a UEFI graphics application that “looks fine” as an example and presents a two-iteration approach for getting from compile failures and startup crashes to stable operation. Readers will gain a problem-localization path, reference fix code, AI prompt templates, an acceptance checklist, plus the risk boundaries and compliance guidance for firmware-layer changes.
First iteration: from crash to running
The goal of the first iteration is not “perfection” but making the program stop failing at startup — getting it to a state where the graphics output protocol is available and stably draws the first frame on QEMU/OVMF or the target platform.
Example environment and build commands
The examples below assume EDK2 Stable202111 or a nearby version, and validate on QEMU/OVMF first before moving to the target platform. If your project uses GNU-EFI, the approach is the same, but headers and build commands must be replaced with the corresponding toolchain.
# Build example: adjust for the actual package name, architecture, and toolchainbuild -a X64 -t GCC5 -p AppPkg/AppPkg.dsc -b DEBUG
# QEMU run exampleqemu-system-x86_64 \-bios OVMF.fd \-drive file=fat:rw:./Build/AppPkg/DEBUG_GCC5/X64,format=raw \-m 1024 \-net none \-serial stdio
All code here is minimal-fix illustration and must be adjusted for the specific platform, DSC, GUID, and memory-access capabilities.
Entry and handle-acquisition failure: why can’t the program even reach the GUI?
Symptom: the application returns immediately after launch, the serial log shows only a few initialization messages, and the screen shows no graphics output; or HandleProtocol returns EFI_NOT_FOUND.
Cause: common reasons include passing the wrong ImageHandle, the graphics output protocol not being ready yet, no fallback to LocateProtocol, no check for Gop == NULL, and running logic checks directly on a null pointer.
Fix code:
EFI_STATUSInitializeGraphics (IN EFI_HANDLE ImageHandle,OUT EFI_GRAPHICS_OUTPUT_PROTOCOL **Gop){EFI_STATUS Status;UINTN SizeOfInfo;UINT32 ModeNumber;EFI_GRAPHICS_OUTPUT_PROTOCOL_MODE_INFORMATION *ModeInfo;if (ImageHandle == NULL || Gop == NULL) {return EFI_INVALID_PARAMETER;}*Gop = NULL;Status = gBS->LocateProtocol (&gEfiGraphicsOutputProtocolGuid,NULL,(VOID **)Gop);if (EFI_ERROR (Status) || *Gop == NULL) {Status = gBS->HandleProtocol (ImageHandle,&gEfiGraphicsOutputProtocolGuid,(VOID **)Gop);}if (EFI_ERROR (Status) || *Gop == NULL) {return EFI_UNSUPPORTED;}Status = (*Gop)->SetMode (*Gop, 0);if (EFI_ERROR (Status)) {for (ModeNumber = 0; ModeNumber < (*Gop)->Mode->MaxMode; ModeNumber++) {Status = (*Gop)->QueryMode (*Gop,ModeNumber,&SizeOfInfo,&ModeInfo);if (Status == EFI_SUCCESS && ModeInfo != NULL) {Status = (*Gop)->SetMode (*Gop, ModeNumber);FreePool (ModeInfo);break;}}}return Status;}
Verification: the serial log should show that protocol acquisition succeeded and the mode was set successfully; QEMU should enter graphics mode. If it fails, it should print the status code rather than crash outright.
Dangling pointers after mode switch: why does it glitch or crash right after SetMode?
Symptom: the first draw succeeds, but after a second SetMode call the code accesses the old frame buffer or old mode information, causing screen glitches, unexpected resets, or data corruption.
Cause: a mode switch can change the frame buffer address, scanline width, pixel format, and mode information pointer. If you keep caching the old FrameBufferBase, Mode->Info, or scanline width, you will end up accessing stale addresses or a wrong layout.
Fix code:
EFI_STATUSRefreshAfterModeSet (IN EFI_HANDLE DeviceHandle,IN EFI_HANDLE ImageHandle,OUT EFI_GRAPHICS_OUTPUT_PROTOCOL **GopOut,OUT UINT64 *FrameBufferOut,OUT UINT32 *StridePixelsOut){EFI_STATUS Status;EFI_GRAPHICS_OUTPUT_PROTOCOL *Gop;EFI_GRAPHICS_OUTPUT_PROTOCOL_MODE_INFORMATION *Info;EFI_BLOCK_IO_PROTOCOL *BlockIo;EFI_BLOCK_IO2_PROTOCOL *BlockIo2;EFI_BLOCK_IO_MEDIA *Media;EFI_BLOCK_IO2_MEDIA *Media2;if (GopOut == NULL || FrameBufferOut == NULL || StridePixelsOut == NULL) {return EFI_INVALID_PARAMETER;}Gop = NULL;BlockIo = NULL;BlockIo2 = NULL;Media = NULL;Media2 = NULL;Status = gBS->HandleProtocol (DeviceHandle,&gEfiBlockIoProtocolGuid,(VOID **)&BlockIo);if (Status == EFI_SUCCESS && BlockIo != NULL) {Media = BlockIo->Media;}Status = gBS->OpenProtocol (DeviceHandle,&gEfiBlockIo2ProtocolGuid,(VOID **)&BlockIo2,ImageHandle,NULL,EFI_OPEN_PROTOCOL_GET_PROTOCOL);if (Status == EFI_SUCCESS && BlockIo2 != NULL) {Media2 = BlockIo2->Media;}Status = gBS->HandleProtocol (DeviceHandle,&gEfiGraphicsOutputProtocolGuid,(VOID **)&Gop);if (EFI_ERROR (Status) || Gop == NULL || Gop->Mode == NULL || Gop->Mode->Info == NULL) {return EFI_NOT_FOUND;}Info = Gop->Mode->Info;Print (L"Mode=%u x %u, PixelsPerScanLine=%u, Format=%d\n",Info->HorizontalResolution,Info->VerticalResolution,Info->PixelsPerScanLine,Info->PixelFormat);*GopOut = Gop;*FrameBufferOut = Gop->Mode->FrameBufferBase;*StridePixelsOut = Info->PixelsPerScanLine;return EFI_SUCCESS;}
Pay special attention here: after a mode switch, re-acquire block I/O with HandleProtocol, then get media information and BlockMedia2 with OpenProtocol; on the graphics side, re-read HorizontalResolution, VerticalResolution, and PixelsPerScanLine. Do not keep using the frame buffer pointer from before the switch.
Verification: immediately after switching modes, print the new resolution and scanline width; draw a rectangle in a fixed color to confirm the position is not offset. If it still glitches, check whether an old pointer or old scanline width is being used.
Misusing the graphics output protocol Blt direction: check Blt first when the screen shows nothing or stays black
Symptom: Gop->Blt returns EFI_INVALID_PARAMETER or EFI_UNSUPPORTED, or the screen is black, colors are wrong, or only part of the region refreshes.
Cause: the usual problem is confusing the screen-to-buffer and buffer-to-screen directions. Different EDK2 versions or code styles may use names like EfiGopBlitterToVideo or VideoToBlt, but everything must be aligned with the current protocol definition, such as EfiBltBufferToVideo or EfiBltVideoToBltBuffer. At the same time, Blt width, height, coordinates, buffer format, and frame buffer format must all match.
Fix code:
EFI_STATUSDrawSolidRect (IN EFI_GRAPHICS_OUTPUT_PROTOCOL *Gop,IN UINT32 *Buffer,IN UINTN Width,IN UINTN Height,IN UINTN X,IN UINTN Y){if (Gop == NULL || Buffer == NULL || Width == 0 || Height == 0) {return EFI_INVALID_PARAMETER;}SetMem (Buffer, Width * Height * sizeof (UINT32), 0);Buffer[0] = 0x00FFFFFF;return Gop->Blt (Gop,Buffer,EfiBltBufferToVideo,0,0,X,Y,Width,Height,0);}
To read screen content back into memory, use EfiBltVideoToBltBuffer. For basic memory operations, standardize on SetMem and CopyMem, and explicitly check for null pointers: write if (Buffer == NULL) or if (Gop != NULL), not if (Buffer) or if (Pointer == 0).
Verification: draw a solid-color rectangle first. If the rectangle’s position and size are correct, the direction, coordinates, and width/height are basically right; if the colors are wrong, keep checking the pixel format and scanline width.
Second iteration: from running to stable
The goal of the second iteration is to keep the program stable during long-running sessions, input interaction, mode switches, and different resolutions. At this point the question is no longer “does it run?” but “will it occasionally misbehave, drop frames, or show wrong colors?”
Pixel format and scanline-width adaptation: why are colors offset or slanted to the right?
Symptom: the display is globally color-shifted, rows are misaligned, black bars appear on the right side, or some resolutions look fine while others show diagonal streaking.
Cause: PixelsPerScanLine is the number of scan pixels per row and is not necessarily equal to the visible width HorizontalResolution. If you compute row addresses with HorizontalResolution * BytesPerPixel, you will progressively drift into the padding region on the right. Another common issue is an RGB vs. BGR byte-order mismatch.
Fix code:
UINT32GetBytesPerPixel (IN EFI_GRAPHICS_PIXEL_FORMAT Format){switch (Format) {case PixelRedGreenBlueReserved8BitPerColor:case PixelBlueGreenRedReserved8BitPerColor:return 4;default:return 2;}}VOIDPrepareRowLayout (IN EFI_GRAPHICS_OUTPUT_PROTOCOL_MODE_INFORMATION *Info,OUT UINT32 *BytesPerPixel,OUT UINT32 *StrideBytes,OUT UINT32 *AlignedStrideBytes){UINT32 Bpp;UINT32 Stride;Bpp = GetBytesPerPixel (Info->PixelFormat);Stride = Info->PixelsPerScanLine * Bpp;*BytesPerPixel = Bpp;*StrideBytes = Stride;*AlignedStrideBytes = (Stride + 3) & ~3;}
For 32-bit pixels, if the format reported by GOP doesn’t match the byte order the actual output device expects, you can swap RGB to BGR:
VOIDSwapRedBlueFor32Bpp (IN UINT64 FrameBufferBase,IN UINT32 AlignedStrideBytes,IN UINT32 Width,IN UINT32 Height){UINTN Y;UINTN X;UINT8 *Row;UINT8 *Pixel;UINT8 Temp;if (FrameBufferBase == 0 || AlignedStrideBytes == 0 || Width == 0 || Height == 0) {return;}for (Y = 0; Y < Height; Y++) {Row = (UINT8 *)(FrameBufferBase + Y * AlignedStrideBytes);for (X = 0; X < Width; X++) {Pixel = Row + X * 4;Temp = Pixel[0];Pixel[0] = Pixel[2];Pixel[2] = Temp;}}}
Verification: draw three rectangles in pure red, pure green, and pure blue. If the color order matches what the device actually displays, the RGB/BGR handling is correct; if the rectangles slant to the right, check whether you mistakenly used the visible width instead of PixelsPerScanLine.
Frame pacing and input debounce: why frames drop, keys repeat, or the picture flickers?
Symptom: animation is unstable — a frame rate that is too high causes flicker, and one that is too low causes stutter; a single key press triggers an action multiple times, or a held-key state jitters.
Cause: the loop lacks timestamp control, so every round redraws; input reading has no sampling period or debounce threshold; key state isn’t merged with the previous state.
Fix code:
#define FRAME_INTERVAL_US 16667ULL#define KEY_DEBOUNCE_US 30000ULLUINT64GetNowUs (VOID){UINT64 NowUs;NowUs = 0;gBS->CalculateTimer (0, &NowUs);return NowUs;}EFI_STATUSReadKeyIfAny (IN EFI_SIMPLE_TEXT_INPUT_PROTOCOL *ConIn,OUT BOOLEAN *KeyReady){EFI_STATUS Status;EFI_INPUT_KEY Key;if (ConIn == NULL || KeyReady == NULL) {return EFI_INVALID_PARAMETER;}Status = ConIn->ReadKeyStroke (ConIn, &Key);if (Status == EFI_SUCCESS) {*KeyReady = TRUE;return EFI_SUCCESS;}if (Status == EFI_NOT_READY) {*KeyReady = FALSE;return EFI_SUCCESS;}*KeyReady = FALSE;return Status;}
In the main loop, sample by frame pacing and input debounce:
UINT64 LastFrameUs = 0;UINT64 LastKeyUs = 0;BOOLEAN KeyReady = FALSE;while (TRUE) {UINT64 NowUs = GetNowUs();if (NowUs - LastFrameUs >= FRAME_INTERVAL_US) {DrawFrame ();LastFrameUs = NowUs;}if (ReadKeyIfAny (gST->ConIn, &KeyReady) == EFI_SUCCESS && KeyReady) {if (NowUs - LastKeyUs >= KEY_DEBOUNCE_US) {HandleKey ();LastKeyUs = NowUs;}}}
Here FRAME_INTERVAL_US is roughly the 16.7ms of 60Hz; KEY_DEBOUNCE_US can be 20ms to 50ms, and this article’s example uses 30ms. The actual values should be tuned based on the input sampling period, display refresh rate, and feel.
Verification: enter key presses through the QEMU serial console to confirm one press triggers only one action; observe whether screen refresh is stable. On the target platform, it’s recommended to add timestamp prints to verify that the frame interval matches expectations.
AI prompt templates and acceptance checklist
AI is well-suited for structured walkthroughs, hypothesis generation, and code drafts, but observability, acceptance, rollback decisions, and compliance judgments should remain under human control. Use it along the following division of labor:
| Stage | AI can handle | Human must handle |
|---|---|---|
| Walkthrough | List possible failure points per module | Confirm real logs and runtime environment |
| Hypothesis | Output “hypothesis + how to verify” | Design observability verification |
| Fix | Generate minimal code drafts | Review protocol, memory, and lifecycle |
| Acceptance | Suggest test cases | Run regression and decide on release |
| Risk | Flag firmware/NVRAM risks | Backup, rollback, and compliance approval |
A reusable AI prompt template:
You are a UEFI/EDK2 firmware debugging assistant.Toolchain: EDK2 Stable202111 or GNU-EFI.Runtime environment: QEMU/OVMF or the target platform.Target file: xxx.c.Current symptom: startup crash / black screen / screen glitch / repeated key press.Log excerpt: already sanitized, containing only status codes and function names.Please answer in the following steps:1. List possible causes, ranked by probability.2. For each cause, give a way to verify it.3. Provide minimal fix code.4. Mark the risk points and rollback points.Do not give unverified conclusions directly.
Getting-started checklist:
- Add serial logging, state-machine prints, and error-code output first, before changing business code.
- Fix only one class of problem at a time; avoid mixing protocol, rendering, and input changes in a single pass.
- After a fix, re-run previously passing cases to prevent “fixing the crash but introducing a black screen.”
- Back up before modifying firmware or NVRAM, and validate on OVMF/QEMU first.
- Sanitize logs before feeding them in: remove build-machine paths, hostnames, SNs, UEFI variables, and other sensitive information.
Risk boundaries and compliance for firmware-layer changes
Firmware-layer changes are different from ordinary application code. A failed firmware or NVRAM write can leave the device unable to boot, lose configuration, or corrupt data. Before any formal flashing, validate in OVMF/QEMU first and prepare recovery options: flashing back the original firmware, dual BIOS, flashing tools, serial output, and JTAG debugging. If the device has no recovery path, avoid writing directly to critical regions.
When feeding logs to AI, you must sanitize build-machine paths, hostnames, SNs, UEFI variables, device paths, and any log excerpts that might contain internal information. Do not feed in sensitive business data or proprietary closed-source code; use a sanitized minimal reproduction excerpt instead. This both improves the efficiency of AI assistance and keeps security and compliance risks under control in firmware development.
