Schematics, Active-Low Circuits, and Register Maps

Start from CMOS output transistors and Kirchhoff's Voltage Law to understand why active-low LEDs illuminate when a GPIO sinks current to ground, trace schematic nets across board-to-board connectors to i.MX6ULL ball GPIO1_IO03, and update single register bits safely in ISO C11.

20 minfree previewLinux 6.12C11U-Boot 2025.x→ module 1 lab
What you'll learn
  • Trace a carrier net through a core connector to its SoC pad.
  • Derive active-low output behavior from an LED current path.
  • Calculate register addresses and masks without altering sibling pins.

CMOS Push-Pull Pads, Active-Low Sinking, and Kirchhoff Current Loops

Beginners often assume "writing 1 to a GPIO pin turns an LED on, and writing 0 turns it off." On industrial ARM boards, writing 1 frequently turns the LED off, and writing 0 turns it brightly on! Why? Because a GPIO pin is not a magic software boolean—it is a pair of physical complementary MOSFET switches (CMOS) wired between the pad's I/O supply rail (NVCC_GPIO = 3.30 V) and board ground (GND = 0 V). Look inside the pad stage in Figure 1.3a:

  1. High-Side PMOS Source (DR = 1): Connects the package ball up to 3.30 V (V_OH). If an external load runs from the pin through a resistor and LED to GND (active-high source topology, right panel), current flows out of the PMOS transistor into the LED when DR = 1.
  2. Low-Side NMOS Sink (DR = 0): Connects the package ball down to GND with a small transistor drop (V_OL = 0.15 V = 150 mV). On most carrier boards (active-low sink topology, left panel), the hardware designer wires 3.30 V -> R (1000 ohm) -> LED Anode | Cathode -> GPIO1_IO03. When DR[3] = 1, both ends of the LED+resistor branch sit near 3.30 V (0 V potential difference -> zero current -> LED dark!). When DR[3] = 0, the NMOS switch closes to GND: applying Kirchhoff's Voltage Law (KVL) around the loop gives I_sink = (V_DD - V_F - V_OL) / R = (3300 - 2050 - 150) mV / 1000 ohm = 1.10 mA (1100 uA), illuminating the LED well below a conservative 8.0 mA (8000 uA) pad current limit!
fig_m01_l03_a.svg — Physical CMOS pad stage — why active-low sink circuits…

Figure 1.3a. Physical CMOS pad stage — why active-low sink circuits conduct I = (V_DD - V_F - V_OL) / R when DR = 0 (left) vs active-high sourcing when DR = 1 (right).

Why do board designers prefer active-low sinking for status LEDs? Historically and physically, silicon NMOS electron mobility exceeds PMOS hole mobility (NMOS sinks low with lower on-resistance than PMOS sources high), and keeping indicator current off the 's high-side NVCC rail reduces supply bounce—provided the external series resistor R limits I_sink safely (R = 100 ohm would pull 11.0 mA, overstressing the pad!).

mental model: A schematic net label (LED0) is like a highway route number crossing county lines: the name can change at a border bridge (SOM-to-carrier connector), and the route name tells you connectivity—never which direction current flows or the pad's current limit.

Where it stops working: Unlike road traffic, electrical current requires a closed voltage loop (V_DD > V_F + V_OL), and shifting a signed 32-bit C integer into bit 31 invokes undefined behavior before a single electron moves.

definition (Schematic Net Continuity, Active-Low Sink & Peripheral Offset Geometry): A schematic net label joins electrically connected nodes on a drawing; tracing a signal from a carrier board load into a System-on-Module (SOM) requires following mating connector pin numbers (LED0 -> J1.14 -> P1.14 -> ball GPIO1_IO03), never guessing from text names. In an active-low sink circuit, logical assertion (on = true) drives the output bit to 0 (level_high = (on != active_low)). Each 32-bit register sits at physical address Base + Offset (GPIO1_DR = 0x0209C000 + 0x00, GPIO1_GDIR = 0x0209C000 + 0x04), where single-pin writes must preserve all 31 sibling bits.

Trace the complete four-stage path from external LED load to 32-bit register bitmask below:

ast_m01_l03.svg — Never guess polarity or GPIO numbers from net names:…step 1/4
  1. Step 1. Step 1 (Load Circuit): 3.3 V -> resistor -> LED -> GPIO cathode conducts when the pin sinks low (active-low).
  2. Step 2. Step 2 (Carrier Net): Follow net label LED0 to its exact board-to-board header pin and check shared pulls or boot straps.
  3. Step 3. Step 3 (Core Pad): Match the mating SOM connector pin to SoC ball GPIO1_IO03 (Bank 1, local bit index 3).
  4. Step 4. Step 4 (Register Mask): Compute Base + Offset (0x0209C000) and update bit 3 via UINT32_C(1) << pin without touching 31 siblings.

