Lab 2: ARMv7-A CPSR Mode Switch, Indexing EA, Nibble BIC/ORR & AAPCS32 Frame
Implement, compile, and verify lab_m02_armv7_isa_sim against ./check.sh.
Prerequisites in this module
What ./check.sh verifies
- Strict C11 build and trusted grader link.
- Repair the C11 build before testing behavior.
- Preserves CPSR fields while selecting a legal ordinary mode.
- Distinguishes pre-indexed and post-indexed access addresses.
step 1/15 · inspect starter files and specification
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.
learner@ksa:~/gl-e01/lab-m02ls -lastarter/Makefilestarter/core.cstarter/core.hstarter/main.clearner@ksa:~/gl-e01/lab-m02starter: starter/Makefile
learner@ksa:~/gl-e01/lab-m02$ bat starter/Makefile File: starter/Makefile CC = gcc AR = ar override CFLAGS += -std=c11 -Wall -Wextra -Werror -pedantic -MMD -MP all: libbsp.a bsp_demo libbsp.a: core.o $(AR) rcs $@ $^ bsp_demo: main.o libbsp.a $(CC) $(CFLAGS) main.o libbsp.a -o $@ %.o: %.c core.h $(CC) $(CFLAGS) -c $< -o $@ -include core.d main.d .PHONY: all clean clean: rm -f core.o main.o core.d main.d libbsp.a bsp_demostarter: starter/core.c
learner@ksa:~/gl-e01/lab-m02$ bat starter/core.c File: starter/core.c #include "core.h" uint32_t select_mode(uint32_t old, uint32_t mode) { return (old & ~UINT32_C(0x1f)) | (mode & 0x1fU); } uint32_t effective(uint32_t base, uint32_t offset, bool pre) { return pre ? base : base + offset; } uint32_t replace_field(uint32_t old, uint32_t value) { return (old & ~UINT32_C(0xf00)) | ((value & 15U) << 8); } bool frame(uint32_t *words, unsigned *sp, uint32_t r4, uint32_t lr) { if (*sp < 2U || *sp > 8U || (*sp & 1U) != 0U) return false; *sp -= 2U; words[*sp] = r4; words[*sp + 1U] = lr; return true; }starter: starter/core.h
learner@ksa:~/gl-e01/lab-m02$ bat starter/core.h File: starter/core.h #ifndef GL_E01_CORE_H #define GL_E01_CORE_H #include <stdbool.h> #include <stdint.h> uint32_t select_mode(uint32_t old, uint32_t mode); uint32_t effective(uint32_t base, uint32_t offset, bool pre); uint32_t replace_field(uint32_t old, uint32_t value); bool frame(uint32_t *words, unsigned *sp, uint32_t r4, uint32_t lr); #endifstarter: starter/main.c
learner@ksa:~/gl-e01/lab-m02$ bat starter/main.c File: starter/main.c #include "core.h" #include <stdio.h> int main(void) { puts("GL-E01 BSP laboratory: run ../check.sh for graded evidence"); return 0; }step 2/15 · 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().
step 3/15 · 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).
step 4/15 · 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).
step 5/15 · 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/lab-m02$ 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.
step 6/15 · 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}).
step 7/15 · 7. expected tap-13 output
learner@ksa:~/gl-e01/lab-m02$ 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/5step 8/15 · 8. 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.
step 9/15 · 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.
step 10/15 · 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) |
step 11/15 · 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 |
step 12/15 · 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)?
step 13/15 · 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).
step 14/15 · 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.
step 15/15 · run verification and inspect output
Run the verification command and confirm the output matches the expected contract.
learner@ksa:~/gl-e01/lab-m02./check.shlearner@ksa:~/gl-e01/lab-m02TAP version 131..5ok 1 - strict C11 build and trusted grader linkProgressive hints & solution
hint 1
Compare starter/Makefile against the module lessons. Focus first on: Strict C11 build and trusted grader link.
hint 2
Compile with -std=c11 -Wall -Wextra -Werror, check every system-call return value before touching output buffers, and verify cleanup on error paths.
solution
warning: Reveal the reference solution files? Running ./check.sh against your own attempt first builds stronger retention.
solution: files/Makefile
learner@ksa:~/gl-e01/lab-m02$ bat files/Makefile File: files/Makefile CC = gcc AR = ar override CFLAGS += -std=c11 -Wall -Wextra -Werror -pedantic -MMD -MP all: libbsp.a bsp_demo libbsp.a: core.o $(AR) rcs $@ $^ bsp_demo: main.o libbsp.a $(CC) $(CFLAGS) main.o libbsp.a -o $@ %.o: %.c core.h $(CC) $(CFLAGS) -c $< -o $@ -include core.d main.d .PHONY: all clean clean: rm -f core.o main.o core.d main.d libbsp.a bsp_demosolution: files/core.c
learner@ksa:~/gl-e01/lab-m02$ bat files/core.c File: files/core.c #include "core.h" uint32_t select_mode(uint32_t old, uint32_t mode) { return (old & ~UINT32_C(0x1f)) | (mode & 0x1fU); } uint32_t effective(uint32_t base, uint32_t offset, bool pre) { return pre ? base + offset : base; } uint32_t replace_field(uint32_t old, uint32_t value) { return (old & ~UINT32_C(0xf00)) | ((value & 15U) << 8); } bool frame(uint32_t *words, unsigned *sp, uint32_t r4, uint32_t lr) { if (*sp < 2U || *sp > 8U || (*sp & 1U) != 0U) return false; *sp -= 2U; words[*sp] = r4; words[*sp + 1U] = lr; return true; }solution: files/core.d
learner@ksa:~/gl-e01/lab-m02$ bat files/core.d File: files/core.d core.o: core.c core.h core.h:solution: files/core.h
learner@ksa:~/gl-e01/lab-m02$ bat files/core.h File: files/core.h #ifndef GL_E01_CORE_H #define GL_E01_CORE_H #include <stdbool.h> #include <stdint.h> uint32_t select_mode(uint32_t old, uint32_t mode); uint32_t effective(uint32_t base, uint32_t offset, bool pre); uint32_t replace_field(uint32_t old, uint32_t value); bool frame(uint32_t *words, unsigned *sp, uint32_t r4, uint32_t lr); #endifsolution: files/main.c
learner@ksa:~/gl-e01/lab-m02$ bat files/main.c File: files/main.c #include "core.h" #include <stdio.h> int main(void) { puts("GL-E01 BSP laboratory: run ../check.sh for graded evidence"); return 0; }solution: files/main.d
learner@ksa:~/gl-e01/lab-m02$ bat files/main.d File: files/main.d main.o: main.c core.h core.h:Run the check
From labs/lab_m02_armv7_isa_sim/, run ./check.sh. A complete solution emits TAP version 13 with every test point marked ok and exits 0:
learner@ksa:~/gl-e01/lab-m02./check.shTAP version 131..5ok 1 - strict C11 build and trusted grader linkok 2 - preserves CPSR fields while selecting a legal ordinary modeok 3 - distinguishes pre-indexed and post-indexed access addressesok 4 - replaces only the selected field and masks oversized valuesok 5 - saves and restores a full-descending aligned register pair# pass 5/5On an incomplete starter tree, ./check.sh exits non-zero and marks the unmet assertion not ok with an indented YAML diagnostic block:
learner@ksa:~/gl-e01/lab-m02./check.shTAP version 131..5ok 1 - strict C11 build and trusted grader linkok 2 - preserves CPSR fields while selecting a legal ordinary modenot 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 valuesok 5 - saves and restores a full-descending aligned register pair# pass 4/5note: How to read TAP diagnostics: 1..N states the total test plan; each ok k confirms a passed check; not ok k pinpoints the failing check alongside message: (what went wrong) and hint: (where to look next) between --- and ....
inspect harness: check.sh
learner@ksa:~/gl-e01/lab-m02$ bat check.sh File: check.sh #!/bin/sh set -u cd "$(dirname "$0")" || exit 1 PASS=0 WORK=$(mktemp -d "./.check.XXXXXX") || exit 1 trap 'rm -rf "$WORK"' EXIT HUP INT TERM printf 'TAP version 13\n1..5\n' if make -B -C files >"$WORK/build.log" 2>&1 && gcc -std=c11 -Wall -Wextra -Werror -pedantic -Ifiles tests.c files/libbsp.a -o "$WORK/verify" >>"$WORK/build.log" 2>&1; then printf 'ok 1 - strict C11 build and trusted grader link\n' PASS=$((PASS + 1)) else printf 'not ok 1 - strict C11 build and trusted grader link\n' printf " ---\n message: 'Compilation failed'\n hint: 'Fix the C11 diagnostics in files and preserve the exported ABI'\n ...\n" printf 'FAIL: repair the C11 build before testing behavior\n' >&2 fi if [ -x "$WORK/verify" ] && "$WORK/verify" 1 >"$WORK/case2.log" 2>&1; then printf 'ok 2 - preserves CPSR fields while selecting a legal ordinary mode\n' PASS=$((PASS + 1)) else printf 'not ok 2 - preserves CPSR fields while selecting a legal ordinary mode\n' printf " ---\n message: 'Behavior differs from the independently specified test vectors'\n hint: 'Repair case 1; inspect tests.c for the exact input and expected result'\n ...\n" fi if [ -x "$WORK/verify" ] && "$WORK/verify" 2 >"$WORK/case3.log" 2>&1; then printf 'ok 3 - distinguishes pre-indexed and post-indexed access addresses\n' PASS=$((PASS + 1)) else printf 'not ok 3 - distinguishes pre-indexed and post-indexed access addresses\n' printf " ---\n message: 'Behavior differs from the independently specified test vectors'\n hint: 'Repair case 2; inspect tests.c for the exact input and expected result'\n ...\n" fi if [ -x "$WORK/verify" ] && "$WORK/verify" 3 >"$WORK/case4.log" 2>&1; then printf 'ok 4 - replaces only the selected field and masks oversized values\n' PASS=$((PASS + 1)) else printf 'not ok 4 - replaces only the selected field and masks oversized values\n' printf " ---\n message: 'Behavior differs from the independently specified test vectors'\n hint: 'Repair case 3; inspect tests.c for the exact input and expected result'\n ...\n" fi if [ -x "$WORK/verify" ] && "$WORK/verify" 4 >"$WORK/case5.log" 2>&1; then printf 'ok 5 - saves and restores a full-descending aligned register pair\n' PASS=$((PASS + 1)) else printf 'not ok 5 - saves and restores a full-descending aligned register pair\n' printf " ---\n message: 'Behavior differs from the independently specified test vectors'\n hint: 'Repair case 4; inspect tests.c for the exact input and expected result'\n ...\n" fi printf '# pass %d/5\n' "$PASS" [ "$PASS" -eq 5 ]Definition of done
Verification checklist
status: 0/3 checks verified
Troubleshooting
Compiler fails under -Werror on sign conversion or unused args
Use exact POSIX return types (ssize_t for read()/write(), size_t for byte counts) rather than relaxing flags.
./check.sh reports missing files in files/
Invoke ./check.sh from inside labs/lab_m02_armv7_isa_sim/ so relative paths to files/ resolve directly.