Lab 2: ARMv7-A CPSR Mode Switch, Indexing EA, Nibble BIC/ORR & AAPCS32 Frame

30 minfree previewLinux 6.12C11U-Boot 2025.x← module 2

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

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-m02
learner@ksa:~/gl-e01/lab-m02ls -lastarter/Makefilestarter/core.cstarter/core.hstarter/main.clearner@ksa:~/gl-e01/lab-m02
starter: starter/Makefile
learner@ksa: ~/gl-e01/lab-m02
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_demo
starter: starter/core.c
learner@ksa: ~/gl-e01/lab-m02
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
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);    #endif
starter: starter/main.c
learner@ksa: ~/gl-e01/lab-m02
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

  1. Preserve CPSR status, endianness, thumb, and interrupt-mask bits (~0x1FU) when replacing M[4:0] (select_mode) to enter SVC (0x13).
  2. Distinguish pre-indexed (base + offset) from post-indexed (base) memory effective addresses in effective() so load/store models match Cortex-A7 AGU hardware.
  3. Mask oversized 4-bit field inputs ((value & 15U) << 8) after clearing bits [11:8] (~0xF00U) in replace_field().
  4. Enforce full-descending 8-byte-aligned two-word stack pushes (r4 at lower address words[*sp], lr at words[*sp + 1U]) in frame().

step 3/15 · 3. environment requirements

  • Tested Workstation Host: Linux 7.0.0-42-generic (x86_64) executing inside labs/lab_m02_armv7_isa_sim/.
  • Target Architecture Alignment: Models 32-bit ARMv7-A (A32 state) architectural registers (CPSR, r0..r15) and AAPCS32 word-indexed stack memory (words[0..7], 4 bytes 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), GNU make, GNU ar, POSIX /bin/sh, and Binutils (nm, objdump).
  • Hardware: Standard Linux workstation (0 JTAG debuggers or physical Cortex-A7 boards required for the 5-check TAP grader).

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
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), modeling BIC r0, r0, #0x1f followed by ORR r0, r0, #0x13. In tests.c case 1, 0xa00000d0U (N=1, C=1, I=1, F=1, USR=0x10) transitions to 0xa00000d3U (SVC=0x13) with upper 27 bits intact.
  • Seeded Flaw in starter/core.c:6-9 (effective): starter computes return pre ? base : base + offset; -- swapping pre-indexed and post-indexed addressing! On ARMv7-A, post-indexed LDR Rt, [Rn], #4 (pre == false) accesses memory at Rn (base) before writing Rn + 4 back to Rn, whereas pre-indexed LDR Rt, [Rn, #4]! (pre == true) accesses memory at Rn + 4 (base + offset).
  • Verified Repair in files/core.c:6-9: Restores return pre ? base + offset : base;, matching tests.c case 2 (effective(0x1000U, 4U, false) == 0x1000U and effective(0x1000U, 4U, true) == 0x1004U).
  • replace_field & frame (core.c:10-21): replace_field() clears [11:8] with ~UINT32_C(0xf00) and truncates oversized value = 0x32U via (value & 15U) << 8 (0xa5a5f2ffU). frame() enforces *sp >= 2U && *sp <= 8U && (*sp & 1U) == 0U (8-byte alignment), decrements *sp -= 2U, and stores lowest-numbered r4 at words[*sp] and lr (r14) at words[*sp + 1U] matching PUSH {r4, lr} (STMDB sp!, {r4, lr}).

step 7/15 · 7. expected tap-13 output

learner@ksa: ~/gl-e01/lab-m02
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/5

step 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

  1. Unmasked ORR Spill in replace_field(): Remove & 15U in a scratch copy so replace_field() computes (old & ~UINT32_C(0xf00)) | (value << 8) on old = 0x00000000U, value = 0x32U: bit 12 and bit 13 (0x3000U) bleed into adjacent register fields, failing tests.c:18.
  2. Swapped Register-List Order in frame(): Swap words[*sp] = lr; words[*sp + 1U] = r4; and run verify 4: ARMv7-A STMDB sp!, {r4, lr} always places the lowest register number (r4) at the lowest memory address regardless of assembly syntax order, so words[6] == 0x44444444U aborts.
  3. 4-Byte Misaligned Call-Site SP: Remove (*sp & 1U) != 0U in a scratch copy and observe tests.c:26 (sp = 1U, byte offset 4) fail, demonstrating why AAPCS32 rejects 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 p50Host p95Host p99Cortex-A7 @ 528 MHz Hardware Timing
