Debugging Graphics Games in Firmware: Lessons from Letting AI Take Over Legacy Code
This article walks through a practical firmware-level debugging effort: getting a graphics game to run in a pre-OS environment such as UEFI, where there is no window system, no driver framework, and only serial output for observability. It covers why firmware graphics code is hard to write, how a structured code review turns "it won't run" into testable hypotheses, and how two concrete symptoms—exiting after the first frame and a permanently blank screen—were traced to a stale display-mode pointer and a mismatched protocol identifier. It then outlines the second pass from "runs" to "playable," and closes with four principles for handing legacy low-level code to an AI coding tool.
1. Why Graphics Programs at the Firmware Layer Are Especially Hard to Write
On a general-purpose operating system, writing a small graphics game usually means calling an existing window library. The event loop, rendering context, and input callbacks are all handled by the framework. In a firmware environment—for example, UEFI, which runs during the boot phase before an operating system is loaded—none of that infrastructure exists. There is no window system and no device driver framework. All you can rely on is the small display output capability established during boot and a limited runtime library.
The screen is not a “window” but a linearly mapped pixel buffer. The keyboard is not a source of “events” but an input device you must poll actively. The program has no exception handling, so a single invalid memory access often shows up as “execution silently stops at a certain line.”
This leads to two consequences. First, the code must be extremely disciplined: memory allocation is manual, coordinate math must account for pixel format and stride, and any out-of-bounds write can corrupt the firmware’s own data structures. Second, debugging options are very limited: without a graphical debugger, serial output is nearly the only observation channel, so observability has to be treated as a first-class requirement in the design.
The approach in the original practice was representative: an AI coding tool was given two kinds of tasks—generating code from scratch and taking over code to fix it—to compare how it actually performs in a constrained environment. The result was not surprising. Generating a structurally complete brick-breaker-style game from scratch went relatively smoothly: it compiled on the first try and entered the game loop on the first run. Taking over a Tetris-style codebase from another tool—one that looked well structured but would not run at all—exposed the real difficulty of low-level debugging.
It is worth noting that the legacy code itself was not poor quality. It was split into seven files by responsibility, with clear separation between the entry point, main loop, logic, rendering, and input. The problem was not messy code; it was wrong assumptions about the platform contract.
2. First Round: From “Compiles” to “Actually Runs”
When taking over legacy code, the worst thing to do is start editing immediately. The sensible order is: reproduce the failure as-is in a clean environment, have the tool perform a static review to produce a verifiable list of problems, then converge on them one symptom at a time.
2.1 Start With a Code Review and Build a Problem List
The first instruction should be very restrained: review this code and list the issues that could cause runtime failure—do not modify anything. An effective review moves module by module along the call chain—entry point, main loop, game logic update, render submission, input read—and produces a categorized list like this:
- Resource acquisition and lifetime: whether the validity of display-related information is misjudged before and after the mode is set;
- Protocol identifier usage: whether the identifier constants for the graphics output interfaces match the firmware specification;
- Memory and buffers: whether the pixel buffer’s stride, bit width, and usable dimensions are hardcoded;
- Loop and exit conditions: whether the main loop’s termination condition is satisfied on the very first frame;
- Missing observability: no log anchors at all, making faults impossible to locate.
The value of this list is not that it “guesses correctly,” but that it breaks a vague “it won’t run” into several independently verifiable hypotheses.
2.2 Symptom One: The Process Exits Right After Printing the Startup Message
On reproduction, the program enters normally, prints a startup line, and then immediately ends. In firmware graphics programming, the most common cause of this “dies on the first frame” behavior is a display information pointer that has already become invalid: the code queries the current display mode and stores the returned information structure pointer, then calls the interface to set the mode. Setting the mode reconfigures the output device, so the memory holding that description is no longer valid, and dereferencing it is a wild pointer access.
The fix principle is equally clear: do not reuse the same pointer across a mode switch. Instead, query the frame buffer information again after the mode is determined, and use that result as the sole basis for subsequent rendering. A sketch:
// Wrong: info is invalid after SetModestatus = gop->QueryMode(gop, mode, &sz, &info);status = gop->SetMode(gop, mode);frame = info->FrameBufferBase; // Dangerous: the memory info points to may have been reclaimed// Right: re-query after the mode is setstatus = gop->SetMode(gop, mode);status = gop->QueryMode(gop, mode, &sz, &info);frame = info->FrameBufferBase;stride = info->Stride; // Stride must come from runtime information
One often-overlooked detail deserves emphasis: a pixel buffer’s stride is usually not equal to “width × bytes per pixel,” because of alignment padding. Treating width as stride is the typical cause of “it displays, but the image is skewed, sheared, or torn at the right edge.”
2.3 Symptom Two: It Runs, but the Screen Stays Blank
The second symptom is more subtle: the process no longer exits, the main loop is spinning, serial logs keep printing, but nothing appears on screen. The problem has now shifted from “memory validity” to “interface contract mismatch.” The graphics output protocol is associated with multiple identifier constants in the firmware specification, used for different purposes. If a mismatched identifier is used when locating the interface, the object you get is not the expected display output interface, and every subsequent drawing call targets the wrong object—no error, no image.
The reliable way to investigate this kind of problem is “confirm in stages,” not retry the whole thing:
- Confirm whether interface location succeeded and whether the return status is success;
- Confirm whether setting the mode succeeded and whether the effective resolution matches the request;
- Confirm whether the frame buffer base address and size fall within a valid physical address range;
- Write a solid color block to a fixed location in the buffer to verify that the “write to memory” stage is visible;
- Then verify that the coordinate conversion and stride usage are correct.
The first three steps rule out contract problems, the fourth separates “cannot write” from “computed the wrong position,” and the fifth narrows it down to rendering logic. In the original practice, it was precisely by adding serial logs and printing each step’s return status and key values that the fault was pinpointed to the interface identifier configuration.
3. Second Round: From “Runs” to “Playable”
Getting an image on screen is only half done. The second round of refinement usually concentrates on four kinds of problems.
- Input and main loop pacing: the firmware phase has no system clock scheduling, so unthrottled polling keeps the main loop at full processor load, showing up as “keys unresponsive, screen flickering.” The sensible approach is to introduce a fixed time slice and advance logic updates and redraws frame by frame.
- Flicker and tearing: repeatedly erasing and rewriting directly on the visible buffer inevitably flickers. Compose the whole frame in memory first and submit it in one shot, or use double buffering with alternating swaps.
- Collision and boundaries: Tetris-style logic is extremely sensitive to boundary and rotation checks. The rotation matrix, wall-kick offsets, and lock delay should each be configurable rather than hardcoded magic numbers.
- Resource and state reset: when starting a new game, the score, random source, current piece, and queue must be explicitly reset, or leftover state causes “the second game onward to behave abnormally.”
4. Methodology: Four Principles for Letting AI Take Over Legacy Code
- Reproduce first, then modify. Any “optimization” that has not been reproduced is a gamble.
- Put observability ahead of features. The first round of changes should already include serial log anchors: entry and exit, status codes, key addresses and sizes.
- Verify one hypothesis at a time. Variables are tightly coupled in low-level environments; change three things at once and even success cannot be attributed.
- Use a contract checklist instead of memory. Write down interface call order, pointer validity, where stride comes from, and what each identifier constant is for as a checklist, and have the tool verify item by item—far more stable than letting it “rewrite from experience.”
As for tool selection, the point is not the name of a particular model or AI coding tool, but three capabilities: whether it can read cross-file call contracts, whether it proactively adds logs when information is insufficient instead of guessing, and whether it strictly follows platform constraints such as “re-query after a mode switch.” These capabilities are likewise emphasized repeatedly in Baidu AI Cloud’s documentation and engineering practice: the prerequisite for improving efficiency in low-level development is making implicit contracts explicit.
