Debugging Legacy Code with Large Language Models: A Practical Workflow
This article shares a practical workflow for using AI coding tools to debug legacy code, especially graphics and firmware programs that are well-structured but fail to run. It covers building observability first, using static review to produce a verifiable issue checklist, diagnosing two common root causes (dangling pointers after mode switches and incorrect interface identifier constants), and refining stability, logging, input-logic decoupling, and resource usage. The key takeaway is that a disciplined process matters more than the choice of tool.
1. Where the Problem Starts: Why Legacy Code Is Hard to Take Over
In engineering practice, the hardest task is often not writing a new program from scratch, but taking over code that “looks well-structured yet won’t run.” A representative case from the original practice: an AI coding tool generated modular code for a small graphics game, split into entry point, main loop, game logic, rendering, and input handling files. The structure was clean, but the project stalled at setting up the build environment and never produced a runnable binary. Only after switching to another AI coding tool was the program gradually brought to life.
Legacy code of this kind typically has three characteristics:
- Correct structure, wrong semantics: The module layout is reasonable and the interface signatures are complete, but semantic details such as pointer lifetimes and resource acquisition order are wrong.
- The failure surfaces far from the root cause: The program exits during graphics initialization, while the root cause lies in a mode switch a few lines earlier.
- Lack of observability: There are no logs, no serial output, and no breakpoint conditions. Failures show up only as “nothing on screen” or “the process disappears.”
So the first step in taking over legacy code is not to change the code, but to establish observability.
2. First Round Goal: From “Won’t Run” to “Runs”
2.1 Do a Static Review First and Build an Issue Checklist
Before making changes, have the AI coding tool perform a full review of the code, covering five main lines: the entry function, the main loop, logic updates, rendering, and input handling. The output should be a verifiable issue checklist, not a vague “the code quality is poor.” A solid checklist usually includes:
- Whether resource acquisition and release are paired;
- Whether pointers passed across functions remain valid after the call returns;
- Whether global state is initialized repeatedly in multiple places;
- Whether protocol/interface identifier constants match the version of the specification they depend on;
- Whether error return values are ignored.
The value of the checklist is turning “mystical debugging” into “item-by-item elimination.”
2.2 Failure One: Dangling Pointer After a Mode Switch
After startup, the program printed its first log line and then the process exited. After adding finer-grained serial logs, the crash was traced to a graphics output protocol call.
The root cause was a classic pointer lifetime error: the mode info pointer obtained when querying mode information pointed to an internal buffer of the protocol. After switching the display mode, the buffer contents became invalid, the pointer turned into a dangling pointer, and dereferencing it later triggered the exception.
The fix is “switch first, then query”: re-fetch the frame buffer info after the mode is set, instead of reusing the query result from before the switch. Illustrative code:
// Wrong: reuse the info pointer from before the switchModeInfo *info = NULL;Status = GraphicsOutput->QueryMode(GraphicsOutput, 0, &Size, &info);Status = GraphicsOutput->SetMode(GraphicsOutput, 1);UseFrameBuffer(info); // info is already invalid// Correct: query again after the switchStatus = GraphicsOutput->SetMode(GraphicsOutput, 1);Status = GraphicsOutput->QueryMode(GraphicsOutput, 1, &Size, &info);UseFrameBuffer(info);
The general lesson here: for a pointer used across calls, always confirm its validity period covers the point of use.
2.3 Failure Two: Incorrect Interface Identifier Constant
The program no longer crashed, but the graphical interface never appeared. Continuing to analyze the logs revealed an incorrect reference to the graphics output protocol’s identifier constant. A single specification often defines several similar identifiers to distinguish different versions or purposes. Referencing the wrong one causes protocol lookup to fail, showing up as “the interface exists but can’t be obtained.”
The fix is to unify the source of identifiers: reference constants only from the specification header file, and never hardcode values in business code. Also, print the specific identifier and status code on the initialization failure path, so next time it’s quick to tell whether it’s “protocol not found” or “the protocol returned an error.”
2.4 Checklist for This Stage
- Have all pointers confirmed for lifetime before use?
- Is there any “use before init” ordering inversion?
- Do all identifier constants come from a unified header file?
- Does every failure branch have a printable status code?
- Do the serial logs cover the three key points: initialization, mode switch, and first-frame rendering?
3. Second Round Goal: From “Runs” to “Usable”
Running is only the starting point. For the refinement stage, advance along four lines:
- Stability: Turn occasional exits into recoverable error handling, and degrade gracefully on rendering failure (for example, fall back to an unbuffered mode) to avoid exiting the whole process.
- Observability: Grade the logs. Output detailed status during initialization, and only anomalies and frame-rate statistics during runtime, to avoid flooding the serial port and affecting timing.
- Decouple input from logic: Separate input sampling from logic updates, use a fixed logic step, and let rendering follow the display refresh, so speed does not depend on machine performance.
- Resource-constraint awareness: Make clear the source and usage of the frame buffer, fonts, and bitmaps, and avoid requesting large temporary memory in constrained environments.
Illustrative main loop structure:
while (running) {PollInput(&input); // sample inputAccumulateTime(&acc); // accumulate with a fixed stepwhile (acc >= STEP) {UpdateGame(&game, &input);acc -= STEP;}Render(&game); // follow the display refresh}
4. Methodology: Four Principles of Human-AI Collaborative Debugging
- Observability first, logic changes second: Debugging without logs and status codes is just guessing.
- Checklist first, action second: Turn review conclusions into a verification table that can be checked off item by item.
- Minimal reproduction first, wider scope second: Change only one variable at a time, and verify immediately after each change.
- Constraints first, optimization second: Clarify boundary conditions such as memory, timing, and display mode before discussing experience improvements.
5. Conclusion
The core conclusion of this practice is not that one tool is “stronger,” but that when facing legacy code, the right process matters more than the choice of tool. Static review produces a checklist, logs drive layer-by-layer localization, the two high-frequency root-cause categories (pointer lifetime and identifier consistency) are checked first, and stability and experience refinement come last. This workflow transfers to the vast majority of graphics and firmware debugging scenarios. Combined with general capabilities such as cloud builds, log services, and monitoring alerts to centralize management of the build environment and runtime logs, teams can further improve collaboration efficiency on similar tasks.
