Does Embedded Code Have to Be Copied from Flash to RAM?

    By default, embedded firmware does not need to be moved from Flash to RAM: on most microcontrollers the code executes in place (XIP), with the hardware reset logic and the vector table setting the initial stack pointer and reset vector. This article explains why in-place execution works, then covers the cases where copying code to RAM is mandatory—erasing or writing the same Flash region, storage media that cannot be read randomly, hard real-time performance requirements, and secure or updatable firmware. It also describes what the startup file and linker script actually do, compares in-place versus RAM execution, and provides a practical checklist for verifying load addresses, run addresses, alignment, and cache coherency.

    Does Embedded Code Have to Be Copied from Flash to RAM?

    The Short Answer: By Default, No Copying Is Needed

    In the vast majority of embedded scenarios, program code does not need to be moved from Flash to RAM. It can execute in place, directly from Flash. After the CPU resets, the hardware points the program counter at the reset vector, and the fetch, decode, execute, and increment cycle all completes within the Flash address space. The code never leaves its original location.

    The behavior described in the original text is a direct result of this mechanism: on a classic class of ARM-based microcontrollers, the first thing that happens after reset is that the vector table at the start of Flash is read to obtain the initial stack pointer and the reset vector, after which execution jumps to the reset handler entry point. No “copying” takes place at any point, and nothing explicitly directs the PC into RAM.

    One common misunderstanding is worth clearing up: the PC is not meaningful only because startup code assigns it explicitly. It is driven by the hardware reset logic, the contents of the vector table, and the subsequent branch instructions. What the vendor-supplied assembly startup file does is simply place a few critical addresses (the top of the stack and the reset entry point) into the vector table; the remaining jumps and initialization are left to the instruction stream.

    Why Code Can Run Directly from Flash: Bus and Fetch Mechanisms

    In-place execution depends on Flash being mapped into the CPU’s addressable space and on its read latency being tolerable within the bus timing. There are two common implementations:

    • Flash is connected directly to the bus, with wait states and a prefetch buffer, and the CPU fetches instructions one by one by address.
    • An on-chip high-speed cache or a dedicated acceleration module prefetches frequently used instructions into storage close to the core, reducing fetch stalls.

    As long as the fetch path is stable, the PC increments once per instruction fetched, which is logically equivalent to “the program running in Flash.” This is also the basis of so-called execute-in-place (XIP).

    A schematic startup flow can be abstracted as follows:

    1. /* Conceptual illustration, not platform-specific code */
    2. void reset_entry(void) {
    3. sp = *(volatile uint32_t *)VECTOR_TABLE; /* Load initial stack pointer */
    4. pc = *(volatile uint32_t *)(VECTOR_TABLE + 4); /* Load reset vector */
    5. /* The instruction stream takes over from here; no code relocation needed */
    6. }

    When Code Must Be Copied to RAM

    Although the default is not to copy, the following four scenarios make it a hard requirement, and they are common pitfalls in engineering practice.

    1. A Region Being Erased or Written Cannot Be Fetched From at the Same Time

    If code and data reside in the same physical storage, that storage cannot respond to reads while an erase or write is in progress. The moment the CPU tries to fetch an instruction, it either stalls or fetches the wrong instruction. The solution is to run the critical code—especially the erase/write routine itself—from RAM, in effect “modifying Flash from within RAM.”

    2. The Storage Medium Does Not Support Random Reads

    Some external storage devices (certain serial-interface memories, NAND-type media, for example) are not suitable as a direct fetch source. A loader must first copy the code into RAM that supports random access, then jump to it. Here the copy step is a mandatory part of the boot chain.

    3. Performance and Real-Time Requirements

    A high-speed core paired with RAM that has low wait states can significantly shorten fetch time, which pays off clearly on hard real-time paths such as interrupt response, control loops, and signal processing. Placing hot functions in RAM is a common performance optimization.

    4. Secure Loading and Updatable Firmware

    Firmware that requires signature verification, decryption, or delta merging is typically verified and unpacked in RAM first, then execution jumps to the valid image, avoiding running directly from untrusted storage.

    What the Startup File and Linker Script Actually Do

    Taking a typical assembly startup flow as an example, its responsibilities come down to four steps: set the stack pointer, initialize a small number of static variables, copy the initialized data section from the storage medium to RAM, zero the uninitialized data section, and finally jump to the C runtime entry point. Note that what gets copied here is the data section, not all of the code.

    The linker script (the scatter loading description file) decides “who lives where.” A typical layout looks like this:

    1. FLASH: vector table + read-only code section + constant tables
    2. RAM: initialized data section + zero-initialized section + stack + heap

    If a partial relocation is needed, you can explicitly declare at the link level that a given code section has a “load address in the storage medium and a run address in RAM,” and have the startup code copy it section by section. For example:

    1. extern uint32_t s_text_load, e_text_load, s_text_run;
    2. void copy_code_to_ram(void) {
    3. for (uint32_t *src = &s_text_load, *dst = &s_text_run; dst < &e_text_run; )
    4. *dst++ = *src++;
    5. }

    Trade-Offs Between In-Place and Copied Execution

    Dimension Execute in Place Copy to RAM and Execute
    Startup time Short Adds copy time
    RAM usage Low High
    Fetch speed Affected by storage timing Faster and more consistent
    Erasing/writing the same region Not feasible Feasible
    Implementation complexity Low Requires linker and startup cooperation

    The decision principle is simple: default to in-place execution, and only when you hit an erase conflict, a media limitation, a real-time bottleneck, or a security verification requirement do you copy the necessary minimal set into RAM rather than moving everything.

    Engineering Practice and Troubleshooting Checklist

    • Confirm the memory mapping: verify whether the actual load address and run address of the code section are the same.
    • Control the scope of relocation: copy only hot functions and erase/write routines so RAM does not get exhausted.
    • Watch the startup sequence: the copy routine itself must reside in executable media, otherwise it will “copy itself” and fetch will fail.
    • Verify alignment and caches: after copying, maintain cache coherency as needed to prevent fetching stale instructions.
    • Verify with a debugger: inspect the vector table contents, the symbol addresses of section boundaries, and whether jump targets land in the expected regions.
    • Use observability: in production, pair logging services and monitoring alerts to collect metrics such as boot time and abnormal reset counts, making problems easier to trace back.

    Clearing Up Common Misconceptions

    • Misconception 1: All code must be copied to RAM. In fact, only the data section and code sections in specific scenarios need to be moved.
    • Misconception 2: The PC must be set manually by code. In fact, the reset hardware and the vector table have already established the initial location.
    • Misconception 3: Copying to RAM is always faster. The copy itself consumes startup time, and if the hot spots are not concentrated, the benefit may be negative.
    • Misconception 4: If the link succeeds, everything is fine. When the run address and load address differ, the linker will not report an error; the problem only surfaces at runtime.

    In one sentence: whether embedded code needs to be copied into RAM depends on the storage medium’s capabilities, concurrent erase/write requirements, real-time goals, and security policy—not on a single universal rule. Make in-place execution the default path and treat relocation as an optimization with clear trigger conditions, and you can strike a balance among startup speed, RAM budget, and reliability.