AI Coding Assistants Building UEFI Tetris: A Hands-On Retrospective on Taking Over Legacy Firmware Code
This article documents two controlled experiments on having AI coding assistants build a small game (Tetris) inside a UEFI firmware environment with no operating system. It contrasts Round 1, where two tools generated games from scratch, with Round 2, where a different model took over an unfinished, non-running Tetris prototype to review, fix, and refine it. The article walks through the concrete UEFI pitfalls encountered—frame buffer lifetime after mode switches, GOP protocol GUID selection, and serial-log-based observability—along with input edge detection, dirty-rectangle rendering, and static memory usage. It closes with five practical lessons for using AI in firmware and embedded development, emphasizing verifiable build-and-observe loops, layered delivery, explicit context, AI-assisted review, and infrastructure that captures the feedback loop. Readers will learn how to set up a minimal firmware build cycle and why building an observable closed loop matters more than raw model capability.
1. Where It Started: Using Code-Generation Tools to Build a Game Inside Firmware
I recently ran two controlled experiments in a firmware (UEFI) environment, with the theme “having AI coding assistants implement Tetris in a pre-OS boot layer.”
The initial idea was “fight magic with magic”: have two different code-generation tools each implement a small game. The results were strikingly different—one tool produced a compilable, runnable Breakout in about two hours, building on the first try and running on first boot; the other tool spent nearly six hours wrestling with Tetris, never even got its build environment set up, and left behind nothing that could run.
A common objection is: “The two models worked on different tasks, so it isn’t a fair comparison.” That’s half right. Switching the task was never meant as a benchmark—I wanted to observe where AI capability actually extends. But the other half holds too: that failed artifact wasn’t worthless. It left seven source files—entry point, main loop, game logic, rendering, and input each separated—with a clean skeleton structure. Throwing it away would have been a waste.
So I designed a round closer to real production work: instead of starting a new project, I had another model take over that “half-finished” artifact, first reviewing it, then getting it to run, and finally polishing it. A different person, changed requirements, a leftover prototype, and a newcomer getting the system running inside someone else’s pit—that’s a far more realistic test.
Round definitions (used throughout this article):
- Round 1: From-scratch generation experiment. Two code-generation tools each implemented a small game from zero (Breakout / Tetris), to observe generation capability and its boundaries.
- Round 2: Legacy-project takeover experiment. A different model took over the “Tetris that wouldn’t run” from Round 1, in two phases: “make it run” and “make it playable.” The debugging and engineering experience in this article comes mainly from Round 2.
2. Experimental Environment and Key Challenges
To understand the debugging that follows, here are the environment’s characteristics and prep work:
- Running in the boot layer (UEFI): Code executes in a firmware environment—no operating system, no system calls, no standard runtime. Everything must be done through protocols (Protocol) provided by firmware.
- Graphics output via GOP: Screen drawing goes through the Graphics Output Protocol (GOP). You must first enumerate available display modes, then set the target resolution, then obtain the frame buffer base address and write pixels directly into linear memory.
- Input via keyboard device polling: There’s no event-loop abstraction. You must continuously query key states in the main loop and handle edge detection (the transitions between pressed/released) yourself.
- Very narrow debugging options: When no mature debugger is available, the most reliable observation channel is the serial log. This proved decisive in the debugging described below.
Recommended minimal build-loop checklist (get this working before you start):
- Firmware spec and version: fix the UEFI spec version and EDK2 baseline (e.g., edk2-stable202x) so protocol symbols line up;
- Toolchain and build: GCC/Clang cross-compilation or the VS toolchain, with a properly configured EDK2
.dsc/.dec/.infand a clean full-rebuild command; - Boot method: prefer local debugging with QEMU/OVMF, and keep a rollback path for real-hardware validation;
- Serial log interface: agree on a unified output function (e.g.,
SerialPrintvia the Serial IO protocol), with a phase number and line number; - Minimal rendering sample: first get a minimal project working that “prints a line of text and draws a rectangle,” confirming both display and observation are wired up.
Risk warning: Firmware flashing and low-level debugging carry the risk of bricking a device (making it unbootable). Back up or preserve the stock firmware before operating on real hardware, and have a serial connection or external programmer ready as a recovery means. Validate the minimal memory-write and display flow before any large-scale changes. The complexity here isn’t in “how much code you write,” but in the fact that “every assumption must be verified”—pointer lifetime, protocol identifiers, memory attributes—any one of them taken for granted can turn into a boot-phase failure.
3. Round 2 · Make It Run: From “Won’t Run” to “Runs”
3.1 The First Step Isn’t Changing Code—It’s Review
After copying the legacy code as-is into a new project and setting up the build environment, the first instruction was very deliberate: do a code review first, list the possible problems, and don’t touch anything.
The order matters. Going straight for “make it run” usually falls into guess-based changes—change one thing, compile, fail, change another—and the context quickly drowns in useless logs. A structured review first collapses the problem domain into a finite list of items, so every subsequent step has a clear target.
The model went through the entry function, main loop, game logic, rendering, and input module by module, producing a checklist covering null-pointer risks, mode-info lifetime, frame buffer acquisition timing, and protocol-identifier selection. It judged that “it should run after these changes,” then worked through the list and ran it to verify.
3.2 Pitfall One: It Boots, Then Immediately Exits
First run: the program started, printed a startup log line, then returned to firmware directly—no crash, no UI. On the surface it looked like an instant quit; in reality, the main flow ended early right after some protocol call.
After streaming progress to the serial port in segments, the problem boundary was narrowed to frame buffer usage after graphics mode setup:
UINT32 Mode = FindBestMode(gGop);EFI_GRAPHICS_OUTPUT_MODE_INFORMATION *Info = NULL;UINTN Size = 0;Status = gGop->QueryMode(gGop, Mode, &Size, &Info); // Query mode informationif (EFI_ERROR(Status)) return Status;Status = gGop->SetMode(gGop, Mode); // Actually switch the modeif (EFI_ERROR(Status)) return Status;// Hazard: Info is returned by QueryMode and points to a buffer// managed internally by the protocol;// after SetMode, this memory's lifetime may already be invalid
The cause needs a tightened statement: after the mode switch, the mode-info pointer obtained earlier may become invalid—the old memory may have been reclaimed or reused by the protocol, and continuing to dereference it reads unusable data, causing the later flow to exit abnormally. This isn’t “must be re-fetched”; it’s “lifetime not guaranteed.” Different firmware implementations vary widely here: some keep the old buffer usable briefly after the switch, others invalidate it immediately, so you can’t rely on the old pointer.
The fix is plain—after switching modes, call QueryMode again, or read the gGop->Mode->Info maintained by the protocol’s current state; take the frame buffer base address from gGop->Mode->FrameBufferBase as authoritative:
Status = gGop->SetMode(gGop, Mode);if (EFI_ERROR(Status)) return Status;// Re-fetch after switching; do not reuse the pre-switch pointerStatus = gGop->QueryMode(gGop, Mode, &Size, &Info);if (EFI_ERROR(Status)) return Status;FrameBufferBase = gGop->Mode->FrameBufferBase; // Use the current mode as authoritative
Run it again after the fix—no more exit. This kind of defect is worth emphasizing: in a firmware environment, “whether a pointer is still valid after a function returns or a state transition” isn’t a style question—it’s the line between crashing and not crashing. When a code-generation tool lacks runtime feedback, it easily carries over the high-level-language habit of “acquire once, hold forever.”
3.3 Pitfall Two: The Process Is Alive, but the Screen Is Black
The program no longer exited, but the picture wouldn’t come up. Feeding the result back to the model, it pinpointed a failed graphics output protocol lookup: multiple graphics-related global unique identifiers (GUIDs) exist in the boot layer, and picking the wrong identifier means you can’t obtain the correct protocol instance—so rendering is out of the question.
#include <Guid/GraphicsOutput.h> // The EDK2 environment provides gEfiGraphicsOutputProtocolGuidEFI_GRAPHICS_OUTPUT_PROTOCOL *gGop = NULL;Status = gLocateProtocol(&gEfiGraphicsOutputProtocolGuid, NULL, (VOID **)&gGop);if (EFI_ERROR(Status) || gGop == NULL) {SerialPrint(L"[ERR] locate GOP failed: %r\n", Status); // Explicit failure exitreturn Status;}
Symbol and version differences: In EDK2 environments you typically use gEfiGraphicsOutputProtocolGuid (note the Efi prefix); some stripped-down SDKs or sample code may write it as gGraphicsOutputProtocolGuid, so be sure to check your headers and spec version before copying, or it won’t compile. There are two key points: first, you must validate the return value before dereferencing; second, failure needs a clear exit that leaves observable information. The problem with the legacy code was that both the identifier reference and error handling were sloppy—after the lookup failed, the fault drifted far downstream before it showed itself.
3.4 What Actually Works: Segmented Observability
What proved decisive wasn’t how smart the model was, but how fine-grained the feedback channel was:
- Insert numbered logs at key phases: protocol lookup, mode enumeration, mode setup, frame buffer acquisition, main-loop entry, first-frame completion;
- Validate one phase at a time, and only move forward once it passes;
- Feed the raw failure text back to the model in full (return values, line numbers, symptom descriptions)—don’t paraphrase it by hand.
By contrast, the failed Round 1 experiment was missing exactly this closed loop: the environment wasn’t set up, symptoms couldn’t be observed, and the model could only keep guessing—six hours produced no result. In this case, whether you can build a minimal observable closed loop matters more to success or failure than the difference in the models’ raw capability.
4. Round 2 · Make It Playable: From “Runs” to “Playable”
Getting it running is just the starting point; the goal of the refinement phase is a Tetris that’s actually playable. A few directions:
Input handling. Keyboard polling must do its own edge detection, or holding a key down will fire the piece at extremely high frequency. The approach is to record the previous frame’s key state and trigger the logic once only on “not pressed → pressed,” while adding a key-repeat delay so left/right movement feel is tunable.
Rendering and refresh. Full-screen redraws are costly in a firmware environment, so switch to dirty-rectangle updates: repaint only the block cells that changed and the cleared rows, leaving other pixels untouched; then use a simple double-buffered off-screen canvas to avoid tearing. The refresh cadence is controlled by the main loop’s time base, decoupling logical stepping from drawing.
while (!ShouldExit()) {Now = ReadTimestamp();PollKeyboard(&Keys); // 1. Sample input (including edge detection)if (Now - LastTick >= TickMs) {UpdateGame(); // 2. Logical step: drop, collision, line clearLastTick = Now;}if (IsDirty()) {RenderDirtyRects(); // 3. Repaint only the changed regions}}
Memory and boundaries. Memory is precious in a firmware environment and there’s no fallback reclamation, so it’s best to use static arrays—not dynamic allocation—for the board, block matrices, and next-piece preview; also handle rotation out-of-bounds, wall kicks, and stack-top overflow explicitly, since these boundaries are the ones generated code most easily overlooks.
Common-failure troubleshooting table:
| Symptom | Log to check first | Key items to inspect |
|---|---|---|
| Black screen (process running) | Protocol lookup, mode setup, first-frame completion | Was GOP located successfully, SetMode return value, is the frame buffer base address correct |
| Instant exit / return to firmware | Last phase log after the startup line | Is a stale pointer reused after the mode switch, any unvalidated return value |
| No input | Keyboard device lookup, PollKeyboard return | Is the key device handle valid, does edge detection toggle correctly |
| Corrupted image / tearing | Frame buffer read/write, refresh cadence | Pixel format (RGB/BGR bit order), resolution and stride, is double buffering present |
Portability and buildability. Confine the platform-dependent parts (frame buffer access, input device, timestamp) behind a thin interface layer so the game logic itself is hardware-agnostic; provide a clean full-rebuild path in the build script so it doesn’t depend on leftover state in a developer’s local environment—which was exactly the root cause of Round 1’s failure.
5. Methodology: Five Practical Lessons for AI Coding in Firmware/Embedded Development
Looking at both rounds together, here are five lessons teams can use directly (conclusion first, with explanation).
First, verifiability beats generation speed. Low-level development has no interpreter to fall back on; any code must go through the full “compile—run—observe” loop. Before starting, get three things working—build, run, and log observation—even if it’s just a minimal sample that “prints a line and draws a rectangle.”
Second, deliver in layers so feedback is attributable. Don’t have the model deliver the entire system at once. Split into milestones—compiles → boots → protocols ready → draws one frame → interactive → playable—and validate each one separately. When something fails, you always know exactly which layer broke, and the context won’t be polluted by irrelevant logs.
Third, context supply sets the ceiling. The model’s grasp of firmware protocol details is incomplete; rather than expecting it to remember every convention, write the key facts explicitly into the prompt: target firmware spec version, build-system conventions, protocol lookup method, frame buffer acquisition order, serial log interface. Spelling out a constraint like “must re-call QueryMode after a mode switch” is far cheaper than fixing the bug afterward.
Fourth, using AI for review and refactoring often pays off more than generating from scratch. What legacy code most lacks usually isn’t inspiration but discipline: missing error handling, unclear pointer lifetimes, uncovered boundaries, heavy platform coupling. Have the model do a structured review and produce a checkable problem list, then fix and verify item by item. Across the two rounds here, the review-checklist path converged faster; as long as the skeleton structure is sound, a half-finished product is worth far more than zero.
Fifth, on the engineering side, turn the closed loop into infrastructure. A pragmatic approach is to keep code in a hosted repository, use pipelines to carry automated builds and static checks, and trigger a clean-environment build on every change; archive build artifacts and run logs to object storage for traceability; collect serial logs centrally into a logging service for keyword search and per-phase timing stats; and feed metrics like build-failure rate and average repair rounds into monitoring alerts, using data to judge whether AI assistance actually improves delivery efficiency. This closed loop can be carried by general-purpose cloud capabilities—code hosting with pipelines, container platforms, object storage, logging services, monitoring alerts—so a team can get it running without building anything from scratch.
6. Conclusion
The most memorable takeaway from this experiment isn’t “which model is stronger,” but three more down-to-earth judgments:
- AI coding assistants are a usable tool in firmware and embedded scenarios—provided you prepare a verifiable runtime environment for them. The success or failure of the two attempts here was almost entirely determined by “whether an observation loop could be built.”
- Low-level debugging has extremely high knowledge density; models can only converge with explicit context and real feedback. Wild pointers, protocol identifiers, mode-switch timing—these can’t be guessed out; they must be ruled out segment by segment via serial logs.
- Letting AI take over and rework existing code often fits engineering reality better than creating from scratch. Checklist-based review, milestone layering, and validation before changes—these three disciplines hold just as true in human development.
If you’re introducing code generation into low-level development, start with a minimal project that “compiles, boots, prints, and draws one frame,” get that loop solid, then gradually loosen task complexity.
