LLM Coding Assistants in Firmware Development: A Practical Workflow for Debugging and Legacy Code
In low-level firmware, driver, and system software work, LLM-based coding assistants are shifting from simple code generators into development collaborators. They can produce a first version of code from a requirement, but they can also join in code review, log analysis, defect localization, refactoring, and engineering cleanup. This article shows how to use them to take over structurally complete but unstable legacy code and refine it through two rounds of iteration: a "runnable" round focused on code review, serial-log analysis, and basic defect fixes, and a "refinement" round focused on refactoring, error handling, state management, and observability. Using a firmware graphical mini-game as the case study, it covers startup-crash diagnosis, frame-buffer and video-mode handling, module decoupling, state-machine design, and log-driven debugging, and it outlines where these tools genuinely help, where they fall short, and how to give them effective constraints and feedback.
In firmware, driver, and system software work, intelligent coding tools are gradually evolving from “code generators” into “development collaborators.” They can generate a first version of code from requirements, but they can also take part in code review, log analysis, defect localization, refactoring, and engineering cleanup. Unlike ordinary application development, however, firmware development places much higher demands on hardware state, memory lifecycle, protocol call order, and debugging observability, where even a small error can cause a failed boot, a black screen, no serial output, or a runtime crash. So the practical question many developers care about is how to properly use intelligent coding tools to take over legacy code, fix defects, and optimize in a second pass.
This article uses a typical firmware graphical mini-game as an example to discuss how intelligent coding tools are used in a real project. The overall approach is not to generate a brand-new project, but to hand a piece of structurally complete but unstable legacy code to an intelligent coding tool and complete the fixes and optimizations through two rounds of iteration. The first round aims to get the program to boot, run, and enter the main loop. The second round aims to improve stability, maintainability, and code quality. This kind of practice is closer to real development scenarios and reflects the value and the limits of intelligent coding tools more objectively.
1. From “Regenerating” to “Taking Over Legacy Code”
When developers first started using intelligent coding tools, many focused on their ability to generate code from scratch—for example, producing a program skeleton directly from natural-language requirements. But once a project reaches a real stage, developers more often run into legacy code maintenance problems: the code is not entirely unusable, but it has structural defects, unclear environment dependencies, incorrect protocol calls, chaotic resource management, or insufficient logging.
This kind of code usually has a few characteristics. First, the module division looks complete, with an entry point, main loop, rendering, input, and game logic, but the boundaries between modules are not clear. Second, the code compiles but behaves unstably at runtime—it exits right after startup, the screen does not refresh, input is unresponsive, or serial logs cut off. Third, the errors are often not isolated syntax issues but cross-module lifecycle problems, such as dangling pointers after a mode switch, incorrect acquisition of protocol instances, or unsynchronized buffer state.
For these reasons, having an intelligent coding tool take part in code review is often more valuable than having it rewrite the entire project. It can help developers quickly build a “problem map,” identify potential defects, and propose changes, which are then verified step by step against real runtime logs. The advantage of this approach is that the developer still holds final control, while the intelligent coding tool plays the role of analyzing, localizing, and suggesting fixes.
2. Test Design: Two Rounds to Improve Verifiability
When evaluating the practicality of an intelligent coding tool, a single generated result is not enough. Tasks differ greatly from one another, so comparing only one output makes it easy to mistake task difficulty, environment complexity, or differences in how requirements are phrased for differences in capability. A more reasonable method is to validate the same class of task in layers.
This article splits testing into two rounds.
The first round is the “runnable round.” The goal is to bring the legacy code from a state where it cannot start, crashes, or shows a black screen back to a state where it can enter the main loop and keep running. This stage mainly validates the tool’s code review, log analysis, and basic defect-fixing ability.
The second round is the “refinement round.” The goal is to optimize code structure and improve stability, readability, and maintainability. This stage mainly validates the tool’s ability in engineering refactoring, error handling, state management, and performance optimization.
The purpose of this staged design is to separate “can run” from “easy to use.” In low-level software, compiling does not equal running, and running does not equal being stable and reliable. Two rounds of iteration make it clearer how the intelligent coding tool contributes at each stage.
3. Round One: From Static Review to Locating Runtime Problems
1. Code Review: Build a Problem List First
Before running anything, the first step is not to make changes blindly, but to review the code as a whole. You can ask the intelligent coding tool to analyze the code structure across several dimensions: the entry function, main loop, game logic, rendering module, input handling, protocol calls, and resource release.
During the review, focus on these questions:
- Does the entry function complete the necessary initialization, including the console, serial port, graphics output, and input devices?
- Is there any blocking in the main loop, and can a single failed call cause it to exit directly?
- Is the graphics output protocol acquired at the right stage, and are the current display details re-queried after a mode switch?
- Does input handling depend on external events, and is there any busy-wait or polling failure?
- Are there any out-of-bounds, wild pointer, or uninitialized memory access issues in memory and buffers?
- Are error codes being ignored, and do failure paths leave resources unreleased?
- Is there enough serial logging, and can it output state at key steps?
Based on these dimensions, the intelligent coding tool can produce a preliminary problem list. For example, it might point out that the main loop lacks state checks, that there is no error handling when graphics output initialization fails, that frame-buffer information is not re-acquired after a mode switch, or that the input module is too tightly coupled with the rendering module.
The key benefit at this stage is not to fix every problem immediately, but to give the developer an overall awareness of the code’s risks. For a complex legacy project, building a problem map first and then addressing issues one by one is safer than making a large-scale change all at once.
2. Startup Crash: Serial Logs Are the Key to Low-Level Debugging
After the first run, a common problem is that the program outputs some logs briefly and then exits directly. For a graphical firmware program, this kind of problem is often related to display initialization, protocol calls, mode settings, or memory state.
In low-level environments, serial logging matters far more than in ordinary desktop applications. Before a graphical interface is established, it is hard to see the cause of an error on screen, whereas serial logs can continuously output initialization steps, return codes, and key state. So during debugging, you can have the intelligent coding tool enhance logging—for example, recording entry into functions, call results, error codes, the current mode, and buffer addresses.
By analyzing the logs, you can often find that the program exits abnormally right after a graphics output protocol call. At this point, two kinds of problems need close attention.
The first is whether the mode was set successfully. If the call to set the display mode fails but the program continues to fetch the frame buffer or enter the render loop, it may not be able to proceed.
The second is whether the data is still valid after the mode switch. Some graphics interfaces return a data structure containing resolution, frame-buffer address, pixel format, and so on after querying the current display information. But once the display mode changes, the previously obtained structure may no longer be reliable, and reusing the old pointer can cause access violations.
Simplified pseudocode can illustrate this problem:
Status = SetVideoMode(gGop, Mode);if (EFI_ERROR(Status)) {return Status;}Status = QueryVideoInfo(gGop, Mode, &Size, &Info);if (EFI_ERROR(Status)) {return Status;}Status = SetVideoMode(gGop, Mode);UseOldInfo(Info);
In this logic, if the second mode set changes the display state, the data that Info previously pointed to may already be invalid. A safer approach is to re-query the current mode information after the mode is set, and then use the latest frame-buffer address:
Status = SetVideoMode(gGop, Mode);if (EFI_ERROR(Status)) {return Status;}Status = QueryVideoInfo(gGop, Mode, &Size, &Info);if (EFI_ERROR(Status)) {return Status;}FrameBuffer = GetFrameBuffer(Info);EnterGameLoop(FrameBuffer);
This kind of fix does not look complicated, but with the help of an intelligent coding tool it can significantly shorten localization time. After the developer feeds the logs back to the tool, it can infer possible failure causes from the error location and propose a change. The developer then recompiles and runs, and verifies the effect through the serial logs.
3. Graphical Interface Not Displaying: Protocol Choice and Interface Semantics Must Match
When the program no longer crashes but the screen still shows nothing, the problem usually shifts from “crash” to “invisible initialization result.” At this point you need to check whether the graphics output protocol was acquired correctly, and whether the way its interfaces are used matches the definition in the development environment.
In low-level graphics development, the choice of protocol or interface is critical. Different interface versions, different implementation paths, and different function signatures can lead to inconsistent behavior. If the acquired protocol instance does not match the calling convention, you may see a call succeed but the screen not refresh, an invalid frame-buffer address, or an incorrect pixel format.
At this stage, the intelligent coding tool can help the developer check how the interfaces are called, including:
- Whether the protocol is located correctly, using a protocol identifier recognized by the current project.
- Whether the queried protocol instance matches the way it is used later.
- Whether the display mode number is valid, and whether the resolution and color depth match expectations.
- Whether the frame-buffer address is non-null and located in accessible memory.
- Whether the rendering function actually writes pixel data, rather than just running an empty loop.
- Whether the screen refresh mechanism is triggered, and whether there is a problem of writing to memory without submitting a refresh.
At this stage, the debugging focus shifts from “does the program crash” to “does the program produce the expected visible effect.” Developers can output the display mode, frame-buffer address, resolution, pixel format, and other information over serial to confirm whether graphics initialization succeeded. If serial shows initialization is normal but the screen still has no content, then you need to further check the render loop, coordinate calculations, color writes, and refresh mechanism.
The intelligent coding tool can offer layered suggestions based on these clues. For example, first verify that the protocol was acquired successfully, then verify that the mode was set correctly, then verify that the frame buffer is writable, and finally verify that the game scene is actually drawn. This layered troubleshooting is more reliable than directly guessing that a particular function is wrong.
4. Round Two: From Runnable to Maintainable
Once the program can run, that does not mean the work is done. Firmware and low-level programs have high requirements for long-term maintenance. If the code structure is chaotic, error handling is inadequate, or state management is unclear, later extensions become noticeably harder. So the goal of the second round is not to keep piling on features, but to do engineering-level optimization.
1. Split Modules to Reduce Coupling
A common problem with legacy code is unclear module responsibilities. For example, game logic directly contains rendering calls, input handling directly modifies global state, and the main loop simultaneously handles initialization, event processing, drawing, and error recovery. This structure can run in the short term but is hard to maintain.
The intelligent coding tool can help the developer split the code into clearer layers, for example:
- System initialization layer: responsible for protocol acquisition, display mode setting, and input device initialization.
- Game state layer: responsible for start, pause, game over, scoring, and collision detection.
- Rendering layer: responsible only for converting game state into graphical output.
- Input layer: responsible for collecting user actions and turning them into events.
- Logging layer: provides unified debug output and error recording.
With modular separation, developers can locate problems more precisely. For example, screen flickering may be a rendering-layer problem, unresponsive keys may be an input-layer problem, and a game-logic error does not require modifying low-level graphics code.
2. Introduce a State Machine to Manage Game Flow
Low-level graphical programs are especially well suited to a state machine. Because the firmware environment often has no complex operating system scheduling, program behavior needs to be controlled through explicit states. Without a state machine, it is easy to handle start, pause, game over, and other flows with a large number of conditional checks in the main loop, which leads to tangled logic.
A simplified state definition can look like this:
typedef enum {STATE_INIT,STATE_READY,STATE_RUNNING,STATE_PAUSED,STATE_GAME_OVER} GAME_STATE;
The main loop decides behavior based on the state:
while (1) {switch (state) {case STATE_READY:WaitForStartInput();break;case STATE_RUNNING:UpdateGameLogic();RenderGame();break;case STATE_PAUSED:HandlePauseInput();break;case STATE_GAME_OVER:RenderGameOver();break;default:break;}}
This approach makes it easier for the intelligent coding tool to understand the program structure and makes it easier to add features later. For example, when adding scoring, levels, difficulty selection, or sound triggers, you only need to extend the corresponding state and events, without breaking the existing flow.
3. Strengthen Error Handling and Recovery
A program that runs is not necessarily robust. Problems common in the first round—ignored error codes, continued execution after a failure, and unreleased resources—need to be addressed in the second round.
A few principles are worth following:
- Every initialization call should check its return status.
- When a critical step fails, output a clear error code rather than exiting directly or silently continuing.
- After a display mode set fails, do not keep accessing a frame buffer that may be invalid.
- When the input device is unavailable, the program should enter a safe state rather than fall into an infinite loop.
- After a rendering failure, record the failure location, and if necessary reduce the frame rate or return to a basic interface.
The intelligent coding tool can help generate a unified error-handling template, for example:
Status = InitGraphics();if (EFI_ERROR(Status)) {LogError("Graphics init failed", Status);return Status;}Status = InitInput();if (EFI_ERROR(Status)) {LogError("Input init failed", Status);return Status;}
This kind of structured error handling significantly improves debugging efficiency and makes the program behave more controllably under abnormal conditions.
4. Improve Observability
The observability of firmware programs is usually weaker than that of server programs. Without a full operating system, file system, or debugger, serial logs, state output, and lightweight counters are very important. In the second round of optimization, you can have the intelligent coding tool add the following observability information:
- Time taken by each initialization stage.
- Display mode and resolution.
- Frame-buffer address and size.
- Input event count.
- Game loop frame count.
- The most recent error code.
- A record of state transitions.
For example, you can output a line of log at each key state change:
LogState("STATE_READY");LogState("STATE_RUNNING");LogState("STATE_GAME_OVER");
These logs may look simple, but they are crucial in low-level environments. They not only help developers locate the current problem, but also provide a basis for later regression testing.
5. Capability Boundaries and Reasonable Positioning of Intelligent Coding Tools
This kind of practice shows that intelligent coding tools can play a clear role in firmware development, but they cannot replace the developer’s engineering judgment.
Tasks they are well suited for include:
- Quickly generating code skeletons and module divisions.
- Statically reviewing legacy code and pointing out potential problems.
- Giving fix suggestions based on logs and error messages.
- Refactoring code with confusing names and complex structures.
- Adding comments, logs, and error handling.
- Generating test cases or verification steps.
- Assisting in writing documentation and interface descriptions.
Scenarios where they should not be fully trusted include:
- Precise control over hardware registers, memory layout, and boot order.
- Unverified protocol calls and low-level interface semantics.
- Complex concurrency, interrupts, and tasks with extremely high real-time requirements.
- Black-box changes made without logs or testing support.
- Directly replacing a critical initialization flow without regression verification.
For this reason, an intelligent coding tool is better viewed as an “efficient collaborator.” Developers need to provide clear context, explicit acceptance criteria, and real runtime feedback. Without a feedback loop, the changes a model suggests may only be syntactically reasonable and not necessarily fit the low-level runtime environment.
6. Practical Recommendations: How to Use Intelligent Coding Tools Effectively
Based on the process above, a few reusable practices can be summarized.
1. Establish Verifiable Goals First
Do not just ask the tool to “fix the code” or “optimize the program”; make the goal explicit. For example:
- Round one: after startup the program does not crash, serial can continuously output logs, and the screen can refresh.
- Round two: input responds stably, state transitions are clear, and key errors are recorded in logs.
The more specific the goal, the easier it is to verify the tool’s proposal.
2. Let the Tool Review the Code First, Then Propose Changes
For a legacy project, it is better to have a code review first rather than asking the tool to rewrite directly. You can first ask for a problem list, then address items one by one by priority. This avoids uncontrolled risk from large-scale changes.
3. Strengthen Log Feedback
Low-level debugging is inseparable from logs. Developers should provide the intelligent coding tool with serial output, error codes, call stacks, or key variable state. Compared with just describing “the program crashes,” providing complete logs makes localization more precise.
4. Modify Only One Key Problem at a Time
When fixing low-level problems, try to avoid modifying multiple modules at once. Each time a problem is fixed, recompile, run, and verify. This reduces variables and avoids introducing new invisible defects.
5. Keep a Minimum Runnable Version
During refactoring and optimization, keep a basic version that can start. If a later change causes new problems, you can roll back at any time, instead of continuing to debug from an unrunnable state.
6. Write Acceptance Criteria into the Prompt
When requesting help from an intelligent coding tool, you can state the constraints explicitly. For example:
Keep the existing module structure; do not rewrite the entire project.Prioritize fixing the startup crash.After the changes, provide verification steps.Every key call must check its return status.Do not introduce new external dependencies.
Clear constraints reduce ineffective changes and improve the usability of the output.
7. Conclusion
The value of intelligent coding tools in firmware development is not only in generating code, but more in helping developers quickly understand a legacy system, locate problems, improve the debugging path, and raise code quality. In low-level scenarios, the real difficulty is often not writing a particular piece of code, but understanding initialization order, resource lifecycles, protocol semantics, and exception recovery. So intelligent coding tools must be combined with serial logs, a runnable version, and manual review in order to work reliably.
From a practical standpoint, using the first round to solve “can it run” and the second round to solve “is it stable and maintainable” is a two-stage model well suited to intelligent coding tool involvement. Developers should use these tools to improve efficiency rather than replace judgment, and should value the feedback loop rather than a single generated result. As long as the method is right, intelligent coding tools can fully become efficient assistants in low-level development and legacy system maintenance.
