Debugging Legacy Code with LLMs: A Practical Two-Round Approach
This article shares a practical workflow for using AI coding tools to debug legacy code, especially firmware and graphics programs. It explains why taking over undocumented existing code is harder than generating from scratch, then walks through a two-round method: first making the code run with static review, minimal verification, observability, and targeted fixes, and then hardening it. Common failure patterns, root causes, and a team checklist are included.
1. Where the Problem Starts: Why Debugging Legacy Code Is Harder Than Generating From Scratch
In real development work, what drains a team’s energy is rarely writing a new module from scratch. It is taking over an existing implementation with unclear origins, missing documentation, and no guarantee that it runs. This kind of code often shares one trait: it looks well-structured at a glance, with clear module boundaries, a reasonable number of files, and acceptable naming. But once it runs in a real environment, it exposes a large number of problems tied to environmental assumptions.
A controlled comparison illustrates the point. When an AI coding tool was asked to build a small graphical game from scratch, one implementation took about two and a half hours, compiled on the first attempt, and ran successfully on the first try. Another took nearly six hours, never got the build environment working, and produced no executable result. It is tempting to read this as a ranking of model capability, but the real value is a pattern it reveals: the success rate of from-scratch generation depends heavily on whether the model has sufficient prior knowledge of the target runtime environment. When you take over legacy code, the model faces an artifact that is already fixed and full of implicit assumptions, so debugging becomes significantly harder.
This makes “fighting magic with magic” a worthwhile experiment: letting another model clean up the mess left by the first one. It is a useful stress test because it measures not generation ability but understanding, diagnosis, and repair.
2. Methodology: Two Rounds, First Make It Run, Then Make It Good
Splitting the work into two rounds is the key to controlling complexity.
The goal of Round 1 is to move from “does not run” to “runs,” making only the minimum necessary changes without chasing elegance. The goal of Round 2 is refinement and optimization: structure cleanup, boundary handling, and improvements to performance and maintainability. This layered approach prevents you from falling into a refactoring pit while you are still trying to locate the problem.
Within each round, a fixed four-step loop works well:
- Static review: Do not run the code. Read it to find suspicious points and build a problem list.
- Minimal verification: Take the shortest path to get the program running and observe the first failure point.
- Evidence gathering: Add logging, serial output, and state prints to turn a “black-box crash” into an observable sequence.
- Targeted fix: Change one variable at a time, regress immediately after each change, and confirm causality.
3. Round 1, Step 1: Static Review Should Produce an Actionable Problem List
After copying the legacy code unchanged into a clean environment, the first instruction should be very restrained: review this code and list possible problems. The point is not to have the model critique code style. It is to require a module-by-module pass covering the entry function, main loop, business logic, rendering module, and input handling, and to output a structured list.
A usable list should contain at least four kinds of information:
- Location: File- and function-level positioning.
- Symptom hypothesis: What the failure would look like if this spot were wrong.
- Root-cause inference: Why it would happen and which implicit assumptions are involved.
- Verification method: How to confirm or rule it out at minimal cost.
A sample list structure can look like this:
[Module] Rendering initialization[Location] Graphics output protocol acquisition logic[Hypothesis] Frame buffer info becomes invalid after mode set[Cause] Reused the buffer descriptor obtained before mode set[Verification] Print buffer base address and size, compare with a fresh query after mode set
The value of this step is that it anchors every later debugging action to a verifiable hypothesis instead of random trial and error.
4. Round 1, Step 2: Root Causes and Fixes for Two Common Failure Classes
Legacy graphics programs running in a firmware environment most often expose two kinds of problems.
4.1 Exits Immediately After Startup: Pointer Reuse Across Lifecycles
The typical symptom: the program starts smoothly, prints the log marking the start of the main loop, and then the process ends with no error message. This kind of “silent exit” is usually not a logic error but an access to memory that is no longer valid.
In a firmware graphics initialization flow, the code typically queries the current mode information first and then sets the target mode. The problem is that setting the mode changes the video memory layout, so the frame buffer descriptor obtained earlier may become invalid. If the code keeps using the old pointer, it reads an invalid address, triggers a fault, and exits.
The fix principle is clear: any time you cross a call boundary that “changes the resource layout,” you must re-acquire the resource descriptor. The corrected logic can be abstracted as:
/* Set the mode first, then query again to avoid using a stale descriptor */status = set_mode(handle, target_mode);if (is_error(status)) return status;/* Key step: re-acquire the frame buffer info */status = query_mode(handle, target_mode, &info);if (is_error(status)) return status;framebuffer = info->frame_buffer;stride = info->stride;
The general lesson is that caching a descriptor is a subtle form of coupling when the resource lifecycle is uncertain.
4.2 Runs but Shows Nothing: Wrong Protocol Identifier Configuration
The second symptom is that the program no longer crashes and the main loop keeps running, but nothing appears on screen. Here the problem is often not in the rendering logic but in the fact that the code “never obtained the correct graphics output interface.”
Firmware specifications usually define multiple graphics-related identifier constants, each pointing to an interface for a different purpose. If initialization uses a mismatched identifier, location fails, and every subsequent draw call operates on a null object, which naturally produces “no response.”
A good investigation path follows the order of evidence:
- Print the return status of the interface location call to confirm whether it failed or succeeded with an invalid object.
- Print the frame buffer base address, stride, and resolution, and compare them with expected values.
- Print a call counter at the entry of the draw function to confirm the code path is actually executed.
- Only if the first three are normal should you suspect pixel format and coordinate conversion.
A defensive pattern looks like this:
void *gop = NULL;status = locate_protocol(&gop_guid, &gop);if (is_error(status) || gop == NULL) {log("gop locate failed: %x", status);return status;}log("fb=%lx stride=%u w=%u h=%u",info->frame_buffer, info->stride,info->width, info->height);
5. A Key Round 1 Technique: Turn the Unobservable Into the Observable
The biggest enemy in legacy debugging is insufficient information. Three effective techniques:
- Move the serial/log channel forward: Add markers before and after every external call to build a timeline.
- State over values: Print not only values but also whether a stage was reached, so you can tell a crash from an early return.
- Binary localization: Split the suspicious interval in half, confirm the boundaries first, then narrow down to the specific call.
Once the failure point is compressed to “right after a specific external call,” the fix often becomes obvious.
6. Round 2: What to Do in the Refinement Phase
Once the program runs, the focus shifts from correctness to robustness:
- Complete error handling: Check the return status of every external call and never ignore it.
- Standardize resource acquisition order: Fix the “set, query, use” sequence as the standard flow and add comments explaining why.
- Validate parameter boundaries: Clamp coordinates, stride, and buffer size uniformly at entry.
- Make it configurable: Extract hard-coded constants into configuration items for easier adaptation to different environments.
- Keep observability: Retain debug logs by level instead of deleting them all.
7. A Practical Checklist for Teams
- When taking over legacy code, require a structured problem list before making changes.
- Change one variable at a time, regress immediately, and keep evidence of causality.
- For any call that “changes the resource layout,” re-acquire the resource descriptor by default.
- For no-output problems, investigate interface location and identifier configuration first, not the rendering algorithm.
- Treat debug logs as part of the deliverable, not temporary scaffolding.
8. Conclusion
The most important takeaway is not that one model is stronger. It is that the value of AI coding tools in diagnosis and repair depends on whether developers can provide clear environmental constraints and observable feedback. Split the task into two rounds, turn review into a list, and turn crashes into a timeline, and human-AI debugging efficiency stabilizes. This method does not depend on any specific tool and can be applied directly to firmware, driver, and graphics development in your own projects.
