Debugging AI-Generated Code in the Firmware Layer: A Practical Guide

    This article shares a real-world workflow for debugging AI-generated code in a UEFI/BIOS firmware environment, where no operating system, runtime, or graphics library is available. Using a modular Tetris implementation as the example, it walks through a two-round iteration process: a static review to surface likely failure points, fixes for a stale pointer after mode switching, correction of a graphics protocol GUID mismatch, and input/event loop handling, followed by a second round focused on logic correctness, rendering performance, observability, and layering. It closes with four human-AI collaboration principles and notes how the same rhythm applies to other constrained environments such as minimal container images, edge devices, and bare-metal programs.

    1. Background and Problem Definition

    Developing a game with a graphical interface in a firmware (UEFI/BIOS) environment is nothing like writing a program on top of an operating system. There is no ready-made runtime and no mature graphics library. All you can rely on is the set of boot services and protocols defined by the firmware specification. When many developers hand this kind of task to an AI coding tool, their first instinct is “make it write everything correctly in one shot.” Real engineering, however, often presents the opposite situation: taking over a piece of code left behind by someone else that looks well structured but does not run.

    This article follows a real practice. One AI coding tool first generated a modular Tetris firmware implementation consisting of seven files with clear layering, but the build environment could not even be set up, and there was no runnable artifact in the end. A different AI coding tool (paired with an AI command-line coding assistant) was then used to clean up the mess, and it ran successfully after two rounds of iteration. The problems exposed in this process are highly representative and worth abstracting into a reusable method.

    One point needs to be clear first: different models completing different tasks does not constitute a fair comparison, nor should it be treated as an evaluation conclusion. What is truly valuable is the process — how AI locates problems in a constrained environment, how humans provide effective feedback, and how the iteration rhythm is designed.

    2. Round One: From “Dead Code” to “Runnable”

    2.1 Do a Static Review First, Don’t Rush to Run

    After copying the legacy code unchanged into a new source directory, the first instruction should be minimal and explicit: review this code and list the problems that could cause failure.

    A usable prompt skeleton is as follows:

    1. Please review the current project. Go through it module by module (entry point, main loop,
    2. game logic, rendering, input handling) and list the problems that could cause a runtime
    3. failure, along with a severity level and a fix suggestion for each. Do not modify the code yet.

    After a few minutes, the tool can usually produce a structured list: improper use of entry parameters, cache invalidation after setting a mode, mismatched protocol identifiers, missing event-wait logic, and so on. The value of this list is that it turns “mystical crashes” into verifiable to-do items.

    2.2 Problem One: Exit on Startup and a Wild Pointer

    The program compiled and started, printed the log showing the main loop had begun, and then exited immediately. The tool was asked to add serial-port debug output and narrow the scope step by step, which eventually localized the issue to right after the graphics output protocol call.

    The root cause was a typical lifetime error: the information pointer obtained when querying the mode pointed to memory that had become invalid after the mode was set, and continuing to dereference it was a wild pointer access.

    1. // Counter-example: keep using the old pointer after switching modes
    2. const EFI_GRAPHICS_MODE_INFORMATION *info = NULL;
    3. UINTN size = 0;
    4. Status = Graphics->QueryMode(Graphics, 0, &size, &info);
    5. Status = Graphics->SetMode(Graphics, 1);
    6. DrawPixel(Graphics, 10, 10, color); // info is already invalid

    The fix is to “re-query after switching”:

    1. Status = Graphics->SetMode(Graphics, 1);
    2. UINTN size2 = 0;
    3. const EFI_GRAPHICS_MODE_INFORMATION *info2 = NULL;
    4. Status = Graphics->QueryMode(Graphics, 1, &size2, &info2);
    5. // From here on, use the resolution and pixel format from info2 consistently

    The general lesson from this kind of problem is that in a firmware environment the validity period of a pointer is often bound to a particular service call, and any pattern of “fetch first, change state afterward” needs to be re-examined.

    2.3 Problem Two: Incorrect Protocol Identifier Configuration

    The program no longer exited, but the screen was completely black. After continuing to report the runtime behavior, the tool determined that the identifier configuration for the graphics output protocol was wrong — the firmware specification defines several related identifiers, and picking the wrong one makes it impossible to locate the actual graphics output instance.

    The engineering practice is to avoid hardcoding, manage these centrally, and perform an existence check with log output during initialization.

    1. // Define centrally to avoid inconsistent hardcoding in multiple places
    2. static const EFI_GUID *gGraphicsGuid = &EFI_GRAPHICS_OUTPUT_PROTOCOL_GUID;
    3. static const EFI_GUID *gLoadedImageGuid = &EFI_LOADED_IMAGE_PROTOCOL_GUID;
    4. Status = gBS->LocateProtocol(gGraphicsGuid, NULL, (void **)&Graphics);
    5. if (EFI_ERROR(Status) || Graphics == NULL) {
    6. DEBUG(L"Graphics protocol not found: %r\n", Status);
    7. return Status;
    8. }

    2.4 Input and the Event Loop

    Once the black screen problem was solved, there was still the issue of “it displays but is not playable.” Keyboard input under firmware depends on events and the keyboard protocol. Common defects include a busy-wait main loop, failure to wait on events properly, and no edge detection on key states, which causes a single press to be recognized multiple times. It is recommended that the main loop keep a fixed rhythm of “render — wait — process input,” and that the time taken per frame be printed to the serial port so it is easy to tell whether the program is stuck.

    3. Round Two: Refinement and Optimization

    The goal of the first round was to “get it running”; only the second round is about quality.

    • Resources and boundaries: collision detection for block rotation, boundary and top-row checks, and index updates when clearing lines are the pure-logic parts most prone to error. They are well suited to having the tool add unit-test-style pure functions before wiring them into rendering.
    • Rendering performance: avoid a full-screen redraw every frame; use dirty rectangles or refresh only when the state changes. Take the resolution and pixel format uniformly from the mode information rather than hardcoding them.
    • Observability: keep a leveled logging switch and turn off debug output in release builds.
    • Code organization: decouple the three layers of “logic — rendering — platform calls,” with no firmware service calls appearing in the logic layer, which keeps the cost of later porting and testing lowest.

    4. Distilled Methodology: Four Principles of Human-AI Collaboration

    1. Break tasks into small pieces and give specific feedback. Don’t say “it doesn’t run”; say “it exits after printing up to a certain line, with no further serial output.”
    2. Review before modifying. Have the tool output a list of problems with severity levels, and let the human make the trade-offs.
    3. Write the environment constraints into the prompt. State clearly that there is no operating system, no third-party graphics library, and only boot services and protocols are available.
    4. Iterate in two rounds. The first round only solves runnability; the second focuses on quality and performance, avoiding changes so large that problems cannot be localized.

    5. Transferable Engineering Value

    This workflow is not limited to firmware games. It applies equally to any scenario that runs in a constrained environment lacking a mature debugger — minimal images inside containers, edge devices, bare-metal programs — following the same rhythm: static review, minimal reproduction, single-point localization, and step-by-step verification. If a team connects logs, metrics, and alerts to a unified logging service and monitoring/alerting system, hosts build artifacts in object storage, and pins down the build environment with a container platform, the debugging loop of AI collaboration becomes more stable and reproducible.

    On a platform like Baidu AI Cloud, the general capabilities above (container platform, object storage, logging service, monitoring and alerting) can serve as an engineering foundation, helping teams turn the “AI writes, AI fixes” process into a standard workflow that is observable and rollback-capable, rather than an occasional success that depends on individual experience.