Lab 1: ARM32 ELF Header Gate, Overflow-Safe RAM Fit & Active-Low Pin Latch
Implement, compile, and verify lab_m01_eabi_workbench 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.
- Recognizes ARM ELF32 and rejects short or mismatched headers.
- Accepts exact RAM fits and rejects arithmetic boundary violations.
step 1/15 · inspect starter files and specification
First-week Cortex-A7 bring-up sessions stall when an engineer downloads an x86_64 host binary (e_machine = 62) over TFTP into 0x87800000, trusts start + length <= base + size near 0xFFFFFFFF where 32-bit unsigned addition wraps modulo 2^32, or drives an active-low cathode-sink LED on GPIO1_IO03 with inverted Boolean logic that extinguishes the indicator when on == true. In this laboratory, you will audit starter/core.c, isolate a silent-compile polarity inversion inside pin_write(), and prove ELF32 EM_ARM identification, subtraction-based RAM placement bounds, and sibling-preserving GPIO data-latch updates under TAP version 13.
learner@ksa:~/gl-e01/lab-m01ls -lastarter/Makefilestarter/core.cstarter/core.hstarter/main.clearner@ksa:~/gl-e01/lab-m01starter: starter/Makefile
learner@ksa:~/gl-e01/lab-m01$ 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-m01$ bat starter/core.c File: starter/core.c #include "core.h" bool elf_arm32(const unsigned char *p, size_t n) { return n >= 20U && p[0] == 0x7fU && p[1] == 'E' && p[2] == 'L' && p[3] == 'F' && p[4] == 1U && p[5] == 1U && p[18] == 40U && p[19] == 0U; } bool image_fits(uint32_t base, uint32_t size, uint32_t start, uint32_t length) { if (start < base || length == 0U) return false; uint32_t offset = start - base; return offset <= size && length <= size - offset; } bool pin_write(uint32_t *dr, unsigned pin, bool on, bool active_low) { if (dr == NULL || pin >= 32U) return false; uint32_t mask = UINT32_C(1) << pin; *dr = (on == active_low) ? *dr | mask : *dr & ~mask; return true; }starter: starter/core.h
learner@ksa:~/gl-e01/lab-m01$ 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> bool elf_arm32(const unsigned char *p, size_t n); bool image_fits(uint32_t base, uint32_t size, uint32_t start, uint32_t length); bool pin_write(uint32_t *dr, unsigned pin, bool on, bool active_low); #endifstarter: starter/main.c
learner@ksa:~/gl-e01/lab-m01$ 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
- Validate
32-bit little-endianARMELFheaders (0x7F 'E' 'L' 'F',EI_CLASS = 1,EI_DATA = 1,e_machine = 40at bytes18..19) while rejecting truncated buffers below20bytes. - Prove overflow-safe target RAM window containment
[start, start + length)inside[base, base + size)using post-guard subtraction (length <= size - (start - base)). - Repair active-low vs active-high
GPIOx_DRpin updates (on != active_low) sopin_write()preserves all31neighboring pins and rejectsNULLpointers orpin >= 32without mutating caller state. - Benchmark archive build and 4-suite verification latency (
p50/p95/p99) usingCLOCK_MONOTONIC.
step 3/15 · 3. environment requirements
- Tested Workstation Host:
Linux 7.0.0-42-generic(x86_64LP64user space) insidelabs/lab_m01_eabi_workbench/. - Target Architecture Alignment:
core.handcore.crestrict register images and RAM addresses to<stdint.h>uint32_tandUINT32_C(1)shifts so hostLP64verification matches32-bitARMv7-AILP32freestanding builds bit-for-bit.
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,readelf). - Hardware: Standard Linux workstation (
0physical target boards or serial adapters required for gradedTAPsign-off;3.3 Vactive-low sink verification applies during optional bench bring-up).
step 5/15 · 5. complete executable commands
Run these commands from labs/lab_m01_eabi_workbench/ to reproduce the starter/ failure in a disposable sandbox, isolate failing test vectors 3 and 4, inspect the static archive libbsp.a, and confirm 5/5 TAP checks on files/:
learner@ksa:~/gl-e01/lab-m01$ bat script.sh File: script.sh # 1. Stage starter/ in a disposable temp directory and run check.sh without clobbering files/ TMP=$(mktemp -d) && cp -r check.sh tests.c starter "$TMP/" && mv "$TMP/starter" "$TMP/files" && sh "$TMP/check.sh" ; rm -rf "$TMP" # 2. Link tests.c directly against starter/core.c to pinpoint which case aborts TMP=$(mktemp -d) && gcc -std=c11 -Wall -Wextra -Werror -pedantic -Istarter tests.c starter/core.c -o "$TMP/v" && { "$TMP/v" 3 || echo "starter case 3 aborted (rc=$?)"; "$TMP/v" 4 || echo "starter case 4 aborted (rc=$?)"; } ; rm -rf "$TMP" # 3. Rebuild the reference library files/libbsp.a and inspect exported ABI symbols make -B -C files ar -t files/libbsp.a && nm -g --defined-only files/libbsp.a # 4. Run the authoritative 5-point TAP version 13 verification harness sh check.sh*Why each step runs:* Step 1 mirrors coursec labs by grading starter/ inside an isolated directory so files/ remains clean; Step 2 executes tests.c cases 3 and 4 directly to expose the SIGABRT exit codes (rc=134); Step 3 proves Makefile -MMD -MP compilation and archive symbol visibility (elf_arm32, image_fits, pin_write); and Step 4 emits graded TAP version 13 output.
step 6/15 · 6. annotated source code (`starter/core.c` defect vs `files/core.c` fix)
elf_arm32(const unsigned char *p, size_t n)(core.c:2-7): Checksn >= 20Ubefore indexingp[0..5]andp[18..19], accepting only0x7f 'E' 'L' 'F',ELFCLASS32(1U),ELFDATA2LSB(1U), and little-endianEM_ARM(p[18] == 40U && p[19] == 0U).tests.ccase1rejectsn = 19U,ELFCLASS64(p[4] = 2U), andEM_X86_64(p[18] = 62U).image_fits(uint32_t base, uint32_t size, uint32_t start, uint32_t length)(core.c:8-13): Rejectsstart < baseorlength == 0Uup front, computesoffset = start - base, and checksoffset <= size && length <= size - offsetsostart = UINT32_MAX, length = 8Uintests.ccase2cannot wrap into range.- Seeded Flaw in
starter/core.c:18(pin_write):starterevaluates*dr = (on == active_low) ? *dr | mask : *dr & ~mask;(logical equivalence / XNOR). Whenon = trueandactive_low = true(cathode-sinkLEDon),starterdrives bit3high (3.3 V), turning theLEDoff; whenon = trueandactive_low = falseonpin = 31U(tests.c:34),starterclears bit31(0x12345678U) instead of setting0x92345678U. - Verified Repair in
files/core.c:14-20: Guardsif (dr == NULL || pin >= 32U) return false;beforeUINT32_C(1) << pin(avoiding C11 shift undefined behavior atpin == 32U), then writes*dr = (on != active_low) ? *dr | mask : *dr & ~mask;.
step 7/15 · 7. expected tap-13 output
learner@ksa:~/gl-e01/lab-m01$ bat listing.txt File: listing.txt # Unmodified starter/ baseline (exits non-zero: # pass 3/5) TAP version 13 1..5 ok 1 - strict C11 build and trusted grader link ok 2 - recognizes ARM ELF32 and rejects short or mismatched headers ok 3 - accepts exact RAM fits and rejects arithmetic boundary violations not ok 4 - maps both output polarities and preserves sibling pins --- message: 'Behavior differs from the independently specified test vectors' hint: 'Repair case 3; inspect tests.c for the exact input and expected result' ... not ok 5 - rejects invalid pins without changing the output object --- message: 'Behavior differs from the independently specified test vectors' hint: 'Repair case 4; inspect tests.c for the exact input and expected result' ... # pass 3/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 - recognizes ARM ELF32 and rejects short or mismatched headers ok 3 - accepts exact RAM fits and rejects arithmetic boundary violations ok 4 - maps both output polarities and preserves sibling pins ok 5 - rejects invalid pins without changing the output object # pass 5/5step 8/15 · 8. explanation of observed behavior
In starter/, check 1 (ok 1), check 2 (ok 2), and check 3 (ok 3) pass cleanly because elf_arm32() and image_fits() are intact and (on == active_low) triggers zero -Wall -Wextra -Werror diagnostics. Check 4 (not ok 4) fails at tests.c:24: starting from dr = 0xa5a5a5a5U (where bit 3 is 0), pin_write(&dr, 3U, true, true) sets bit 3 (0xa5a5a5adU) instead of keeping before & ~8U. Check 5 (not ok 5) passes the pin = 32U and NULL guards at tests.c:32-33 but aborts at tests.c:34 because pin_write(&dr, 31U, true, false) clears bit 31 instead of producing 0x92345678U. Changing == to != in files/core.c satisfies all four polarity combinations (# pass 5/5).
step 9/15 · 9. experiment variations
- Signed-Shift Undefined Behavior at Pin 31 (
UBSan): ReplaceUINT32_C(1) << pinwith1 << pinin a scratch copy and compile with-fsanitize=undefined:tests.ccase4(pin = 31U) shifts1into the sign bit of32-bit signedint, triggering an immediate runtimeUBSandiagnostic. - Modular Addition Wrap in
image_fits(): Temporarily rewriteimage_fits()asreturn length > 0U && start >= base && start + length <= base + size;and runverify 2:UINT32_MAX + 8Uwraps to7U <= 0x1100U, falsely accepting a span past4 GiB. - Big-Endian
EM_ARMSpoof: Seth[18] = 0U; h[19] = 40U;(0x0028big-endian) in a scratch test and confirmelf_arm32()rejects mismatched byte order even whenEI_DATAclaims little-endian.
step 10/15 · 10. performance measurements
Timed on Linux 7.0.0-42-generic (x86_64) with CLOCK_MONOTONIC across 5 warmup runs and 35 measured iterations (reproduce binary timing via python3 -c 'import subprocess,time,statistics as s; [subprocess.run(["sh","check.sh"],stdout=-3) for _ in range(5)]; t=[(time.monotonic_ns(),subprocess.run(["sh","check.sh"],stdout=-3),time.monotonic_ns()) for _ in range(35)]; d=sorted((b-a)/1e6 for a,_,b in t); print(f"p50={s.median(d):.2f}ms p95={d[33]:.2f}ms")'):
Workload Measured (N = 35, warmup = 5) | Host p50 | Host p95 | Host p99 | Cortex-A7 @ 528 MHz Equivalent |
|---|---|---|---|---|
Full sh check.sh (make -B + gcc link + 4 processes) | 130.92 ms | 139.14 ms | 146.45 ms | Host-only toolchain step |
verify 4-case binary suite (verify 1..4 sequential) | 3434.1 us | 3861.1 us | 4202.8 us | < 2 us in-SRAM function calls (0 fork/exec) |
Single GPIO1_DR RMW (LDR + BIC/ORR + STR) | ~1 ns (L1 RAM) | ~2 ns | ~3 ns | ~40 - 90 ns across IPG peripheral bridge |
step 11/15 · 11. troubleshooting
| Symptom | Root Cause | Fix | ||
|---|---|---|---|---|
not ok 4 & not ok 5 (# pass 3/5) | pin_write() uses (on == active_low) instead of (on != active_low) | Use `(on != active_low) ? *dr \ | mask : *dr & ~mask in core.c` | |
Shift warning or pin = 31 sign-extension corruption | 1 << pin shifts signed int instead of unsigned uint32_t | Form the bitmask as UINT32_C(1) << pin after checking pin < 32U | ||
verify 4 crashes with SIGSEGV | *dr read occurs before checking dr == NULL or pin >= 32U | Place `if (dr == NULL \ | \ | pin >= 32U) return false; on the first line of pin_write()` |
elf_arm32 accepts 256+ machine IDs | Checked p[18] == 40U without verifying high byte p[19] == 0U | Require both p[18] == 40U && p[19] == 0U for 16-bit little-endian e_machine |
step 12/15 · 12. guided questions
- Why must
pin_write()checkpin >= 32Ubefore evaluatingUINT32_C(1) << pin, even whenpin == 32Ureturnsfalseon the next line?
- *Hint 1:* Consult ISO C11 Section 6.5.7 on bitwise shift operators when the right operand equals or exceeds the promoted width of the left operand (
32bits). - *Hint 2:* On
x86_64,SHL eax, clmasksclmodulo32(1U << 32yields1!), whereas onARMv7-A,LSL Rd, Rm, Rsuses the bottom8bits ofRs(1U << 32yields0) -- the compiler may optimize assumingpin < 32Ualready holds!
- Why does an active-low cathode-sink
LEDrequireDR[pin] = 0foron == truewhile an active-high sourceLEDrequiresDR[pin] = 1?
- *Hint 1:* Trace the potential difference
V_DD - V_padacross the series resistor andLEDwhen the anode is tied to3.3 V. - *Hint 2:* Write the
2 x 2truth table of(on, active_low) -> pad_highand verify whypad_high = (on != active_low)covers all four rows.
step 13/15 · 13. independent challenges
- Near Transfer — Full
Elf32_Ehdr+PT_LOADSegment Gate: Extendelf_arm32()intoelf_arm32_loadable(const unsigned char *buf, size_t len, uint32_t ram_base, uint32_t ram_size)that parsese_phoff,e_phentsize == 32U, ande_phnum, rejectsp_memsz < p_filesz, and verifies everyPT_LOADsegment (p_type == 1U) fits[ram_base, ram_base + ram_size)viaimage_fits(). - Far Transfer — Multi-Pin Atomic Mask Update (
pin_group_write): Implementbool pin_group_write(uint32_t *dr, uint32_t group_mask, uint32_t logical_on, uint32_t active_low_mask)that updates an arbitrary subset of pins in one read-modify-write expression without per-pin loops while preserving all bits outsidegroup_mask.
step 14/15 · 14. solutions & explanations
- Guided Question 1: Shifting a
32-bituint32_tby>= 32is undefined behavior in ISO C11; evaluatingUINT32_C(1) << pinprior toif (pin >= 32U)lets an optimizing compiler elide thepin >= 32Ubranch altogether! - Guided Question 2: With anode at
3.3 V, drivingDR = 1(3.3 V) yields0 Vacross theLED(off), whereas drivingDR = 0(V_OL) forward-biases the diode (on). Across all four(on, active_low)pairs, the output latch bit is1when(true, false)or(false, true), which is exact Boolean inequalityon != active_low. - Challenge 2 Key Formula: Compute
desired_levels = logical_on ^ active_low_mask; *dr = (*dr & ~group_mask) | (desired_levels & group_mask);.
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-m01./check.shlearner@ksa:~/gl-e01/lab-m01TAP 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-m01$ 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-m01$ bat files/core.c File: files/core.c #include "core.h" bool elf_arm32(const unsigned char *p, size_t n) { return n >= 20U && p[0] == 0x7fU && p[1] == 'E' && p[2] == 'L' && p[3] == 'F' && p[4] == 1U && p[5] == 1U && p[18] == 40U && p[19] == 0U; } bool image_fits(uint32_t base, uint32_t size, uint32_t start, uint32_t length) { if (start < base || length == 0U) return false; uint32_t offset = start - base; return offset <= size && length <= size - offset; } bool pin_write(uint32_t *dr, unsigned pin, bool on, bool active_low) { if (dr == NULL || pin >= 32U) return false; uint32_t mask = UINT32_C(1) << pin; *dr = (on != active_low) ? *dr | mask : *dr & ~mask; return true; }solution: files/core.d
learner@ksa:~/gl-e01/lab-m01$ 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-m01$ 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> bool elf_arm32(const unsigned char *p, size_t n); bool image_fits(uint32_t base, uint32_t size, uint32_t start, uint32_t length); bool pin_write(uint32_t *dr, unsigned pin, bool on, bool active_low); #endifsolution: files/main.c
learner@ksa:~/gl-e01/lab-m01$ 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-m01$ bat files/main.d File: files/main.d main.o: main.c core.h core.h:Run the check
From labs/lab_m01_eabi_workbench/, run ./check.sh. A complete solution emits TAP version 13 with every test point marked ok and exits 0:
learner@ksa:~/gl-e01/lab-m01./check.shTAP version 131..5ok 1 - strict C11 build and trusted grader linkok 2 - recognizes ARM ELF32 and rejects short or mismatched headersok 3 - accepts exact RAM fits and rejects arithmetic boundary violationsok 4 - maps both output polarities and preserves sibling pinsok 5 - rejects invalid pins without changing the output object# 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-m01./check.shTAP version 131..5ok 1 - strict C11 build and trusted grader linkok 2 - recognizes ARM ELF32 and rejects short or mismatched headersok 3 - accepts exact RAM fits and rejects arithmetic boundary violationsnot ok 4 - maps both output polarities and preserves sibling pins --- message: 'Behavior differs from the independently specified test vectors' hint: 'Repair case 3; inspect tests.c for the exact input and expected result' ...not ok 5 - rejects invalid pins without changing the output object --- message: 'Behavior differs from the independently specified test vectors' hint: 'Repair case 4; inspect tests.c for the exact input and expected result' ...# pass 3/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-m01$ 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 - recognizes ARM ELF32 and rejects short or mismatched headers\n' PASS=$((PASS + 1)) else printf 'not ok 2 - recognizes ARM ELF32 and rejects short or mismatched headers\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 - accepts exact RAM fits and rejects arithmetic boundary violations\n' PASS=$((PASS + 1)) else printf 'not ok 3 - accepts exact RAM fits and rejects arithmetic boundary violations\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 - maps both output polarities and preserves sibling pins\n' PASS=$((PASS + 1)) else printf 'not ok 4 - maps both output polarities and preserves sibling pins\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 - rejects invalid pins without changing the output object\n' PASS=$((PASS + 1)) else printf 'not ok 5 - rejects invalid pins without changing the output object\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_m01_eabi_workbench/ so relative paths to files/ resolve directly.