start.S, SVC Entry, Data Copy, and BSS Initialization
Build the bare-metal C runtime environment from first principles in ARMv7-A assembly: mask IRQ/FIQ in Supervisor mode, align SP_svc to 8 bytes, relocate .data from LMA to VMA, zero [__bss_start, __bss_end), and enter main safely.
What you'll learn
- Establish an aligned SVC stack before calling any C function.
- Copy the linked .data initialization span when its load and execution addresses differ.
- Zero exactly the linker-defined .bss range without damaging adjacent state.
What ISO C11 Quietly Assumes Before main() Executes Its First Line
On a desktop Linux workstation, writing int g_retry = 3; static int g_err_cnt; int main(void) { ... } feels effortless because the Linux kernel execve() loader and user-space _start (crt1.o) build an entire world before main() runs: virtual pages are mapped, an 8-byte-aligned stack is allocated, .data pages hold 3, and .bss pages are demand-zeroed to 0. On bare-metal Cortex-A7 silicon, none of that happens automatically! When the i.MX6ULL Boot ROM finishes copying your .imx payload to 0x87800000 (IVT.entry) and branches to _start, Figure 5.1a shows the raw hardware reality:
- No valid C stack exists yet (
SP_svcis unknown): If your very first C function pushes{r4, lr}(stmfd sp!, {r4, lr}) or spills a64-bit integer (strd, requiring8-byteAAPCSstack alignment), an uninitialized or4-byte-misalignedSPcorrupts random memory or triggers an alignment Data Abort! .datainitializers may sit at a different Load Memory Address (LMA) than their runtime Virtual Memory Address (VMA): When.datais linked atVMA 0x87810000(__data_start) while its initial bytes{1..8}are packed right after.rodataatLMA 0x87800090(__data_load),0x87810000still holds randomDDR3power-on bit patterns (0xA5A5A5A5) until startup copies[__data_load, __data_load + len)to__data_start!.bssoccupies zero file bytes (SHT_NOBITS): Uninitialized globals (static int g_err_cnt;) have no zero bytes stored inbsp.bin. Unless startup explicitly writes0across[__bss_start, __bss_end), everyif (g_err_cnt == 0)check in C reads randomDDR3charge!
Figure 5.1a. Supervisor/interrupt-mask configuration (top) and physical RAM transformation performed by start.S before bl main (bottom).
mental model: Entering C main() on bare silicon without start.S is like walking surgeons into an operating theater before facilities turn on power (OCRAM/DDR3), clear stray trays (.bss), unpack calibrated instruments (.data LMA -> VMA), or lock the operating table (8-byte-aligned SP_svc): every assumption C makes fails on contact.
Where it stops working: Unlike preparing a room once, start.S executes with zero stack until ldr sp completes, relies on prior /DDR3 readiness, and must honor exact half-open linker address intervals.
definition (Freestanding C Runtime Startup (crt0 / start.S)): In a freestanding ARMv7-A binary, start.S (crt0) is the stackless assembly entry routine at _start that establishes every hardware precondition assumed by ISO C11 and AAPCS: (1) masking asynchronous IRQ/FIQ (CPSR.I = 1, F = 1) and selecting Supervisor mode (SVC, 0x13) from a compatible privileged state; (2) loading an 8-byte-aligned SP_svc = __stack_top in live RAM; (3) copying initialized writable .data from __data_load (LMA) to [__data_start, __data_end) (VMA) when LMA != VMA; (4) zeroing [__bss_start, __bss_end); and (5) calling bl main followed by a deterministic wfi halt loop.
Step through the four-stage runtime bring-up sequence below:
- Step 1. Step 1: Enter _start in 32-bit ARM privileged state with OCRAM or -trained DDR3 already backing RAM.
- Step 2. Step 2: Mask IRQ/FIQ (0xC0) in SVC mode (0x13) via CPSR RMW, then load 8-byte-aligned SP = __stack_top.
- Step 3. Step 3: Copy [__data_load, +size) to __data_start and zero [__bss_start, __bss_end) with pre-checked loops.
- Step 4. Step 4: Branch-with-link (bl main) into C11 and catch any return inside a bounded 5: wfi; b 5b loop.
Figure 5.1b. Never execute a C call before SP_svc, .data relocation, and .bss zeroing all complete.
Half-Open Loop Invariants, Unsigned BHS & Stackless Discipline
Inspect Figure 5.1b alongside target.S below to see why every instruction in _start is chosen deliberately. First, _start modifies CPSR via read-modify-write (mrs r0, cpsr -> bic #0x1f -> orr #0x13 -> orr #0xc0 -> msr cpsr_c, r0) rather than blasting a magic literal across all 32 CPSR bits. Note the architectural precondition: if a bootloader ever entered your image in Hyp mode (0x1A), exiting Hyp to SVC requires eret (msr elr_hyp / spsr_hyp), not msr cpsr_c. Second, notice that _start touches zero stack memory until ldr sp, =__stack_top completes!
Third, trace the .data and .bss word loops in Figure 5.1b: why cmp r0, r1 followed by bhs (Branch if Higher or Same, unsigned >=) before str?
- Pre-checked (
cmpbeforestr) handles0-byte sections: When.bssis empty (__bss_start == __bss_end),cmp r0, r1setsC = 1, Z = 1andbhs 4fexits immediately with zero stores—whereas a post-checkeddo..whileloop overwrites4bytes past__bss_end! - Exclusive upper bound (
bhs, notbhi): Linker end symbols (__data_end,__bss_end) mark the first byte after the section ([start, end)), sor0 == r1must stop immediately without clobbering the neighbor at[end]. - Unsigned (
bhs, not signedbge):DDR3addresses at0x87800000have bit31 == 1(negative if misinterpreted as signedint32_t!); unsigned carry flags order the full0x00000000..0xFFFFFFFFphysical map monotonically.
Figure 5.1b. Pre-checked unsigned half-open [start, end) word loops (left) contrasted against three classic bare-metal startup bugs (right).
| Startup Implementation Detail | Instruction Sequence | Empty / Boundary Behavior | Defect When Violated |
|---|---|---|---|
| Pre-checked unsigned loop | cmp r0, r1 -> bhs done -> str | 0 stores when start == end; stops at end | Production safe across 0..4 GiB |
Post-checked loop (do..while) | str -> cmp r0, r1 -> blo loop | Writes 4 B when start == end! | Corrupts word at __bss_end on empty .bss |
Inclusive upper bound (<=) | cmp r0, r1 -> bhi done | Writes 1 extra word past end every boot! | Silently zeroes first word of .stack/.rodata |
Early bl before ldr sp | bl debug_led at line 1 of _start | Pushes {r4, lr} to wild/unaligned SP_svc | Immediate Data Abort or Boot ROM/RAM corruption |
learner@ksa:~/gl-e01/m05-l01$ bat -H 7 -H 8 -H 9 -H 10 -H 11 -H 12 -H 16 -H 17 -H 18 -H 19 -H 20 -H 21 -H 22 -H 23 -H 24 -H 25 -H 26 -H 28 -H 29 -H 30 target.S File: target.S .syntax unified .cpu cortex-a7 .arm .section .text.start, "ax" .global _start _start: mrs r0, cpsr bic r0, r0, #0x1f orr r0, r0, #0x13 orr r0, r0, #0xc0 msr cpsr_c, r0 ldr sp, =__stack_top ldr r0, =__data_start ldr r1, =__data_end ldr r2, =__data_load 1: cmp r0, r1 bhs 2f ldr r3, [r2], #4 str r3, [r0], #4 b 1b 2: ldr r0, =__bss_start ldr r1, =__bss_end mov r2, #0 3: cmp r0, r1 bhs 4f str r2, [r0], #4 b 3b 4: bl main 5: wfi b 5b- Establish 8-byte-aligned SP_svc AFTER masking IRQ/FIQ in SVC mode and BEFORE any bl call.
- Pre-checked unsigned bhs handles start == end cleanly and stops before exclusive __data_end / __bss_end.
- Catch any return from main() inside a low-power wfi loop instead of falling into literal pools.
Sentinel-Poisoned Relocation & BSS Boundary Proof in ISO C11
In lds_vma_lma_solver.c below, we poison a 64-byte simulated RAM arena with 0xA5, place 8 initializer bytes {1..8} at the LMA offset (4), copy them to VMA (16..23), and zero .bss ([24, 40)). Asserting ram[23] == 8U (last .data byte intact) and ram[40] == 0xA5U (byte right at exclusive bss_end untouched!), followed by an empty [48, 48) .bss pass (ram[48] == 0xA5U) and an unaligned SP = 0x87820004U rejection, proves every boundary algebraically!
learner@ksa:~/gl-e01/m05-l01$ bat -H 10 -H 11 -H 12 -H 13 -H 14 -H 15 -H 16 -H 17 -H 18 -H 19 -H 20 -H 22 -H 23 -H 24 -H 25 -H 26 -H 27 -H 28 -H 29 -H 30 -H 31 -H 32 -H 33 -H 34 lds_vma_lma_solver.c File: lds_vma_lma_solver.c #include <assert.h> #include <stdbool.h> #include <stddef.h> #include <stdint.h> #include <stdio.h> #include <string.h> struct crt_syms { uint32_t text_base, etext, data_load, data_start, edata; uint32_t bss_start, bss_end, stack_top; }; static struct crt_syms solve_syms(uint32_t base, uint32_t text_ro, uint32_t data_vma, uint32_t data_sz, uint32_t bss_sz, uint32_t stack_top) { struct crt_syms s; s.text_base = base; s.etext = base + text_ro; s.data_load = (s.etext + 3U) & ~3U; s.data_start = data_vma; s.edata = data_vma + ((data_sz + 3U) & ~3U); s.bss_start = (s.edata + 3U) & ~3U; s.bss_end = s.bss_start + ((bss_sz + 3U) & ~3U); s.stack_top = stack_top; return s; } static bool crt_init_ram(unsigned char *ram, size_t cap, size_t lma_off, size_t vma_off, size_t data_sz, size_t bss_off, size_t bss_end, uint32_t sp_top) { if ((sp_top & 7U) != 0U || bss_off > bss_end || bss_end > cap) return false; if (lma_off + data_sz > cap || vma_off + data_sz > bss_off) return false; if (data_sz > 0U && lma_off != vma_off) memcpy(ram + vma_off, ram + lma_off, data_sz); for (size_t i = bss_off; i < bss_end; ++i) ram[i] = 0U; return true; } int main(void) { struct crt_syms s = solve_syms(0x87800000U, 144U, 0x87810000U, 8U, 16U, 0x87820000U); assert(s.etext == 0x87800090U && s.data_load == 0x87800090U); assert(s.edata == 0x87810008U && s.bss_end == 0x87810018U); unsigned char ram[64]; const unsigned char init[8] = {1U, 2U, 3U, 4U, 5U, 6U, 7U, 8U}; memset(ram, 0xa5, sizeof ram); memcpy(ram + 4U, init, sizeof init); /* LMA image bytes at offset 4 */ assert(crt_init_ram(ram, 64U, 4U, 16U, 8U, 24U, 40U, s.stack_top)); assert(memcmp(ram + 16U, init, 8U) == 0 && ram[23] != 0U && ram[40] == 0xa5U); for (size_t i = 24U; i < 40U; ++i) assert(ram[i] == 0U); assert(crt_init_ram(ram, 64U, 4U, 16U, 0U, 48U, 48U, s.stack_top) && ram[48] == 0xa5U); assert(!crt_init_ram(ram, 64U, 4U, 16U, 8U, 24U, 40U, 0x87820004U)); printf("etext=0x%08X data_vma=0x%08X..0x%08X bss_end=0x%08X sp=0x%08X\n", s.etext, s.data_start, s.edata, s.bss_end, s.stack_top); return 0; }- Compute _etext, __data_load (LMA), __data_start.._edata (VMA), [__bss_start, __bss_end), and 8-byte aligned __stack_top.
- Require 8-byte AAPCS32 stack alignment and non-overlap above __bss_end before copying .data or zeroing .bss.
- Copy [lma, lma + data_sz) to vma and zero [bss_start, bss_end) exclusively, performing zero writes when bss_start == bss_end.
Running the Relocation Solver & Assembling start.S for Cortex-A7
Compile and run lds_vma_lma_solver.c on the workstation, then assemble target.S into ARMv7-A object code (target.o) to verify instruction syntax and label resolution.
learner@ksa:~/gl-e01/m05-l01gcc -std=c11 -Wall -Wextra -Werror -pedantic lds_vma_lma_solver.c -o lds_vma_lma_solverlearner@ksa:~/gl-e01/m05-l01./lds_vma_lma_solveretext=0x87800090 data_vma=0x87810000..0x87810008 bss_end=0x87810018 sp=0x87820000learner@ksa:~/gl-e01/m05-l01clang --target=armv7a-none-eabi -mcpu=cortex-a7 -marm -c target.S -o target.olearner@ksa:~/gl-e01/m05-l01learner@ksa:~/gl-e01/m05-l01strace -e trace=write,exit_group \./lds_vma_lma_solverwrite(1, "etext=0x87800090 data_vma=0x8781"..., 82) = 82exit_group(0) = ?+++ exited with 0 +++Flat RAM Builds vs Split XIP Builds & Linker Contract Coupling
Notice two subtle couplings between start.S and the rest of the boot chain. First, if a flat TFTP or DDR3 image links .data with LMA == VMA (__data_load == __data_start), inserting cmp r0, r2; beq 2f ahead of the .data loop skips redundant self-copying cleanly; conversely, on a QSPI Execute-in-Place (XIP) build (LMA in 0x60000000 flash, VMA in 0x00908000 OCRAM), that LMA -> VMA copy is the only way writable globals receive their initializers! Second, BootData.length (m04-l02) must cover __data_load + (__data_end - __data_start)—otherwise start.S diligently copies uninitialized RAM into .data! Later: Lesson m05-l02 authors the exact GNU ld script (bsp.lds) that defines __data_load, __data_start, __data_end, __bss_start, __bss_end, and __stack_top.
Common Production Pitfalls
warning: Symptom: Zero-initialized globals (static int count;) start at 0 as expected, yet initialized globals (int baud = 115200;) hold random garbage inside main(). Root Cause: The linker script placed .data at VMA 0x87810000 using AT(_etext) (LMA 0x87800090), and start.S zeroed .bss while omitting the __data_load -> __data_start relocation loop (or BootData.length stopped before _etext + SIZEOF(.data)). Fix: Always copy [__data_load, __data_load + (__data_end - __data_start)) to __data_start when __data_load != __data_start and verify BootData.length covers the packed .data LMA tail.
warning: Symptom: When a diagnostic main() returns 0 at the end of a self-test, the board unexpectedly fires random GPIO writes or triggers an Undefined Instruction exception. Root Cause: start.S branched to main with b main (leaving LR pointing back into Boot ROM) or omitted a halt loop after bl main, allowing execution to fall straight into literal pools (=0x87820000) assembled immediately after _start! Fix: Always invoke bl main and follow it immediately with 5: wfi; b 5b.
Practice & Retrieval
Guided Practice: Solving QSPI-to-OCRAM Relocation Symbols
Trace a split XIP build where .text + .rodata (0x1240 B) execute in QSPI flash at 0x60001000 while .data (20 B), .bss (48 B), and .stack live in OCRAM starting at 0x00908000 (stack_top = 0x00918000). Step 1 (Addresses): Compute _etext = __data_load = 0x60002240, __data_start = 0x00908000, _edata = __bss_start = 0x00908014, and __bss_end = 0x00908044. Step 2 (Word Loop Check): Verify (0x14 % 4 == 0) and (0x30 % 4 == 0) so word-stepped #4 loops never overrun a 1-, 2-, or 3-byte tail.
Independent Practice: Overlap-Safe Memmove & Arbitrary-Byte Tail Verifier
Extend lds_vma_lma_solver.c into crt_reloc_verifier.c supporting unrounded byte counts (data_sz = 7 B) and overlapping self-relocation (vma > lma with vma < lma + len), proving why forward copy corrupts overlapping upper destinations while backward copy preserves every byte.
Key takeaways
- Bare-metal
_startmust maskIRQ/FIQ(0xC0), selectSVCmode (0x13), and load a valid, reservedSP_svc = __stack_topbefore calling any C function. AAPCSrequires8-byte stack alignment ((SP & 7) == 0) at every public call interface (bl main).- When
.data's Load Memory Address (__data_load) differs from its execution Virtual Memory Address (__data_start),start.Scopies[__data_load, __data_load + size)before C reads writable globals. - Pre-checked unsigned
cmp + bhsloops zero[__bss_start, __bss_end)cleanly without touching[__bss_end]or misfiring on0-byte sections. - Bare-metal startup must establish a valid stack before calling C code that can use it.
- A public call boundary requires eight-byte stack alignment.
- The helper may use an invalid stack before its preconditions hold.