Struct-Mapped MMIO and Auditable SDK Header Adaptation
Replace fragile raw hex casts with compile-time-verified C11 MMIO struct overlays: prove byte offsets with offsetof and _Static_assert, understand why packed structs and C bit-fields break ARMv7-A peripheral buses, and isolate silicon headers from board policy.
What you'll learn
- Verify GPIO struct offsets with offsetof and static assertions.
- Explain why volatile is neither an atomic update nor a CPU memory barrier.
- Adapt register and pin identifiers through a narrow board wrapper without copying opaque policy.
How C Struct Overlays Map Onto Silicon Decode Comparators
In early assembly experiments (m03-l03), poking 0x0209C000 (GPIO1_DR) and 0x0209C004 (GPIO1_GDIR) by raw numeric literals works for five lines—then rapidly turns unmaintainable across seven GPIO registers, CCM clock gates, and SRC status blocks. Firmware engineers replace raw #define pointer arithmetic with struct-mapped Memory-Mapped I/O (MMIO) overlays (KSA_GPIO1->GDIR |= mask;), as shown on the left of Figure 5.3a. Physically, inside the i.MX6ULL AIPS peripheral bus bridge, hardware address comparators decode bits [4:2] of the 32-bit bus transaction relative to 0x0209C000: +0x00 routes to DR, +0x04 to GDIR, +0x08 to read-only PSR, and +0x18 to Write-One-to-Clear (W1C) ISR. If a C struct accidentally omits ICR2 (+0x10), gpio->ISR silently compiles to ldr/str [r0, #0x14]—writing an interrupt acknowledgment mask straight into IMR (+0x14) without a single compiler warning!
Look at the right panel of Figure 5.3a to see why two well-intentioned "defensive" C habits actually break ARMv7-A MMIO hardware:
- Why
__attribute__((packed))breaks32-bit peripheral registers: Addingpackeddropsalignof(struct gpio_regs)from4down to1. Under-ffreestanding/-mno-unaligned-access, the compiler can no longer assume the struct base pointer is4-byte aligned, so it decomposesgpio->DR = valinto four8-bitstrbbyte transactions! Oni.MX6ULLIPS/AIPSperipheral bridges, many32-bit control registers fault or corrupt state on narrow byte accesses. Always use natural4-byte-aligneduint32_tmembers (explicit uint32_t _pad[N]arrays for address gaps) and prove every offset at compile time with_Static_assert(offsetof(...) == ...)! - Why C bit-fields (
uint32_t pin3 : 1;) breakW1Cand bus width: Bit-field bit ordering and storage-unit load width (ldrbvsldr) are implementation-defined inISO C11. Worse,gpio->ISR.pin3 = 1;compiles intoldr r1, [r0, #0x18] -> orr r1, #8 -> str r1, [r0, #0x18]—a read-modify-write on aW1Cstatus register that wipes every concurrent pending interrupt in the bank!
Figure 5.3a. Verified 32-byte struct gpio_regs layout (left) and why packed attributes and C bit-fields fail on ARMv7-A peripheral buses (right).
mental model: A C register struct overlay is a machined drilling jig clamped over an engine block (0x0209C000): if every bushing lines up to the byte (_Static_assert + offsetof), every 32-bit ldr/str hits the intended register; if one member shifts by 4 bytes, you bore through a neighboring register with zero syntax errors.
Where it stops working: Even a millimeter-accurate struct jig constrains only C byte offsets and compiler lvalue caching—it never makes read-modify-write updates atomic, inserts ARMv7-A memory barriers, or replaces hardware rules.
definition (Struct-Mapped Overlay, volatile Semantics & SDK Header Layering): A struct-mapped MMIO overlay binds naturally aligned volatile uint32_t fields (and uint32_t _pad[k] reserved gaps) to documented hardware byte offsets verified at compile time via _Static_assert(offsetof(T, member) == offset, ...). Qualifying members volatile prevents compiler dead-store removal and register caching, without making load -> modify -> store sequences atomic or inserting CPU memory barriers (dsb). Clean SDK header adaptation keeps immutable silicon offsets in an header while isolating carrier-specific pin assignments and active-low polarity inside a narrow board wrapper.
Step through the four-stage workflow for engineering auditable MMIO headers below:
- Step 1. Step 1: Record peripheral base addresses, 32-bit register offsets, reserved gaps, and RW/RO/W1C contracts.
- Step 2. Step 2: Define naturally aligned volatile uint32_t members locked by _Static_assert(offsetof(...)) and sizeof.
- Step 3. Step 3: Mark read-only status volatile const, serialize shared DR RMW, and write pure masks to W1C ISR.
- Step 4. Step 4: Wrap board pin and active-low policy behind a narrow API tracked by GCC -MMD -MP dependencies.
Figure 5.3b. Prove every struct offset with _Static_assert(offsetof(...)), use explicit 32-bit masks, and separate silicon facts from board polarity.
Volatile Lost-Update Proof & Three-Tier SDK Adaptation
Examine Figure 5.3b to separate two distinct boundaries that vendor SDKs routinely blur. In panel 1, watch what happens when main() (Writer A) and an interrupt handler (Writer B) both update a volatile uint32_t DR register on different pins (bit 0 vs bit 1): Writer A loads 0, computes 1, and gets preempted; Writer B loads 0, computes 2, and stores 2; when Writer A resumes (or vice versa, as modeled sequentially in mmio_map_dep_auditor.c), the second stale store overwrites the first, leaving DR == 2 instead of 3! volatile forced the compiler to emit every ldr and str, yet zero atomicity existed across the two instructions. Shared DR banks require single-owner discipline or IRQ masking (cpsid i / spinlock).
In panel 2 of Figure 5.3b, observe how to adapt a vendor header cleanly instead of dumping a 40,000-line SDK header into every .c file:
soc_imx6ull.h: Pure silicon facts (0x0209C000U,0x020C4000U).gpio_regs.h(target_m05_l03below):struct gpio_regswithvolatile const uint32_t PSR(turning accidental writes to read-onlyPSRinto compile errors!),_Static_assertchecks, andgpio_ack_mask()writinggpio->ISR = maskdirectly withoutRMW.board_led.h: Carrier pin (GPIO1_IO03) and active-low policy, exposingled_set(bool on)tomain.c.
Figure 5.3b. Why volatile RMW still loses concurrent updates without serialization (top) and the three-tier SDK adaptation boundary (bottom).
| Register Access Strategy | Emitted ARM Instructions | Offset & Semantic Safety | Engineering Verdict |
|---|---|---|---|
Aligned volatile uint32_t struct + _Static_assert + masks | 32-bit ldr / str | Compile-time offset proof; explicit W1C vs RMW | Production bare-metal standard |
Raw #define REG(a) (*(volatile uint32_t *)(a)) | 32-bit ldr / str | No struct type safety across peripheral blocks | Minimal start stubs only |
C bit-fields (volatile uint32_t isr_3 : 1;) | ldrb/strb or ldr+orr+str | Broken: narrow bus faults + wipes sibling W1C IRQs | Never use on MMIO |
__attribute__((packed)) on 32-bit MMIO struct | 4 x ldrb / 4 x strb | Broken: alignof == 1 splits 32-bit bus cycles | Never pack aligned MMIO |
learner@ksa:~/gl-e01/m05-l03$ bat -H 8 -H 11 -H 12 -H 13 -H 14 -H 18 gpio_regs.h File: gpio_regs.h #ifndef KSA_GPIO_REGS_H #define KSA_GPIO_REGS_H #include <stddef.h> #include <stdint.h> struct gpio_regs { volatile uint32_t DR; volatile uint32_t GDIR; volatile const uint32_t PSR; volatile uint32_t ICR1, ICR2, IMR, ISR, EDGE_SEL; }; _Static_assert(offsetof(struct gpio_regs,GDIR)==0x04U,"GDIR offset"); _Static_assert(offsetof(struct gpio_regs,PSR)==0x08U,"PSR offset"); _Static_assert(offsetof(struct gpio_regs,ISR)==0x18U,"ISR offset"); _Static_assert(sizeof(struct gpio_regs)==0x20U,"GPIO span"); #define KSA_GPIO1 ((struct gpio_regs *)(uintptr_t)0x0209c000U) static inline void gpio_ack_mask(struct gpio_regs *gpio, uint32_t mask) { gpio->ISR = mask; } #endif- Qualify PSR as volatile const uint32_t so hardware reads always execute while accidental C assignments fail to compile.
- Prove GDIR (+0x04), PSR (+0x08), ISR (+0x18), and total 32-byte struct size on every compilation.
- Write mask directly to W1C ISR without reading first so concurrent pending interrupt flags survive.
Proving Offset Geometry, Interleaved RMW Loss & -MMD -MP Guards in C11
In mmio_map_dep_auditor.c below, we verify three interlocking firmware invariants on the host: (1) _Static_assert locks the 32-byte GPIO struct layout; (2) interleaving wa = g.dr; wb = g.dr; wa |= 1U; wb |= 2U; g.dr = wa; g.dr = wb; proves g.dr == 2U (bit 0 lost!) versus serialized 0x80000003U (UINT32_C(1) << 31 safe from signed shift UB); and (3) audit_image_map() + has_mmd_mp_guard() verify .bin/.imx/BootData span equations and -MMD -MP phony header rules so header edits never leave stale .o files behind!
learner@ksa:~/gl-e01/m05-l03$ bat -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 26 -H 27 -H 28 -H 29 -H 30 -H 31 -H 32 mmio_map_dep_auditor.c File: mmio_map_dep_auditor.c #include <assert.h> #include <stdbool.h> #include <stddef.h> #include <stdint.h> #include <stdio.h> #include <string.h> struct gpio_overlay { uint32_t dr, gdir, psr, icr1, icr2, imr, isr, edge_sel; }; _Static_assert(offsetof(struct gpio_overlay, gdir) == 0x04U, "GDIR"); _Static_assert(offsetof(struct gpio_overlay, psr) == 0x08U, "PSR"); _Static_assert(offsetof(struct gpio_overlay, isr) == 0x18U, "ISR"); _Static_assert(sizeof(struct gpio_overlay) == 0x20U, "GPIO span"); static bool audit_image_map(uint32_t entry, uint32_t load_end, uint32_t max_ram, uint32_t *bin_sz, uint32_t *imx_sz, uint32_t *boot_span) { if (load_end <= entry || load_end - entry > max_ram) return false; *bin_sz = load_end - entry; *imx_sz = 0x0c00U + *bin_sz; *boot_span = 0x1000U + *bin_sz; return true; } static bool has_mmd_mp_guard(const char *dep_text, const char *obj, const char *hdr) { char phony[64]; int n = snprintf(phony, sizeof phony, "\n%s:", hdr); if (n <= 0 || (size_t)n >= sizeof phony) return false; return strstr(dep_text, obj) != NULL && strstr(dep_text, hdr) != NULL && strstr(dep_text, phony) != NULL; } int main(void) { struct gpio_overlay g = {0U}; uint32_t wa = g.dr, wb = g.dr; wa |= 1U; wb |= 2U; g.dr = wa; g.dr = wb; assert(g.dr == 2U); /* interleaved RMW loses bit 0 */ g.dr = 0U; g.dr |= 1U; g.dr |= 2U; g.dr |= (UINT32_C(1) << 31); assert(g.dr == 0x80000003U); uint32_t bin = 0U, imx = 0U, span = 0U; assert(audit_image_map(0x87800000U, 0x87800098U, 0x100000U, &bin, &imx, &span)); assert(bin == 152U && imx == 3224U && span == 4248U); assert(!audit_image_map(0x87800000U, 0x87800000U, 0x100000U, &bin, &imx, &span)); const char *good_d = "obj/led.o: bsp/led.c include/gpio_regs.h\ninclude/gpio_regs.h:\n"; const char *no_mp = "obj/led.o: bsp/led.c include/gpio_regs.h\n"; assert(has_mmd_mp_guard(good_d, "obj/led.o:", "include/gpio_regs.h")); assert(!has_mmd_mp_guard(no_mp, "obj/led.o:", "include/gpio_regs.h")); printf("gpio=%zuB ISR=+%zu lost=2 ser=0x%08X bin=%uB imx=%uB mp=ok\n", sizeof g, offsetof(struct gpio_overlay, isr), g.dr, bin, imx); return 0; }- Lock every 32-bit GPIO register offset at compile time via _Static_assert and offsetof.
- Verify .bin, compact .imx (+0x0C00), and Boot Data (+0x1000) spans from symbol-map addresses.
- Confirm GCC -MMD -MP output contains both the object target rule and the phony header: target.
Cross-Checking Struct Layout on Both Host GCC & Target ARMv7-A Clang
Run the host verifier and cross-compile gpio_regs.h directly with clang --target=armv7a-none-eabi ... -x c -c gpio_regs.h! Compiling a header standalone as a translation unit forces the 32-bit ARM EABI front-end to check #ifndef guards, self-contained #includes, and every _Static_assert under the exact target data model (ILP32).
learner@ksa:~/gl-e01/m05-l03gcc -std=c11 -Wall -Wextra -Werror -pedantic -MMD -MP mmio_map_dep_auditor.c -o mmio_map_dep_auditorlearner@ksa:~/gl-e01/m05-l03./mmio_map_dep_auditorgpio=32B ISR=+24 lost=2 ser=0x80000003 bin=152B imx=3224B mp=oklearner@ksa:~/gl-e01/m05-l03clang --target=armv7a-none-eabi -mcpu=cortex-a7 -marm -mfloat-abi=soft -ffreestanding -std=c11 -Wall -Wextra -Werror -Wno-unused-function -x c -c gpio_regs.h -o target.olearner@ksa:~/gl-e01/m05-l03learner@ksa:~/gl-e01/m05-l03strace -e trace=write,exit_group \./mmio_map_dep_auditorwrite(1, "gpio=32B ISR=+24 lost=2 ser=0x80"..., 64) = 64exit_group(0) = ?+++ exited with 0 +++From Bare-Metal Physical Casts to Linux 6.12 ioremap() & Modular BSPs
Keep two architectural horizons clear as your codebase grows. First, #define KSA_GPIO1 ((struct gpio_regs *)(uintptr_t)0x0209c000U) works in bare-metal GL-E01 only while SCTLR.M == 0 (flat physical addressing) or under an identity MT_DEVICE MMU map; once the Linux kernel boots with virtual memory active (GL-E04), drivers replace raw physical casts with devm_ioremap_resource() + readl()/writel() (or gpiod consumer descriptors). Second, now that we have clean, assertion-locked peripheral headers, how do we scale from single-file programs to a multi-directory bare-metal Board Support Package without header spaghetti or stale incremental builds? Later: Module m06 (m06-l01) builds that complete modular BSP and Makefile graph.
Common Production Pitfalls
warning: Symptom: Annotating struct gpio_regs with __attribute__((packed)) causes freestanding Cortex-A7 builds (-mno-unaligned-access) to trigger Data Aborts or corrupt peripheral state whenever writing gpio->DR. Root Cause: packed sets alignof(struct gpio_regs) == 1, forcing the compiler to assume misaligned pointers and emit four 8-bit strb instructions instead of a single 32-bit str across the AIPS bus. Fix: Remove packed from aligned 32-bit MMIO structs, pad reserved gaps explicitly with volatile uint32_t _pad[N], and verify offsets with _Static_assert(offsetof(...)).
warning: Symptom: Modeling GPIO1_ISR (+0x18) as a 32-bit C bit-field union and executing gpio->ISR_bits.pin18 = 1U; silently drops simultaneous interrupts on sibling pins in GPIO1. Root Cause: Bit-field assignment compiles to ldr + orr + str (RMW), replaying 1s onto every already-set bit in the W1C status register and clearing unhandled interrupts! Fix: Keep volatile uint32_t ISR; as an undivided 32-bit word and write (UINT32_C(1) << pin) directly via gpio_ack_mask().
Practice & Retrieval
Guided Practice: Sizing Reserved Gap Arrays for CCM (0x020C4000)
Design a sparse struct ccm_slice overlay without packed covering CCSR (+0x0C), CACRR (+0x10), and CCGR[7] (+0x68..+0x80). Step 1 (Compute Gaps): Before +0x0C lie 0x0C / 4 = 3 words (volatile uint32_t _pad0[3];); between CACRR end (+0x14) and CCGR[0] (+0x68) lie (0x68 - 0x14) / 4 = 0x54 / 4 = 21 words (volatile uint32_t _pad1[21];). Step 2 (Prove Layout): Write _Static_assert(offsetof(struct ccm_slice, CCGR[0]) == 0x68U, "CCGR0"); and _Static_assert(sizeof(struct ccm_slice) == 0x84U, "CCM size");.
Independent Practice: Multi-Peripheral Header Suite (soc_headers_audit.c)
Author a self-contained soc_headers_audit.c defining assertion-locked overlays for GPIO (0x20 B), CCM (0x84 B), and SRC (0x20 B with SCR +0x00, SBMR1 +0x04, _pad[5], SBMR2 +0x1C), asserting alignof(T) == 4U on all three structs and separating silicon offsets from board-level LED/KEY pin macros.
→ open standalone lab workbench
1. Motivation
Freestanding C firmware crashes before main() -- or corrupts the bottom word of an adjacent stack/heap -- when _start zeroes [__bss_start, __bss_end] with an inclusive <= comparison instead of the half-open linker interval [__bss_start, __bss_end), when ALIGN(8) address rounding overflows uint32_t near 0xFFFFFFFF, or when a careless edit to a peripheral struct shifts GPIOx_ISR off byte +0x18. In this laboratory, you will diagnose an off-by-one .bss overrun inside starter/core.c, verify compile-time _Static_assert register offsets in struct gpio_model, and prove overflow-safe alignment and masked data updates under TAP version 13.
2. Learning Objectives
- Verify
32-byteGPIOperipheral struct layout (psrat+8,israt+24,sizeof == 32) at compile time using_Static_assertandoffsetof. - Round addresses upward to power-of-two boundaries in
align_address()while rejecting0, non-powers-of-two (3), and inputs exceedingUINT32_MAX - (alignment - 1U). - Repair
init_runtime()so.datarelocation (memcpy) and.bssclearing (for (size_t i = bss_begin; i < bss_end; ++i)) honor half-open intervals, reject.data/.bssoverlap, and leave surrounding sentinels untouched. - Apply arbitrary multi-bit masks cleanly in
data_update()via(old & ~mask) | (value & mask).
3. Environment Requirements
- Tested Workstation Host:
Linux 7.0.0-42-generic(x86_64) insidelabs/lab_m05_lds_crt_sdk/. - Target Runtime Contract: Models GNU
ldsection bounds (__data_start,__bss_start,__bss_end),ARMv7-A4/8-byte address alignment, andi.MX6ULLGPIO0x00..0x1Cregister offsets.
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 (
0physical target hardware required forTAPverification).
5. Complete Executable Commands
Run the commands below from labs/lab_m05_lds_crt_sdk/ to reproduce starter/ failing check 3, catch starter/'s out-of-bounds write with AddressSanitizer (ASan), build files/libbsp.a, and verify 5/5 TAP checks:
learner@ksa:~/gl-e01/m05-l03$ bat script.sh File: script.sh # 1. Run check.sh against starter/ in a disposable temp folder 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 starter/ with AddressSanitizer (-fsanitize=address) on cases 2 and 3 to expose both OOB bugs TMP=$(mktemp -d) && gcc -std=c11 -Wall -Wextra -Werror -pedantic -fsanitize=address -g -Istarter tests.c starter/core.c -o "$TMP/crt" && { "$TMP/crt" 2 || echo "case 2 sentinel clobbered (rc=$?)"; "$TMP/crt" 3 || echo "case 3 ASan stack-buffer-overflow (rc=$?)"; } ; rm -rf "$TMP" # 3. Build files/libbsp.a and verify exported C-runtime and SDK symbols make -B -C files nm -g --defined-only files/libbsp.a # 4. Execute the authoritative 5-check TAP version 13 harness sh check.sh*Why each step runs:* Step 1 reproduces not ok 3 without touching files/; Step 2 reveals a critical bonus insight -- under -fsanitize=address, starter/ not only clobbers ram[40] in case 2 (rc=134) but also commits a 1-byte stack buffer overflow (ram[64] = 0U on unsigned char ram[64]) in case 3 (init_runtime(ram, 64U, data, 0U, 64U, 64U, 64U))!; Step 3 builds files/libbsp.a; and Step 4 confirms # pass 5/5.
6. Annotated Source Code (starter/core.c Defect vs files/core.c Fix)
struct gpio_model(core.h:6,tests.c:5-7): Declares eightuint32_tregisters (dr,gdir,psr,icr1,icr2,imr,isr,edge);tests.cenforcesoffsetof(psr) == 8U,offsetof(isr) == 24U, andsizeof == 32Uat compile time beforemain()even links.align_address(core.c:3-9): Rejectsalignment == 0U || (alignment & (alignment - 1U)) != 0U, checksvalue > UINT32_MAX - add(add = alignment - 1U) soUINT32_MAXaligned to8Ufails without overwriting*out = 0x55U, and computes(value + add) & ~add.- Seeded Flaw in
starter/core.c:17(init_runtime):starterloopsfor (size_t i = bss_begin; i <= bss_end; ++i) ram[i] = 0U;. In GNUldscripts (.bss : { __bss_start = .; *(.bss*) __bss_end = .; }),__bss_endis the first byte after.bss: when.bssis[24, 40),ram[40]belongs to the next section (or lies1byte pastram[63]whenbss_begin == bss_end == 64!). - Verified Repair in
files/core.c:10-19: Validates bounds (data_at <= size,data_size <= size - data_at,bss_begin <= bss_end <= size), rejects non-empty.dataoverlapping non-empty.bss(data_at < bss_end && bss_begin < data_at + data_size), guardsif (data_size != 0U) memcpy(...), and zeroes strictlyfor (size_t i = bss_begin; i < bss_end; ++i).
7. Expected TAP-13 Output
learner@ksa:~/gl-e01/m05-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 - aligns valid addresses and rejects overflow or non-power-of-two requests not ok 3 - copies data and clears only the exclusive BSS interval --- 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 - handles empty ranges and rejects invalid geometry without modification ok 5 - proves GPIO offsets and preserves neighboring output bits # 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 - aligns valid addresses and rejects overflow or non-power-of-two requests ok 3 - copies data and clears only the exclusive BSS interval ok 4 - handles empty ranges and rejects invalid geometry without modification ok 5 - proves GPIO offsets and preserves neighboring output bits # pass 5/58. Explanation of Observed Behavior
In tests.c case 2, ram[0..63] is filled with sentinel 0xa5U, 4 bytes of .data ({1, 2, 3, 4}) are copied into ram[8..11], and .bss spans [24, 40) (16 bytes: indices 24..39). Because starter/core.c uses i <= bss_end, iteration i = 40U writes 0U into ram[40], tripping assert(... && ram[40] == 0xa5U) at tests.c:23 (not ok 3). Even more subtly, without ASan, tests.c case 3 appeared to pass (ok 4) on starter/ only because ram[64] = 0U overwrote unasserted stack padding outside ram[0..63]! Repairing i < bss_end eliminates both the sentinel overwrite and the latent undefined behavior (# pass 5/5, ASan-clean).
9. Experiment Variations
- Unchecked
memcpyon Zero-Length.dataat End of RAM: Passdata = NULL, data_size = 0Uin a scratch test after removingif (data_size != 0U)beforememcpy(ram + data_at, data, data_size)under-fsanitize=undefined: ISO C11 Section 7.24.1p2 forbidsNULLpointers inmemcpyeven when the byte count is zero! - Struct Member Insertion Caught at Compile Time: Insert
uint32_t pad;betweenpsrandicr1in a scratch copy ofcore.hand runsh check.sh: check1fails immediately at compile time on_Static_assert(offsetof(struct gpio_model, isr) == 24U, "ISR"). - Unmasked
valueindata_update(): Rewritedata_update()as(old & ~mask) | valueand runverify 4:data_update(0U, 0x80000000U, 0xffffffffU)returns0xffffffffUinstead of0x80000000U.
10. Performance Measurements
Measured on Linux 7.0.0-42-generic (x86_64) via CLOCK_MONOTONIC (5 warmup runs, 35 timed iterations):
Workload Measured (N = 35, warmup = 5) | Host p50 | Host p95 | Host p99 | Cortex-A7 @ 528 MHz Startup Cost |
|---|---|---|---|---|
Full sh check.sh (make -B + gcc link + 4 cases) | 143.25 ms | 157.56 ms | 165.52 ms | Host compile + archive + test execution |
verify 4-case runtime/SDK suite (verify 1..4) | 3524.5 us | 4305.9 us | 4863.4 us | < 2 us in-memory .data/.bss simulation |
Zeroing 64 KiB .bss (16,384 32-bit STR words) | ~4 us (L1/L2) | ~7 us | ~9 us | ~95 - 180 us in OCRAM/DDR3 before I/D caches enable |
11. Troubleshooting
| Symptom | Root Cause | Fix | ||
|---|---|---|---|---|
not ok 3 (ram[40] is 0U instead of 0xa5U) | .bss loop used inclusive i <= bss_end | Loop over half-open for (size_t i = bss_begin; i < bss_end; ++i) | ||
not ok 2 (align_address(1U, 3U, &out) returns true) | Missing power-of-two bit test (alignment & (alignment - 1U)) == 0U | Reject `alignment == 0U \ | \ | (alignment & (alignment - 1U)) != 0U` |
not ok 2 (align_address(UINT32_MAX, 8U, &out) wraps to 0U) | Computed (value + add) & ~add before checking value > UINT32_MAX - add | Guard if (value > UINT32_MAX - add) return false; before modifying *out | ||
not ok 4 (data and bss overlap accepted when data_size > 0) | Omitted half-open interval intersection test [data_at, data_end) vs [bss_begin, bss_end) | Reject when data_size != 0U && bss_begin < bss_end && data_at < bss_end && bss_begin < data_at + data_size |
12. Guided Questions
- Why does
(alignment & (alignment - 1U)) == 0U(combined withalignment != 0U) identify powers of two across all32-bit unsigned integers inO(1)time?
- *Hint 1:* Write the binary representation of
2^k(0b001000) and2^k - 1(0b000111). - *Hint 2:* What happens to the highest set bit of any composite number
n = 2^k + m(0 < m < 2^k, e.g.,6 = 0b0110,5 = 0b0101) when bitwise-ANDed withn - 1?
- Why does an
ARMv7-A_startassembly loop (cmp r0, r1/blo 1bwithstr r2, [r0], #4) require. = ALIGN(4);on both__bss_startand__bss_endin the linker script?
- *Hint 1:* Suppose
.bssends with a singlechar flag;so__bss_end - __bss_start == 5bytes (__bss_end = 0x87810005). - *Hint 2:* Trace
r0stepping by+4(0x87810000 -> 0x87810004 -> 0x87810008) underblo: how many bytes past0x87810005get zeroed on the second4-byteSTR?
13. Independent Challenges
- Near Transfer — Word-Wide
init_runtime_aligned32(): Write a stricter startup verifier requiringdata_at,data_size,bss_begin, andbss_endto be multiples of4U(just like a4-byteLDR/STR_startloop), performing4-byte chunk operations and rejecting unaligned linker symbols cleanly. - Far Transfer — Full
.text+.rodata+.data(LMA != VMA) +.bss+IRQ/SVCStack Solver: Implementbool solve_lds_layout(...)that computes_etext,__data_load(LMA),__data_start.._edata(VMA),[__bss_start, __bss_end), and8-byte-alignedIRQ/SVCstack tops inside[ram_base, ram_base + ram_size), rejecting stack-into-.bsscollisions.
14. Solutions & Explanations
- Guided Question 1: An exact power of two has a single
1bit (2^k), and subtracting1clears bitkand sets bits0..k-1, yielding zero bit overlap (& == 0); any number with two or more1bits retains its most-significant1bit inn - 1, son & (n - 1)is non-zero. - Guided Question 2: Stepping
4bytes perSTRwhiler0 < __bss_endwhen__bss_endis unaligned (+5) executes at+0and+4, writing bytes+4..+7(3bytes past__bss_end!); aligning__bss_end = ALIGN(4)reserves those3tail padding bytes explicitly inside.bss. - Challenge 1 Alignment Check: Guard
if (((data_at | data_size | bss_begin | bss_end) & 3U) != 0U) return false;before delegating to the bounds and overlap checks.
Run locally in your terminal and check off each verification milestone.
Not started
Key takeaways
- Every member of a struct-mapped
MMIOoverlay must sit at its exact documented peripheral byte offset, proven at compile time withoffsetofand_Static_assert(never__attribute__((packed))). volatileprevents compiler load/store removal and merging, yet provides neither atomic read-modify-write execution norARMv7-ACPU memory barriers.- Explicit
32-bit unsigned masks avoid implementation-defined C bit-field ordering, narrow byte loads (ldrb/strb), and accidentalRMWonW1Cstatus registers (gpio->ISR = mask). - Clean SDK adaptation keeps silicon base addresses and register structs separate from carrier-board pin assignments and active-low polarity wrappers.
- A struct-mapped register header must place every member at the peripheral's exact documented byte offset.
- Volatile-qualified accesses constrain compiler treatment but do not make a read-modify-write atomic.
- Assign the acknowledgment mask directly to the ISR member.