From Broken Code to a Working Firmware Project: Using LLMs to Repair Low-Level Software
A practical look at using large language models to recover a modular game project that could not build or run in a constrained pre-boot firmware environment. The workflow focuses on code review, runtime instrumentation, minimal patches, lifecycle safety, regression testing, and a two-stage delivery strategy: restore basic execution first, then improve reliability and maintainability.
A large language model producing code that “looks right” is no longer unusual. The real challenge is whether that code can build and run inside a constrained pre-boot firmware environment, enter its main loop, render reliably, respond correctly to input, and provide enough evidence to diagnose and repair failures.
In one typical exercise, a modular game project containing multiple source files appeared structurally complete but could not be turned into a runnable program. Another large language model was then asked to take over the same codebase using a two-stage strategy: get it running first, then refine and optimize it. This process is more valuable than simply comparing which model writes code faster. It exposes the engineering capabilities that matter most in low-level software delivery: code review, runtime evidence collection, minimal patching, regression validation, and risk control.
1. Why Low-Level Environments Demand a Complete Engineering Loop
In ordinary application development, model-generated code can often be validated quickly with mature frameworks, standard libraries, and powerful debugging tools. A pre-boot firmware environment is different. Its constraints are closer to those of an embedded system:
- The runtime is limited. There is no complete operating-system process model or full standard-library implementation. Memory management, graphics output, input polling, and timing all depend on firmware services.
- Observability is weak. Without a full debugger and logging system, developers may have to print a small amount of text on the screen or use a debug output channel to record progress. Without logs, it is difficult to distinguish initialization failure, graphics-mode failure, and a main-loop bug.
- Interface lifetimes are unusual. Pointers and descriptors returned by some protocols or services may not remain valid indefinitely. After switching graphics modes, reallocating buffers, or relocating a protocol, an old pointer may already be invalid.
- The build pipeline is often opaque. A mismatch in header paths, target architecture, linker scripts, compiler options, or dependency versions can cause the project to fail before the program starts.
- Error handling is not optional. In application software, some errors can be ignored. In firmware, a null-pointer access or an incorrect identifier match can lead directly to a blank screen or a reboot.
Therefore, a modular appearance only shows that the code has some organizational structure. It does not prove that the code satisfies low-level runtime constraints. A successful build means only that syntax, types, and linking relationships work in one particular environment. A successful first run means only that the main path did not immediately hit an obvious error. Maintainable delivery still requires systematic validation of lifecycles, boundary conditions, resource cleanup, and observability.
2. A Two-Stage Delivery Strategy: Restore Execution, Then Improve Quality
When a structurally complete legacy codebase does not run, asking an LLM to perform a large rewrite is usually not the safest approach. A more reliable method is to divide the work into two stages.
Stage One: From Non-Executable to Basically Runnable
The first stage is not about elegance. Its goal is to establish the smallest working loop:
- Freeze the original code, preserve the directory structure, and record the current dependencies and build commands.
- Review the code first, identifying build blockers, startup blockers, runtime crashes, resource leaks, and logic risks.
- Add phase-level logging to confirm whether the entry point, protocol discovery, mode switching, main loop, and exit path are reached.
- Use minimal patches to remove blockers. Avoid changing the architecture, interfaces, and business logic in the same modification.
- Rebuild and run after every patch, recording the result so that the problem remains reproducible and the fix remains verifiable.
Stage Two: Refinement and Stability Improvements
Once the program can enter its main loop, the second stage can address quality issues:
- Verify that framebuffer width, height, stride, and pixel format are consistent.
- Add coordinate clipping to prevent out-of-bounds drawing.
- Optimize dirty-rectangle updates to reduce unnecessary full-screen redraws.
- Improve key mapping, debouncing, and key-repeat behavior.
- Review timing mechanisms and avoid busy waiting that can produce abnormal responsiveness.
- Complete exit and recovery paths so that failures do not leave the environment in an unusable state.
- Create repeatable acceptance tests covering startup, rendering, input, pause, termination, and exit.
The central idea is to turn “not runnable” into “observable,” then turn “observable” into “repairable,” and finally turn “repairable” into “verifiable.”
3. Step One: Code Review Should Build a Risk List, Not Repeat the Code
The first instruction given to the model should be deliberately restrained: review the code, but do not rewrite it. Ask the model to categorize problems and provide evidence and an impact assessment for each one.
An effective review checklist can include:
- Does the entry function initialize global state correctly?
- Does protocol discovery check the return status and handle count?
- Are necessary descriptors reacquired before and after switching graphics modes?
- Are the framebuffer pointer, width, height, stride, and pixel format validated together?
- Does the main loop have an exit condition, and can error paths clean up resources?
- Does input polling handle empty events, repeated events, and invalid key values?
- Is there a fallback when memory allocation fails, and are allocation and release paths paired?
- Is the build configuration consistent with the target architecture and toolchain?
One advantage of an LLM is that it can inspect multiple modules quickly and produce a candidate list of issues. However, candidate issues are not conclusions. In engineering practice, the results should be divided into three categories:
- Must fix
- Needs verification
- Can be deferred for optimization
This prevents style suggestions from being mixed together with genuine startup blockers.
Example pseudocode:
Input: original source code, build logs, runtime logs, target-environment constraintsOutput:1. Build-blocking issues (must fix)2. Startup or runtime crash issues (must fix)3. Resource and lifecycle risks (needs verification)4. Performance and maintainability issues (can be scheduled)Requirements:- For each issue, provide the file, function, trigger condition,evidence, and the smallest verification method.- Mark uncertain conclusions as hypotheses.- Do not invent interface behavior.
4. Step Two: Turn “The Program Exits” into a Locatable Runtime Failure
A common symptom is that the program starts, prints “entered the main loop,” and then exits immediately. This proves that at least part of the initialization path was reached, but it does not prove that initialization completed correctly.
At this point, the priority is not to ask the model to guess another version of the code. Instead, add phase markers and status output so that the failure can be narrowed to a specific call range.
Useful logging points include:
- Entry into the main function.
- Successful or failed graphics-output protocol discovery.
- Successful or failed queries for the current display mode.
- Successful or failed attempts to set the target display mode.
- Successful or failed retrieval of framebuffer information.
- Entry into the first frame of the main loop.
- A heartbeat message every few frames.
- Exit from the main loop and resource cleanup.
If the logs show that the failure occurs after a graphics-protocol call, pointer lifetime should become a primary suspect.
A typical mistake is to query the display mode and receive a pointer to a descriptor. The program then changes the display mode. After the mode change, the old descriptor may no longer be valid because an internal buffer was rebuilt. If the program continues to use the old pointer to access width, height, or framebuffer information, it may crash or display a blank screen.
The repair principle is:
After switching modes, query the descriptor again and reacquire the required information. Do not reuse pointers that may have become invalid across a state transition.
Illustrative pseudocode:
status = locate_protocol(&handle, TARGET_GRAPHICS_ID, &gfx);if (status != OK) {log("locate graphics failed, status=%d", status);return;}status = query_mode(gfx, &mode);if (status != OK) {log("query mode failed, status=%d", status);return;}status = set_mode(gfx, mode);if (status != OK) {log("set mode failed, status=%d", status);return;}/* Important: reacquire the descriptor after changing the mode */status = query_mode(gfx, &mode);if (status != OK) {log("requery mode failed, status=%d", status);return;}fb = get_frame_buffer(gfx);if (fb == NULL || fb->width == 0 || fb->height == 0) {log("invalid frame buffer");return;}
The important point is not the exact function names. It is the need to collect fresh evidence after a state change. In low-level development, any operation that switches, resets, relocates, or reallocates a resource may invalidate old pointers, handles, or descriptors. If a model checks only types and signatures, it can easily miss this runtime contract.
5. Step Three: Why Incorrect Protocol Identifiers Are Difficult to Detect
Another common failure is that the graphics interface never appears, even though the program does not crash. Logs may show that the main loop continues to run, but the display does not show the expected output.
The problem may occur during protocol discovery. A system can contain multiple protocol identifiers or configuration constants with similar names. If the wrong identifier is passed to the discovery function, the call may fail or return a handle that does not provide the expected capability.
This class of defect has several characteristics:
- The project compiles normally.
- The constant looks plausible during a static review.
- If the error path does not record the status code and handle count, the failure may be mistaken for a rendering bug.
- Once the problem is misclassified as a drawing issue, development can continue in the wrong direction.
Effective practices include:
- Define protocol identifiers in one place instead of scattering similar constants across multiple files.
- Record the return status, handle count, and whether the handle is null after protocol discovery.
- Perform startup self-checks for critical protocols and return early when they fail.
- Verify identifiers against the target-environment specification rather than relying on similar names.
- Test protocol discovery, mode switching, and framebuffer acquisition as separate stages to avoid coupling failures.
Illustrative validation logic:
status = locate_protocol(&handle, EXPECTED_GRAPHICS_ID, &gfx);if (status != OK || handle == NULL) {log("protocol locate failed: status=%d, handle=%p", status, handle);return;}if (!validate_graphics_capability(gfx)) {log("graphics capability invalid");return;}
The key is to make failures visible. Without status codes and handle information, a model may interpret “the protocol was not found” as “the rendering function was never called.” With the additional logs, “the screen is blank” becomes “matching a specific identifier failed,” which sharply reduces the repair scope.
6. Step Four: Common Quality Gaps in Low-Level Game Loops
Once the program runs, the second stage of optimization can begin. Common quality gaps in low-level game projects include the following.
1. Framebuffer Access Boundaries
Before drawing, verify that coordinates fall within the valid region. Also account for stride, pixel format, and total buffer size. A single out-of-bounds write can corrupt adjacent memory and appear later as a random crash.
2. Pixel Format and Color Ordering
Different graphics modes may use different pixel layouts. If the color-channel order is incorrect, the image may appear discolored or display stripes. Start with a single-pixel rendering test before expanding to rectangles, text, and sprites.
3. Input Polling and Key Debouncing
Firmware input events may be repeated, dropped, or delivered in an unexpected order. The game loop should distinguish between press, hold, and release states, and key actions should have debouncing or a minimum interval. Pause, restart, and exit controls require an explicit state machine.
4. Timing and Frame-Rate Control
Busy waiting is simple but wastes processor time and can affect input responsiveness. Use available timing services or schedule frames based on elapsed time to prevent logic speed from varying with machine performance.
5. Clean Exit and State Restoration
If the program changes the display mode, it should restore the original mode when possible and release resources before exiting. Error paths also need cleanup logic; otherwise, a later run may be affected by leftover state.
6. Preserving Observability
Do not remove all diagnostic output during the refinement stage. A tiered logging system can emit only errors and key state changes by default, while debug builds provide detailed phase information. This preserves maintainability and makes future failures easier to reproduce.
Example acceptance checklist:
| Acceptance area | What to check | Pass criteria |
|---|---|---|
| Build | Dependencies, architecture, and linker configuration | Reproducible build in a clean environment |
| Startup | Entry point, protocol discovery, and mode setting | Each phase produces status output |
| Rendering | Screen clearing, pixels, rectangles, and text | Drawing is correct within boundaries |
| Input | Direction, confirmation, pause, and exit | Debouncing and state transitions work correctly |
| Logic | Collision, scoring, game over, and restart | Behavior is repeatably verifiable |
| Exit | Resource release and mode restoration | No residual invalid state |
| Regression | Patch history and test results | Issues are traceable and reversible |
7. Why “It Compiles Once” Does Not Mean High-Quality Delivery
When generating code, a model can often keep type signatures consistent and preserve module interfaces. As a result, a successful build is entirely possible. But many risks in a low-level project exist outside the compilation stage:
- Did protocol discovery occur during the correct initialization phase?
- Were return statuses checked at every layer?
- Is a pointer still being used after a state transition?
- Does the buffer size match the display mode?
- Can an input event be empty?
- Does an abnormal exit restore the environment?
- Can long-running execution reveal a memory leak or counter overflow?
These questions cannot be answered reliably by simply rereading the source. They require logs, minimal reproductions, and gradual isolation. An LLM can accelerate hypothesis generation, but it cannot replace verification.
A practical collaboration model is:
- The human defines goals and constraints: runtime environment, acceptance criteria, and code that must not be changed.
- The model proposes candidate solutions: review checklists, patch suggestions, and test cases.
- The human maintains the evidence chain: run, record, compare, and roll back.
- The model performs secondary analysis: narrow the hypothesis space using newly collected logs.
- Engineering acceptance makes the final decision: completion is not based on whether the code merely looks reasonable.
8. A Reusable AI-Assisted Repair Workflow
The overall process can be summarized as a five-step loop:
Observe → Hypothesize → Instrument → Apply a Minimal Patch → Regression Test
- Observe: Preserve build logs, runtime logs, screen output, and status codes.
- Hypothesize: Ask the model for the three most likely causes and the evidence required for each one.
- Instrument: Add logs or self-checks at critical stages instead of blindly changing business logic.
- Apply a minimal patch: Fix one verifiable issue at a time and preserve the diff.
- Regression test: Repeat startup, rendering, input, and exit tests to confirm that no new issue was introduced.
A neutral prompt template could be:
You are helping repair a project in a pre-boot firmware environment.Constraints:1. Do not rewrite the entire project; use minimal patches only.2. Analyze the logs before drawing conclusions.3. Mark uncertain interface behavior as a hypothesis.4. Provide verification steps and a rollback point for every fix.5. Organize the response into: hypotheses, evidence, patch, and verification.Current symptom: the program prints that it entered the main loop and then exits.Existing logs: protocol discovery succeeded, but the descriptor was notqueried again after changing the display mode.Provide no more than three root-cause hypotheses and specify whatadditional observations should be added next.
This style of prompt shifts the model from being a code generator to being a diagnostic assistant, which is more suitable for risk control in low-level engineering.
9. A Note on Fair Model Comparisons
Comparing models based on two different tasks, different code sizes, or different environment states is not rigorous. Game type, initial context, prompt wording, and build environment can all affect the outcome.
A more meaningful evaluation should control the variables: the same requirements, the same token or time budget, the same build environment, and the same acceptance tests. The number of human interventions should also be recorded.
For engineering teams, a single comparison between models is not the most important issue. The more important question is whether the team can establish a stable collaboration process in which models continuously produce verifiable value during review, repair, testing, and documentation.
10. Conclusion: The Key Is Orchestrated Repair, Not Getting Everything Right the First Time
The most important lesson from this exercise is not whether a model can write a game in a few hours. It is whether the model can maintain engineering discipline when faced with legacy code:
- Review before changing.
- Collect evidence before guessing.
- Restore the smallest working loop before optimizing.
- Verify each patch before expanding the scope of modification.
Pre-boot firmware projects have strict constraints, weak observability, and complex lifecycle requirements. Any code that merely “looks runnable” must still pass state checks, boundary checks, resource cleanup, and regression testing.
Large language models can be effective assistants in low-level development, especially for code review, hypothesis generation, log analysis, and incremental repairs. They cannot replace engineering judgment. The reusable methodology is to place the model inside an observe → hypothesize → instrument → patch → verify loop, ensuring that every change has evidence, a defined scope, and a rollback point.
That is how broken code can be moved reliably toward a state that is runnable, maintainable, and ready for delivery.
