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

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

Implement, compile, and verify lab_m05_lds_crt_sdk 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.
  • Aligns valid addresses and rejects overflow or non-power-of-two requests.
  • Copies data and clears only the exclusive BSS interval.
step 1/15

step 1/15 · inspect starter files and specification

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.

learner@ksa: ~/gl-e01/lab-m05
learner@ksa:~/gl-e01/lab-m05ls -lastarter/Makefilestarter/core.cstarter/core.hstarter/main.clearner@ksa:~/gl-e01/lab-m05
starter: starter/Makefile
learner@ksa: ~/gl-e01/lab-m05
learner@ksa:~/gl-e01/lab-m05$ 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-m05
learner@ksa:~/gl-e01/lab-m05$ bat starter/core.c File: starter/core.c    #include "core.h"    #include <string.h>    bool align_address(uint32_t value, uint32_t alignment, uint32_t *out)    {        if (alignment==0U || (alignment & (alignment-1U))!=0U) return false;        uint32_t add=alignment-1U;        if (value>UINT32_MAX-add) return false;        *out=(value+add)&~add; return true;    }    bool init_runtime(unsigned char *ram, size_t size, const unsigned char *data,                      size_t data_size, size_t data_at, size_t bss_begin, size_t bss_end)    {        if (data_at>size || data_size>size-data_at ||            bss_begin>bss_end || bss_end>size) return false;        if (data_size!=0U && data_at<bss_end && bss_begin<data_at+data_size) return false;        if (data_size!=0U) memcpy(ram+data_at,data,data_size);        for(size_t i=bss_begin;i<=bss_end;++i) ram[i]=0U;        return true;    }    uint32_t data_update(uint32_t old, uint32_t mask, uint32_t value)    {        return (old & ~mask)|(value & mask);    }
starter: starter/core.h
learner@ksa: ~/gl-e01/lab-m05
learner@ksa:~/gl-e01/lab-m05$ bat starter/core.h File: starter/core.h    #ifndef GL_E01_CORE_H    #define GL_E01_CORE_H    #include <stdbool.h>    #include <stddef.h>    #include <stdint.h>    struct gpio_model { uint32_t dr,gdir,psr,icr1,icr2,imr,isr,edge; };    bool align_address(uint32_t value, uint32_t alignment, uint32_t *out);    bool init_runtime(unsigned char *ram, size_t size, const unsigned char *data,                      size_t data_size, size_t data_at, size_t bss_begin, size_t bss_end);    uint32_t data_update(uint32_t old, uint32_t mask, uint32_t value);    #endif
starter: starter/main.c
learner@ksa: ~/gl-e01/lab-m05
learner@ksa:~/gl-e01/lab-m05$ 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. 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).

step 3/15 · 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.

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

step 5/15 · 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/lab-m05
learner@ksa:~/gl-e01/lab-m05$ 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.

step 6/15 · 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).

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

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

step 8/15 · 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).

step 9/15 · 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.

step 10/15 · 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

step 11/15 · 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

step 12/15 · 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?

step 13/15 · 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.

step 14/15 · 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.

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-m05
learner@ksa:~/gl-e01/lab-m05./check.shlearner@ksa:~/gl-e01/lab-m05
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_m05_lds_crt_sdk/, run ./check.sh. A complete solution emits TAP version 13 with every test point marked ok and exits 0:

./check.sh — lab m05
learner@ksa:~/gl-e01/lab-m05./check.shTAP version 131..5ok 1 - strict C11 build and trusted grader linkok 2 - aligns valid addresses and rejects overflow or non-power-of-two requestsok 3 - copies data and clears only the exclusive BSS intervalok 4 - handles empty ranges and rejects invalid geometry without modificationok 5 - proves GPIO offsets and preserves neighboring output bits# 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 m05 (starter)
learner@ksa:~/gl-e01/lab-m05./check.shTAP version 131..5ok 1 - strict C11 build and trusted grader linkok 2 - aligns valid addresses and rejects overflow or non-power-of-two requestsnot 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 modificationok 5 - proves GPIO offsets and preserves neighboring output bits# 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-m05
learner@ksa:~/gl-e01/lab-m05$ 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 - aligns valid addresses and rejects overflow or non-power-of-two requests\n'        PASS=$((PASS + 1))    else        printf 'not ok 2 - aligns valid addresses and rejects overflow or non-power-of-two requests\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 - copies data and clears only the exclusive BSS interval\n'        PASS=$((PASS + 1))    else        printf 'not ok 3 - copies data and clears only the exclusive BSS interval\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 - handles empty ranges and rejects invalid geometry without modification\n'        PASS=$((PASS + 1))    else        printf 'not ok 4 - handles empty ranges and rejects invalid geometry without modification\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 - proves GPIO offsets and preserves neighboring output bits\n'        PASS=$((PASS + 1))    else        printf 'not ok 5 - proves GPIO offsets and preserves neighboring output bits\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_m05_lds_crt_sdk/ 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