Debugging Legacy Code with Large Language Models: A Practical Workflow

    This article presents a practical workflow for using large language models to debug and revive legacy code that does not run. It explains why generating syntactically correct code is not the same as achieving runtime correctness, and organizes the work into two iterative rounds: first making the code runnable through static review, minimal environment setup, crash reproduction, logging, and fixes; then refining performance, input handling, rendering stability, and maintainability. Concrete examples cover resource lifetime errors with handles and mode switches, and protocol GUID mismatches. The article concludes with four rules for using LLMs as reliable debugging assistants.

    1. Where the Problem Starts: Why “It Generates” Is Not “It Runs”

    In low-level development, handing a requirement to an AI coding tool to generate code is no longer new. The real difficulty is often not “generating from scratch” but “taking over someone else’s code that does not run.” This kind of legacy code usually has some structure but lacks a verifiable runtime baseline, with problems hidden in details such as initialization order, resource lifetimes, and protocol identifier configuration.

    A typical session unfolds like this: first, you ask the tool to generate a small graphical game, and it exits as soon as it reaches the main loop entry; with a different generated result, the build environment cannot even be set up. This shows that generative tools perform well on “syntactic correctness” but still need human-led verification for “runtime semantic correctness.” So instead of comparing specific tools, this article abstracts the problem into: how to let a large language model safely take over legacy code and make it runnable.

    2. Overall Approach: A Closed Loop of Two Rounds

    Split the remediation into two rounds to avoid making too many demands at once, which makes changes hard to control.

    • Round 1 (make it runnable): static review → set up a minimal runtime environment → reproduce the crash → add logging to localize → fix → regression test.
    • Round 2 (refine and optimize): performance, input responsiveness, rendering stability, exception handling, and maintainability.

    Each round must follow one principle: change only one class of problem at a time, and verify immediately after each change. Low-level program crashes are often strongly coupled, and changing multiple places at once makes attribution difficult.

    3. Round 1: From “Has Code” to “Starts Up”

    3.1 Start with Static Review, Not Running

    After copying the legacy code unchanged into a new environment, the first instruction should be “review this code and list the problems that could prevent it from running,” not “help me run it.” The review scope should cover:

    • Entry functions and call order;
    • The main loop and event handling;
    • Game/business logic and state machines;
    • The rendering module and framebuffer acquisition;
    • Input handling and device dependencies.

    Have the tool output a list of problems sorted by severity, annotated with the impact scope of each change. The value of this step is to build a “map of changes” and avoid blind trial and error later.

    3.2 Problem One: Exits at the Main Loop Entry (Resource Lifetime Error)

    The symptom: the program starts, prints the log that the main loop has begun, and then exits immediately. Most “dies on startup” problems are not logic errors but resources that are already invalid before use.

    The way to localize it is to add serial or log output, mark before and after key calls, and observe which step fails. In practice, the pointer returned by the graphics output protocol after querying mode information points to memory that is no longer valid after switching modes—a classic “get the pointer first, switch state, then use the old pointer” lifetime error.

    The fix is to adjust the order and re-acquire:

    1. // Bad: keep using the old pointer after switching modes
    2. info = gop->QueryMode(gop, mode, &size);
    3. gop->SetMode(gop, mode);
    4. use_framebuffer(info); // info may already be invalid
    5. // Good: re-query the current framebuffer info after switching modes
    6. gop->SetMode(gop, mode);
    7. info = gop->QueryMode(gop, mode, &size);
    8. use_framebuffer(info);

    The general rule abstracted from this is: for any combination of “handle/pointer + state switch,” assume the old handle is invalid, and re-query after the switch instead of caching and reusing it.

    3.3 Problem Two: The Program Runs but No UI Appears (Protocol Identifier Configuration Error)

    The second symptom is that the process does not crash but there is no output on screen. This is very common in low-level graphics development, and the cause is often a wrong protocol identifier (GUID): the same kind of protocol may have multiple related identifiers in the framework, and picking the wrong one is equivalent to not getting the protocol at all.

    There are three key points to the fix:

    1. Confirm the authoritative definition location of the protocol identifier in the firmware/framework version you are using;
    2. Use a “probe—print—assert” approach to confirm whether the protocol instance is actually obtained;
    3. Centralize the identifier definition in one header file or configuration item to avoid scattered hardcoding.
    1. // Centralize management to avoid inconsistent hardcoding in multiple places
    2. static const EFI_GUID *gGraphicsGuid = &EFI_GRAPHICS_OUTPUT_PROTOCOL_GUID;
    3. status = locate_protocol(gGraphicsGuid, &gop);
    4. if (status != OK || gop == NULL) {
    5. log("gop not found, guid mismatch?");
    6. return status;
    7. }

    3.4 Round 1 Summary: Make “Runnable” a Repeatable Fact

    The standard for finishing Round 1 is not “it runs on my machine” but: reproduce success step by step in a clean environment. Write the environment setup, build commands, and run steps into a checklist, and have the tool generate documentation to reduce handover costs later.

    4. Round 2: Refinement and Optimization, Turning “It Runs” into “It’s Usable”

    In the second round, optimization should revolve around measurable goals rather than changing things by feel:

    • Input responsiveness: reduce the latency from input to on-screen feedback, and handle key bounce and repeated triggering;
    • Rendering stability: fix the refresh cadence and avoid busy waiting; introduce simple time slicing or frame rate control when necessary;
    • Resource management: clarify the acquisition and release paths for buffers and device handles to avoid leaks;
    • Maintainability: decouple constants, state, rendering, and logic, and split into modules;
    • Observability: keep a leveled logging switch for on-site troubleshooting.

    A schematic main loop skeleton:

    1. while (running) {
    2. process_input();
    3. update_state();
    4. render_frame();
    5. throttle_to_target_fps();
    6. }

    5. Lessons Learned: Four Rules for Using LLMs as a Reliable Assistant

    1. Review before acting: have the tool produce the problem list and impact scope first, then fix items one by one.
    2. One class of problem at a time: low-level faults are strongly coupled, and batch changes break attribution.
    3. Trade logs for time: instrument before and after key calls; it converges faster than repeated guessing.
    4. Turn conclusions into standards: write “re-acquire the handle after switching” and “centralize identifier management” into team checklists.

    6. Conclusion

    Having a large language model take over legacy code is essentially turning “experience” into “an executable process.” When review, reproduction, localization, fixing, and regression form a closed loop, generative tools can reliably take on the repetitive work in low-level debugging. Combined with general-purpose container platforms, logging services, and monitoring and alerting capabilities in the cloud, standardizing the build and runtime environment and making the troubleshooting process observable further improves the certainty of team delivery.