Refactoring a Graphics Mini-Game with AI in UEFI: From Unbootable to Playable
Developing graphics programs in firmware and bare-metal environments is hard because there is no window system, no mature input subsystem, and no easy debugger attachment. This article walks through using an AI coding assistant to take a legacy UEFI mini-game from "compiles" to "runs" and then to "fun," covering static review, two representative failures (a stale frame buffer pointer after mode switch and a wrong protocol identifier), and refinement work on input edge detection, double buffering, fixed-tick timing, and resource robustness. It also summarizes practical tips for collaborating with AI and a quick troubleshooting table. Readers will get a reusable, verifiable checklist for debugging constrained graphics code.
1. Background: Why “It Compiles” Is Far From “It Runs”
Developing graphics programs in firmware and bare-metal environments means that a successful build is only the starting point. Unlike writing applications on a mature operating system, these environments have no ready-made window system, no mature input subsystem, and no debugger you can attach at any time. Whether the program runs stably depends on precise control over low-level protocols, memory lifetimes, and hardware timing.
A typical exercise is to hand a piece of legacy code generated by another model to an AI coding tool, with the goal of getting it running first and then refining and optimizing it. The problems this process exposes are highly representative and worth abstracting into a general methodology.
2. Round One: From “Not Runnable” to “Runnable”
2.1 Do a Static Review Before Changing Anything
The first step when taking over unfamiliar code is not to run it, but to do a structured review. It helps to slice the check by module:
- Entry point and dependency wiring: are protocol handles acquired correctly, and are dependencies closed-loop;
- Main loop structure: is there any blocking, and is there a clear exit condition;
- Coupling between game logic and rendering: are state updates separated from drawing;
- Input handling: are keys polled correctly, and is there edge detection;
- Resource lifetime: are the allocation and release of buffers, handles, and memory paired.
Having the AI output a three-column structure of “issue list + fix suggestion + verification method” is more controllable than letting it directly modify code. The value of the list is that it breaks a vague “it won’t run” into atomic issues that can be verified one by one.
2.2 Failure One: Frame Buffer Pointer Invalid After Mode Switch
The symptom is that the program prints the loop-start log after launch and then exits immediately. Most “crash on startup” problems like this are not logic errors but pointer lifetime errors.
A common trap in using the graphics output protocol is: first query the current mode information and save the pointer, then call the set-mode interface, and then keep using the old pointer. A mode switch reconfigures the display device, and the memory where the previously returned description block resides may have been reclaimed or overwritten, so subsequent reads and writes become accesses to a wild pointer.
Illustrative bad pattern (pseudocode):
// Wrong: reuse the old pointer across a mode switchconst MODE_INFO *info = NULL;UINTN size = 0;gop->QueryMode(gop, mode, &size, &info);gop->SetMode(gop, mode);// info may already be invalid hereframe = gop->GetFrameBuffer(gop); // calls that depend on info will misbehave
The correct approach is to adjust the order: complete the mode setting first, then re-query the mode information and frame buffer address, and copy key fields into local variables instead of holding external pointers for a long time.
gop->SetMode(gop, mode);const MODE_INFO *info = NULL;UINTN size = 0;gop->QueryMode(gop, mode, &size, &info);UINT32 bpp = info->PixelFormat-dependent-bpp;frame = gop->GetFrameBuffer(gop);
For troubleshooting, it is recommended to print full logs over the serial output: mode number, resolution, bits per pixel, frame buffer base address, and the return value of the first write. Logs are more suitable for this environment than breakpoints.
2.3 Failure Two: Wrong Protocol Identifier Means No Graphics Appear
The program no longer crashes, but there is no output on screen. This kind of problem usually comes from “finding the wrong object”: the firmware specification defines multiple identifiers related to graphics output with different purposes, and mixing them up means the protocol instance you get is not the real display channel, or is an empty implementation.
There are three handling principles:
- Locate the protocol starting from an explicit device handle, rather than globally searching for the first match;
- Check the returned status code, and treat any non-success return as a hard error and print it;
- Do a capability probe on the obtained protocol, for example by querying the number of supported modes, and if it is zero, directly judge it as unusable.
STATUS s = handle_protocol(handles[i], &PROTOCOL_GUID, (void **)&gop);if (s != SUCCESS || gop == NULL) continue;if (gop->Mode == NULL || gop->Mode->MaxMode == 0) continue;
3. Round Two: Refinement and Optimization, From “Runs” to “Fun”
3.1 Input Handling: Polling and Edge Detection
In a bare-metal environment there is no event queue, so input must be actively polled. If every frame judges only “is it pressed right now,” a single long press will trigger the action multiple times. Introducing edge detection solves this:
BOOLEAN prev_up = FALSE;while (running) {BOOLEAN up = read_key_up();if (up && !prev_up) move_paddle_left();prev_up = up;render();}
3.2 Rendering: Double Buffering and Tearing
Writing directly to the visible frame buffer causes screen tearing and flicker. A workable approach is to prepare a back buffer, and after logic drawing is complete, copy the whole block or sync-refresh by scan-line ranges. If memory is tight, you can degrade to “dirty rectangle” partial refresh, redrawing only the changed areas.
3.3 Timing: Do Not Use Busy Waiting for Delays
Using an empty loop to control ball speed will spin out of control as the clock frequency changes. Logic updates should be driven by a fixed tick, with rendering decoupled from logic, to keep speed consistent across platforms.
ticks = read_timer();if (ticks - last >= FRAME_INTERVAL) {update_game();last = ticks;}
3.4 Resources and Robustness
- Every allocation and release appears in pairs, and is reclaimed on exception paths too;
- Clamp frame buffer boundaries to avoid out-of-range coordinates writing over adjacent memory;
- Keep a self-check flow that can be triggered over serial, outputting the status of each module.
4. Practical Points for AI-Assisted Development
- Break tasks small: split “fix it” into three steps: review, fix a single point, verify a single point;
- Make feedback observable: provide serial logs, symptom descriptions, and reproduction steps, rather than just saying “it doesn’t work”;
- Make constraints explicit: state the target environment, available protocols, memory limits, and prohibited items;
- Keep changes minimal: change only one variable at a time for easier attribution;
- Distill conclusions: abstract each failure into a check item to form a reusable troubleshooting checklist for the team.
5. Quick Reference for Common Failures
| Symptom | High-Probability Cause | Handling Direction |
|---|---|---|
| Exits on startup | Reusing an old pointer across a mode switch | Re-query after setting the mode |
| No picture but no crash | Wrong protocol identifier or empty capability | Check status and mode count |
| Long press repeats | Missing edge detection | Record the previous frame’s key state |
| Screen tearing | Writing directly to the visible buffer | Back buffer or dirty-rectangle refresh |
| Unstable speed | Busy-wait delay | Fixed-tick driven logic |
6. Conclusion
Developing graphics programs in constrained environments is difficult not because of syntax but because of respect for resource lifetimes and hardware timing. Only by treating the AI coding tool as a collaborator that “can read code, can list issues, and can make small-step changes,” together with observable logs and a strict verification process, can you steadily move unrunnable legacy code to a playable and maintainable state.
