AI Takes Over Legacy Code: Troubleshooting a Firmware Graphics Application

    This article uses a firmware preboot graphics application as a case study to show how AI coding assistants can help debug legacy code. It covers setting acceptance criteria, reviewing code before modification, serial-log instrumentation, common protocol lifecycle and constant-selection errors, rendering and input improvements, and practical engineering principles for AI-assisted low-level development.

    1. Why Taking Over Legacy Code Is a Different Engineering Problem

    Generating code from scratch and taking over legacy code are fundamentally different tasks.

    When generating from scratch, the context is clean: requirements are explicit, constraints are clear, and acceptance criteria are defined by the author. In that case, the model mainly needs to write the code correctly.

    Taking over legacy code introduces three additional burdens:

    • Hidden constraints are often invisible. The code may have been written for a specific runtime environment such as preboot firmware, bare-metal execution without an operating system, no standard library, and limited memory or graphics memory. These assumptions may exist only in comments, headers, or the original author’s mind.
    • Acceptance criteria are missing. There may be no tests and no specification. “It runs” and “it runs correctly” are separated by a large semantic gap.
    • Errors are tightly coupled. A null pointer may not cause a crash until three modules later. Observing only the symptom often does not reveal the root cause.

    The practical conclusion is that model differences are easier to hide during code generation because impressive output can mask mistakes. During debugging, those differences are amplified. The final quality depends on whether the engineer can accurately feed symptoms back to the model, understand its reasoning, and validate fixes. In other words, the bottleneck in human-AI collaboration is usually not generation, but diagnosis.

    2. Case Study: A Graphics Application in a Firmware Preboot Environment

    The target is a small graphics game, similar to Breakout, running in a firmware preboot environment. The requirements include four points: on-screen prompts, interactivity, serial-visible runtime logs, and observability during failures.

    The legacy code shows a certain level of engineering quality. It is split into modules, with separate responsibilities for the entry point, main loop, game logic, rendering, and input handling. Naming is generally clear. However, it has two critical problems:

    1. The build and runtime environment cannot be established.
    2. Even when it barely runs, it stays at the stage of “exit immediately after startup” or “black screen.”

    2.1 Define Acceptance Criteria Before Making Changes

    For this kind of code, the first step is not to modify code, but to turn acceptance criteria into a checkable list. This creates a consistent evidence format for every debugging round and avoids guessing between human and model.

    • L1 Build passes: the cross-compilation toolchain produces a loadable firmware image without errors.
    • L2 Main loop is reached: the serial port shows loop-start logs, and frame counts continue updating.
    • L3 Visible frame: at the target resolution, the background color, boundaries, and initial blocks appear.
    • L4 Interaction works: key presses move the paddle, and collision detection takes effect.
    • L5 Stable and exitable: long-running execution does not crash, and the exit path does not produce anomalies.

    This tiered acceptance approach can be reused in other legacy-system takeover scenarios: break a vague goal such as “make it run” into independently verifiable milestones, each supported by objective evidence such as logs, screenshots, or memory readings rather than subjective judgment.

    3. Round 1: From “Cannot Run” to “Runs Stably”

    3.1 Review Before Editing

    After taking over the code, the first instruction is not “fix it,” but “review it.” The order matters. If the model is asked to modify code immediately, it may make many changes based on wrong assumptions. In the end, no one can clearly explain what changed, and rollback becomes difficult.

    An effective review prompt should include four elements:

    • Review scope: a list of modules or files to examine.
    • Review perspective: lifecycle management, boundary conditions, error-code handling, and protocol call contracts.
    • Output format: a problem list, evidence locations, impact area, and suggested fix order.
    • Constraints: do not change external interfaces.

    Typical model output includes null-check missing protocol pointers, cached pointers reused across state changes, wrong identifier constants, unreleased temporary buffers, array bounds risks, division-by-zero paths, and call sites that do not print error codes.

    The key is human review. The review may contain real issues as well as model misjudgments based on general experience, such as worrying about a memory allocation failure path that does not exist in this environment. Real issues should be sorted by priority: blockers to running first, correctness issues second, maintainability issues last. This sorted list becomes the task queue for Round 1.

    3.2 First Issue: An Information Pointer Becomes Invalid After a Protocol State Change

    The symptom is typical: the image loads, the serial port prints the loop-start log, and then the program exits immediately. This is even more confusing than a startup crash.

    The debugging method is serial instrumentation plus bisection. Print stage markers in order along the critical path, narrow the interval step by step, and quickly identify the abnormal point: the first framebuffer access after setting the graphics mode.

    The root cause is a lifecycle error. The mode information pointer obtained from the graphics output protocol points to data maintained inside the protocol. After calling SetMode, the protocol’s internal state and memory layout change. The previously obtained mode information pointer is no longer valid. Dereferencing it returns memory that has already been reused or released.

    The problematic pattern is roughly as follows:

    1. /* Bad example: reusing a mode information pointer across a state change */
    2. Status = Gop->SetMode(Gop, kTargetMode);
    3. Mode = Gop->QueryMode(Gop, kTargetMode, &InfoSize, &Info);
    4. /* The memory pointed to by Mode is no longer valid */
    5. FrameBuffer = (UINT8 *)(UINTN)Mode->FrameBufferBase;

    The correct sequence is: first check the return value of SetMode; after success, query the mode information again; then check the query result for errors and null pointers; and release temporary buffers when they are no longer needed.

    1. /* Corrected version: reacquire information after the state change and validate at each step */
    2. Status = Gop->SetMode(Gop, kTargetMode);
    3. if (EFI_ERROR(Status)) {
    4. LOG_ERR("SetMode failed, status=0x%x\n", Status);
    5. return Status;
    6. }
    7. Status = Gop->QueryMode(Gop, kTargetMode, &InfoSize, &Info);
    8. if (EFI_ERROR(Status) || Info == NULL) {
    9. LOG_ERR("QueryMode failed, status=0x%x\n", Status);
    10. return Status;
    11. }
    12. FrameBuffer = (UINT8 *)(UINTN)Info->FrameBufferBase;

    A reusable lesson from this issue is that any pattern of “obtain a handle or information, trigger a state change, then use old information” is high-risk. Similar traps exist with graphics devices, file handles, and network connections.

    3.3 Second Issue: Wrong Identifier Constant Causes Protocol Lookup Failure

    After the frame problem is fixed, the program can run, but the screen still shows no output and the graphics interface never appears. At this point, the model correctly identifies that the problem is likely in protocol lookup.

    In firmware environments, multiple related identifier constants, often GUIDs, may exist for the same functional family. They may point to different instances or different interface versions. Using the wrong one makes the lookup return “not found.” If the caller does not check the return value and directly dereferences the output parameter, the result may be the hardest symptom to debug: no picture, but no crash.

    The fix has two layers:

    • Correct the constant and use the graphics output protocol identifier that matches the current firmware specification.
    • Add defensive checks: every protocol lookup must check the return status; output parameters must be checked for null before use; and logs should print the identifier value and handle value for later comparison.
    1. EFI_STATUS Status;
    2. EFI_GRAPHICS_OUTPUT_PROTOCOL *Gop = NULL;
    3. Status = BootServices->LocateProtocol(&GraphicsOutputGuid, NULL, (VOID **)&Gop);
    4. if (EFI_ERROR(Status) || Gop == NULL) {
    5. LOG_ERR("LocateProtocol failed, status=0x%x\n", Status);
    6. return Status;
    7. }

    3.4 Prioritize Observability to Reduce Debugging Cost

    What really saved time in Round 1 was not the speed at which the model wrote code, but the quality of feedback. Three practices are worth keeping:

    • Grade serial logs by stage markers, parameter values, and error codes. Use a consistent format so they are easy to grep.
    • Print return codes for all external calls, turning silent failures into explicit failures.
    • Change only one verifiable goal at a time. After each change, run the L1-L5 checklist immediately so that conclusions can be attributed to specific edits.

    4. Round 2: From Running to Running Long and Running Well

    At the end of the first round, the program can run, display content, and respond to input. The second round focuses on four improvements.

    Rendering performance. Clearing the entire screen and redrawing all pixels every frame is expensive in a preboot environment. The optimization path is to use double buffering to reduce tearing, refresh only changed regions, and cap the frame rate to avoid unnecessary processor usage.

    Chinese text rendering. Chinese glyphs are not monospaced single-byte characters. The implementation needs a mapping from encoding to glyph indexes, line breaking and truncation based on glyph width, and caching of frequently used strings to avoid recalculating them every frame.

    Input handling. Add debouncing and key-repeat logic. Write key events to a ring buffer and consume them in the main loop, avoiding tight coupling between rendering and input.

    Robustness. Handle boundaries centrally: blocks leaving the play area, collision tunneling, array indexes, division by zero, and memory growth during long-running execution. Extract magic numbers into named constants, reduce header dependencies, and clarify module boundaries.

    5. Six Principles for Using AI Coding Assistants on Legacy Systems

    1. Review first, modify second. Ask the model to produce a problem list with evidence, decide priorities manually, and fix issues one by one.
    2. Define acceptance criteria early. Break the goal into tiered milestones, each requiring objective evidence.
    3. Make small, fast changes with one variable at a time. Each change should correspond to an attributable validation, avoiding a single large refactor.
    4. Make implicit constraints explicit. Runtime environment, available memory, lack of a standard library, logging conventions, and constant definitions must be written into the context. Do not expect the model to infer them.
    5. Treat observability as the first priority. Logs and error codes are more valuable than any optimization because they determine the iteration speed of human-AI collaboration.
    6. Low-level changes must be reviewed by a human. Code involving memory, handle lifecycles, and protocol calls requires model judgment to be confirmed by both specification requirements and practical testing.

    Supporting engineering infrastructure is also important. Put the code in a traceable repository, use continuous integration to ensure every change can be built, and use logging services and monitoring alerts to collect runtime data and detect anomalies. Teams can use standard cloud code hosting, logging, and monitoring capabilities to institutionalize this workflow and reduce repeated setup costs.

    6. Common Pitfalls Checklist

    • Reusing old device information pointers after a state change.
    • Failing to check the return status of a lookup call and directly dereferencing an output parameter.
    • Using an identifier constant that does not match the actual firmware version.
    • Not releasing temporary buffers, causing memory to grow during long-running execution.
    • Misusing standard library functions in an environment without a standard library, causing link-time or runtime errors.
    • Redrawing the entire screen every frame, leading to unpredictable frame rates.
    • Not printing error codes, making silent failures hard to locate.

    7. Conclusion

    The output of this case is a graphics application that can run, be played, and run for a long time. More valuable, however, is the process itself. The real value of an AI coding assistant is not how many lines of code it can generate in one pass. It is that it shortens every loop of “read code, form hypotheses, add instrumentation, inspect logs, and fix issues.” For engineers, the role shifts from “writing implementation” to “defining standards, validating conclusions, and controlling risk.” For domains such as firmware, drivers, and embedded systems, which depend heavily on runtime environments, this collaboration style is especially valuable. In these areas, the hardest part has always been not writing the code, but proving that it is correct.