Debugging Legacy Code with Large Language Models: A Practical Workflow
This article walks through a practical workflow for using large language models to debug legacy and half-finished code in firmware and low-level graphics development. It explains why code that looks well-structured can still fail at runtime, then covers a two-round process: first getting the program to run through static review, observability, and minimal fixes for pointer lifetime and configuration errors, then improving stability with prioritized optimizations and measurable regression criteria. A five-step loop and key engineering takeaways are included.
1. Where the Problem Starts: “It Generates” Is Not “It Runs”
In firmware and low-level graphics development, a familiar situation arises: code produced by AI coding tools looks well organized. The entry point, main loop, business logic, rendering, and input handling are split across multiple files, and both naming and layering feel natural. Yet once the code is loaded onto the target environment, the program may exit within seconds, or it may run normally while producing no visible output at all.
Code that “looks right but does not run” is usually described as legacy code or half-finished code. Its value is that it preserves the design intent and the module skeleton; its defects are concentrated in three areas: environment assumptions, resource lifetimes, and configuration constants. Handing it to another large language model for cleanup is therefore not a rewrite. It is a constrained, incremental debugging effort.
2. First Round: Make It Run
2.1 Static Review Before Blind Changes
The first step is not to run the code, but to have the model read through every module and produce a list of problems, focusing on four categories of risk:
- Whether resource acquisition and release are correctly ordered in time;
- Whether pointers remain valid before and after calls;
- Whether global state and initialization order carry implicit dependencies;
- Whether configuration constants and identifier parameters match the target environment.
An example review prompt:
Review the following code module by module. List only issues that could causecrashes, missing output, or undefined behavior. For each one, use three sections:symptom, root cause, minimal fix. Do not rewrite the overall architecture.
Constraining the output format matters. Without limits, the model tends to restructure the directory layout, which only amplifies regression risk.
2.2 Symptom One: Immediate Exit on Startup
The program prints the main loop startup message and then ends right away. This means control flow never entered the expected loop and was instead taken away by a failing branch or an abnormal termination. The most effective move here is not more guessing but more observability: instrument the key steps and stream progress continuously over the serial port to build an execution trace you can compare against expectations.
The logs placed the failure right after a mode-setting call. The root cause was a classic lifetime error: the buffer information pointer obtained while querying the mode pointed to a memory region that was no longer valid once the mode had been set. Subsequent rendering wrote through a wild pointer, triggering unpredictable behavior.
The fix follows the minimal-change principle: query the buffer information again after the mode is set, instead of caching the old pointer.
/* Bad: caching buffer info across calls */info = query_mode_info(protocol, mode);set_mode(protocol, mode);draw(info->frame_buffer, ...); /* info may already be invalid *//* Fixed: query again after setting the mode */set_mode(protocol, mode);info = query_mode_info(protocol, mode);draw(info->frame_buffer, ...);
The general lesson: for any three-step “query, change, use” sequence, confirm whether the change step invalidates the earlier result.
2.3 Symptom Two: It Runs, but Nothing Appears
Once the crash was gone, the program entered the loop but the screen stayed black. The problem had shifted from memory safety to configuration correctness. Graphics output protocols often carry several related identifiers within the same specification family to distinguish different purposes; referencing the wrong identifier makes protocol location fail, leaves the function pointer table empty, and causes rendering calls to be skipped silently.
The approach is to validate the identifier and check whether the protocol location result is null before deciding whether to continue:
status = locate_protocol(&graphics_protocol_guid, NULL, &gop);if (status != OK || gop == NULL) {log("gop not located, guid may be wrong");return status;}
The point most worth turning into a team standard: return values from low-level interfaces must be checked explicitly, and failure branches must emit diagnosable logs. Otherwise the problem is deferred until it surfaces as something as expensive as a black screen.
3. Second Round: Refinement and Stability
Once the program runs, move into the optimization round, ordered from highest to lowest payoff:
- Debounce input handling and deduplicate events to avoid repeated triggering from long presses;
- Add rendering clipping and dirty-rectangle updates to reduce the bandwidth pressure of full-screen refreshes;
- Decouple timing by separating logic updates from presentation, so frame rate fluctuation does not affect decisions;
- Fill in resource allocation failure paths so any failing step can roll back safely;
- Centralize constants and magic numbers to lower future maintenance cost.
The optimization round must come with regression criteria; otherwise “smoother” cannot be verified. Quantifiable acceptance items include continuous runtime, time from initialization to the first frame, whether memory usage stays stable, and whether abnormal exits are zero.
4. The Method: A Five-Step Loop
- Review: produce the problem list first, and limit the scope to minimal fixes;
- Reproduce: fix the environment and inputs so the symptom recurs reliably;
- Observe: externalize internal state with logs to narrow the suspect range;
- Fix: change one variable at a time and keep a revertible version;
- Regress: confirm no new defects with quantitative metrics.
5. Engineering Takeaways
Whether one model can take over legacy code from another depends on two things: whether the code has clear module boundaries, and whether the debugging process is sufficiently observable. The first determines whether the model can make local changes without breaking the whole; the second determines how fast the root cause can be located. If an organization wants to use large language models to improve maintenance efficiency for existing projects, it can embed them in the containerized build, logging, and monitoring and alerting systems already in place, so every change is traceable and measurable rather than relying on a one-off “generate and ship.”
