AI-Assisted Legacy Code Repair for a UEFI Graphics Program: A Two-Round Debugging Practice
This article explores how AI coding tools can take over a legacy UEFI graphics program that looks well-structured but fails to run. It presents a two-round repair approach: first, building hypotheses through static review, adding observability, and fixing startup failures; second, improving rendering stability, input handling, robustness, resource management, configurability, and maintainability. It also summarizes reusable engineering methods and common pitfalls for AI-assisted legacy code repair in firmware and low-level graphics development.
1. The Real Shape of the Problem: Not “Can’t Write It” but “Can’t Run It”
In firmware and low-level graphics development, the hardest scenario is often not starting from scratch, but taking over code that looks fairly well-structured yet cannot run. Such legacy code usually has a complete directory layout, modular naming, and clear responsibility boundaries. A static read-through may reveal almost no fatal flaws. But once placed in a real environment, the program exits during startup and cannot draw even a single frame.
This “half-runnable” state is difficult to handle for three reasons:
- Lack of observability: at the firmware stage, there is no mature debugger or stack trace, so the crash point can only be inferred from logs.
- Strong environment coupling: the same code may behave completely differently across development framework versions and firmware configurations.
- Silent errors: protocol call failures often return only a status code. If the upper layer does not check it, the failure is exposed dozens of lines later.
Therefore, when letting intelligent coding tools take over such a task, the core is not to “rewrite it once,” but to have the tool play the role of systematic investigation and iterative repair.
2. First-Round Goal: From “Compiles” to “Runs”
The only acceptance criterion for the first round is: after startup, the program does not exit and continuously outputs observable runtime traces.
2.1 Step 1: Static Review, Starting with an Issue List
The first instruction after taking over the code should be very restrained—review only, no modifications:
Please read through the current project, by module (entry, main loop, game logic, rendering, input handling), list issues that may cause runtime failure, and mark severity and verification method.
A valuable output is not generic advice such as “add exception handling,” but locatable and verifiable items, for example: a protocol pointer may become invalid after a mode switch, the graphics protocol identifier constant selection is inconsistent, the event queue is consumed before initialization, or buffer boundaries lack validation.
The purpose of this step is to build a set of hypotheses. Each subsequent run validates or eliminates one hypothesis instead of relying on blind trial and error.
2.2 Step 2: Turn “Silent Failures” into “Observable Failures”
Before fixing bugs, first let the tool add observability: print timestamped logs at key points (entry, mode setting, protocol acquisition, first frame of the main loop), and check the return value of every protocol call.
STATUS = gBS->LocateProtocol(&GraphicsProtocolGuid, NULL, (VOID **)&Graphics);if (EFI_ERROR(STATUS)) {DEBUG(("locate graphics protocol failed: %r\n", STATUS));return STATUS;}
The benefit of this step is an order-of-magnitude improvement: the crash location narrows from “somewhere during startup” to “after a specific protocol call.”
2.3 Failure 1: Framebuffer Address Invalid After Mode Switch
A typical symptom is: the program successfully prints the main loop start log, then exits entirely.
The root cause is a reference lifetime error: the code obtains a framebuffer information pointer before setting the display mode, but mode setting reallocates or maps video memory. The memory pointed to by the old pointer then becomes invalid, and subsequent writes trigger an exception.
The fix principle is “switch first, query later,” and re-acquire after every mode change:
Graphics->SetMode(Graphics, TARGET_MODE);/* After a mode switch, re-acquire; do not reuse the old pointer */STATUS = Graphics->QueryMode(Graphics, TARGET_MODE, &ModeInfo);FrameBuffer = &Graphics->Mode->FrameBufferBase;
Such defects are less common in ordinary application-layer development, but they are a high-frequency trap in firmware and direct video memory operations. They deserve an explicit constraint in coding standards.
2.4 Failure 2: Wrong Graphics Protocol Identifier
The program no longer crashes, but the screen is completely black. Logs show protocol location failure or an unexpected instance.
In low-level frameworks, there are usually multiple graphics-output-related identifier constants, pointing to protocol instances for different purposes. When the wrong identifier is selected, the call may “succeed” but return an object that cannot be used for drawing, or it may fail directly at the location stage.
The handling method is: verify the definition and semantics of the identifier constants in the target framework version, and centralize them in one configuration to avoid hardcoding in multiple modules:
/* Central definition to avoid inconsistencies after version upgrades */static const EFI_GUID mGraphicsProtocolGuid = { /* ... */ };
2.5 First-Round Summary
At this point, the program can run continuously and render the first frame. The first-round method can be summarized as: review first to build hypotheses → add logs for observability → change only one place at a time → run and verify immediately.
3. Second-Round Goal: Refinement, Performance, and Robustness
Being able to run is only the starting point. The acceptance criteria for the second round shift to quality and maintainability.
- Rendering stability: use an off-screen buffer plus full-frame refresh to eliminate tearing and flicker caused by per-pixel direct writes; advance logic updates on fixed time slices so frame rate and logic speed are decoupled.
- Input handling: decouple key scanning from game logic and introduce edge detection to avoid a long press being recognized as repeated triggers.
- Robustness: check return values for all protocol calls; bounds-check all array and buffer accesses; on allocation failure, fall back to a safe state instead of continuing execution.
- Resource management: clarify resource release responsibilities on startup and exit paths to avoid leak accumulation caused by repeated loading in a firmware environment.
- Configurability: extract parameters such as grid size, brick rows, and initial speed into constants or configuration structures for later tuning and porting.
- Maintainability: keep module boundaries clear; the rendering layer does not need to know game rules, and the logic layer does not directly manipulate video memory.
4. Four Reusable Methodologies
- Environment first: pin the development framework version and firmware configuration, and archive build artifacts and logs in a unified artifact and log service so issues are reproducible and traceable.
- Observability before fixes: do not change code without logs; otherwise you are only guessing.
- Small-step verification: introduce only one change at a time and use a minimal runnable sample, avoiding multiple stacked changes that make attribution impossible.
- Context constraints: clearly specify input boundaries to intelligent coding tools—target hardware, protocol version, available interfaces, and prohibited items—to significantly improve output quality.
5. Common Pitfalls
- Asking the tool to “rewrite all modules at once,” which loses existing usable logic and makes newly introduced defects hard to locate.
- Ignoring return value checks and delaying errors to undiagnosable positions.
- Reusing pointers across lifetimes, especially in mode switching and memory remapping scenarios.
- Hardcoding protocol identifiers in multiple places, causing hard-to-troubleshoot behavior differences after framework upgrades.
6. Conclusion
The value of letting intelligent coding tools take over legacy code is not replacing human design decisions, but compressing repetitive review, log completion, compile verification, and iteration into very short cycles. What still determines success is engineering method: a reproducible environment, observable runtime traces, and attributable small changes. With this process, whether for firmware graphics programs or other low-level components, there is a clear path forward when facing code that “looks good but cannot run.”