Figure 1.3b. Never guess polarity or GPIO numbers from net names: trace Load -> Connector Pin -> SoC Ball -> Masked Base+Offset.

Tracing Carrier Nets Across Connectors to Physical GPIO Registers

Most production i.MX6ULL hardware splits into two schematics: a compact Core SOM (housing the SoC, DDR3, PMIC, and eMMC/NAND) and a Carrier Board (housing LEDs, relays, UART headers, and Ethernet PHYs). Searching the SOM schematic PDF for LED0 often returns zero hits because the carrier net LED0 terminates on header J1 pin 14, while the mating SOM connector P1 pin 14 names that exact copper conductor GPIO1_IO03! Always build the four-column trace shown at the top of Figure 1.3b (Load Terminal -> Carrier Net/Pin -> SOM Pin/Ball -> Bank/Bit/Address) and note whether any external pull resistor shares a reset BOOT_CFG strap pin.

fig_m01_l03_b.svg — Four-column schematic trace across board-to-board…

Figure 1.3b. Four-column schematic trace across board-to-board connectors (top) and 32-bit GPIO1 masked update geometry preserving all 31 sibling pins (bottom).

Once GPIO1_IO03 maps to Bank GPIO1 (0x0209C000), local bit 3, examine how schematic_gpio.c translates logical intent into an electrical level without scattering inverted 0/1 magic numbers across application code:

  1. Bounds-First Unsigned Shift (pin < 32U + UINT32_C(1) << pin): In ISO C11, shifting by >= 32 on a 32-bit type—or shifting signed literal 1 into sign bit 31 (1 << 31)—is Undefined Behavior (UB)! Checking if (pin >= 32U) return false; before evaluating UINT32_C(1) << pin eliminates both traps.
  2. Boolean XOR Polarity (high = (on != active_low)): When active_low is true and caller requests on = true, true != true evaluates to false (0), clearing bit 3 (value & ~mask) to sink current while leaving all 31 sibling GPIO1 pins untouched.
learner@ksa: ~/gl-e01/m01-l03
learner@ksa:~/gl-e01/m01-l03$ bat schematic_gpio.c File: schematic_gpio.c    #include <stdint.h>    #include <stdbool.h>    static volatile uint32_t *const gpio1_dr =        (volatile uint32_t *)(uintptr_t)0x0209c000U;    bool led_write(unsigned pin, bool on, bool active_low)    {        if (pin >= 32U) return false;        const uint32_t mask = UINT32_C(1) << pin;        const bool high = on != active_low;        uint32_t value = *gpio1_dr; /* exclusive bank ownership required */        value = high ? value | mask : value & ~mask;        *gpio1_dr = value;        return true;    }

Verifying KVL Sink Headroom, Polarity XOR, and Shift Safety in C11

Never dereference (volatile uint32_t *)0x0209c000U in a host process (where 0x0209C000 is an unmapped virtual address, not an i.MX6ULL IPG peripheral bus!). Instead, sink_drive_audit.c verifies both integer microampere KVL circuit analysis and 32-bit RAM-modeled GPIO1_DR bit preservation on the host. Notice how sink_current_ua() checks vdd_mv <= vf_mv + vol_mv before subtracting so an under-volted 1.8 V (1800 mV) rail driving a 2.05 V (2050 mV) red LED returns false cleanly instead of wrapping unsigned headroom to 4.29 GV, and rejects R = 100 ohm (11000 uA > 8000 uA).

