GNU ld Scripts, VMA/LMA, and Linker Boundary Symbols
Author auditable GNU ld linker scripts from first principles: pin _start with ENTRY and KEEP, separate packed AT(LMA) load images from VMA execution maps, export aligned BSS/stack symbols without C dereference bugs, and enforce RAM ceilings via link-time ASSERTs.
What you'll learn
- Place the entry section and data spans explicitly with ENTRY and SECTIONS.
- Compute VMA/LMA relocation and the serialized image extent.
- Assert aligned non-overlapping BSS and stack boundaries.
How GNU ld Turns Relocatable .o Files Into Dual-Address Firmware Maps
In Lesson m05-l01, start.S consumed six magic names—__stack_top, __data_load, __data_start, __data_end, __bss_start, and __bss_end—without defining any of them! Where do those exact addresses come from, and what stops the linker from placing a random helper function at 0x87800000 ahead of _start, or inflating bsp.bin by 64 KiB of useless zeros? That contract belongs to the GNU ld linker script (bsp.lds).
Trace Figure 5.2a from left to right to understand the two distinct addresses every output section possesses inside ELF program headers (readelf -l), even when the ARMv7-A MMU is completely turned off (SCTLR.M = 0):
- Virtual Memory Address (
VMA, queried viaADDR(.data)): The runtime execution address baked into Cldr/strinstructions andblbranch targets. In Figure 5.2a,.text(128 B) and.rodata(16 B) execute at0x87800000..0x87800090, while writable.data(8 B) is linked atVMA = 0x87810000. - Load Memory Address (
LMA, set viaAT(__data_lma)and queried viaLOADADDR(.data)): Whereobjcopy -O binary(and the Boot ROM) places the section's initial image bytes! If you link.dataat0x87810000withoutAT(__data_lma),LMAdefaults toVMA(0x87810000), forcingobjcopyto zero-pad the entire65,392-byte gap (0x87800090..0x87810000) and bloatingbsp.binfrom152 Bto65,544 B! AddingAT(__data_lma)packs those8.databytes snugly at0x87800090(152 Btotal.bin), while(NOLOAD)marks.bssand.stackasSHT_NOBITS(0file bytes!).
Figure 5.2a. Packed 152-byte LMA load image (left) versus sparse runtime VMA execution map with 8-byte-aligned banked IRQ and SVC stacks (right).
mental model: A linker script (bsp.lds) is the civil blueprint that assigns both compact shipping-container slots (LMA for objcopy / SD transfer) and anchored factory floor pads (VMA for C execution): startup cranes (start.S) read the blueprint's survey stakes (linker boundary symbols) directly rather than opening crates to look for coordinates inside.
Where it stops working: Unlike paper survey stakes, linker symbols live solely in the symbol table (allocating zero bytes in RAM), and link-time ASSERTs verify address arithmetic without proving physical DDR3 is powered or trained.
definition (GNU ld Location Counter (.), VMA vs AT(LMA) & Symbol-Address Semantics): Inside a GNU ld SECTIONS block, ENTRY(_start) records the ELF entry symbol, . (the location counter) tracks the current output VMA, and ALIGN(n) rounds upward to ( . + n - 1 ) & ~(n - 1) (leaving already-aligned addresses unchanged). ADDR(sec) yields runtime VMA while LOADADDR(sec) yields AT(...) load placement. A script assignment __bss_start = .; creates an ELF symbol-table entry whose address equals . (allocating zero storage bytes in RAM!), defining the exact [__bss_start, __bss_end) interval zeroed by start.S.
Walk through the four-stage contract connecting input .o sections, bsp.lds policy, boundary symbols, and banked stacks:
- Step 1. Step 1: Set ENTRY(_start) and place KEEP(*(.text.start)) first in .text so _start stays pinned at 0x87800000.
- Step 2. Step 2: Pack .data initializers at AT(__data_lma) while linking live globals at VMA 0x87810000.
- Step 3. Step 3: Define __bss_start and ALIGN(4)-rounded __bss_end inside a (NOLOAD) .bss section including *(COMMON).
- Step 4. Step 4: Reserve 8-byte-aligned banked stacks above .bss and guard alignment + RAM ceiling with ASSERT().
Figure 5.2b. Linker boundary symbols are an executable contract: define them inside aligned output sections and reference their addresses, never their dereferenced values.
Linker Symbol Address-vs-Value Semantics & Exact ALIGN Placement
Study Figure 5.2b carefully—it illustrates one of the most notorious C firmware bugs in industry. When you write uint32_t g_var = 42; in C, the linker reserves 4 bytes in .data and puts g_var's address in .symtab; evaluating g_var in C emits an ldr that reads 42 from memory. When you write __bss_start = .; in bsp.lds, the linker puts 0x87810008 in .symtab and reserves zero bytes (0x87810008 is the first global inside .bss!). Therefore, declaring extern uint32_t __bss_start; and casting (void *)__bss_start in C dereferences 0x87810008 and treats whatever garbage sits in .bss as a pointer! Always declare linker symbols in C as extern char __bss_start[], __bss_end[]; so array-to-pointer decay yields the symbol address 0x87810008 directly (matching ldr r0, =__bss_start in start.S).
Check two placement rules inside bsp.lds below as well. First, put __bss_start = .; inside .bss ALIGN(4) (NOLOAD) : { ... } (after section alignment adjusts .) and put . = ALIGN(4); before __bss_end = .;, guaranteeing (__bss_end - __bss_start) % 4 == 0 for start.S's 4-byte str r2, [r0], #4 loop! Second, wrap *(.text.start) in KEEP(...) so --gc-sections never deletes _start as "uncalled by C."
Figure 5.2b. Why linker symbols must be declared as char arrays in C (top) and how ALIGN(4) brackets [__bss_start, __bss_end) for word loops (bottom).
GNU ld Directive | Effect on bsp.elf / bsp.bin | Runtime / Packer Obligation | Defect When Omitted |
|---|---|---|---|
KEEP(*(.text.start)) at .text start | Pins _start at 0x87800000; survives --gc-sections | IVT.entry must also store 0x87800000 | Helper function lands at 0x87800000 ahead of _start! |
.data VMA : AT(__data_lma) | Separates ADDR(.data) from LOADADDR(.data) | start.S copies SIZEOF(.data) LMA -> VMA | 64 KiB+ zero-padding bloat in bsp.bin |
(NOLOAD) on .bss and .stack | Emits SHT_NOBITS (0 file bytes in bsp.bin) | start.S zeroes [__bss_start, __bss_end) | .bss/.stack dumped into .bin, inflating transfer |
ASSERT((__stack_top & 7) == 0, ...) | Fails ld exit status immediately on overflow/misalign | Sync ceiling (0x87900000) with board RAM map | Silent stack/.bss overlap or AAPCS alignment fault |
learner@ksa:~/gl-e01/m05-l02$ bat -H 5 -H 8 -H 9 -H 10 -H 11 -H 12 -H 13 -H 14 -H 15 -H 16 -H 17 -H 18 -H 19 -H 20 -H 21 -H 22 -H 23 -H 30 -H 31 bsp.lds File: bsp.lds ENTRY(_start) SECTIONS { . = 0x87800000; .text : { KEEP(*(.text.start)) *(.text*) } .rodata ALIGN(4) : { *(.rodata*) } __data_lma = ALIGN(., 4); .data 0x87810000 : AT(__data_lma) { __data_start = .; *(.data*) . = ALIGN(4); __data_end = .; } __data_load = LOADADDR(.data); __image_load_end = LOADADDR(.data) + SIZEOF(.data); .bss ALIGN(4) (NOLOAD) : { __bss_start = .; *(.bss*) *(COMMON) . = ALIGN(4); __bss_end = .; } .stack ALIGN(8) (NOLOAD) : { __stack_bottom = .; . += 4096; __stack_top = .; } ASSERT((__stack_top & 7) == 0, "stack alignment") ASSERT(__stack_top <= 0x87900000, "RAM window exceeded") }- Pin .text.start at 0x87800000 with KEEP() so neither link order nor --gc-sections displaces _start.
- Export LOADADDR(.data) as __data_load and compute __image_load_end for BootData.length validation.
- Fail the link at build time if __stack_top violates 8-byte alignment or exceeds the 1 MiB RAM window.
Verifying Overflow-Safe ALIGN() & Dual-Mode Stack Partitioning in C11
When firmware enables GICv2 interrupts (GL-E02), _start partitions both SP_irq (4 KiB) and SP_svc (8 KiB) above __bss_end while CPSR keeps I | F == 0xC0 masked. In reset_sp_bss_verifier.c below, align_up() validates power-of-two alignments ((a & (a - 1)) == 0) and guards value <= UINT32_MAX - (a - 1) before adding, while verify_reset_map() checks CPSR interrupt masking, 4-byte .bss alignment, 8-byte IRQ/SVC stack alignment, and non-overflow inside [0x87800000, 0x87900000).
learner@ksa:~/gl-e01/m05-l02$ bat -H 7 -H 8 -H 9 -H 10 -H 11 -H 12 -H 13 -H 15 -H 16 -H 17 -H 18 -H 19 -H 20 -H 21 -H 22 -H 23 -H 24 -H 25 -H 26 -H 27 -H 28 reset_sp_bss_verifier.c File: reset_sp_bss_verifier.c #include <assert.h> #include <stdbool.h> #include <stdint.h> #include <stdio.h> static bool align_up(uint32_t value, uint32_t alignment, uint32_t *out) { if (alignment == 0U || (alignment & (alignment - 1U)) != 0U) return false; uint32_t add = alignment - 1U; if (value > UINT32_MAX - add) return false; *out = (value + add) & ~add; return true; } static bool verify_reset_map(uint32_t cpsr_reset, uint32_t bss_start, uint32_t bss_end, uint32_t irq_sz, uint32_t svc_sz, uint32_t win_end, uint32_t *irq_sp, uint32_t *svc_sp) { if ((cpsr_reset & 0xc0U) != 0xc0U) return false; /* CPSID if required */ if (bss_start > bss_end || ((bss_start | bss_end) & 3U) != 0U) return false; if (irq_sz == 0U || svc_sz == 0U || ((irq_sz | svc_sz) & 7U) != 0U) return false; uint32_t irq_bot = 0U; if (!align_up(bss_end, 8U, &irq_bot)) return false; if (irq_sz > win_end - irq_bot) return false; uint32_t irq_top = irq_bot + irq_sz; if (svc_sz > win_end - irq_top) return false; *irq_sp = irq_top; *svc_sp = irq_top + svc_sz; return ((*irq_sp & 7U) == 0U) && ((*svc_sp & 7U) == 0U); } int main(void) { uint32_t out = 0U; assert(align_up(0x87800000U, 4U, &out) && out == 0x87800000U); assert(align_up(0x87800003U, 4U, &out) && out == 0x87800004U); assert(!align_up(UINT32_MAX, 8U, &out) && !align_up(10U, 3U, &out)); uint32_t text = 128U, rodata = 16U, data = 8U, bss = 64U; uint32_t data_lma = 0x87800000U + text + rodata; uint32_t data_vma = 0x87810000U, bss_start = data_vma + data; uint32_t bss_end = bss_start + bss, irq_sp = 0U, svc_sp = 0U; assert(data_lma == 0x87800090U && text + rodata + data == 152U); assert(verify_reset_map(0xd3U, bss_start, bss_end, 4096U, 8192U, 0x87900000U, &irq_sp, &svc_sp)); assert(!verify_reset_map(0x13U, bss_start, bss_end, 4096U, 8192U, 0x87900000U, &irq_sp, &svc_sp)); assert(!verify_reset_map(0xd3U, bss_start, bss_end + 2U, 4096U, 8192U, 0x87900000U, &irq_sp, &svc_sp)); printf("LMA=0x%08X packed=%uB bss_end=0x%08X irq_sp=0x%08X svc_sp=0x%08X\n", data_lma, text + rodata + data, bss_end, irq_sp, svc_sp); return 0; }- Accept only power-of-two alignments and guard value <= UINT32_MAX - add before rounding up.
- Require I|F masked (0xC0) and word-aligned [bss_start, bss_end) boundaries matching the 4-byte zero loop.
- Place 8-byte-aligned IRQ and SVC stacks sequentially above __bss_end without overlapping or exceeding win_end.
Executing the Linker-Map & Banked-Stack Verifier
Compile and run reset_sp_bss_verifier.c below. Confirm that packed=152B (128 + 16 + 8), bss_end=0x87810048, irq_sp=0x87811048, and svc_sp=0x87813048 (0x48 == 72 == 9 * 8, 8-byte aligned), while unmasked CPSR = 0x13U and unrounded bss_end + 2U are rejected cleanly.
learner@ksa:~/gl-e01/m05-l02gcc -std=c11 -Wall -Wextra -Werror -pedantic reset_sp_bss_verifier.c -o reset_sp_bss_verifierlearner@ksa:~/gl-e01/m05-l02./reset_sp_bss_verifierLMA=0x87800090 packed=152B bss_end=0x87810048 irq_sp=0x87811048 svc_sp=0x87813048learner@ksa:~/gl-e01/m05-l02learner@ksa:~/gl-e01/m05-l02strace -e trace=write,exit_group \./reset_sp_bss_verifierwrite(1, "LMA=0x87800090 packed=152B bss_e"..., 82) = 82exit_group(0) = ?+++ exited with 0 +++Auditing Orphan Sections with readelf -l & nm -n
Even with bsp.lds in place, compilers occasionally emit auxiliary sections—such as .ARM.exidx (unwind tables) or .rodata.str1.4 (merged strings). If a wildcard (*(.rodata*)) misses an input section, GNU ld places that orphan section heuristically, potentially slipping bytes after __image_load_end! Always pass -Wl,--orphan-handling=warn (or =error once .ARM.attributes / .comment are handled) and inspect readelf -S -l bsp.elf plus nm -n bsp.elf so __image_load_end - 0x87800000 equals the exact bsp.bin file size. Later: Lesson m05-l03 moves from RAM layout to Memory-Mapped I/O (MMIO) peripheral structs, proving register byte offsets at compile time with _Static_assert and offsetof.
Common Production Pitfalls
warning: Symptom: A C startup helper declares extern uint32_t __bss_start, __bss_end; and calls memset((void *)__bss_start, 0, __bss_end - __bss_start), immediately crashing or zeroing address 0x00000000. Root Cause: Evaluating __bss_start as a uint32_t variable loads the word stored at __bss_start instead of taking the linker symbol's address. Fix: Declare linker boundary symbols as extern char __bss_start[], __bss_end[]; (using (size_t)(__bss_end - __bss_start)), where array decay yields the symbol table address directly without dereferencing RAM.
warning: Symptom: Adding -ffunction-sections -fdata-sections -Wl,--gc-sections shrinks bsp.bin, but the board stops booting because bsp.bin is 0 bytes (or starts inside an unrelated C helper at 0x87800000). Root Cause: Without ENTRY(_start) and KEEP(*(.text.start)) at the top of .text, linker garbage collection prunes _start (and .ivt) because no C function references them. Fix: Root reachability with ENTRY(_start) and wrap .ivt, .dcd, .vectors, and .text.start in KEEP(...).
Practice & Retrieval
Guided Practice: Binary Gap Bloat & Banked SP Initialization
Check three linker mechanics by hand. Step 1 (Binary Size): With .text (512 B) at 0x87800000 and .data (32 B) at 0x87810000, compute bsp.bin size without AT(...) (0x87810020 - 0x87800000 = 65,568 B) versus with AT(ALIGN(LOADADDR(.text) + SIZEOF(.text), 4)) (512 + 32 = 544 B). Step 2 (Pre-Align Bug): If __bss_start = .; sits outside .bss ALIGN(16) when . = 0x87810004, note that [0x87810004, 0x87810010) (12 padding bytes before .bss) would be zeroed unintentionally.
Independent Practice: Multi-Section Overlap & Orphan Auditor (lds_map_auditor.c)
Extend reset_sp_bss_verifier.c into lds_map_auditor.c checking an array of section records (name, vma, lma, size, align, noload): verify power-of-two vma and lma alignments, pairwise non-overlap of all runtime [vma, vma + size) intervals, pairwise non-overlap of load [lma, lma + size) intervals on non-NOLOAD sections, and exact agreement between serialized .bin span and BootData.length - 0x1000.
Key takeaways
ENTRY(_start)plusKEEP(*(.text.start))at the start of.textpins the reset entry point at0x87800000and protects it from--gc-sections.- The location counter
.tracks currentVMA, whileALIGN(n)rounds upward to power-of-two boundaries without advancing already-aligned addresses. .data VMA : AT(LMA)separates runtimeADDR(.data)from packedLOADADDR(.data), preventing multi-kilobyte zero-padding bloat inobjcopy -O binaryoutputs while(NOLOAD)omits.bssand.stackbytes.- Linker boundary symbols (
__bss_start,__bss_end,__stack_top) encode addresses in.symtab(never allocated C pointer variables) and pair withASSERT(...)to catch alignment or RAM overflows at link time. - ENTRY selects the entry symbol, while SECTIONS controls placement of linked output sections.
- The location counter denotes the current linked address; ALIGN adjusts placement to the required boundary.
- No; the boot structure must carry the matching entry value.