Debugging Legacy Code with Large Language Models: A Practical Playbook
This article presents a practical methodology for taking over half-finished legacy code—especially low-level graphics code left behind by another developer or AI model—using large language models as reviewable collaborators. It breaks the work into two rounds (getting the code to run, then refining it) and three diagnostic layers (static, runtime, and protocol/environment). Key lessons include requesting a structured issue list before any patches, treating platform constants as strict contracts, re-acquiring framebuffer descriptions within their valid lifetime, and prioritizing observability through staged serial logging and fail-fast checks. The article also covers input handling, timing, resource cleanup, and how collaboration structure determines output quality.
1. The Starting Point: Why Legacy Code Is Harder Than a Blank Project
In real development work, taking over a half-finished codebase left by someone else—or by another AI—often takes longer than starting from an empty project. There are three main reasons:
- Hidden assumptions are invisible: The original author (or model) made many unwritten assumptions about the runtime environment, call ordering, and memory lifetime. When those assumptions break, the program fails in opaque ways such as crashes or a black screen.
- Failure signals are extremely sparse: Low-level graphics programs do not produce rich stack traces. You may get only a line or two over the serial console, so diagnosis relies on inference.
- Modules are tightly coupled: The entry point, main loop, game logic, rendering, and input handling are all intertwined, so changing one place can break another.
A typical case looked like this: an AI coding tool was asked to build a small graphics game. After several hours it still could not set up a compilable environment and produced no runnable program. Yet the code it left behind was structurally reasonable—split across multiple files with clear modularity. Throwing it away seemed wasteful, so a different model was brought in to clean up the mess, creating a scenario of “one AI cleaning up after another.” That scenario is a useful abstraction for a general methodology.
2. Methodology Overview: Two Rounds and Three Layers
Split the legacy-code takeover into two rounds:
- Round 1: From dead code to runnable. The goal is to eliminate crashes and black screens and to establish observability.
- Round 2: Refinement and optimization. The goal is to remove stutter, tearing, input latency, and memory risks.
Diagnose problems across three layers:
| Layer | Focus | Typical approach |
|---|---|---|
| Static | Module responsibilities, interface contracts, resource lifetime | Have the model review module by module and produce an issue list |
| Runtime | Call ordering, return values, pointer validity | Add serial logging and use bisection |
| Protocol/environment | Identifier constants, mode settings, dependency versions | Check constants and call order against the specification |
3. Round 1, Step One: Have the Model Do a Structured Review
Do not open with “fix this for me.” First ask for an issue list. The instruction can be very restrained:
Review this code. List, by module, the issues that could cause crashesor a black screen. For each issue, note the evidence and the suggestedfix location. Do not modify the code directly.
An effective review should cover the entry function, main loop, game logic, rendering module, and input handling. The output should be a set of verifiable hypotheses, not vague commentary. The value of this step is turning debugging from blind trial-and-error into working through a checklist.
4. Typical Issue One: Framebuffer Info Becomes Invalid After a Mode Switch
Symptom: After startup, the program prints the log marking the start of the main loop, then exits immediately—a classic crash.
Diagnosis: Add serial logs along the critical path and observe where output stops. The failure occurred right after a graphics output protocol call. Inspecting the information pointer returned by the mode query revealed that it pointed to memory that was not held stably: after the display mode was set, the contents of that memory block were already invalid, so dereferencing it later meant accessing a wild pointer.
Root cause abstraction: Resource description information must be re-acquired within the lifetime in which it is used. A “queried description” cannot be treated as a long-lived handle.
Fix outline:
1. Query the available modes and select the target mode.2. Set the mode.3. After setting is complete, re-acquire the current mode's framebufferdescription (address, dimensions, pixel format).4. Use that description only during the current draw pass; do not cacheit across frames.
After the fix, the program no longer crashes—the first gate toward “runnable.”
5. Typical Issue Two: Wrong Graphics Protocol Identifier Causes a Black Screen
Symptom: The process stays alive, but nothing appears on screen.
Diagnosis: Comparing the runtime log against the code showed that the identifier constant used when locating the graphics output protocol did not match the one defined in the platform specification. This is very common in low-level development: multiple related identifiers often exist for the same functionality, and picking the wrong one makes the interface lookup fail. That failure is frequently ignored by upper layers, ending up as a silent black screen.
Root cause abstraction: Platform constants are a strict contract and must follow the specification; never guess based on name similarity.
Fix points:
- Maintain a “constant-to-purpose” reference table in one place to avoid scattered hard-coded values.
- Check the return value of every protocol/interface acquisition, and print an explicit error code on failure instead of continuing.
- Write “acquire-use-release” as a fixed template to reduce omissions.
6. Observability: The First Priority in Low-Level Debugging
Where there is no graphical output, logs are your eyes. Follow three principles:
- Stage your checkpoints: one line each for initialization, mode setting, buffer acquisition, main loop, and input reading.
- Carry context: print return values, error codes, whether key pointers are null, and dimension parameters.
- Make it switchable: use compile-time macros to separate debug and release builds so logging does not drag down performance.
#define LOG(fmt, ...) serial_printf("[%s] " fmt, __func__, ##__VA_ARGS__)status = locate_protocol(id, &gop);LOG("locate_protocol status=%r gop=%p", status, gop);if (EFI_ERROR(status) || gop == NULL) {return status; // fail fast to avoid downstream wild pointers}
“Failing early and fast” is easier to diagnose than “running on with an error.”
7. Round 2: From Runnable to Usable
Getting it running is only the start. During refinement, focus on:
- Timing and frame rate: update logic with a fixed timestep and decouple rendering from logic so logic speed is not tied to frame rate.
- Input handling: debounce and use edge detection so a single key press does not trigger multiple actions.
- Memory and resources: unify release paths to avoid leaks on exceptional branches.
- Portability: funnel platform-specific calls into an adaptation layer to make reproduction in other environments easier.
8. Collaboration Lessons: Treat the Model as a Reviewable Collaborator
The real takeaway is not that one model is stronger, but that collaboration structure determines output quality:
- Ask for a list first and patches second, avoiding large uncontrolled changes.
- Solve only one class of problem per round, producing small, rollback-friendly steps.
- Use logs and return values as a shared factual basis to reduce mutual guessing between models.
- Write specification constants and interface contracts into prompts and comments so context is portable.
Productizing this workflow typically requires supporting engineering capabilities: a container platform to unify the build environment, object storage to archive versioned artifacts, a logging service to collect serial and runtime logs centrally, and monitoring and alerting to track build and runtime failure rates. The general capabilities Baidu AI Cloud offers for this kind of development pipeline are meant to make “reproducible, observable, and rollback-able” the default.
9. Conclusion
Legacy code is not the real problem; repeated trial-and-error without a method is. Break the takeover into static review, runtime observation, protocol verification, small-step fixes, and refinement, then let a large model play a reviewable execution role. That turns a “train wreck” into a high-quality refactoring exercise.