Full sh check.sh (make -B + gcc link + verify 1..4)127.95 ms136.35 ms142.79 msHost build + process spawn overhead
verify 4-case ISA simulator suite (1..4 sequential)3466.4 us4050.7 us4293.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

SymptomRoot CauseFix
not ok 3 (effective fails case 2 at tests.c:14)Ternary returns base for pre == true and base + offset for pre == falseReturn 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 ~0x1fUClear 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 11Mask 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) != 0UValidate *sp >= 2U && *sp <= 8U && (*sp & 1U) == 0U prior to mutating *sp

step 12/15 · 12. guided questions

  1. Why do .data copy loops in ARMv7-A _start overwhelmingly use post-indexed LDR r3, [r0], #4 / STR r3, [r1], #4 rather than pre-indexed [r0, #4]!?
  • *Hint 1:* Linker symbols __data_load (r0) and __data_start (r1) point directly to byte 0 of the section, not 4 bytes below it.
  • *Hint 2:* Trace which address the very first iteration loads under pre = true (r0 + 4, skipping word 0!) versus pre = false (r0, then advancing r0 <- r0 + 4 for iteration 2).
  1. Why does AAPCS32 mandate 8-byte SP alignment ((*sp & 1U) == 0U in 32-bit words) at public function boundaries when ordinary r0..r15 registers are only 4 bytes wide?
  • *Hint 1:* Consider instructions that transfer 64-bit doublewords on the stack (LDRD/STRD, VPUSH/VPOP, and int64_t/uint64_t/double printf varargs).
  • *Hint 2:* What alignment fault fires on Cortex-A7 when LDRD executes against an address that is 4-byte aligned (0x...4) instead of 8-byte aligned (0x...0 or 0x...8)?

step 13/15 · 13. independent challenges

  1. Near Transfer — Legal Cortex-A7 Mode Whitelist (select_mode_checked): Write bool select_mode_checked(uint32_t old, uint32_t mode, uint32_t *out) that accepts only the 9 architectural Cortex-A7 M[4:0] encodings (0x10, 0x11, 0x12, 0x13, 0x16, 0x17, 0x1A, 0x1B, 0x1F) and rejects reserved 5-bit patterns such as 0x00 or 0x14 without altering *out.
  2. Far Transfer — Paired Epilogue unframe() (LDMIA sp!, {r4, pc}): Implement bool unframe(const uint32_t *words, unsigned *sp, uint32_t *r4_out, uint32_t *pc_out) that validates *sp <= 6U && (*sp & 1U) == 0U, pops r4 and pc in full-descending order, increments *sp += 2U, and proves frame followed by unframe is 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], #4 dereferences Rn + 0 on iteration 0 and leaves Rn equal to _edata when the loop terminates; pre-indexed [Rn, #4]! would skip [Rn + 0] unless the pointer were pre-biased by -4.
  • Guided Question 2: AAPCS32 aligns SP to 8 bytes at every public call site so callees can issue 64-bit LDRD/STRD and VFP stack spills without runtime realignment prologues or alignment data aborts.
  • Challenge 1 Bitmask Trick: Since mode & 0x1fU lies in 0..31, test membership in O(1) via const 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
learner@ksa:~/gl-e01/lab-m02./check.shlearner@ksa:~/gl-e01/lab-m02
expected output
TAP version 131..5ok 1 - strict C11 build and trusted grader link

Progressive 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

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:

./check.sh — lab m02
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/5

On an incomplete starter tree, ./check.sh exits non-zero and marks the unmet assertion not ok with an indented YAML diagnostic block:

./check.sh — lab m02 (starter)
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/5

note: 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
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.

Progress is saved on this device.

search — fzf

0/0 ───────────────────────────────────────────

keyboard shortcuts — less

/
search
f
focus mode
[
previous
]
next
?
help
Esc
close

figure