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.

20 minfree previewLinux 6.12C11U-Boot 2025.x→ module 5 lab
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:

  1. Why __attribute__((packed)) breaks 32-bit peripheral registers: Adding packed drops alignof(struct gpio_regs) from 4 down to 1. Under -ffreestanding / -mno-unaligned-access, the compiler can no longer assume the struct base pointer is 4-byte aligned, so it decomposes gpio->DR = val into four 8-bit strb byte transactions! On i.MX6ULL IPS/AIPS peripheral bridges, many 32-bit control registers fault or corrupt state on narrow byte accesses. Always use natural 4-byte-aligned uint32_t members (explicit uint32_t _pad[N] arrays for address gaps) and prove every offset at compile time with _Static_assert(offsetof(...) == ...)!
  2. Why C bit-fields (uint32_t pin3 : 1;) break W1C and bus width: Bit-field bit ordering and storage-unit load width (ldrb vs ldr) are implementation-defined in ISO C11. Worse, gpio->ISR.pin3 = 1; compiles into ldr r1, [r0, #0x18] -> orr r1, #8 -> str r1, [r0, #0x18]—a read-modify-write on a W1C status register that wipes every concurrent pending interrupt in the bank!
fig_m05_l03_a.svg — Verified 32-byte struct gpio_regs layout (left) and why…

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:

ast_m05_l03.svg — Prove every struct offset with…step 1/4
  1. Step 1. Step 1: Record peripheral base addresses, 32-bit register offsets, reserved gaps, and RW/RO/W1C contracts.
  2. Step 2. Step 2: Define naturally aligned volatile uint32_t members locked by _Static_assert(offsetof(...)) and sizeof.
  3. Step 3. Step 3: Mark read-only status volatile const, serialize shared DR RMW, and write pure masks to W1C ISR.
  4. 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:

  1. soc_imx6ull.h: Pure silicon facts (0x0209C000U, 0x020C4000U).
  2. gpio_regs.h (target_m05_l03 below): struct gpio_regs with volatile const uint32_t PSR (turning accidental writes to read-only PSR into compile errors!), _Static_assert checks, and gpio_ack_mask() writing gpio->ISR = mask directly without RMW.
  3. board_led.h: Carrier pin (GPIO1_IO03) and active-low policy, exposing led_set(bool on) to main.c.
fig_m05_l03_b.svg — Why volatile RMW still loses concurrent updates without…

Figure 5.3b. Why volatile RMW still loses concurrent updates without serialization (top) and the three-tier SDK adaptation boundary (bottom).

Register Access StrategyEmitted ARM InstructionsOffset & Semantic SafetyEngineering Verdict
Aligned volatile uint32_t struct + _Static_assert + masks32-bit ldr / strCompile-time offset proof; explicit W1C vs RMWProduction bare-metal standard
Raw #define REG(a) (*(volatile uint32_t *)(a))32-bit ldr / strNo struct type safety across peripheral blocksMinimal start stubs only
C bit-fields (volatile uint32_t isr_3 : 1;)ldrb/strb or ldr+orr+strBroken: narrow bus faults + wipes sibling W1C IRQsNever use on MMIO
__attribute__((packed)) on 32-bit MMIO struct4 x ldrb / 4 x strbBroken: alignof == 1 splits 32-bit bus cyclesNever pack aligned MMIO
learner@ksa: ~/gl-e01/m05-l03
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
  1. Qualify PSR as volatile const uint32_t so hardware reads always execute while accidental C assignments fail to compile.
  2. Prove GDIR (+0x04), PSR (+0x08), ISR (+0x18), and total 32-byte struct size on every compilation.
  3. 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
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;    }
  1. Lock every 32-bit GPIO register offset at compile time via _Static_assert and offsetof.
  2. Verify .bin, compact .imx (+0x0C00), and Boot Data (+0x1000) spans from symbol-map addresses.
  3. 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-l03
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-l03
strace — learner@ksa: ~/gl-e01/m05-l03
learner@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.

quiz · 1 of 3

During SDK header adaptation, a missing reserved word shifts ISR inside struct gpio_regs to byte offset 0x14 instead of 0x18. What catches that defect deterministically at compile time?

quiz · 2 of 3

Why does updating gpio->DR |= (1U << 3); on a volatile uint32_t DR member still require exclusive bank ownership or interrupt masking?

quiz · 3 of 3

Retrieval: how must a struct-based inline helper acknowledge pending interrupt mask inside the Write-One-to-Clear (W1C) ISR member?

Lab 5: Linker Alignment, Exclusive .bss C-Runtime Init & GPIO Struct Geometry

