Branches, Full-Descending Stacks, and Calling C
Understand why Cortex-A7 stores subroutine return addresses in a single Link Register (LR), trace full-descending stack frames (STMFD/LDMFD) down to their 16-bit hardware register bitmask, and enforce 8-byte AAPCS32 stack alignment across nested C calls.
What you'll learn
- Trace B, BL, and BX without confusing subroutine and exception returns.
- Construct an eight-byte-aligned full-descending frame around a nested call.
- Verify saved-register order and restore the caller-visible state.
Link-Register Lifetime, Full-Descending Stacks, and 8-Byte Alignment
On x86_64, executing call helper automatically decrements %rsp and writes an 8-byte return address into RAM—even if helper is a 2-instruction leaf function (add + ret) that never needed RAM at all! ARM RISC designers asked: why burn two memory bus cycles on every tiny leaf call? Instead, BL (Branch with Link) writes the return address (next_instr) directly into r14 (LR, the Link Register) in zero memory cycles, allowing a leaf function (add_words) to return instantly via BX LR! What is the catch? Look at the timeline in Figure 2.3b: Cortex-A7 has only ONE live LR in the current mode! The instant a non-leaf function (sum_then_double) executes a nested bl add_words, that inner bl overwrites LR, erasing the outer caller's return address forever unless the prologue saved LR to RAM first!
How does ARMv7-A organize that stack in RAM, and why can pushing {lr} alone (4 bytes) crash a C program? Inspect both halves of Figure 2.3a:
- Full-Descending Stack (
STMFD==STMDB,LDMFD==LDMIA): Descending means the stack grows downward from high RAM addresses (0x1000) toward low addresses (0x0FF8); Full meansSP(r13) always points at the last occupied word (not the next empty slot). Executingstmfd sp!, {r4, lr}(popcount = 2words =8bytes) decrementsSPfrom0x1000to0x0FF8before storing. Even more important: inside the32-bit ARM opcode,{r4, lr}is encoded as a16-bit register bitmask ((1 << 4) | (1 << 14) = 0x4010)! Hardware always stores the lowest-numbered register (r4) at the lowest byte address (0x0FF8 = [sp]) and higher-numberedlr(r14) at0x0FFC = [sp + 4], even if you type{lr, r4}in source! - Mandatory
8-Byte PublicSPAlignment (SP mod 8 == 0):AAPCS32requiresSPto be a multiple of8bytes at every public C call boundary because64-bit integers (uint64_t),doublevalues,va_arg(), andARMv7-Adoubleword instructions (LDRD/STRD) require8-byte stack alignment. If incomingSP = 0x1000(mod 8 == 0) and an assembly wrapper pushes{lr}alone (4bytes ->SP = 0x0FFC,mod 8 == 4), callingprintfor anyuint64_tC helper either triggers a hardware AlignmentData Abortor reads swapped32-bit words! Pushing an even register pair (stmfd sp!, {r4, lr}) subtracts8bytes (0x0FF8 mod 8 == 0), saving both outerLRand callee-ownedr4in one instruction!
Figure 2.3a. frame layout and 16-bit register bitmask ordering (left) vs why public C calls require 8-byte SP alignment (right).
mental model: Holding a return address in LR is like keeping a finger on page 104 while reading a footnote (leaf call): before jumping from that footnote to a second index table (nested BL), you must tuck an 8-byte bookmark pair ({r4, lr}) onto the stack.
Where it stops working: Unlike paper bookmarks, STMFD orders registers strictly by hardware register number rather than assembly text order, public C calls mandate 8-byte SP alignment, and hardware exception returns (subs pc, lr, #4) must never be used to return from BL subroutines.
definition (B / BL / BX Control Transfer, Full-Descending Stack & 8-Byte AAPCS32 Frame): In ARMv7-A, B jumps without touching LR; BL writes the subroutine return address into LR before branching; and BX Rm branches to Rm & ~1U while setting CPSR.T = Rm[0] (1 = Thumb, 0 = ARM interworking). STMFD sp!, {reglist} (STMDB) allocates 4 * k bytes below SP and stores registers in ascending register-number order (r0..r15) from lowest to highest address; LDMFD sp!, {..., pc} (LDMIA) pops the frame and returns. Every public AAPCS32 call site must satisfy SP mod 8 == 0.
Step through the four phases of a non-leaf assembly-to-C call frame below:
- Step 1. Step 1 (Caller Entry): Outer BL writes return address into live LR with incoming SP aligned to 8 bytes.
- Step 2. Step 2 (Prologue Save): stmfd sp!, {r4, lr} decrements SP by 8 bytes, placing r4 at [sp] and LR at [sp + 4].
- Step 3. Step 3 (Nested Call): Inner BL overwrites live LR and scratch r0..r3/r12 while saved LR and r4 remain safe on the stack.
- Step 4. Step 4 (Epilogue Pop): ldmfd sp!, {r4, pc} restores caller r4, pops outer LR into PC, and restores SP.
Figure 2.3b. Every non-leaf assembly routine calling C must save outer LR and keep SP 8-byte aligned across all exit paths.
Tracing Nested Calls and Separating Subroutine vs Exception Returns
Follow the exact register and stack values across sum_then_double in Figure 2.3b and target.S below:
- Caller enters
sum_then_double(7, 9)viabl:r0 = 7,r1 = 9,SP = 0x1000,LR = 0x87800104. - Prologue
stmfd sp!, {r4, lr}setsSP = 0x0FF8, writes callerr4to[0x0FF8]and0x87800104to[0x0FFC]. bl add_wordsoverwrites liveLRwith0x87800208;add_wordscomputesr0 = 7 + 9 = 16and executesbx lr(PC <- 0x87800208, zero stack traffic!).lsl r0, r0, #1doublesr0to32, and epilogueldmfd sp!, {r4, pc}restoresr4, loads[0x0FFC] = 0x87800104directly intoPC(interworking-capable inARMv7-A!), and restoresSP = 0x1000.
Look at Panel 2 of Figure 2.3b: never confuse bx lr with subs pc, lr, #4! Hardware IRQ exception entry biases LR_irq = interrupted_PC + 4 and snapshots SPSR_irq, so IRQ handlers return via subs pc, lr, #4 (copying SPSR -> CPSR). Subroutine BL already stores the exact next instruction address in LR without touching SPSR; running subs pc, lr, #4 at the end of add_words jumps 4 bytes backward right onto bl add_words in an infinite loop (or faults in USR/SYS where no SPSR exists)!
Figure 2.3b. Return-address lifetime across nested BL calls (top) and why BX LR / LDMFD subroutine returns differ fundamentally from subs pc, lr, #4 exception returns (bottom).
learner@ksa:~/gl-e01/m02-l03$ bat target.S File: target.S .syntax unified .cpu cortex-a7 .arm .text .global sum_then_double .type sum_then_double, %function sum_then_double: stmfd sp!, {r4, lr} bl add_words lsl r0, r0, #1 ldmfd sp!, {r4, pc} .size sum_then_double, .-sum_then_double .type add_words, %function add_words: add r0, r0, r1 bx lr .size add_words, .-add_wordsProving AAPCS32 Stack Alignment and Callee Preservation in C11
aapcs32_frame_verifier.c simulates the 16-word ARMv7-A register file and a 16-word full-descending stack. Notice three deliberate adversarial checks inside simulate_nested_call(): (1) push_pair_fd() rejects any misaligned incoming SP (sp_word = 7 -> 28 bytes, 28 & 7 != 0) before touching memory; (2) stack[sp] receives r4 while stack[sp + 1] receives lr (reg_lo < reg_hi); and (3) the simulated nested BL fills caller-saved r1, r2, r12, and live r14 (LR) with 0xDEADBEEFU while asserting every callee-saved register r4..r11 emerges bit-for-bit identical on return!
learner@ksa:~/gl-e01/m02-l03$ bat -H 11 -H 12 -H 13 -H 14 -H 15 -H 16 -H 17 -H 18 -H 22 -H 23 -H 24 -H 25 -H 26 -H 27 -H 28 -H 29 -H 30 aapcs32_frame_verifier.c File: aapcs32_frame_verifier.c #include <assert.h> #include <stdbool.h> #include <stdint.h> #include <stdio.h> struct aapcs_ctx { uint32_t r[16]; /* r13 = SP word index, r14 = LR, r15 = PC */ uint32_t stack[16]; }; static bool push_pair_fd(struct aapcs_ctx *c, unsigned reg_lo, unsigned reg_hi) { if (reg_lo >= reg_hi || c->r[13] < 2U || ((c->r[13] * 4U) & 7U) != 0U) return false; c->r[13] -= 2U; c->stack[c->r[13]] = c->r[reg_lo]; c->stack[c->r[13] + 1U] = c->r[reg_hi]; return ((c->r[13] * 4U) & 7U) == 0U; } static bool simulate_nested_call(struct aapcs_ctx *c) { uint32_t saved_callees[8]; for (unsigned i = 0U; i < 8U; ++i) saved_callees[i] = c->r[4U + i]; if (!push_pair_fd(c, 4U, 14U)) return false; c->r[4] = c->r[0] + c->r[1]; /* caller uses r4 across nested BL */ c->r[14] = 0x87800208U; /* nested BL overwrites live LR */ c->r[0] = c->r[4]; c->r[1] = 0xdeadbeefU; c->r[2] = 0xdeadbeefU; c->r[12] = 0xdeadbeefU; c->r[0] <<= 1; /* helper result doubled */ c->r[4] = c->stack[c->r[13]]; c->r[15] = c->stack[c->r[13] + 1U]; c->r[13] += 2U; for (unsigned i = 0U; i < 8U; ++i) if (c->r[4U + i] != saved_callees[i]) return false; return true; } int main(void) { struct aapcs_ctx c = {{0U}, {0U}}; c.r[0] = 7U; c.r[1] = 9U; c.r[13] = 8U; c.r[14] = 0x87800104U; for (unsigned i = 4U; i <= 11U; ++i) c.r[i] = 0x40000000U + i; assert(simulate_nested_call(&c)); assert(c.r[0] == 32U && c.r[4] == 0x40000004U); assert(c.r[15] == 0x87800104U && c.r[13] == 8U); assert(c.stack[6] == 0x40000004U && c.stack[7] == 0x87800104U); c.r[13] = 7U; /* 28 bytes: 4-byte aligned, violates 8-byte public boundary */ assert(!push_pair_fd(&c, 4U, 14U) && c.r[13] == 7U); printf("AAPCS32 frame=8B sp_word=%u r0=%u r4=0x%08X ret_pc=0x%08X\n", 8U, c.r[0], c.r[4], c.r[15]); return 0; }- Require 8-byte SP alignment and an even push count before entering a nested AAPCS32 public call.
- Store r4 at the lower word (sp) and lr at the upper word (sp + 1) matching hardware register-number order.
- Clobber caller-saved r1..r3, r12, and live lr inside the nested call while requiring r4..r11 to match on exit.
Running the Frame Verifier and Checking Target Encodings
Compile and run aapcs32_frame_verifier.c, then cross-assemble target.S. Remember that on physical i.MX6ULL silicon, stmfd sp!, {r4, lr} also requires sp to point into live RAM (128 KiB OCRAM 0x00900000..0x00920000 before DDR3 init, or calibrated DDR3 afterward)—an 8-byte-aligned pointer into uninitialized DDR3 still crashes on first push!
learner@ksa:~/gl-e01/m02-l03gcc -std=c11 -Wall -Wextra -Werror -pedantic aapcs32_frame_verifier.c -o aapcs32_frame_verifierlearner@ksa:~/gl-e01/m02-l03./aapcs32_frame_verifierAAPCS32 frame=8B sp_word=8 r0=32 r4=0x40000004 ret_pc=0x87800104learner@ksa:~/gl-e01/m02-l03clang --target=armv7a-none-eabi -mcpu=cortex-a7 -marm -c target.S -o target.olearner@ksa:~/gl-e01/m02-l03learner@ksa:~/gl-e01/m02-l03strace -e trace=write,exit_group \./aapcs32_frame_verifierwrite(1, "AAPCS32 frame=8B sp_word=8 r0=32"..., 65) = 65exit_group(0) = ?+++ exited with 0 +++Control-Transfer Matrix and Balanced Exit Paths
Audit every early-return branch in hand-written assembly: if an error path jumps to bx lr after stmfd sp!, {r4, lr} without executing ldmfd sp!, {r4, pc}, SP leaks 8 bytes and bx lr jumps to a clobbered inner LR!
| Instruction | Updates LR? | Restores CPSR? | Interworks ARM/Thumb? | Valid Use Case |
|---|---|---|---|---|
b label | No | No | No (same ISA state) | Local unconditional jump or zero-frame tail-call |
bl helper | Yes (LR = next_instr) | No | No (BLX switches state) | Standard subroutine call; clobbers caller's live LR |
bx lr | No | No | Yes (LR[0] == 1 -> Thumb) | Leaf-function subroutine return (0 stack accesses) |
ldmfd sp!, {r4, pc} | No (loads saved LR -> PC) | No (^ suffix is exception-only) | Yes in ARMv7-A | Non-leaf subroutine epilogue restoring 8-byte frame |
Later: Module 3 (m03-l01..m03-l03) applies BIC, ORR, DSB SY, and AAPCS32-callable assembly routines directly to i.MX6ULL CCM clock gates, IOMUXC pad electricals, and GPIO1 W1C registers.
Common Production Pitfalls
warning: Symptom: An assembly startup stub pushes {lr} (4 bytes) from an 8-byte-aligned stack and calls a C diagnostic function using uint64_t or LDRD, triggering an Alignment Data Abort or printing garbled 64-bit numbers. Root Cause: Subtracting 4 bytes left SP mod 8 == 4 at a public AAPCS32 C interface where the compiler assumes SP mod 8 == 0. Fix: Push an even number of registers (stmfd sp!, {r4, lr}) so SP moves in multiples of 8 bytes.
warning: Symptom: A leaf assembly function called via bl delay_ticks ends with subs pc, lr, #4 instead of bx lr, hanging in an infinite loop re-executing bl delay_ticks (or trapping). Root Cause: subs pc, lr, #4 is the hardware IRQ exception return (restoring SPSR and subtracting the +4 pipeline bias), whereas bl stores the exact return address in lr. Fix: Return from BL subroutines exclusively via bx lr (leaf) or ldmfd sp!, {..., pc} (non-leaf).
Practice & Retrieval
Guided Practice: Five-Argument Stack Passing & Register-List Ordering
Step 1 (5th Argument Frame): To call uint32_t pack5(uint32_t a, uint32_t b, uint32_t c, uint32_t d, uint32_t e) from assembly with SP = 0x87820000, state where a..d and e go and how much stack space to allocate (a..d in r0..r3; allocate 8 bytes via sub sp, sp, #8 so SP = 0x8781FFF8 stays 8-byte aligned, placing e at [sp, #0] and 4 pad bytes at [sp, #4]). Step 2 (Bitmask Order): List the exact byte addresses written by stmfd sp!, {r12, r4, lr, r6} from SP = 0x1000 (r4 @ 0x0FF0, r6 @ 0x0FF4, r12 @ 0x0FF8, lr @ 0x0FFC). Step 3 (Scratch Check): State whether r12 survives bl pack5 (No—r12 is caller-saved IP scratch!).
Independent Practice: General 16-Bit Bitmask STMFD/LDMFD Verifier (stmfd_abi_audit.c)
Extend aapcs32_frame_verifier.c into stmfd_abi_audit.c implementing exec_stmfd() and exec_ldmfd() for any non-zero uint16_t regmask. Prove that storage order depends solely on bit index 0..15, reject regmask == 0, enforce SP mod 8 == 0 at simulated C call sites, and verify a 5-argument call frame ([sp, #0] = arg4, [sp, #4] = pad).
→ open standalone lab workbench
1. Motivation
Early ARMv7-A startup routines fail in subtle ways when a mode transition from IRQ (0x12) to SVC (0x13) accidentally clears CPSR.I/CPSR.F (bits 7:6) or condition flags NZCV (bits 31:28), when a memory-copy loop confuses pre-indexed [Rn, #4]! with post-indexed [Rn], #4 and skips the first word of .data, or when a prologue pushes an odd register count and violates AAPCS32 8-byte SP alignment ((SP mod 8) == 0) before calling C. In this laboratory, you will diagnose a swapped effective-address calculation in starter/core.c and verify CPSR mode-field masking, pre/post indexing semantics, 4-bit BIC/ORR field replacement, and full-descending AAPCS32 stack-frame invariants.
2. Learning Objectives
- Preserve
CPSRstatus, endianness, thumb, and interrupt-mask bits (~0x1FU) when replacingM[4:0](select_mode) to enterSVC(0x13). - Distinguish pre-indexed (
base + offset) from post-indexed (base) memory effective addresses ineffective()so load/store models matchCortex-A7AGU hardware. - Mask oversized
4-bit field inputs ((value & 15U) << 8) after clearingbits [11:8](~0xF00U) inreplace_field(). - Enforce full-descending
8-byte-aligned two-word stack pushes (r4at lower addresswords[*sp],lratwords[*sp + 1U]) inframe().
3. Environment Requirements
- Tested Workstation Host:
Linux 7.0.0-42-generic(x86_64) executing insidelabs/lab_m02_armv7_isa_sim/. - Target Architecture Alignment: Models
32-bitARMv7-A(A32state) architectural registers (CPSR,r0..r15) andAAPCS32word-indexed stack memory (words[0..7],4bytes per word, even word index<=>8-byte byte-address alignment).
4. Required Software & Hardware
- Software:
gcc(-std=c11 -Wall -Wextra -Werror -pedantic -MMD -MP), GNUmake, GNUar, POSIX/bin/sh, and Binutils (nm,objdump). - Hardware: Standard Linux workstation (
0JTAG debuggers or physicalCortex-A7boards required for the 5-checkTAPgrader).
5. Complete Executable Commands
Execute the command sequence below inside labs/lab_m02_armv7_isa_sim/ to reproduce not ok 3 on starter/, inspect the failing case-2 assertion, build files/libbsp.a, and verify 5/5 TAP checks:
learner@ksa:~/gl-e01/m02-l03$ bat script.sh File: script.sh # 1. Run check.sh against an isolated copy of starter/ to observe check 3 fail (# pass 4/5) TMP=$(mktemp -d) && cp -r check.sh tests.c starter "$TMP/" && mv "$TMP/starter" "$TMP/files" && sh "$TMP/check.sh" ; rm -rf "$TMP" # 2. Compile tests.c against starter/core.c and execute cases 1..4 individually TMP=$(mktemp -d) && gcc -std=c11 -Wall -Wextra -Werror -pedantic -Istarter tests.c starter/core.c -o "$TMP/sim" && for c in 1 2 3 4; do "$TMP/sim" "$c" && echo "case $c: PASS" || echo "case $c: FAIL (rc=$?)"; done ; rm -rf "$TMP" # 3. Compile files/libbsp.a and disassemble effective() and frame() to inspect generated instructions make -B -C files nm -g --defined-only files/libbsp.a && objdump -d files/core.o # 4. Run the graded TAP version 13 harness on files/ sh check.sh*Why each step runs:* Step 1 exercises starter/ through the exact check.sh grader without overwriting files/core.c; Step 2 isolates case 2 (effective) as the sole SIGABRT while confirming cases 1, 3, and 4 pass; Step 3 confirms clean -Werror archive generation; and Step 4 validates all 5 TAP invariants.
6. Annotated Source Code (starter/core.c Defect vs files/core.c Fix)
select_mode(uint32_t old, uint32_t mode)(core.c:2-5): Evaluates(old & ~UINT32_C(0x1f)) | (mode & 0x1fU), modelingBIC r0, r0, #0x1ffollowed byORR r0, r0, #0x13. Intests.ccase1,0xa00000d0U(N=1, C=1, I=1, F=1, USR=0x10) transitions to0xa00000d3U(SVC=0x13) with upper27bits intact.- Seeded Flaw in
starter/core.c:6-9(effective):startercomputesreturn pre ? base : base + offset;-- swapping pre-indexed and post-indexed addressing! OnARMv7-A, post-indexedLDR Rt, [Rn], #4(pre == false) accesses memory atRn(base) before writingRn + 4back toRn, whereas pre-indexedLDR Rt, [Rn, #4]!(pre == true) accesses memory atRn + 4(base + offset). - Verified Repair in
files/core.c:6-9: Restoresreturn pre ? base + offset : base;, matchingtests.ccase2(effective(0x1000U, 4U, false) == 0x1000Uandeffective(0x1000U, 4U, true) == 0x1004U). replace_field&frame(core.c:10-21):replace_field()clears[11:8]with~UINT32_C(0xf00)and truncates oversizedvalue = 0x32Uvia(value & 15U) << 8(0xa5a5f2ffU).frame()enforces*sp >= 2U && *sp <= 8U && (*sp & 1U) == 0U(8-byte alignment), decrements*sp -= 2U, and stores lowest-numberedr4atwords[*sp]andlr(r14) atwords[*sp + 1U]matchingPUSH {r4, lr}(STMDB sp!, {r4, lr}).
7. Expected TAP-13 Output
learner@ksa:~/gl-e01/m02-l03$ bat listing.txt File: listing.txt # Unmodified starter/ baseline (exits non-zero: # pass 4/5) TAP version 13 1..5 ok 1 - strict C11 build and trusted grader link ok 2 - preserves CPSR fields while selecting a legal ordinary mode not ok 3 - distinguishes pre-indexed and post-indexed access addresses --- message: 'Behavior differs from the independently specified test vectors' hint: 'Repair case 2; inspect tests.c for the exact input and expected result' ... ok 4 - replaces only the selected field and masks oversized values ok 5 - saves and restores a full-descending aligned register pair # pass 4/5 # Repaired files/ implementation (sh check.sh -> exits 0: # pass 5/5) TAP version 13 1..5 ok 1 - strict C11 build and trusted grader link ok 2 - preserves CPSR fields while selecting a legal ordinary mode ok 3 - distinguishes pre-indexed and post-indexed access addresses ok 4 - replaces only the selected field and masks oversized values ok 5 - saves and restores a full-descending aligned register pair # pass 5/58. Explanation of Observed Behavior
Under starter/, tests.c case 2 aborts immediately at line 14 (assert(effective(0x1000U, 4U, false) == 0x1000U)) because starter added offset = 4U on a post-indexed access and returned 0x1004U. Notice why line 16 (effective(0x1000U, 0U, true) == 0x1000U) would not have caught this defect on its own: when offset == 0U, base and base + offset coincide! Testing a non-zero offset (4U) across both pre == false and pre == true exposes the reversed ternary expression immediately, and repairing files/core.c:8 brings the suite to # pass 5/5.
9. Experiment Variations
- Unmasked
ORRSpill inreplace_field(): Remove& 15Uin a scratch copy soreplace_field()computes(old & ~UINT32_C(0xf00)) | (value << 8)onold = 0x00000000U, value = 0x32U: bit12and bit13(0x3000U) bleed into adjacent register fields, failingtests.c:18. - Swapped Register-List Order in
frame(): Swapwords[*sp] = lr; words[*sp + 1U] = r4;and runverify 4:ARMv7-ASTMDB sp!, {r4, lr}always places the lowest register number (r4) at the lowest memory address regardless of assembly syntax order, sowords[6] == 0x44444444Uaborts. - 4-Byte Misaligned Call-Site
SP: Remove(*sp & 1U) != 0Uin a scratch copy and observetests.c:26(sp = 1U, byte offset4) fail, demonstrating whyAAPCS32rejects odd-word stack pointers at public boundaries.
10. Performance Measurements
Benchmarked on Linux 7.0.0-42-generic (x86_64) via CLOCK_MONOTONIC (5 warmup runs, 35 timed runs):
Workload Measured (N = 35, warmup = 5) | Host p50 | Host p95 | Host p99 | Cortex-A7 @ 528 MHz Hardware Timing |
|---|---|---|---|---|
Full sh check.sh (make -B + gcc link + verify 1..4) | 127.95 ms | 136.35 ms | 142.79 ms | Host build + process spawn overhead |
verify 4-case ISA simulator suite (1..4 sequential) | 3466.4 us | 4050.7 us | 4293.0 us | < 1.5 us direct C calls without OS execve |
CPSR mode change (MRS + BIC + ORR + MSR + ISB) | ~1 ns pure ALU | ~2 ns | ~2 ns | ~12 - 20 cycles (23 - 38 ns, pipeline flush at ISB) |
11. Troubleshooting
| Symptom | Root Cause | Fix | |
|---|---|---|---|
not ok 3 (effective fails case 2 at tests.c:14) | Ternary returns base for pre == true and base + offset for pre == false | Return pre ? base + offset : base; in files/core.c | |
not ok 2 (CPSR NZCV or I/F bits clobbered) | Wrote old = mode or masked ~0xffU instead of ~0x1fU | Clear only M[4:0] via `(old & ~UINT32_C(0x1f)) \ | (mode & 0x1fU)` |
not ok 4 (0xa5a5ffffU becomes 0xa5a7f2ffU) | Missing & 15U allowed upper bits of 0x32U to overflow past bit 11 | Mask input width before shifting: ((value & 15U) << 8) | |
not ok 5 (sp = 1U modifies sp or words[]) | Decremented *sp -= 2U before checking *sp < 2U or (*sp & 1U) != 0U | Validate *sp >= 2U && *sp <= 8U && (*sp & 1U) == 0U prior to mutating *sp |
12. Guided Questions
- Why do
.datacopy loops inARMv7-A_startoverwhelmingly use post-indexedLDR r3, [r0], #4/STR r3, [r1], #4rather than pre-indexed[r0, #4]!?
- *Hint 1:* Linker symbols
__data_load(r0) and__data_start(r1) point directly to byte0of the section, not4bytes below it. - *Hint 2:* Trace which address the very first iteration loads under
pre = true(r0 + 4, skipping word0!) versuspre = false(r0, then advancingr0 <- r0 + 4for iteration2).
- Why does
AAPCS32mandate8-byteSPalignment ((*sp & 1U) == 0Uin32-bit words) at public function boundaries when ordinaryr0..r15registers are only4bytes wide?
- *Hint 1:* Consider instructions that transfer
64-bit doublewords on the stack (LDRD/STRD,VPUSH/VPOP, andint64_t/uint64_t/doubleprintfvarargs). - *Hint 2:* What alignment fault fires on
Cortex-A7whenLDRDexecutes against an address that is4-byte aligned (0x...4) instead of8-byte aligned (0x...0or0x...8)?
13. Independent Challenges
- Near Transfer — Legal
Cortex-A7Mode Whitelist (select_mode_checked): Writebool select_mode_checked(uint32_t old, uint32_t mode, uint32_t *out)that accepts only the9architecturalCortex-A7M[4:0]encodings (0x10,0x11,0x12,0x13,0x16,0x17,0x1A,0x1B,0x1F) and rejects reserved5-bit patterns such as0x00or0x14without altering*out. - Far Transfer — Paired Epilogue
unframe()(LDMIA sp!, {r4, pc}): Implementbool unframe(const uint32_t *words, unsigned *sp, uint32_t *r4_out, uint32_t *pc_out)that validates*sp <= 6U && (*sp & 1U) == 0U, popsr4andpcin full-descending order, increments*sp += 2U, and provesframefollowed byunframeis an exact identity on(sp, r4, lr).
14. Solutions & Explanations
- Guided Question 1: Because linker start symbols address the first element (
offset 0), post-indexed[Rn], #4dereferencesRn + 0on iteration0and leavesRnequal to_edatawhen the loop terminates; pre-indexed[Rn, #4]!would skip[Rn + 0]unless the pointer were pre-biased by-4. - Guided Question 2:
AAPCS32alignsSPto8bytes at every public call site so callees can issue64-bitLDRD/STRDandVFPstack spills without runtime realignment prologues or alignment data aborts. - Challenge 1 Bitmask Trick: Since
mode & 0x1fUlies in0..31, test membership inO(1)viaconst uint32_t legal = (1U<<0x10)|(1U<<0x11)|(1U<<0x12)|(1U<<0x13)|(1U<<0x16)|(1U<<0x17)|(1U<<0x1a)|(1U<<0x1b)|(1U<<0x1f);and check(mode <= 0x1fU) && ((legal >> mode) & 1U) != 0U.
Run locally in your terminal and check off each verification milestone.
Not started
Key takeaways
Bjumps without touchingLR,BLrecords the subroutine return address inLR(clobbering any unsavedLR), andBX Rmbranches while selecting ARM/Thumb state fromRm[0].STMFD sp!, {...}(STMDB) grows a full-descending stack downward and stores registers strictly in ascending register-number order (r0..r15), placing the lowest register at the lowest address.AAPCS32requires8-byte stack alignment (SP mod 8 == 0) at every public call site and requires callees to preserver4..r11andSP.- Never use
subs pc, lr, #4(anIRQexception return) to return from an ordinaryBLsubroutine; usebx lr(leaf) orldmfd sp!, {..., pc}(non-leaf). - B branches without creating a subroutine return address, while BL records a return address in LR.
- BX branches to a register target and uses the architectural instruction-state convention encoded in that target.
- At the lower address of the newly allocated two-word frame.