How AI Takes Over Legacy Firmware Code: A Two-Round Debugging Approach

    A practical walkthrough of using AI to take over and debug legacy firmware code. It splits the work into two rounds — first making the code runnable, then making it usable — and explains how to build evidence, fix the build environment, set up observability, and verify each change. It walks through two common firmware defect patterns (a dangling pointer across calls and a protocol identifier mismatch), provides prompt templates and acceptance criteria, and closes with a discussion of where AI helps in debugging and where humans must step in.

    1. Background: AI Taking Over Legacy Code and Firmware Debugging

    When developers hand legacy code over to AI, firmware debugging is usually the scenario that most tests context and the evidence chain. Unlike generating a new project from scratch, legacy code may come from a departed colleague, an open-source repository, a previous AI-generated result, or an early human implementation. It might have a complete module layout yet still fail to boot, fail to display, or even behave differently on every power-on.

    There are two common tasks in AI-assisted programming. The first is greenfield generation: requirements are clear, the model builds a skeleton and writes logic in an empty directory, and as long as the syntax is correct and it compiles, you get an initial version. The second is taking over legacy code: the code already exists, but design documentation is missing, compilation may fail, it may crash at runtime, and the UI may stay blank. The difficulty of the second case concentrates in three areas:

    • Missing context: the model can’t see the original design intent and has to reverse-engineer it from the code surface.
    • Implicit contracts: especially visible in firmware code, where what really constrains behavior is often not the code itself but the runtime environment, protocol specifications, and hardware state.
    • Long feedback loop: after a change you must recompile, flash, power on, and observe the serial port and screen. Each verification is expensive and can’t be refreshed quickly like a web project.

    The scenario in this article is a typical case: a graphics program with a fairly tidy module layout — entry point, main loop, logic layer, rendering layer, and input handling each separated, seven files in total, with a clear structure — yet it neither boots nor draws anything. Deleting it outright is wasteful, and rewriting from scratch is also wasteful. A more reasonable approach is to have AI run a legacy-system health check on the existing code: since the legacy code may have been generated by a previous AI or by a human, AI shouldn’t blindly rewrite it, but instead behave like an engineer taking over an old system — establish evidence, locate the problem, and converge step by step.

    2. Methodology: Two Rounds, Not One “Just Fix It”

    The effective approach is to split the goal into two rounds, optimizing only one dimension per round.

    Round Goal Success criteria Explicitly out of scope
    Round 1 From non-runnable to runnable Enter the main loop after power-on, output the first frame, no crash Feel, performance, code aesthetics
    Round 2 From running to usable Normal input response, stable over long runs, controllable edge cases Architecture-level rewrite

    Mixing “make it run” and “make it run well” into a single instruction is a common cause of failure in AI troubleshooting. The model may change multiple variables at once; once behavior changes, the developer can’t tell which change had an effect, nor whether the problem was actually fixed or just happened to be bypassed.

    Once the methodology is set, you also need to add hardware risk warnings. Firmware debugging involves flashing, powering on, and interacting with real devices, so the risk is higher than in ordinary software engineering. Before flashing, back up the firmware first; confirm the device model, chip version, and flashing parameters; prioritize verifying on a development board or in an emulator; and don’t mistakenly flash production or mass-production devices without confirmation.

    Step 0: Fix the Environment and Observability First

    The bottleneck in firmware debugging is usually not “the model can’t make changes” but “you can’t see what’s happening inside.” Therefore, before writing the first fix instruction, do two things:

    1. Fix the build environment: pin the compiler toolchain version, dependency library versions, and compiler options. Environment drift turns “it builds on my machine” into a worthless statement.
    2. Set up a minimal observability channel: firmware usually uses serial debug output, while ordinary projects use structured logging. At minimum, you should be able to answer: which step has the program reached? What did the key call return?
    1. #define LOG(fmt, ...) SerialPrint(L"[" DBG_TAG "] " fmt L"\r\n", ##__VA_ARGS__)
    2. Status = GraphicsOutput->SetVideoMode(GraphicsOutput, Mode);
    3. LOG(L"SetVideoMode mode=%d status=%r", Mode, Status);
    4. Status = GraphicsOutput->QueryMode(GraphicsOutput, Mode, &Size, &Info);
    5. LOG(L"QueryMode status=%r size=%d info=%p", Status, Size, Info);

    The value of this step is that it turns “AI guesses” into “AI reads evidence.” Without logs, the model can only output changes that look correct probabilistically but have no logical basis; with logs, the model can make causal inferences around specific return codes, states, and branches.

    In the cloud, this “reproducible build + full logging” approach can also map to a general combination of capabilities: use a container platform to freeze the build image, use object storage to archive each build artifact, use a log service to centrally collect serial and CI output, and use monitoring and alerting to notify people when the pipeline failure rate is abnormal. These capabilities can help a team make the debugging process traceable rather than depending on individual memory every time a problem occurs.

    3. Round 1: Make It Run First

    3.1 Layered Code Review, Not a Vague “Find the Problems”

    The first instruction shouldn’t be “fix it for me,” but rather “review this code, find the problems that could prevent it from running, rank them by likelihood, and explain your reasoning.” To give the review structure, provide the model with a fixed checklist:

    • Entry and initialization: are return values checked when memory is allocated? Are handles or protocols actually acquired?
    • Main loop: what is the exit condition? Is there an exit branch that can’t be reached?
    • Resource lifecycle: are allocate, use, and free paired up? Do pointers remain valid after crossing calls?
    • Configuration and identifiers: do protocol IDs, mode numbers, and device handles match the platform spec?
    • Input handling: is key state debounced? How are long press and multi-tap handled?
    • Error paths: are all return status codes checked, or silently ignored?

    The point of a checklist isn’t to constrain the model but to make the output verifiable. The developer can confirm item by item whether the model actually read the code, rather than generating a plausible-looking but unfounded summary.

    3.2 Defect Type 1: Pointer Lifecycle Mismatch Causing a Crash

    After startup, the program prints the log that the main loop has begun, then exits immediately, indicating that the crash happens between initialization and the first frame render. Once located via serial output, the problem points to a common dangling-pointer-across-calls scenario: during the graphics output protocol’s display-mode switch, the internal data may be reorganized; after a successful switch, the previously queried mode info buffer may no longer represent the current mode, or may be invalidated by the protocol’s internal buffer management.

    Counter-example:

    1. UINTN SizeOfInfo = 0;
    2. MODE_INFO *Info = NULL;
    3. QueryMode(Gfx, Mode, &SizeOfInfo, &Info); // query mode info
    4. SetVideoMode(Gfx, Mode); // switch mode
    5. UINTN stride = Info->PixelsPerScanLine; // keep using the old query result, risky

    The fix idea is not simply to add a null check to the pointer, but to re-fetch authoritative data at the right time. If the project uses the standard graphics output protocol, you generally shouldn’t get the framebuffer base address directly from the mode info returned by QueryMode; a safer approach is to read it from the Mode structure of the current protocol instance. If the code’s MODE_INFO is a custom structure and does include a framebuffer base address field, then you must clearly state the field’s origin in the interface definition and comments, otherwise it’s easy to mislead.

    Fix example:

    1. Status = GraphicsOutput->SetVideoMode(GraphicsOutput, Mode);
    2. if (EFI_ERROR(Status)) {
    3. LOG(L"SetVideoMode failed: %r", Status);
    4. return Status;
    5. }
    6. UINTN SizeOfInfo = 0;
    7. MODE_INFO *Info = NULL;
    8. Status = GraphicsOutput->QueryMode(GraphicsOutput, Mode, &SizeOfInfo, &Info);
    9. if (EFI_ERROR(Status) || Info == NULL) {
    10. LOG(L"QueryMode after SetVideoMode failed: %r", Status);
    11. return Status;
    12. }
    13. // In standard contexts, prefer reading the framebuffer base from the current Mode structure
    14. if (GraphicsOutput->Mode == NULL) {
    15. LOG(L"GraphicsOutput Mode is null");
    16. FreePool(Info);
    17. return EFI_UNSUPPORTED;
    18. }
    19. FrameBufferBase = (volatile UINT8 *)(UINTN)GraphicsOutput->Mode->FrameBufferBase;
    20. PixelsPerScanLine = Info->PixelsPerScanLine;
    21. FreePool(Info); // The buffer returned by QueryMode is usually freed by the caller

    The general identification signal for this kind of defect is: the object itself is fine; the problem is its validity period. Any code that “queries first, acts, then uses the query result” should ask one question: after the action, does the query result still hold? If the action changes the mode, handle, layout, or buffer lifecycle, you should re-query rather than reuse the old result.

    3.3 Defect Type 2: Protocol Identifier Configuration Error Causing a Blank Screen

    The program no longer crashes, but the screen stays blank. At this point the problem shifts from “crashing” to “getting the wrong thing.” Services like graphics output need to locate a specific protocol instance by identifier; if the identifier doesn’t match the platform spec, three outcomes are possible: location fails, location finds the wrong instance, or you get a handle that doesn’t correspond to the actual display device.

    A safer approach is to enumerate handles rather than assume a single instance, and validate each protocol’s capability one by one:

    1. UINTN HandleCount = 0;
    2. EFI_HANDLE *Handles = NULL;
    3. Status = LocateHandleBuffer(ByProtocol, &GraphicsOutputGuid, NULL, &HandleCount, &Handles);
    4. if (EFI_ERROR(Status)) {
    5. LOG(L"no graphics output handle");
    6. return Status;
    7. }
    8. for (UINTN i = 0; i < HandleCount; i++) {
    9. Status = HandleProtocol(Handles[i], &GraphicsOutputGuid, (VOID **)&Gfx);
    10. if (EFI_ERROR(Status)) continue;
    11. UINTN Size = 0;
    12. MODE_INFO *Info = NULL;
    13. Status = QueryMode(Gfx, 0, &Size, &Info);
    14. LOG(L"handle %d mode0 status=%r resolution=%dx%d",
    15. (int)i, Status,
    16. (UINT32)(Info ? Info->HorizontalResolution : 0),
    17. (UINT32)(Info ? Info->VerticalResolution : 0));
    18. if (Info) FreePool(Info);
    19. }

    This probing code is itself a debugging tool. It first proves that the protocol exists, the handle is accessible, and the mode is queryable, and only then discusses rendering. Breaking the vague symptom of “can’t render” into four independently verifiable sub-problems — “protocol not found / mode not supported / wrong framebuffer address / wrong pixel format” — is a faster convergence path for this kind of problem.

    3.4 Let the Model Work in a Closed Loop

    The key to the first round isn’t how strong the model is, but whether the developer has given it a closed loop. A practical instruction template is as follows:

    1. Background: This is a graphics program that runs in a firmware environment, 7 files in total, with the goal of drawing an interactive block game on screen.
    2. Version and toolchain: firmware platform version <fill in>, compiler version <fill in>, current build command <fill in>.
    3. Log format: serial output is uniformly [TAG] message; key states use %r for the status code.
    4. Current state: after power-on, serial output <paste log>, then <crash / black screen / no response>.
    5. Expected: <describe the expected behavior>.
    6. Constraints:
    7. 1. Change one thing at a time; after each change, explain the reason and the verification method;
    8. 2. Don't rewrite the directory structure; don't introduce new dependencies;
    9. 3. Keep and add serial logs; output key return statuses;
    10. 4. Don't touch the following files: <list of files that must not be modified>;
    11. 5. If unsure, list the information you need me to supply rather than guessing.

    Among these, “change one thing at a time” and “ask if unsure, don’t guess” — in many practices, these two improve result quality more than frequently switching models.

    4. Round 2: From Runnable to Usable

    Being able to display a block only meets Round 1’s criteria. The real experience problems usually hide in the details, and this round is suitable for AI to handle in bulk, because each item is very specific and can be clearly verified.

    • Input handling: coupling key-scan frequency with the main loop frame rate causes movement to be too fast or too slow when a key is held. Decouple input sampling from logic updates, and add debouncing and repeat throttling. Acceptance criteria: in the serial log, record the x-coordinate after holding a direction key for 1 second and 5 seconds; the displacement difference should be less than one block width.
    • Frame rate and time step: advance game state with a fixed logic step and render independently, to avoid inconsistent speed across machines. Acceptance criteria: the log outputs the number of logic steps and the actual elapsed time; the number of logic steps per unit time should be stable rather than drifting with the render frame rate.
    • Framebuffer write range: full-frame redraw is expensive in a firmware environment; you can do partial refresh over the changed block region, and watch for pixel format and line stride. Acceptance criteria: the log outputs the dirty-rectangle coordinates and the write line stride; after partial refresh there’s no tearing or misalignment.
    • Collision detection and boundaries: handle the left/right walls and the top first, then the bottom determination, to avoid multiple state changes in the same frame overriding each other. Acceptance criteria: the log outputs collision event numbers and coordinates; each collision triggers only once per frame.
    • Randomness and reproducibility: fix the random seed to make it easy to compare behavior across versions; this is very important for regression testing. Acceptance criteria: with the same seed, running twice consecutively should produce an identical initial block position and subsequent sequence.
    • Resources and exception paths: all allocated memory and handles must be freed on the exit path; on abnormal exit, restore text output mode to avoid leaving the device on a black screen. Acceptance criteria: the log outputs resource allocate/free counts; after abnormal exit the count is zero and the screen returns to a diagnosable state.

    This round’s recommendation likewise follows “one item at a time + a clear verification method”:

    1. File: input.c.
    2. Problem: the block's movement speed fluctuates with the frame rate when a direction key is held.
    3. Requirement: change input sampling to a fixed-frequency poll independent of rendering, adding a 150ms initial delay and a 60ms repeat interval.
    4. Verification: record the x-coordinate after 1 second and 5 seconds respectively; in both cases the displacement difference should be less than one block width.
    5. Don't modify the rendering or game logic code.

    5. Conclusion: AI’s Capability Boundaries in This Kind of Work

    Abstracting this practice yields several transferable judgments.

    AI is good at evidence-based reasoning. Given logs, code, and clear constraints, it can converge the cause of a crash to a specific pointer use or an error path within a few rounds. This has an advantage over having it write a new feature from scratch, because the search space for troubleshooting is smaller and the feedback signal is clearer.

    AI is not good at filling in implicit conventions. Platform specs, hardware characteristics, and team historical decisions — things not in the code — it can only infer. So the part humans must take on is: providing context, defining acceptance criteria, and judging whether something is really fixed.

    Process matters more than the model. Fixing the environment, establishing logs, checklist-based review, single-variable changes, and reproducible verification — this process determines the upper limit of AI output usability. Missing any link, and even the strongest model may give a pile of changes that look reasonable but can’t be verified.

    The conclusion should also be measurable. It’s recommended to write an acceptance checklist for this kind of task rather than finishing by feel: can it go from power-on to first frame, does input respond, is it stable after 30 minutes of continuous running, can the exception path recover, and do key modules have testable pure-logic parts. Once it’s a checklist, AI collaboration can move from luck to engineering practice.