LLM-Assisted Firmware Legacy Code Repair: A Practical Engineering Approach
This article walks through a hands-on practice of using a large language model (LLM) to repair unstable firmware legacy code. Using a small block-style game as the case study, it covers a two-round repair process: the first round moves the program from crashing on startup to running stably with visible graphics and responsive input, and the second round turns a "runnable" program into one that is maintainable and extensible through rendering optimization, input debouncing, fixed-timestep logic, and diagnosable error handling. Readers will find concrete lessons on observability-first debugging, re-validating state after mode switches, unifying protocol interfaces, staged verification of graphics initialization, and small-step fixes, plus guidance on how to use LLMs as a code reviewer and debugging assistant rather than an unverified black box. It is intended for developers working on firmware, drivers, bootloaders, and low-level graphics programs.
LLM-Assisted Firmware Legacy Code Repair: A Practical Engineering Approach
1. Background: Why Firmware-Layer Code Is Hard to Repair
In software engineering, firmware-layer and bare-metal programs are often more complex and more dependent on environment details than ordinary application-layer code. Regular business code runs on top of mature process management, memory management, file systems, and debuggers. Firmware code, by contrast, typically has to face the boot flow, memory layout, the hardware abstraction layer, the graphics output protocol, input polling mechanisms, and serial log channels directly. Once a program crashes during the boot stage, developers often cannot rely on a graphical interface to inspect state or read the crash stack directly. Instead, they have to locate the problem step by step through serial output, memory markers, protocol handle checks, and similar means.
Because of this, repairing firmware legacy code is not simply a matter of “changing a few variables.” It involves constraints at multiple levels:
- Initialization order constraints: some protocols can only be located after the system table or image modules are loaded;
- Lifecycle constraints: a pointer may become invalid after a mode is set and its old value can no longer be used;
- Interface contract constraints: interfaces such as the graphics output protocol and input protocol have explicit requirements on parameter format and call order;
- Resource constraints: memory, stack space, and the frame buffer region are all very limited;
- Observability constraints: without a mature graphical interface, logs become the primary troubleshooting tool.
In this context, the value of a large language model is not to “write a finished product for the developer with one click,” but to make complex code review, hypothesis generation, log design, and repair-path planning more efficient. A mature approach is to treat the LLM as a code reviewer, debugging assistant, and refactoring advisor rather than as an unverified black box. Engineers still remain responsible for architectural judgment, interface confirmation, on-site verification, and final quality control.
The goal of this practice is not to evaluate a particular model, but to focus on “how to repair a piece of firmware graphics code that has already been generated but does not run stably.” The subject of the task is existing block-game code. Its code base is not large, but it involves entry logic, the main loop, rendering, input, game state, and protocol calls, making it a typical case for repairing low-level code. The overall process is divided into two rounds: the first round aims to get the program to start stably and display a screen; the second round aims to optimize rendering, input, logic, and error handling so that the program goes from “running” to “demonstrable, maintainable, and extensible.”
2. Overall Approach: Make It Observable First, Then Make It Run
In low-level program repair, the most common mistake is guessing the cause too early. Many developers, upon seeing a program crash, immediately modify memory allocation, protocol calls, or the entry function; upon seeing the interface fail to display, they repeatedly adjust the graphics mode. In reality, the root cause of a firmware problem is often hidden in call order, pointer lifecycle, or interface return values. Without logs and state markers, such changes become blind trial and error.
This practice follows these principles:
2.1 Logs First
Add prints before and after each critical call, for example:
log_info("enter init");log_info("locate protocol start");log_info("set mode start");log_info("query mode start");log_info("render start");
This lets you see exactly which stage the program stops at, rather than only knowing that “it crashed.”
2.2 Layered Verification
Break the boot process into multiple stages: initialization, protocol location, mode setting, frame buffer acquisition, input initialization, the main loop, rendering, and exit. Set a verifiable goal for each stage. Only when the previous stage is verified as passing do you move on to the next one.
2.3 Minimal Changes
When repairing, do not immediately refactor the entire code base. First locate the smallest fault point. For example, if the problem is that an old pointer becomes invalid after a mode switch, first fix the pointer-refresh logic rather than rewriting the rendering module.
2.4 Interface Contracts First
Many firmware interfaces depend on protocol handles and mode parameters. Before calling them, you must confirm whether the handle is valid, whether the return value is successful, whether the mode is supported, and whether the buffer pointer has been updated.
2.5 Preserve the Scene
After each repair, keep a runnable or rollback-able version. If a new change makes the problem worse, you can immediately fall back to the last stable point.
3. First Round of Repair: From Not Running to Running
3.1 Code Review: Build a Module Map First
At the start of the repair, first have the large language model do an overall review of the existing code rather than running the program directly. The review goals include:
- Whether the entry function completes the necessary initialization;
- Whether the graphics output protocol has been located;
- Whether the display mode was set successfully;
- Whether the frame buffer information was obtained correctly;
- Whether the main loop keeps running;
- Whether input polling contains an infinite loop;
- Whether there are null pointers, dangling pointers, or unchecked return values;
- Whether there is inconsistent state between modules.
From the review results, the program was divided into several modules: an entry module responsible for the boot flow, a main loop module responsible for frame scheduling, a game logic module responsible for collisions and state changes, a rendering module responsible for drawing graphics, and an input module responsible for reading keys. This structure itself is reasonable, showing that the original code was not entirely without architectural awareness. The real problems lie in the details of low-level interface usage and lifecycle management.
The model’s first-level conclusion was: the code structure can be kept, but there are risks in the boot flow and graphics protocol calls, especially in the way frame buffer information is obtained after a mode switch. This judgment set the direction for the subsequent repair.
3.2 Crash Problem: The Program Exits Immediately After Starting
When the program was first run, the boot log printed normally, but it quickly entered the exit flow. On the surface it looked like the entry failed, but the logs showed that the program had already attempted to enter the main loop, indicating that the problem may have occurred in the graphics initialization stage before the main loop.
To locate the issue further, more fine-grained debugging information was needed. After the fix, the serial output showed that the program threw an exception after setting the graphics mode and querying the mode information. The root cause gradually became clear: the code obtained mode information once before setting the mode and continued to use that pointer afterward. However, after a mode switch, the firmware graphics interface may change the underlying buffer, mode parameters, or internal data structures, so the old mode information pointer is no longer valid. Continuing to dereference the old pointer causes an abnormal read or an access to freed memory.
This kind of problem is uncommon in the ordinary application layer but very typical in firmware and driver layers. States such as hardware modes, video memory layout, and frame buffer addresses may change with mode setting. Any context obtained before a mode switch cannot be reused after the switch unless its validity is re-verified.
The repair strategy is clear: after setting the mode successfully, re-query the current mode and re-obtain the frame buffer information. The pseudocode is as follows:
status = set_mode(mode);if (error(status)) {log_error("set_mode failed");return status;}status = query_mode(current_mode, &info);if (error(status)) {log_error("query_mode failed after set_mode");return status;}frame_buffer = info->frame_buffer;pixels_per_scan_line = info->pixels_per_scan_line;
This code looks simple, but it embodies a core principle in firmware development: a mode switch must be accompanied by a state refresh. Any pointer, handle, offset, or size reused across a mode phase must be re-verified.
After the fix, the program no longer crashed during the boot stage and began entering the main loop. This was the first key milestone of the first round.
3.3 Interface Not Displaying: A Graphics Output Protocol Configuration Problem
The program no longer crashed, but the screen still showed no graphics. The logs indicated that the main loop had started and the rendering function was being called, but the target buffer was not initialized correctly, or the program had not correctly located an available graphics output protocol.
In low-level graphics programs, “protocol not found” and “protocol found but unusable” are two different kinds of problems. The former is usually a protocol location error, such as using a mismatched protocol identifier, a wrong load order, or image modules that were not registered correctly. The latter may be that the protocol handle is valid, but the mode parameters are unsupported, or the frame buffer address is empty.
During the code review, an inconsistency was found in the graphics output protocol identifier configuration: some places used a broad protocol definition, some used a specific version definition, and the current firmware environment only exposed one of the usable interfaces. Because low-level interfaces are very sensitive to protocol identifiers, an identifier mismatch causes the lookup to fail, or causes a lookup to find an unusable interface.
The fixes included:
- Unifying the graphics output protocol interface definition to avoid mixing definitions from different sources;
- Printing the protocol location result in the boot log;
- If protocol location fails, explicitly returning an error code and stopping subsequent rendering;
- If protocol location succeeds, continuing to check the mode count and current mode;
- Before rendering, verifying that the frame buffer address is non-null, the scanline width is valid, and the mode is reasonable.
The flow after the fix can be expressed like this:
status = locate_protocol(protocol_type, &interface);if (error(status)) {log_error("locate graphics protocol failed");return status;}status = check_mode(interface, &mode);if (error(status)) {log_error("mode check failed");return status;}render_frame(interface, frame_buffer);
The key to this kind of change is not any specific function, but turning “graphics initialization” into a checkable, fail-able, rollback-able state machine. Only when the protocol, mode, buffer, and rendering function are all verified as successful is the graphics environment considered ready.
3.4 Input Handling: Avoiding a Blocked Main Loop
In the later stage of the first round, the program could display a basic screen, but input response was unstable. Low-level input devices are usually read by polling. If the polling frequency is too high, it may cause meaningless interrupts or repeated key presses; if the polling interval is too long, it causes input latency.
The fix approach is to introduce a fixed time step:
- The main loop does not run at full speed according to the machine’s clock;
- Each frame first reads input;
- Then updates game logic;
- Finally renders the screen;
- Frame rate is controlled by counting or timestamps.
The logic looks roughly like this:
while (running) {poll_input(&input);update_game(&state, &input);render(&state);delay_frame();}
This approach avoids making game speed depend on hardware performance. Although a firmware environment has no full operating system scheduling, a relatively stable rhythm can still be achieved through simple delays, counters, or periodic timing.
3.5 First Round Summary
After the first round, the program went from “crashing on startup with no graphics” to “can start, can display, can receive input, and can enter the main loop.” The core lessons of this round are:
- Low-level code must establish logs first;
- After a mode switch, state must be re-obtained;
- Protocol location needs a unified interface definition;
- Graphics initialization should be verified in stages;
- Input polling must avoid blocking the main loop.
4. Second Round of Repair: From Running to Maintainable
The goal of the first round was to keep the program alive; the goal of the second round is to make the program stable, optimizable, and extensible. For a graphics program, “displaying” does not equal “a good experience.” If rendering is too frequent, input is duplicated, or game logic depends on frame speed, the program can still suffer from visual jitter, logic anomalies, and resource waste.
4.1 Rendering Optimization: Reducing Redundant Drawing
In a low-level graphics program, if every frame unconditionally refreshes all regions, it increases the number of frame buffer writes and may also cause screen flicker. Optimizations include:
- Refreshing only when the screen content changes;
- Using simple rectangular region updates instead of full-screen refresh;
- Separating the static background from dynamic objects;
- Choosing a suitable data-write method based on the frame buffer format;
- Performing boundary checks on the drawing region.
Illustrative code:
if (state->dirty) {draw_game(&state->frame_buffer, state);state->dirty = false;}
This change looks basic, but it can significantly reduce redundant rendering. For a block game, the background is usually fixed, and only the active block and the already-fixed blocks change. As long as dirty regions are marked correctly, repeated drawing can be reduced.
4.2 Input Optimization: Key Debouncing and a State Machine
Low-level input devices usually have no operating system input queue, so polling results may carry noise. If a key press is recognized as a new press multiple times in a row after being pressed, it causes game state to change rapidly, such as a block moving quickly left and right or falling quickly.
The fix is to introduce a simple key state machine:
- Record the current key;
- Record the previous frame’s key;
- Trigger an action only when the key transitions from not pressed to pressed;
- For continuous movement, set a separate repeat interval.
Pseudocode:
bool pressed = read_key();bool just_pressed = pressed && !prev_pressed;if (just_pressed) {handle_action(&state, pressed);}prev_pressed = pressed;
This approach can greatly improve the input experience and also avoid false triggers caused by low-level hardware noise.
4.3 Game Logic: Fixed Time Step and Separation of State
A common problem with graphics programs is that logic speed depends on rendering speed. If rendering is faster, the block falls faster, and the program behaves inconsistently across different devices. A more robust approach is to separate game logic from rendering:
- The game state stores the current block, next block, score, pause state, and so on;
- The logic update function handles only state and timing;
- The rendering function is responsible only for converting state into images;
- The main loop calls logic updates at a fixed rhythm;
- The rendering frequency can be independent of the logic frequency, or synchronized by frame.
This design helps with later extensions. For example, when adding pause, restart, increasing difficulty, a leaderboard, or sound effects, you do not have to modify the low-level drawing code.
4.4 Error Handling: Turning Failures into Diagnosable Information
In a firmware environment, program crashes often have no friendly interface. Therefore, error handling should aim to be “diagnosable.” It is recommended to add error codes and logs to each critical module:
if (error(status)) {log_error("module=%s code=%d", module_name, status_code);return status;}
For errors that prevent further execution, do not return silently and do not enter an infinite loop. Instead, you can:
- Print a clear error;
- Stop the main loop;
- Keep the serial log available;
- Return a unified error code;
- In a debug build, output the module name and stage information.
This kind of handling does not affect normal demonstrations, but it can significantly reduce later maintenance costs.
4.5 Maintainability: Module Boundaries and Interface Documentation
As a program moves from prototype to maintainable code, module boundaries need to be defined clearly. Each module should expose only the necessary interfaces, for example:
- Initialization module: provides an init entry and a destroy entry;
- Graphics module: provides clear-screen, draw, and refresh interfaces;
- Input module: provides polling and key-state interfaces;
- Game module: provides update, reset, and pause interfaces;
- Logging module: provides leveled logging interfaces.
Interface names should reflect their purpose, and parameters and return values should follow a unified convention. For example, all init functions should return a unified status code, and all draw functions should not assume that the caller has prepared all resources, but should perform minimal checks internally.
5. Key Lessons: The Right Way to Do AI-Assisted Low-Level Development
This practice yields several more general lessons.
5.1 LLMs Are Good at Code Review and Hypothesis Generation, but Must Be Verified
Large language models are good at quickly spotting suspicious points in large amounts of code, such as pointer usage, return value checks, initialization order, protocol calls, and error handling. But in firmware scenarios, the model’s suggestions can only serve as leads and cannot replace real runtime verification. Every change should have a clear observable metric, such as serial logs, memory addresses, return codes, or screen state.
5.2 The More Specific the Requirement, the More Reliable the Model Output
If you only say “help me fix the program,” the model has difficulty judging the fault point. More effective prompting includes:
- At which stage the current program exits;
- What the serial log outputs;
- What the behavioral difference is before and after the change;
- Which interfaces returned errors;
- Whether there is a fixed reproduction path;
- Which modules you want to keep unchanged.
This kind of context lets the model focus on the local problem rather than output generic advice.
5.3 Low-Level Programs Should Establish Observability First
For firmware programs, logs are more important than guesses. It is recommended to include at least:
- The boot version number;
- The initialization stage;
- The protocol location result;
- The mode setting result;
- Whether the frame buffer address is valid;
- Whether the main loop is entered;
- The input polling frequency;
- Exception error codes.
When each stage has clear logs, problem localization goes from “something feels wrong” to “the chain is traceable.”
5.4 Small-Step Fixes Are More Stable Than a One-Time Rewrite
Legacy code often contains valuable parts, such as module division, state structures, and the rendering framework. If the problem is concentrated in interfaces and lifecycle, prefer small-step fixes. Only when there is a fundamental architectural flaw, or when the repair cost exceeds the rewrite cost, should you consider a redesign.
5.5 Engineering Accumulation Determines Long-Term Efficiency
If this kind of repair work needs to become part of a team’s daily development, it is recommended to engineer the process:
- Use version control to save each repair node;
- Establish a unified build script to reduce environment differences;
- Bring firmware artifacts, logs, and build numbers under unified management;
- Use a log service to view serial output or runtime logs centrally;
- Use monitoring and alerting to detect batch build failures or release anomalies;
- Store key version artifacts in object storage to facilitate rollback;
- Build checklists for high-frequency errors, such as pointer lifecycle, protocol identifiers, and state refresh after a mode switch.
These practices do not depend on any particular cloud vendor; they are general engineering practices. On cloud platforms such as Baidu AI Cloud, you can also use general-category capabilities—such as code hosting, object storage, log services, and monitoring and alerting—to manage build artifacts, aggregate logs, and observe releases. But regardless of the tools used, the core remains reproducibility, traceability, and rollback capability.
6. Further Expansion Directions
Once the basic program can run stably, you can continue to extend its capabilities, but expansion must be built on top of stability.
6.1 Adding a Debug Mode
You can design two run modes: normal mode and debug mode. Normal mode pursues a clean demonstration, while debug mode outputs more logs, displays frame rate, and records input events and memory state. This way, demonstrations are unaffected while troubleshooting capability is preserved.
6.2 Adding Configuration Parameters
For example, difficulty level, frame rate cap, key repeat interval, block generation speed, and so on. Configuration items should be managed through a unified structure to avoid being scattered across multiple files. If a configuration is invalid, it should fall back to the default value and log it.
6.3 Adding Regression Tests
Although a firmware graphics program may not have a full test framework, you can build a minimal regression checklist:
- Whether startup passes;
- Whether protocol location succeeds;
- Whether mode setting succeeds;
- Whether the frame buffer address is valid;
- Whether the main loop keeps running;
- Whether keys can trigger actions;
- Whether logs can be output on exceptions.
Running these checks after every change reduces regression risk.
6.4 Strengthening Safety Boundaries
Firmware programs usually run at a lower level, where any out-of-bounds access can have serious consequences. During repair, pay special attention to:
- Whether array access is out of bounds;
- Whether pointers are initialized before use;
- Whether return values are checked;
- Whether buffer lengths match;
- Whether input values are valid;
- Whether frame buffer writes stay within range.
Safety boundaries are not an after-the-fact patch, but should be incorporated at the design stage.
7. Conclusion
This repair process—from legacy firmware graphics code to a runnable prototype—shows that a large language model can significantly improve the efficiency of low-level code repair, especially in code review, log design, protocol problem localization, and refactoring suggestions. But it cannot replace an engineer’s understanding of system boundaries, interface contracts, and the runtime environment.
A truly effective AI-assisted development process should place the model in a “assistive analysis” position and place verification in a “final decision” position. Developers need to provide sufficient context, establish observable logs, verify problems stage by stage, and use small-step fixes to ensure stability. For complex scenarios such as firmware, drivers, bootloaders, and low-level graphics programs, this approach is more reliable than simply demanding an “immediate fix.”
In the end, the value of this kind of practice lies not only in getting a particular program to run, but more in forming a reusable method: first sort out the modules, then establish logs; first verify interfaces, then optimize the experience; first make small-step fixes, then accumulate engineering practices. In this way, AI can truly become an effective tool in complex system development rather than an uncontrollable code generator.
