UEFI Snake: AI Coding Assistant Pitfalls and Verification Guide

    An AI coding assistant can noticeably shorten coding, debugging, and verification time in UEFI firmware development — but only if directory boundaries, the build environment, and acceptance criteria are enforced by your process instead of being left to the model's own judgment. Using "running a graphical Snake game under the UEFI Shell" as the worked example, this guide walks through building a loadable, displayable, and interactive firmware-layer application, with a focus on the errors people actually hit: QEMU graphics startup, GOP pixel drawing, bitmap font rendering for Chinese characters, keyboard input, double buffering, and a pre-release acceptance checklist. It also covers the target audience, prerequisites, minimal EDK2 project layout, and reproduction of the build.

    When you use an AI coding assistant in a UEFI environment, you can significantly cut the time spent on coding, debugging, and verification. The precondition is that directory boundaries, the build environment, and acceptance criteria are controlled by your process — not by the model improvising on its own.

    This article uses “running a graphical Snake game under the UEFI Shell” as the example. It walks through how to use an AI coding assistant to build a loadable, displayable, interactive firmware-layer application, and focuses on the common failure points: QEMU graphics startup, GOP drawing, Chinese bitmap font display, keyboard input, and pre-release acceptance.

    1. Who This Is For, and What You Need First

    UEFI is the firmware environment a computer runs in after power-on and before the operating system loads. Unlike a desktop application, a UEFI application does not depend on the host OS — it runs directly at the firmware layer. That makes it a good fit for firmware diagnostics, self-test tools, pre-boot graphical configuration, recovery helpers, and simple interactive visualizations.

    These applications are resource-constrained and expose few abstractions. There is no desktop window system and no mature high-level graphics library, so developers usually call UEFI protocols directly. To follow along with this article, you should be comfortable with:

    • Reading C, including pointers, structures, function calls, and memory access;
    • The basic EDK2 directory layout and build commands;
    • Booting a UEFI VM or virtual firmware with QEMU;
    • Browsing devices and directories in the UEFI Shell and loading files manually;
    • The fact that UEFI applications are normally compiled into .efi executables.

    If you have no EDK2 or QEMU experience at all, build a minimal UEFI Hello World inside a controlled virtual machine first, then move on to graphics.

    2. How Do You Set Up the Minimal UEFI Snake Project?

    An AI coding assistant is at its best when generating repetitive code. Without project boundaries, however, it may create a messy directory tree, wrong paths, or a project that simply will not build. So the first round should not be “write the complete Snake game logic” — it should be “produce a minimal runnable skeleton.”

    Have the assistant output the directory structure first, then generate the files. A minimal project can look like this:

    1. Snake/
    2. Snake.c
    3. Snake.inf

    Inside an EDK2 source tree, place it in a package you control — for example, create a Snake directory under AppPkg. Adjust the actual path to match your EDK2 version, but keep everything inside the working directory. Without that constraint, the assistant may write files into a parent or system directory.

    Snake.inf can stay minimal:

    1. [Defines]
    2. INF_VERSION = 0x00010005
    3. BASE_NAME = Snake
    4. FILE_GUID = 7b5b0a11-2c7c-4d55-9a80-7b67e3d3f6a1
    5. MODULE_TYPE = UEFI_APPLICATION
    6. VERSION_STRING = 0.1
    7. ENTRY_POINT = SnakeMain
    8. [Sources]
    9. Snake.c
    10. [Packages]
    11. MdePkg/MdePkg.dec
    12. [LibraryClasses]
    13. UefiApplicationEntryPoint
    14. UefiBootServicesTableLib
    15. UefiLib
    16. [Protocols]
    17. gEfiGraphicsOutputProtocolGuid
    18. gEfiSimpleTextInputProtocolGuid
    19. [Depex]
    20. TRUE

    Snake.c needs only an entry point at this stage:

    1. #include <Uefi.h>
    2. #include <Library/UefiLib.h>
    3. #include <Library/UefiBootServicesTableLib.h>
    4. #include <Protocol/GraphicsOutput.h>
    5. #include <Protocol/SimpleTextIn.h>
    6. EFI_STATUS
    7. EFIAPI
    8. SnakeMain (
    9. IN EFI_HANDLE ImageHandle,
    10. IN EFI_SYSTEM_TABLE *SystemTable
    11. )
    12. {
    13. SystemTable->ConOut->OutputString (
    14. SystemTable->ConOut,
    15. L"UEFI Snake Skeleton OK\r\n"
    16. );
    17. return EFI_SUCCESS;
    18. }

    Next, build it in the EDK2 environment. If AppPkg is the package that hosts your app, the command looks roughly like this:

    1. build -p AppPkg/AppPkg.dsc -m Snake/Snake.inf -a X64 -b RELEASE -t GCC5

    After a successful build, the output is usually somewhere like:

    1. Build/AppPkg/RELEASE_GCC5/X64/Snake.efi

    Different EDK2 versions, DSC configurations, or build flags can change the path, so verify the actual artifact with find:

    1. find Build/AppPkg -name "Snake.efi"

    Common causes of build failure include: edksetup.sh was not run, BaseTools was not built, nasm or uuid-dev is missing, the GCC5 toolchain is not installed correctly, or the EDK2 version does not match the DSC path. In a clean environment, start by building a minimal UEFI application that is known to work, then add functionality incrementally.

    Once the artifact is confirmed, copy it into a FAT boot directory:

    1. mkdir -p usb/EFI/BOOT
    2. cp Build/AppPkg/RELEASE_GCC5/X64/Snake.efi usb/EFI/BOOT/Snake.efi

    If you want it to launch automatically when the virtual disk is attached, name it BOOTX64.EFI:

    1. cp Build/AppPkg/RELEASE_GCC5/X64/Snake.efi usb/EFI/BOOT/BOOTX64.EFI

    The goal of this stage is not the Snake game. It is to confirm three things: the project is recognized by EDK2, the application compiles into a .efi, and the application can be loaded either from the UEFI Shell or by auto-start.

    3. How Do You Draw GOP Pixels in UEFI Snake?

    A UEFI graphics application normally reaches the screen frame buffer through the Graphics Output Protocol (GOP). Drawing in a UEFI Snake game is not GPU-accelerated — it is the CPU writing directly into the GOP frame buffer. That means you need to pay close attention to pixel format, stride, resolution, the frame buffer base address, and bounds checking.

    You must acquire GOP before calling any drawing function. Otherwise, even with correct game logic, you get gGop == NULL, a protocol-not-found error, or nothing on screen. Initialize it at entry:

    1. EFI_GRAPHICS_OUTPUT_PROTOCOL *gGop = NULL;
    2. EFI_STATUS
    3. SnakeInitGop (
    4. IN EFI_SYSTEM_TABLE *SystemTable
    5. )
    6. {
    7. EFI_STATUS Status;
    8. Status = SystemTable->BootServices->LocateProtocol (
    9. &gEfiGraphicsOutputProtocolGuid,
    10. NULL,
    11. (VOID **)&gGop
    12. );
    13. if (EFI_ERROR (Status) || gGop == NULL) {
    14. gGop = NULL;
    15. return EFI_NOT_FOUND;
    16. }
    17. Status = gGop->SetMode (gGop, 0);
    18. if (EFI_ERROR (Status)) {
    19. return EFI_UNSUPPORTED;
    20. }
    21. return EFI_SUCCESS;
    22. }

    To pick a specific resolution, enumerate the available modes with QueryMode first, then select the target one. The key point is that SetMode can fail and its return value must not be ignored. On failure, return a clear error rather than continuing to call drawing functions.

    Before you take a frame buffer pointer, confirm the following:

    • Enumerate available modes with QueryMode;
    • Select the target resolution with SetMode;
    • Read HorizontalResolution and VerticalResolution;
    • Read PixelsPerScanLine;
    • Read FrameBufferBase and FrameBufferSize;
    • Inspect PixelFormat and distinguish BGR from RGB;
    • Return an explicit error for unsupported pixel formats instead of pretending success.

    A more defensive DrawPixel looks like this:

    1. EFI_STATUS
    2. EFIAPI
    3. SnakeDrawPixel (
    4. IN UINTN X,
    5. IN UINTN Y,
    6. IN UINT32 Color
    7. )
    8. {
    9. EFI_GRAPHICS_OUTPUT_MODE_INFORMATION *Info;
    10. UINT8 *Pixel;
    11. UINT32 *Pixel32;
    12. if (gGop == NULL || gGop->Mode == NULL || gGop->Mode->Info == NULL) {
    13. return EFI_NOT_READY;
    14. }
    15. Info = gGop->Mode->Info;
    16. if (gGop->Mode->FrameBufferBase == 0) {
    17. return EFI_UNSUPPORTED;
    18. }
    19. if (X >= Info->HorizontalResolution ||
    20. Y >= Info->VerticalResolution) {
    21. return EFI_INVALID_PARAMETER;
    22. }
    23. Pixel = (UINT8 *)gGop->Mode->FrameBufferBase
    24. + (Y * Info->PixelsPerScanLine + X) * 4;
    25. Pixel32 = (UINT32 *)Pixel;
    26. switch (Info->PixelFormat) {
    27. case PixelBlueGreenRedReserved8BitPerColor:
    28. *Pixel32 = Color;
    29. return EFI_SUCCESS;
    30. case PixelRedGreenBlueReserved8BitPerColor:
    31. *Pixel32 = ((Color & 0x00FF0000) >> 16) |
    32. (Color & 0x0000FF00) |
    33. ((Color & 0x000000FF) << 16);
    34. return EFI_SUCCESS;
    35. default:
    36. return EFI_UNSUPPORTED;
    37. }
    38. }

    Two details matter here. First, gGop, Mode, and Info must all be checked for NULL. Second, when PixelFormat is unsupported, do not return EFI_SUCCESS — otherwise the layer above assumes the pixel was written.

    In a real project, build the following on top of DrawPixel:

    • DrawRect: fill a rectangle;
    • FillRect: clear the whole screen or a region;
    • DrawLine: draw a straight line;
    • CopyFrame: copy a back buffer into the screen frame buffer.

    4. QEMU Shows No Graphics: What Do You Do?

    Many readers can load the .efi from the UEFI Shell but see no graphics under QEMU. There are three usual causes: you launched with -nographic, the virtual FAT directory was not attached correctly, or GOP initialization failed / SetMode did not succeed.

    To be clear, -nographic is primarily for text and serial-port debugging. If the goal is to verify a graphical UEFI Snake game, enable graphics explicitly, for example -display gtk or -display sdl. -nographic can only validate text output, not the GOP picture.

    Assume you have built OVMF and have a usb directory containing EFI/BOOT/Snake.efi. Copy the firmware into a temporary directory first so the originals stay untouched:

    1. mkdir -p qemu-work
    2. cp OVMF_CODE.fd qemu-work/
    3. cp OVMF_VARS.fd qemu-work/

    The recommended launch command:

    1. qemu-system-x86_64 -m 1024 -display gtk \
    2. -drive if=pflash,format=raw,readonly=on,file=qemu-work/OVMF_CODE.fd \
    3. -drive if=pflash,format=raw,file=qemu-work/OVMF_VARS.fd \
    4. -drive file=fat:rw:dir=usb,format=raw

    The virtual FAT syntax can differ slightly between QEMU versions. These equivalent or alternative forms are worth trying:

    1. -drive file=fat:rw:usb,format=raw

    or:

    1. -drive file=fat:ro:dir=usb,format=raw

    If virtual FAT is not recognized with some firmware/QEMU combinations, prefer a pre-built FAT image:

    1. dd if=/dev/zero of=usb.img bs=1M count=64
    2. mkfs.vfat -F 32 usb.img
    3. sudo mount -o loop,uid=$(id -u),gid=$(id -g) usb.img mnt
    4. cp -r usb/* mnt/
    5. sudo umount mnt

    Then start:

    1. qemu-system-x86_64 -m 1024 -display gtk \
    2. -drive if=pflash,format=raw,readonly=on,file=qemu-work/OVMF_CODE.fd \
    3. -drive if=pflash,format=raw,file=qemu-work/OVMF_VARS.fd \
    4. -drive file=usb.img,format=raw

    Shared-directory mechanisms such as 9p and virtiofs can be used to pass files around, but they are not the same as a traditional FAT boot medium. Whether they work depends on whether the firmware supports the corresponding protocol and whether the application can be loaded from that device. So if the goal is to validate the UEFI Shell boot chain, still prefer a FAT virtual disk or a FAT image.

    Also watch the risk of writable pflash. A writable variable store can modify the emulated firmware variables, and fat=rw may let the guest write into the boot directory. Copy the firmware and variable files into a temporary directory before launching the VM, so you do not accidentally modify a real image or production data.

    5. How Do You Build a Chinese Bitmap Font?

    UEFI has no desktop-grade font rendering. Copying desktop font files in usually does not work. The more reliable approach is to maintain only the characters actually used — menu text, score, prompts — generate 16x16 or 12x12 bitmaps for them, and build an index mapping.

    If your source stores the character table as UTF-8, note that UEFI text interfaces commonly use CHAR16. You cannot treat raw UTF-8 bytes as glyph indices when drawing. Convert the UTF-8 characters to Unicode code points or CHAR16 first, then look up the bitmap index.

    For example, a character may be stored in UTF-8 in the string, but drawing requires a lookup of its 16x16 bitmap by code point. If the character was not included in the font, render a box or a question mark instead of reading out of bounds. For Chinese fonts, you also need to handle double-width characters, line-width calculation, text wrapping, and truncation protection.

    The recommended strategy:

    • Include only the characters the UI actually uses;
    • Use a fixed-width bitmap, such as 16x16;
    • Build an index for each commonly used character;
    • Transcode from UTF-8 before the table lookup;
    • Use a placeholder for characters that are not included;
    • Do not depend on system font files;
    • Check character bounds and line width before drawing.

    This avoids shipping a huge font resource and avoids garbled text or crashes caused by missing glyphs.

    6. Keyboard Input Does Nothing: How Do You Diagnose It?

    UEFI keyboard input involves scan codes, Unicode characters, and extended keys. Arrow keys normally require checking ScanCode; letter keys can be handled via UnicodeChar. You can start with EFI_SIMPLE_TEXT_INPUT_PROTOCOL, or use EFI_SIMPLE_TEXT_INPUT_EX_PROTOCOL, which offers richer extended capabilities.

    Basic pseudocode:

    1. WaitForEvent (1, &SimpleTextIn->WaitForKey, &Index);
    2. ReadKeyStroke (SimpleTextIn, &Key);
    3. if (Key.ScanCode == SCAN_UP) {
    4. SnakeChangeDirection (UP);
    5. } else if (Key.ScanCode == SCAN_DOWN) {
    6. SnakeChangeDirection (DOWN);
    7. } else if (Key.ScanCode == SCAN_LEFT) {
    8. SnakeChangeDirection (LEFT);
    9. } else if (Key.ScanCode == SCAN_RIGHT) {
    10. SnakeChangeDirection (RIGHT);
    11. } else if (Key.UnicodeChar == L'W' || Key.UnicodeChar == L'w') {
    12. SnakeChangeDirection (UP);
    13. } else if (Key.UnicodeChar == L'A' || Key.UnicodeChar == L'a') {
    14. SnakeChangeDirection (LEFT);
    15. }

    If the input logic handles only ScanCode, WASD will not respond. If it handles only UnicodeChar, the arrow keys will not respond. Before release, cover arrow keys, WASD, the pause key, and the exit key.

    With EFI_SIMPLE_TEXT_INPUT_EX_PROTOCOL, you can also register a key-press notification callback or read key repeat state. That suits more complex interaction, but you then have to handle key repeat and debouncing yourself, or the direction will be changed repeatedly.

    7. How Do You Do Double Buffering and Frame Buffer Synchronization?

    Double buffering means finishing a whole frame off-screen and copying it to the screen frame buffer in one shot, which reduces tearing and localized flicker. In pseudocode:

    1. AllocateBuffer (FrameBufferSize);
    2. DrawAllToBuffer ();
    3. CopyMem (FrameBufferBase, Buffer, FrameBufferSize);

    In UEFI, allocate the back buffer with AllocatePool:

    1. UINT8 *BackBuffer;
    2. UINTN FrameSize;
    3. FrameSize = gGop->Mode->FrameBufferSize;
    4. Status = gBS->AllocatePool (
    5. EfiBootServicesData,
    6. FrameSize,
    7. (VOID **)&BackBuffer
    8. );
    9. if (EFI_ERROR (Status)) {
    10. return Status;
    11. }

    Drawing functions should write to BackBuffer rather than the screen frame buffer. After the full frame is drawn, synchronize:

    1. gBS->CopyMem (
    2. (VOID *)gGop->Mode->FrameBufferBase,
    3. BackBuffer,
    4. FrameSize
    5. );

    Watch two boundaries: FrameBufferBase must be valid, and the copy length must not exceed FrameBufferSize. If the resolution changes, the old back buffer cannot be reused directly — reallocate it or recompute the stride.

    8. Pre-Release Acceptance Checklist

    Before submitting or delivering, work through this table:

    Check item Failure symptom How to diagnose Fix
    Directory boundary Files written into a parent directory Inspect the paths the assistant created Force all output into the designated directory
    Reproducible build Build fails on another machine Check EDK2 version, BaseTools, toolchain Pin dependencies and the build script
    Artifact path Snake.efi cannot be found Run find Build -name Snake.efi Fix the DSC or build flags
    GOP acquisition Drawing function returns not-ready Check whether LocateProtocol succeeded Add GOP initialization
    SetMode failure Black screen or wrong resolution Print or return the status code Select a supported mode
    Pixel format Colors are wrong Check PixelFormat Add BGR/RGB conversion
    Stride Image shifted or skewed Check PixelsPerScanLine Compute with the real stride
    Double buffering Flicker or tearing Check whether the whole frame is copied Synchronize the full back buffer
    Chinese display Garbled text or boxes Check whether the character is included Add the missing bitmap glyphs
    Keyboard input WASD or arrow keys do nothing Check ScanCode and UnicodeChar separately Handle both input types
    Boot chain Loading from the UEFI Shell fails Check the directory and file naming Place it in EFI/BOOT or the specified path
    QEMU graphics No window, or a black screen Check for accidental -nographic Use -display gtk or sdl
    Virtual FAT Guest cannot see the boot disk Check the fat: syntax Switch to valid virtual FAT or a FAT image
    Firmware risk Variables get polluted Check whether pflash is writable Use a temporary copy and a read-only code flash

    Overall, an AI coding assistant can raise development efficiency for UEFI applications substantially, but “it compiles”, “it runs”, and “it passes acceptance” are three different levels. What really determines whether the project succeeds is not whether the assistant can generate a large volume of code in one pass, but whether the developer can turn directory constraints, a controlled build, GOP initialization, frame buffer details, non-ASCII text display, QEMU verification, and boot-chain acceptance into a repeatable process. Put the boundaries first, script the environment, and turn acceptance into a checklist — that is what lets AI-generated code reliably become a runnable, maintainable firmware-layer application.