learner@ksa: ~/gl-e01/m01-l03
learner@ksa:~/gl-e01/m01-l03$ bat -H 8 -H 9 -H 10 -H 11 -H 12 -H 13 -H 14 -H 15 -H 19 -H 20 -H 21 -H 22 -H 23 sink_drive_audit.c File: sink_drive_audit.c    #include <assert.h>    #include <stdbool.h>    #include <stddef.h>    #include <stdint.h>    #include <stdio.h>        static bool sink_current_ua(uint32_t vdd_mv, uint32_t vf_mv, uint32_t vol_mv,                                uint32_t r_ohm, uint32_t max_ua, uint32_t *out_ua)    {        if (r_ohm == 0U || vdd_mv <= vf_mv + vol_mv) return false;      uint32_t headroom_mv = vdd_mv - vf_mv - vol_mv;        uint32_t ua = (headroom_mv * 1000U) / r_ohm;        if (ua == 0U || ua > max_ua) return false;        *out_ua = ua;        return true;    }        static bool set_pin_level(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;    }        int main(void)    {        uint32_t ua = 0U;        assert(sink_current_ua(3300U, 2050U, 150U, 1000U, 8000U, &ua) && ua == 1100U);        assert(sink_current_ua(3300U, 2100U, 0U, 1200U, 8000U, &ua) && ua == 1000U);        assert(!sink_current_ua(3300U, 2050U, 150U, 100U, 8000U, &ua));        assert(!sink_current_ua(1800U, 2050U, 150U, 1000U, 8000U, &ua));        assert(0x0209c000U + 0x04U == 0x0209c004U);            uint32_t dr = 0xa5a5a5a5U, before = dr;        assert(set_pin_level(&dr, 3U, true, true));        assert((dr & 8U) == 0U && (dr & ~8U) == (before & ~8U));        assert(set_pin_level(&dr, 3U, false, true) && (dr & 8U) != 0U);        assert(set_pin_level(&dr, 3U, false, false) && (dr & 8U) == 0U);        assert(set_pin_level(&dr, 3U, true, false) && (dr & 8U) != 0U);        before = dr;        assert(!set_pin_level(&dr, 32U, true, true) && dr == before);        printf("sink_ua=1100 gdir=0x%08X dr_active_low_on=0x%08X\n",               0x0209c000U + 0x04U, before & ~8U);        return 0;    }
  1. Evaluate (vdd_mv - vf_mv - vol_mv) * 1000 / r_ohm in uint32_t microamps and enforce the pad sink ceiling.
  2. Reject pin >= 32 before shifting UINT32_C(1) << pin so C11 shift-width undefined behavior never executes.
  3. Map logical assertion through (on != active_low) while preserving all 31 sibling bits in *dr.

Running the Circuit Current and Mask Verifier

Execute sink_drive_audit on the workstation and cross-compile schematic_gpio.c into freestanding ARMv7-A machine code (target.o) with -mfloat-abi=soft -ffreestanding -Werror to confirm clean target code generation alongside host algebraic verification.

learner@ksa: ~/gl-e01/m01-l03
learner@ksa:~/gl-e01/m01-l03gcc -std=c11 -Wall -Wextra -Werror -pedantic sink_drive_audit.c -o sink_drive_auditlearner@ksa:~/gl-e01/m01-l03./sink_drive_auditsink_ua=1100 gdir=0x0209C004 dr_active_low_on=0xA5A5A5A5learner@ksa:~/gl-e01/m01-l03clang --target=armv7a-none-eabi -mcpu=cortex-a7 -marm -mfloat-abi=soft -ffreestanding -std=c11 -Wall -Wextra -Werror -x c -c schematic_gpio.c -o target.olearner@ksa:~/gl-e01/m01-l03
strace — learner@ksa: ~/gl-e01/m01-l03
learner@ksa:~/gl-e01/m01-l03strace -e trace=write,exit_group \./sink_drive_auditwrite(1, "sink_ua=1100 gdir=0x0209C004 dr_"..., 57) = 57exit_group(0)                           = ?+++ exited with 0 +++

End-to-End Signal Provenance and Drive Topology Trade-Offs

Compare the four drive and register patterns in the matrix below. Notice that led_write() updating GPIO1_DR at 0x0209C000 is necessary but still not sufficient to light the physical LED on cold silicon: Module 3 will add CCM_CCGR1 clock gating, IOMUXC ALT5 pad routing, SW_PAD_CTL DSE output drive, and GPIO1_GDIR (0x0209C004) output direction!

Circuit / Software ChoiceDrive Equation / ExpressionPin Stress & Sibling SafetyFailure Mode When Misapplied
direct GPIO sink (<= 2 mA)dr &= ~(1U << pin) asserts; I = (V_DD - V_F - V_OL)/RSafe within pad I_OL budget; 31 siblings preservedDriving 1 turns LED off; omitting R overcurrents pad bond wire
Active-high direct GPIO source`dr \= (1U << pin) asserts; I = (V_OH - V_F)/R`Pulls current from NVCC rail; 31 siblings preservedFails to conduct if V_OH rail (1.8 V) sits below V_F (2.05 V)
Whole-bank write *gpio1_dr = 0U1 store, 0 mask logicUnsafe: clobbers all 31 neighboring GPIO1 pinsAsserts or drops unrelated relays, chip-selects, and reset lines on GPIO1
Unchecked shift 1 << pin (signed int)Undefined behavior for pin >= 31 in ISO C11Corrupts sign bit at pin == 31 or shifts out of boundsTraps under -fsanitize=undefined or toggles wrong bit

