Debugging Legacy Code with LLMs: A Practical Methodology
This article shares a practical methodology for using large language models to debug legacy code, based on a hands-on session with a legacy graphics program. It explains why taking over existing code is often harder than generating a new project from scratch, then walks through a two-round workflow: first static code review and dynamic fault localization to reach a runnable baseline, and then refinement of input handling, rendering performance, and resource management. Readers will find reusable debugging principles, illustrative C code snippets, and engineering practices for turning one-off debugging into a repeatable process.
1. Background: Why Taking Over a Mess Is Harder Than Generating from Scratch
In real-world AI-assisted programming, a common scenario looks like this: the code left behind by a previous generation pass appears complete, with clear module boundaries and a reasonable number of files, yet it simply will not run. Debugging this kind of legacy code is often harder than generating a new project from scratch. When generating from scratch, the model has the full context. When taking over someone else’s code, the model faces a black box: the design intent is unclear, boundary conditions are unknown, and bugs may hide at the seams between any two modules.
This article uses a typical practice session, in which a large model takes over a legacy graphics program, as a thread to abstract a reusable troubleshooting methodology. The testing was split into two rounds: the first aimed to get the code basically running, and the second focused on refinement and optimization. This “runnable first, optimize later” order is critical. If you chase structure and performance from the start, you can easily burn a great deal of time just trying to locate the faults.
2. Round One: From Static Review to Dynamic Localization
2.1 Always Start with Code Review, Not by Running It
The first instruction after taking over the code should be: review this code and list the likely problem points. The model checks module by module: the entry function, the main loop, the business logic, the rendering module, and input handling. Within minutes, it produces a list of issues.
The value of this step is that it builds a “hypothesis set.” Running the code directly can expose problems too, but error messages often point only to surface symptoms, whereas static review can surface deeper risks in advance, such as type mismatches, unreleased resources, and incorrect protocol identifier references.
2.2 Typical Issue One: Frame Buffer Pointer Invalid After a Mode Switch
The program could start and print a log showing that it had entered the main loop, and then it exited immediately. After adding finer-grained serial debug output, the exception could be observed occurring right after the graphics output protocol call.
Root cause analysis: the information structure returned when querying modes contains frame buffer-related pointers, but after the mode is set, that block of memory may have been reallocated or invalidated. Continuing to hold the old pointer results in a wild pointer access.
The fix is to query the frame buffer information again after setting the mode, instead of reusing the result obtained earlier. Illustrative code:
// Query the available modes firstEFI_GRAPHICS_OUTPUT_PROTOCOL_MODE *mode = gop->Mode;// Set the target modegop->SetMode(gop, target_mode);// Key point: after the mode switch, you must read it again; do not reuse the old pointerUINTN fb_size = 0;EFI_PHYSICAL_ADDRESS fb_base = 0;gop->QueryMode(gop, target_mode, &fb_size, &fb_base);
This reflects a general principle: after any “set” operation, the associated “query” results should be treated as invalid and must be fetched again. The same principle applies to resource management scenarios involving graphics, networking, files, and more.
2.3 Typical Issue Two: Incorrect Protocol Identifier Prevents the GUI from Appearing
The program no longer crashed on startup, but the interface remained blank. Further analysis showed that the graphics output protocol has several related identifiers. Firmware development frameworks such as EDK2 define a number of similar protocol identifiers, and referencing the wrong one prevents the protocol from being located correctly, so graphics output naturally fails.
The fix is to change the protocol identifier to the correct definition that matches the current firmware specification, and to add return value checks in the initialization flow: if any step fails, print the error code and terminate immediately rather than continuing to execute. This “fail fast” strategy can significantly shorten the localization time.
2.4 Round One Summary: Runnable Comes First
By the end of the first round, the program could stably enter the main loop and produce output on screen. At this point, you should not rush to optimize the structure. Instead, lock in a reproducible baseline version first, so that later changes can be compared against it.
3. Round Two: Refinement and Optimization
With the baseline established, the second round focuses on three things:
- Input handling: verify the key scanning and debounce logic to avoid repeated triggering;
- Rendering performance: reduce full-screen redraws every frame, and switch to partial refresh or a dirty rectangle strategy;
- Resource management: ensure that resources already allocated are released on the exit path, avoiding resource leaks in a firmware environment.
An illustrative main loop structure:
while (running) {scan_input();update_game();render_dirty_region();}
4. Distilled Methodology
Four transferable lessons emerge from the process above:
- Review before running, and let the issue list drive debugging;
- Re-query after setting, to eliminate wild pointers;
- Protocol identifiers must align with the target firmware specification, with return value validation added;
- Two-round iteration: runnable first, then refinement.
For a more engineering-oriented implementation, serial output can be collected and searched through logging services and monitoring alerts, the build environment can be pinned with a container platform, and baseline versions can be stored in object storage. This turns one-off debugging experience into a reusable development process.
