Debugging Legacy Code with LLMs: A Practical Walkthrough for Firmware Graphics Programs
This article shares a practical approach to using AI coding tools to debug inherited legacy code in a firmware environment. It explains why "looks complete but won't run" code is harder to fix than a blank project, how limited observability shapes the debugging process, and how to move from static review to a runnable program. You will find a structured troubleshooting workflow, real examples of pointer lifetime and protocol identifier bugs, and four principles for collaborating effectively with AI coding assistants.
1. Where the Problem Starts: Why Taking Over Legacy Code Is Harder Than Generating from Scratch
In real development, we often run into this scenario: a project has an initial version of code generated by an automated pipeline or another developer. The structure looks complete and the modules seem clearly separated, but the program simply won’t run. This kind of legacy code—presentable but non-functional—is often harder to handle than an empty project, for several reasons:
- The generator has already “assumed” certain preconditions hold, and those preconditions do not hold in the real environment;
- Clean code structure creates a false sense of security and hides runtime problems;
- There is no observability, so when something fails there are no logs to trace.
This article uses a hands-on example of letting an AI coding tool take over a legacy graphics program in a firmware environment. The goal is to discuss how to systematically move it from “non-runnable” to “runnable and optimizable.” Note that the point of this practice is not to compare the capabilities of different tools, but to summarize a general troubleshooting workflow.
2. Environment Constraints Determine Debugging Difficulty
In firmware and low-level graphics programming, debugging options are naturally limited:
- There is no mature operating system runtime, so exceptions often show up as a direct reboot or a silent exit, with no stack trace;
- The only output channel is usually the serial port, which has extremely low bandwidth;
- Graphics output depends on protocol interfaces provided by the firmware, and their lifecycle management rules differ greatly from conventional user-space programming.
As a result, any “just get it running first” strategy fails here. You must establish observability first, and only then talk about fixes.
3. Round One: From Static Review to Runnable
3.1 Start with a Code Review and Build a Problem List
The first instruction after taking over should not be “fix this for me,” but “review this code and list the possible problems.” Have the model inspect each module—entry point, main loop, business logic, rendering, and input handling—and produce a structured list. The value of this step is that it:
- Breaks the vague “it won’t run” into several verifiable hypotheses;
- Establishes a priority order for subsequent fixes;
- Avoids changing code while guessing, which introduces new uncertainty.
3.2 Problem One: Exits Immediately After Startup
The program does start, but it exits right after printing the loop-start message. After adding finer-grained serial logs, the exception is located to just after a graphics protocol call. Further analysis reveals that the information pointer returned when querying the mode has become invalid after the mode switch—a classic wild pointer problem where the memory a pointer points to has a shorter lifetime than the pointer itself.
The fix is to adjust the call order: re-fetch the frame buffer information after the mode is set, instead of reusing the pointer from before the switch.
// Bad: keep using the old pointer after switching modesQueryMode(gop, mode, &info);SetMode(gop, mode);use_framebuffer(info); // memory info points to may already be invalid// Good: re-fetch after switchingQueryMode(gop, mode, &info);SetMode(gop, mode);QueryMode(gop, mode, &info);use_framebuffer(info);
The general lesson from this kind of problem is: whenever a state-changing operation sits between “acquiring a handle/pointer” and “using the handle/pointer,” you must re-confirm whether the handle is still valid.
3.3 Problem Two: The Graphics UI Fails to Render
The program no longer exits, but nothing appears on the screen. Analysis points to an incorrect identifier configuration for the graphics output protocol: the underlying framework defines several related identifier constants, and using the wrong constant means you cannot obtain the correct protocol instance.
The fix is to check the constant definitions, switch to the identifier that matches the current graphics output protocol, and add an explicit error return when acquisition fails, rather than continuing to execute.
4. Round Two: Refinement and Stability Hardening
Once it runs, the focus shifts to maintainability:
- Add return value checks for every external interface call; on failure, print the error code and exit safely;
- Consolidate the repeated “acquire—use—release” logic into a single wrapper function to prevent reusing expired pointers again;
- Add consistent stage labels to the serial logs to quickly tell which step it is stuck on;
- Add boundary checks to rendering and input handling to avoid illegal coordinates or out-of-range indices.
An illustrative error-handling wrapper:
Status start_graphics(void) {Status s = locate_protocol(&guid, &gop);if (s != OK) { log("locate failed: %d", s); return s; }s = gop->SetMode(gop, kMode);if (s != OK) { log("setmode failed: %d", s); return s; }s = gop->QueryMode(gop, kMode, &info);if (s != OK) { log("query failed: %d", s); return s; }fb = info->FrameBufferBase;return OK;}
5. Methodology: Four Principles for Working with AI Coding Tools
- Review first, modify later: have the tool output a problem list, then let a human confirm the priorities;
- Observability first, fixes later: don’t touch the code without logs;
- Verify in small steps: change only one variable at a time, and run immediately after each change;
- Make the tool “converge” rather than “diverge”: merging duplicate logic and unifying error handling is the highest-value direction for refinement.
6. Conclusion
Making legacy code runnable is essentially an engineering process of “hypothesize—verify—converge.” AI coding tools can significantly speed up each iteration, but only if a human provides clear constraints and verifiable feedback signals. In low-level environments lacking a graphical interface and stack traces, serial logs and strict interface return value checks remain the irreplaceable first-hand evidence.