Later: Module 2 (m02-l01..m02-l03) dives inside the Cortex-A7 core itself—processor modes, banked registers, CP15 SCTLR/VBAR, load/store writeback, and 8-byte-aligned assembly stack frames—before Module 3 lights the physical LED in assembly and C.

Common Production Pitfalls

warning: Symptom: Searching the core SOM schematic for carrier net name LED0 yields zero matches, leading an engineer to guess GPIO1_IO00 and toggle an unrelated board net. Root Cause: Net names are local to a schematic sheet or hierarchy unless linked by ports; across a SOM-to-carrier header (J1 pin 14 -> P1 pin 14), the same electrical conductor is renamed GPIO1_IO03. Fix: Always trace signals by physical connector pin numbers from load terminal to SoC ball before writing software.

warning: Symptom: Calling set_pin_level(&dr, 31U, true, false) triggers a signed-overflow sanitizer abort when the mask is written 1 << pin instead of UINT32_C(1) << pin. Root Cause: Integer literal 1 has type signed int, and left-shifting 1 into sign bit 31 overflows INT32_MAX (Undefined Behavior in ISO C11). Fix: Reject pin >= 32U first and form every 32-bit register mask from unsigned UINT32_C(1) << pin.

Practice & Retrieval

Guided Practice: Sizing a 1.8 V Rail Indicator & Pin 31 Masking

Step 1 (1.8 V Headroom): A board revision moves an active-low indicator onto a 1800 mV (1.8 V) bank using a low-forward-voltage LED (V_F = 1200 mV, V_OL = 120 mV); solve (1800 - 1200 - 120) * 1000 / 1600 for series resistor R at 1600 uA (300 ohm). Step 2 (Pin 31 Polarity): Starting from dr = 0x80000008U, evaluate set_pin_level(&dr, 31U, true, true) in hex (0x00000008U). Step 3 (Offset Math): Given GPIO5 base 0x020AC000, state the physical addresses of GPIO5_DR (+0x00) and GPIO5_GDIR (+0x04).

Independent Practice: Worst-Case Tolerance & Netlist Auditor (board_led_spec.c)

Write a standalone ISO C11 verifier board_led_spec.c evaluating struct led_circuit across supply tolerance (vdd_min_mv, vdd_max_mv), LED drop spread (vf_min_mv, vf_max_mv), vol_max_mv, and resistor tolerance (r_nominal_ohm, r_tol_pct). Assert both worst-case visibility (I_min >= 500 uA at vdd_min, vf_max, R_max) and pad safety (I_max <= 6000 uA at vdd_max, vf_min, vol = 0, R_min) across 6 valid and faulted circuits.

quiz · 1 of 3

An indicator branch runs from 3.3 V through a 1 kOhm resistor to an LED anode, with the LED cathode wired to GPIO1_IO03. Which register state illuminates the LED?

quiz · 2 of 3

A helper computes uint32_t mask = 1U << pin; if (pin >= 32U) return false;. Why is this C11 code defective?

quiz · 3 of 3

Retrieval: does computing 0x0209C000U + 0x04U == 0x0209C004U in a host C11 program map GPIO1_GDIR into the workstation process?

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

env: host

1. Motivation

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.

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.

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.

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

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/m01-l03
learner@ksa:~/gl-e01/m01-l03$ 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.

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

7. Expected TAP-13 Output

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

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

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.

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

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

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.

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.

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);.

Run locally in your terminal and check off each verification milestone.

Not started

Key takeaways

  • Schematic net labels denote electrical conductors on a sheet; always trace across mating SOM-to-carrier connector pin numbers to identify the exact SoC ball and GPIO bank/bit.
  • sink circuits (V_DD -> R -> LED -> GPIO) conduct I = (V_DD - V_F - V_OL) / R when DR drives 0 (level_high = (on != active_low)).
  • Peripheral registers sit at Base + Offset (GPIO1_DR = 0x0209C000, GPIO1_GDIR = 0x0209C004); never dereference physical SoC addresses inside host user space.
  • Guard pin < 32U before evaluating UINT32_C(1) << pin and use masked read-modify-write under exclusive ownership so all 31 sibling pins remain intact.
  • A schematic net label names electrical connectivity rather than a software GPIO number.
  • An active-low LED connected from a supply through resistance to a GPIO conducts when the GPIO sinks current.
  • No; it identifies a target address, not a host mapping.
Progress is saved on this device.
up next · module 1 labLab: ARM32 ELF Header Gate, Overflow-Safe RAM Fit & Active-Low Pin Latch (30 min)
→ module 1 lab

search — fzf

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

keyboard shortcuts — less

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

figure