Debugging Legacy Code with Large Language Models: A Practical Workflow
This article shares a practical workflow for using large language models to debug legacy code that compiles but fails to run. It explains why diagnosing existing code demands different skills than generating a project from scratch, then walks through a two-round iteration approach built on observability first. Key sections cover staged logging, two common failure patterns involving frame buffer information and graphics protocol identifiers, a refinement checklist for stability and usability, and four reusable principles for AI-assisted troubleshooting. Readers will learn how to turn vague failures into verifiable checklists and reduce uncertainty through structured review and small, reversible fixes.
1. Background: Why Taking Over a Mess Is Harder Than Generating from Scratch
In real development work, the most common scenario for AI-assisted programming is not generating a complete project from scratch. It is taking over legacy code of unknown origin that has a reasonable structure but does not run. This kind of code usually has a few recognizable traits: the module layout looks organized and the naming is acceptable, but the way key platform interfaces are used hides potential problems; there is no observability design, so a crash leaves nothing but a blank screen; and the original author has left, so comments no longer match the implementation.
From an engineering perspective, generating from scratch tests a model’s construction ability, while taking over legacy code tests its diagnostic ability. The model must rebuild a mental model of the program within a limited context, bridge the gap between “compiles” and “runs,” and locate faults in a bare-metal environment with no graphical interface by relying on serial output. This kind of task demands a more complete reasoning chain and better reveals the boundaries of AI value in real delivery workflows.
2. Overall Approach: Two Rounds of Iteration with Observability First
I split the practice into two rounds. The first round had a single goal: turn a program that “compiles but does not run” into a minimal, stable closed loop. Only the second round moved into refinement and optimization, covering input response, rendering cadence, resource release, and exception fallbacks.
The core principle across both rounds was observability first. In an environment with no display output, logs are the only eyes available. The concrete practices included:
- Insert staged logs with sequence numbers at each key phase, instead of only printing “success/failure”;
- Validate return values, handles, and pointers one by one, printing the error code and call site on failure;
- Break long flows into small steps that can be verified independently, avoiding too many changes at once that make attribution impossible.
A schematic example of log instrumentation looks like this:
// Staged logging: sequence numbers keep order traceableSTAGE_LOG(1, "enter main, image_base=%p", image_base);status = gBS->LocateProtocol(&gGopGuid, NULL, (VOID**)&gop);STAGE_LOG(2, "locate gop status=%r, gop=%p", status, gop);if (EFI_ERROR(status)) return status;status = gop->SetMode(gop, 0);STAGE_LOG(3, "set_mode status=%r", status);// Key point: re-fetch frame buffer info after SetModestatus = gop->QueryMode(gop, gop->Mode->Mode, &info);STAGE_LOG(4, "query_mode status=%r, fb=%p size=%u",status, info->FrameBufferBase, info->FrameBufferSize);
3. First Round of Debugging: Root Causes and Fixes for Two Frequent Faults
3.1 Review First, Then Act
The first instruction after taking over code should be a static review, not an immediate run. Have the model go through the code module by module across five dimensions: entry point, main loop, business logic, rendering, and input. The output should be a structured issue list: which items are fatal and will certainly cause a crash, which are latent risks triggered only on specific paths, and which are merely style issues. The benefit is converging uncertainty into a checklist you can tick off, avoiding a loop of “fix one thing, break another.”
3.2 Fault One: Frame Buffer Information Invalid After Mode Switch
The symptom was that the program printed a log entering the main loop right after startup, then exited. The root cause was ignoring the timing relationship between the graphics output protocol’s mode information and the mode switch: the frame buffer description obtained before the switch pointed to a memory region that was no longer valid after the switch, and continuing to use it meant accessing a wild pointer.
The fix was to adjust the call order and re-fetch the description: complete the mode set first, then query the current mode parameters, and base all subsequent drawing on the newly obtained base address and size. At the same time, add validation for null pointers and buffer size to prevent out-of-bounds writes to video memory when the resolution is abnormal.
// Wrong order: Query before SetMode, then use the old info// Correct order: SetMode -> Query -> use the latest infogop->SetMode(gop, mode);gop->QueryMode(gop, mode, &info);if (info == NULL || info->FrameBufferSize == 0) return EFI_UNSUPPORTED;
3.3 Fault Two: Incorrect Graphics Protocol Identifier Configuration
The program no longer crashed on startup, but the screen stayed blank. This kind of silent failure is usually not a logic error but a misconfigured platform interface identifier: the underlying framework contains multiple identifier constants related to graphics output, each with a different purpose, and mixing them up causes the located protocol instance to differ from expectations, so all subsequent calls return invalid results.
There are three ways to fix this. First, check the semantic comments of the identifier constants in the framework header files you are using, and choose the one that strictly corresponds to the graphics output protocol. Second, immediately after locating, validate that the returned instance’s member function pointers are non-null. Third, print the error code from the locate failure to avoid falling into silence again. As a rule of thumb, for any “no output but no crash” problem, suspect the identifier and handle acquisition first, not the rendering algorithm.
4. Second Round of Refinement: From Running to Usable
In the second round, the focus shifted to stability and experience:
- Input handling: apply debouncing and repeat-rate control to key presses to avoid continuous jumps caused by long presses;
- Rendering cadence: refresh on a fixed tick to avoid the main loop spinning and consuming all compute;
- Resource management: make buffer lifetimes explicit and release uniformly on exit paths to prevent repeated initialization;
- Exception fallback: add protection around the outer main loop so that on an exception it prints the stage sequence number and shuts down safely instead of going straight to a blank screen.
The acceptance criteria are best written as an executable checklist: cold start runs continuously for several minutes with no exit; a resolution change or a failed mode query produces a clear message; input latency stays within an acceptable range; and every stage sequence number in the logs appears in order.
5. Methodology: Four Practical Principles for AI-Assisted Debugging
- Build a checklist before changing code, breaking vague problems into verifiable items;
- Put observability first; logs and error codes are the only reliable evidence in a bare-metal environment;
- Verify in small steps, changing one variable at a time and keeping a rollback path;
- Drive the model with generalized descriptions, writing platform differences as constraints rather than implicit assumptions.
For enterprise-level development, this workflow can be consolidated into pipeline capabilities: code hosting and version management handle traceability, a container platform provides a consistent build environment, log services and monitoring alerts handle runtime observability, and object storage archives build artifacts and reproduction materials. Baidu AI Cloud offers corresponding capabilities in these general categories and can serve as a foundation for turning individual debugging experience into standard team practices.
6. Conclusion
The real takeaway from this practice was not that one model performed better, but that it validated a transferable collaboration paradigm: treat AI as a collaborator that needs explicit constraints and feedback loops, and use structured review, staged logging, and small fixes to push uncertainty to a minimum. When the workflow is clear enough, differences in model capability get smoothed out by the stability of the process, and delivery quality becomes predictable.
