Lab 5: Linker Alignment, Exclusive .bss C-Runtime Init & GPIO Struct Geometry
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 · 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-m05ls -lastarter/Makefilestarter/core.cstarter/core.hstarter/main.clearner@ksa:~/gl-e01/lab-m05starter: starter/Makefile
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_demostarter: starter/core.c
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$ 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); #endifstarter: starter/main.c
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
- 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).
step 3/15 · 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.
step 4/15 · 4. required software & hardware
- Software:
gcc(-std=c11 -Wall -Wextra -Werror -pedantic -MMD -MP), GNUmake, GNUar, POSIX/bin/sh, and Binutils (nm,objdump). - Hardware: Standard Linux workstation (
0physical target hardware required forTAPverification).
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$ 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 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).
step 7/15 · 7. expected tap-13 output
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/5step 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
- 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.
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 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 |
step 11/15 · 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 |
step 12/15 · 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?
step 13/15 · 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.
step 14/15 · 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.
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./check.shlearner@ksa:~/gl-e01/lab-m05TAP version 131..5ok 1 - strict C11 build and trusted grader linkProgressive hints & solution
hint 1
Compare starter/Makefile against the module lessons. Focus first on: Strict C11 build and trusted grader link.
hint 2
Compile with -std=c11 -Wall -Wextra -Werror, check every system-call return value before touching output buffers, and verify cleanup on error paths.
solution
warning: Reveal the reference solution files? Running ./check.sh against your own attempt first builds stronger retention.
solution: files/Makefile
learner@ksa:~/gl-e01/lab-m05$ bat files/Makefile File: files/Makefile CC = gcc AR = ar override CFLAGS += -std=c11 -Wall -Wextra -Werror -pedantic -MMD -MP all: libbsp.a bsp_demo libbsp.a: core.o $(AR) rcs $@ $^ bsp_demo: main.o libbsp.a $(CC) $(CFLAGS) main.o libbsp.a -o $@ %.o: %.c core.h $(CC) $(CFLAGS) -c $< -o $@ -include core.d main.d .PHONY: all clean clean: rm -f core.o main.o core.d main.d libbsp.a bsp_demosolution: files/core.c
learner@ksa:~/gl-e01/lab-m05$ bat files/core.c File: files/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); }solution: files/core.d
learner@ksa:~/gl-e01/lab-m05$ bat files/core.d File: files/core.d core.o: core.c core.h core.h:solution: files/core.h
learner@ksa:~/gl-e01/lab-m05$ bat files/core.h File: files/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); #endifsolution: files/main.c
learner@ksa:~/gl-e01/lab-m05$ bat files/main.c File: files/main.c #include "core.h" #include <stdio.h> int main(void) { puts("GL-E01 BSP laboratory: run ../check.sh for graded evidence"); return 0; }solution: files/main.d
learner@ksa:~/gl-e01/lab-m05$ bat files/main.d File: files/main.d main.o: main.c core.h core.h: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:
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/5On an incomplete starter tree, ./check.sh exits non-zero and marks the unmet assertion not ok with an indented YAML diagnostic block:
learner@ksa:~/gl-e01/lab-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/5note: How to read TAP diagnostics: 1..N states the total test plan; each ok k confirms a passed check; not ok k pinpoints the failing check alongside message: (what went wrong) and hint: (where to look next) between --- and ....
inspect harness: check.sh
learner@ksa:~/gl-e01/lab-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.