Creating bare-metal ARM Cortex-A startup code
A startup assembly snippet is crafted to disable interrupts, switch CPU to SVC, IRQ, and FIQ modes setting SP for each, zero the .bss section using linker-defined labels, then branch to main(), followed by an infinite loop; stack areas are also defined in .bss with aligned space and appropriately named labels for the stack tops.
On an ARMv7‑A core the processor comes out of reset in Supervisor mode at address 0. A minimal bare‑metal layout therefore needs a vector table at 0, some startup code to put sensible values in each mode’s stack pointer, clear the .bss, and then branch into your C main.
Here's a simple startup.S using GNU as syntax that does that:
.syntax unified
.cpu cortex-a9 @ pick your Cortex-A core
.arm
.global _start
.extern main
.extern __bss_start__
.extern __bss_end__
/* Vector table at address 0 */
.section .vectors, "ax"
.align 5
b _start @ Reset
b . @ Undefined instruction
b . @ Supervisor call
b . @ Prefetch abort
b . @ Data abort
b . @ Reserved
b . @ IRQ
b . @ FIQ
/* Startup code */
.section .text, "ax"
.align 4
_start:
cpsid if @ disable IRQ and FIQ while we set up
/* Switch to SVC and set its stack */
cps #0x13 @ SVC mode (0b10011)
ldr sp, =_svc_stack_top
/* Switch to IRQ mode and set its stack */
cps #0x12 @ IRQ mode (0b10010)
ldr sp, =_irq_stack_top
/* Switch to FIQ mode and set its stack */
cps #0x11 @ FIQ mode (0b10001)
ldr sp, =_fiq_stack_top
/* Return to SVC mode for C runtime */
cps #0x13
/* Zero out the .bss section: for (p = __bss_start__; p < __bss_end__; ++p) *p = 0; */
ldr r0, =__bss_start__
ldr r1, =__bss_end__
movs r2, #0
zero_loop:
cmp r0, r1
bge zero_done
str r2, [r0], #4
b zero_loop
zero_done:
/* Call C main() */
bl main
/* If main returns, just loop forever */
hang:
b hang
/* Reserve stacks in .bss */
.section .bss, "aw"
.align 3
.global _svc_stack_top, _irq_stack_top, _fiq_stack_top
_svc_stack:
.space 1024 @ 1 KB SVC stack
_svc_stack_top:
_irq_stack:
.space 512 @ 512 B IRQ stack
_irq_stack_top:
_fiq_stack:
.space 512 @ 512 B FIQ stack
_fiq_stack_top:
A matching C main can be as simple as:
/* main.c */
int main(void) {
/* Your bare-metal application code here */
while (1) {
/* spin */
}
return 0;
}
And a linker script should provide the __bss_start__ and __bss_end__ symbols to delimit the .bss section and place the vectors at address 0. For example:
SECTIONS {
. = 0x00000000;
.vectors : { KEEP(*(.vectors)) }
.text : { *(.text*) }
.bss : {
__bss_start__ = .;
*(.bss*)
*(COMMON)
__bss_end__ = .;
}
/* ...other sections... */
}
Assemble startup.S, compile main.c, and link with the linker script to produce a bare‑metal image. At reset the CPU will branch to _start, the stacks will be initialized for IRQ, FIQ, and SVC, .bss will be cleared, and execution will jump into main().