Lab 1: ARM32 ELF Header Gate, Overflow-Safe RAM Fit & Active-Low Pin Latch

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

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

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-m01
learner@ksa:~/gl-e01/lab-m01ls -lastarter/Makefilestarter/core.cstarter/core.hstarter/main.clearner@ksa:~/gl-e01/lab-m01
starter: starter/Makefile
learner@ksa: ~/gl-e01/lab-m01
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_demo
starter: starter/core.c
learner@ksa: ~/gl-e01/lab-m01
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
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);    #endif
starter: starter/main.c
learner@ksa: ~/gl-e01/lab-m01
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

  1. Validate 32-bit little-endian ARM ELF headers (0x7F 'E' 'L' 'F', EI_CLASS = 1, EI_DATA = 1, e_machine = 40 at bytes 18..19) while rejecting truncated buffers below 20 bytes.
  2. Prove overflow-safe target RAM window containment [start, start + length) inside [base, base + size) using post-guard subtraction (length <= size - (start - base)).
  3. Repair active-low vs active-high GPIOx_DR pin updates (on != active_low) so pin_write() preserves all 31 neighboring pins and rejects NULL pointers or pin >= 32 without mutating caller state.
  4. Benchmark archive build and 4-suite verification latency (p50/p95/p99) using CLOCK_MONOTONIC.

step 3/15 · 3. environment requirements

  • Tested Workstation Host: Linux 7.0.0-42-generic (x86_64 LP64 user space) inside labs/lab_m01_eabi_workbench/.
  • Target Architecture Alignment: core.h and core.c restrict register images and RAM addresses to <stdint.h> uint32_t and UINT32_C(1) shifts so host LP64 verification matches 32-bit ARMv7-A ILP32 freestanding builds bit-for-bit.

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, readelf).
  • Hardware: Standard Linux workstation (0 physical target boards or serial adapters required for graded TAP sign-off; 3.3 V active-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
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): Checks n >= 20U before indexing p[0..5] and p[18..19], accepting only 0x7f 'E' 'L' 'F', ELFCLASS32 (1U), ELFDATA2LSB (1U), and little-endian EM_ARM (p[18] == 40U && p[19] == 0U). tests.c case 1 rejects n = 19U, ELFCLASS64 (p[4] = 2U), and EM_X86_64 (p[18] = 62U).
  • image_fits(uint32_t base, uint32_t size, uint32_t start, uint32_t length) (core.c:8-13): Rejects start < base or length == 0U up front, computes offset = start - base, and checks offset <= size && length <= size - offset so start = UINT32_MAX, length = 8U in tests.c case 2 cannot wrap into range.
  • Seeded Flaw in starter/core.c:18 (pin_write): starter evaluates *dr = (on == active_low) ? *dr | mask : *dr & ~mask; (logical equivalence / XNOR). When on = true and active_low = true (cathode-sink LED on), starter drives bit 3 high (3.3 V), turning the LED off; when on = true and active_low = false on pin = 31U (tests.c:34), starter clears bit 31 (0x12345678U) instead of setting 0x92345678U.
  • Verified Repair in files/core.c:14-20: Guards if (dr == NULL || pin >= 32U) return false; before UINT32_C(1) << pin (avoiding C11 shift undefined behavior at pin == 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
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/5

step 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

  1. Signed-Shift Undefined Behavior at Pin 31 (UBSan): Replace UINT32_C(1) << pin with 1 << pin in a scratch copy and compile with -fsanitize=undefined: tests.c case 4 (pin = 31U) shifts 1 into the sign bit of 32-bit signed int, triggering an immediate runtime UBSan diagnostic.
  2. Modular Addition Wrap in image_fits(): Temporarily rewrite image_fits() as return length > 0U && start >= base && start + length <= base + size; and run verify 2: UINT32_MAX + 8U wraps to 7U <= 0x1100U, falsely accepting a span past 4 GiB.
  3. Big-Endian EM_ARM Spoof: Set h[18] = 0U; h[19] = 40U; (0x0028 big-endian) in a scratch test and confirm elf_arm32() rejects mismatched byte order even when EI_DATA claims 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 p50Host p95Host p99Cortex-A7 @ 528 MHz Equivalent
Full sh check.sh (make -B + gcc link + 4 processes)130.92 ms139.14 ms146.45 msHost-only toolchain step
verify 4-case binary suite (verify 1..4 sequential)3434.1 us3861.1 us4202.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

SymptomRoot CauseFix
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 corruption1 << pin shifts signed int instead of unsigned uint32_tForm 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 >= 32UPlace `if (dr == NULL \\pin >= 32U) return false; on the first line of pin_write()`
elf_arm32 accepts 256+ machine IDsChecked p[18] == 40U without verifying high byte p[19] == 0URequire both p[18] == 40U && p[19] == 0U for 16-bit little-endian e_machine

step 12/15 · 12. guided questions

  1. Why must pin_write() check pin >= 32U before evaluating UINT32_C(1) << pin, even when pin == 32U returns false on 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 (32 bits).
  • *Hint 2:* On x86_64, SHL eax, cl masks cl modulo 32 (1U << 32 yields 1!), whereas on ARMv7-A, LSL Rd, Rm, Rs uses the bottom 8 bits of Rs (1U << 32 yields 0) -- the compiler may optimize assuming pin < 32U already holds!
  1. Why does an active-low cathode-sink LED require DR[pin] = 0 for on == true while an active-high source LED requires DR[pin] = 1?
  • *Hint 1:* Trace the potential difference V_DD - V_pad across the series resistor and LED when the anode is tied to 3.3 V.
  • *Hint 2:* Write the 2 x 2 truth table of (on, active_low) -> pad_high and verify why pad_high = (on != active_low) covers all four rows.

step 13/15 · 13. independent challenges

  1. Near Transfer — Full Elf32_Ehdr + PT_LOAD Segment Gate: Extend elf_arm32() into elf_arm32_loadable(const unsigned char *buf, size_t len, uint32_t ram_base, uint32_t ram_size) that parses e_phoff, e_phentsize == 32U, and e_phnum, rejects p_memsz < p_filesz, and verifies every PT_LOAD segment (p_type == 1U) fits [ram_base, ram_base + ram_size) via image_fits().
  2. Far Transfer — Multi-Pin Atomic Mask Update (pin_group_write): Implement bool 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 outside group_mask.

step 14/15 · 14. solutions & explanations

  • Guided Question 1: Shifting a 32-bit uint32_t by >= 32 is undefined behavior in ISO C11; evaluating UINT32_C(1) << pin prior to if (pin >= 32U) lets an optimizing compiler elide the pin >= 32U branch altogether!
  • Guided Question 2: With anode at 3.3 V, driving DR = 1 (3.3 V) yields 0 V across the LED (off), whereas driving DR = 0 (V_OL) forward-biases the diode (on). Across all four (on, active_low) pairs, the output latch bit is 1 when (true, false) or (false, true), which is exact Boolean inequality on != 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
learner@ksa:~/gl-e01/lab-m01./check.shlearner@ksa:~/gl-e01/lab-m01
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_m01_eabi_workbench/, run ./check.sh. A complete solution emits TAP version 13 with every test point marked ok and exits 0:

./check.sh — lab m01
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/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 m01 (starter)
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/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-m01
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.

Progress is saved on this device.

search — fzf

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

keyboard shortcuts — less

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

figure