From Disassembly to Execution: Translating 6502 Assembly to C with LLMs and Running it in UEFI

    This article explores a rigorous testing scenario for Large Language Models (LLMs): translating legacy 8-bit 6502 disassembled code into a compilable and runnable C program, and reproducing it in a modern UEFI environment. It outlines the end-to-end technical pipeline, including disassembly baseline acquisition, prompt design, semantic equivalence handling, and iterative debugging. Furthermore, it evaluates the current capabilities and limitations of LLMs in such tasks and offers a reusable methodology for reverse engineering and firmware reproduction.

    1. Background and Problem Definition

    In the field of embedded systems and firmware development, a classic hardcore testing scenario arises: given a piece of disassembled code from a legacy 8-bit processor, can a Large Language Model (LLM) translate it function-by-function into a compilable and runnable C program that ultimately runs independently of the original hardware environment? This task is considered “hardcore” because it simultaneously tests multiple capabilities of the model:

    1. Assembly Semantic Understanding: The 6502 is an 8-bit CPU with very few registers and complex addressing modes. The model must accurately understand the memory access semantics of each addressing mode (zero-page, absolute, indirect indexed, etc.).
    2. Cross-Paradigm Conversion: 6502 programs heavily rely on using memory as registers, self-modifying code, and precise cycle timing. C, however, is a structured high-level language. Translation is not a simple instruction mapping; it requires “understanding the intent first, then rewriting the implementation.”
    3. End-to-End Engineering Capability: Going from a disassembly listing to a complete toolchain that outputs graphics in a modern firmware environment (like UEFI Shell) involves compilation environments, memory layout, and graphics frame buffers.

    This article does not target any specific vendor’s product. Instead, it abstracts “how to evaluate whether an LLM is competent for such tasks” into a general methodology and reviews a complete practical process.

    2. Why Choose This Task as an LLM Benchmark

    Most model evaluations on the market remain at the level of code completion, algorithmic problems, and Q&A, making it difficult to distinguish the genuine engineering capabilities of models. Tasks like “disassembly translation + firmware environment reproduction” offer several unique advantages:

    • Objective Acceptance Criteria: The program either renders the screen correctly and responds to input via the Graphics Output Protocol (GOP) under the UEFI Shell, or it fails. There is no gray area.
    • Locatable Errors: If a function or an addressing mode is translated incorrectly, the runtime behavior will directly expose it, making it easy to provide targeted feedback for correction.
    • Tests Long Context and Multimodality: Disassembly listings often span thousands of lines, requiring the model to have a sufficiently long effective context. If the model can “identify errors from images” when debugging graphical issues, it further tests multimodal capabilities.

    3. Overall Technical Pipeline

    The entire process can be broken down into five stages:

    3.1 Obtaining the Disassembly Baseline

    First, use a static disassembly tool to completely disassemble the target ROM, yielding an assembly listing with address annotations. Organize the symbol table, interrupt entry points, and the boundaries between data and code segments. During this step, it is recommended to manually verify the following key points:

    • Addresses of the reset vector and interrupt vectors.
    • Usage annotations for zero-page variables (the zero page is the “pseudo-register area” of the 6502, and is key to successful translation).
    • Non-executable data tables (such as character libraries and palettes) must be excluded from the translation scope.

    3.2 Function-by-Function Segmentation and Prompt Design

    Do not feed the entire disassembly to the model at once. Instead, segment it by functions (or subroutines bounded by jump targets), providing context with each segment: the meaning of the zero-page variables used, calling conventions, and return value locations. The prompt template can follow this structure:

    1. [Background] 6502 assembly, NMI/IRQ disabled, current task is subroutine translation
    2. [Global Conventions] Zero-page variable table: {ZP_00: Player X coord, ZP_01: Player Y coord, ...}
    3. [Task] Translate the following assembly to C99, keeping memory side effects consistent, without introducing UB (Undefined Behavior)
    4. [Code] <Assembly snippet>
    5. [Output Requirements] Output only the function body + brief comments on uncertainties

    3.3 Key Points for Semantic Equivalence

    The most error-prone areas during translation include:

    • Carry and Overflow Flags: The 6502’s ADC/SBC instructions rely on the carry flag. Directly using C’s addition will lose the carry semantics. A safe approach is to explicitly expand it:
    1. // ADC semantic restoration
    2. uint16_t sum = (uint16_t)a + operand + carry;
    3. carry = (sum > 0xFF) ? 1 : 0;
    4. overflow = ((a ^ sum) & (operand ^ sum) & 0x80) ? 1 : 0;
    5. a = (uint8_t)sum;
    • Avoiding Undefined Behavior: Signed left-shift overflows and out-of-bounds indirect addressing must be avoided using unsigned types and explicit masks (& 0xFFFF).
    • Timing-Sensitive Logic: Code that depends on instruction cycle counts (such as raster effects) has no direct equivalent in modern environments. It needs to be rewritten into logic based on frame numbers or scanline counters—a typical scenario of “rewriting rather than literal translation.”

    3.4 Setting up the UEFI Host Environment

    Running under the UEFI Shell involves three core tasks:

    1. Build a bare-metal executable image using a UEFI-compliant cross-compilation environment.
    2. Locate the Graphics Output Protocol via boot services to obtain the frame buffer base address and resolution information:
    1. EFI_GRAPHICS_OUTPUT_PROTOCOL *gop;
    2. BS->LocateProtocol(&gGopGuid, NULL, (VOID**)&gop);
    3. UINT32 *fb = (UINT32*)gop->Mode->FrameBufferBase;
    4. // Expand simulated VRAM content into the frame buffer according to the palette
    1. Read key presses via a simple input protocol or polling method, mapping them to the original controller’s state variables.

    The original machine’s VRAM, palettes, and sprite mechanisms need to be handled by a software simulation layer. Abstract the PPU-like background/sprite composition into a “per-frame render function,” where the input is the simulated VRAM array and the output writes pixels to the frame buffer.

    3.5 Iterative Debugging Loop

    The first round of translation is almost impossible to run perfectly on the first try. An effective debugging loop is: run -> observe anomalies (screen corruption, hangs, logic offsets) -> locate suspicious functions -> feed back specific phenomena and the original disassembly to the model -> let the model correct it. Practical experience shows that the model’s self-correction ability is limited. Continuous manual identification of problem points and providing precise evidence (e.g., “this function’s carry flag handling missed the inversion before SBC”) is a necessary condition for final convergence. In this practice, most bugs were only fixed after multiple rounds of manual feedback.

    4. Observations on Current LLM Capability Boundaries

    Through this practice, several objective observations can be made regarding model capabilities:

    1. Clear Generational Progress: New-generation models significantly outperform their predecessors in understanding long disassembly listings and restoring function intents. They show substantial improvements in global understanding, such as cross-function passing of zero-page variables, and their multimodal capabilities allow them to directly analyze runtime screenshots.
    2. Still a Gap Compared to the Best: Under the same task, top-tier models achieve higher correctness rates in a single translation and require fewer rounds of manual intervention. The gap is mainly reflected in missing details of flag semantics, misjudgments of self-modifying code, and the insight into implicit intents like “this line of code is actually waiting for a raster position.”
    3. Image Recognition is a Weakness: When asking the model to determine “what is drawn wrong” based on rendered images, its localization accuracy is far inferior to textual descriptions of the error. There were multiple instances where the model “saw” non-existent issues or ignored real anomalies, ultimately requiring manual annotation tools to draw the problem area to align understanding.
    4. Cost and Latency Cannot Be Ignored: Translating thousands of lines of disassembly function-by-function means a massive number of long-context requests. Token consumption and response latency become engineering obstacles, requiring a trade-off between batching strategies and context truncation in practical use.

    5. Reusable Methodology and Recommendations

    This practice can be abstracted into a general methodology for readers to reference in similar tasks:

    • Acceptance Criteria First: Define the objective standard for “running successfully” (correct graphics, input response, no crashes) before deriving quality gates, to avoid falling into vague assessments of “looks about right.”
    • Small Steps Commit: Translate and verify function by function. Perform regression tests for each passed function to prevent difficult bug attribution later on.
    • Human-in-the-Loop: At the current stage, do not expect the model to autonomously complete the entire chain. Design human problem identification as a first-class citizen in the process.
    • Use Multimodality Cautiously: For graphical bugs, prioritize precise textual descriptions of the phenomena (pixel offsets, color values, occurrence conditions). Use images as supporting evidence rather than primary evidence.
    • Cost Control: Prioritize long listing tasks. Focus on precise translation for core logic (main game loop, collision detection), while decorative code can be roughly translated and gradually refined later.

    6. Conclusion

    Using LLMs to restore decades-old machine code into a runnable C program in a modern environment is both an interesting reverse engineering experiment and a high-quality benchmark for testing the genuine engineering capabilities of models. The conclusion can be summarized as follows: new-generation models can already handle most of the manual labor in such tasks, but verifying semantic details, confirming cross-function intents, and judging visual anomalies still rely heavily on experienced engineers continuously staying in the loop. The correct posture for AI-assisted programming is not replacement, but freeing humans from line-by-line translation so they can focus on semantic correctness and system-level validation.