env: host

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

  1. Verify 32-byte GPIO peripheral struct layout (psr at +8, isr at +24, sizeof == 32) at compile time using _Static_assert and offsetof.
  2. Round addresses upward to power-of-two boundaries in align_address() while rejecting 0, non-powers-of-two (3), and inputs exceeding UINT32_MAX - (alignment - 1U).
  3. Repair init_runtime() so .data relocation (memcpy) and .bss clearing (for (size_t i = bss_begin; i < bss_end; ++i)) honor half-open intervals, reject .data/.bss overlap, and leave surrounding sentinels untouched.
  4. 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) inside labs/lab_m05_lds_crt_sdk/.
  • Target Runtime Contract: Models GNU ld section bounds (__data_start, __bss_start, __bss_end), ARMv7-A 4/8-byte address alignment, and i.MX6ULL GPIO 0x00..0x1C register offsets.

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 physical target hardware required for TAP verification).

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
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 eight uint32_t registers (dr, gdir, psr, icr1, icr2, imr, isr, edge); tests.c enforces offsetof(psr) == 8U, offsetof(isr) == 24U, and sizeof == 32U at compile time before main() even links.
  • align_address (core.c:3-9): Rejects alignment == 0U || (alignment & (alignment - 1U)) != 0U, checks value > UINT32_MAX - add (add = alignment - 1U) so UINT32_MAX aligned to 8U fails without overwriting *out = 0x55U, and computes (value + add) & ~add.
  • Seeded Flaw in starter/core.c:17 (init_runtime): starter loops for (size_t i = bss_begin; i <= bss_end; ++i) ram[i] = 0U;. In GNU ld scripts (.bss : { __bss_start = .; *(.bss*) __bss_end = .; }), __bss_end is the first byte after .bss: when .bss is [24, 40), ram[40] belongs to the next section (or lies 1 byte past ram[63] when bss_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 .data overlapping non-empty .bss (data_at < bss_end && bss_begin < data_at + data_size), guards if (data_size != 0U) memcpy(...), and zeroes strictly for (size_t i = bss_begin; i < bss_end; ++i).

7. Expected TAP-13 Output

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

8. 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

  1. Unchecked memcpy on Zero-Length .data at End of RAM: Pass data = NULL, data_size = 0U in a scratch test after removing if (data_size != 0U) before memcpy(ram + data_at, data, data_size) under -fsanitize=undefined: ISO C11 Section 7.24.1p2 forbids NULL pointers in memcpy even when the byte count is zero!
  2. Struct Member Insertion Caught at Compile Time: Insert uint32_t pad; between psr and icr1 in a scratch copy of core.h and run sh check.sh: check 1 fails immediately at compile time on _Static_assert(offsetof(struct gpio_model, isr) == 24U, "ISR").
  3. Unmasked value in data_update(): Rewrite data_update() as (old & ~mask) | value and run verify 4: data_update(0U, 0x80000000U, 0xffffffffU) returns 0xffffffffU instead of 0x80000000U.

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 p50Host p95Host p99Cortex-A7 @ 528 MHz Startup Cost
Full sh check.sh (make -B + gcc link + 4 cases)143.25 ms157.56 ms165.52 msHost compile + archive + test execution
verify 4-case runtime/SDK suite (verify 1..4)3524.5 us4305.9 us4863.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

SymptomRoot CauseFix
not ok 3 (ram[40] is 0U instead of 0xa5U).bss loop used inclusive i <= bss_endLoop 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)) == 0UReject `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 - addGuard 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

  1. Why does (alignment & (alignment - 1U)) == 0U (combined with alignment != 0U) identify powers of two across all 32-bit unsigned integers in O(1) time?
  • *Hint 1:* Write the binary representation of 2^k (0b001000) and 2^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 with n - 1?
  1. Why does an ARMv7-A _start assembly loop (cmp r0, r1 / blo 1b with str r2, [r0], #4) require . = ALIGN(4); on both __bss_start and __bss_end in the linker script?
  • *Hint 1:* Suppose .bss ends with a single char flag; so __bss_end - __bss_start == 5 bytes (__bss_end = 0x87810005).
  • *Hint 2:* Trace r0 stepping by +4 (0x87810000 -> 0x87810004 -> 0x87810008) under blo: how many bytes past 0x87810005 get zeroed on the second 4-byte STR?

13. Independent Challenges

  1. Near Transfer — Word-Wide init_runtime_aligned32(): Write a stricter startup verifier requiring data_at, data_size, bss_begin, and bss_end to be multiples of 4U (just like a 4-byte LDR/STR _start loop), performing 4-byte chunk operations and rejecting unaligned linker symbols cleanly.
  2. Far Transfer — Full .text + .rodata + .data (LMA != VMA) + .bss + IRQ/SVC Stack Solver: Implement bool solve_lds_layout(...) that computes _etext, __data_load (LMA), __data_start.._edata (VMA), [__bss_start, __bss_end), and 8-byte-aligned IRQ/SVC stack tops inside [ram_base, ram_base + ram_size), rejecting stack-into-.bss collisions.

14. Solutions & Explanations

  • Guided Question 1: An exact power of two has a single 1 bit (2^k), and subtracting 1 clears bit k and sets bits 0..k-1, yielding zero bit overlap (& == 0); any number with two or more 1 bits retains its most-significant 1 bit in n - 1, so n & (n - 1) is non-zero.
  • Guided Question 2: Stepping 4 bytes per STR while r0 < __bss_end when __bss_end is unaligned (+5) executes at +0 and +4, writing bytes +4..+7 (3 bytes past __bss_end!); aligning __bss_end = ALIGN(4) reserves those 3 tail 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 MMIO overlay must sit at its exact documented peripheral byte offset, proven at compile time with offsetof and _Static_assert (never __attribute__((packed))).
  • volatile prevents compiler load/store removal and merging, yet provides neither atomic read-modify-write execution nor ARMv7-A CPU memory barriers.
  • Explicit 32-bit unsigned masks avoid implementation-defined C bit-field ordering, narrow byte loads (ldrb/strb), and accidental RMW on W1C status 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.
Progress is saved on this device.
up next · module 5 labLab: Linker Alignment, Exclusive .bss C-Runtime Init & GPIO Struct Geometry (30 min)
→ module 5 lab

search — fzf

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

keyboard shortcuts — less

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

figure