Using LLMs to Repair Firmware Graphics Code: From Crashes to a Runnable Program
This article presents a reusable method for using LLMs to repair legacy firmware graphics code that compiles but does not run correctly. It explains why firmware, bare-metal, and pre-boot environments are harder than OS-level applications, focusing on protocol lifetimes, memory visibility, build and link issues, graphics mode switching, and limited debugging. The article then describes a two-round acceptance process: first moving from non-runnable to basically runnable through review-first diagnosis, targeted logging, graphics protocol GUID checks, framebuffer lifecycle fixes, and reproducible builds; second improving maintainability through rendering boundaries, input timing, error handling, module contracts, smoke tests, and rollback. It also provides recommended constraints for prompting LLMs, emphasizing review before modification, minimal patches, protocol lifetime explanations, diagnostic logs, staged validation, and human review of critical paths.
Writing a small casual game on top of an operating system often leads an LLM to produce a buildable project skeleton. Moving the same task into firmware, bare-metal, or a pre-boot environment raises the difficulty sharply. The cause is usually not syntax; it is protocol lifecycle, memory visibility, compilation and linking, graphics mode switching, and the debugging chain. Rather than retelling a specific product comparison, this article abstracts a repair process for bringing a legacy firmware graphics program from non-runnable to runnable into a reusable technical method: how to make an LLM review before modifying, how to use logs to locate crashes, how to check protocol GUIDs and framebuffer pointers, and how to validate the work in two rounds.
1. Why Firmware Environments Make It Easier to “Write” Code Than to “Run” It
Upper-layer applications have mature runtimes, exception stacks, logging libraries, and debuggers, so many errors surface quickly. Firmware environments are different:
- There is no complete operating system as a fallback. Memory allocation, exception handling, input/output, and graphics initialization all depend on platform services. Errors often appear as silent exits or a black screen.
- Protocol objects have lifetimes. Pointer values obtained from queries, mode information, and framebuffer addresses may become invalid after a mode switch. Caching pointers across phases is a common risk.
- GUID and protocol matching are strict. The same category of graphics protocol may have multiple related GUIDs or service-location paths. Using the wrong one prevents access to the correct interface.
- Debugging options are limited. In many scenarios, developers can rely only on serial logs, screen output, or minimal smoke tests. Log design itself is an engineering capability.
- The build chain is coupled to the runtime environment. Compiling does not mean it can start; starting does not mean it can draw; drawing does not mean input works. Validation must be staged.
For these reasons, an LLM is better suited to firmware repair work as a code-review assistant, patch-candidate generator, and log summarizer, rather than as a one-shot replacement for the engineer making all low-level decisions.
2. Task Setup: Two Rounds of Acceptance, Not a Single “Score”
Repairing this kind of legacy project should define two clear rounds.
Round 1: From non-runnable to basically runnable. Acceptance criteria include: the project compiles and links; the program starts without immediately exiting; the graphics protocol can be located successfully; the screen can enter the target mode and display a basic image; input events can be read; and the exit path can clean up resources.
Round 2: Refinement and maintainability optimization. This includes error handling, log levels, module boundaries, rendering efficiency, input timing, resource release, fixed build scripts, and supplementary smoke tests.
It is important to note that differences between generated solutions on similar tasks are only observations, not direct rankings of model capability. Task complexity, context length, toolchain differences, and the quality of human instructions all significantly affect results. The valuable part is preserving the modular structure of a failed project and restoring it to a runnable state through a controlled process.
3. Round 1: Review First, Then Make Minimal Fixes
3.1 Start with a Code Review Checklist
Do not begin by asking the model to “rewrite” the project. The first step should be a module-by-module review: entry function, main loop, protocol acquisition, mode setup, framebuffer usage, input handling, and resource release. The output should include issue locations, risk levels, repair suggestions, and verification methods.
Human engineers should focus on three categories of issues: whether protocol acquisition happens at the correct stage; whether information is re-queried after a mode switch; and whether error branches actually return and log. Review conclusions should not merely sound plausible; they must map to code lines and runtime behavior.
3.2 Crash Localization: Logs Should Follow the Protocol Call Chain
A typical symptom is that the program starts, prints “entered main loop”, and then exits directly. At this point, do not blindly change business logic. Instead, add leveled logs around protocol location, mode query, mode setup, framebuffer acquisition, and first-frame rendering.
An illustrative pseudocode example is shown below:
status_t init_graphics(graphics_t *g) {status_t st = locate_graphics_protocol(&g);if (st != OK) {log_error("graphics protocol locate failed: %d", st);return st;}mode_info_t info;st = graphics_query_mode(g, &info);if (st != OK) {log_error("query mode failed: %d", st);return st;}st = graphics_set_mode(g, info.mode);if (st != OK) {log_error("set mode failed: %d", st);return st;}/* Incorrect: continue using info.framebuffer cached before set_mode *//* Fix: query current mode information again after setting the mode */mode_info_t current;st = graphics_query_current_mode(g, ¤t);if (st != OK) {log_error("query current mode failed: %d", st);return st;}g->framebuffer = current.framebuffer;g->width = current.width;g->height = current.height;return OK;}
The core conclusion is: a mode switch changes the internal state of the protocol, and information pointers obtained before the switch cannot be cached long-term across phases. The fix is not to “add a null check” and stop. It is to adjust the lifetime: after the mode is set successfully, acquire the framebuffer information again and use only the currently valid handle in later rendering.
3.3 GUID Issues: Print Diagnostic Information When Location Fails
A common cause of a program that does not crash but never shows a graphics interface is that graphics protocol location fails or resolves to a mismatched service. During repair, inject the target GUID explicitly as platform configuration and output diagnostic information on failure.
status_t locate_graphics_protocol(graphics_t **out) {guid_t target = platform_graphics_protocol_guid();status_t st = locate_protocol(&target, NULL, (void **)out);if (st != OK) {log_error("target graphics protocol not found");log_guid("target guid", &target);return st;}return OK;}
The key here is not to memorize a particular macro name; it is to establish a checking habit: confirm the source of the target protocol GUID; confirm that location happens after the protocol service is available; confirm that failure branches can output the GUID and status code; and confirm that the handle is stored within a clear lifetime after success.
3.4 Include the Build Environment in the Repair Scope
Common problems in legacy projects also include missing build scripts, dependency version drift, and inconsistent compiler options. Round 1 should fix the build entry point, record the toolchain version and key compiler parameters, and ensure that “the same source can be built repeatedly.” This is more important than asking the model to keep generating new features.
4. Round 2: Refinement Should Focus on Maintainability
After the program is basically runnable, Round 2 should not pursue a “large rewrite.” It should make small, incremental optimizations:
- Rendering layer: Define framebuffer boundaries clearly and avoid out-of-bounds writes. If necessary, introduce dirty rectangles or double-buffering ideas, but only on the premise that they can be verified.
- Input layer: Handle polling timing, key debouncing, and exit events, and avoid a busy-waiting main loop that makes the interface unresponsive.
- Error handling: Unify status codes and log levels. Critical failures must be returned upward and must not be silently ignored.
- Module boundaries: Preserve reasonable modular design in the legacy project. Fix interface contracts only; do not easily discard everything and start over.
- Testing and rollback: Build a minimal smoke checklist for startup, drawing, input, and exit. Every patch should be reversible.
5. Recommended Patterns for Instructing LLMs
In practice, high-quality instructions should include the following constraints:
- “Review first; do not modify. Output a list of issues and verification methods.”
- “Make only minimal patches and do not refactor unrelated modules. Explain the reason for each change.”
- “Explain the lifetime of protocol objects and identify which pointers must not be cached across mode switches.”
- “Add logs for failure branches. The logs must distinguish location failure, query failure, setup failure, and rendering failure.”
- “Provide staged acceptance steps: build, startup, drawing, input, and exit.”
- “Do not invent interfaces that do not exist. Mark assumptions where uncertain and wait for human confirmation.”
In real deployments, teams can use general-purpose model services and code-assistance capabilities in a controlled workflow for code review, log summarization, and patch generation. However, model output can only be treated as candidate patches. Critical protocol lifetimes, memory safety, and startup timing must still be reviewed by engineers.
6. Conclusion
The value of LLM-assisted development in firmware environments is not “generate once and it runs.” It is organizing legacy code review, log-based localization, minimal repair, staged acceptance, and human review of critical paths into a closed loop. First stop the program from crashing, then make the graphics protocol work correctly, and finally refine and optimize. This path is more reliable than simply pursuing generation speed. For developers, what is reusable is not the name of a particular model, but a verifiable, rollback-capable, and auditable method for repairing low-level code.
