Linux Host Workbench, POSIX Shell, Network Boot & Embedded C Style
Engineers transitioning from bare-metal MCUs or desktop software to Linux host toolchains, embedded board bring-up, and kernel C development
Outcome: Provision, audit, and troubleshoot a deterministic Linux embedded engineering host, multi-NIC TFTP/NFS boot bench, kernel-style C11 codebase, and ARMv7-A cross-ABI deployment pipeline.
Print this handbook or save as PDF (A4 or Letter) for offline engineering reference. Terminal listings convert automatically to crisp white ink-saving frames in print.
m01/
Host Virtualization Bridges, PTY Streams & Shell Pipelines
Provision hardware-virtualized Linux network bridges, deterministic udev USB device permissions, POSIX file-descriptor redirection pipelines, sudo-safe cross-compiler PATH environments, and modal tree-search workflows verified by an ISO C11 workbench auditor.
What you'll learn
- Configure a dual-NIC hypervisor topology separating NAT internet access from a wired Layer-2 bench bridge.
- Diagnose why Wi-Fi 802.11 client stations reject spoofed guest MAC frames and why NAT blocks unsolicited board TFTP requests.
- Author deterministic udev rules for CH340 USB-UART consoles (1a86:7523) and i.MX6ULL SDP Boot ROM recovery devices (15a2:0080).
Why Embedded Benches Break Inside Default Virtual Machine Settings
Desktop software engineers rarely notice whether their Linux virtual machine sits behind hypervisor Network Address Translation (NAT), because outbound TCP connections to Git servers originate from inside the guest. Embedded board bring-up reverses the connection direction. On power-on, U-Boot broadcasts an ARP request on the bench cable and sends an unsolicited UDP/69 TFTP read request toward the Linux workstation to fetch zImage and the Device Tree blob. Behind NAT, the guest owns a private address invisible to the physical Ethernet port, so every frame from the board vanishes at the host interface.
Switching the single virtual adapter to automatic Bridged mode creates a subtle trap on laptops. Hypervisors set to Auto-bridging frequently bind to the host Wi-Fi adapter, where standard 802.11 client frames carry only three MAC address fields and access points silently drop packets whose source MAC differs from the authenticated laptop radio. At the same time, plugging in a CH340 (1a86:7523) USB-serial cable or resetting an i.MX6ULL board into Serial Download Protocol (0x15a2:0x0080) creates a fresh /dev node owned by root:root (0600) or root:dialout (0660), breaking unprivileged tools whenever a engineer relies on manual sudo or temporary chmod workarounds.
Figure 1.1a. Hardware EPT paging plus isolated NAT (WAN) and wired L2 Bridge (bench) paths eliminate MAC drops and USB re-enumeration permission loss.
mental model: Think of a hypervisor network and USB layer like a laboratory building's mailroom and badge desk: NAT acts like an outbound corporate mailroom where staff can mail letters out, yet couriers arriving from the hardware lab bench with no employee extension number are turned away at the lobby. A dedicated wired Bridge opens a direct loading-dock bay straight into the bench subnet, while udev acts as permanent badge-provisioning rules keyed to a device's manufacturer serial (idVendor:idProduct) rather than a visitor sticker (chmod) that falls off every time the device walks out and re-enters.
Where it stops working: Unlike physical doors, 802.11 Wi-Fi station interfaces enforce strict MAC-address framing at the radio link layer, and Linux udev evaluates keys across a hierarchy of parent sysfs kobjects where mixing ATTR and ATTRS from two distinct parent levels fails to match.
definition (Extended Page Tables (EPT) and Netlink uevent): Extended Page Tables (EPT on Intel VT-x, Rapid Virtualization Indexing on AMD-V) add a second hardware MMU translation stage mapping guest-physical addresses (gPA) to host-physical RAM (hPA), allowing KVM or VMware guests to compile the Linux kernel without trapping on guest page-table updates. When a USB device enumerates inside the guest, the Linux kernel emits a AF_NETLINK (NETLINK_KOBJECT_UEVENT) message to user-space systemd-udevd, which evaluates /etc/udev/rules.d/*.rules in lexical order before exposing the /dev character node.
- Step 1. Verify hardware virtualization flags and assign two distinct virtual NICs: NAT for internet and a wired-only Bridge for the target board.
- Step 2. Query sysfs attributes on the enumerated serial or Boot ROM device to extract exact hexadecimal idVendor and idProduct strings.
- Step 3. Write /etc/udev/rules.d/99-embedded-bench.rules separating boolean match keys (==) from mode, group, and symlink mutations (= / +=).
- Step 4. Reload the systemd-udevd rule cache, replay kernel uevents, and confirm non-root group access without unplugging the cable.
Figure 1.1b. Separate NAT WAN from wired L2 bridges and bind USB permissions via udev == matchers.
Inside KVM/VMware L2 Bridging and udev Operator Semantics
At the CPU and memory boundary, a Type-1/2 hypervisor (KVM/QEMU or VMware Workstation) executes guest Ring-0 Linux kernel instructions and Ring-3 compiler processes directly on physical cores using VT-x non-root operation. Whenever a gcc worker faults a new heap page, the hardware page-table walker traverses the 4-level guest CR3 hierarchy and resolves each intermediate guest physical address through the host EPT root pointer (EPTP), keeping parallel make -j$(nproc) builds within a few percent of bare-metal throughput.
At the I/O boundary, udev rule syntax is unforgiving because C-like operators carry distinct state-machine meanings. == and != are pure predicates (SUBSYSTEM=="tty"), whereas = overwrites a property (MODE="0660"), += appends to a list (SYMLINK+="ttyBENCH0"), and := locks a value against later rules (99-*.rules). Writing a single = on ATTR{idVendor} attempts an invalid attribute write instead of filtering, causing the rule either to fail or to match unintended devices! Furthermore, users added via usermod -aG dialout,plugdev $USER must start a fresh login session because supplementary GID arrays are inherited at login setgroups(2) time, not re-read dynamically by running shells.
Figure 1.1b. Exact operator distinction (== predicate vs = / += assignment) prevents silent wildcard matches and world-writable 0666 hazards.
| VM Network Mode | Host WAN / apt | Board -> Host TFTP/NFS | Engineering Verdict |
|---|---|---|---|
Single NIC (NAT) | Works via host SNAT | Blocked (board cannot address private NAT subnet) | Unsuitable for U-Boot TFTP or NFS rootfs |
Single NIC (Auto-Bridge) | Depends on LAN DHCP | Fails silently when hypervisor binds host 802.11 Wi-Fi | Fragile on laptops; breaks offline bench work |
Host-Only (vmnet1) | No WAN route | Guest-to-Host only; never reaches physical RJ45 port | Good for QEMU virtual boards, useless for real silicon |
Dual NIC (NAT + Pinned Wired Bridge) | Always online via eth0 | Direct L2 ARP / UDP / TCP over dedicated USB-LAN | Production gold standard for embedded bring-up |
learner@ksa:~/gl-e00/m01-l01$ bat -H 3 -H 7 99-embedded-bench.rules File: 99-embedded-bench.rules # /etc/udev/rules.d/99-embedded-bench.rules # 1. USB-UART serial console (CH340 1a86:7523 & CP2102 10c4:ea60) -> /dev/ttyBENCH0 SUBSYSTEM=="tty", ATTRS{idVendor}=="1a86", ATTRS{idProduct}=="7523", MODE="0660", GROUP="dialout", SYMLINK+="ttyBENCH0" SUBSYSTEM=="tty", ATTRS{idVendor}=="10c4", ATTRS{idProduct}=="ea60", MODE="0660", GROUP="dialout", SYMLINK+="ttyBENCH0" # 2. i.MX6ULL Boot ROM USB OTG Serial Download Protocol (SDP HID 15a2:0080) for UUU SUBSYSTEM=="usb", ATTR{idVendor}=="15a2", ATTR{idProduct}=="0080", MODE="0660", GROUP="plugdev", TAG+="uaccess"- Double-equals (==) predicates filter tty nodes strictly by parent USB VID:PID before = and += mutate node metadata.
- Boot ROM SDP recovery exposes raw USB interface 15a2:0080 (not a tty), so SUBSYSTEM=='usb' and GROUP='plugdev' govern UUU access.
udev(7) GL-E00 Quick Reference udev(7) NAME udev, udevadm - Linux kernel dynamic device management and rule verifier SYNOPSIS udevadm info -a -n /dev/ttyUSB0 sudo udevadm control --reload-rules && sudo udevadm trigger udevadm test $(udevadm info -q path -n /dev/ttyUSB0) OPERATORS == Compare key for equality (predicate; MUST be used on SUBSYSTEM/ATTR/ATTRS). != Compare key for inequality. = Assign value to key (MODE="0660", GROUP="dialout"), overwriting prior rules. += Append value to multi-string key (SYMLINK+="ttyBENCH0", TAG+="uaccess"). ERRORS & SECURITY Using = instead of == on idVendor turns a predicate into an attribute write fault. Avoid MODE="0666": world-writable USB/serial nodes let any local UID hijack U-Boot. Kernel Systems Academy Lesson 1.1 udev(7) GL-E00 quick reference · full manual page: man 7 udev Auditing VM Bridge Selection and udev Rules in Host C11
Before deploying workstation onboarding scripts across an engineering team, we can validate both hypervisor adapter bindings and /etc/udev/rules.d/ rule files deterministically in ISO C11. Our host verifier verify.c inspects candidate VM NIC topologies—confirming that a NAT WAN interface is paired with a wired 802.3 Ethernet bridge rather than an 802.11 Wi-Fi station—and parses raw udev clauses token by token.
Pay close attention to how audit_udev_line() distinguishes == match predicates from = assignments and parses the octal MODE string. It explicitly rejects single-= typos on SUBSYSTEM, ATTR, or ATTRS, requires 4-character hexadecimal idVendor/idProduct identifiers, and blocks world-writable (mode & 0002) permissions (0666). While this host program proves configuration invariants in user space, verifying physical xhci_hcd USB signal integrity and U-Boot serial framing still requires attaching the target board.
learner@ksa:~/gl-e00/m01-l01$ bat -H 37 -H 53 verify.c File: verify.c #define _POSIX_C_SOURCE 200809L #include <ctype.h> #include <stdio.h> #include <stdlib.h> #include <string.h> typedef struct { const char *name; int has_nat_wan; int has_wired_bridge; int bridges_wifi; } vm_net_cfg_t; static int verify_vm_topology(const vm_net_cfg_t *cfg) { if (!cfg->has_nat_wan) return -1; /* No outbound WAN for apt/git */ if (cfg->bridges_wifi) return -2; /* 802.11 station drops guest MAC */ if (!cfg->has_wired_bridge) return -3; /* Board L2 ARP/TFTP unreachable */ return 0; } static int is_hex4(const char *s) { if (strlen(s) != 4) return 0; for (int i = 0; i < 4; ++i) { if (!isxdigit((unsigned char)s[i])) return 0; } return 1; } static int audit_udev_line(const char *line, unsigned int *mode_out) { char buf[256]; snprintf(buf, sizeof(buf), "%s", line); int has_subsys = 0, has_vid = 0, has_pid = 0, has_grp = 0, has_mode = 0; *mode_out = 0; char *save = NULL; for (char *tok = strtok_r(buf, ",", &save); tok; tok = strtok_r(NULL, ",", &save)) { while (*tok == ' ' || *tok == '\t') tok++; int is_eq2 = (strstr(tok, "==") != NULL); if (strncmp(tok, "SUBSYSTEM", 9) == 0 || strncmp(tok, "ATTR", 4) == 0) { if (!is_eq2) return -10; /* Fatal: single '=' on match key */ } const char *q1 = strchr(tok, '"'); const char *q2 = q1 ? strchr(q1 + 1, '"') : NULL; if (!q1 || !q2 || (size_t)(q2 - q1 - 1) >= 32) return -11; char val[32]; memcpy(val, q1 + 1, (size_t)(q2 - q1 - 1)); val[q2 - q1 - 1] = '\0'; if (strncmp(tok, "SUBSYSTEM==", 11) == 0) has_subsys = 1; else if (strstr(tok, "{idVendor}==")) has_vid = is_hex4(val); else if (strstr(tok, "{idProduct}==")) has_pid = is_hex4(val); else if (strncmp(tok, "GROUP=", 6) == 0 && tok[6] == '"') has_grp = (val[0] != '\0'); else if (strncmp(tok, "MODE=", 5) == 0 && tok[5] == '"') { char *end = NULL; unsigned long m = strtoul(val, &end, 8); if (*end != '\0' || (m & 0002UL) != 0) return -12; /* Reject world-writable */ *mode_out = (unsigned int)m; has_mode = 1; } } return (has_subsys && has_vid && has_pid && has_grp && has_mode) ? 0 : -13; } int main(void) { vm_net_cfg_t bad_vm = {"auto-wifi-bridge", 0, 0, 1}; vm_net_cfg_t good_vm = {"nat+usb-eth-bridge", 1, 1, 0}; const char *good_uart = "SUBSYSTEM==\"tty\", ATTRS{idVendor}==\"1a86\", ATTRS{idProduct}==\"7523\", " "MODE=\"0660\", GROUP=\"dialout\", SYMLINK+=\"ttyBENCH0\""; const char *bad_op = "SUBSYSTEM==\"usb\", ATTR{idVendor}=\"15a2\", ATTR{idProduct}==\"0080\", " "MODE=\"0660\", GROUP=\"plugdev\""; const char *bad_mode = "SUBSYSTEM==\"tty\", ATTRS{idVendor}==\"1a86\", ATTRS{idProduct}==\"7523\", " "MODE=\"0666\", GROUP=\"dialout\""; unsigned int m_good = 0, m_bad1 = 0, m_bad2 = 0; int r_vm_bad = verify_vm_topology(&bad_vm); int r_vm_ok = verify_vm_topology(&good_vm); int r_u_ok = audit_udev_line(good_uart, &m_good); int r_u_op = audit_udev_line(bad_op, &m_bad1); int r_u_md = audit_udev_line(bad_mode, &m_bad2); printf("vm_check: auto_wifi=%d dual_nic_wired=%d\n", r_vm_bad, r_vm_ok); printf("udev_check: ch340_0660=%d (mode=0%03o) single_eq=%d mode_0666=%d\n", r_u_ok, m_good, r_u_op, r_u_md); return (r_vm_bad == -1 && r_vm_ok == 0 && r_u_ok == 0 && r_u_op == -10 && r_u_md == -12) ? 0 : 1; }- Rejects single '=' on SUBSYSTEM/ATTR/ATTRS keys before a silent assignment bug ever reaches /etc/udev/rules.d/.
- Parses MODE in base-8 and rejects any rule setting the world-writable o+w bit (0002, such as 0666).
Verifying Rule Diagnostics and System Call Output
Compile verify.c under strict -std=c11 -Wall -Wextra -Werror and inspect both stdout and the strace syscall stream. Notice how audit_udev_line() accepts the 1a86:7523 0660 dialout rule (rc = 0), immediately flags the single-= typo on ATTR{idVendor}="15a2" with -10, and blocks the world-writable MODE="0666" rule with -12. In strace, glibc buffers the two formatted diagnostic lines into a single write(1, ...) syscall when stdout is non-interactive, terminating cleanly with exit_group(0).
learner@ksa:~/gl-e00/m01-l01gcc -std=c11 -Wall -Wextra -Werror verify.c -o verifylearner@ksa:~/gl-e00/m01-l01./verifyvm_check: auto_wifi=-1 dual_nic_wired=0udev_check: ch340_0660=0 (mode=0660) single_eq=-10 mode_0666=-12learner@ksa:~/gl-e00/m01-l01learner@ksa:~/gl-e00/m01-l01strace -e trace=write,exit_group ./verifywrite(1, "vm_check: auto_wifi=-1 dual_nic_"..., 105) = 105exit_group(0) = ?+++ exited with 0 +++Common Virtualization & USB Hotplug Failure Modes
A reliable embedded Linux workstation separates network planes and eliminates manual root interventions on device nodes. Keep Adapter 1 on NAT so package updates work on any network, pin Adapter 2 strictly to the physical USB-Ethernet controller wired to your target board, and manage both serial consoles (1a86:7523) and Boot ROM SDP interfaces (15a2:0080) through version-controlled /etc/udev/rules.d/ files.
Mixing ATTRS Parent Walks Across Unrelated sysfs Ancestors:
- Symptom:
udevadm testreports zero matching rules even though bothATTRS{idVendor}and an interface-levelATTRS{bInterfaceNumber}exist inudevadm info -a. - Root Cause:
systemd-udevdrequires allATTRS{...}predicates within a single rule to match on the same parentsysfsdevice node rather than cherry-picking attributes from two different ancestor levels. - Fix: Match
SUBSYSTEM=="tty"at the leaf node and keepATTRS{idVendor}plusATTRS{idProduct}on the singleusb-serialorusb_deviceparent, or useENV{ID_VENDOR_ID}=="1a86"populated byusb_id.
Running Terminal Emulators or Flashing Tools Under sudo:
- Symptom: After running
sudo minicom -sorsudo uuu, subsequent non-root runs fail to save configuration files or build artifacts in$HOMEwithPermission denied. - Root Cause: Invoking interactive tools under
sudopreserves$HOMEon many distributions while running asUID 0, creating root-owned dotfiles (~/.minirc.dfl) and masking missingdialout/plugdevgroup membership. - Fix: Fix
/etc/udev/rules.d/permissions to0660withGROUP="dialout"orGROUP="plugdev", add your user viasudo usermod -aG dialout,plugdev $USER, re-login soid -Gnshows the new groups, and chown any root-owned$HOMEfiles back.
Guided Practice
Extend verify.c to parse an optional SYMLINK+="ttyBENCH0" token and reject rules that use SYMLINK="ttyBENCH0" (overwrite =) instead of SYMLINK+="ttyBENCH0" (append +=). Why does overwriting SYMLINK with = break systemd persistent paths such as /dev/serial/by-id/... created by earlier 60-serial.rules?
Independent Practice
Write a two-rule udev snippet and matching C11 unit test for a dual-channel FT2232H (0403:6010) JTAG + UART debug probe where interface 00 (ENV{ID_USB_INTERFACE_NUM}=="00") is bound to GROUP="plugdev" for OpenOCD JTAG and interface 01 creates SYMLINK+="ttyJTAG_UART" under GROUP="dialout", verifying zero world-writable bits.
Verification Checks
? check 1 · Your Linux VM uses a single network adapter set to 'Bridged (Automatic)' on a laptop connected to corporate Wi-Fi and a USB-Ethernet dongle wired to an i.MX6ULL board. U-Boot prints ARP Retry count exceeded. What is the root cause?
- [ ] Linux udev defaults to blocking Ethernet link-layer broadcasts until dialout group membership is active.
- [x] Automatic bridging bound to the 802.11 Wi-Fi station interface, and the USB-Ethernet bench port never received L2 frames from the guest.
- [ ] KVM Extended Page Tables (EPT) block raw ARP EtherType 0x0806 frames unless IOMMU passthrough is enabled.
- [ ] U-Boot requires NAT port-forwarding on TCP port 69 before ARP broadcasts can resolve.
Answer: Automatic bridging bound to the 802.11 Wi-Fi station interface, and the USB-Ethernet bench port never received L2 frames from the guest.
Why: Hypervisor Auto-Bridging frequently selects the primary host route (Wi-Fi) rather than an unrouted USB-Ethernet bench dongle, and 802.11 client stations cannot bridge spoofed guest MAC addresses.
Common misconception: Assuming 'Bridged (Automatic)' bridges all physical host adapters simultaneously or works transparently over 802.11 client Wi-Fi.
? check 2 · An engineer writes SUBSYSTEM=="usb", ATTR{idVendor}="15a2", ATTR{idProduct}=="0080", MODE="0660", GROUP="plugdev" in /etc/udev/rules.d/99-sdp.rules, reloads udev, and finds UUU still gets LIBUSB_ERROR_ACCESS. Why?
- [x]
ATTR{idVendor}="15a2"uses the assignment operator=instead of the equality predicate==, invalidating the rule match. - [ ] Hexadecimal USB vendor IDs in udev rules must always carry a leading
0xprefix (0x15a2). - [ ] Rules numbered
99-*run before50-udev-default.rules, so default0664 root:rootpermissions overwrite0660. - [ ]
SUBSYSTEM=="usb"requiresMODE="0777"because USB character endpoints require execute permission.
Answer: ATTR{idVendor}="15a2" uses the assignment operator = instead of the equality predicate ==, invalidating the rule match.
Why: In udev syntax, == tests equality while = attempts to write to a sysfs attribute or property; idVendor is a read-only USB descriptor field requiring == and bare 4-digit lowercase hex without 0x.
Common misconception: Treating single = and double == as interchangeable or misremembering lexical rule order (99-* runs AFTER 50-*).
? check 3 · After adding yourself to dialout via sudo usermod -aG dialout $USER and reloading udev, opening /dev/ttyUSB0 (crw-rw---- 1 root dialout) in your existing terminal still fails with Permission denied. What is the fastest causal check?
- [ ] Reboot the target ARMv7-A board so UART1 renegotiates group credentials over RS-232 DTR/RTS.
- [ ] Change the udev rule to
MODE="0666"because Linux ignores supplementary groups on character devices. - [ ] Delete
/dev/ttyUSB0withrmand recreate it manually usingmknod /dev/ttyUSB0 c 188 0. - [x] Run
id -Gnin that shell; existing login processes retain the supplementary GID list captured at login until a new login session ornewgrp dialoutstarts.
Answer: Run id -Gn in that shell; existing login processes retain the supplementary GID list captured at login until a new login session or newgrp dialout starts.
Why: Process credentials (cred->group_info) are inherited from parent to child at fork() time; usermod edits /etc/group on disk without mutating already-running shell processes.
Common misconception: Believing /etc/group is consulted dynamically by the kernel VFS on every open(2) call.
Summary
- Hardware virtualization pairs VT-x or AMD-V guest execution modes with Extended Page Tables (EPT) so guest virtual-to-host-physical translations resolve in silicon without per-fault hypervisor traps.
- A dual-adapter VM layout uses Adapter 1 in NAT mode for outbound WAN package traffic and Adapter 2 bridged exclusively to a wired USB-Ethernet bench NIC for L2 ARP, TFTP, and NFS traffic.
- Declarative /etc/udev/rules.d/ rules match SUBSYSTEM and hexadecimal idVendor/idProduct attributes with == to assign 0660 dialout or plugdev group ownership across every USB hotplug cycle.
- USB Boot ROM recovery tools re-enumerate target silicon from SDP HID mode (15a2:0080) into Fastboot endpoints, requiring persistent udev rules and hypervisor vendor-ID filters instead of one-shot chmod 666 hacks.
Step sequence — frame strip: steps_m01_l01
Verify hardware virtualization flags and assign two distinct virtual NICs: NAT for internet and a wired-only Bridge for the target board.
reveals: step1
highlights: step1
Query sysfs attributes on the enumerated serial or Boot ROM device to extract exact hexadecimal idVendor and idProduct strings.
reveals: step2
highlights: step2
Write /etc/udev/rules.d/99-embedded-bench.rules separating boolean match keys (==) from mode, group, and symlink mutations (= / +=).
reveals: step3
highlights: step3
Reload the systemd-udevd rule cache, replay kernel uevents, and confirm non-root group access without unplugging the cable.
reveals: step4
highlights: step4
What you'll learn
- Contrast kernel n_tty signal/canonical processing on /dev/pts/N against raw 8N1 serial byte streams on /dev/ttyUSB0.
- Trace exact file-descriptor table mutations across dup2(1, 2) redirection orders and pipefail shell pipelines.
- Prevent sudo secure_path cross-compiler loss by separating unprivileged compilation from staged root installation.
Where Bytes and Signals Actually Go Inside a Terminal Window
When you open an SSH session or a desktop terminal tab (Ctrl-Shift-T) and run ps -ef, the TTY column reports pts/0 rather than a hardware UART. Every terminal tab allocates a pseudoterminal (PTY) pair inside the Linux kernel: the terminal emulator holds the master file descriptor from /dev/ptmx, the shell attaches stdin (0), stdout (1), and stderr (2) to /dev/pts/0, and the n_tty line discipline sits in between.
Pressing Ctrl-C sends byte 0x03; n_tty intercepts it under ISIG mode and delivers SIGINT to the local foreground process group. By contrast, a serial program (picocom or minicom) puts its local /dev/ttyUSB0 descriptor into cfmakeraw() mode so 0x03 travels across the physical wire to interrupt U-Boot or a target process!
Two daily build failures stem directly from how shells wire descriptors and environments around child processes. Writing make 2>&1 >build.log leaves every gcc error on screen and absent from build.log, while make | tee build.log reports exit status 0 in CI even when compilation aborts! Worse, typing sudo make ARCH=arm CROSS_COMPILE=arm-linux-gnueabihf- suddenly fails with arm-linux-gnueabihf-gcc: Command not found even though which found the compiler one second earlier.
Figure 1.2a. Redirection operators mutate the child file-descriptor table sequentially from left to right; 2>&1 copies the current target of fd 1, not its future target.
mental model: Picture fd 1 (stdout) and fd 2 (stderr) as two clipboards holding room numbers—both initially say Room pts/0. Writing 2>&1 does not glue the two clipboards together forever; it tells the clerk: copy whatever room number is written on Clipboard 1 right now onto Clipboard 2. If you copy Clipboard 1 onto Clipboard 2 first (2>&1, both say pts/0) and then erase Clipboard 1 to write build.log (>build.log), Clipboard 2 still says pts/0!
Where it stops working: The clipboard metaphor shows pointer assignment order, whereas in the Linux kernel dup2(1, 2) increments the reference count on a shared struct file description—meaning fd 1 and fd 2 also share a single atomic f_pos file offset rather than overwriting each other at byte 0.
definition (Open File Description Sharing (dup2) and sudo secure_path): POSIX separates a process-private file descriptor integer (0, 1, 2) from the kernel-wide open file description (struct file holding f_pos and O_APPEND flags). Calling dup2(1, 2) closes fd 2 and points slot 2 at the exact struct file currently referenced by slot 1. Separately, sudo enforces privilege-escalation hygiene via Defaults env_reset and Defaults secure_path in /etc/sudoers, discarding caller PATH and LD_LIBRARY_PATH variables so an unprivileged user cannot trick a root command into executing a trojan ls or gcc placed in /tmp.
- Step 1. Enable set -euo pipefail at the top of build and deployment scripts so downstream loggers like tee cannot mask compiler failures.
- Step 2. Redirect fd 1 to the target file before evaluating 2>&1 so stderr inherits the newly opened log description.
- Step 3. Run all kernel, U-Boot, and rootfs compilation steps as an unprivileged user so cross-compilers remain in PATH and object files stay user-owned.
- Step 4. Stage kernel modules into an unprivileged INSTALL_MOD_PATH directory instead of running sudo make against the host /lib/modules tree.
Figure 1.2b. Order >log before 2>&1, set pipefail on build pipes, and never compile under sudo.
Kernel File Table Mechanics, Pipeline Exit Codes & sudoers Scrubbing
Inside fs/file.c, each task holds current->files->fdt->fd[], an array mapping small integers (0, 1, 2) to struct file * pointers. Notice why cmd >build.log 2>build.log (opening the same file twice independently) is a classic bug: two separate open() calls allocate two independent struct file objects, each starting at f_pos = 0, so stdout and stderr overwrite one another's bytes! Using >build.log 2>&1 calls open() once and dup2(1, 2) once, sharing a single f_pos cursor.
When chaining processes with | (make -j8 2>&1 | tee build.log), the shell creates an anonymous pipe2() buffer, binds the left child's fd 1 and fd 2 to the pipe write end, and binds tee's fd 0 to the read end. By POSIX default, $? equals only the rightmost command's exit status (tee returns 0!), whereas set -o pipefail surfaces the rightmost non-zero exit code across the entire pipeline.
Finally, /etc/sudoers compiles Defaults secure_path="/usr/local/sbin:...:/bin". Even sudo -E refuses to preserve PATH when secure_path is active, explaining why cross-compilation always belongs in unprivileged user space.
Figure 1.2b. Sharing one struct file via dup2(1, 2) serializes f_pos offsets, while pipefail preserves left-hand compiler failures.
| Shell Construct | fd 1 Target | fd 2 Target | Failure / Production Consequence | |
|---|---|---|---|---|
make >build.log 2>&1 | build.log (struct file A) | build.log (struct file A) | Unified chronological log; single shared f_pos offset | |
make 2>&1 >build.log | build.log (struct file A) | /dev/pts/N (terminal) | Errors vanish from build.log; CI log lacks compiler diagnostics | |
make >build.log 2>build.log | build.log (struct file A) | build.log (struct file B) | Two independent f_pos = 0 cursors overwrite each other! | |
| `make 2>&1 | tee build.log (no pipefail`) | Pipe -> tee (pts/N + log) | Pipe -> tee (pts/N + log) | Log is complete, but $? is 0 (tee) even when make fails! |
learner@ksa:~/gl-e00/m01-l02$ bat -H 2 -H 12 safe_cross_build.sh File: safe_cross_build.sh #!/usr/bin/env bash set -euo pipefail export PATH="/opt/toolchains/arm-gnu-toolchain/bin:${PATH}" STAGE_DIR="${PWD}/_rootfs_stage" LOG_FILE="${PWD}/build_kernel.log" # 1. Unprivileged cross-build: stdout + stderr share pipe into tee; pipefail guards rc make ARCH=arm CROSS_COMPILE=arm-linux-gnueabihf- -j"$(nproc)" zImage modules dtbs 2>&1 | tee "${LOG_FILE}" # 2. Stage modules without sudo (preserves CROSS_COMPILE in PATH and user file ownership) make ARCH=arm CROSS_COMPILE=arm-linux-gnueabihf- INSTALL_MOD_PATH="${STAGE_DIR}" modules_install >"${STAGE_DIR}.log" 2>&1- set -euo pipefail ensures a non-zero exit from make propagates past tee instead of reporting success.
- INSTALL_MOD_PATH stages /lib/modules unprivileged, avoiding sudo secure_path stripping of arm-linux-gnueabihf-.
dup2(2) GL-E00 Quick Reference dup2(2) NAME dup2, pts, sudoers - duplicate file descriptors, PTY pairs, and sudo PATH policy SYNOPSIS #include <unistd.h> int dup2(int oldfd, int newfd); DESCRIPTION dup2() makes newfd refer to the same open file description (struct file) as oldfd. In POSIX sh: >file 2>&1 opens file on fd 1, then calls dup2(1, 2). 2>&1 >file calls dup2(1, 2) while fd 1 is still /dev/pts/N, then reopens fd 1. NOTES ON SUDOERS /etc/sudoers 'Defaults secure_path' overrides PATH even under 'sudo -E'. Never run 'sudo make' on Linux kernel or U-Boot trees; stage via INSTALL_MOD_PATH. Kernel Systems Academy Lesson 1.2 dup2(2) GL-E00 quick reference · full manual page: man 2 dup2 Proving dup2() Redirection Order With Real Kernel Pipes in C11
Rather than memorizing shell folklore, we can execute the exact kernel pipe() and dup2() sequences in ISO C11 and measure how many bytes arrive at the terminal stream versus the log stream. In verify.c, run_redirection_case() allocates two real kernel pipes—one standing in for /dev/pts/0 and one standing in for build.log—saves original stdout/stderr via dup(), applies dup2() in both >log 2>&1 and 2>&1 >log orders, and writes OUT\n to fd 1 plus ERR\n to fd 2.
We also test sudo secure_path scrubbing by verifying whether /opt/toolchains/arm/bin survives a reset to /usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin. Running under strace -e trace=pipe2,dup2,write,read,close exposes every single kernel descriptor re-binding step directly in the captured trace.
learner@ksa:~/gl-e00/m01-l02$ bat -H 25 -H 29 verify.c File: verify.c #define _POSIX_C_SOURCE 200809L #include <stdio.h> #include <string.h> #include <unistd.h> static int drain_pipe(int rfd, char *buf, size_t cap) { ssize_t n = read(rfd, buf, cap - 1); if (n < 0) n = 0; buf[n] = '\0'; return (int)n; } static int run_redirection_case(int log_before_dup, char *pts_out, char *log_out) { int pts_p[2], log_p[2]; if (pipe(pts_p) != 0 || pipe(log_p) != 0) return -1; int saved_out = dup(STDOUT_FILENO); int saved_err = dup(STDERR_FILENO); /* Initial terminal state: both fd 1 and fd 2 point to pts_p[1] */ dup2(pts_p[1], STDOUT_FILENO); dup2(pts_p[1], STDERR_FILENO); if (log_before_dup) { /* Equivalent to: cmd >build.log 2>&1 */ dup2(log_p[1], STDOUT_FILENO); dup2(STDOUT_FILENO, STDERR_FILENO); } else { /* Equivalent to: cmd 2>&1 >build.log */ dup2(STDOUT_FILENO, STDERR_FILENO); dup2(log_p[1], STDOUT_FILENO); } const char *m_out = "OUT\n"; const char *m_err = "ERR\n"; if (write(STDOUT_FILENO, m_out, 4) != 4) return -2; if (write(STDERR_FILENO, m_err, 4) != 4) return -3; /* Restore real stdout/stderr and close write ends before draining */ dup2(saved_out, STDOUT_FILENO); dup2(saved_err, STDERR_FILENO); close(saved_out); close(saved_err); close(pts_p[1]); close(log_p[1]); drain_pipe(pts_p[0], pts_out, 32); drain_pipe(log_p[0], log_out, 32); close(pts_p[0]); close(log_p[0]); return 0; } static int path_contains_dir(const char *path_env, const char *needle) { size_t nlen = strlen(needle); const char *p = path_env; while (*p) { const char *sep = strchr(p, ':'); size_t slen = sep ? (size_t)(sep - p) : strlen(p); if (slen == nlen && memcmp(p, needle, nlen) == 0) return 1; if (!sep) break; p = sep + 1; } return 0; } int main(void) { char pts_ok[32] = {0}, log_ok[32] = {0}; char pts_bad[32] = {0}, log_bad[32] = {0}; if (run_redirection_case(1, pts_ok, log_ok) != 0) return 1; if (run_redirection_case(0, pts_bad, log_bad) != 0) return 1; const char *user_path = "/opt/toolchains/arm/bin:/usr/bin:/bin"; const char *sudo_secure_path = "/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin"; int in_user = path_contains_dir(user_path, "/opt/toolchains/arm/bin"); int in_sudo = path_contains_dir(sudo_secure_path, "/opt/toolchains/arm/bin"); printf("case_gt_log_2gt1: pts_bytes=%zu log=[%.3s+%.3s] (%zuB)\n", strlen(pts_ok), log_ok, log_ok + 4, strlen(log_ok)); printf("case_2gt1_gt_log: pts=[%.3s] (%zuB) log=[%.3s] (%zuB)\n", pts_bad, strlen(pts_bad), log_bad, strlen(log_bad)); printf("cross_cc_visible: user_shell=%d sudo_secure_path=%d\n", in_user, in_sudo); return (strlen(pts_ok) == 0 && strcmp(log_ok, "OUT\nERR\n") == 0 && strcmp(pts_bad, "ERR\n") == 0 && strcmp(log_bad, "OUT\n") == 0 && in_user == 1 && in_sudo == 0) ? 0 : 1; }- cmd >log 2>&1 binds fd 1 to log_p[1] first, so dup2(1, 2) routes both OUT and ERR (8 bytes) into log_p.
- cmd 2>&1 >log duplicates fd 1 while it still points to pts_p[1], leaking ERR (4 bytes) to the terminal.
Inspecting Real pipe2() and dup2() Syscalls Under strace
Examine the captured shell output and strace trace below. In case_gt_log_2gt1, 0 bytes leak to pts and all 8 bytes (OUT+ERR) arrive sequentially in log. In case_2gt1_gt_log, ERR (4B) leaks onto pts while log receives only OUT (4B). Reading the strace window confirms the kernel sequence directly: pipe2() allocates descriptor pairs, dup2() rewrites fd 1 and fd 2 in exact call order, and read() drains each buffer deterministically.
learner@ksa:~/gl-e00/m01-l02gcc -std=c11 -Wall -Wextra -Werror verify.c -o verifylearner@ksa:~/gl-e00/m01-l02./verifycase_gt_log_2gt1: pts_bytes=0 log=[OUT+ERR] (8B)case_2gt1_gt_log: pts=[ERR] (4B) log=[OUT] (4B)cross_cc_visible: user_shell=1 sudo_secure_path=0learner@ksa:~/gl-e00/m01-l02learner@ksa:~/gl-e00/m01-l02strace -e trace=pipe2,dup2,write,read,close \./verifyclose(3) = 0read(3, "\177ELF\2\1\1\3\0\0\0\0\0\0\0\0\3\0>\0\1\0\0\0\220\243\2\0\0\0\0\0"..., 832) = 832close(3) = 0pipe2([3, 4], 0) = 0pipe2([5, 6], 0) = 0dup2(4, 1) = 1dup2(4, 2) = 2dup2(6, 1) = 1dup2(1, 2) = 2write(1, "OUT\n", 4) = 4write(2, "ERR\n", 4) = 4dup2(7, 1) = 1dup2(8, 2) = 2close(7) = 0close(8) = 0close(4) = 0close(6) = 0read(3, "", 31) = 0read(5, "OUT\nERR\n", 31) = 8close(3) = 0close(5) = 0pipe2([3, 4], 0) = 0pipe2([5, 6], 0) = 0dup2(4, 1) = 1dup2(4, 2) = 2dup2(1, 2) = 2dup2(6, 1) = 1write(1, "OUT\n", 4) = 4write(2, "ERR\n", 4) = 4dup2(7, 1) = 1dup2(8, 2) = 2close(7) = 0close(8) = 0close(4) = 0close(6) = 0read(3, "ERR\n", 31) = 4read(5, "OUT\n", 31) = 4close(3) = 0close(5) = 0write(1, "case_gt_log_2gt1: pts_bytes=0 lo"..., 147) = 147+++ exited with 0 +++Subtle Redirection, PTY Signal & sudo Build Traps
Understanding descriptor tables and line disciplines eliminates mysterious terminal behavior across both host builds and target UART consoles. Always pair 2>&1 | tee with set -euo pipefail, keep U-Boot and Linux kernel builds completely out of sudo, and distinguish local PTY SIGINT handling from raw UART wire bytes.
Pressing Ctrl-C Kills the Host Serial Program Instead of Target ping:
- Symptom: While logged into a target board over a naive script (
cat /dev/ttyUSB0), pressingCtrl-Ckills the localcatcommand on the host instead of stoppingpingon the board. - Root Cause: The host shell's
/dev/pts/Nn_ttyline discipline still hasISIGenabled, so0x03generatesSIGINTlocally on the host before ever reaching/dev/ttyUSB0. - Fix: Use a dedicated serial terminal (
picocom -b 115200 /dev/ttyBENCH0orminicom) that puts the local PTY intocfmakeraw()(~ISIG & ~ICANON & ~ECHO), forwarding0x03verbatim over UART and reserving an escape chord (Ctrl-A Ctrl-X) for host exit.
Root-Owned Build Artifacts After One Accidental sudo make:
- Symptom: Subsequent normal
makeinvocations fail withFatal error: can't create scripts/basic/.fixdep.d: Permission denied. - Root Cause: A single
sudo makeleft.o,.cmd, andinclude/config/directories owned byUID 0:0inside your working tree, blocking unprivileged compiler updates. - Fix: Reclaim ownership once via
sudo chown -R "$(id -u):$(id -g)" ., and never invokesudoformenuconfig,zImage,dtbs, ormodulesbuilds.
Guided Practice
Modify verify.c to add a third helper run_dual_open_case() that opens a temporary file twice (fd_a = open(path, O_WRONLY|O_CREAT|O_TRUNC, 0600) and fd_b = open(path, O_WRONLY)) without O_APPEND, binds fd 1 to fd_a and fd 2 to fd_b, and writes "STDOUT_LINE\n" followed by "ERR\n". Inspect the resulting file bytes to see "ERR\nUT_LINE\n" clobbering at byte offset 0!
Independent Practice
Write a POSIX C11 wrapper using fork(), pipe(), dup2(), and waitpid() that runs two child stages (stage1 exiting with code 2 and stage2 exiting with code 0) and implements pipefail semantics in C by returning the rightmost non-zero WEXITSTATUS.
Verification Checks
? check 1 · A CI script runs ./build_uboot.sh 2>&1 >/tmp/uboot.log. When compilation fails with an undefined symbol error, /tmp/uboot.log contains Makefile echo lines but zero linker error messages. Why?
- [x]
2>&1ran first and pointedfd 2at the original stdout (the CI terminal), after which>/tmp/uboot.logredirected onlyfd 1. - [ ] GNU
ldwrites undefined symbol errors directly to/dev/ttyviaioctlinstead ofSTDERR_FILENO(fd 2). - [ ] POSIX shells evaluate redirections from right to left, so
2>&1overwrote/tmp/uboot.logwith an empty descriptor. - [ ]
/tmphas the sticky bit (01777) set, which blocksfd 2writes from child processes.
Answer: 2>&1 ran first and pointed fd 2 at the original stdout (the CI terminal), after which >/tmp/uboot.log redirected only fd 1.
Why: Redirections execute strictly left to right: 2>&1 duplicates whatever fd 1 points to at that moment, so >/tmp/uboot.log must appear BEFORE 2>&1.
Common misconception: Thinking 2>&1 creates a permanent symbolic alias to 'whatever fd 1 eventually becomes' rather than an immediate dup2(1, 2) call.
? check 2 · Why does sudo -E make ARCH=arm CROSS_COMPILE=arm-linux-gnueabihf- still fail to find arm-linux-gnueabihf-gcc installed in /opt/arm-gcc/bin on Ubuntu and Debian hosts?
- [ ] The Linux kernel
execve()syscall deletesPATHautomatically whenevereuid == 0. - [ ]
CROSS_COMPILEvariables cannot contain hyphens when passed throughsudo. - [ ] ARM cross-compilers check
getuid()at startup and refuse to run as root. - [x]
Defaults secure_pathin/etc/sudoersexplicitly overridesPATHwith a fixed system directory list even when-E(--preserve-env) is passed.
Answer: Defaults secure_path in /etc/sudoers explicitly overrides PATH with a fixed system directory list even when -E (--preserve-env) is passed.
Why: When /etc/sudoers defines secure_path, sudo replaces PATH unconditionally for security against untrusted user directories, regardless of -E.
Common misconception: Assuming sudo -E bypasses /etc/sudoers secure_path enforcement.
? check 3 · Without set -o pipefail, what exit code ($?) does make -j8 zImage 2>&1 | tee build.log return when gcc aborts with a syntax error?
- [ ]
130, becausen_ttysynthesizesSIGINTwheneverfd 2is merged into a pipe. - [ ]
1, because POSIX pipes return the bitwise OR of every stage's exit code by default. - [x]
0, becauseteesuccessfully copied the error text to stdout andbuild.logand exited cleanly. - [ ]
2, because GNUmakesendsSIGPIPEforward toteeon compiler failure.
Answer: 0, because tee successfully copied the error text to stdout and build.log and exited cleanly.
Why: By default, POSIX shells set $? to the exit status of the last command in a pipeline (tee), completely hiding failures in upstream compilation stages unless pipefail is enabled.
Common misconception: Assuming a shell pipeline automatically fails when its first command exits non-zero.
Summary
- A pseudoterminal pairs a /dev/ptmx master descriptor owned by the terminal emulator with a /dev/pts/N replica governed by the Linux kernel n_tty line discipline.
- Shell redirections execute strictly left to right via dup2(oldfd, newfd): >build.log 2>&1 sends both streams to build.log, whereas 2>&1 >build.log leaves stderr pointing at the terminal.
- Enabling set -euo pipefail causes a pipeline such as make 2>&1 | tee build.log to return the non-zero exit code of the failing build stage instead of tee's zero exit status.
- Default /etc/sudoers env_reset and secure_path policies replace user PATH variables during sudo execution, hiding user-installed ARM cross-toolchains unless builds run unprivileged with DESTDIR or INSTALL_MOD_PATH.
Step sequence — frame strip: steps_m01_l02
Enable set -euo pipefail at the top of build and deployment scripts so downstream loggers like tee cannot mask compiler failures.
reveals: step1
highlights: step1
Redirect fd 1 to the target file before evaluating 2>&1 so stderr inherits the newly opened log description.
reveals: step2
highlights: step2
Run all kernel, U-Boot, and rootfs compilation steps as an unprivileged user so cross-compilers remain in PATH and object files stay user-owned.
reveals: step3
highlights: step3
Stage kernel modules into an unprivileged INSTALL_MOD_PATH directory instead of running sudo make against the host /lib/modules tree.
reveals: step4
highlights: step4
What you'll learn
- Operate Vim across Normal, Insert, and Ex modes while auditing hard tabs with :set list in Makefiles and kernel configs.
- Construct NUL-delimited find -print0 | xargs -0 and grep -rn pipelines to locate Device Tree bindings and driver symbols safely.
- Implement a C11 workbench auditor verifying udev rules, dup2 redirection states, and colon-delimited PATH security invariants.
Surviving Headless Bring-Up Servers and 80,000-File Source Trees
Sooner or later every embedded engineer SSHes into a build server, a stripped Docker container, or a target BusyBox console where no GUI editor exists and /etc/fstab or a Device Tree source file needs an immediate surgical fix. vim (and BusyBox vi) models editing as an explicit finite-state machine (FSM): sessions always start in Normal mode where keys are motion and operator verbs (gg, G, /compatible, dd, ci", u).
Pressing i, a, or o enters Insert mode for raw text, Esc returns to Normal mode, and : enters Command-line (Ex) mode (:w, :q!, :%s/old/new/gc, :set list). Running :set list immediately exposes whether a Makefile recipe starts with a genuine 0x09 hard tab (^I) or spaces that trigger Makefile:14: *** missing separator. Stop.
Equally critical is searching huge trees (Linux kernel 6.12 exceeds 82,000 files) and auditing PATH strings safely. Naive shell loops like grep foo $(find . -name '*.c') overflow the kernel execve() ARG_MAX ceiling (E2BIG) and split filenames on spaces, while a single stray trailing colon in export PATH="/opt/arm/bin:$PATH:" silently adds . (the current working directory!) to command lookup!
Figure 1.3a. NUL (0x00) is the sole byte value illegal inside POSIX path components, making -print0 | xargs -0 immune to spaces and quotes.
mental model: Using newline-delimited find | xargs on arbitrary trees is like shipping parts in a crate where commas separate item names, even though product labels themselves can contain commas! Switching to find -print0 | xargs -0 seals each path with 0x00—a physical bulkhead byte that the Linux kernel VFS forbids inside any filename—while scanning PATH with strchr instead of strtok inspects every empty crate slot (::) rather than skipping past empty compartments.
Where it stops working: For interactive human queries in clean Git repositories, grep -rn --include='*.[ch]' or git grep -n avoids spawning find + xargs altogether by walking directory dentries inside a single process without building giant argv[] vectors.
definition (Empty PATH Segment (Implicit '.') and Vim Swap Recovery): Under historical POSIX.1 shell lookup rules, an empty colon-separated field in PATH—whether leading (:/usr/bin), adjacent (usr/bin::/bin), or trailing (/usr/bin:)—is interpreted as . (the current working directory). Writing export PATH="/opt/arm/bin:$PATH" when $PATH was unset expands to "/opt/arm/bin:", letting an untrusted source archive hijack make or ls! Meanwhile, vim protects active edits via .filename.swp journals; if an SSH link drops, inspect differences with vim -r filename before removing stale swap files.
- Step 1. Open target files directly at the diagnostic line (+42), run :set list in Ex mode to distinguish ^I tabs from spaces, and write atomically.
- Step 2. Search kernel subsystems by compatible string or symbol using grep -rn --include to skip compiled .o and .ko binaries.
- Step 3. Pipe find -print0 into xargs -0 -r whenever passing file lists to external tools across large directory trees.
- Step 4. Execute the Module 1 TAP-13 studio to verify all host workbench invariants and record CLOCK_MONOTONIC percentiles.
Figure 1.3b. Use :set list for tabs, -print0 | xargs -0 for paths, and strchr to audit PATH.
Inside Vim State Transitions, VFS Filename Bytes & C11 PATH Scanning
In Linux kernel fs/namei.c, path resolution splits strings solely on '/' (0x2F) and terminates C strings on '\0' (0x00); literally every other byte 0x01..0xFF (including ' ' 0x20, '\t' 0x09, and '\n' 0x0A) can legally exist inside an ext4 directory entry! That single kernel invariant explains why find ... -print0 paired with xargs -0 -r is mathematically lossless, whereas line-oriented pipelines break on embedded vendor drops containing spaces like Schematics Rev 1.2/.
Notice the classic C11 bug waiting inside our workbench PATH auditor: if an engineer uses strtok(buf, ":") to split PATH="/usr/bin::/bin", ISO C strtok() treats consecutive delimiters "::" as a single separator and returns only "/usr/bin" and "/bin", completely missing the empty segment ("" -> current directory .)! Scanning explicitly with strchr(cursor, ':') inspects seg_len == 0, catching leading :, interior ::, and trailing : every time—hence shell scripts must write PATH="/new/dir${PATH:+:$PATH}".
Figure 1.3b. Explicit colon-pointer scanning catches leading ':', interior '::', and trailing ':' hazards that C strtok() silently skips.
| Task | Fragile Command / Idiom | Production Command / Idiom | Defect Prevented | |
|---|---|---|---|---|
Prepend dir to PATH | export PATH="/opt/arm/bin:$PATH" | export PATH="/opt/arm/bin${PATH:+:$PATH}" | Avoids trailing : (CWD .) when PATH was unset/empty | |
| Bulk file search | grep -n foo $(find . -name '*.c') | `find . -type f -name '*.c' -print0 | xargs -0 -r grep -n foo` | Prevents execve E2BIG overflow and space/quote splitting |
| Targeted kernel search | grep -r foo . (scans .git & .o) | grep -rn --include='*.[ch]' foo drivers/ | Skips binary .o/.ko noise and prints exact file:line | |
| Makefile edit over SSH | Space-indented recipe + :q hang | vim Makefile -> :set list (^I) -> :wq | Eliminates missing separator tab errors |
learner@ksa:~/gl-e00/m01-l03$ bat -H 6 -H 14 tree_and_path_audit.sh File: tree_and_path_audit.sh #!/usr/bin/env bash set -euo pipefail # 1. Safe parameter expansion: appends :$PATH only when PATH is non-empty TOOLCHAIN_BIN="/opt/toolchains/arm-gnu-toolchain/bin" export PATH="${TOOLCHAIN_BIN}${PATH:+:${PATH}}" # 2. Reject any empty PATH segment (leading ':', '::', or trailing ':') case ":${PATH}:" in *::*) echo "FATAL: empty PATH segment (implicit CWD '.') detected" >&2; exit 1 ;; esac # 3. NUL-delimited search across Device Tree bindings and C headers find . -type f \( -name "*.dts*" -o -name "*.h" \) -print0 | xargs -0 -r grep -n "compatible"- ${PATH:+:${PATH}} expands to nothing if PATH is empty, preventing a trailing ':' current-directory hazard.
- -print0 paired with xargs -0 -r frames every path with NUL (0x00) and skips execution cleanly on zero matches.
xargs(1) GL-E00 Quick Reference xargs(1) NAME find, xargs, grep, vim - tree search pipelines and modal file editing SYNOPSIS find <dir> -type f -name "*.c" -print0 | xargs -0 -r grep -n "<pattern>" grep -rn --include="*.[ch]" "<pattern>" <dir>/ vim +<line> <file> (Normal: Esc, /pat, n, u, dd | Insert: i, a, o | Ex: :set list, :wq, :q!) FLAGS -print0 / -0 Use NUL (0x00) instead of whitespace/quotes as record separator. -r (--no-run-if-empty) Do not invoke command when input stream is empty. :set list Render hard tabs as ^I and end-of-line as $ inside vim. Kernel Systems Academy Lesson 1.3 xargs(1) GL-E00 quick reference · full manual page: man 1 xargs Verifying NUL-Delimited Streams and Colon-Exact PATH Parsing in C11
In verify.c, we test both halves of Lesson 1.3 directly in ISO C11. First, we write a real NUL-delimited (-print0) stream containing a path with embedded spaces ("boards/rev B/pin mux.c") into an unprivileged temporary file, read it back, and prove that 0x00 framing preserves all 3 filenames intact where whitespace splitting produces 5 broken fragments.
Second, we contrast audit_path_strchr() against count_strtok_segments() on "/usr/bin::/bin". Notice how strtok() silently reports 2 clean segments while strchr() catches the 0-length middle segment (rc = -2), giving you the exact pattern needed for the Module 1 graded lab studio.
learner@ksa:~/gl-e00/m01-l03$ bat -H 14 -H 40 verify.c File: verify.c #define _POSIX_C_SOURCE 200809L #include <fcntl.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <unistd.h> static int audit_path_strchr(const char *path_str, int *seg_count) { if (!path_str || path_str[0] == '\0') return -1; *seg_count = 0; const char *p = path_str; for (;;) { const char *colon = strchr(p, ':'); size_t len = colon ? (size_t)(colon - p) : strlen(p); (*seg_count)++; if (len == 0) return -2; /* Empty segment ('::', leading/trailing ':') -> CWD '.' */ if (p[0] != '/') return -3; /* Relative directory in PATH */ if (!colon) break; p = colon + 1; } return 0; } static int count_strtok_segments(const char *path_str) { char tmp[128]; snprintf(tmp, sizeof(tmp), "%s", path_str); int n = 0; char *save = NULL; for (char *t = strtok_r(tmp, ":", &save); t; t = strtok_r(NULL, ":", &save)) n++; return n; } int main(void) { char tmpl[] = "/tmp/ksa_print0_XXXXXX"; int fd = mkstemp(tmpl); if (fd < 0) return 1; static const char nul_stream[] = "drivers/tty/serial.c\0boards/rev B/pin mux.c\0include/linux/init.h\0"; size_t stream_len = sizeof(nul_stream) - 1; if (write(fd, nul_stream, stream_len) != (ssize_t)stream_len) { unlink(tmpl); close(fd); return 1; } lseek(fd, 0, SEEK_SET); char buf[128] = {0}; ssize_t r = read(fd, buf, sizeof(buf)); close(fd); unlink(tmpl); if (r != (ssize_t)stream_len) return 1; int nul_records = 0; for (ssize_t i = 0; i < r; ++i) { if (buf[i] == '\0') nul_records++; } const char *good_path = "/opt/toolchains/arm/bin:/usr/bin:/bin"; const char *bad_path = "/usr/bin::/bin"; int n_good = 0, n_bad = 0; int rc_good = audit_path_strchr(good_path, &n_good); int rc_bad = audit_path_strchr(bad_path, &n_bad); int strtok_seen = count_strtok_segments(bad_path); printf("print0_stream: bytes=%zd nul_records=%d second_record='%s'\n", r, nul_records, buf + strlen(buf) + 1); printf("path_audit: clean_rc=%d(segs=%d) double_colon_rc=%d strtok_blind_segs=%d\n", rc_good, n_good, rc_bad, strtok_seen); return (nul_records == 3 && rc_good == 0 && n_good == 3 && rc_bad == -2 && strtok_seen == 2) ? 0 : 1; }- strchr() measures exact distance to the next ':' so consecutive '::' yields len == 0 and returns -2 immediately.
- Writing and reading raw 0x00-terminated records preserves 'boards/rev B/pin mux.c' as one intact path.
Confirming NUL Framing and strtok Blindness Under strace
Check both the program output and the strace capture. verify creates /tmp/ksa_print0_XXXXXX via openat(), writes 65 bytes containing 3 NUL-terminated records (preserving spaces inside "boards/rev B/pin mux.c"), unlinks the scratch file cleanly, and proves that strtok_r sees only 2 segments on "/usr/bin::/bin" while audit_path_strchr catches the hidden len == 0 segment (rc = -2).
learner@ksa:~/gl-e00/m01-l03gcc -std=c11 -Wall -Wextra -Werror verify.c -o verifylearner@ksa:~/gl-e00/m01-l03./verifyprint0_stream: bytes=65 nul_records=3 second_record='boards/rev B/pin mux.c'path_audit: clean_rc=0(segs=3) double_colon_rc=-2 strtok_blind_segs=2learner@ksa:~/gl-e00/m01-l03learner@ksa:~/gl-e00/m01-l03strace -e trace=openat,read,write,unlinkat \./verifyopenat(AT_FDCWD, "/etc/ld.so.cache", O_RDONLY|O_CLOEXEC) = 3openat(AT_FDCWD, "/lib/x86_64-linux-gnu/libc.so.6", O_RDONLY|O_CLOEXEC) = 3read(3, "\177ELF\2\1\1\3\0\0\0\0\0\0\0\0\3\0>\0\1\0\0\0\220\243\2\0\0\0\0\0"..., 832) = 832openat(AT_FDCWD, "/tmp/ksa_print0_0GSgQx", O_RDWR|O_CREAT|O_EXCL, 0600) = 3write(3, "drivers/tty/serial.c\0boards/rev "..., 65) = 65read(3, "drivers/tty/serial.c\0boards/rev "..., 128) = 65write(1, "print0_stream: bytes=65 nul_reco"..., 147) = 147+++ exited with 0 +++Modal Editing and Tree-Pipeline Pitfalls
Fluency with modal editing, NUL-delimited search streams, and strict environment hygiene turns any headless Linux box into a predictable embedded workbench. Before moving on to Module 2's filesystem and partition-table mechanics, complete the graded lab_m01_shell_env_audit studio below.
Makefile 'missing separator' After Copy-Pasting From Browser or Terminal:
- Symptom:
makeaborts immediately on line 12 withMakefile:12: *** missing separator. Stop.even though indentation looks aligned. - Root Cause: Terminal mouse selection converted the leading
0x09hard tab (\t) into4or8ASCII spaces (0x20), which GNUmakerejects on recipe lines. - Fix: Open the
Makefileinvim, run:set listto verify whether lines begin with^I(tab) or spaces, and replace leading spaces on recipe lines with a literalTab(:set noexpandtab).
Deleting a Vim .swp File Without Checking Crash Recovery:
- Symptom:
vimwarnsSwap file ".board.dts.swp" already exists!and an engineer reflexively pressesD(Delete) or runsrm .*.swp, losing an hour of unsavedDevice Treeedits. - Root Cause: Either a second terminal window currently has
board.dtsopen (ps aux | grep vim), or a dropped SSH session left unsaved buffer deltas inside.board.dts.swp. - Fix: First check whether another live
vimPID owns the file; if none exists, open withvim -r board.dts, save to a recovery copy (:w board.dts.recovered), diff withdiff -u, and only then remove.board.dts.swp.
Guided Practice
Extend audit_path_strchr() in verify.c to accept an array of mode_t directory permission values corresponding to each PATH segment and return -4 if any directory has the world-writable 0002 bit set (for example /tmp with 01777), even when the sticky bit is present.
Independent Practice
Now open labs/lab_m01_shell_env_audit/ and repair all three defects in starter/core.c so sh check.sh passes 5/5 TAP version 13 checks and ./files/lab_cli --bench prints CLOCK_MONOTONIC percentiles.
Verification Checks
? check 1 · Why does find . -name '*.c' -print0 | xargs -0 grep -n 'clk_prepare_enable' succeed on paths containing spaces and quotes where find . -name '*.c' | xargs grep -n ... fails?
- [ ]
-print0compresses filenames with zlib soexecve()never enforcesARG_MAX. - [ ]
xargs -0runsgrepinside kernel mode where spaces inext4filenames are automatically stripped. - [ ] Default
findomits subdirectories deeper than 4 levels unless-print0is passed. - [x]
-print0and-0delimit paths solely with0x00(NUL), which the Linux VFS forbids inside filenames, whereas defaultxargssplits on whitespace and interprets quotes.
Answer: -print0 and -0 delimit paths solely with 0x00 (NUL), which the Linux VFS forbids inside filenames, whereas default xargs splits on whitespace and interprets quotes.
Why: Because / and \0 are the only two bytes prohibited inside POSIX filenames, 0x00 is the single unambiguous delimiter for arbitrary file paths.
Common misconception: Thinking newline (0x0A) or quotes are safe filename delimiters in POSIX user space.
? check 2 · In ISO C11, why is strtok(path_copy, ":") unsafe for auditing a PATH environment variable for current-working-directory (.) security hazards?
- [ ]
strtok()callschdir(".")internally whenever a colon appears at byte index 0. - [ ]
strtok()rejects strings longer than64bytes under-std=c11. - [x]
strtok()treats consecutive:delimiters (::) and leading/trailing colons as a single separator, silently skipping empty segments that POSIX shells resolve to.. - [ ]
strtok()converts uppercase directory names to lowercase on LP64 Linux hosts.
Answer: strtok() treats consecutive : delimiters (::) and leading/trailing colons as a single separator, silently skipping empty segments that POSIX shells resolve to ..
Why: strtok() scans past any run of delimiter characters before starting the next token, making "/usr/bin::/bin" indistinguishable from "/usr/bin:/bin".
Common misconception: Assuming C strtok() behaves like Python str.split(':') on adjacent delimiters.
? check 3 · You open a broken Makefile in vim over SSH. Which command sequence enters Ex mode and makes hard tabs visible as ^I versus spaces?
- [ ] Run
:wq!inInsertmode to convert all spaces into8-column tabs. - [x] Press
Escto guaranteeNormalmode, then type:set listand pressEnter. - [ ] Press
ito enterInsertmode, then type:show-tabs. - [ ] Press
Ctrl-Ctwice to invoken_ttytab visualization.
Answer: Press Esc to guarantee Normal mode, then type :set list and press Enter.
Why: Esc transitions the Vim FSM from Insert/Visual back to Normal mode, from which : enters Ex command-line mode and set list renders 0x09 tabs as ^I and EOL as $.
Common misconception: Typing :commands while still inside Insert mode, which inserts literal characters into the file.
1. Motivation
Onboarding scripts for embedded Linux teams routinely break because one typo in /etc/udev/rules.d/ grants world-writable 0666 permissions or fails to match 15a2:0080, inverted 2>&1 >log redirection loses compiler errors, and an unguarded PATH append introduces an implicit . current-directory vulnerability. In this studio you repair a deterministic ISO C11 workbench auditor that enforces all three contracts before a host machine touches target hardware.
2. Learning objectives
- Enforce udev
==predicate syntax, 4-digit hexidVendor/idProductbounds, and non-world-writable!(mode & 0002)rules. - Model left-to-right POSIX
dup2(oldfd, newfd)descriptor routing across>build.log 2>&1and2>&1 >build.log. - Scan colon-delimited
PATHstrings via pointer arithmetic (strchr) to reject leading:, interior::, trailing:, and world-writable (0002) directories.
3. Environment requirements
All automated verification steps run in unprivileged user space on a POSIX Linux host using gcc -std=c11 -Wall -Wextra -Werror and clock_gettime(CLOCK_MONOTONIC). Recorded transcripts in captures.json were generated on x86_64 running kernel 7.0.0-42-generic and prove protocol, state-machine, and memory invariants only. Physical bus timing, DMA cache coherency, and board peripheral behavior require target validation on Linux kernel 6.12 LTS (ARMv7-A Cortex-A7).
4. Required software and hardware
- Host workstation:
gcc(-std=c11 -Wall -Wextra -Werror), GNUmake,ar(binutils), and POSIX/bin/sh. - Target environment (optional hardware step, Section 13):
ARMv7-ACortex-A7board connected viaCH340(1a86:7523) USB-UART console and USB OTGSDP(15a2:0080) recovery cable to verify/dev/ttyBENCH0symlink creation underudevadm.
5. Complete executable commands
learner@ksa:~/gl-e00/m01-l03$ bat script.sh File: script.sh make -B -C files ./files/lab_cli ./files/lab_cli --bench sh check.sh6. Annotated source code
files/core.c enforces the production invariants that starter/core.c breaks:
learner@ksa:~/gl-e00/m01-l03$ bat example.c File: example.c if ((m & 0002UL) != 0) return -5; /* Reject world-writable 0666 */ ... const char *colon = strchr(p, ':'); size_t len = colon ? (size_t)(colon - p) : strlen(p); if (len == 0) { out->empty_seg_index = (int)idx; return -2; /* Empty segment -> implicit '.' CWD hazard */ }starter/core.c contains three realistic defects: (1) ksa_audit_udev_rule() masks m & 0000UL and lets MODE="0666" slip through; (2) ksa_simulate_redir() ignores left-to-right dup2() order when log_first == 0; and (3) ksa_audit_path_env() fails to reject len == 0 empty :: or trailing : segments.
7. Expected output
Passing files/ run (sh check.sh, exit code 0):
learner@ksa:~/gl-e00/m01-l03$ bat listing.txt File: listing.txt TAP version 13 1..5 ok 1 - builds libcore.a and lab_cli cleanly with -std=c11 -Wall -Wextra -Werror ok 2 - archives core.o into libcore.a and links independent TAP verifier ok 3 - validates udev == predicates, hex4 VID:PID, and rejects world-writable MODE 0666 ok 4 - models left-to-right dup2 order distinguishing >log 2>&1 from 2>&1 >log ok 5 - audits colon-delimited PATH rejecting empty ::/trailing : and 0002 world-writable dirs # pass 5/5CLI verification output (./files/lab_cli):
learner@ksa:~/gl-e00/m01-l03$ bat listing.txt File: listing.txt udev_ch340: rc=0 mode=0660 redir_order: gt_log_2gt1=(1,1) 2gt1_gt_log=(1,0) path_audit: clean_rc=0(segs=3) double_colon_rc=-2(empty_idx=1)Defective starter/ run (exit code 1): emits FAIL: diagnostics on the broken contract assertions.
8. Explanation of observed behavior
When all three invariants are restored in files/core.c, sh check.sh compiles libcore.a cleanly under -std=c11 -Wall -Wextra -Werror, links the independent tests.c harness, and verifies all 5 TAP version 13 assertions (CH340 + 15a2:0080 udev rules, dup2 redirection order, and colon-exact PATH auditing).
9. Experiment variations
- Near transfer: Extend
ksa_audit_udev_rule()to rejectSYMLINK="..."(overwrite=) and requireSYMLINK+="..."(append+=) so custom bench aliases never wipe out/dev/serial/by-id/links. - Far transfer: Write a companion shell/C11 preflight tool that reads live
/etc/udev/rules.d/*.rulesandgetenv("PATH")+stat(2)on your workstation, failing CI if any directory inPATHis writable by group or other (st_mode & 0022).
10. Performance measurements
Recorded host benchmark (./files/lab_cli --bench, CLOCK_MONOTONIC, warmup=5, N=40 batches):
learner@ksa:~/gl-e00/m01-l03$ bat listing.txt File: listing.txt BENCH lab_m01_shell_env_audit clock=CLOCK_MONOTONIC warmup=5 samples=40 p50_ns=468 p95_ns=484 p99_ns=497 sink=0The CLOCK_MONOTONIC numbers above measure pure in-memory C11 rule and PATH parsing cost on the host CPU (p50 typically sub-microsecond per 3-call batch). Never extrapolate these host numbers to physical USB 2.0 enumeration (~tens of milliseconds) or systemd-udevd netlink worker fork latency.
11. Troubleshooting
| Symptom | Root cause | Fix |
|---|---|---|
not ok 3 - validates udev == predicates... | ksa_audit_udev_rule() still permits (m & 0002UL) != 0 (MODE="0666"). | Check (m & 0002UL) != 0 after strtoul(val, &end, 8) and return -5. |
not ok 4 - models left-to-right dup2 order... | log_first == 0 updates fd1 before copying fd1 into fd2. | In the else branch (2>&1 >log), set fd2 = fd1 (FD_TARGET_PTS) first, then fd1 = FD_TARGET_LOG. |
not ok 5 - audits colon-delimited PATH... | strtok() was used or len == 0 check is disabled, missing :: and trailing :. | Keep the strchr(p, ':') loop and return -2 whenever len == 0. |
12. Guided questions
- Why does
ksa_audit_path_env()reject/tmp(01777) when(dir_modes[idx] & 0002U) != 0even though/tmphas the sticky bit (01000) set?
- *Hint 1:* What does the sticky bit (
01000) prevent (unlink/renameof existing files), and what does0002(o+w) still allow any local user to create? - *Hint 2:* Any unprivileged user can still create a brand-new executable (such as a fake
arm-linux-gnueabihf-gccorsltypo binary) inside/tmpif it does not yet exist!
- Why does
strtoul(val, &end, 8)explicitly pass base8instead of base0when parsingMODE="0660"?
- *Hint 1:* What happens under base
0if someone writesMODE="660"without a leading'0'? - *Hint 2:* Base
0parses"660"as decimal660(01224octal!) instead of octal0660, whereasudevalways interpretsMODEstrings in base8.
13. Independent challenges
Add a ksa_audit_sudo_secure_path() function to core.c that compares a developer's cross-build PATH against /etc/sudoers secure_path, returning the exact list of stripped toolchain directories so an onboarding doctor CLI can explain why sudo make failed.
14. Solutions and explanations
The reference files/core.c validates == predicates and !(m & 0002UL) octal permissions in ksa_audit_udev_rule(), preserves strict left-to-right fd2 = fd1; fd1 = FD_TARGET_LOG; ordering in ksa_simulate_redir(0, ...), and scans raw : boundaries with strchr() in ksa_audit_path_env() to reject empty segments and world-writable directories.
Run locally in your terminal and check off each verification milestone.
Not started
Summary
- Vim separates Normal navigation/operator mode, Insert text-entry mode, and Command-line Ex mode (:w, :q!, :set list) so headless SSH repairs never depend on a graphical desktop.
- In Makefile recipes and Linux kernel Kconfig/C sources, :set list reveals 8-column hard tab characters (^I) versus spaces, preventing 'missing separator' build failures.
- Pairing find -print0 with xargs -0 delimits file paths with NUL (0x00) bytes—the only byte value forbidden alongside '/' inside Linux VFS filenames—preventing whitespace splitting and E2BIG.
- A secure build PATH contains only absolute ('/...') non-world-writable directories and zero empty ('::', leading ':', or trailing ':') segments that implicitly search the current working directory.
Step sequence — frame strip: steps_m01_l03
Open target files directly at the diagnostic line (+42), run :set list in Ex mode to distinguish ^I tabs from spaces, and write atomically.
reveals: step1
highlights: step1
Search kernel subsystems by compatible string or symbol using grep -rn --include to skip compiled .o and .ko binaries.
reveals: step2
highlights: step2
Pipe find -print0 into xargs -0 -r whenever passing file lists to external tools across large directory trees.
reveals: step3
highlights: step3
Execute the Module 1 TAP-13 studio to verify all host workbench invariants and record CLOCK_MONOTONIC percentiles.
reveals: step4
highlights: step4
m02/
Filesystem Hierarchy, Permissions, Archives & Partition Guards
Master FHS 3.0 directory roles, VFS hard vs symbolic link semantics, character and block device major:minor nodes, octal permission/umask/sticky invariants, MBR 1 KiB raw IVT boot offsets, removable-disk safety guards, and numeric-owner rootfs tar archives.
What you'll learn
- Map FHS 3.0 directories (/bin, /sbin, /usr, /etc, /var, /run, /proc, /sys) to read-only flash, tmpfs RAM, and kernel pseudo-filesystems.
- Contrast hard-link inode sharing (link, st_nlink, EXDEV) against symbolic-link path indirection (symlink, lstat vs stat) inside staged rootfs trees.
- Decode character and block device nodes via makedev, major, and minor numbers for serial UARTs and MMC storage partitions.
Why Everything in Linux Looks Like a File Yet Lives in Different Worlds
When an ARMv7-A board mounts its root filesystem (/) at the end of Linux kernel boot, user space expects strict Filesystem Hierarchy Standard (FHS 3.0) invariants. Essential binaries (/bin/sh, /sbin/init) and the ELF dynamic loader (/lib/ld-linux-armhf.so.3) must exist inside / before any secondary partition mounts. Meanwhile, /run is a pure tmpfs RAM filesystem holding volatile PID files and Unix sockets that vanish on power-off, and /proc (procfs) plus /sys (sysfs) consume zero flash bytes—reading /sys/class/net/eth0/carrier invokes a live kernel show() callback on the spot!
Understanding how the Virtual Filesystem (VFS) binds names to inodes prevents two classic rootfs bugs. In a BusyBox rootfs, 300+ applets (/bin/ls, /sbin/ifconfig) are symlinks to one binary. If an engineer creates an absolute host symlink ln -s /home/dev/rootfs/bin/busybox ls, ls works on the host and fails with No such file or directory on the board because /home/dev/rootfs does not exist on target silicon! Conversely, /dev/ttymxc0 and /dev/mmcblk1p2 store major:minor driver IDs (st_rdev) rather than data blocks.
Figure 2.1a. VFS unifies flash files, RAM tmpfs (/run), kernel pseudo-filesystems (/proc, /sys), and major:minor device nodes under one namespace.
mental model: Think of an inode (st_ino) as a numbered warehouse vault and directory entries (dentries) as catalog cards: a hard link prints a second catalog card stamped with the exact same vault number #4092 (the vault is emptied only after the last card is shredded and the last worker steps out of the vault), whereas a symbolic link is a sticky note on an empty box saying *'walk one aisle left to ../bin/busybox'*—if that note says *'go to the factory in Chicago'*, it breaks the moment you ship the crate to the lab!
Where it stops working: Vault numbers (ino_t) are unique only within one filesystem (st_dev)—both / (ext4) and /proc (procfs) can legitimately have an inode #2—which is why link(2) returns EXDEV (Invalid cross-device link) across mount points.
definition (Inode Reference Count (st_nlink) and Device ID (dev_t st_rdev)): Every POSIX file object is represented by a struct inode identified by (st_dev, st_ino). Regular files reclaim disk blocks only when both on-disk st_nlink == 0 and in-RAM open struct file count reach 0—explaining why deleting a huge log file (unlink) while a daemon still holds it open leaves df -h 100% full! For S_IFCHR and S_IFBLK device inodes, st_size is unused and st_rdev packs major (driver class, e.g., 179 mmcblk) and minor (partition index) via makedev(maj, min).
- Step 1. Inspect live mount types with findmnt so runtime logs and sockets go to /run (tmpfs) rather than wearing out raw flash.
- Step 2. Use ls -li and stat to verify whether two paths share one st_ino (hard link) or traverse a separate S_IFLNK inode.
- Step 3. Audit staged rootfs symlinks with readlink and find -type l to ensure zero host-workspace paths leaked into target links.
- Step 4. Confirm 'c'/'b' file type indicators and major, minor pairs exposed by devtmpfs under /dev.
Figure 2.1b. Keep rootfs symlinks relative, check st_dev+st_ino for hard links, and read st_rdev on /dev.
FHS 3.0 Layout, VFS Link Rules & Character/Block Major:Minor Numbers
Inside an embedded ARMv7-A rootfs, FHS 3.0 gives every top-level directory a strict lifecycle contract: /bin, /sbin, /lib, and /usr can be mounted completely read-only (ro SquashFS or ext4) to survive abrupt power cuts; /etc holds board configuration (fstab, inittab, nfs.conf); /var holds persistent mutable logs or package databases; and /run plus /tmp mount as RAM tmpfs so PID locks never persist across hard resets. Modern desktop distributions apply usrmerge (/bin -> usr/bin, /sbin -> usr/sbin, /lib -> usr/lib), so scripts must remain portable across both split and merged layouts.
At the VFS syscall layer, stat(path, &sb) follows symlinks to the terminal target (returning -1 with ENOENT on a dangling symlink!), whereas lstat(path, &sb) inspects the link inode itself (S_ISLNK(sb.st_mode) is true and sb.st_size equals the byte length of the stored target string!). Hard links (link(old, new)) are prohibited on directories (EPERM) so find and garbage collection never encounter reference cycles in the VFS tree.
Figure 2.1b. lstat() inspects the S_IFLNK inode directly instead of dereferencing host paths, catching broken rootfs links before flashing.
| Property | Hard Link (ln a b) | Symbolic Link (ln -s a b) | Device Node (mknod / devtmpfs) |
|---|---|---|---|
Inode (st_ino) | Identical st_ino & st_dev as a | New independent S_IFLNK inode | Independent S_IFCHR or S_IFBLK inode |
| Crosses filesystems? | No (EXDEV across mounts) | Yes (stores arbitrary path text) | N/A (dispatches via kernel st_rdev) |
| Links directories? | No (EPERM prevents VFS cycles) | Yes (e.g., /bin -> usr/bin) | No (represents stream or block hardware) |
If original a is unlinked | b still accesses all file data (st_nlink--) | b dangles (stat -> ENOENT; lstat succeeds) | Other nodes with same major:minor still reach driver |
learner@ksa:~/gl-e00/m02-l01$ bat -H 8 -H 11 stage_fhs_rootfs.sh File: stage_fhs_rootfs.sh #!/usr/bin/env bash set -euo pipefail STAGE="${PWD}/_stage_rootfs" mkdir -p "${STAGE}"/{bin,sbin,etc,lib,proc,sys,run,tmp,usr/bin,var/log} # 1. Portable relative symlink: sbin/init -> ../bin/busybox (survives host stage & target /) ln -snf ../bin/busybox "${STAGE}/sbin/init" # 2. Audit staged tree: fail build if any symlink points into host $HOME or build directory while IFS= read -r -d '' lnk; do tgt="$(readlink "${lnk}")" case "${tgt}" in "${HOME}"*|"${PWD}"*) echo "FATAL: host path in symlink ${lnk} -> ${tgt}" >&2; exit 1 ;; esac done < <(find "${STAGE}" -type l -print0)- Relative '../bin/busybox' resolves from sbin/ regardless of whether STAGE is mounted at /srv/nfs/rootfs or /.
- find -type l -print0 + readlink catches leaked host workspace paths before tar or NFS export.
lstat(2) GL-E00 Quick Reference lstat(2) NAME stat, lstat, link, symlink, makedev - VFS inode metadata, links, and device IDs SYNOPSIS #include <sys/stat.h> #include <sys/sysmacros.h> int stat(const char *pathname, struct stat *statbuf); int lstat(const char *pathname, struct stat *statbuf); dev_t makedev(unsigned int maj, unsigned int min); DESCRIPTION stat() dereferences symbolic links; if a symlink dangles, stat() fails with ENOENT. lstat() inspects the link inode itself (S_ISLNK(statbuf->st_mode) != 0). major(statbuf->st_rdev) and minor(statbuf->st_rdev) decode S_IFCHR / S_IFBLK drivers. ERRORS EXDEV link() oldpath and newpath reside on different mounted filesystems (st_dev). EPERM link() oldpath is a directory (forbidden to keep VFS dentry graph acyclic). Kernel Systems Academy Lesson 2.1 lstat(2) GL-E00 quick reference · full manual page: man 2 lstat Proving Hard Links, Dangling Symlinks & dev_t Encoding in C11
Let us verify these exact VFS behaviors on the Linux host in ISO C11. In verify.c, we create a private /tmp/ksa_vfs_XXXXXX sandbox, write a regular busybox file, create a hard link (bin_sh) via link(2), and create both a valid relative symlink (../bin/busybox) and a deliberately dangling symlink (missing_target) via symlink(2).
Notice how stat() on the dangling symlink fails with errno == ENOENT while lstat() succeeds and reports S_ISLNK(sb.st_mode) with st_size == 14 (exact length of "missing_target"). Finally, we encode i.MX6ULL eMMC partition 2 (major 179, minor 2) with makedev() and verify lossless round-trip extraction.
learner@ksa:~/gl-e00/m02-l01$ bat -H 29 -H 39 verify.c File: verify.c #define _DEFAULT_SOURCE #include <errno.h> #include <fcntl.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <sys/stat.h> #include <sys/sysmacros.h> #include <unistd.h> int main(void) { char root[] = "/tmp/ksa_vfs_XXXXXX"; if (!mkdtemp(root)) return 1; char bin_dir[128], sbin_dir[128], bb_path[160], hlink_path[160], slink_path[160], dang_path[160]; snprintf(bin_dir, sizeof(bin_dir), "%s/bin", root); snprintf(sbin_dir, sizeof(sbin_dir), "%s/sbin", root); snprintf(bb_path, sizeof(bb_path), "%s/bin/busybox", root); snprintf(hlink_path, sizeof(hlink_path), "%s/bin/sh", root); snprintf(slink_path, sizeof(slink_path), "%s/sbin/init", root); snprintf(dang_path, sizeof(dang_path), "%s/sbin/broken", root); mkdir(bin_dir, 0755); mkdir(sbin_dir, 0755); int fd = open(bb_path, O_WRONLY | O_CREAT | O_TRUNC, 0755); if (fd < 0 || write(fd, "ELF_ARM", 7) != 7) return 1; close(fd); if (link(bb_path, hlink_path) != 0) return 1; if (symlink("../bin/busybox", slink_path) != 0) return 1; if (symlink("missing_target", dang_path) != 0) return 1; struct stat sb_bb, sb_hl, sb_sl_lstat, sb_sl_stat, sb_dang_stat, sb_dang_lstat; stat(bb_path, &sb_bb); stat(hlink_path, &sb_hl); lstat(slink_path, &sb_sl_lstat); stat(slink_path, &sb_sl_stat); errno = 0; int dang_stat_rc = stat(dang_path, &sb_dang_stat); int dang_errno = errno; int dang_lstat_rc = lstat(dang_path, &sb_dang_lstat); dev_t mmc_p2 = makedev(179U, 2U); unsigned int maj = major(mmc_p2); unsigned int min = minor(mmc_p2); printf("hard_link: same_ino=%d nlink=%lu\n", sb_bb.st_ino == sb_hl.st_ino, (unsigned long)sb_bb.st_nlink); printf("rel_symlink: is_lnk=%d target_follows_bb=%d\n", S_ISLNK(sb_sl_lstat.st_mode) != 0, sb_sl_stat.st_ino == sb_bb.st_ino); printf("dangling_link: stat_rc=%d(ENOENT=%d) lstat_rc=%d(len=%ld)\n", dang_stat_rc, dang_errno == ENOENT, dang_lstat_rc, (long)sb_dang_lstat.st_size); printf("dev_t_encode: mmcblk1p2 major=%u minor=%u\n", maj, min); unlink(dang_path); unlink(slink_path); unlink(hlink_path); unlink(bb_path); rmdir(sbin_dir); rmdir(bin_dir); rmdir(root); return (sb_bb.st_ino == sb_hl.st_ino && sb_bb.st_nlink == 2 && S_ISLNK(sb_sl_lstat.st_mode) && sb_sl_stat.st_ino == sb_bb.st_ino && dang_stat_rc == -1 && dang_errno == ENOENT && dang_lstat_rc == 0 && maj == 179U && min == 2U) ? 0 : 1; }- link() shares the exact st_ino with busybox (nlink=2), while symlink('../bin/busybox') stores a portable relative string.
- stat() fails with ENOENT on dangling symlinks, whereas lstat() inspects the S_IFLNK inode directly without following.
Tracing linkat, symlinkat, and newfstatat Flags in strace
Inspect the strace capture closely: glibc translates stat() and lstat() into the same newfstatat() syscall, passing 0 for stat() (follow symlink -> -1 ENOENT on broken) and AT_SYMLINK_NOFOLLOW for lstat() (inspect link inode -> 0!). Meanwhile, linkat() increments st_nlink to 2 with same_ino=1, and makedev(179, 2) decodes back to major=179 minor=2 cleanly.
learner@ksa:~/gl-e00/m02-l01gcc -std=c11 -Wall -Wextra -Werror verify.c -o verifylearner@ksa:~/gl-e00/m02-l01./verifyhard_link: same_ino=1 nlink=2rel_symlink: is_lnk=1 target_follows_bb=1dangling_link: stat_rc=-1(ENOENT=1) lstat_rc=0(len=14)dev_t_encode: mmcblk1p2 major=179 minor=2learner@ksa:~/gl-e00/m02-l01learner@ksa:~/gl-e00/m02-l01strace -e \trace=linkat,symlinkat,newfstatat,unlinkat ./verifynewfstatat(AT_FDCWD, "/tmp/ksa_vfs_OjbTMI/bin/busybox", {st_mode=S_IFREG|0755, st_size=7, ...}, 0) = 0newfstatat(AT_FDCWD, "/tmp/ksa_vfs_OjbTMI/bin/sh", {st_mode=S_IFREG|0755, st_size=7, ...}, 0) = 0newfstatat(AT_FDCWD, "/tmp/ksa_vfs_OjbTMI/sbin/init", {st_mode=S_IFLNK|0777, st_size=14, ...}, AT_SYMLINK_NOFOLLOW) = 0newfstatat(AT_FDCWD, "/tmp/ksa_vfs_OjbTMI/sbin/init", {st_mode=S_IFREG|0755, st_size=7, ...}, 0) = 0newfstatat(AT_FDCWD, "/tmp/ksa_vfs_OjbTMI/sbin/broken", 0x7ffc811ebe90, 0) = -1 ENOENT (No such file or directory)newfstatat(AT_FDCWD, "/tmp/ksa_vfs_OjbTMI/sbin/broken", {st_mode=S_IFLNK|0777, st_size=14, ...}, AT_SYMLINK_NOFOLLOW) = 0+++ exited with 0 +++Rootfs Staging, Open-Unlinked Disk Leaks & Pseudo-FS Pitfalls
Mastering FHS lifecycles, relative symlinks, and dev_t semantics prepares you to build clean minimal root filesystems (BusyBox, Buildroot, Debian debootstrap) without boot-time init panics or mysterious flash exhaustion.
Disk Stays 100% Full After rm /var/log/daemon.log:
- Symptom:
df -hreports0 Bfree on/var, you runrm /var/log/daemon.log(2 GiB),lsshows the file is gone, yetdf -hstill reports0 Bfree! - Root Cause:
rmcallsunlink(2), decrementingst_nlinkfrom1to0, but the running daemon still holds an openstruct filedescriptor (fd 3), soext4cannot free the blocks. - Fix: Identify the holder with
lsof +L1(open files withnlink < 1), then either truncate in place (: > /var/log/daemon.logbefore unlinking) or reload/restart the daemon (SIGHUP/systemctl kill -s HUP) so it closesfd 3.
Copying /dev, /proc, or /sys With Plain cp -r Without Archive Flags:
- Symptom: Copying a rootfs directory with
cp -rturns/dev/nullinto a multi-megabyte regular file and converts300BusyBox symlinks into300full1 MiBbinary copies (300 MiBflash bloat!). - Root Cause: Plain
cp -rdereferences symlinks and reads from character device nodes instead of preservingS_IFLNKandS_IFCHRmetadata. - Fix: Always copy rootfs staging directories with
cp -a(-dR --preserve=all) orrsync -aHAX, and keep/proc,/sys,/dev, and/runas empty mount-point directories in the image.
Guided Practice
Extend verify.c to open bb_path read-only (fd_hold = open(bb_path, O_RDONLY)), unlink both hlink_path and bb_path (st_nlink drops to 0), and call fstat(fd_hold, &sb) plus read(fd_hold, ...) to prove in C11 that data blocks stay allocated (sb.st_nlink == 0, sb.st_size == 7) until close(fd_hold) runs!
Independent Practice
Write a C11 directory scanner using opendir(), readdir(), lstat(), and readlink() that walks a staged rootfs path and exits non-zero if any symlink points outside the staging root via excessive .. parent traversals.
Verification Checks
? check 1 · While staging an embedded BusyBox rootfs at /home/eng/rootfs, why does ln -s /home/eng/rootfs/bin/busybox /home/eng/rootfs/sbin/init cause a kernel panic on the ARMv7-A target?
- [x] The symlink stores the literal string
"/home/eng/rootfs/bin/busybox", which dangles (ENOENT) once the target mounts that directory as/. - [ ] Symbolic links cannot cross between
/sbinand/bineven within the sameext4partition. - [ ]
ARMv7-Aext4drivers only support hard links and ignoreS_IFLNKinodes during early boot. - [ ]
ln -sembeds the host x86_64st_devUUID inside the symlink inode.
Answer: The symlink stores the literal string "/home/eng/rootfs/bin/busybox", which dangles (ENOENT) once the target mounts that directory as /.
Why: Kernel symlink resolution replays the literal stored path string relative to the live root (/), so internal rootfs links must be relative (../bin/busybox) or target-rooted (/bin/busybox).
Common misconception: Thinking ln -s automatically strips the staging prefix directory from an absolute target path.
? check 2 · Why does ln /var/log/messages /home/backup/messages fail with Invalid cross-device link (EXDEV) when /var and /home are separate partitions?
- [ ] Hard links require
CAP_SYS_ADMINroot privileges whenever source files live under/var/log. - [ ] POSIX forbids hard links on files larger than
4 KiB(PAGE_SIZE). - [ ]
/varusesS_IFCHRinodes whereas/homeusesS_IFREGinodes. - [x] A hard link binds a directory entry directly to an
ino_tnumber, and inode numbers are unique only within a single mounted filesystem (st_dev).
Answer: A hard link binds a directory entry directly to an ino_t number, and inode numbers are unique only within a single mounted filesystem (st_dev).
Why: Each mounted filesystem maintains its own independent inode table starting from inode 1/2, so a directory entry on filesystem B cannot reference an inode index in filesystem A's superblock.
Common misconception: Assuming ino_t inode numbers are globally unique across all mounted disks on a Linux machine.
? check 3 · What do the numbers 179, 2 represent in brw-rw---- 1 root disk 179, 2 Nov 24 01:00 /dev/mmcblk0p2?
- [ ]
179is theext4superblock magic byte and2is theUIDof thediskgroup. - [ ]
bmarks a bootable binary executable starting at sector179with2ELF segments. - [x]
bmarks a block device (S_IFBLK),major = 179selects the kernelmmcblkblock driver, andminor = 2selects partition2. - [ ]
179is the file size in KiB and2is thest_nlinkhard-link reference count.
Answer: b marks a block device (S_IFBLK), major = 179 selects the kernel mmcblk block driver, and minor = 2 selects partition 2.
Why: On S_IFBLK (b) and S_IFCHR (c) device nodes, ls -l prints major(st_rdev), minor(st_rdev) in place of st_size.
Common misconception: Reading the major, minor column of ls -l /dev as byte size.
Summary
- FHS 3.0 separates essential boot binaries (/bin, /sbin, /lib) and static configuration (/etc) from volatile tmpfs runtime state (/run) and RAM-backed kernel pseudo-filesystems (/proc, /sys).
- A hard link creates an additional directory entry pointing to the exact same inode number (st_ino) within a single mounted filesystem (st_dev) and increments st_nlink without duplicating data blocks.
- A symbolic link allocates a distinct S_IFLNK inode storing a target path string, allowing cross-filesystem and directory links that must remain relative inside staged target root filesystems.
- Character (S_IFCHR) and block (S_IFBLK) device inodes store no file payload blocks; their st_rdev field encodes major(dev) to select a Linux kernel driver and minor(dev) to select the instance or partition.
Step sequence — frame strip: steps_m02_l01
Inspect live mount types with findmnt so runtime logs and sockets go to /run (tmpfs) rather than wearing out raw flash.
reveals: step1
highlights: step1
Use ls -li and stat to verify whether two paths share one st_ino (hard link) or traverse a separate S_IFLNK inode.
reveals: step2
highlights: step2
Audit staged rootfs symlinks with readlink and find -type l to ensure zero host-workspace paths leaked into target links.
reveals: step3
highlights: step3
Confirm 'c'/'b' file type indicators and major, minor pairs exposed by devtmpfs under /dev.
reveals: step4
highlights: step4
What you'll learn
- Evaluate Linux VFS permission checks across UID/GID classes, directory traverse (x) vs list (r) bits, and sticky (01000) shared directories.
- Calculate effective file and directory modes under process umask values and explain why chmod -R 777 disables sudo and OpenSSH.
- Author syntax-checked, idempotent /etc/profile.d/ environment scripts without causing desktop or SSH login loops.
Why 'chmod -R 777' and Naive /etc/profile Edits Destroy Workstations
Two reflexes account for more reinstalled Ubuntu workstations in embedded courses than any other mistake. First, a learner hits Permission denied on a build folder and runs sudo chmod -R 777 / or chmod -R 777 ~. Within milliseconds, OpenSSH refuses every public-key login because StrictModes rejects group- or world-writable ~/.ssh (0700 required) and ~/.ssh/authorized_keys (0600 required), and if /etc/sudoers (0440) or /usr/bin/sudo (04755 setuid root) is touched, sudo itself aborts with /etc/sudoers is world writable—leaving no way to fix the machine without booting recovery media!
Second, when adding an ARM cross-compiler permanently, an engineer edits /etc/profile and writes export PATH=/opt/arm/bin (forgetting :$PATH!) or leaves an unclosed quote or blocking foreground command. On the next boot, the display manager sources /etc/profile, fails to find /bin/ls or /usr/bin/dbus-run-session, and bounces straight back to the login screen in an infinite loop!
Figure 2.2a. VFS checks owner, group, and other classes mutually exclusively (first match wins, never union!) alongside 04000/02000/01000 high bits.
mental model: Think of a directory as a locked filing-cabinet room containing sealed envelopes (files): r (04) turns on the room light so you can read the index sheet of envelope names, x (01) unlocks the door so you can walk in and grab an envelope whose exact name you already know (even in the dark when r is off!), and w (02) lets you toss envelopes into the shredder—regardless of whose seal is on the envelope—unless the room guard (01000 sticky bit) checks that your badge matches the envelope's owner!
Where it stops working: Unlike physical rooms where holding both an employee badge and a visitor badge gives you the best of both, POSIX VFS permission matching is strictly mutually exclusive: if euid == st_uid and owner bits are 000 (---rwxrwx), open() returns EACCES even when group and world have rwx!
definition ( and Set-Group-ID Directory (S_ISGID / 02000)): Historically named because early Unix kept a program's text segment 'stuck' in swap space, on modern Linux kernel directories S_ISVTX (01000, rendered as t in drwxrwxrwt when o+x is set, or T when o+x is clear) modifies may_delete() in fs/namei.c: unlinking or renaming a child requires w+x on the directory plus euid == 0 || euid == dir_uid || euid == file_uid. Meanwhile, S_ISGID (02000, drwxrwsr-x) on a shared team build directory makes newly created files and subdirectories inherit the directory's st_gid automatically.
- Step 1. Query numeric and symbolic mode bits with stat -c '%a %A' to audit special high bits (4=setuid, 2=setgid, 1=sticky).
- Step 2. Check active shell umask in both symbolic and octal forms before unpacking toolchains or creating staging trees.
- Step 3. Place global environment additions in a standalone /etc/profile.d/*.sh file rather than hand-editing /etc/profile.
- Step 4. Validate POSIX sh syntax with sh -n and spawn a clean login subshell (bash -lc) before logging out.
Figure 2.2b. Avoid chmod 777; dir w+x + 01000 governs unlink; syntax-check profile.d via sh -n.
12-Bit Mode Masks, First-Match Credential Evaluation & visudo Safety
Inside generic_permission() (fs/namei.c), the Linux kernel evaluates a 12-bit mode word (4 octal digits: [special][user][group][other]). For fsuid == 0, read/write checks succeed via CAP_DAC_OVERRIDE (though executing a regular file still requires at least one x bit 0111!). For non-root processes, the kernel tests fsuid == inode->i_uid first (using (mode >> 6) & 7); only if false does it check in_group_p(inode->i_gid) ((mode >> 3) & 7); and only if both are false does it use mode & 7.
Look closely at directory deletion: unlink("/shared/report.pdf") mutates /shared's directory entries, not report.pdf's bytes! Consequently, a user with 0000 permissions on report.pdf can still delete report.pdf if /shared is 0777 without the 01000 sticky bit. Finally, never edit /etc/sudoers directly with vim; always run sudo visudo (or drop validated files into /etc/sudoers.d/ mode 0440), which parses grammar on a temp file before atomic rename—and if /etc/sudoers ever becomes 0777 on a desktop machine with PolicyKit active, pkexec chmod 0440 /etc/sudoers can rescue it without rebooting!
Figure 2.2b. Unlinking a file checks w+x (03) on the parent directory plus the 01000 sticky owner invariant—never the victim file's mode bits.
| Critical Path | Required Octal Mode | Consequence of chmod 777 | Safe Collaborative Alternative |
|---|---|---|---|
/etc/sudoers & /etc/sudoers.d/* | 0440 (root:root) | sudo refuses all commands (world writable) | Edit exclusively via sudo visudo -f /etc/sudoers.d/dev |
~/.ssh & ~/.ssh/authorized_keys | 0700 dir / 0600 file | sshd StrictModes rejects SSH key login silently | Use ssh-copy-id which enforces 0700 / 0600 |
/tmp & /var/tmp | 01777 (drwxrwxrwt) | 0777 (without 01000) lets any UID delete others' temp files | Always include leading 1 (chmod 1777 /tmp) |
Team shared /srv/builds | 02775 (root:eng) | 0777 exposes artifacts to untrusted daemons/users | chmod 2775 (setgid) + umask 0002 for group collaboration |
learner@ksa:~/gl-e00/m02-l02$ bat -H 2 -H 5 90-arm-toolchain.sh File: 90-arm-toolchain.sh # /etc/profile.d/90-arm-toolchain.sh (mode 0644, root:root) # Sourced by /etc/profile using POSIX sh — NEVER use bash-only arrays here! if [ -d "/opt/toolchains/arm-gnu-toolchain/bin" ]; then case ":${PATH:-}:" in *":/opt/toolchains/arm-gnu-toolchain/bin:"*) ;; *) PATH="/opt/toolchains/arm-gnu-toolchain/bin${PATH:+:${PATH}}" ;; esac export PATH fi- /etc/profile is sourced by /bin/sh (dash on Ubuntu/Debian) during GUI session startup, so bashisms crash login!
- Idempotent case guard prevents duplicate entries while ${PATH:+:${PATH}} preserves /usr/bin:/bin.
chmod(2) GL-E00 Quick Reference chmod(2) NAME chmod, umask, visudo - POSIX file mode bits, creation mask, and sudoers editor SYNOPSIS chmod 1777 /tmp # Sticky shared directory (drwxrwxrwt) chmod 2775 /srv/builds # Setgid shared team directory (drwxrwsr-x) sudo visudo -c # Validate /etc/sudoers syntax & 0440 permissions sh -n /etc/profile.d/custom.sh # Parse-check POSIX login script without executing OCTAL SUMMARY 4000 setuid | 2000 setgid | 1000 sticky 400 u+r | 200 u+w | 100 u+x (dir traverse) 040 g+r | 020 g+w | 010 g+x 004 o+r | 002 o+w | 001 o+x Kernel Systems Academy Lesson 2.2 chmod(2) GL-E00 quick reference · full manual page: man 2 chmod Verifying umask, First-Match Triads & Sticky Unlink Rules in C11
In verify.c, we test both the Linux kernel's VFS permission logic and real host filesystem umask() syscalls in ISO C11. First, vfs_can_unlink() implements the exact kernel first-match triad (actor == dir_uid vs actor_gid == dir_gid vs other), checks w+x (03) on the parent directory, and enforces the 01000 sticky invariant.
Second, we temporarily set umask(0027), create a real scratch file with open(..., 0666) and scratch directory with mkdir(..., 0777), read back stat().st_mode & 07777, and confirm 0640 and 0750 directly from the host ext4/tmpfs VFS!
learner@ksa:~/gl-e00/m02-l02$ bat -H 19 -H 30 verify.c File: verify.c #define _POSIX_C_SOURCE 200809L #include <fcntl.h> #include <stdint.h> #include <stdio.h> #include <stdlib.h> #include <sys/stat.h> #include <unistd.h> static int vfs_triad_bits(uint32_t mode, uint32_t obj_uid, uint32_t obj_gid, uint32_t actor_uid, uint32_t actor_gid) { if (actor_uid == obj_uid) return (int)((mode >> 6) & 7U); if (actor_gid == obj_gid) return (int)((mode >> 3) & 7U); return (int)(mode & 7U); } static int vfs_can_unlink(uint32_t dir_mode, uint32_t dir_uid, uint32_t dir_gid, uint32_t file_uid, uint32_t actor_uid, uint32_t actor_gid) { if (actor_uid == 0) return 1; /* UID 0 CAP_DAC_OVERRIDE + CAP_FOWNER */ int bits = vfs_triad_bits(dir_mode, dir_uid, dir_gid, actor_uid, actor_gid); if ((bits & 03) != 03) return 0; /* Parent dir requires BOTH write (2) and search/exec (1) */ if ((dir_mode & 01000U) != 0) { if (actor_uid != dir_uid && actor_uid != file_uid) return 0; /* Sticky block */ } return 1; } int main(void) { char root[] = "/tmp/ksa_perm_XXXXXX"; if (!mkdtemp(root)) return 1; mode_t old_mask = umask(0027); char fpath[160], dpath[160]; snprintf(fpath, sizeof(fpath), "%s/secret.conf", root); snprintf(dpath, sizeof(dpath), "%s/sub", root); int fd = open(fpath, O_WRONLY | O_CREAT | O_TRUNC, 0666); if (fd < 0) return 1; close(fd); if (mkdir(dpath, 0777) != 0) return 1; umask(old_mask); struct stat sf, sd; stat(fpath, &sf); stat(dpath, &sd); unsigned int fm = (unsigned int)(sf.st_mode & 07777); unsigned int dm = (unsigned int)(sd.st_mode & 07777); unlink(fpath); rmdir(dpath); rmdir(root); /* Actor 1001 deleting UID 1000's file in 0777 (no sticky) vs 01777 (/tmp sticky) */ int del_0777 = vfs_can_unlink(0777U, 0U, 0U, 1000U, 1001U, 1001U); int del_1777_stranger = vfs_can_unlink(01777U, 0U, 0U, 1000U, 1001U, 1001U); int del_1777_owner = vfs_can_unlink(01777U, 0U, 0U, 1001U, 1001U, 1001U); /* First-match exclusivity: owner bits 000 on 0077 denies owner UID 1000! */ int owner_0077 = vfs_triad_bits(0077U, 1000U, 1000U, 1000U, 1000U); printf("umask_0027: open_0666=0%03o mkdir_0777=0%03o\n", fm, dm); printf("unlink_check: dir_0777=%d tmp_01777_stranger=%d tmp_01777_owner=%d\n", del_0777, del_1777_stranger, del_1777_owner); printf("first_match_0077_owner_bits: 0%o\n", (unsigned int)owner_0077); return (fm == 0640U && dm == 0750U && del_0777 == 1 && del_1777_stranger == 0 && del_1777_owner == 1 && owner_0077 == 0) ? 0 : 1; }- Deleting an entry requires BOTH write (02) and execute/search (01) on the parent directory.
- umask(0027) strips group-write (0020) and all other bits (0007), turning 0666->0640 and 0777->0750.
Confirming Kernel umask Masking in strace
Observe the strace output: umask(027) returns the caller's previous mask, openat(..., 0666) and mkdirat(..., 0777) pass the unmasked request to the Linux kernel, and newfstatat() proves the kernel masked the created inodes to 0640 and 0750. At the same time, our VFS verifier confirms that 01777 blocks cross-user unlinks (0) while 0777 permits them (1).
Notice one subtle contrast between openat() creation and explicit chmod()/fchmodat(): umask filters permissions only at inode creation time (O_CREAT or mkdir), whereas an explicit chmod(path, 01777) sets mode bits verbatim without consulting umask. That is why sudo and sshd call stat() directly on /etc/sudoers (0440) and ~/.ssh (0700) before trusting configuration files.
learner@ksa:~/gl-e00/m02-l02gcc -std=c11 -Wall -Wextra -Werror verify.c -o verifylearner@ksa:~/gl-e00/m02-l02./verifyumask_0027: open_0666=0640 mkdir_0777=0750unlink_check: dir_0777=1 tmp_01777_stranger=0 tmp_01777_owner=1first_match_0077_owner_bits: 00learner@ksa:~/gl-e00/m02-l02learner@ksa:~/gl-e00/m02-l02strace -e \trace=umask,openat,mkdirat,newfstatat,unlinkat ./verifyopenat(AT_FDCWD, "/etc/ld.so.cache", O_RDONLY|O_CLOEXEC) = 3openat(AT_FDCWD, "/lib/x86_64-linux-gnu/libc.so.6", O_RDONLY|O_CLOEXEC) = 3umask(027) = 002openat(AT_FDCWD, "/tmp/ksa_perm_IsTEc8/secret.conf", O_WRONLY|O_CREAT|O_TRUNC, 0666) = 3umask(002) = 027newfstatat(AT_FDCWD, "/tmp/ksa_perm_IsTEc8/secret.conf", {st_mode=S_IFREG|0640, st_size=0, ...}, 0) = 0newfstatat(AT_FDCWD, "/tmp/ksa_perm_IsTEc8/sub", {st_mode=S_IFDIR|0750, st_size=4096, ...}, 0) = 0+++ exited with 0 +++Desktop Login Loops, Bashisms in /etc/profile & sudo Lockouts
Respecting octal mode invariants keeps multi-user build servers and embedded root filesystems secure without locking yourself out. Use 2775 + groups for shared directories, 1777 for /tmp, 0440 via visudo for /etc/sudoers, and POSIX-clean /etc/profile.d/*.sh scripts.
Ubuntu Desktop Infinite Login Loop After Adding Bash Syntax to /etc/profile.d/:
- Symptom: You enter your correct password on the Ubuntu GUI login screen, the screen flashes black for one second, and returns straight to the password prompt.
- Root Cause:
gdm3/lightdmXsessionsources/etc/profileand/etc/profile.d/*.shusing/bin/sh(dash), which aborts the entire session startup on non-POSIX bashisms ([[ ... ]],source, arrays) or a clobberedPATH. - Fix: Switch to a text virtual console with
Ctrl-Alt-F3(or SSH in), inspect~/.xsession-errorsorjournalctl -b, validate/etc/profile.d/*.shwithdash -n, and ensurePATHretains/usr/bin:/bin.
Directory Marked r-- (0400) Without Execute x (0100) Bit:
- Symptom:
ls dir/lists filenames mixed withls: cannot access 'dir/foo': Permission deniedand??????????stat columns, andcat dir/foofails even thoughdir/foois0644! - Root Cause: Read (
r,04) on a directory permitsgetdents64()to read raw filename strings, but without execute/search (x,01) the VFS refuses inode lookup (stat/open) on every child insidedir/. - Fix: Directories practically always pair
rwithx(0755or0750); usechmod -R a+X(capitalXadds+xonly to directories and already-executable files, leaving regular0644data files non-executable!).
Guided Practice
Test the difference between lowercase chmod -R a+x and uppercase chmod -R a+X on a scratch directory in /tmp containing one subdirectory (0700) and one regular C source file (0600). Why is capital +X essential when fixing permissions across a source tree?
Independent Practice
Extend verify.c with a check_ssh_strict_modes(uint32_t home_mode, uint32_t ssh_dir_mode, uint32_t auth_keys_mode) function enforcing OpenSSH StrictModes (!(mode & 0022) on $HOME, ~/.ssh == 0700, authorized_keys == 0600).
Verification Checks
? check 1 · User bob (UID 1001, GID 1001) finds a file /srv/drop/calib.bin owned by root:root with mode 0400 (-r--------). The parent directory /srv/drop is 0777 (drwxrwxrwx, no sticky bit). What happens if bob runs rm -f /srv/drop/calib.bin?
- [ ]
unlink(2)fails withEACCESbecausecalib.binis mode0400owned byUID 0. - [ ]
rm -ftruncatescalib.binto0bytes while keeping the directory entry intact. - [ ] The kernel automatically promotes
/srv/dropto01777whenever a root-owned file is placed inside. - [x] The file is deleted!
unlink(2)checksw+xon the parent directory/srv/drop(0777), not write permission oncalib.bin, and/srv/droplacks the01000sticky bit.
Answer: The file is deleted! unlink(2) checks w+x on the parent directory /srv/drop (0777), not write permission on calib.bin, and /srv/drop lacks the 01000 sticky bit.
Why: Removing a filename mutates the parent directory's dentry list rather than the file's data blocks; without 01000 (S_ISVTX) on /srv/drop, w+x on the directory suffices to unlink any child.
Common misconception: Thinking read-only mode 0400 on a file protects that filename from deletion inside a non-sticky writable directory.
? check 2 · With umask 0027, what octal permissions are assigned to a newly created regular log file (open(..., O_CREAT, 0666)) and a newly created directory (mkdir(..., 0777))?
- [ ] File
0639and directory0750via decimal subtraction. - [ ] File
0027and directory0027. - [x] File
0640(-rw-r-----) and directory0750(drwxr-x---). - [ ] File
0750(-rwxr-x---) and directory0750(drwxr-x---).
Answer: File 0640 (-rw-r-----) and directory 0750 (drwxr-x---).
Why: 0666 & ~0027 = 0666 & 0750 = 0640 (regular open() passes 0666, never 0777), and 0777 & ~0027 = 0750.
Common misconception: Subtracting umask in decimal or forgetting that open() starts from 0666 (no execute bits) rather than 0777.
? check 3 · A file secret.key has permissions 0070 (----rwx---) and ownership alice:engineers. alice is a member of engineers. What happens when alice runs cat secret.key?
- [ ] POSIX takes the bitwise OR (
000 | 070 = 070) across all matching credential classes. - [x]
Permission denied(EACCES): VFS matchesfsuid == st_uid(alice) first, sees owner bits000, and stops without consulting group bits! - [ ]
catsucceeds becausealicebelongs toengineers, which grantsrwx(0070). - [ ]
catprints the file but kernelauditdlogs aCAP_DAC_READ_SEARCHwarning.
Answer: Permission denied (EACCES): VFS matches fsuid == st_uid (alice) first, sees owner bits 000, and stops without consulting group bits!
Why: POSIX credential evaluation is a strict if (uid) else if (gid) else ladder, never a union across owner, group, and other.
Common misconception: Believing group permissions act as a fallback when owner permissions are more restrictive.
Summary
- Directory permissions govern namespace operations rather than file contents: read (04) allows listing names via getdents64, execute (01) allows traversing into known child inodes, and write (02) allows creating or unlinking entries.
- The sticky bit (S_ISVTX, octal 01000) on shared writable directories like /tmp (01777) restricts unlink and rename to UID 0, the directory owner, or the individual file owner.
- Kernel file creation masks effective_mode = base_mode & ~umask (0666 for regular files, 0777 for directories), and recursive chmod -R 777 breaks sudo (/etc/sudoers must remain 0440) and SSH StrictModes.
- Shell startup scripts in /etc/profile and /etc/profile.d/*.sh must preserve existing PATH entries and pass sh -n syntax validation while keeping a rescue root PTY open to prevent login loops.
Step sequence — frame strip: steps_m02_l02
Query numeric and symbolic mode bits with stat -c '%a %A' to audit special high bits (4=setuid, 2=setgid, 1=sticky).
reveals: step1
highlights: step1
Check active shell umask in both symbolic and octal forms before unpacking toolchains or creating staging trees.
reveals: step2
highlights: step2
Place global environment additions in a standalone /etc/profile.d/*.sh file rather than hand-editing /etc/profile.
reveals: step3
highlights: step3
Validate POSIX sh syntax with sh -n and spawn a clean login subshell (bash -lc) before logging out.
reveals: step4
highlights: step4
What you'll learn
- Audit target block devices via /sys/block/<dev>/removable, size, and mount tables before executing raw dd or sfdisk commands.
- Calculate exact byte and 512-byte LBA boundaries across MBR (0x000), i.MX6ULL IVT + U-Boot (0x400), Partition 1 FAT32 (LBA 2048), and Partition 2 ext4.
- Construct and verify POSIX ustar --numeric-owner rootfs tarballs and complete the Module 2 partition/permission guard studio.
Three Ways SD Card Flashing Goes Catastrophically Wrong
dd is affectionately nicknamed disk destroyer by kernel engineers for good reason: block devices (/dev/sda, /dev/sdb, /dev/mmcblk0) expose raw 512-byte sectors from byte 0 to the end of the drive with zero confirmation prompts. On a desktop or VM where the root OS lives on /dev/sda, running sudo dd if=u-boot.imx of=/dev/sda instantly overwrites the host's MBR/GPT partition table!
Even when you select the right USB SD reader (/dev/sdb), omitting bs=1K seek=1 writes u-boot.imx at byte 0x000 (LBA 0) instead of byte 0x400 (1 KiB, LBA 2). That single mistake erases your freshly created MBR partition table AND leaves the i.MX6ULL internal Boot ROM staring at zeros at 0x400!
Once Partition 1 (FAT32 holding zImage + .dtb) and Partition 2 (ext4 rootfs) are formatted, a third silent failure strikes during rootfs extraction: running tar -xpf rootfs.tar.xz without --numeric-owner looks up uname/gname strings from the tarball inside the host's /etc/passwd, mapping target daemon accounts onto random workstation UIDs—or worse, packing an unprivileged staging directory leaves /sbin/init and /etc/sudoers owned by UID 1000 on the board!
Figure 2.3a. Leaving LBA 2..2047 (1,023 KiB from 0x400 to 0xFFFFF) unpartitioned lets raw U-Boot coexist cleanly alongside standard MBR partitions.
mental model: An i.MX6ULL SD card is laid out like a hardcover reference book: page 0 (LBA 0, 0x000) is the Table of Contents (MBR listing where Chapter 1 and Chapter 2 begin), pages 2..2047 (0x400..0xFFFFF) are a dedicated preface reserved for the silicon Boot ROM's IVT and U-Boot binary, and Chapter 1 (Partition 1 FAT32) begins strictly at page 2048 (1 MiB). Forgetting seek=1 glues the preface right over the Table of Contents, while starting Chapter 1 on page 63 lets a 700 KiB preface bleed straight across Chapter 1's opening pages!
Where it stops working: Not all SoCs sample LBA 2 (1 KiB): i.MX8M moves the Boot ROM offset to 32 KiB or 33 KiB so a full 34-sector (17 KiB) GUID Partition Table (GPT header at LBA 1 + 128 partition entries across LBA 2..33) can sit below U-Boot—whereas on i.MX6ULL, standard GPT entries at LBA 2 collide directly with 0x400 unless GPT entry array LBA is relocated or classic MBR is used!
definition (Image Vector Table (IVT @ 0x400) and POSIX ustar Numeric-Owner Header): On power-on reset in SD/eMMC boot mode, the i.MX6ULL internal Boot ROM reads byte offset 0x400 (LBA 2), checking for a 32-byte Image Vector Table (IVT) header starting with tag byte 0xD1 (0x402000D1 or 0x412000D1) followed by DCD DDR3 init commands and U-Boot. Separately, every file in a POSIX.1-1988 ustar .tar archive carries a 512-byte header containing octal ASCII uid (offset 108) and gid (offset 116) plus string uname (offset 265) and gname (offset 297). By default, GNU tar prefers uname/gname strings; passing --numeric-owner forces tar to ignore string names and honor raw 0:0 integers.
- Step 1. Gate every raw flash script on /sys/block/<dev>/removable == 1 and zero active /proc/mounts entries.
- Step 2. Script deterministic partition boundaries with sfdisk starting Partition 1 at LBA 2048 (1 MiB) so U-Boot never overlaps FAT32.
- Step 3. Flash u-boot-dtb.imx at byte 0x400 (bs=1K seek=1) with conv=fsync so unplugging the card never truncates buffered sectors.
- Step 4. Unpack the target rootfs onto mounted Partition 2 with --numeric-owner and run sync + umount before ejecting.
Figure 2.3b. Check removable==1, start p1 >= LBA 2048, flash with bs=1K seek=1, and --numeric-owner.
Exact MBR + IVT Byte Offsets, GPT LBA-2 Collision & ustar Checksums
Let us verify the exact byte arithmetic on an i.MX6ULL bootable SD card. LBA 0 spans 0x000..0x1FF (512 B): the 4 primary partition entries occupy 0x1BE..0x1FD (64 B), where Partition 1's 32-bit little-endian starting LBA sits at 0x1BE + 8 = 0x1C6, followed by MBR signature 0x55, 0xAA at 0x1FE..0x1FF.
LBA 1 (0x200..0x3FF) is unused on MBR, whereas standard GPT places its header at LBA 1 and partition entries across LBA 2..33, colliding straight into 0x400! Starting Partition 1 at LBA 2048 (2048 * 512 = 1,048,576 = 0x100000) gives u-boot-dtb.imx 1,047,552 bytes (1,023 KiB) of headroom above 0x400.
Inside a .tar rootfs archive, each 512-byte ustar block stores magic "ustar" at offset 257, uid (0000000\0) at 108, gid (0000000\0) at 116, and chksum at 148..155. Per POSIX.1-1988, the header checksum equals the unsigned sum of all 512 header bytes when chksum[0..7] is filled with eight ASCII spaces (0x20). Packing a staging folder via tar --numeric-owner --owner=0 --group=0 -cpJf rootfs.tar.xz -C stage . zeroes both uid/gid and uname/gname cleanly without needing sudo chown on the host!
Figure 2.3b. Byte-exact arithmetic proves 0x400 + uboot_bytes <= p1_lba_start * 512 and ustar uid/gid == 0 before hardware flashing.
| Operation | Dangerous Command | Safe Production Command | Failure Prevented |
|---|---|---|---|
| Target device check | Blind DEV=/dev/sda | Verify /sys/block/${DEV}/removable == 1 & lsblk -o NAME,RM,SIZE,MOUNTPOINTS | Prevents overwriting host OS NVMe/SATA disk |
Flash U-Boot (i.MX6ULL) | dd if=u-boot.imx of=/dev/sdb | dd if=u-boot-dtb.imx of=/dev/sdb bs=1K seek=1 conv=fsync | Preserves LBA 0 MBR (seek=1) and flushes dirty cache (conv=fsync) |
| Pack staged rootfs | tar -cpJf rootfs.tar.xz -C stage . | tar --numeric-owner --owner=0 --group=0 -cpJf rootfs.tar.xz -C stage . | Stamps UID 0:0 without leaking host UID 1000 |
Unpack onto SD ext4 | sudo tar -xpf rootfs.tar.xz -C /mnt/p2 | sudo tar --numeric-owner -xpf rootfs.tar.xz -C /mnt/p2 && sync | Avoids remapping target names to host /etc/passwd UIDs |
learner@ksa:~/gl-e00/m02-l03$ bat -H 8 -H 14 flash_sdcard_safe.sh File: flash_sdcard_safe.sh #!/usr/bin/env bash set -euo pipefail DEV_NAME="${1:?Usage: $0 sdX (e.g. sdb)}" SYS_BLK="/sys/block/${DEV_NAME}" # 1. Mandatory host-disk destruction guards [[ "$(cat "${SYS_BLK}/removable")" == "1" ]] || { echo "FATAL: ${DEV_NAME} is NOT removable!" >&2; exit 1; } ! grep -Eq "^/dev/${DEV_NAME}[0-9p]*" /proc/mounts || { echo "FATAL: /dev/${DEV_NAME} has mounted partitions!" >&2; exit 1; } # 2. Partition starting at LBA 2048 (1 MiB) and flash U-Boot at 1 KiB (0x400) sfdisk "/dev/${DEV_NAME}" <<'EOF' label: dos start=2048, size=131072, type=c, bootable start=133120, type=83 EOF dd if=u-boot-dtb.imx of="/dev/${DEV_NAME}" bs=1K seek=1 conv=fsync status=progress- Refuses non-removable SATA/NVMe disks and mounted filesystems before sfdisk or dd can touch a single sector.
- start=2048 places Partition 1 at 1 MiB (0x100000), leaving LBA 2..2047 clear for dd bs=1K seek=1.
dd(1) GL-E00 Quick Reference dd(1) NAME dd, sfdisk, tar - raw sector flashing, MBR partitioning, and numeric-owner archives SYNOPSIS dd if=u-boot-dtb.imx of=/dev/sdX bs=1K seek=1 conv=fsync tar --numeric-owner --owner=0 --group=0 -cpJf rootfs.tar.xz -C _stage . sudo tar --numeric-owner -xpf rootfs.tar.xz -C /mnt/p2 && sync CRITICAL FLAGS seek=N Skip N output blocks (bs=1K seek=1 -> byte 0x400 = LBA 2 on i.MX6ULL). conv=fsync Flush kernel block page cache to physical SD/USB media before dd exits. --numeric-owner Ignore uname/gname strings; store/restore raw numeric UID/GID. Kernel Systems Academy Lesson 2.3 dd(1) GL-E00 quick reference · full manual page: man 1 dd Auditing MBR/IVT Overlap and ustar Numeric-Owner Headers in C11
In verify.c, we synthesize a byte-accurate 512-byte MBR (0x55AA signature + Partition 1 starting LBA in little-endian at 0x1C6) alongside a 512-byte POSIX ustar header in ISO C11. Our auditor checks /sys/block removable flags, verifies whether 0x400 + uboot_size collides with p1_lba_start * 512 (catching legacy LBA 63 overlap on a 650 KiB U-Boot image!), and computes the exact ustar space-filled header checksum while enforcing uid == 0, gid == 0, and empty uname/gname.
learner@ksa:~/gl-e00/m02-l03$ bat -H 16 -H 45 verify.c File: verify.c #define _POSIX_C_SOURCE 200809L #include <stdint.h> #include <stdio.h> #include <stdlib.h> #include <string.h> static int check_mbr_uboot_fit(const unsigned char mbr[512], int is_removable, uint32_t uboot_bytes) { if (!is_removable) return -1; if (mbr[510] != 0x55U || mbr[511] != 0xAAU) return -2; uint32_t p1_lba = (uint32_t)mbr[0x1C6] | ((uint32_t)mbr[0x1C7] << 8) | ((uint32_t)mbr[0x1C8] << 16) | ((uint32_t)mbr[0x1C9] << 24); if (p1_lba < 2048U) return -3; uint64_t uboot_end = 0x400ULL + (uint64_t)uboot_bytes; uint64_t p1_byte_start = (uint64_t)p1_lba * 512ULL; return (uboot_end <= p1_byte_start) ? 0 : -4; } static void build_ustar_hdr(unsigned char h[512], const char *name, unsigned int uid, const char *uname_str) { memset(h, 0, 512); snprintf((char *)(h + 0), 100, "%s", name); snprintf((char *)(h + 100), 8, "%07o", 0755U); snprintf((char *)(h + 108), 8, "%07o", uid); snprintf((char *)(h + 116), 8, "%07o", 0U); snprintf((char *)(h + 124), 12, "%011o", 0U); h[156] = '0'; memcpy(h + 257, "ustar", 6); memcpy(h + 263, "00", 2); snprintf((char *)(h + 265), 32, "%s", uname_str); memset(h + 148, ' ', 8); unsigned int sum = 0; for (int i = 0; i < 512; ++i) sum += h[i]; snprintf((char *)(h + 148), 7, "%06o", sum); h[154] = '\0'; h[155] = ' '; } static int verify_ustar_numeric_root(const unsigned char h[512]) { if (memcmp(h + 257, "ustar", 5) != 0) return -1; unsigned int expected = (unsigned int)strtoul((const char *)(h + 148), NULL, 8); unsigned int sum = 0; for (int i = 0; i < 512; ++i) { sum += (i >= 148 && i < 156) ? (unsigned char)' ' : h[i]; } if (sum != expected) return -2; unsigned long uid = strtoul((const char *)(h + 108), NULL, 8); unsigned long gid = strtoul((const char *)(h + 116), NULL, 8); if (uid != 0UL || gid != 0UL) return -3; if (h[265] != '\0') return -4; /* Host username leaked without --numeric-owner */ return 0; } int main(void) { unsigned char mbr_ok[512] = {0}, mbr_lba63[512] = {0}; mbr_ok[510] = 0x55U; mbr_ok[511] = 0xAAU; mbr_ok[0x1C6] = 0x00U; mbr_ok[0x1C7] = 0x08U; /* 2048 LE = 0x00000800 */ mbr_lba63[510] = 0x55U; mbr_lba63[511] = 0xAAU; mbr_lba63[0x1C6] = 63U; /* Legacy LBA 63 = 31.5 KiB */ uint32_t uboot_sz = 650U * 1024U; int rc_fixed_sda = check_mbr_uboot_fit(mbr_ok, 0, uboot_sz); int rc_lba63 = check_mbr_uboot_fit(mbr_lba63, 1, uboot_sz); int rc_lba2048 = check_mbr_uboot_fit(mbr_ok, 1, uboot_sz); unsigned char tar_good[512], tar_leaked[512]; build_ustar_hdr(tar_good, "sbin/init", 0U, ""); build_ustar_hdr(tar_leaked, "sbin/init", 1000U, "developer"); int rc_tar_ok = verify_ustar_numeric_root(tar_good); int rc_tar_bad = verify_ustar_numeric_root(tar_leaked); printf("sdcard_guard: fixed_sda=%d lba63_overlap=%d lba2048_ok=%d\n", rc_fixed_sda, rc_lba63, rc_lba2048); printf("ustar_guard: numeric_uid0=%d host_uid1000_leak=%d\n", rc_tar_ok, rc_tar_bad); return (rc_fixed_sda == -1 && rc_lba63 == -3 && rc_lba2048 == 0 && rc_tar_ok == 0 && rc_tar_bad == -3) ? 0 : 1; }- Checks 0x400 + uboot_bytes <= p1_lba * 512 so raw U-Boot never clobbers Partition 1's FAT32 superblock.
- Recomputes the POSIX.1-1988 ustar checksum with bytes 148..155 treated as 0x20 spaces and rejects non-zero UIDs.
Confirming Sector Boundary & ustar Header Rejections
Review the execution output: fixed non-removable disks (sda) fail immediately (-1), legacy LBA 63 partitioning fails (-3), and LBA 2048 (1 MiB) accommodates a 650 KiB U-Boot image cleanly (0). On the archive side, sbin/init packed with UID 0 and empty uname passes (0), whereas a host-contaminated UID 1000 header is rejected (-3).
learner@ksa:~/gl-e00/m02-l03gcc -std=c11 -Wall -Wextra -Werror verify.c -o verifylearner@ksa:~/gl-e00/m02-l03./verifysdcard_guard: fixed_sda=-1 lba63_overlap=-3 lba2048_ok=0ustar_guard: numeric_uid0=0 host_uid1000_leak=-3learner@ksa:~/gl-e00/m02-l03learner@ksa:~/gl-e00/m02-l03strace -e trace=write,exit_group ./verifywrite(1, "sdcard_guard: fixed_sda=-1 lba63"..., 106) = 106exit_group(0) = ?+++ exited with 0 +++Page-Cache Eject Corruption & GPT-vs-IVT Collisions
With removable-disk sysfs checks, LBA 2048 alignment, dd bs=1K seek=1 conv=fsync, and tar --numeric-owner, SD and eMMC provisioning becomes deterministic and repeatable. Proceed to labs/lab_m02_perm_partition_guard/ to complete the Module 2 studio.
Pulling the SD Card Right After dd or cp Finishes Without conv=fsync / sync:
- Symptom:
ddprints680240 bytes copiedand returns to the shell prompt in0.02 s, you pull the USB SD reader out, and the board refuses to boot or printsEXT4-fs error: bad magic. - Root Cause: Without
conv=fsync(oroflag=direct/sync),write(2)copies sectors into theLinux kerneldirty page cache in host RAM while USB mass-storage writeback is still in flight! - Fix: Always append
conv=fsyncto rawddinvocations, and after copying files to mountedFAT32/ext4partitions runsync && sudo umount /dev/sdX*and wait forumountto return before unplugging.
Formatting an i.MX6ULL Boot SD Card With Default GPT (gdisk / parted mklabel gpt):
- Symptom: Partitioning succeeds in
gdisk, then runningdd if=u-boot-dtb.imx of=/dev/sdb bs=1K seek=1causesfdisk -lto reportGPT PMBR size mismatch/corrupt primary GPT table! - Root Cause: Standard
GPTplaces its Primary Header atLBA 1(0x200) and its128-entry Partition Array acrossLBA 2..33(0x400..0x43FF)—the exact0x400byte offset wherei.MX6ULLrequires itsIVT! - Fix: Use
MBR(label: dosinsfdisk) oni.MX6ULLSD/eMMC boot media, or ifGPTis mandatory, relocate theGPTpartition entry array (--move-main-tableinsgdisk -j 2048) pastU-Boot.
Guided Practice
Calculate the maximum u-boot-dtb.imx file size (in bytes and KiB) that fits between byte 0x400 (1 KiB) and Partition 1 at LBA 2048 (1 MiB) when U-Boot also stores a 128 KiB persistent environment block at byte offset 0xC0000 (768 KiB). Check your formula in verify.c!
Independent Practice
Complete labs/lab_m02_perm_partition_guard/ by repairing starter/core.c so all 5 TAP version 13 checks pass (sh check.sh) and record CLOCK_MONOTONIC percentiles with ./files/lab_cli --bench.
Verification Checks
? check 1 · Why must dd if=u-boot-dtb.imx of=/dev/sdb bs=1K seek=1 conv=fsync include bs=1K seek=1 when flashing an i.MX6ULL SD card?
- [ ]
bs=1K seek=1enables USB 3.0xhci_hcdscatter-gather DMA. - [ ] Without
seek=1,ddwrites to/dev/sdainstead of/dev/sdb. - [x] It skips bytes
0x000..0x3FF(preserving the512-byte MBR atLBA 0) and writes theIVTheader at byte0x400(LBA 2), where thei.MX6ULLBoot ROM samples it. - [ ]
seek=1skips Partition 1 (FAT32) and writesU-Bootinto Partition 2 (ext4).
Answer: It skips bytes 0x000..0x3FF (preserving the 512-byte MBR at LBA 0) and writes the IVT header at byte 0x400 (LBA 2), where the i.MX6ULL Boot ROM samples it.
Why: Byte 0x000..0x1FF holds the MBR partition table and 0x400 (1024 bytes = 1 KiB) is the hardware-fixed i.MX6ULL SD/MMC IVT boot offset.
Common misconception: Confusing seek= (skipping output blocks on of=) with skip= (skipping input blocks on if=).
? check 2 · An unprivileged engineer stages a target rootfs in /home/alex/rootfs (UID 1000:1000) and packs it with plain tar -cpJf rootfs.tar.xz -C /home/alex/rootfs .. What goes wrong on the target board?
- [ ]
U-Bootchecks.tar.xzheaders at0x400before loadingzImage. - [x] Every file in the archive records
uid=1000(uname="alex"), so/sbin/init,/etc/sudoers, and/etc/sshon the board are owned by non-rootUID 1000instead of0:0. - [ ]
tar -J(xz) stripsS_IFLNKBusyBox symlinks unless run as root. - [ ]
ext4refuses to mount partitions containing files withUID >= 1000.
Answer: Every file in the archive records uid=1000 (uname="alex"), so /sbin/init, /etc/sudoers, and /etc/ssh on the board are owned by non-root UID 1000 instead of 0:0.
Why: Without --numeric-owner --owner=0 --group=0 (or fakeroot), tar records the host user's UID 1000 and username string inside every ustar header.
Common misconception: Assuming tar -p magically converts UID 1000 files to root:root (0:0) during archiving.
? check 3 · Why does formatting an i.MX6ULL boot SD card with a default GPT partition table break as soon as dd bs=1K seek=1 writes u-boot-dtb.imx?
- [x] Default
GPTstores its partition entry array atLBA 2..33(0x400..0x43FF), colliding directly withu-boot-dtb.imxat byte0x400(LBA 2). - [ ] The
Linux kernel6.12mmcblkdriver does not supportGPTonARMv7-A. - [ ]
FAT32(zImagepartition) cannot exist inside aGPTdisk. - [ ]
GPTuses4096-byte sectors exclusively on SDHC cards.
Answer: Default GPT stores its partition entry array at LBA 2..33 (0x400..0x43FF), colliding directly with u-boot-dtb.imx at byte 0x400 (LBA 2).
Why: While MBR occupies only LBA 0 (0x000..0x1FF), standard GPT occupies LBA 1..33 (0x200..0x43FF), overlapping 0x400 unless the GPT entry table LBA is moved.
Common misconception: Assuming GPT fits inside the first 512 bytes like MBR.
1. Motivation
Automated BSP image-creation pipelines must guarantee three non-negotiable safety invariants: never write raw bootloaders onto non-removable host disks or across Partition 1's FAT32 boundary (0x400 + sizeof(u-boot.imx) <= p1_lba * 512), enforce VFS sticky/triad permissions accurately, and ensure staged rootfs tarballs carry clean UID 0:0 --numeric-owner headers.
2. Learning objectives
- Guard raw block writes by validating
removable == 1,mounted_partitions == 0, and exact0x400 + uboot_bytes <= p1_lba_start * 512bounds. - Implement Linux VFS first-match credential triads plus parent
w+x(03) and01000stickyunlinkauthorization. - Verify 512-byte POSIX
ustartar headers for space-filled checksums, octal0:0ownership, and emptyuname/gnamestrings.
3. Environment requirements
All automated verification steps run in unprivileged user space on a POSIX Linux host using gcc -std=c11 -Wall -Wextra -Werror and clock_gettime(CLOCK_MONOTONIC). Recorded transcripts in captures.json were generated on x86_64 running kernel 7.0.0-42-generic and prove protocol, state-machine, and memory invariants only. Physical bus timing, DMA cache coherency, and board peripheral behavior require target validation on Linux kernel 6.12 LTS (ARMv7-A Cortex-A7).
4. Required software and hardware
- Host workstation:
gcc(-std=c11 -Wall -Wextra -Werror), GNUmake,ar(binutils), and POSIX/bin/sh. - Target environment (optional hardware step, Section 13): MicroSD card (
>= 8 GiB) inspected via/sys/block/sdX/removableand booted on ani.MX6ULLARMv7-Aboard (BOOT_MODE = 10internal SD boot) to confirmIVTload at0x400andFAT32zImage/.dtbmount.
5. Complete executable commands
learner@ksa:~/gl-e00/m02-l03$ bat script.sh File: script.sh make -B -C files ./files/lab_cli ./files/lab_cli --bench sh check.sh6. Annotated source code
files/core.c enforces the production invariants that starter/core.c breaks:
learner@ksa:~/gl-e00/m02-l03$ bat example.c File: example.c uint64_t uboot_end_byte = 0x400ULL + (uint64_t)uboot_bytes; uint64_t p1_start_byte = (uint64_t)p1_lba_start * 512ULL; if (uboot_end_byte > p1_start_byte) { return -7; /* Raw U-Boot image overlaps Partition 1 FAT32 superblock */ }starter/core.c seeds three subtle bugs: (1) ksa_guard_sdcard_layout() forgets the 0x400 (1 KiB) IVT offset, allowing a 1024 KiB U-Boot binary to overwrite the first 1 KiB of Partition 1 (FAT32 boot sector at 0x100000!); (2) ksa_check_sticky_unlink() masks 04000U (setuid) instead of 01000U (sticky); and (3) ksa_verify_ustar_root() skips checking uname/gname at bytes 265 and 297.
7. Expected output
Passing files/ run (sh check.sh, exit code 0):
learner@ksa:~/gl-e00/m02-l03$ bat listing.txt File: listing.txt TAP version 13 1..5 ok 1 - builds libcore.a and lab_cli cleanly with -std=c11 -Wall -Wextra -Werror ok 2 - archives core.o into libcore.a and links independent TAP verifier ok 3 - enforces removable==1, 0 mounts, and 0x400 + uboot_bytes <= p1_lba_start * 512 ok 4 - enforces VFS first-match triad, directory w+x (03), and 01000 sticky unlink ownership ok 5 - validates POSIX ustar 512-byte checksum, octal uid/gid == 0, and empty uname/gname # pass 5/5CLI verification output (./files/lab_cli):
learner@ksa:~/gl-e00/m02-l03$ bat listing.txt File: listing.txt sdcard_guard: sda_fixed=-2 sdb_ok=0 sdb_1200k_overlap=-7 sticky_unlink: stranger=0 file_owner=1 ustar_verify: numeric_root=0 leaked_uid1000=-4Defective starter/ run (exit code 1): emits FAIL: diagnostics on the broken contract assertions.
8. Explanation of observed behavior
Look closely at boundary test case 1 in tests.c: when p1_lba_start = 2048 (0x100000 = 1,048,576 B), a 1,023 KiB (1,047,552 B) U-Boot image starting at 0x400 (1,024 B) ends at exact byte 1,048,576 (rc == 0), whereas a 1,024 KiB image overflows by 1,024 bytes into Partition 1 (rc == -7)! Restoring all three checks turns all 5 TAP version 13 assertions green.
9. Experiment variations
- Near transfer: Extend
ksa_guard_sdcard_layout()to accept a persistentU-Bootenvironment region (env_offset = 0xC0000,env_size = 0x20000) and verify that0x400 + uboot_bytes <= env_offsetso growingU-Bootbinaries never overwrite saved board MAC addresses orbootargs. - Far transfer: Write a host CLI tool that opens an actual
.tar(uncompressed) rootfs image, iterates 512-byteustarheaders (advancing by((size + 511) / 512) * 512data blocks), and reports any entry with non-zero UID/GID or host-absolute symlink targets (linknameat offset157).
10. Performance measurements
Recorded host benchmark (./files/lab_cli --bench, CLOCK_MONOTONIC, warmup=5, N=40 batches):
learner@ksa:~/gl-e00/m02-l03$ bat listing.txt File: listing.txt BENCH lab_m02_perm_partition_guard clock=CLOCK_MONOTONIC warmup=5 samples=40 p50_ns=863 p95_ns=1210 p99_ns=1210 sink=0Host CLOCK_MONOTONIC percentiles reflect CPU L1-cached arithmetic and 512-byte checksum loops (~hundreds of nanoseconds), whereas physical SDHC/eMMC sector writes take milliseconds due to NAND block erase cycles.
11. Troubleshooting
| Symptom | Root cause | Fix | ||
|---|---|---|---|---|
not ok 3 - enforces removable==1... (ovl=0 instead of < 0) | uboot_end_byte omitted 0x400ULL, misjudging a 1024 KiB image against LBA 2048. | Compute 0x400ULL + (uint64_t)uboot_bytes and reject > (uint64_t)p1_lba_start * 512ULL. | ||
not ok 4 - enforces VFS first-match triad... (str=1) | Checked 04000U (S_ISUID) instead of 01000U (S_ISVTX sticky bit). | Test (dir_mode & 01000U) != 0U in ksa_check_sticky_unlink(). | ||
not ok 5 - validates POSIX ustar 512-byte checksum... | Disabled check on hdr[265] (uname) and hdr[297] (gname). | Return -5 whenever `hdr[265] != '\0' | hdr[297] != '\0'`. |
12. Guided questions
- Why does a
1,024 KiB(1 MiB)u-boot-dtb.imxoverflow Partition 1 when Partition 1 starts at1 MiB(LBA 2048)?
- *Hint 1:* At what byte offset on the SD card does
dd bs=1K seek=1begin writingu-boot-dtb.imx? - *Hint 2:* Because writing starts at
0x400(1 KiB), a1,024 KiBimage spans0x400..0x1003FF, overwriting the first1,024bytes (2sectors) of Partition 1 at0x100000!
- Why does the POSIX.1-1988
ustarchecksum loop treat bytes148..155as ASCII' '(0x20) instead of0x00?
- *Hint 1:* What characters occupy
hdr[148..155]at the exact momenttarcomputes the sum before formatting the octal checksum string into that same field? - *Hint 2:* Before writing the octal digits into
hdr[148..155], a compliant writer pre-fills the 8-byte checksum field with spaces (0x20), sums all 512 bytes, and then writes the octal sum intohdr[148..154].
13. Independent challenges
Add ksa_parse_mbr_table(const unsigned char mbr[512], uint32_t *p1_lba, uint32_t *p2_lba) to verify 0x55AA, ensure Partition 1 (0x1BE) has type 0x0C (FAT32 LBA), Partition 2 (0x1CE) has type 0x83 (Linux), and confirm p1_lba + p1_sectors <= p2_lba (zero partition overlap).
14. Solutions and explanations
The reference files/core.c adds 0x400ULL to uboot_bytes before comparing against p1_lba_start * 512ULL, tests 01000U for sticky directory unlinks after first-match triad w+x evaluation, and verifies both 0:0 numeric IDs and empty uname/gname fields in ustar headers.
Run locally in your terminal and check off each verification milestone.
Not started
Summary
- Before raw SD card writes, scripts must verify /sys/block/<dev>/removable == 1, zero mounted partitions in /proc/mounts, and sane capacity bounds so dd never targets host /dev/sda or /dev/nvme0n1.
- On i.MX6ULL SD/eMMC boot media, LBA 0 (0x000..0x1FF) holds the 512-byte MBR, LBA 2 (byte 0x400, 1 KiB) holds the raw Boot ROM IVT + U-Boot image (dd bs=1K seek=1), and Partition 1 starts at LBA 2048 (1 MiB).
- Partition 1 (FAT32, 0x0C) stores zImage and Device Tree .dtb files read by U-Boot, while Partition 2 (ext4, 0x83) stores the persistent Linux root filesystem.
- Packing and extracting target rootfs archives with tar --numeric-owner --owner=0 --group=0 -cpf preserves raw UID/GID 0:0 integers in POSIX ustar headers without host /etc/passwd name contamination.
Step sequence — frame strip: steps_m02_l03
Gate every raw flash script on /sys/block/<dev>/removable == 1 and zero active /proc/mounts entries.
reveals: step1
highlights: step1
Script deterministic partition boundaries with sfdisk starting Partition 1 at LBA 2048 (1 MiB) so U-Boot never overlaps FAT32.
reveals: step2
highlights: step2
Flash u-boot-dtb.imx at byte 0x400 (bs=1K seek=1) with conv=fsync so unplugging the card never truncates buffered sectors.
reveals: step3
highlights: step3
Unpack the target rootfs onto mounted Partition 2 with --numeric-owner and run sync + umount before ejecting.
reveals: step4
highlights: step4
m03/
APT Package Graphs, Dual-NIC Routing & TFTP/NFS Boot Bench
Operate signed APT/dpkg package state machines, isolate ARMv7 cross-compilation pkg-config sysroots from host x86_64 headers, route multi-homed WAN + static bench Ethernet subnets without dual-gateway blackholes, and verify RFC 1350 TFTP plus NFSv3 rootfs network boot.
What you'll learn
- Trace package ownership and state transitions using dpkg -L, dpkg -S, /var/lib/dpkg/status, and signed APT DEB822 repositories.
- Diagnose /var/lib/dpkg/lock-frontend flock contention via fuser/lsof and recover interrupted unpacks with dpkg --configure -a.
- Isolate ARMv7-A cross-compilation from host x86_64 headers and libraries using PKG_CONFIG_LIBDIR and PKG_CONFIG_SYSROOT_DIR.
How Host Package Managers Help—and Quietly Sabotage—Cross-Compilation
Setting up a fresh Ubuntu 22.04/24.04 LTS or Debian 12 workstation for Linux kernel and U-Boot development starts with installing host build tools (bc, bison, flex, libssl-dev, device-tree-compiler, u-boot-tools). Under the hood, two distinct tools cooperate: apt fetches repository metadata listed in /etc/apt/sources.list.d/ubuntu.sources, verifies GPG signatures (signed-by /usr/share/keyrings/*.gpg), solves the dependency graph, and hands downloaded .deb archives (ar containers holding control.tar.zst and data.tar.zst) to dpkg, which unpacks files and updates /var/lib/dpkg/status.
Two traps hit embedded engineers immediately. First, right after a VM boots, background unattended-upgrades holds an exclusive flock(2) on /var/lib/dpkg/lock-frontend; following bad forum advice to run sudo rm /var/lib/dpkg/lock* does not stop the running dpkg process and risks corrupting /var/lib/dpkg/status mid-write! Second, once you install host -dev libraries (zlib1g-dev, libasound2-dev), running a cross-compiled Makefile that invokes pkg-config --cflags --libs alsa silently returns host -I/usr/include and -L/usr/lib/x86_64-linux-gnu, causing arm-linux-gnueabihf-ld to abort with skipping incompatible /usr/lib/x86_64-linux-gnu/libasound.so!
Figure 3.1a. PKG_CONFIG_LIBDIR replaces the default x86_64 search path (unlike PKG_CONFIG_PATH, which only prepends!), while PKG_CONFIG_SYSROOT_DIR prefixes -I and -L.
mental model: Think of dpkg as a warehouse inventory clerk who bolts crates onto shelves and writes every bolt's shelf coordinate into /var/lib/dpkg/status, while apt is the procurement planner who checks supplier wax seals (GPG -> SHA-256) and orders every prerequisite bracket first. Ripping the Occupied sign off the warehouse door (rm lock-frontend) while a clerk is still inside causes two clerks to overwrite the same ledger page! And setting PKG_CONFIG_PATH instead of PKG_CONFIG_LIBDIR tells the clerk *'check the ARM shelf first, and if a part is missing, silently grab an x86 truck bolt off the host shelf!'*
Where it stops working: flock(2) locks the kernel open file description (struct file / inode), not the directory pathname: unlinking /var/lib/dpkg/lock-frontend allows a second apt process to create a brand-new inode and acquire a second flock concurrently with the first!
definition (Advisory Inode Lock (flock) and PKG_CONFIG_LIBDIR vs PKG_CONFIG_PATH): When apt starts, it opens /var/lib/dpkg/lock-frontend and issues flock(fd, LOCK_EX | LOCK_NB). If the process crashes (SIGKILL or power loss), the Linux kernel closes fd automatically and releases the lock—leaving the zero-byte file on disk harmlessly! Only package state iU (unpacked, unconfigured) remains, which sudo dpkg --configure -a completes. In pkg-config, PKG_CONFIG_PATH prepends to /usr/lib/x86_64-linux-gnu/pkgconfig, whereas PKG_CONFIG_LIBDIR replaces the compiled-in host search list completely.
- Step 1. Use dpkg -S to identify which package owns a header or binary and dpkg -L to inspect installed utilities like mkimage.
- Step 2. Inspect live lock holders via fuser -v instead of unlinking lock files, then replay unfinished postinst scripts if idle.
- Step 3. Pin every repository in /etc/apt/sources.list.d/*.sources to a dedicated keyring file via Signed-By.
- Step 4. Export PKG_CONFIG_DIR, PKG_CONFIG_LIBDIR, and PKG_CONFIG_SYSROOT_DIR inside cross-build scripts and verify emitted flags.
Figure 3.1b. Never rm dpkg locks; use fuser + dpkg --configure -a and PKG_CONFIG_LIBDIR.
Inside .deb Archives, flock() Lifetimes & Cross-Sysroot Flag Rewriting
A .deb package is a standard Unix ar archive (ar t foo.deb) containing three members in fixed order: debian-binary (2.0\n), control.tar.zst (control metadata, md5sums, preinst/postinst scripts), and data.tar.zst (the FHS payload tree). During installation, dpkg transitions the package status in /var/lib/dpkg/status from not-installed -> unpacked (iU) -> installed (ii), syncing journal updates under /var/lib/dpkg/updates/.
Now trace what happens when cross-compiling an ALSA or DRM application for ARMv7-A against a staged sysroot at /opt/sysroots/armhf. Inside the sysroot, alsa.pc states prefix=/usr and includedir=${prefix}/include, so raw pkg-config --cflags alsa would print -I/usr/include! Setting PKG_CONFIG_SYSROOT_DIR=/opt/sysroots/armhf instructs pkg-config to rewrite every -I/usr/... and -L/usr/... token into -I/opt/sysroots/armhf/usr/include and -L/opt/sysroots/armhf/usr/lib/arm-linux-gnueabihf, while PKG_CONFIG_LIBDIR guarantees that missing target .pc files fail loudly instead of falling back to host x86_64 .pc files.
Figure 3.1b. Combining PKG_CONFIG_LIBDIR (search isolation) with PKG_CONFIG_SYSROOT_DIR (prefix rewriting) guarantees 100% EM_ARM header/library purity.
| Environment / Command | Behavior on Missing Target .pc | Emitted -I / -L Flags | Cross-Build Safety |
|---|---|---|---|
Unconfigured pkg-config | Reads host x86_64 .pc silently! | -I/usr/include -L/usr/lib/x86_64-linux-gnu | Broken: mixes x86 headers & fails ARM link |
PKG_CONFIG_PATH=$SYS/... only | Falls back to host x86_64 .pc! | Bare -I/usr/include (no $SYS prefix!) | Broken: silent fallback + unprefixed -I |
PKG_CONFIG_LIBDIR=$SYS/... only | Fails cleanly (Package not found) | Bare -I/usr/include (prefix=/usr unrewritten) | Incomplete: still points -I at host /usr |
PKG_CONFIG_DIR='' + LIBDIR + SYSROOT_DIR | Fails cleanly (Package not found) | -I$SYS/usr/include -L$SYS/usr/lib/... | Production safe: isolated search + prefixed paths |
learner@ksa:~/gl-e00/m03-l01$ bat -H 6 -H 9 arm-pkg-config File: arm-pkg-config #!/usr/bin/env bash set -euo pipefail : "${KSA_ARM_SYSROOT:?Set KSA_ARM_SYSROOT to your staged ARMv7 rootfs path}" unset PKG_CONFIG_PATH export PKG_CONFIG_DIR="" export PKG_CONFIG_LIBDIR="${KSA_ARM_SYSROOT}/usr/lib/arm-linux-gnueabihf/pkgconfig:${KSA_ARM_SYSROOT}/usr/lib/pkgconfig:${KSA_ARM_SYSROOT}/usr/share/pkgconfig" export PKG_CONFIG_SYSROOT_DIR="${KSA_ARM_SYSROOT}" exec pkg-config "$@"- Unsetting PKG_CONFIG_PATH and replacing PKG_CONFIG_LIBDIR cuts off /usr/lib/x86_64-linux-gnu completely.
- PKG_CONFIG_SYSROOT_DIR rewrites prefix=/usr inside target .pc files to ${KSA_ARM_SYSROOT}/usr.
dpkg(1) GL-E00 Quick Reference dpkg(1) NAME dpkg, apt-get, pkg-config - Debian package ledger, signed repo solver, and sysroot flags SYNOPSIS dpkg -L <pkg> # List all files installed by <pkg> dpkg -S /usr/bin/mkimage # Find which installed package owns a file sudo fuser -v /var/lib/dpkg/lock-frontend sudo dpkg --configure -a # Finish interrupted iU package configuration CROSS-COMPILATION ENVIRONMENT PKG_CONFIG_DIR="" PKG_CONFIG_LIBDIR="$SYSROOT/usr/lib/arm-linux-gnueabihf/pkgconfig:$SYSROOT/usr/share/pkgconfig" PKG_CONFIG_SYSROOT_DIR="$SYSROOT" Kernel Systems Academy Lesson 3.1 dpkg(1) GL-E00 quick reference · full manual page: man 1 dpkg Testing Kernel flock() Contention and Sysroot Flag Isolation in C11
In verify.c, we exercise real Linux kernel flock() advisory locking on two independent open file descriptions (open() called twice on the same lock path, mirroring two concurrent apt processes) and confirm that the second flock(fd2, LOCK_EX | LOCK_NB) fails immediately with EWOULDBLOCK—and succeeds the instant close(fd1) releases the kernel lock without deleting the lock file!
Next, rewrite_and_audit_cflags() models PKG_CONFIG_SYSROOT_DIR rewriting and inspects compiler/linker token streams to block bare -I/usr/include or -L/usr/lib/x86_64-linux-gnu host-poisoning flags.
learner@ksa:~/gl-e00/m03-l01$ bat -H 41 -H 47 verify.c File: verify.c #define _DEFAULT_SOURCE #include <errno.h> #include <fcntl.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <sys/file.h> #include <unistd.h> static int audit_cross_flags(const char *flags) { char buf[320]; snprintf(buf, sizeof(buf), "%s", flags); char *save = NULL; for (char *t = strtok_r(buf, " ", &save); t; t = strtok_r(NULL, " ", &save)) { if (strncmp(t, "-I/usr/", 7) == 0 || strcmp(t, "-I/usr") == 0) { return -1; /* Unprefixed host /usr header leak */ } if (strncmp(t, "-L/usr/", 7) == 0 || strstr(t, "x86_64-linux-gnu") != NULL) { return -2; /* Host x86_64 library directory leak */ } } return 0; } static void apply_sysroot_prefix(const char *sysroot, const char *raw_flag, char *out, size_t cap) { if ((strncmp(raw_flag, "-I/", 3) == 0 || strncmp(raw_flag, "-L/", 3) == 0) && strncmp(raw_flag + 2, sysroot, strlen(sysroot)) != 0) { snprintf(out, cap, "%.2s%s%s", raw_flag, sysroot, raw_flag + 2); } else { snprintf(out, cap, "%s", raw_flag); } } int main(void) { char lpath[] = "/tmp/ksa_dpkg_lock_XXXXXX"; int fd1 = mkstemp(lpath); if (fd1 < 0) return 1; int fd2 = open(lpath, O_RDWR); if (fd2 < 0) return 1; int r1 = flock(fd1, LOCK_EX | LOCK_NB); errno = 0; int r2_contend = flock(fd2, LOCK_EX | LOCK_NB); int contend_eagain = (r2_contend == -1 && errno == EWOULDBLOCK); /* Closing fd1 (as when apt exits or crashes) releases flock without unlink! */ close(fd1); int r2_after = flock(fd2, LOCK_EX | LOCK_NB); close(fd2); unlink(lpath); const char *leaked = "-I/usr/include/alsa -L/usr/lib/x86_64-linux-gnu -lasound"; char fixed_i[128], fixed_l[128], combined[320]; apply_sysroot_prefix("/opt/sysroots/armhf", "-I/usr/include/alsa", fixed_i, sizeof(fixed_i)); apply_sysroot_prefix("/opt/sysroots/armhf", "-L/usr/lib/arm-linux-gnueabihf", fixed_l, sizeof(fixed_l)); snprintf(combined, sizeof(combined), "%s %s -lasound", fixed_i, fixed_l); int rc_bad = audit_cross_flags(leaked); int rc_good = audit_cross_flags(combined); printf("dpkg_flock: acquire1=%d contend_eblock=%d acquire_after_close=%d\n", r1, contend_eagain, r2_after); printf("pkgconfig_audit: host_leak_rc=%d sysroot_clean_rc=%d\n", rc_bad, rc_good); printf("rewritten_flags: %s\n", combined); return (r1 == 0 && contend_eagain == 1 && r2_after == 0 && rc_bad == -1 && rc_good == 0) ? 0 : 1; }- Second open() creates an independent struct file, so flock(LOCK_EX|LOCK_NB) returns -1 (EWOULDBLOCK).
- Closing fd1 immediately releases the kernel inode lock without unlinking the lock file.
Observing flock(LOCK_EX|LOCK_NB) = -1 EAGAIN in strace
Look right inside the strace capture: flock(3, LOCK_EX|LOCK_NB) = 0, followed by flock(4, LOCK_EX|LOCK_NB) = -1 EAGAIN (Resource temporarily unavailable), close(3) = 0, and flock(4, LOCK_EX|LOCK_NB) = 0! That single four-syscall sequence proves why an idle /var/lib/dpkg/lock-frontend file on disk never blocks apt once the owning process exits, and why rm /var/lib/dpkg/lock* is always wrong.
learner@ksa:~/gl-e00/m03-l01gcc -std=c11 -Wall -Wextra -Werror verify.c -o verifylearner@ksa:~/gl-e00/m03-l01./verifydpkg_flock: acquire1=0 contend_eblock=1 acquire_after_close=0pkgconfig_audit: host_leak_rc=-1 sysroot_clean_rc=0rewritten_flags: -I/opt/sysroots/armhf/usr/include/alsa -L/opt/sysroots/armhf/usr/lib/arm-linux-gnueabihf -lasoundlearner@ksa:~/gl-e00/m03-l01learner@ksa:~/gl-e00/m03-l01strace -e \trace=openat,flock,close,unlinkat,write ./verifyopenat(AT_FDCWD, "/etc/ld.so.cache", O_RDONLY|O_CLOEXEC) = 3close(3) = 0openat(AT_FDCWD, "/lib/x86_64-linux-gnu/libc.so.6", O_RDONLY|O_CLOEXEC) = 3close(3) = 0openat(AT_FDCWD, "/tmp/ksa_dpkg_lock_UA12qG", O_RDWR|O_CREAT|O_EXCL, 0600) = 3openat(AT_FDCWD, "/tmp/ksa_dpkg_lock_UA12qG", O_RDWR) = 4flock(3, LOCK_EX|LOCK_NB) = 0flock(4, LOCK_EX|LOCK_NB) = -1 EAGAIN (Resource temporarily unavailable)close(3) = 0flock(4, LOCK_EX|LOCK_NB) = 0close(4) = 0write(1, "dpkg_flock: acquire1=0 contend_e"..., 229) = 229+++ exited with 0 +++Multiarch Conflicts and Deprecated apt-key Anti-Patterns
Keeping host package management clean and cross-build pkg-config strictly fenced inside $SYSROOT prevents subtle ABI mismatches before they turn into mysterious target SIGSEGV crashes.
Using [trusted=yes] or Legacy apt-key add for Third-Party Toolchains:
- Symptom:
apt updateprintsKey is stored in legacy trusted.gpg keyringor accepts unsignedPackagesfiles over plain HTTP. - Root Cause:
[trusted=yes]disables GPG verification completely, while/etc/apt/trusted.gpgtrusts a third-party vendor's key to sign packages for every repository on the system (includinglinux-image-generic!). - Fix: Place the dearmored
.gpgkey in/etc/apt/keyrings/<vendor>.gpg(0644) and scope it strictly inside that single.sourcesentry usingSigned-By: /etc/apt/keyrings/<vendor>.gpg.
Autotools ./configure Runs Host pkg-config Instead of Cross Wrapper:
- Symptom: You pass
--host=arm-linux-gnueabihfto./configure, yet the build still pulls/usr/includefrom thex86_64host. - Root Cause: Autotools looks for
arm-linux-gnueabihf-pkg-configfirst; if no prefixed wrapper exists onPATH, it falls back to bare hostpkg-configwith default hostPKG_CONFIG_LIBDIR! - Fix: Either save our
arm-pkg-configwrapper ontoPATHnamedarm-linux-gnueabihf-pkg-config(chmod 0755), or exportPKG_CONFIG=/path/to/arm-pkg-configexplicitly.
Guided Practice
Modify verify.c to open lpath a third time (fd3) after unlinking lpath while fd2 still holds LOCK_EX (unlink(lpath) -> fd3 = open(lpath, O_CREAT|O_RDWR, 0600) -> flock(fd3, LOCK_EX|LOCK_NB)). Observe that flock(fd3) returns 0—proving in C11 how rm /var/lib/dpkg/lock-frontend lets two dpkg processes corrupt /var/lib/dpkg/status simultaneously!
Independent Practice
Write a C11 parser for /var/lib/dpkg/status stanzas (Package:, Status:, Architecture:) that flags any package not in install ok installed (ii) state so CI container health checks detect interrupted iU transactions.
Verification Checks
? check 1 · Why does running sudo rm /var/lib/dpkg/lock-frontend when apt says Could not get lock risk corrupting /var/lib/dpkg/status?
- [ ]
lock-frontendstores the GPG master private key needed to verify Ubuntu updates. - [ ] Deleting
lock-frontenddeletes/bin/dpkgbecause the two files are hard links. - [ ] The
Linux kernelpanics whenever anflock-locked file is unlinked from/var/lib. - [x]
flock(2)is bound to the open inode held by a liveapt/unattended-upgradesprocess; unlinking the path lets a secondaptcreate a new inode and mutate/var/lib/dpkg/statusconcurrently!
Answer: flock(2) is bound to the open inode held by a live apt/unattended-upgrades process; unlinking the path lets a second apt create a new inode and mutate /var/lib/dpkg/status concurrently!
Why: Because unlink() only removes the directory entry while the first process keeps writing under its open struct file, a new process opening the same path creates a second inode with its own independent flock!
Common misconception: Thinking presence of the file /var/lib/dpkg/lock-frontend itself is the lock rather than an active process holding flock(fd, LOCK_EX).
? check 2 · When cross-compiling an ARMv7-A user-space daemon against $SYSROOT, why must you set PKG_CONFIG_LIBDIR instead of only PKG_CONFIG_PATH?
- [ ]
pkg-configignoresPKG_CONFIG_PATHwheneverCROSS_COMPILEis set. - [ ]
PKG_CONFIG_LIBDIRautomatically invokesqemu-arm-staticon x86_64.sofiles. - [x]
PKG_CONFIG_PATHonly prepends directories and still falls back to/usr/lib/x86_64-linux-gnu/pkgconfigwhen a target library is missing, whereasPKG_CONFIG_LIBDIRreplaces the host search path completely. - [ ]
PKG_CONFIG_PATHignores-Llinker flags and only rewrites-Iheader flags.
Answer: PKG_CONFIG_PATH only prepends directories and still falls back to /usr/lib/x86_64-linux-gnu/pkgconfig when a target library is missing, whereas PKG_CONFIG_LIBDIR replaces the host search path completely.
Why: Replacing the default compiled-in x86_64 directory list via PKG_CONFIG_LIBDIR ensures missing target dependencies fail cleanly at configure time rather than poisoning the build with host .pc files.
Common misconception: Assuming PKG_CONFIG_PATH disables the built-in host /usr/lib/<arch>/pkgconfig fallback.
? check 3 · Which command identifies the exact installed Debian/Ubuntu package that placed /usr/bin/mkimage onto your workstation?
- [ ]
pkg-config --modversion mkimage - [x]
dpkg -S /usr/bin/mkimage - [ ]
dpkg -L /usr/bin/mkimage - [ ]
apt-get install --dry-run /usr/bin/mkimage
Answer: dpkg -S /usr/bin/mkimage
Why: dpkg -S (--search) scans /var/lib/dpkg/info/*.list to map a filesystem path back to its owning package (u-boot-tools: /usr/bin/mkimage), whereas dpkg -L expects a package name.
Common misconception: Swapping dpkg -S <path> (owner lookup) and dpkg -L <pkg> (package file listing).
Summary
- Debian and Ubuntu split package management into dpkg (/var/lib/dpkg/status local archive installer and file-ownership ledger) and apt (cryptographically signed InRelease dependency solver).
- APT verifies a three-link trust chain—GPG signed-by keyring on InRelease, SHA-256 of Packages.xz, and SHA-256 of each .deb—while serializing mutations via kernel flock() on /var/lib/dpkg/lock-frontend.
- Cross-compiling against an ARMv7 target sysroot requires setting PKG_CONFIG_DIR='', PKG_CONFIG_LIBDIR to the sysroot pkgconfig directories, and PKG_CONFIG_SYSROOT_DIR so host /usr/include paths never leak.
- When an interrupted dpkg run leaves half-configured packages (state iU) and zero live apt/dpkg processes hold the flock, dpkg --configure -a replays idempotent postinst scripts safely without deleting lock files.
Step sequence — frame strip: steps_m03_l01
Use dpkg -S to identify which package owns a header or binary and dpkg -L to inspect installed utilities like mkimage.
reveals: step1
highlights: step1
Inspect live lock holders via fuser -v instead of unlinking lock files, then replay unfinished postinst scripts if idle.
reveals: step2
highlights: step2
Pin every repository in /etc/apt/sources.list.d/*.sources to a dedicated keyring file via Signed-By.
reveals: step3
highlights: step3
Export PKG_CONFIG_DIR, PKG_CONFIG_LIBDIR, and PKG_CONFIG_SYSROOT_DIR inside cross-build scripts and verify emitted flags.
reveals: step4
highlights: step4
What you'll learn
- Configure a multi-homed Netplan/iproute2 host table keeping 0.0.0.0/0 on WAN while serving 192.168.10.0/24 on-link to the target board.
- Trace RFC 1350 TFTP opcodes (RRQ=1, WRQ=2, DATA=3, ACK=4, ERROR=5), ephemeral UDP TIDs, and exact-512B-multiple 0-byte EOF packets.
- Verify non-overlapping U-Boot DDR3 load addresses (0x80800000 zImage, 0x83000000 .dtb) before executing bootz.
Why Plugging In Your Board's Ethernet Cable Suddenly Breaks Host Internet
Watch what happens on almost every engineer's first embedded network-boot setup: the laptop or VM has working internet over wlan0 (or eth0 NAT), the engineer plugs a USB-Ethernet dongle (enx00e04c680102) straight into the i.MX6ULL board's RJ45 port, opens network settings, types IP 192.168.10.10, mask 255.255.255.0, and—out of habit—fills in Gateway: 192.168.10.1. Instantly, git fetch, apt update, and SSH to cloud servers hang completely!
Why? The Linux kernel Forwarding Information Base (FIB, inspected via ip route) matches destinations by longest prefix length first (/24 beats /0), and breaks ties between equal prefixes (0.0.0.0/0) by lowest metric. NetworkManager and systemd-networkd assign wired Ethernet metric 100 and Wi-Fi metric 600.
Adding a fake gateway on the wired bench dongle installs default via 192.168.10.1 metric 100, routing all world internet packets down a 1-meter cable connected only to your target board! Leaving gateway blank on the bench NIC preserves 192.168.10.0/24 scope link for U-Boot TFTP while keeping 0.0.0.0/0 cleanly on wlan0.
Figure 3.2a. An isolated point-to-point or bench-switch subnet needs only an on-link /24 prefix (ARP), never a default gateway.
mental model: A default gateway (0.0.0.0/0) is the highway on-ramp sign for *'All Other Cities'*. If you bolt a private cul-de-sac driveway (192.168.10.0/24) onto the back of your lab and hang an *'All Other Cities — Express Lane'* (metric 100) sign over that dead-end driveway, every delivery truck bound for New York drives straight into your workbench wall! Labelling the driveway strictly *'192.168.10.1–.254 Only'* (scope link) sends board traffic down the cable and everything else onto the real highway.
Where it stops working: If two NICs accidentally share the same IPv4 subnet (for instance corporate Wi-Fi is already 192.168.10.0/24 and you assign 192.168.10.10/24 to the bench dongle), even omitting gateway fails because both interfaces own /24 prefixes of equal length—pick a dedicated RFC 1918 bench subnet like 192.168.77.0/24 or 10.77.0.0/24!
definition (RFC 1350 Trivial File Transfer Protocol (TFTP) Lockstep Framing): Designed in 1981 (RFC 1350) to fit inside tiny 4 KiB boot ROMs and U-Boot without a TCP state machine, TFTP runs over UDP. Every packet starts with a 16-bit big-endian opcode: 1 = RRQ (Read Request to UDP/69 carrying NUL-terminated filename + "octet\0"), 2 = WRQ, 3 = DATA (2 B opcode + 2 B 1-based block number + 0..512 B payload), 4 = ACK (2 B opcode + 2 B block number), and 5 = ERROR. Because DATA headers carry no length field, UDP datagram payload length determines end-of-file: 512 B means more blocks follow, whereas 0..511 B terminates the transfer immediately.
- Step 1. Assign a /24 address without a gateway to the wired bench interface and verify routing with ip route get 8.8.8.8 and ip route get 192.168.10.50.
- Step 2. Configure /etc/default/tftpd-hpa with --secure so U-Boot requests bare filenames ('zImage') confined inside /srv/tftp.
- Step 3. Copy compiled zImage and .dtb artifacts into /srv/tftp with world-readable 0644 permissions for the unprivileged tftp daemon.
- Step 4. Fetch zImage at 0x80800000 and Device Tree at 0x83000000 in U-Boot, then launch Linux 6.12 via bootz.
Figure 3.2b. Omit gateway on bench NICs, pass bare names to --secure tftpd, and separate DTB by 40 MiB.
RFC 1350 Wire Bytes, Exact-512B EOF Edge Case & DDR3 Load Map
Examine RFC 1350's wire framing closely because you will implement its verifier in the Module 3 studio. When U-Boot runs tftp 0x80800000 zImage, it sends RRQ [00 01 'z' 'I' 'm' 'a' 'g' 'e' 00 'o' 'c' 't' 'e' 't' 00] to 192.168.10.10:69. in.tftpd opens a fresh ephemeral socket (UDP/54321, the server Transfer Identifier TID) and sends DATA [00 03 00 01 <512B>] directly from port 54321 (leaving port 69 free for other boards; note host ufw/nftables needs nf_conntrack_tftp or bench interface allow-rules so ephemeral replies aren't dropped!).
What if board.dtb is exactly 32,768 bytes (64 * 512, size % 512 == 0)? Block 64 carries 512 bytes, which tells U-Boot more data follows! After U-Boot sends ACK 64, tftpd must transmit Block 65 ([00 03 00 41] with 0 payload bytes, 4 B total UDP payload) to signal EOF (total_blocks = size / 512 + 1!). Finally, on i.MX6ULL (512 MiB DDR3 at 0x80000000..0x9FFFFFFF), zImage at 0x80800000 (+8 MiB) decompresses Image (typically 12..24 MiB + .bss); placing .dtb at 0x83000000 (+48 MiB) guarantees a 40 MiB decompression buffer!
Figure 3.2b. Exact-multiple-of-512 files require N/512 + 1 DATA blocks (a final 0-byte DATA packet) to close an RFC 1350 session cleanly.
| Symptom on Bench | Underlying Network / Memory Root Cause | Diagnostic Command | Fix | |
|---|---|---|---|---|
| Host internet dies when bench NIC connects | Bench NIC configured a gateway, installing 0.0.0.0/0 metric 100 | ip route show & ip route get 8.8.8.8 | Remove gateway4/routes: default on static bench NIC | |
U-Boot prints TFTP error: 'File not found' (1) | Passed /srv/tftp/zImage to --secure chrooted tftpd-hpa | journalctl -u tftpd-hpa | Use relative tftp 0x80800000 zImage + chmod 0644 | |
U-Boot prints T T T T (timeouts) | Host firewall (ufw) blocks UDP/69 or bench NIC lacks /24 IP | `ss -ulnp | grep :69 & sudo tcpdump -ni enx0` | sudo ufw allow in on enx0 to any port 69 proto udp |
Starting kernel ... hangs silently | Loaded .dtb at 0x80A00000, overwritten by zImage decompression! | Check bdinfo & fdtaddr in U-Boot | Load .dtb at 0x83000000 (>= 32 MiB above 0x80800000) |
learner@ksa:~/gl-e00/m03-l02$ bat -H 5 -H 9 99-bench-dual-nic.yaml File: 99-bench-dual-nic.yaml # /etc/netplan/99-bench-dual-nic.yaml (chmod 0600 root:root -> sudo netplan apply) network: version: 2 ethernets: enp0s3: # Adapter 1 (WAN / NAT): owns sole 0.0.0.0/0 default gateway dhcp4: true enx00e04c680102: # Adapter 2 (USB-Ethernet to i.MX6ULL): ON-LINK ONLY, NO routes/gateway4! dhcp4: false addresses: - 192.168.10.10/24- WAN interface acquires 0.0.0.0/0 via DHCP so git and apt remain online at all times.
- Omitting routes/gateway4 installs only '192.168.10.0/24 scope link', preventing dual-gateway blackholes.
in.tftpd(8) GL-E00 Quick Reference in.tftpd(8) NAME in.tftpd, ip-route, bootz - RFC 1350 TFTP server, FIB routing, and U-Boot ARMv7 boot SYNOPSIS ip route show # Verify sole 0.0.0.0/0 WAN route ip route get 192.168.10.50 # Confirm on-link bench NIC selection sudo systemctl status tftpd-hpa && ss -ulnp | grep :69 U-Boot COMMANDS (i.MX6ULL DDR3 @ 0x80000000) setenv ipaddr 192.168.10.50; setenv serverip 192.168.10.10 tftp 0x80800000 zImage tftp 0x83000000 imx6ull-board.dtb bootz 0x80800000 - 0x83000000 Kernel Systems Academy Lesson 3.2 in.tftpd(8) GL-E00 quick reference · full manual page: man 8 in.tftpd Simulating Kernel FIB Longest-Prefix Lookup and RFC 1350 Framing in C11
In verify.c, we build two deterministic verifiers in ISO C11. First, fib_lookup() implements exact Linux kernel IPv4 longest-prefix-length + lowest-metric tie-breaking, demonstrating mathematically how adding 0.0.0.0/0 metric 100 on enx0 steals 8.8.8.8 away from wlan0 (metric 600), while an on-link /24 (gateway == 0) keeps 8.8.8.8 on wlan0 and routes 192.168.10.50 (0xC0A80A32) straight to enx0.
Second, run_tftp_codec() encodes a real big-endian RFC 1350 RRQ + DATA/ACK transfer for a 1,024-byte (2 * 512) payload, verifying that 3 DATA blocks (512 + 512 + 0 bytes) and 3 ACK blocks execute in lockstep, alongside checking zImage/DTB DDR3 decompression clearance.
learner@ksa:~/gl-e00/m03-l02$ bat -H 20 -H 31 verify.c File: verify.c #define _POSIX_C_SOURCE 200809L #include <stdint.h> #include <stdio.h> #include <string.h> typedef struct { const char *dev; uint32_t prefix; int prefix_len; uint32_t gateway; int metric; } fib_route_t; static uint32_t mask_from_len(int plen) { return (plen <= 0) ? 0U : (0xFFFFFFFFU << (32 - plen)); } static const fib_route_t *fib_lookup(const fib_route_t *rt, size_t n, uint32_t dst_ip) { const fib_route_t *best = NULL; for (size_t i = 0; i < n; ++i) { uint32_t m = mask_from_len(rt[i].prefix_len); if ((dst_ip & m) != (rt[i].prefix & m)) continue; if (!best || rt[i].prefix_len > best->prefix_len || (rt[i].prefix_len == best->prefix_len && rt[i].metric < best->metric)) { best = &rt[i]; } } return best; } static int simulate_tftp_blocks(size_t file_bytes, size_t *last_payload_out) { size_t blocks = (file_bytes / 512U) + 1U; *last_payload_out = file_bytes % 512U; unsigned char pkt[516]; for (size_t b = 1; b <= blocks; ++b) { size_t pay = (b < blocks) ? 512U : *last_payload_out; pkt[0] = 0x00U; pkt[1] = 0x03U; /* DATA opcode = 3 */ pkt[2] = (unsigned char)((b >> 8) & 0xFFU); pkt[3] = (unsigned char)(b & 0xFFU); uint16_t rx_op = ((uint16_t)pkt[0] << 8) | pkt[1]; uint16_t rx_blk = ((uint16_t)pkt[2] << 8) | pkt[3]; if (rx_op != 3U || rx_blk != (uint16_t)b) return -1; if (b == blocks && pay >= 512U) return -2; } return (int)blocks; } static int check_ddr3_bootz_gap(uint32_t zimage_addr, uint32_t zimage_len, uint32_t dtb_addr) { uint64_t decomp_end = (uint64_t)zimage_addr + (uint64_t)zimage_len * 4ULL; return (zimage_addr >= 0x80000000U && (uint64_t)dtb_addr >= decomp_end) ? 0 : -1; } int main(void) { uint32_t wan_dns = 0x08080808U; /* 8.8.8.8 */ uint32_t board_ip = 0xC0A80A32U; /* 192.168.10.50 */ uint32_t bench_sub = 0xC0A80A00U; /* 192.168.10.0 */ fib_route_t broken_tbl[] = { {"wlan0", 0x00000000U, 0, 0x0A000202U, 600}, {"enx0", 0x00000000U, 0, 0xC0A80A01U, 100}, /* Fatal bench default gw! */ {"enx0", bench_sub, 24, 0x00000000U, 100}, }; fib_route_t clean_tbl[] = { {"wlan0", 0x00000000U, 0, 0x0A000202U, 600}, {"enx0", bench_sub, 24, 0x00000000U, 100}, /* On-link only */ }; const fib_route_t *b_wan = fib_lookup(broken_tbl, 3, wan_dns); const fib_route_t *c_wan = fib_lookup(clean_tbl, 2, wan_dns); const fib_route_t *c_brd = fib_lookup(clean_tbl, 2, board_ip); size_t last_pay = 999U; int blks_1024 = simulate_tftp_blocks(1024U, &last_pay); int gap_ok = check_ddr3_bootz_gap(0x80800000U, 7U * 1024U * 1024U, 0x83000000U); int gap_bad = check_ddr3_bootz_gap(0x80800000U, 7U * 1024U * 1024U, 0x81000000U); printf("fib_routing: broken_8888=%s clean_8888=%s clean_board=%s\n", b_wan->dev, c_wan->dev, c_brd->dev); printf("tftp_1024B: blocks=%d final_eof_bytes=%zu\n", blks_1024, last_pay); printf("ddr3_gap: dtb_0x83000000=%d dtb_0x81000000_collision=%d\n", gap_ok, gap_bad); return (strcmp(b_wan->dev, "enx0") == 0 && strcmp(c_wan->dev, "wlan0") == 0 && strcmp(c_brd->dev, "enx0") == 0 && blks_1024 == 3 && last_pay == 0U && gap_ok == 0 && gap_bad == -1) ? 0 : 1; }- Longest prefix (/24 > /0) wins first; ties at /0 pick lowest metric (100 beats 600, hijacking WAN!).
- An exact 1,024-byte file requires (1024 / 512) + 1 = 3 DATA blocks, ending with a 0-byte EOF packet.
Verifying FIB Selection, 0-Byte TFTP EOF & DDR3 Separation
Confirm all three lines of output from ./verify: in broken_tbl, 8.8.8.8 routes mistakenly out enx0 (metric 100), whereas clean_tbl sends 8.8.8.8 to wlan0 and 192.168.10.50 to enx0. Meanwhile, the 1,024 B TFTP transfer produces blocks=3 with final_eof_bytes=0, and placing .dtb too close at 0x81000000 (+8 MiB above a 7 MiB zImage expanding ~4x to 28 MiB) triggers -1 collision detection.
learner@ksa:~/gl-e00/m03-l02gcc -std=c11 -Wall -Wextra -Werror verify.c -o verifylearner@ksa:~/gl-e00/m03-l02./verifyfib_routing: broken_8888=enx0 clean_8888=wlan0 clean_board=enx0tftp_1024B: blocks=3 final_eof_bytes=0ddr3_gap: dtb_0x83000000=0 dtb_0x81000000_collision=-1learner@ksa:~/gl-e00/m03-l02learner@ksa:~/gl-e00/m03-l02strace -e trace=write,exit_group ./verifywrite(1, "fib_routing: broken_8888=enx0 cl"..., 158) = 158exit_group(0) = ?+++ exited with 0 +++Firewall Ephemeral UDP Drops & bootm vs bootz Confusion
With clean dual-NIC routing and TFTP delivering zImage and .dtb into DDR3 in under two seconds, the final piece of a frictionless driver-development bench is mounting the live root filesystem over NFS in Lesson 3.3.
Host Firewall Allows UDP/69 Yet TFTP Still Hangs at 0%:
- Symptom:
tcpdumpshowsRRQarriving onUDP/69andin.tftpdsendingDATA block 1fromUDP/53104, yetACK block 1from the board is dropped by the host (ICMP port unreachable). - Root Cause: Because RFC 1350 switches from
UDP/69to an ephemeral server port (TID) on the first reply, a stateless firewall rule allowing onlyport 69drops incomingACKpackets to53104unlessnf_conntrack_tftpor an interface-level allow rule is present. - Fix: Trust the isolated dedicated bench interface (
sudo ufw allow in on enx00e04c680102) or load the TFTP connection-tracking helper (sudo modprobe nf_conntrack_tftp).
Running U-Boot 'bootm' on an ARMv7 zImage:
- Symptom:
tftp 0x80800000 zImagesucceeds, thenbootm 0x80800000 - 0x83000000fails withWrong Image Format for bootm command / ERROR: can't get kernel image!. - Root Cause:
bootmexpects a legacy64-bytemkimageuImageheader (0x27051956magic) or FIT image, whereas Kbuildmake zImageproduces a self-decompressing ARMv7zImage(0x016F2818magic at0x24). - Fix: Use
bootz 0x80800000 - 0x83000000forARMv7-AzImage(bootiis for 64-bitARM64Image, andbootmis foruImage/FIT.itbimages).
Guided Practice
Extend simulate_tftp_blocks() in verify.c to parse the RFC 1350 blksize option extension (RFC 2348, e.g., blksize=1468 negotiated by modern U-Boot to avoid IP fragmentation on 1500-byte Ethernet MTU) and verify how many blocks a 6,291,456-byte (6 MiB) zImage needs at 1468 B versus 512 B!
Independent Practice
Add a check to fib_lookup() that scans the entire routing table before lookup and returns an error if two distinct interfaces configure overlapping IPv4 subnets (for example both wlan0 and enx0 claiming 192.168.1.0/24).
Verification Checks
? check 1 · Your workstation connects to internet Wi-Fi (wlan0, DHCP 192.168.1.44/24, metric 600) and a wired bench adapter (enx0, static 192.168.10.10/24). Why must enx0 NOT define gateway4: 192.168.10.1?
- [ ] Linux
ARPstops answering192.168.10.50whenever a gateway address ends in.1. - [ ]
U-Bootoverwrites host/etc/resolv.confvia TFTPWRQif a gateway is present. - [x] Wired
enx0installs a0.0.0.0/0default route with lower metric (100<600), hijacking all internet traffic onto the isolated board cable. - [ ]
tftpd-hparefuses to bindUDP/69on any interface that defines a default gateway.
Answer: Wired enx0 installs a 0.0.0.0/0 default route with lower metric (100 < 600), hijacking all internet traffic onto the isolated board cable.
Why: Because 0.0.0.0/0 has prefix length 0 on both NICs, the kernel FIB picks the lower metric (100 wired over 600 Wi-Fi), sending WAN packets toward a nonexistent router on the bench wire.
Common misconception: Thinking every static IPv4 interface requires a gateway field even when no router exists on that cable.
? check 2 · Under RFC 1350 TFTP (512-byte standard blocks), how many DATA packets (opcode 3) are transmitted for a Device Tree blob that is exactly 32,768 bytes (64 * 512)?
- [ ]
32DATApackets, because standard RFC 1350 uses1,024-byte blocks. - [x]
65DATApackets:64full512-byte packets followed by1final0-byteDATApacket (block = 65) to signal EOF. - [ ]
64DATApackets, because theRRQheader pre-declaresContent-Length: 32768. - [ ]
64DATApackets followed by anERRORopcode5packet.
Answer: 65 DATA packets: 64 full 512-byte packets followed by 1 final 0-byte DATA packet (block = 65) to signal EOF.
Why: RFC 1350 DATA packets have no length field and signal EOF solely via payload length < 512 bytes; therefore any exact multiple of 512 requires a trailing 0-byte packet.
Common misconception: Computing ceil(size / 512) instead of (size / 512) + 1 for TFTP block counts.
? check 3 · With TFTP_DIRECTORY="/srv/tftp" and TFTP_OPTIONS="--secure" in /etc/default/tftpd-hpa, which U-Boot command fetches /srv/tftp/zImage into DDR3?
- [x]
tftp 0x80800000 zImage - [ ]
tftp 0x80800000 /srv/tftp/zImage - [ ]
tftp 0x00000400 zImage - [ ]
bootm 0x80800000 /srv/tftp/zImage
Answer: tftp 0x80800000 zImage
Why: --secure (-s) chroots in.tftpd into /srv/tftp, so requesting /srv/tftp/zImage looks for /srv/tftp/srv/tftp/zImage and fails with File not found.
Common misconception: Passing the full host filesystem path to a --secure chrooted TFTP server.
Summary
- On a dual-NIC workstation, the WAN interface (Wi-Fi/LAN DHCP) owns the sole 0.0.0.0/0 default route while the static bench NIC (e.g., 192.168.10.10/24) configures NO default gateway, using on-link ARP only.
- Setting a gateway on an isolated wired bench NIC installs a lower-metric 0.0.0.0/0 route (metric 100 wired vs 600 Wi-Fi) in the Linux kernel FIB, blackholing internet traffic onto the board cable.
- RFC 1350 TFTP initiates via RRQ (opcode 1) on UDP port 69 and transfers 512-byte DATA blocks (opcode 3) in lockstep with ACK packets (opcode 4), signaling EOF with a final DATA block strictly under 512 bytes (0 bytes if image_size % 512 == 0).
- In i.MX6ULL DDR3 RAM (base 0x80000000), U-Boot loads zImage at 0x80800000 and the flattened Device Tree (.dtb) at 0x83000000 (~40 MiB higher) so kernel self-decompression never overwrites the Device Tree.
Step sequence — frame strip: steps_m03_l02
Assign a /24 address without a gateway to the wired bench interface and verify routing with ip route get 8.8.8.8 and ip route get 192.168.10.50.
reveals: step1
highlights: step1
Configure /etc/default/tftpd-hpa with --secure so U-Boot requests bare filenames ('zImage') confined inside /srv/tftp.
reveals: step2
highlights: step2
Copy compiled zImage and .dtb artifacts into /srv/tftp with world-readable 0644 permissions for the unprivileged tftp daemon.
reveals: step3
highlights: step3
Fetch zImage at 0x80800000 and Device Tree at 0x83000000 in U-Boot, then launch Linux 6.12 via bootz.
reveals: step4
highlights: step4
What you'll learn
- Author whitespace-safe /etc/exports entries with no_root_squash and enable NFSv3 TCP support in /etc/nfs.conf on modern Ubuntu/Debian hosts.
- Construct exact U-Boot Linux kernel bootargs (root=/dev/nfs, nfsroot=<srv>:<path>,vers=3,tcp, and static ip= tuple) matching host exports.
- Compare TFTP+NFS network boot, SSH/rsync delta sync, and raw flash image deployment, and complete the Module 3 network boot studio.
Three-Second Driver Turnaround—and Why Modern Ubuntu Rejects Default nfsroot
Re-partitioning or reflashing an SD card every time you tweak one line in a character driver wastes ten minutes per iteration. With TFTP + NFS network boot, U-Boot pulls zImage and .dtb over TFTP in one second, and the Linux kernel (CONFIG_IP_PNP=y, CONFIG_ROOT_NFS=y) mounts /srv/nfs/rootfs from your workstation directly as /! The instant make modules finishes on your host and copies led_drv.ko into /srv/nfs/rootfs/lib/modules/..., you type modprobe led_drv on the board's UART console—zero SD swaps, zero scp copies!
Two notorious bugs trip up engineers on Ubuntu 22.04 and 24.04 LTS. First, kernel Documentation/admin-guide/nfs/nfsroot.rst historically defaulted nfsroot= to NFSv2 over UDP, whereas modern nfs-kernel-server disables NFSv2 completely and often requires explicit [nfsd] vers3=y + tcp=y in /etc/nfs.conf paired with ,vers=3,tcp inside bootargs! Second, writing /srv/nfs/rootfs 192.168.10.0/24 (rw,no_root_squash) with one space before ( tells exportfs to export read-only (ro,root_squash) to 192.168.10.0/24 and rw,no_root_squash to the entire world (*)!
Figure 3.3a. Both sides of the wire must agree on protocol version (vers=3,tcp), subnet CIDR without spaces, and UID 0 preservation ().
mental model: Mounting / over NFS is like running a restaurant kitchen (ARMv7-A board) whose walk-in pantry door opens directly into the central commissary (host /srv/nfs/rootfs): whenever the commissary places a fresh spice jar (driver.ko) on the shelf, the chef grabs it immediately without waiting for a delivery van (SD card). root_squash is a cautious commissary guard who strips the Head Chef (UID 0) of master keys and treats them as an untrusted visitor (UID 65534), while a space before ( in /etc/exports hangs the *'Master Keys Granted'* sign on the public street door instead of the kitchen door!
Where it stops working: no_root_squash grants any machine on the allowed subnet genuine UID 0 write access inside /srv/nfs/rootfs—never export / or /home with no_root_squash, and always restrict /srv/nfs/rootfs strictly to the isolated wired bench CIDR (192.168.10.0/24)!
definition (Kernel IP Autoconfiguration (ip= 7-Tuple) and NFS Root Squashing): Because user-space tools (ip, NetworkManager, dhclient) live inside the root filesystem that has not been mounted yet, the Linux kernel brings up eth0 in Ring 0 using the ip= bootargs 7-tuple: ip=<client-ip>:<server-ip>:<gw-ip>:<netmask>:<hostname>:<device>:<autoconf> (for example ip=192.168.10.50:192.168.10.10::255.255.255.0:board:eth0:off, leaving <gw-ip> empty on an isolated bench!). Once TCP/IP is live, fs/nfs/nfsroot.c contacts the host NFS server; no_root_squash disables default UID 0 -> 65534 (nobody) credential remapping inside /srv/nfs/rootfs.
- Step 1. Extract your target rootfs archive into /srv/nfs/rootfs using sudo tar --numeric-owner so UID 0 ownership is intact on disk.
- Step 2. Enable vers3=y under [nfsd] in /etc/nfs.conf, restart nfs-kernel-server, and verify +3 appears in /proc/fs/nfsd/versions.
- Step 3. Add the tight CIDR(options) entry to /etc/exports, reload via exportfs -rav, and confirm zero '*' wildcard leaks in exportfs -v.
- Step 4. Pass explicit vers=3,tcp and static eth0 ip= parameters in U-Boot bootargs, boot via TFTP, and verify live host-to-target file sync.
Figure 3.3b. Enable [nfsd] vers3=y, write cidr(rw,no_root_squash), and pin nfsroot=...,vers=3,tcp.
Inside /etc/exports Parsing, bootargs Tokenization & Deployment Trade-Offs
Why do embedded kernels prefer NFSv3 over NFSv4 for root=/dev/nfs? NFSv4 introduced pseudo-root path stripping (fsid=0) and string-based user@domain idmapd mapping, which frequently mismatches minimal BusyBox systems lacking rpc.idmapd during early boot; NFSv3 over TCP (vers=3,tcp) uses raw numeric 32-bit UID/GID integers on the wire and mounts exact absolute export paths (/srv/nfs/rootfs) reliably in fs/nfs/nfsroot.c.
Choosing the right transport across the engineering lifecycle is equally straightforward: use TFTP + NFSv3 during daily Linux kernel, Device Tree, and .ko driver bring-up (zero flash wear, 3 s turnaround); use rsync -avz or scp over SSH when iterating on user-space C/C++ applications on a board already booted from eMMC; and use offline SD images or USB UUU Fastboot to validate standalone cold-boot timing before shipping.
Figure 3.3b. Cross-checking /etc/exports against U-Boot bootargs catches path mismatches, missing vers=3,tcp, and subnet typos before power-on.
| Deployment Workflow | Turnaround Time | Flash Wear | Best Engineering Stage |
|---|---|---|---|
U-Boot TFTP + Kernel NFSv3 / | ~3 s (make -> reboot / insmod) | Zero (100% DDR3 + host disk) | Active Linux kernel, Device Tree & .ko driver bring-up |
rsync -avz / scp over SSH (OpenSSH) | < 1 s (delta user-space binary) | Minimal (target ext4 only) | Application, daemon, or Qt UI iteration on booted eMMC |
Raw dd / sfdisk MicroSD Card | ~2–4 min (sync, umount, swap) | Moderate (removable card) | Bootloader (SPL/U-Boot) & cold-boot partition validation |
USB OTG SDP + UUU -> eMMC / NAND | ~1–3 min (full image burn) | One full Factory/CI cycle | Board bring-up without SD slot & production provisioning |
learner@ksa:~/gl-e00/m03-l03$ bat -H 3 -H 7 nfs_bench_setup.conf File: nfs_bench_setup.conf # 1. /etc/nfs.conf (Ubuntu 22.04 / 24.04 LTS: re-enable NFSv3 for embedded U-Boot/kernel) [nfsd] vers3=y tcp=y # 2. /etc/exports (ZERO space between 192.168.10.0/24 and '('!) /srv/nfs/rootfs 192.168.10.0/24(rw,sync,no_root_squash,no_subtree_check) # 3. Matching U-Boot environment script setenv bootargs 'console=ttymxc0,115200 root=/dev/nfs nfsroot=192.168.10.10:/srv/nfs/rootfs,vers=3,tcp rw ip=192.168.10.50:192.168.10.10::255.255.255.0:imx6ull:eth0:off'- Explicitly enables NFSv3 over TCP on Ubuntu 22.04+/24.04 so fs/nfs/nfsroot.c mounts cleanly.
- Adjacent '192.168.10.0/24(' scopes no_root_squash strictly to the isolated bench subnet.
exports(5) GL-E00 Quick Reference exports(5) NAME exports, exportfs, nfs.conf - NFS server export table and kernel nfsroot bootargs SYNOPSIS sudo exportfs -rav # Reload /etc/exports and print active options cat /proc/fs/nfsd/versions # Confirm +3 is active in rpc.nfsd showmount -e 192.168.10.10 # Query rpc.mountd export list EXPORTS & BOOTARGS CONTRACT /srv/nfs/rootfs 192.168.10.0/24(rw,sync,no_root_squash,no_subtree_check) root=/dev/nfs nfsroot=192.168.10.10:/srv/nfs/rootfs,vers=3,tcp rw ip=192.168.10.50:192.168.10.10::255.255.255.0:board:eth0:off Kernel Systems Academy Lesson 3.3 exports(5) GL-E00 quick reference · full manual page: man 5 exports Cross-Checking /etc/exports Against Kernel nfsroot= bootargs in C11
Before rebooting a board only to watch VFS: Unable to mount root fs via NFS scroll across UART, we can cross-validate /etc/exports and U-Boot bootargs deterministically in ISO C11. In verify.c, audit_nfs_contract() parses an /etc/exports line—catching the classic whitespace-before-( wildcard bug (-2) and missing no_root_squash (-4)—then parses bootargs to confirm root=/dev/nfs, exact export directory match, ,vers=3,tcp pinning, and CIDR subnet membership.
Notice how bitwise subnet verification ((srv_ip & mask) == (net_ip & mask)) converts dotted-quad IPv4 strings into 32-bit host-order integers and applies 0xFFFFFFFFU << (32 - plen). If you change your bench NIC from 192.168.10.10/24 to 10.77.0.10/24 and forget to update /etc/exports, audit_nfs_contract() rejects the mismatch (-11) before rpc.mountd denies the target mount request.
learner@ksa:~/gl-e00/m03-l03$ bat -H 20 -H 50 verify.c File: verify.c #define _POSIX_C_SOURCE 200809L #include <stdint.h> #include <stdio.h> #include <stdlib.h> #include <string.h> static int parse_ipv4(const char *s, uint32_t *out) { unsigned int a, b, c, d; char tail; if (sscanf(s, "%u.%u.%u.%u%c", &a, &b, &c, &d, &tail) != 4) return -1; if (a > 255U || b > 255U || c > 255U || d > 255U) return -1; *out = (a << 24) | (b << 16) | (c << 8) | d; return 0; } static int audit_nfs_contract(const char *exports_ln, const char *bootargs) { char exp_path[128] = {0}, spec[160] = {0}, extra[32] = {0}; int n = sscanf(exports_ln, "%127s %159s %31s", exp_path, spec, extra); if (n < 2) return -1; if (n >= 3 && extra[0] == '(') return -2; /* Fatal space between CIDR and '('! */ char *lp = strchr(spec, '('); char *rp = lp ? strchr(lp + 1, ')') : NULL; if (!lp || !rp || lp == spec) return -3; char cidr[64] = {0}, opts[128] = {0}; memcpy(cidr, spec, (size_t)(lp - spec)); memcpy(opts, lp + 1, (size_t)(rp - lp - 1)); if (!strstr(opts, "rw") || !strstr(opts, "no_root_squash")) return -4; char *slash = strchr(cidr, '/'); if (!slash) return -5; *slash = '\0'; int plen = atoi(slash + 1); uint32_t net_ip = 0; if (plen < 8 || plen > 30 || parse_ipv4(cidr, &net_ip) != 0) return -5; uint32_t mask = 0xFFFFFFFFU << (32 - plen); if (!strstr(bootargs, "root=/dev/nfs")) return -6; const char *nr = strstr(bootargs, "nfsroot="); if (!nr) return -7; nr += 8; const char *end = strchr(nr, ' '); char nr_tok[192] = {0}; size_t nr_len = end ? (size_t)(end - nr) : strlen(nr); if (nr_len >= sizeof(nr_tok)) return -7; memcpy(nr_tok, nr, nr_len); if (!strstr(nr_tok, ",vers=3") || !strstr(nr_tok, ",tcp")) return -8; char *colon = strchr(nr_tok, ':'); char *comma = colon ? strchr(colon + 1, ',') : NULL; if (!colon || !comma) return -9; *colon = '\0'; *comma = '\0'; uint32_t srv_ip = 0; if (parse_ipv4(nr_tok, &srv_ip) != 0) return -10; if ((srv_ip & mask) != (net_ip & mask)) return -11; if (strcmp(colon + 1, exp_path) != 0) return -12; return 0; } int main(void) { const char *exp_ok = "/srv/nfs/rootfs 192.168.10.0/24(rw,sync,no_root_squash,no_subtree_check)"; const char *exp_sp = "/srv/nfs/rootfs 192.168.10.0/24 (rw,sync,no_root_squash)"; const char *ba_ok = "console=ttymxc0,115200 root=/dev/nfs " "nfsroot=192.168.10.10:/srv/nfs/rootfs,vers=3,tcp rw " "ip=192.168.10.50:192.168.10.10::255.255.255.0::eth0:off"; const char *ba_nov3 = "console=ttymxc0,115200 root=/dev/nfs " "nfsroot=192.168.10.10:/srv/nfs/rootfs rw"; int r_ok = audit_nfs_contract(exp_ok, ba_ok); int r_space = audit_nfs_contract(exp_sp, ba_ok); int r_nov3 = audit_nfs_contract(exp_ok, ba_nov3); printf("nfs_audit: valid=%d exports_space_bug=%d missing_vers3_tcp=%d\n", r_ok, r_space, r_nov3); return (r_ok == 0 && r_space == -2 && r_nov3 == -8) ? 0 : 1; }- Detects whitespace between CIDR and '(' via extra[0] == '(', catching the world-writable '*' export hazard.
- Requires explicit ',vers=3' and ',tcp' on nfsroot= so Ubuntu 22.04/24.04 rpc.nfsd accepts the root mount.
Confirming /etc/exports Whitespace & vers=3,tcp Rejections
Inspect the execution output: the matched /etc/exports + vers=3,tcp bootargs contract returns valid=0, inserting a single space before ( immediately triggers exports_space_bug=-2, and omitting ,vers=3,tcp triggers missing_vers3_tcp=-8.
While this host C11 verifier proves lexical and subnet consistency across host and U-Boot configuration files, live bring-up still requires confirming cat /proc/fs/nfsd/versions includes +3 on the workstation and verifying physical 100BASE-TX link carrier on the target Ethernet PHY.
learner@ksa:~/gl-e00/m03-l03gcc -std=c11 -Wall -Wextra -Werror verify.c -o verifylearner@ksa:~/gl-e00/m03-l03./verifynfs_audit: valid=0 exports_space_bug=-2 missing_vers3_tcp=-8learner@ksa:~/gl-e00/m03-l03learner@ksa:~/gl-e00/m03-l03strace -e trace=write,exit_group ./verifywrite(1, "nfs_audit: valid=0 exports_space"..., 61) = 61exit_group(0) = ?+++ exited with 0 +++Host NetworkManager Conflicts & Target connman/systemd-networkd Drops
You now control the complete host-to-target network boot pipeline—from signed APT/sysroot isolation through dual-NIC FIB routing and RFC 1350 TFTP to NFSv3 / mounting. Put all three pieces together in the graded lab_m03_tftp_nfs_bootargs studio below.
Board Mounts NFS Root Successfully, Then Hangs Mid-Boot Starting NetworkManager!:
- Symptom: Kernel prints
VFS: Mounted root (nfs filesystem) on device 0:15,/sbin/initstarts services, and two seconds later the console freezes withnfs: server 192.168.10.10 not responding, still trying! - Root Cause: A user-space network daemon inside the target rootfs (
connman,NetworkManager, orifupdownDHCP oneth0) flushedeth0's IP address to run DHCP, severing the live TCP connection backing/itself! - Fix: When booting
root=/dev/nfs, configure target user-space network managers to ignoreeth0(ConnMan-I eth0orCriticalConnection=true/KeepConfiguration=yesinsystemd-networkd).
Host Firewall Allows Port 2049 Yet NFSv3 Mount Still Hangs:
- Symptom: You opened
TCP/2049(nfs) inufw, yetU-BootTFTPsucceeds and kernelNFSv3root mount times out. - Root Cause: Unlike
NFSv4(single port2049),NFSv3first queriesrpcbind(portmapperonTCP/UDP 111) to discoverrpc.mountd's port (MOUNTv3handshake) before openingTCP/2049! - Fix: Allow all traffic from the dedicated wired bench interface (
sudo ufw allow in on enx_bench from 192.168.10.0/24) or pin a staticrpc.mountdport in/etc/nfs.conf([mountd] port=20048) alongside111and2049.
Guided Practice
Extend audit_nfs_contract() in verify.c to parse the ip= 7-tuple (ip=<client>:<srv>:<gw>:<mask>:...) from bootargs and verify that <srv> in ip= equals <srv> in nfsroot= and that <client> lies inside the same /24 subnet without colliding with <srv>!
Independent Practice
Open labs/lab_m03_tftp_nfs_bootargs/ and fix all three bugs in starter/core.c so sh check.sh passes 5/5 TAP version 13 assertions and ./files/lab_cli --bench records CLOCK_MONOTONIC percentiles.
Verification Checks
? check 1 · What does /srv/nfs/rootfs 192.168.10.0/24 (rw,sync,no_root_squash) (notice the space before () actually configure in /etc/exports?
- [ ] It restricts
rwaccess toNFSv4Kerberos clients only. - [x] It exports
/srv/nfs/rootfsread-only withroot_squashto192.168.10.0/24, andrw,no_root_squashto every other IP address in the world (*)! - [ ]
exportfsignores whitespace before(and appliesrw,no_root_squashonly to192.168.10.0/24. - [ ]
rpc.nfsdrefuses to start and exits with code1.
Answer: It exports /srv/nfs/rootfs read-only with root_squash to 192.168.10.0/24, and rw,no_root_squash to every other IP address in the world (*)!
Why: In /etc/exports whitespace separates distinct client specifications; a bare (rw,...) token with no hostname prefix means wildcard * (everyone), while 192.168.10.0/24 gets default (ro,root_squash)!
Common misconception: Treating /etc/exports parenthesized options like C function arguments where spaces before ( are harmless.
? check 2 · An i.MX6ULL board boots Linux kernel 6.12 via TFTP, prints VFS: Mounted root (nfs filesystem), starts systemd, and immediately hangs printing nfs: server 192.168.10.10 not responding. What happened?
- [x] A user-space network service inside the target rootfs reset
eth0(e.g., to request DHCP), tearing down the active TCP socket carrying the root filesystem! - [ ]
U-Bootreclaimed0x83000000DDR3 RAM afterPID 1started. - [ ]
tftpd-hpaclosed port69afterzImagefinished downloading. - [ ]
PKG_CONFIG_LIBDIRleaked x86_64 paths into/etc/exports.
Answer: A user-space network service inside the target rootfs reset eth0 (e.g., to request DHCP), tearing down the active TCP socket carrying the root filesystem!
Why: When / resides over eth0, re-initializing eth0 in user space drops the underlying transport needed to read libraries and binaries from / (KeepConfiguration=yes or -I eth0 prevents this).
Common misconception: Blaming the host NFS daemon when target user-space scripts reset the interface backing root=/dev/nfs.
? check 3 · Why does booting an embedded target with nfsroot=192.168.10.10:/srv/nfs/rootfs (without ,vers=3,tcp) commonly fail against an out-of-the-box Ubuntu 24.04 LTS host?
- [ ] Ubuntu 24.04 removed
nfs-kernel-serverin favor oftftpd-hpablock devices. - [ ]
ARMv7-Akernels cannot speakTCPbefore/sbin/initstarts. - [ ]
NFSv3requiresroot_squashand refusesno_root_squash. - [x] Legacy
nfsrootdefaults attemptNFSv2/UDP, whereas Ubuntu 24.04 disablesNFSv2and requires[nfsd] vers3=yin/etc/nfs.confplus,vers=3,tcpinbootargs.
Answer: Legacy nfsroot defaults attempt NFSv2/UDP, whereas Ubuntu 24.04 disables NFSv2 and requires [nfsd] vers3=y in /etc/nfs.conf plus ,vers=3,tcp in bootargs.
Why: Pinning ,vers=3,tcp in bootargs and enabling vers3=y in /etc/nfs.conf aligns kernel fs/nfs/nfsroot.c with modern rpc.nfsd.
Common misconception: Assuming host nfs-kernel-server still enables legacy NFSv2 over UDP on modern LTS releases.
1. Motivation
A broken network-boot bench silently wastes hours of board bring-up: one stray gateway4 on the USB-Ethernet dongle kills internet access, off-by-one 512-byte TFTP framing truncates exact-multiple Device Trees, and missing ,vers=3,tcp or no_root_squash panics the Linux kernel on root mount. This studio builds a preflight C11 verifier catching all three before power-on.
2. Learning objectives
- Audit multi-homed FIB tables to forbid
0.0.0.0/0gateways on isolated bench NICs while confirming/24on-link reachability. - Validate RFC 1350
DATA/ACKlockstep sequences including theN / 512 + 1zero-byte EOF packet invariant. - Cross-validate
/etc/exports(rw,no_root_squash, no space before() againstLinux kernelnfsroot=...,vers=3,tcpbootargs.
3. Environment requirements
All automated verification steps run in unprivileged user space on a POSIX Linux host using gcc -std=c11 -Wall -Wextra -Werror and clock_gettime(CLOCK_MONOTONIC). Recorded transcripts in captures.json were generated on x86_64 running kernel 7.0.0-42-generic and prove protocol, state-machine, and memory invariants only. Physical bus timing, DMA cache coherency, and board peripheral behavior require target validation on Linux kernel 6.12 LTS (ARMv7-A Cortex-A7).
4. Required software and hardware
- Host workstation:
gcc(-std=c11 -Wall -Wextra -Werror), GNUmake,ar(binutils), and POSIX/bin/sh. - Target environment (optional hardware step, Section 13):
i.MX6ULLARMv7-Aboard wired via100BASE-TXEthernet (ENET1/ENET2) to a host static192.168.10.10/24USB-Ethernet adapter runningtftpd-hpaandnfs-kernel-server(vers3=y).
5. Complete executable commands
learner@ksa:~/gl-e00/m03-l03$ bat script.sh File: script.sh make -B -C files ./files/lab_cli ./files/lab_cli --bench sh check.sh6. Annotated source code
files/core.c enforces the production invariants that starter/core.c breaks:
learner@ksa:~/gl-e00/m03-l03$ bat example.c File: example.c size_t expected_blocks = (image_bytes / 512U) + 1U; if (frame_count != expected_blocks * 2U) return -2; ... size_t exp_len = (b < expected_blocks) ? 512U : (image_bytes % 512U);starter/core.c introduces three authentic network-boot bugs: (1) ksa_validate_dual_nic_fib() ignores default routes attached to is_bench_nic; (2) ksa_verify_tftp_session() computes (image_bytes + 511U) / 512U (ceil), failing whenever image_bytes is an exact multiple of 512 bytes (1,024 B needs 3 blocks, not 2!); and (3) ksa_validate_nfs_boot() omits verifying ,vers=3 and ,tcp on nfsroot=.
7. Expected output
Passing files/ run (sh check.sh, exit code 0):
learner@ksa:~/gl-e00/m03-l03$ bat listing.txt File: listing.txt TAP version 13 1..5 ok 1 - builds libcore.a and lab_cli cleanly with -std=c11 -Wall -Wextra -Werror ok 2 - archives core.o into libcore.a and links independent TAP verifier ok 3 - rejects competing default gateway on bench NIC while preserving WAN 0.0.0.0/0 and /24 link ok 4 - verifies RFC 1350 TFTP DATA/ACK lockstep including trailing 0-byte EOF on exact 512B multiples ok 5 - cross-checks /etc/exports whitespace and no_root_squash against kernel nfsroot=...,vers=3,tcp # pass 5/5CLI verification output (./files/lab_cli):
learner@ksa:~/gl-e00/m03-l03$ bat listing.txt File: listing.txt dual_nic_fib: rc=0 tftp_1024B_3blk_eof: rc=0 nfs_exports_bootargs: rc=0Defective starter/ run (exit code 1): emits FAIL: diagnostics on the broken contract assertions.
8. Explanation of observed behavior
Restoring all three invariants makes libcore.a pass all 5 TAP version 13 checks cleanly: dual_gw routing tables are rejected before blackholing WAN traffic, 1,024-byte TFTP transfers require the trailing 0-byte block 3 EOF packet, and /etc/exports + bootargs agree on path, subnet CIDR, no_root_squash, and vers=3,tcp.
9. Experiment variations
- Near transfer: Extend
ksa_validate_nfs_boot()to parse theip=<client>:<srv>:<gw>:<mask>:...parameter and reject non-empty<gw>values when<client>and<srv>sit on an isolated/24bench. - Far transfer: Write a live Linux workstation preflight script that feeds
ip -4 route show,/etc/default/tftpd-hpa,/proc/fs/nfsd/versions, and/etc/exportsintolab_clibefore launchingpicocom.
10. Performance measurements
Recorded host benchmark (./files/lab_cli --bench, CLOCK_MONOTONIC, warmup=5, N=40 batches):
learner@ksa:~/gl-e00/m03-l03$ bat listing.txt File: listing.txt BENCH lab_m03_tftp_nfs_bootargs clock=CLOCK_MONOTONIC warmup=5 samples=40 p50_ns=752 p95_ns=801 p99_ns=807 sink=0CLOCK_MONOTONIC host benchmark numbers measure in-memory C11 validation speed (~nanoseconds), not 100BASE-TX wire propagation, UDP socket round-trip time, or host SSD /srv/nfs/rootfs read latency.
11. Troubleshooting
| Symptom | Root cause | Fix | ||
|---|---|---|---|---|
not ok 3 - rejects competing default gateway... | routes[i].is_bench_nic check on prefix_len == 0 is disabled, allowing wan_defaults or bench default route. | Return -2 immediately if routes[i].prefix_len == 0 && routes[i].is_bench_nic. | ||
not ok 4 - verifies RFC 1350 TFTP DATA/ACK lockstep... | Used ceiling division (image_bytes + 511U) / 512U, yielding 2 blocks instead of 3 for 1,024 B. | Use (image_bytes / 512U) + 1U so exact 512 B multiples include the mandatory 0-byte EOF block. | ||
not ok 5 - cross-checks /etc/exports whitespace... | Missing check for ,vers=3 and ,tcp inside nfsroot= token. | Return -9 if `!strstr(nr_tok, ",vers=3") | !strstr(nr_tok, ",tcp")`. |
12. Guided questions
- Why does
(image_bytes + 511U) / 512Uagree with(image_bytes / 512U) + 1Uon700bytes (2blocks) yet disagree on0bytes (0vs1) and1,024bytes (2vs3)?
- *Hint 1:* How does an RFC 1350 receiver know that the sender has no further blocks after receiving a full
512-byteDATApacket? - *Hint 2:* A
512-byteDATApacket ALWAYS means 'at least one more packet follows', so every remainderr = image_bytes % 512(includingr = 0) ends with a final block of lengthr < 512, givingfloor(N / 512) + 1blocks for everyN >= 0!
- In
ksa_validate_nfs_boot(), how doessscanf(exports_line, "%127s %159s %31s", exp_dir, spec, extra)detect/srv/nfs/rootfs 192.168.10.0/24 (rw,...)?
- *Hint 1:* What gets stored into
specandextrawhen a space separates192.168.10.0/24from(rw,...)? - *Hint 2:* When a space precedes
(,specreceives"192.168.10.0/24"(with no'(') andextrareceives"(rw,...)", son >= 3 && extra[0] == '('catches the wildcard leak immediately!
13. Independent challenges
Add RFC 2348 blksize option-negotiation support (OACK opcode 6, e.g., blksize=1468) to ksa_verify_tftp_session_ext() and benchmark 512 B vs 1468 B block counts for an 8 MiB zImage.
14. Solutions and explanations
The reference files/core.c forbids prefix_len == 0 on is_bench_nic interfaces, computes (image_bytes / 512U) + 1U blocks for RFC 1350 TFTP EOF framing, and enforces tight cidr(rw,...,no_root_squash) + ,vers=3,tcp consistency across /etc/exports and bootargs.
Run locally in your terminal and check off each verification milestone.
Not started
Summary
- Exporting a target root filesystem in /etc/exports requires path cidr(rw,sync,no_root_squash,no_subtree_check) with ZERO whitespace between the CIDR subnet and '(' so options bind to that subnet rather than '*'.
- Without no_root_squash, the host NFS server maps target UID 0 requests to nobody (65534), causing /sbin/init, systemd, and device/module operations on the board to fail with EACCES.
- On Ubuntu 22.04+ and 24.04 LTS hosts, /etc/nfs.conf must enable [nfsd] vers3=y and tcp=y to match Linux kernel bootargs root=/dev/nfs nfsroot=192.168.10.10:/srv/nfs/rootfs,vers=3,tcp rw ip=...
- Embedded workflows use TFTP + NFS root during rapid kernel/driver iteration, rsync/scp over SSH for incremental user-space updates on booted targets, and UUU/SD partition images for standalone release.
Step sequence — frame strip: steps_m03_l03
Extract your target rootfs archive into /srv/nfs/rootfs using sudo tar --numeric-owner so UID 0 ownership is intact on disk.
reveals: step1
highlights: step1
Enable vers3=y under [nfsd] in /etc/nfs.conf, restart nfs-kernel-server, and verify +3 appears in /proc/fs/nfsd/versions.
reveals: step2
highlights: step2
Add the tight CIDR(options) entry to /etc/exports, reload via exportfs -rav, and confirm zero '*' wildcard leaks in exportfs -v.
reveals: step3
highlights: step3
Pass explicit vers=3,tcp and static eth0 ip= parameters in U-Boot bootargs, boot via TFTP, and verify live host-to-target file sync.
reveals: step4
highlights: step4
m04/
Linux Kernel & Embedded C11 Coding Style & Defensive Hygiene
Enforce Linux kernel C11 formatting, internal static symbol hygiene, centralized LIFO goto error unwinding, and single-evaluation macro safety verified by a host static-rule and unwind auditor.
What you'll learn
- Audit embedded C11 source lines for 8-column tab visual width, K&R control braces, and aligned switch/case fallthrough annotations.
- Analyze pointer-declarator binding and operator-spacing defects that disguise non-pointer declarations or visual precedence traps.
- Evaluate multi-line block comments to replace line-by-line syntax narration with hardware and concurrency invariant contracts.
Visual Nesting Alarms and Asymmetric Brace Placement
Code inside a bootloader or Linux kernel driver is written once and audited hundreds of times during bring-up panics, race-condition reviews, and LTS backports. When each engineer invents personal spacing, 2-space indents, or brace styles, reviewers waste working memory parsing typography instead of spotting a missing spinlock release or an implicit switch fallthrough.
The Linux kernel CodingStyle uses 8-column hard tabs ('\t') deliberately as a structural complexity alarm rather than an aesthetic preference. Against an 80-column target (100-column ceiling), four nested if/for levels push code past column 32 before an expression even starts. Instead of shrinking indentation to 2 spaces to hide spaghetti state machines, you invert guard conditions early or extract single-purpose static helpers.
Figure 4.1a. 8-column tabs expose excessive cyclomatic nesting early so drivers refactor into flat guard clauses.
mental model: Think of kernel C formatting like standardized aircraft cockpit switch guards and color bands: every pilot reads control state in milliseconds without mentally translating personal layout quirks during an emergency.
Where it stops working: Formatting rules never prove algorithmic correctness on their own; clean indentation makes deeply nested bugs visible so engineers refactor control flow before shipping.
definition (8-Column Tab Complexity Alarm): Named from the Linux kernel CodingStyle chapter 1 rule equating one ASCII HT (0x09) character to eight terminal columns, the 8-column tab complexity alarm pairs wide visual steps with an 80-column soft margin so deeply nested conditionals physically run out of horizontal space, compelling the author to flatten control flow with guard clauses.
- Step 1. Hard tabs advance to multiples of 8 columns, making >3 nested levels immediately obvious.
- Step 2. Column-1 braces anchor top-level functions while K&R braces conserve vertical lines inside bodies.
- Step 3. Vertical switch/case alignment avoids double-indentation and pairs with -Wimplicit-fallthrough.
- Step 4. sizeof(*rx_buf) survives type refactors automatically without repeating struct names.
Figure 4.1b. Use 8-col tabs, K&R control braces, identifier-bound *stars, and why-not-how comments.
Brace Geometry, Operator Spacing, and Fallthrough Discipline
Every token spacing rule in CodingStyle eliminates a concrete visual ambiguity. Reserved control keywords (if, for, while, switch, return) take one space before (, visually separating control flow from function calls (spin_lock(&q->lock)). Conversely, sizeof, alignof, and typeof behave syntactically like compile-time functions and never take a space before (: write sizeof(*dev) rather than sizeof (struct my_dev) so changing the pointer's struct type never leaves a stale allocation size behind.
In C grammar, the pointer * modifier binds to the declarator, not the type specifier. Writing uint8_t* tx, rx; declares tx as a pointer and rx as a single uint8_t byte, whereas uint8_t *tx, *rx; matches the compiler's actual AST. Likewise, in multi-branch if (cond) { ... } else { ... } chains, whenever any branch spans multiple lines, every sibling branch receives braces so adding a log statement later cannot trigger a dangling-statement bug.
Figure 4.1b. Declarator-bound stars and compiler-checked fallthrough attributes turn style rules into bug prevention.
| Construct | Kernel C11 Contract | Rejected Pattern | Defect Prevented |
|---|---|---|---|
| Indentation | 1 hard tab = 8 columns (<= 3 levels) | 2 or 4 spaces hiding 6 nested if blocks | Unreadable arrow-code state machines |
| Pointer declaration | uint32_t *reg_a, *reg_b; | uint32_t* reg_a, reg_b; | reg_b silently compiled as scalar integer |
| Allocation size | kzalloc(sizeof(*priv), GFP_KERNEL) | kzalloc(sizeof (struct old_priv), ...) | Heap buffer under-allocation after type change |
| Switch fallthrough | Aligned case + __attribute__((fallthrough)) | Indented case missing break; comment | Accidental execution of adjacent reset handler |
learner@ksa:~/gl-e00/m04-l01$ bat -H 17 -H 31 coding_style_irq.c File: coding_style_irq.c // SPDX-License-Identifier: GPL-2.0 #include <stdint.h> #define UART_SR_RXRDY (1U << 0) #define UART_SR_OVERRUN (1U << 3) struct uart_port_ctx { volatile uint32_t *sr_reg; uint32_t rx_drops; uint32_t rx_frames; }; /* * Why: Clearing OVERRUN on i.MX6ULL USR2 requires acknowledging the status * bit before draining URXD; reversing the order drops the newly arrived byte. */ int uart_poll_status(struct uart_port_ctx *ctx, int mode) { uint32_t status; if (!ctx || !ctx->sr_reg) return -1; status = *ctx->sr_reg; switch (mode) { case 0: if (status & UART_SR_OVERRUN) { *ctx->sr_reg = UART_SR_OVERRUN; ctx->rx_drops++; } __attribute__((fallthrough)); case 1: if (status & UART_SR_RXRDY) ctx->rx_frames++; break; default: return -2; } return (int)sizeof(*ctx); }- Function opening brace sits alone at column 1 while guard clauses keep the body at 1-2 tab stops.
- Aligned switch/case uses __attribute__((fallthrough)) so GCC -Wextra verifies intentional fallthrough.
checkpatch.pl / CodingStyle(7) GL-E00 Quick Reference checkpatch.pl / CodingStyle(7) SYNOPSIS ./scripts/checkpatch.pl --no-tree --strict -f driver_file.c gcc -std=c11 -Wall -Wextra -Wimplicit-fallthrough -Wmisleading-indentation -Werror -c file.c KEY RULES (Linux kernel Documentation/process/coding-style.rst) Tabs & Width Hard tab ('\t') = 8 columns; preferred limit 80 cols (100 cols max when readability wins). Braces Functions open '{' on column 1 of next line; if/for/while/switch/struct open '{' on same line. Multi-branch If any branch of if/else needs braces, place braces on EVERY branch of that construct. Operators Space after if/for/while/switch/return; NO space after sizeof/alignof/typeof or unary ! ~ ++ --. Comments Use /* ... */ block comments explaining invariants (why), never restating C syntax (how). Kernel Systems Academy Lesson 4.1 checkpatch.pl / CodingStyle(7) GL-E00 quick reference · full manual page: man 7 checkpatch.pl / CodingStyle Host C11 Style Scanner for Tabs, Stars, and Fallthroughs
Before running scripts/checkpatch.pl against a full driver tree, understanding how each lexical check works removes all mystery from build-gate failures. On our Linux host, we can write a compact ISO C11 style scanner (verify.c) that expands 8-column tab stops, measures visual line width and indentation depth, detects sizeof ( spacing and type* var star misplacement, and checks switch blocks for unannotated fallthrough.
This host verification binary runs in unprivileged user space under gcc -std=c11 -Wall -Wextra -Werror and proves exact lexical rule detection on representative C lines. Hardware register side effects cited in comments still require validation on ARMv7-A silicon.
learner@ksa:~/gl-e00/m04-l01$ bat -H 22 -H 35 verify.c File: verify.c #define _POSIX_C_SOURCE 200809L #include <stdbool.h> #include <stdint.h> #include <stdio.h> #include <string.h> struct line_metrics { int tab_depth; int visual_cols; bool leading_spaces; bool bad_sizeof_space; bool bad_type_star; }; static struct line_metrics scan_style_line(const char *line) { struct line_metrics m = {0, 0, false, false, false}; bool in_indent = true; for (size_t i = 0; line[i] != '\0' && line[i] != '\n'; i++) { char c = line[i]; if (in_indent && c == '\t') { m.tab_depth++; m.visual_cols += 8 - (m.visual_cols % 8); } else if (in_indent && c == ' ') { if (line[i + 1] != '*') m.leading_spaces = true; m.visual_cols++; } else { in_indent = false; m.visual_cols += (c == '\t') ? (8 - (m.visual_cols % 8)) : 1; } } if (strstr(line, "sizeof (") != NULL) m.bad_sizeof_space = true; if (strstr(line, "char* ") != NULL || strstr(line, "uint32_t* ") != NULL) m.bad_type_star = true; return m; } int main(void) { const char *clean = "\t\tstatus = sizeof(*ctx) + (*reg & 0xFFU);\n"; const char *flawed = " char* buf = alloc_pkt(sizeof (struct hdr));\n"; const char *deep = "\t\t\t\t\t*reg = 0x1U;\n"; struct line_metrics c = scan_style_line(clean); struct line_metrics f = scan_style_line(flawed); struct line_metrics d = scan_style_line(deep); if (c.tab_depth != 2 || c.leading_spaces || c.bad_sizeof_space || c.bad_type_star) return 1; if (!f.leading_spaces || !f.bad_sizeof_space || !f.bad_type_star) return 2; if (d.tab_depth <= 3 || d.visual_cols < 40) return 3; printf("CLEAN_LINE tabs=%d cols=%d violations=0\n", c.tab_depth, c.visual_cols); printf("FLAWED_LINE spaces=%d sizeof_sp=%d type_star=%d\n", f.leading_spaces ? 1 : 0, f.bad_sizeof_space ? 1 : 0, f.bad_type_star ? 1 : 0); printf("DEEP_NEST_ALARM tabs=%d visual_col_start=%d (>3 refactor!)\n", d.tab_depth, 5 * 8); return 0; }- Each leading hard tab advances visual_cols to the next 8-column boundary while counting nesting depth.
- Detects space-indented code (excluding block-comment '*'), 'sizeof (' spacing, and 'char* ' star traps.
Verifying Compiler Diagnostics and Tab-Stop Telemetry
Compiling verify.c under gcc -std=c11 -Wall -Wextra -Werror exercises GCC's built-in -Wmisleading-indentation and -Wimplicit-fallthrough passes directly on our scanner implementation. On execution, CLEAN_LINE confirms 2 hard tabs (16 visual columns plus expression width = 54 columns) with zero formatting violations.
Simultaneously, FLAWED_LINE flags leading-space indentation, sizeof ( spacing, and type-attached char* syntax in a single pass, while DEEP_NEST_ALARM demonstrates why 5 tab stops consume 40 columns before a single token of C logic is written.
learner@ksa:~/gl-e00/m04-l01gcc -std=c11 -Wall -Wextra -Werror verify.c -o verifylearner@ksa:~/gl-e00/m04-l01./verifyCLEAN_LINE tabs=2 cols=55 violations=0FLAWED_LINE spaces=1 sizeof_sp=1 type_star=1DEEP_NEST_ALARM tabs=5 visual_col_start=40 (>3 refactor!)learner@ksa:~/gl-e00/m04-l01learner@ksa:~/gl-e00/m04-l01strace -e trace=write,exit_group ./verifywrite(1, "CLEAN_LINE tabs=2 cols=55 violat"..., 142) = 142exit_group(0) = ?+++ exited with 0 +++Formatting Traps That Disguise Control-Flow and Type Bugs
Treat style conformance as a zero-noise baseline for code review. When indentation, braces, and operator spacing are 100% uniform, any visual asymmetry on screen immediately corresponds to a genuine semantic anomaly — such as an unbraced macro expansion, a missing break;, or an inverted error check.
Pair .editorconfig / .clang-format (UseTab: Always, IndentWidth: 8, TabWidth: 8) with compiler warning flags so formatting drift never reaches peer review.
Dangling Multi-Line Branch in Partially Braced if/else:
- Symptom: Adding a
pr_debug()trace line to anelseclause causes the subsequent operational statement to execute unconditionally on both true and false paths. - Root Cause: Leaving one branch of an
if/elseunbraced when the sibling branch spans multiple lines invites human edit errors thatGCConly catches if indentation happens to remain consistent. - Fix: Place K&R
{ ... }braces around every branch of anif/else if/elsechain whenever any single branch requires more than one line or statement.
Comma-Separated Pointer Declarator Star Misplacement:
- Symptom: Declaration
uint8_t* rx_buf, tx_buf;fails with invalid type conversion or truncates a32-bit buffer address into an8-bit byte when assigningtx_buf. - Root Cause: C grammar binds
*to the individual declarator (*rx_buf), not the base type (uint8_t), sotx_bufis silently allocated as a scalaruint8_t. - Fix: Always attach
*to the variable identifier (uint8_t *rx_buf, *tx_buf;) and prefer one initialized pointer declaration per line.
Guided Practice
Extend scan_style_line() in verify.c to flag lines whose expanded visual_cols exceed 80 characters unless the line contains a quoted diagnostic format string ("). Why does Linux kernel CodingStyle forbid splitting user-visible printk strings across multiple lines even when they exceed column 80?
Recompile with gcc -std=c11 -Wall -Wextra -Werror verify.c -o verify and test two inputs: a 92-column arithmetic expression (must flag over_80 = true) and a 92-column pr_err string literal (must pass so engineers can git grep exact dmesg error text).
Independent Practice
Write a multi-line scanner function check_switch_fallthrough(const char **lines, size_t n) that inspects consecutive lines inside a switch block and detects any case body that executes statements and reaches the next case or default label without break;, return, goto, or an explicit fallthrough annotation.
Verify your scanner against three synthetic switch blocks: a clean break;-terminated case, an empty stacked label (case 1: case 2:), and an unannotated non-empty fallthrough (must return exact offending line index with 0 compiler warnings).
Verification Checks
? check 1 · Why does Linux kernel CodingStyle specify 8-column hard tabs rather than 2-space indentation?
- [ ] Hard tabs shrink compiled
.textmachine-code size inside loadable.komodules. - [ ]
8-column tabs are required by theARMv7-AAAPCS32procedure-call standard. - [x] Wide
8-column tabs push> 3nested control blocks against the80-column margin early, acting as a complexity alarm to extract helpers or guard clauses. - [ ] The GNU assembler rejects C source files indented with ASCII space (
0x20) characters.
Answer: Wide 8-column tabs push > 3 nested control blocks against the 80-column margin early, acting as a complexity alarm to extract helpers or guard clauses.
Why: Tabs affect source readability, not machine code; 8-column visual steps expose excessive cyclomatic complexity before functions become unmaintainable.
Common misconception: Thinking 8-column tabs are an arbitrary legacy quirk rather than a deliberate nesting-depth guardrail.
? check 2 · Which allocation pattern follows Linux kernel CodingStyle and survives changing the struct type of struct sai_priv *priv without introducing a heap size mismatch?
- [ ]
priv = kzalloc(sizeof * priv, GFP_KERNEL); - [x]
priv = kzalloc(sizeof(*priv), GFP_KERNEL); - [ ]
priv = kzalloc(sizeof (struct sai_priv), GFP_KERNEL); - [ ]
priv = (struct sai_priv*) kzalloc(sizeof(priv), GFP_KERNEL);
Answer: priv = kzalloc(sizeof(*priv), GFP_KERNEL);
Why: sizeof(*priv) omits space before (, avoids redundant void-pointer casts in C, and computes the exact pointee struct size even if priv's type is later renamed.
Common misconception: Using sizeof(priv) (which allocates only 4 or 8 pointer bytes!) or hardcoding the struct tag in sizeof (struct ...).
? check 3 · Why does CodingStyle permit a single-line pr_err("...") string literal to exceed 80 columns rather than breaking it into concatenated fragments?
- [x] Keeping user-visible diagnostic strings unbroken allows engineers to
git grepan exactdmesgerror message directly back to its source line. - [ ] ISO C11 forbids adjacent string-literal concatenation inside variadic macros.
- [ ] Splitting a string literal adds extra NUL terminators between fragments in
.rodata. - [ ]
printktruncates any format string containing compile-time line breaks.
Answer: Keeping user-visible diagnostic strings unbroken allows engineers to git grep an exact dmesg error message directly back to its source line.
Why: C11 concatenates adjacent string literals automatically at compile time, so the rule exists purely for grep discoverability during production fault triage.
Common misconception: Splitting error messages across lines to satisfy an 80-column counter, breaking grep lookup during bring-up.
Summary
- Linux kernel CodingStyle mandates 8-column hard tabs and an 80-to-100 column line budget so functions exceeding 3 indentation levels force helper extraction.
- Control statements place opening braces on the same K&R line while function definitions place opening braces at column 1, and switch/case labels align vertically with explicit fallthrough annotations.
- Pointer asterisks bind to the identifier (
char *buf) rather than the base type, while function-like operators (sizeof(struct file)) omit space before the opening parenthesis. - C89/C11 block comments (
/* ... */) document hardware timing, lock order, and ownership invariants (why) rather than restating C syntax mechanics (how).
Step sequence — frame strip: steps_m04_l01
Hard tabs advance to multiples of 8 columns, making >3 nested levels immediately obvious.
reveals: step1
highlights: step1
Column-1 braces anchor top-level functions while K&R braces conserve vertical lines inside bodies.
reveals: step2
highlights: step2
Vertical switch/case alignment avoids double-indentation and pairs with -Wimplicit-fallthrough.
reveals: step3
highlights: step3
sizeof(*rx_buf) survives type refactors automatically without repeating struct names.
reveals: step4
highlights: step4
What you'll learn
- Enforce
staticinternal linkage (STB_LOCAL) and subsystem-prefixedsnake_caseantonym pairs across module boundaries. - Analyze partial-initialization failure paths in multi-resource
probe()routines to eliminate resource leaks and double-frees. - Construct a centralized forward-only
goto err_*cleanup tail that releases acquired resources in strict reverseLIFOorder.
Symbol Namespace Isolation and Antonym Lifecycle Symmetry
In a monolithic Linux kernel image or multi-file embedded firmware archive, all non-static functions and globals share one flat linker namespace. Naming a helper init_timer_hw() without static exports an ELF STB_GLOBAL symbol that collides at link time with unrelated drivers or prevents -O2 from inlining private fast paths. Marking every non-exported symbol static restricts visibility to STB_LOCAL inside that single translation unit, while exported symbols carry a subsystem snake_case prefix (imx_sai_enable).
Equally critical is antonym symmetry across resource pairs: alloc pairs with free, register with unregister, enable with disable, map with unmap, and lock with unlock. Rejecting Hungarian prefixes (lpszBuf, bReady) keeps names concise while the C11 type system (-Wall -Wextra -Wmissing-prototypes) enforces type and prototype contracts.
Figure 4.2a. Forward-only goto labels unwind strictly the prefix of resources that succeeded before the error.
mental model: Think of centralized goto unwinding like a mountaineering rope team retreating down pitched anchors: if climber 3 slips before reaching the summit, you unclip anchor 2 then anchor 1 in exact reverse order rather than cutting the rope mid-cliff.
Where it stops working: Backward or spaghetti goto jumps across loop bodies destroy control-flow reducibility; kernel C restricts goto strictly to forward jumps into a linear LIFO cleanup tail at function end.
definition (Centralized LIFO goto Unwind): Originating in systems C where ISO C lacks C++ RAII destructors, centralized LIFO goto unwind places a single reverse-ordered cascade of err_<action>_<resource>: labels at the bottom of a function so each failure after acquisition k jumps to the exact entry point that releases resources k .. 1 in Last-In, First-Out order.
- Step 1. STB_LOCAL symbols never collide across driver objects and let GCC inline single-caller helpers.
- Step 2. Step 1 holds nothing yet, so no cleanup label is needed if the very first acquisition fails.
- Step 3. Jumping to err_clk skips freeing the unallocated buf while guaranteeing the enabled clock turns off.
- Step 4. Omitting 'return 0;' before the error tail is a classic bug that tears down a healthy probe!
Figure 4.2b. Mark internal helpers static (STB_LOCAL) and unwind partial probes in strict LIFO order.
ELF Symbol Tables and Reverse-Cascade Error Labels
Inspecting a compiled object with nm or readelf -s reveals the binary consequence of static: global functions appear as uppercase T (STB_GLOBAL in .text), whereas static functions appear as lowercase t (STB_LOCAL). Enabling -Wmissing-prototypes in Makefile forces every non-static function to have a prior header declaration, turning accidental global symbol leaks into immediate compiler errors.
Inside probe(), name each unwind label after the action it performs (err_free_ring:, err_unmap_io:, err_disable_clk:), never after the error that jumped to it (err1:, bad_irq:). Action-named labels make mismatches self-evident at the goto site: if request_irq() fails right after ring_alloc(), goto err_free_ring; reads as an English proof that ring is the newest live resource requiring release.
Figure 4.2b. Action-named labels (err_free_ring) verify at the jump site which live resource unrolls first.
| Error-Handling Pattern | Code Duplication | Partial-Init Safety | Kernel Review Verdict |
|---|---|---|---|
Mid-function return -ERR | Low | Broken — leaks resources acquired earlier | Rejected (memory/clock/lock leak) |
Single goto fail; with if (p) checks | Low | Fragile — crashes if scalar/handle wasn't zero-initialized | Discouraged when pointers/scalars mix |
Repeated inline free() before each return | High (O(N^2) lines) | Drifts when a new resource is inserted mid-probe | Rejected (maintenance hazard) |
Centralized goto err_<action>; LIFO cascade | Zero (O(N) tail) | Exact prefix unwound in reverse acquisition order | Gold standard across Linux kernel subsystems |
learner@ksa:~/gl-e00/m04-l02$ bat -H 21 -H 54 probe_lifo_unwind.c File: probe_lifo_unwind.c // SPDX-License-Identifier: GPL-2.0 #include <errno.h> #include <stdint.h> struct spi_adc_dev { int clk_on; void *mmio_base; uint8_t *rx_ring; int irq_registered; }; int spi_adc_clk_enable(struct spi_adc_dev *d); void spi_adc_clk_disable(struct spi_adc_dev *d); void *spi_adc_iomap(void); void spi_adc_iounmap(void *base); uint8_t *spi_adc_ring_alloc(void); void spi_adc_ring_free(uint8_t *ring); int spi_adc_irq_register(struct spi_adc_dev *d); void spi_adc_irq_unregister(struct spi_adc_dev *d); static int spi_adc_hw_reset(struct spi_adc_dev *d) { return d->mmio_base ? 0 : -ENODEV; } int spi_adc_probe(struct spi_adc_dev *d) { int rc; rc = spi_adc_clk_enable(d); if (rc < 0) return rc; d->mmio_base = spi_adc_iomap(); if (!d->mmio_base) { rc = -ENOMEM; goto err_disable_clk; } d->rx_ring = spi_adc_ring_alloc(); if (!d->rx_ring) { rc = -ENOMEM; goto err_unmap_mmio; } rc = spi_adc_hw_reset(d); if (rc < 0) goto err_free_ring; rc = spi_adc_irq_register(d); if (rc < 0) goto err_free_ring; return 0; err_free_ring: spi_adc_ring_free(d->rx_ring); err_unmap_mmio: spi_adc_iounmap(d->mmio_base); err_disable_clk: spi_adc_clk_disable(d); return rc; }- Internal helper is marked static so ELF symbol binding stays STB_LOCAL inside this object.
- Explicit 'return 0;' guards the success path before the reverse-ordered LIFO err_* cascade.
nm(1) / CodingStyle Ch.4,6,7(1) GL-E00 Quick Reference nm(1) / CodingStyle Ch.4,6,7(1) SYNOPSIS nm --defined-only driver.o # 't'/'b'/'d' = static STB_LOCAL; 'T'/'B'/'D' = global STB_GLOBAL gcc -std=c11 -Wall -Wextra -Wmissing-prototypes -Werror -c driver.c NAMING & UNWIND RULES snake_case Lowercase words_with_underscores for variables/functions; UPPER_SNAKE_CASE for macros/enums. Antonyms Pair alloc/free, enable/disable, map/unmap, lock/unlock, register/unregister consistently. static Mandatory on every file-scope function and variable not declared in a shared header. goto err_* Forward-only jumps to action-named labels unwinding resources in strict LIFO order. Kernel Systems Academy Lesson 4.2 nm(1) / CodingStyle Ch.4,6,7(1) GL-E00 quick reference · full manual page: man 1 nm(1) / CodingStyle Ch.4,6,7 Fault-Injecting LIFO Unwind Versus Early-Return Leaks in C11
The fastest way to prove a probe() cleanup spine has zero leaks and zero out-of-order releases is deterministic fault injection. In verify.c, we model four sequential hardware acquisitions (CLK=bit0, MMIO=bit1, RING=bit2, IRQ=bit3) where the hardware bus asserts a fatal bus-clock fault if MMIO is unmapped after CLK has already been disabled (FIFO teardown bug!) or if any bit remains set on error return.
We sweep fail_step from 1 through 4 plus the 0 (no-fault) path, contrasting a naive early-return function against our centralized goto LIFO cascade under -Wmissing-prototypes.
learner@ksa:~/gl-e00/m04-l02$ bat -H 19 -H 52 verify.c File: verify.c #define _POSIX_C_SOURCE 200809L #include <errno.h> #include <stdint.h> #include <stdio.h> enum res_bit { RES_CLK = 1U << 0, RES_MMIO = 1U << 1, RES_RING = 1U << 2, RES_IRQ = 1U << 3 }; struct sim_bus { uint32_t live_mask; int order_violations; int release_log[4]; int release_cnt; }; static void record_rel(struct sim_bus *b, enum res_bit bit) { if (!(b->live_mask & bit)) b->order_violations++; if (bit == RES_MMIO && !(b->live_mask & RES_CLK)) b->order_violations++; b->live_mask &= ~bit; if (b->release_cnt < 4) b->release_log[b->release_cnt++] = (int)bit; } static int probe_lifo(struct sim_bus *b, int fail_step) { int rc = 0; if (fail_step == 1) return -EIO; b->live_mask |= RES_CLK; if (fail_step == 2) { rc = -ENOMEM; goto err_disable_clk; } b->live_mask |= RES_MMIO; if (fail_step == 3) { rc = -ENOMEM; goto err_unmap_mmio; } b->live_mask |= RES_RING; if (fail_step == 4) { rc = -EBUSY; goto err_free_ring; } b->live_mask |= RES_IRQ; return 0; err_free_ring: record_rel(b, RES_RING); err_unmap_mmio: record_rel(b, RES_MMIO); err_disable_clk: record_rel(b, RES_CLK); return rc; } int main(void) { for (int step = 1; step <= 4; step++) { struct sim_bus bus = {0}; int rc = probe_lifo(&bus, step); if (rc >= 0 || bus.live_mask != 0U || bus.order_violations != 0) return 10 + step; printf("FAULT_STEP=%d rc=%d released=%d live_mask=0x%x violations=%d\n", step, rc, bus.release_cnt, bus.live_mask, bus.order_violations); } struct sim_bus ok_bus = {0}; if (probe_lifo(&ok_bus, 0) != 0 || ok_bus.live_mask != 0xFU) return 20; printf("PROBE_OK live_mask=0x%x (all 4 resources active, STB_LOCAL clean)\n", ok_bus.live_mask); return 0; }- Simulates a real SoC bus fault if MMIO registers are touched/unmapped after their gate clock is disabled.
- Reverse-ordered err_free_ring -> err_unmap_mmio -> err_disable_clk unwinds strictly in LIFO order.
Confirming Zero Leaks Across All Four Fault Injection Points
Notice -Wmissing-prototypes on the gcc command line: because both record_rel and probe_lifo are declared static, the translation unit compiles cleanly with zero exported global symbols other than main. Removing static from either helper immediately fails -Werror=missing-prototypes.
In the execution output, FAULT_STEP=1..4 releases 0, 1, 2, 3 resources respectively, always terminating with live_mask=0x0 and violations=0, while PROBE_OK preserves live_mask=0xf because return 0; exits cleanly above err_free_ring:.
learner@ksa:~/gl-e00/m04-l02gcc -std=c11 -Wall -Wextra -Werror -Wmissing-prototypes verify.c -o verifylearner@ksa:~/gl-e00/m04-l02./verifyFAULT_STEP=1 rc=-5 released=0 live_mask=0x0 violations=0FAULT_STEP=2 rc=-12 released=1 live_mask=0x0 violations=0FAULT_STEP=3 rc=-12 released=2 live_mask=0x0 violations=0FAULT_STEP=4 rc=-16 released=3 live_mask=0x0 violations=0PROBE_OK live_mask=0xf (all 4 resources active, STB_LOCAL clean)learner@ksa:~/gl-e00/m04-l02learner@ksa:~/gl-e00/m04-l02strace -e trace=write,exit_group ./verifywrite(1, "FAULT_STEP=1 rc=-5 released=0 li"..., 296) = 296exit_group(0) = ?+++ exited with 0 +++Classic Unwind Ordering and Missing-Return Disasters
A driver's remove() callback must mirror the exact same LIFO order as probe()'s err_* tail, plus tearing down the final resource (irq_unregister, then ring_free, then iounmap, then clk_disable). Unregistering the user-visible device or IRQ first prevents new callers or interrupts from entering while underlying buffers are being freed.
In modern Linux kernel 6.12 code, devm_* managed APIs and <linux/cleanup.h> (guard(mutex)) automate this exact LIFO stack — and whenever raw subsystems mix with managed ones, explicit goto unwinding obeys the identical reverse-order law.
Missing return 0 Above the First err_* Label:
- Symptom:
probe()initializes hardware cleanly and returns0, yet the device immediately faults or hangs on firstopen()because clocks are off and buffers are freed. - Root Cause: Omitting
return 0;beforeerr_free_ring:causes the happy path (whererc == 0from the last helper call!) to fall straight through the cleanup cascade and still returnrc(0)! - Fix: Always place an explicit
return 0;separated by a blank line directly above the toperr_*label, and verify happy-pathlive_maskstate in unit tests.
FIFO Cleanup Tearing Down Clocks or IRQ Dependencies Backwards:
- Symptom: Unloading a module or failing late in
probe()triggers an imprecise external abort onARMv7-Aor a use-after-free inside the interrupt handler. - Root Cause: Disabling peripheral clocks before unmapping/stopping registers, or freeing
rx_ringbefore callingfree_irq(), lets a pending IRQ or bus write access dead memory/clocks. - Fix: Write cleanup labels in exact reverse order of acquisition: stop IRQ/device entry points first, free buffers second, unmap MMIO third, and gate clocks last.
Guided Practice
Add a fifth resource RES_DEVNODE = 1U << 4 (cdev_add) at the end of probe_lifo() in verify.c, along with a corresponding remove_lifo(struct sim_bus *b) function that tears down a fully initialized 0x1FU device.
Verify that fail_step = 5 jumps to a new err_unreg_irq: label above err_free_ring:, releasing 4 resources in order IRQ -> RING -> MMIO -> CLK, and confirm remove_lifo() releases all 5 resources down to live_mask == 0x0U.
Independent Practice
Temporarily remove static from probe_lifo in verify.c and run gcc -std=c11 -Wall -Wextra -Wmissing-prototypes -Werror verify.c -o verify to observe the exact compiler diagnostic. Restore static, compile to an object file (gcc -c verify.c -o verify.o), and inspect nm verify.o.
Confirm that record_rel and probe_lifo carry lowercase t (STB_LOCAL) while only main carries uppercase T (STB_GLOBAL).
Verification Checks
? check 1 · In probe() acquiring (1) clk_enable -> (2) ioremap -> (3) dma_alloc -> (4) request_irq, which label must a failure in request_irq() jump to?
- [ ]
return -EBUSY;directly because the kernel garbage-collects rawioremapandclk_enablecalls. - [x]
goto err_free_dma;which frees theDMAbuffer, falls throughiounmap, and finally disables the clock. - [ ]
goto err_disable_clk;which disables the clock first and then unmaps MMIO and freesDMA. - [ ]
goto err_free_irq;which callsfree_irq()on the failed IRQ before freeingDMA.
Answer: goto err_free_dma; which frees the DMA buffer, falls through iounmap, and finally disables the clock.
Why: Because request_irq() failed, IRQ (4) was NOT acquired; cleanup starts at the most recently acquired resource (3: dma_alloc) and cascades through (2) and (1).
Common misconception: Calling free_* on the step that just failed, or tearing down resources in FIFO order.
? check 2 · What is the binary effect in the ELF object file when you mark a file-private C helper static?
- [x] Its
.symtabentry receivesSTB_LOCALbinding (tinnm), hiding it from the linker across other.ofiles and permitting aggressive inlining. - [ ] Its local stack variables are moved permanently from the stack into
.rodata. - [ ] It disables preemption automatically whenever the function executes.
- [ ] It forces the linker to place the function in non-cacheable SRAM.
Answer: Its .symtab entry receives STB_LOCAL binding (t in nm), hiding it from the linker across other .o files and permitting aggressive inlining.
Why: On a function definition, static specifies internal linkage (STB_LOCAL), isolating the symbol to the current translation unit.
Common misconception: Confusing static storage duration on local variables with static internal linkage on functions.
? check 3 · Retrieval check from Lesson 4.1: Why should err_* labels be named err_free_ring: rather than numbered err1:, err2:?
- [ ] ISO C11 forbids digits inside
gotolabel identifiers. - [ ]
scripts/checkpatch.plrewrites numbered labels automatically duringmake. - [ ] Numbered labels generate slower indirect jump tables on
ARMv7-A. - [x] Action-named labels let a reviewer verify locally at each
gotostatement that the jump target releases the exact resource acquired immediately above.
Answer: Action-named labels let a reviewer verify locally at each goto statement that the jump target releases the exact resource acquired immediately above.
Why: Inserting a new acquisition mid-function invalidates err1/err2 mental numbering silently, whereas goto err_free_ring; remains self-documenting.
Common misconception: Naming error labels by step number (err1, err2), which silently misroutes jumps when a middle step is added.
Summary
- Kernel C11 uses lowercase
snake_caseidentifiers with symmetric lifecycle antonyms (alloc/free,register/unregister,enable/disable,lock/unlock) and rejects Hungarian type prefixes. - Every file-private function and module variable must be declared
staticso the compiler emitsELFSTB_LOCALlinkage, preventing global symbol collisions and enabling dead-code inlining. - Multi-resource initialization functions unwind partial failures by jumping forward to centralized
err_*labels arranged in strict Last-In, First-Out (LIFO) order. - Returning directly from the middle of a multi-step
probe()after acquiring clocks, mappings, or IRQs leaks earlier resources and leaves hardware clocks or locks wedged.
Step sequence — frame strip: steps_m04_l02
STB_LOCAL symbols never collide across driver objects and let GCC inline single-caller helpers.
reveals: step1
highlights: step1
Step 1 holds nothing yet, so no cleanup label is needed if the very first acquisition fails.
reveals: step2
highlights: step2
Jumping to err_clk skips freeing the unallocated buf while guaranteeing the enabled clock turns off.
reveals: step3
highlights: step3
Omitting 'return 0;' before the error tail is a classic bug that tears down a healthy probe!
reveals: step4
highlights: step4
What you'll learn
- Replace multi-purpose
tempvariables andlong-sized hardware fields with single-purpose<stdint.h>declarations. - Analyze preprocessor token-pasting and precedence hazards to choose between
static inlinefunctions and fully parenthesized macros. - Implement a C11 static-hygiene and
LIFOunwind auditor verifying macro parenthesization,do { ... } while (0)wrapping, and zero hidden control-flow jumps.
Single-Purpose Locals, LP64/ILP32 Widths, and Inline Type Safety
Two habits ported from tiny 8-bit microcontrollers cause severe defects in 32/64-bit Linux systems C. First, reusing a single int temp; variable across a function — first as a loop index, next as a status register mask, and finally as a return code — creates overlapping live ranges where an uninitialized branch reads stale bits. Modern GCC allocates registers via Static Single Assignment (SSA); giving each value a narrow, initialized single-purpose variable (uint32_t sr_val = 0;) costs zero extra stack bytes under -O2 while making dataflow crystal clear.
Second, unsigned long changes width between your x86_64 workstation (LP64: 8 bytes) and your ARMv7-A Cortex-A7 target (ILP32: 4 bytes). Defining an MMIO descriptor or binary header with unsigned long shifts every subsequent field offset by 4 bytes between host unit tests and target silicon! Always use <stdint.h> (uint32_t, uint64_t) or kernel <linux/types.h> (u32, u64), and prefer enum + static inline functions over #define whenever compile-time constant folding is not required.
Figure 4.3a. Textual macro substitution occurs before C parsing; parentheses and do-while(0) preserve AST structure.
mental model: Think of a do { ... } while (0) macro wrapper like shipping a multi-piece circuit subassembly inside one sealed IC package: no matter where the board layout places it, neighboring traces cannot accidentally short into only half of its internal pins.
Where it stops working: do { ... } while (0) protects statement grouping and trailing semicolons, but it STILL evaluates macro arguments each time they appear inside the body — only static inline functions guarantee single evaluation without GNU statement expressions.
definition ( Idiom): A standard C preprocessor idiom that wraps multiple statements inside a do { ... } while (0) loop executing exactly once; unlike a bare { ... } compound block, it requires a trailing semicolon at the invocation site (MACRO(x);), preventing a syntax error before else inside unbraced if (cond) MACRO(x); else ... constructs while optimizing away completely.
- Step 1. _Static_assert(sizeof(struct desc) == 8, ...) catches accidental LP64 pointer/long fields at compile time.
- Step 2. Passing *fifo_reg++ to a static inline reads the hardware FIFO once; a MAX(a,b) macro reads it twice!
- Step 3. Without outer parentheses, ~MASK_MACRO or 2 * ADD_MACRO re-associates with neighbouring operators.
- Step 4. The caller supplies the final semicolon after while (0), forming one syntactic statement.
Figure 4.3b. Use uint32_t for register structs, static inline for functions, and do-while(0) for multi-stmt macros.
Anatomy of Preprocessor Substitution Hazards
The C preprocessor (cpp) knows nothing about C expressions, statements, or types — it performs blind token substitution prior to syntax parsing. Consider #define BIT_MASK(n) 1U << n: calling BIT_MASK(2 + 1) expands to 1U << 2 + 1. Because + has higher precedence than << in C, that one happens to shift by 3, yet writing ~BIT_MASK(3) expands to ~1U << 3 (0xFFFFFFF0U instead of 0xFFFFFFF7U!) because unary ~ binds tighter than <<! Only ((1U) << (n)) is immune in both inner and outer contexts.
Now consider #define ACK_BOTH(a, b) *(a) = 1; *(b) = 1; used inside if (irq) ACK_BOTH(r1, r2);: after expansion, *(b) = 1; sits outside the if statement and fires unconditionally! Wrapping in bare { *(a) = 1; *(b) = 1; } fixes the if-only case, but if (irq) ACK_BOTH(r1, r2); else ... expands to { ... }; else ... — the extra empty ; terminates the if, leaving else with a hard compile error! do { *(a) = 1; *(b) = 1; } while (0) solves both.
Figure 4.3b. Host x86_64 LP64 makes sizeof(long)==8 while ARMv7-A ILP32 makes sizeof(long)==4; uint32_t stays 4 everywhere.
| Mechanism | Type Checking | Argument Evaluation | Best Embedded C11 Use Case |
|---|---|---|---|
enum { FIFO_DEPTH = 32 }; | Integer constant | Compile-time constant | Array bounds, case labels, register bit positions |
static inline uint32_t ... | Strict C11 types | Evaluated once | Register helpers, clamping, bitfield extraction |
#define MASK(n) ((1U) << (n)) | Untyped tokens | Each occurrence evaluated | Compile-time initializers & _Static_assert expressions |
#define PAIR(a,b) do {...} while (0) | Untyped tokens | Each occurrence evaluated | Multi-statement logging or paired debug assertions (__FILE__, __LINE__) |
learner@ksa:~/gl-e00/m04-l03$ bat -H 19 -H 30 mmio_defensive_macros.h File: mmio_defensive_macros.h /* SPDX-License-Identifier: GPL-2.0 */ #ifndef KSA_MMIO_DEFENSIVE_MACROS_H #define KSA_MMIO_DEFENSIVE_MACROS_H #include <stdint.h> enum ccm_gate_mode { CCM_GATE_OFF = 0x0U, CCM_GATE_RUN_ONLY = 0x1U, CCM_GATE_ALWAYS = 0x3U, }; struct dma_bd_hw { uint16_t length; uint16_t status; uint32_t buf_phys; }; _Static_assert(sizeof(struct dma_bd_hw) == 8U, "DMA BD must be 8 bytes on LP64 and ILP32"); #define CCM_CG_SHIFT(slot) (((uint32_t)(slot)) * 2U) #define CCM_CG_MASK(slot) (0x3U << CCM_CG_SHIFT(slot)) static inline uint32_t ccm_set_gate_val(uint32_t reg, unsigned int slot, enum ccm_gate_mode mode) { uint32_t mask = CCM_CG_MASK(slot); return (reg & ~mask) | ((((uint32_t)mode) << CCM_CG_SHIFT(slot)) & mask); } #define MMIO_WRITE_PAIR(reg_a, val_a, reg_b, val_b) \ do { \ *(reg_a) = (val_a); \ *(reg_b) = (val_b); \ } while (0) #endif /* KSA_MMIO_DEFENSIVE_MACROS_H */- C11 _Static_assert locks the 8-byte hardware descriptor size identically across x86_64 and ARMv7-A.
- do { ... } while (0) without a trailing semicolon makes MMIO_WRITE_PAIR safe inside unbraced if/else.
stdint.h(0p) / C11 _Static_assert(3) GL-E00 Quick Reference stdint.h(0p) / C11 _Static_assert(3) SYNOPSIS #include <stdint.h> _Static_assert(constant-expression, "diagnostic string"); DEFENSIVE MACRO & TYPE CHECKLIST Fixed-width Use uint8_t, uint16_t, uint32_t, uint64_t, uintptr_t for HW registers & binary protocols. static inline Prefer over #define for typed, single-evaluation helpers (safe with ptr++ or FIFO reads). Parentheses Wrap EVERY macro arg (x) and the ENTIRE outer expression ((x) + 1U). do-while(0) Wrap multi-statement macros in 'do { ... } while (0)' (no trailing semicolon). Control flow NEVER put 'return', 'goto', or 'break' inside a macro body. Kernel Systems Academy Lesson 4.3 stdint.h(0p) / C11 _Static_assert(3) GL-E00 quick reference · full manual page: man 3 stdint.h(0p) / C11 _Static_assert Proving Macro Precedence, Side-Effect, and Width Invariants in C11
In verify.c, we verify all four defensive rules quantitatively on our workstation: sizeof(unsigned long) vs sizeof(uint32_t) inside descriptor structs, precedence inversion when outer or inner parentheses are omitted, single evaluation of idx++ inside static inline versus double evaluation in naive MAX macros, and do { ... } while (0) branch binding inside an unbraced if/else.
Passing these assertions sets up lab_m04_c_style_auditor, where you will build a reusable C11 static-hygiene and LIFO unwind analyzer benchmarked with CLOCK_MONOTONIC.
learner@ksa:~/gl-e00/m04-l03$ bat -H 27 -H 34 verify.c File: verify.c #define _POSIX_C_SOURCE 200809L #include <stdint.h> #include <stdio.h> struct hw_desc_fixed { uint32_t ctrl; uint32_t buf_addr; }; _Static_assert(sizeof(struct hw_desc_fixed) == 8U, "Fixed-width descriptor must be 8 bytes"); #define BAD_SHIFT(n) 1U << n #define SAFE_SHIFT(n) ((1U) << (n)) #define SAFE_LATCH(pa, pb, v) \ do { \ *(pa) = (v); \ *(pb) = (v) + 1U; \ } while (0) static inline uint32_t max_u32_once(uint32_t a, uint32_t b) { return (a > b) ? a : b; } int main(void) { uint32_t broken_inv = ~BAD_SHIFT(3); uint32_t safe_inv = ~SAFE_SHIFT(3); uint32_t counter = 4U; uint32_t mval = max_u32_once(counter++, 2U); uint32_t reg_a = 0U, reg_b = 0U; int gate_enabled = 0; if (gate_enabled) SAFE_LATCH(®_a, ®_b, 10U); else reg_a = 99U; if (broken_inv == safe_inv || safe_inv != 0xFFFFFFF7U) return 1; if (mval != 4U || counter != 5U) return 2; if (reg_a != 99U || reg_b != 0U) return 3; printf("LP64_CHECK sizeof_ulong=%zu sizeof_fixed_desc=%zu\n", sizeof(unsigned long), sizeof(struct hw_desc_fixed)); printf("MACRO_PARENS broken_not=0x%08X safe_not=0x%08X\n", broken_inv, safe_inv); printf("INLINE_ONCE result=%u post_counter=%u do_while_else_reg_a=%u reg_b=%u\n", mval, counter, reg_a, reg_b); return 0; }- ~BAD_SHIFT(3) expands to (~1U) << 3 == 0xFFFFFFF0 because unary ~ binds tighter than <<!
- do { ... } while (0) keeps both assignments inside the false branch and pairs cleanly with else.
Inspecting LP64 Host Widths and Precedence Bitmasks
Observe the recorded host output: on x86_64 Linux, sizeof(unsigned long) is 8 bytes while sizeof(struct hw_desc_fixed) remains locked at 8 bytes (2 x 4B uint32_t), matching the ARMv7-A DMA hardware descriptor ring byte-for-byte. Had those two fields used unsigned long, the struct would have ballooned to 16 bytes on the host!
Equally stark is MACRO_PARENS: ~BAD_SHIFT(3) silently cleared bits 0..2 (0xFFFFFFF0) instead of clearing bit 3 (0xFFFFFFF7), proving why outer parentheses on #define expressions are mandatory even when parameters appear trivial.
learner@ksa:~/gl-e00/m04-l03gcc -std=c11 -Wall -Wextra -Werror verify.c -o verifylearner@ksa:~/gl-e00/m04-l03./verifyLP64_CHECK sizeof_ulong=8 sizeof_fixed_desc=8MACRO_PARENS broken_not=0xFFFFFFF0 safe_not=0xFFFFFFF7INLINE_ONCE result=4 post_counter=5 do_while_else_reg_a=99 reg_b=0learner@ksa:~/gl-e00/m04-l03learner@ksa:~/gl-e00/m04-l03strace -e trace=write,exit_group ./verifywrite(1, "LP64_CHECK sizeof_ulong=8 sizeof"..., 168) = 168exit_group(0) = ?+++ exited with 0 +++Hidden Macro Control Flow and Side-Effect Double Reads
Before moving into lab_m04_c_style_auditor, lock in the hierarchy of C11 abstractions: use enum for integer constants, const objects for read-only tables, static inline for typed single-evaluation helpers, and reserve #define strictly for compile-time bitmasks, stringification/__LINE__ diagnostics, or type-generic wrappers.
Whenever a macro must exist, audit three things mechanically: inner (param) parentheses, outer (...) or do { ... } while (0) framing, and zero hidden return/goto statements.
Double FIFO Pop from Passing Volatile Register Read to MAX/MIN Macro:
- Symptom: Reading an
I2CorUARTreceive FIFO insideCLAMP(*rx_fifo_reg, 0, 127)drops every second byte on the wire without setting any hardware overrun flag. - Root Cause: A naive
#define CLAMP(x, lo, hi)mentions(x)two or three times in its ternary expansion, issuing multiplevolatileMMIO read cycles that pop distinct bytes from the hardware FIFO. - Fix: Replace value macros with a
static inlineC11 function, or read thevolatileregister once into a single-purposeuint32_t samplelocal variable first.
Deadlocked Mutex from Hidden return Inside CHECK_ERR Macro:
- Symptom: After an intermittent
I2CNAK error, every subsequent thread opening the device hangs forever insidemutex_lock()(Duninterruptible sleep inps). - Root Cause: Calling
CHECK_RET(i2c_xfer(...));betweenmutex_lock(&dev->lock)andmutex_unlock(&dev->lock)executed a hiddenreturn rc;inside the macro, bypassinggoto err_unlock;. - Fix: Delete return-hiding macros completely; write explicit
if (rc < 0) goto err_unlock;statements so every exit path through held locks is visible.
Guided Practice
In verify.c, add a second broken macro #define BAD_ADD_OFFSET(x) (x) + 0x10U (note inner parameter parentheses are present, outer expression parentheses are missing!) and compare BAD_ADD_OFFSET(4U) * 2U against #define SAFE_ADD_OFFSET(x) ((x) + 0x10U).
Verify that BAD_ADD_OFFSET(4U) * 2U evaluates to 4 + 32 = 36 instead of (4 + 16) * 2 = 40, confirming why both parameter and outer parentheses are required.
Independent Practice
Open labs/lab_m04_c_style_auditor/ and inspect starter/core.c alongside tests.c. Repair the three intentional defects in audit_macro_def(), audit_symbol_hygiene(), and verify_lifo_unwind() so unparenthesized macro args/hidden return tokens are rejected, missing static linkage is flagged, and LIFO release order (k-1 .. 0) is enforced.
Run sh check.sh to confirm 5/5 TAP version 13 checks pass, then run ./files/lab_cli --bench to record CLOCK_MONOTONIC p50/p95/p99 host auditing latency.
Verification Checks
? check 1 · Why does #define ACK_IRQ(a, b) { *(a) = 1; *(b) = 1; } fail to compile inside if (pending) ACK_IRQ(r0, r1); else count++;?
- [x] The caller's semicolon after
}creates an empty statement that terminates theifearly, leavingelsedetached without a matchingif. - [ ] ISO C11 forbids curly braces inside
#definereplacement lists. - [ ] Pointer dereferences inside macros require
typeof()casts in C11. - [ ] The preprocessor strips semicolons inside
{ ... }blocks before passing tokens tocc1.
Answer: The caller's semicolon after } creates an empty statement that terminates the if early, leaving else detached without a matching if.
Why: Expanding { ... }; else parses as a block statement followed by a null statement ;, making the subsequent else token a syntax error; do { ... } while (0) absorbs the ;.
Common misconception: Assuming bare { ... } braces around a multi-statement macro behave identically to do { ... } while (0) inside if/else.
? check 2 · Why is unsigned long unsafe inside a shared DMA buffer-descriptor struct compiled in both x86_64 host tests and ARMv7-A firmware?
- [ ]
unsigned longis big-endian onx86_64and little-endian onARMv7-A. - [ ] ISO C11 defines
unsigned longas16bits unless-std=gnu11is passed. - [ ]
ARMv7-ACortex-A7hardware triggers an undefined-instruction trap onunsigned longarithmetic. - [x] Linux uses
LP64onx86_64(sizeof(unsigned long) == 8) andILP32onARMv7-A(sizeof(unsigned long) == 4), shifting field offsets.
Answer: Linux uses LP64 on x86_64 (sizeof(unsigned long) == 8) and ILP32 on ARMv7-A (sizeof(unsigned long) == 4), shifting field offsets.
Why: Both x86_64 and ARMv7-A Linux run little-endian, but LP64 widens long and pointers to 64 bits while uint32_t stays exactly 4 bytes on both.
Common misconception: Assuming long is always 32 bits on Linux the way it is on 32-bit MCUs or LLP64 Windows.
? check 3 · Retrieval check from Lesson 4.2: Why are macros like #define TRY_CALL(expr) if ((expr) < 0) return -EIO banned in Linux kernel C?
- [ ]
-EIOevaluates to positive5when expanded inside a macro. - [ ] Macros containing
ifdisable-Wallwarnings for the rest of the file. - [x] Hiding
returninside a macro conceals control-flow exits, causing callers to bypass held locks and centralizedgoto err_*LIFOcleanup. - [ ] The preprocessor cannot expand
returnkeywords insidestaticfunctions.
Answer: Hiding return inside a macro conceals control-flow exits, causing callers to bypass held locks and centralized goto err_* LIFO cleanup.
Why: Every control-flow exit in C must remain explicit at the call site so reviewers can trace lock/resource invariants down to the err_* tail.
Common misconception: Using Rust-like TRY() return macros in plain C functions that hold manual locks or raw allocations.
1. Motivation
Production kernel patches fail review immediately when macros hide return jumps, private helpers omit static (STB_GLOBAL namespace pollution), or goto cleanup labels release clocks before unmapping registers.
In this studio, you implement a deterministic C11 static-rule and resource-unwind verifier that catches all three classes of defects automatically before target compilation.
2. Learning objectives
- Detect unparenthesized macro parameters, bare multi-statement bodies, trailing semicolons, and hidden
return/gotoexits inaudit_macro_def(). - Flag file-private symbols lacking
static(STB_LOCAL) linkage and Hungarian/camelCasenaming violations inaudit_symbol_hygiene(). - Verify reverse-order
LIFOresource release (k-1 .. 0) and rejectFIFOor leaked unwind traces inverify_lifo_unwind().
3. Environment requirements
All automated verification steps run in unprivileged user space on a POSIX Linux host using gcc -std=c11 -Wall -Wextra -Werror and clock_gettime(CLOCK_MONOTONIC). Recorded transcripts in captures.json were generated on x86_64 running kernel 7.0.0-42-generic and prove protocol, state-machine, and memory invariants only. Physical bus timing, DMA cache coherency, and board peripheral behavior require target validation on Linux kernel 6.12 LTS (ARMv7-A Cortex-A7).
4. Required software and hardware
- Host workstation:
gcc(-std=c11 -Wall -Wextra -Werror), GNUmake,ar(binutils), and POSIX/bin/sh. - Target environment (optional hardware step, Section 13): Any
ARMv7-ACortex-A7driver.kobuilt againstLinux kernel6.12 withscripts/checkpatch.plandnm --defined-only.
5. Complete executable commands
learner@ksa:~/gl-e00/m04-l03$ bat script.sh File: script.sh make -B -C files ./files/lab_cli ./files/lab_cli --bench sh check.sh6. Annotated source code
files/core.c enforces the production invariants that starter/core.c breaks:
learner@ksa:~/gl-e00/m04-l03$ bat example.c File: example.c for (size_t i = 0U; i < tr->released_count; i++) { uint8_t expected_id = (uint8_t)(tr->acquired_count - 1U - i); if (tr->released_ids[i] != expected_id) return false; }starter/core.c omits the MACRO_HIDDEN_FLOW check on return/goto tokens, skips counting non-static private symbol leaks, and checks FIFO (0 .. k-1) instead of LIFO (k-1 .. 0) release order.
7. Expected output
Passing files/ run (sh check.sh, exit code 0):
learner@ksa:~/gl-e00/m04-l03$ bat listing.txt File: listing.txt TAP version 13 1..5 ok 1 - builds libcore.a and lab_cli cleanly with -std=c11 -Wall -Wextra -Werror ok 2 - archives core.o into libcore.a and links independent TAP verifier ok 3 - detects unparenthesized macro params, missing do-while(0), trailing semicolons, and hidden return/goto ok 4 - flags non-static private functions leaking STB_GLOBAL symbols and non-snake_case identifiers ok 5 - enforces strict reverse LIFO goto unwind order (k-1 down to 0) and rejects FIFO or partial-leak traces # pass 5/5CLI verification output (./files/lab_cli):
learner@ksa:~/gl-e00/m04-l03$ bat listing.txt File: listing.txt MACRO clean_flags=0x0 hazard_flags=0xf SYMBOLS global_leaks=1 naming_violations=1 UNWIND lifo_valid=1 fifo_rejected=1Defective starter/ run (exit code 1): emits FAIL: diagnostics on the broken contract assertions.
8. Explanation of observed behavior
When all three invariants are restored, audit_macro_def() verifies token-bounded return/goto absence alongside (param) and do { ... } while (0) framing, audit_symbol_hygiene() enforces STB_LOCAL static linkage on non-header declarations, and verify_lifo_unwind() confirms exact reverse teardown across every partial failure count.
9. Experiment variations
- Near transfer: Extend
audit_macro_def()to detectbreakandcontinuetokens hidden inside loop-unsafe macros. - Far transfer: Parse
nm -Psymbol table output from compiled.ofiles to verify zero unexpectedT/D/Bglobals outside a module's public header.
10. Performance measurements
Recorded host benchmark (./files/lab_cli --bench, CLOCK_MONOTONIC, warmup=5, N=40 batches):
learner@ksa:~/gl-e00/m04-l03$ bat listing.txt File: listing.txt BENCH lab_m04_c_style_auditor clock=CLOCK_MONOTONIC batches=40x500 p50_ns=106462 p95_ns=125711 p99_ns=126434 sink=1The CLOCK_MONOTONIC benchmark measures user-space string/array auditing throughput (40 x 500 checks per sample) on the Linux host CPU; these nanosecond figures characterize static-check overhead only and never represent target ARMv7-A runtime execution.
11. Troubleshooting
| Symptom | Root cause | Fix | ||
|---|---|---|---|---|
Check 3 fails with flow=0x0 | audit_macro_def() is not scanning for token-bounded return and goto keywords. | Restore `contains_token(body, "return") | contains_token(body, "goto") setting MACRO_HIDDEN_FLOW`. | |
Check 4 fails with leaks=0 | audit_symbol_hygiene() ignores symbols where !in_public_header && !is_static. | Increment out->global_leak_count whenever a private symbol omits static. | ||
Check 5 accepts fifo trace and rejects lifo trace | expected_id uses i (0..N-1) instead of tr->acquired_count - 1U - i. | Compute reverse LIFO index (uint8_t)(tr->acquired_count - 1U - i). |
12. Guided questions
- Why does
contains_token()check!is_ident_char(p[-1])and!is_ident_char(p[tlen])around"return"instead of using plainstrstr(body, "return")?
- *Hint 1:* Consider a valid macro calling a C helper named
return_code_clamp(x)or readinggoto_count. - *Hint 2:* Without identifier-boundary checks,
strstrtriggers false positives wheneverreturnorgotoappears as a substring of a validsnake_caseidentifier.
- Why must
verify_lifo_unwind()verifytr->released_count == tr->acquired_countbefore looping overreleased_ids?
- *Hint 1:* What happens if 4 resources were acquired (
0..3) and only3, 2were released before returning-ENOMEM? - *Hint 2:* Checking only the prefix loop
0 .. released_count - 1would pass3, 2even though resources1and0leaked permanently!
13. Independent challenges
Add a multi-parameter macro auditor audit_macro_multi(const char **params, size_t n_params, const char *body) that detects both unparenthesized occurrences AND duplicate evaluation (count > 1) of any parameter so macros susceptible to fn(i++) double-evaluation are flagged for static inline conversion.
14. Solutions and explanations
The reference files/core.c combines token-bounded control-flow scanning, (param) and do { ... } while (0) structural checks, STB_LOCAL static linkage verification, and acquired_count - 1 - i reverse LIFO indexing to pass all 5/5 TAP checks cleanly.
Run locally in your terminal and check off each verification milestone.
Not started
Summary
- Hardware register layouts and wire headers must use
<stdint.h>fixed-width types (uint8_t,uint16_t,uint32_t,uint64_t) becauseunsigned longis64bits onx86_64(LP64) and32bits onARMv7-A(ILP32). - Typed
constvalues,enumconstants, andstatic inlinefunctions are preferred over#definemacros because they enforce parameter types and evaluate side-effecting arguments (i++) exactly once. - Every expression macro must parenthesize each parameter use and the outer expression (
#define OFF(x) (((x) * 4U) + 8U)), while multi-statement macros wrap their body indo { ... } while (0)without a trailing semicolon. - Macros must never hide control-flow exits (
return,goto,break) because invisible jumps bypass caller spinlocks and centralizedgotocleanup spines.
Step sequence — frame strip: steps_m04_l03
_Static_assert(sizeof(struct desc) == 8, ...) catches accidental LP64 pointer/long fields at compile time.
reveals: step1
highlights: step1
Passing *fifo_reg++ to a static inline reads the hardware FIFO once; a MAX(a,b) macro reads it twice!
reveals: step2
highlights: step2
Without outer parentheses, ~MASK_MACRO or 2 * ADD_MACRO re-associates with neighbouring operators.
reveals: step3
highlights: step3
The caller supplies the final semicolon after while (0), forming one syntactic statement.
reveals: step4
highlights: step4
m05/
Serial Consoles, Boot Straps, UUU Flashing & Bring-Up Triage
Calculate 115200 8N1 UART bit timing, eliminate RTS/CTS flow-control console deadlocks, decode i.MX6ULL BOOT_MODE/BOOT_CFG straps and UUU SDP-to-Fastboot provisioning, and triage bare-metal AAPCS32/.bss, U-Boot PHY/bootargs, and kernel VFS rootfs faults.
What you'll learn
- Calculate
115200 8N1bit-cell duration (8.68 us), frame throughput, and receiver oversampling clock-drift tolerance. - Diagnose asymmetric
RX-works /TX-dead serial console hangs caused byCRTSCTSorIXONflags in POSIXtermios. - Decode
i.MX6ULLSRC_SBMR2(BOOT_MODE[1:0]) andSRC_SBMR1(BOOT_CFG1) register bitmasks to selectUSBSDP,SD,eMMC, orNANDboot.
Asynchronous 8N1 Timing and the Classic Frozen-Keyboard Trap
Your single umbilical cord during early board bring-up — long before Ethernet, USB, or LCD drivers exist — is UART1 running at 115200 8N1. Because UART has no shared clock wire, both ends agree ahead of time on 115,200 symbols per second (1 / 115200 s = 8.6806 us per bit). An idle line rests high (1); a falling edge starts 1 low Start bit, followed by 8 data bits (LSB b0 first), zero parity bits, and 1 high Stop bit — 10 bits (86.81 us) per byte, capping raw console throughput at 11,520 bytes/s.
Nearly every engineer hits the same baffling symptom on day one: U-Boot prints its countdown (Hit any key to stop autoboot: 3 2 1 0) crystal clearly, yet hammering the keyboard does nothing! Board debug headers route only 3 wires (TX, RX, GND) to the USB-TTL chip, leaving CTS# floating unasserted. When minicom defaults to Hardware Flow Control: Yes (CRTSCTS), the host USB-UART refuses to shift out TX bytes while still forwarding incoming RX bytes freely.
Figure 5.1a. 3-wire debug consoles omit RTS#/CTS#; enabling CRTSCTS blocks only host TX while target RX keeps streaming.
mental model: Think of RTS/CTS enabled on a 3-wire UART cable like a polite speaker waiting at a disconnected green talk-light button: you hear everyone in the room (RX) clearly, yet your microphone stays muted forever (TX) waiting for a wire nobody soldered.
Where it stops working: Disabling CRTSCTS fixes 3-wire debug consoles, whereas high-baud (3 Mbps) Bluetooth or cellular UART links genuinely require physical RTS#/CTS# traces to prevent FIFO overruns.
definition (BOOT_MODE & BOOT_CFG Strap Pins): Dual-purpose SoC pads (such as BOOT_MODE0/1 and LCD_DATA00..23 on the i.MX6ULL) whose weak pull-up/pull-down resistor or DIP-switch logic levels are latched once by the System Reset Controller into SRC_SBMR1 and SRC_SBMR2 on the rising edge of POR_B, telling the mask Boot ROM which boot media or USB recovery protocol to execute before pinmuxing.
- Step 1. Missing dialout membership returns EACCES on /dev/ttyUSB0 before baud configuration even runs.
- Step 2. Clearing both CRTSCTS and IXON prevents floating CTS# pins and stray 0x13 XOFF bytes from freezing TX.
- Step 3. Warm watchdog resets do not re-sample external LCD_DATA straps unless POR_B is asserted.
- Step 4. Reading SBMR1/SBMR2 directly catches stuck DIP switches or LCD peripheral pull-up contention.
Figure 5.1b. Disable CRTSCTS on 3-wire 115200 8N1 consoles; set BOOT_MODE=01 for USB SDP or 10 for flash boot.
i.MX6ULL Reset Strap Latches (SRC_SBMR1 and SRC_SBMR2)
When POR_B deasserts, the i.MX6ULL Cortex-A7 starts at 0x00000000 inside on-chip mask Boot ROM (96 KiB) and reads two read-only shadow registers in the System Reset Controller (SRC, base 0x020D8000): SRC_SBMR2 (+0x1C, where bits [25:24] hold latched BMOD[1:0] from BOOT_MODE1:0) and SRC_SBMR1 (+0x04, holding BOOT_CFG1, BOOT_CFG2, and BOOT_CFG4 latched from LCD_DATA00..23).
During development, boards expose BOOT_MODE[1:0] on a 2-pole DIP switch rather than burning one-time-programmable (OTP) eFUSEs (00). Setting BOOT_MODE = 01 forces the Boot ROM straight into USB_OTG1 HID Serial Downloader (SDP) even if flash holds a corrupted bootloader that hangs early! Setting BOOT_MODE = 10 selects Internal Boot and decodes BOOT_CFG1[7:4]: 0b010x boots SD (USDHC1), 0b011x boots eMMC (USDHC2), and 0b1xxx boots raw NAND via GPMI.
Figure 5.1b. External LCD pins act as boot straps only during POR_B assertion; if an attached LCD pulls them high, Internal Boot misroutes!
BOOT_MODE[1:0] | BOOT_CFG1[7:4] | Selected Boot Path | Engineering Use Case |
|---|---|---|---|
01 (SDP) | Ignored | USB_OTG1 HID Serial Downloader (15a2:0080) | Blank-flash factory provisioning or unbricking hung U-Boot via UUU |
10 (Internal) | 0b0100 / 0b0101 | SD / ESD card on USDHC1 (LBA 2, 0x400) | Rapid daily bootloader & Device Tree iteration on removable card |
10 (Internal) | 0b0110 / 0b0111 | eMMC managed flash on USDHC2 (boot0 / user) | Soldered production storage with hardware FTL and boot0 partition |
10 (Internal) | 0b1000..0b1111 | Raw SLC NAND flash on GPMI + BCH ECC | Cost-optimized 512 MiB raw flash using MTD + UBI/UBIFS |
learner@ksa:~/gl-e00/m05-l01$ bat -H 14 -H 28 imx6ull_sbmr_uart.h File: imx6ull_sbmr_uart.h /* SPDX-License-Identifier: GPL-2.0 */ #ifndef KSA_IMX6ULL_SBMR_UART_H #define KSA_IMX6ULL_SBMR_UART_H #include <stdint.h> #include <termios.h> #define IMX6ULL_SRC_SBMR1_ADDR 0x020D8004UL #define IMX6ULL_SRC_SBMR2_ADDR 0x020D801CUL #define SBMR2_BMOD_SHIFT 24U #define SBMR2_BMOD_MASK (0x3U << SBMR2_BMOD_SHIFT) #define BMOD_FUSES 0x0U #define BMOD_SERIAL_DOWNLOADER 0x1U #define BMOD_INTERNAL_BOOT 0x2U #define SBMR1_CFG1_DEV_SHIFT 4U #define SBMR1_CFG1_DEV_MASK (0xFU << SBMR1_CFG1_DEV_SHIFT) static inline void uart_cfg_raw_115200_3wire(struct termios *tio) { cfsetispeed(tio, B115200); cfsetospeed(tio, B115200); tio->c_cflag |= (tcflag_t)(CLOCAL | CREAD | CS8); tio->c_cflag &= ~(tcflag_t)(PARENB | CSTOPB | CSIZE); tio->c_cflag |= (tcflag_t)CS8; #ifdef CRTSCTS tio->c_cflag &= ~(tcflag_t)CRTSCTS; #endif tio->c_iflag &= ~(tcflag_t)(IXON | IXOFF | IXANY); } #endif /* KSA_IMX6ULL_SBMR_UART_H */- BMOD[1:0] at SRC_SBMR2[25:24] distinguishes USB OTG1 SDP (01) from Internal Boot (10).
- Explicitly clears both CRTSCTS and IXON/IXOFF so floating CTS# or 0x13 bytes never freeze TX.
picocom(1) / termios(3)(1) GL-E00 Quick Reference picocom(1) / termios(3)(1) SYNOPSIS picocom -b 115200 -d 8 -p n -y n --flow n /dev/ttyUSB0 minicom -D /dev/ttyUSB0 -b 115200 # Ctrl-A Z -> O -> Serial port setup -> F (Hardware Flow: No!) KEY DIAGNOSTICS RX prints, TX dead Hardware Flow Control (CRTSCTS) is ON over a 3-wire cable, or Ctrl-S (XOFF) paused TX. Garbled characters Baud rate mismatch (e.g., 9600 vs 115200) or missing common GND reference wire. Zero output at POR BOOT_MODE=01 (waiting silently on USB SDP!), blank flash, or TX/RX crossed backwards. Exit picocom Press Ctrl-A followed by Ctrl-X. Kernel Systems Academy Lesson 5.1 picocom(1) / termios(3)(1) GL-E00 quick reference · full manual page: man 1 picocom(1) / termios(3) Calculating 8N1 Timing Margins and Decoding SRC Strap Registers in C11
In verify.c, we compute exact 115200 8N1 bit and frame durations in integer nanoseconds, verify the 16x oversampling Stop-bit drift limit (~4.69%), model the 3-wire CRTSCTS TX-deadlock state table, and decode real SRC_SBMR1/SRC_SBMR2 register snapshots for SD, eMMC, NAND, and USB_OTG1 SDP.
Running this model on our host proves exact bitmask extraction and termios flag invariants before probing 0x020D8004 and 0x020D801C from the U-Boot prompt.
learner@ksa:~/gl-e00/m05-l01$ bat -H 29 -H 39 verify.c File: verify.c #define _POSIX_C_SOURCE 200809L #include <stdbool.h> #include <stdint.h> #include <stdio.h> static const char *decode_imx_boot(uint32_t sbmr1, uint32_t sbmr2) { uint32_t bmod = (sbmr2 >> 24U) & 0x3U; uint32_t cfg1_hi = (sbmr1 >> 4U) & 0xFU; uint32_t port = (sbmr1 >> 11U) & 0x1U; if (bmod == 0x1U) return "USB_OTG1_SDP"; if (bmod == 0x0U) return "FUSE_BOOT"; if (bmod != 0x2U) return "RESERVED"; if ((cfg1_hi & 0x8U) != 0U) return "GPMI_RAW_NAND"; if ((cfg1_hi == 0x4U || cfg1_hi == 0x5U) && port == 0U) return "USDHC1_SD"; if ((cfg1_hi == 0x6U || cfg1_hi == 0x7U) && port == 1U) return "USDHC2_EMMC"; return "OTHER_INTERNAL"; } int main(void) { uint64_t baud = 115200ULL; uint64_t bit_ps = 1000000000000ULL / baud; /* picoseconds per bit */ uint64_t frame_ps = bit_ps * 10ULL; /* 1 start + 8 data + 1 stop */ uint64_t max_bytes_sec = baud / 10ULL; bool three_wire_cts_asserted = false; bool crtscts_on = true; bool tx_blocked = crtscts_on && !three_wire_cts_asserted; const char *sd = decode_imx_boot(0x00000040U, 0x02000000U); const char *emmc = decode_imx_boot(0x00000860U, 0x02000000U); const char *nand = decode_imx_boot(0x00000080U, 0x02000000U); const char *sdp = decode_imx_boot(0x00000860U, 0x01000000U); if (max_bytes_sec != 11520ULL || !tx_blocked) return 1; printf("UART_8N1 bit_us=%.2f frame_us=%.2f max_Bps=%llu 3wire_crtscts_tx_blocked=%d\n", (double)bit_ps / 1e6, (double)frame_ps / 1e6, (unsigned long long)max_bytes_sec, tx_blocked ? 1 : 0); printf("STRAPS sd=%s emmc=%s nand=%s recovery=%s\n", sd, emmc, nand, sdp); return 0; }- 10 bits per byte at 115200 baud yields 8.68 us/bit, 86.81 us/frame, and 11,520 B/s ceiling.
- Notice sdp overrides the identical SBMR1=0x860 eMMC straps when SBMR2 BMOD[1:0] is 01!
Validating Bit Timing and Strap Override Precedence
Look closely at the fourth decode_imx_boot() call in STRAPS: even when SRC_SBMR1 still holds 0x00000860 (USDHC2 eMMC DIP switches untouched!), setting BOOT_MODE[1:0] = 01 (sbmr2 = 0x01000000) routes execution straight to USB_OTG1_SDP! That is why factory recovery needs only a single BOOT_MODE toggle without disturbing your BOOT_CFG storage switch bank.
UART_8N1 also confirms why dumping 1 MiB of hex over 115200 UART takes over 90 seconds (11,520 B/s raw byte cap, and 3x longer in ASCII hex), motivating TFTP/USB for bulk image transfer.
learner@ksa:~/gl-e00/m05-l01gcc -std=c11 -Wall -Wextra -Werror verify.c -o verifylearner@ksa:~/gl-e00/m05-l01./verifyUART_8N1 bit_us=8.68 frame_us=86.81 max_Bps=11520 3wire_crtscts_tx_blocked=1STRAPS sd=USDHC1_SD emmc=USDHC2_EMMC nand=GPMI_RAW_NAND recovery=USB_OTG1_SDPlearner@ksa:~/gl-e00/m05-l01learner@ksa:~/gl-e00/m05-l01strace -e trace=write,exit_group ./verifywrite(1, "UART_8N1 bit_us=8.68 frame_us=86"..., 155) = 155exit_group(0) = ?+++ exited with 0 +++Boot-Strap Contention and Serial Console Failure Modes
Whenever a newly powered board shows a completely blank 115200 8N1 terminal, check four physical facts in 30 seconds before touching source code: (1) BOOT_MODE isn't left in 01 (USB SDP prints zero UART characters while waiting silently on USB_OTG1!), (2) GND is shared and TX/RX aren't swapped, (3) BOOT_CFG matches the populated flash chip, and (4) POR_B was pulsed after setting the DIP switches.
If RX prints normally while TX ignores keystrokes, clear CRTSCTS and IXON first.
Silent Blank UART Because BOOT_MODE Left in 01 After UUU Flashing:
- Symptom: Flashing
U-BoottoeMMCviaUUUsucceeds100%, yet pressing the reset button produces zero characters onUART1. - Root Cause: With
BOOT_MODE[1:0]still set to01(Serial Downloader), thei.MX6ULLBoot ROM never readseMMCand outputs nothing onUART1— it silently enumeratesUSB_OTG1waiting for anotherSDPhost command. - Fix: Switch
BOOT_MODE[1:0]back to10(Internal Boot), verifyBOOT_CFGselectseMMC/NAND/SD, and trigger a fullPOR_Bpower-on reset.
RGB LCD Ribbon Cable Pulling LCD_DATA Boot Straps High at POR_B:
- Symptom: Board boots reliably from
SDcard when bare, then stops booting completely the instant an externalRGBLCDpanel or peripheral hat is plugged into theLCD_DATAheader. - Root Cause: The
i.MX6ULLmultiplexesBOOT_CFG1/2/4ontoLCD_DATA00..23duringPOR_B; external pull-ups or powered back-feeding on theLCDcable override weak10 kOhmboard strap resistors and select a non-existent boot device. - Fix: Isolate
LCD_DATAperipheral loads untilPOR_Bdeasserts, strengthen strap resistors per hardware design guidelines, or burnBT_FUSE_SEL+ boot fuses for production boards.
Guided Practice
Extend verify.c to compute receiver sampling drift at bit 9.5 (middle of the Stop bit, 9.5 bit periods after the falling Start edge): if the target UART baud clock runs at 118,500 Hz (+2.86% fast) while the host runs at 112,500 Hz (-2.34% slow), does cumulative phase error exceed 0.5 bit periods (4.34 us)?
Print the cumulative drift in microseconds and verify that 5.20% > 4.76% (0.5 / 10.5) triggers a Stop-bit framing error (FE), explaining why garbage characters often appear at the tail of 0xFF/0x55 bytes when baud dividers are misconfigured.
Independent Practice
Write a C11 helper check_termios_3wire_safe(uint32_t c_cflag, uint32_t c_iflag) using <termios.h> constants that verifies CS8 is set, PARENB and CSTOPB are clear, CRTSCTS (when defined) is clear, and IXON | IXOFF are clear.
Test it on a cfmakeraw(&tio) struct before and after masking CRTSCTS to verify whether cfmakeraw alone clears hardware flow control on Linux glibc (spoiler: cfmakeraw does not touch CRTSCTS!).
Verification Checks
? check 1 · During bring-up over a 3-wire (TX, RX, GND) USB-TTL adapter, U-Boot prints its boot banner cleanly, yet pressing keys on your laptop never interrupts autoboot. What is the first host setting to check?
- [ ]
BOOT_MODE[1:0]set to01(Serial Downloader) on the target DIP switch. - [x] Hardware flow control (
CRTSCTS) or XON/XOFF (IXON) enabled inminicom/picocom, blocking hostTXon the unconnectedCTS#pin. - [ ] Baud rate set to
9600instead of115200on/dev/ttyUSB0. - [ ]
TXandRXwires swapped backwards on the board header.
Answer: Hardware flow control (CRTSCTS) or XON/XOFF (IXON) enabled in minicom/picocom, blocking host TX on the unconnected CTS# pin.
Why: Wrong baud produces garbled RX characters; swapped TX/RX or BOOT_MODE=01 produces zero RX output. Clean RX paired with dead TX is the signature of flow-control blocking (or a broken host TX wire).
Common misconception: Assuming both RX and TX must fail together whenever UART settings are wrong.
? check 2 · How long does a single byte take on the wire at 115200 8N1, and what is the maximum continuous byte rate?
- [x]
10bits x8.68 us/bit=86.81 us/byte, yielding11,520 bytes/smaximum. - [ ]
8bits x8.68 us/bit=69.44 us/byte, yielding14,400 bytes/smaximum. - [ ]
12bits x11.52 us/bit=138.24 us/byte, yielding7,233 bytes/smaximum. - [ ]
9bits x8.68 us/bit=78.13 us/byte, yielding12,800 bytes/smaximum.
Answer: 10 bits x 8.68 us/bit = 86.81 us/byte, yielding 11,520 bytes/s maximum.
Why: 8N1 adds 1 Start bit and 1 Stop bit (0 parity bits) around each 8-bit payload byte = 10 bit cells per byte (115200 / 10 = 11,520 B/s).
Common misconception: Dividing baud rate by 8 instead of 10 by forgetting Start and Stop framing bits.
? check 3 · You flip the i.MX6ULL BOOT_MODE[1:0] DIP switch from 10 to 01 while the board is running Linux, then run reboot from the shell. Why does the board boot eMMC again instead of entering USB SDP?
- [ ]
Linux kernel6.12 overwrites OTP boot eFUSEs during graceful shutdown. - [ ]
BOOT_MODE = 01selectseMMCUSDHC2while10selectsUSBSDP. - [ ]
USB_OTG1must enumerate aFAT32thumb drive beforeSDPactivates. - [x] External
BOOT_MODE/BOOT_CFGpads are latched intoSRC_SBMR1/SBMR2onPOR_Bpower-on reset, not on a warm watchdog software reboot.
Answer: External BOOT_MODE/BOOT_CFG pads are latched into SRC_SBMR1/SBMR2 on POR_B power-on reset, not on a warm watchdog software reboot.
Why: Software reboot triggers a warm WDOG reset that preserves latched SRC shadow state; cold power-cycling or asserting physical POR_B re-samples the DIP switches.
Common misconception: Expecting Linux reboot to re-latch external hardware boot-mode pins.
Summary
- At
115200 8N1, each asynchronous frame carries10bit cells (1Start,8LSB-first data,0parity,1Stop) at8.68 us/bit(86.81 us/frame,11,520 bytes/smax). - Leaving hardware flow control (
CRTSCTS) enabled inminicomorpicocomon a3-wire (TX/RX/GND) USB-TTL bridge blocks host keyboardTXwaiting on unassertedCTS#while targetRXprints normally. - At
POR_Breset release, thei.MX6ULLBoot ROM samplesBOOT_MODE[1:0](SRC_SBMR2[25:24]):10selects Internal Boot viaBOOT_CFGstraps,01entersUSB_OTG1Serial Downloader (SDP), and00boots from eFUSEs. - Under Internal Boot (
BOOT_MODE = 10),BOOT_CFG1[7:4](SRC_SBMR1[7:4]sampled fromLCD_DATApins) selectsSD(USDHC1),eMMC(USDHC2), or rawNAND(GPMI).
Step sequence — frame strip: steps_m05_l01
Missing dialout membership returns EACCES on /dev/ttyUSB0 before baud configuration even runs.
reveals: step1
highlights: step1
Clearing both CRTSCTS and IXON prevents floating CTS# pins and stray 0x13 XOFF bytes from freezing TX.
reveals: step2
highlights: step2
Warm watchdog resets do not re-sample external LCD_DATA straps unless POR_B is asserted.
reveals: step3
highlights: step3
Reading SBMR1/SBMR2 directly catches stuck DIP switches or LCD peripheral pull-up contention.
reveals: step4
highlights: step4
What you'll learn
- Contrast
SD/eMMC512-byteLBA+boot0hardware partitions against rawSLC NANDeraseblock, page/OOB,MTD, andUBI/UBIFSgeometry. - Analyze why placing
FAT32orext4directly onto rawNANDfails immediately due to factory bad blocks and missing wear leveling. - Trace
UUUprovisioning scripts fromSDP:Boot ROMDCD+DDR3download intoFB:U-BootFastbootflash commands.
Managed FTL Block Flash Versus Raw SLC NAND Geometry
Embedded i.MX6ULL boards ship in two primary non-volatile storage variants: 8 GiB eMMC (USDHC2) and 512 MiB raw SLC NAND (GPMI), alongside a removable SD slot (USDHC1). Although all three store bits in floating-gate/charge-trap NAND cells under the hood, their software interfaces belong to two completely different worlds!
SD cards and eMMC packages integrate a dedicated controller running a Flash Translation Layer (FTL). Linux sees /dev/mmcblk0 or /dev/mmcblk1 as clean 512-byte sectors (LBA 0..N), so MBR/GPT, FAT32 (/boot), and ext4 (rootfs) work directly once Partition 1 starts at LBA 2048 (1 MiB) above u-boot.imx at 0x400 (LBA 2), or inside eMMC's hardware mmcblk1boot0 partition.
Raw SLC NAND has zero internal controller: the i.MX6ULL GPMI and BCH engines drive raw 2 KiB page writes (+ 64 B OOB ECC), 128 KiB block erases, and Bad Block Tables (BBT) through MTD (/dev/mtd0..N) paired with UBI and UBIFS.
Figure 5.2a. Boot ROM SDP only knows how to initialize DDR3 via DCD and jump to RAM U-Boot; U-Boot Fastboot writes the flash.
mental model: Managed SD/eMMC flash is like checking luggage at an airport desk that hides conveyor routing behind clean claim-tag numbers (LBA), whereas raw SLC NAND hands you the warehouse forklift directly — you must track worn floor bays (BBT) and erase entire shelves (128 KiB PEBs) before stacking a 2 KiB box.
Where it stops working: An internal eMMC FTL handles wear leveling and bad blocks, yet sudden power loss during metadata updates can still corrupt FAT32 or FTL tables without ext4 journaling or read-only squashfs.
definition (UBI (Unsorted Block Images)): A Linux kernel volume-management layer sitting directly above raw MTD flash devices that maps contiguous, bad-block-free Logical Eraseblocks (LEBs) onto Physical Eraseblocks (PEBs), maintaining erase-counter headers across the entire NAND chip and transparently relocating data away from newly failing blocks for UBIFS.
- Step 1. Even a brand-new board with completely erased eMMC/NAND boots U-Boot into DDR3 in < 1 second via SDP.
- Step 2. Storing U-Boot in mmcblk1boot0 isolates bootloader updates from MBR/GPT re-partitioning in user space.
- Step 3. -raw2sparse avoids transferring gigabytes of unallocated ext4 zeros over USB 2.0 High-Speed.
- Step 4. FB: done verifies the final Fastboot ACK before you switch BOOT_MODE=10 to test standalone cold boot.
Figure 5.2b. Keep LBA 2..2047 clear on SD, use boot0 on eMMC, use UBI/UBIFS on raw NAND, and stream via UUU SDP->FB.
eMMC Partition Offsets Versus NAND FCB, MTD, and LEB Sizing
Compare exact byte layouts on both media types so partition math never collides with the Boot ROM! On SD (USDHC1) or eMMC User Area, LBA 0 (0x000..0x1FF) holds the 512-byte MBR; byte 0x400 (LBA 2, 1 KiB offset) holds u-boot.imx (IVT magic 0xD1 followed by DCD and U-Boot binary, ~500..800 KiB); and Partition 1 begins cleanly at LBA 2048 (1 MiB = 0x100000), leaving 1,023 KiB of protected headroom.
On 512 MiB SLC NAND (4,096 PEBs x 128 KiB, 64 pages/block x 2,048 B + 64 B OOB), block 0 cannot simply hold raw u-boot.imx: the Boot ROM expects a Flash Control Block (FCB, written with redundant copies + BCH ECC by kobs-ng or U-Boot bcb) and Discovered Bad Block Table (DBBT). Above U-Boot, DTB, and zImage MTD partitions, UBI subtracts 2 pages (4 KiB: EC + VID headers) from each 128 KiB PEB (LEB = 124 KiB) and reserves ~20 PEBs per 1,024 (2%) for bad-block replacement.
Figure 5.2b. UBI consumes 2 NAND pages (EC + VID headers = 4 KiB on 2 KiB-page SLC NAND) per 128 KiB physical eraseblock.
| Dimension | SD / eMMC (USDHC1/2) | Raw SLC NAND (GPMI) | Operational Consequence |
|---|---|---|---|
| Controller & ECC | Internal FTL MCU handles ECC & wear | Host i.MX6ULL GPMI + BCH hardware ECC | Raw NAND exposes bitflips (-EUCLEAN) and bad blocks to MTD |
| Minimum write / erase | 512 B LBA sector (FTL-managed) | Write 2 KiB page; erase 128 KiB PEB | In-place sector overwrite is physically impossible on raw NAND |
| Bootloader header | IVT at 0x400 (LBA 2 or boot0) | FCB + DBBT in Block 0 + redundant copies | Raw dd of u-boot.imx to /dev/mtd0 fails without FCB ECC! |
| Root filesystem | ext4 or squashfs on /dev/mmcblkXp2 | UBIFS on UBI volume (ubi0:rootfs) | bootargs differ: root=/dev/mmcblk1p2 rootwait vs ubi.mtd=4 root=ubi0:rootfs |
learner@ksa:~/gl-e00/m05-l02$ bat -H 4 -H 13 emmc_nand_provision.uuu File: emmc_nand_provision.uuu uuu_version 1.4.182 # Stage 1: Stream U-Boot (+ IVT/DCD) over USB OTG1 HID SDP into DDR3 RAM SDP: boot -f u-boot-imx6ull-14x14-evk-emmc.imx # Stage 2: RAM U-Boot runs USB Fastboot gadget on OTG1 FB: ucmd setenv fastboot_dev mmc FB: ucmd setenv mmcdev 1 FB: ucmd mmc dev 1 # Program U-Boot into dedicated eMMC boot0 hardware partition & enable boot0 FB: flash bootloader u-boot-imx6ull-14x14-evk-emmc.imx FB: ucmd mmc partconf 1 1 1 0 # Stream full MBR + FAT32 (zImage/dtb) + ext4 rootfs with sparse zero-skipping FB: flash -raw2sparse all core-image-minimal-imx6ull.sdcard FB: Sync FB: done- SDP: talks directly to the i.MX6ULL mask Boot ROM over USB HID to init DDR3 via DCD and boot U-Boot in RAM.
- mmc partconf 1 1 1 0 configures eMMC EXT_CSD[179] so Internal Boot reads boot0 with BOOT_ACK enabled.
uuu(1) / ubiattach(8)(1) GL-E00 Quick Reference uuu(1) / ubiattach(8)(1) SYNOPSIS sudo uuu -lsusb # Verify board enumerates as 15a2:0080 (SE Blank 6ULL) in BOOT_MODE=01 sudo uuu -b emmc_all u-boot.imx rootfs.sdcard sudo uuu emmc_nand_provision.uuu KEY STORAGE COMMANDS (Target Linux / U-Boot) dd if=u-boot.imx of=/dev/sdX bs=1K seek=1 conv=fsync # SD card 1 KiB (0x400) IVT offset ubiformat /dev/mtd4 -f rootfs.ubi # Preserves UBI erase counters (never raw nandwrite over UBI!) ubiattach -p /dev/mtd4 && mount -t ubifs ubi0:rootfs /mnt Kernel Systems Academy Lesson 5.2 uuu(1) / ubiattach(8)(1) GL-E00 quick reference · full manual page: man 1 uuu(1) / ubiattach(8) Verifying LBA Headroom, UBI LEB Overhead, and UUU Ordering in C11
Storage-layout arithmetic bugs wipe partition tables or underestimate UBIFS image limits when mkfs.ubifs -m 2048 -e 126976 -c ... is configured. In verify.c, we validate SD/eMMC IVT (0x400) + u-boot.imx bounds against Partition 1 (LBA 2048), compute exact UBI LEB size (126,976 bytes = 124 KiB) and usable capacity on a 512 MiB SLC NAND chip, and check UUU SDP -> FB transition order.
All geometry math executes deterministically in host C11; actual USB SDP enumeration and GPMI BCH ECC timings belong strictly to physical i.MX6ULL target hardware.
learner@ksa:~/gl-e00/m05-l02$ bat -H 17 -H 28 verify.c File: verify.c #define _POSIX_C_SOURCE 200809L #include <stdbool.h> #include <stdint.h> #include <stdio.h> #include <string.h> struct nand_ubi_geom { uint32_t total_pebs; uint32_t leb_bytes; uint32_t reserved_bad_pebs; uint32_t usable_lebs; }; static struct nand_ubi_geom calc_ubi_geom(uint32_t mtd_pebs, uint32_t peb_bytes, uint32_t page_bytes) { struct nand_ubi_geom g; g.total_pebs = mtd_pebs; g.leb_bytes = peb_bytes - (2U * page_bytes); /* EC + VID headers = 2 pages on non-subpage SLC */ g.reserved_bad_pebs = (4096U * 20U) / 1024U; /* Per-chip 20/1024 BBT pool charged to UBI */ g.usable_lebs = mtd_pebs - g.reserved_bad_pebs - 4U; /* 2 layout + 2 WL/atomic PEBs */ return g; } static bool validate_uuu_steps(const char **cmds, size_t n) { bool ram_uboot_live = false; for (size_t i = 0U; i < n; i++) { if (strncmp(cmds[i], "SDP: boot", 9U) == 0) ram_uboot_live = true; else if (strncmp(cmds[i], "FB:", 3U) == 0 && !ram_uboot_live) return false; } return ram_uboot_live; } int main(void) { uint32_t ivt_offset = 0x400U; /* LBA 2 = 1024 B */ uint32_t uboot_bytes = 640U * 1024U; /* 640 KiB u-boot.imx */ uint32_t part1_lba = 2048U; /* 1 MiB = 1,048,576 B */ bool sd_safe = (ivt_offset + uboot_bytes) <= (part1_lba * 512U); /* 480 MiB rootfs MTD partition = 3840 PEBs of 128 KiB, 2 KiB page */ struct nand_ubi_geom ubi = calc_ubi_geom(3840U, 131072U, 2048U); const char *good_uuu[] = {"SDP: boot -f u-boot.imx", "FB: ucmd mmc dev 1", "FB: done"}; const char *bad_uuu[] = {"FB: flash bootloader u-boot.imx", "SDP: boot -f u-boot.imx"}; if (!sd_safe || ubi.leb_bytes != 126976U || !validate_uuu_steps(good_uuu, 3U) || validate_uuu_steps(bad_uuu, 2U)) return 1; printf("SD_LAYOUT ivt=0x%x uboot_end=%u part1_start=%u headroom_B=%u\n", ivt_offset, ivt_offset + uboot_bytes, part1_lba * 512U, (part1_lba * 512U) - (ivt_offset + uboot_bytes)); printf("NAND_UBI leb_B=%u bad_rsv_pebs=%u usable_lebs=%u usable_MiB=%.1f\n", ubi.leb_bytes, ubi.reserved_bad_pebs, ubi.usable_lebs, ((double)ubi.usable_lebs * (double)ubi.leb_bytes) / (1024.0 * 1024.0)); printf("UUU_SEQ valid_sdp_then_fb=1 reversed_fb_first_rejected=1\n"); return 0; }- Without subpage writes, UBI places EC and VID headers in 2 separate 2 KiB pages -> LEB = 126,976 B.
- Any FB: Fastboot command fails unless an earlier SDP: boot command already started U-Boot in RAM!
Checking Partition Headroom and mkfs.ubifs Parameters
Notice the 126,976-byte (124 KiB) leb_B figure in NAND_UBI: that exact integer is what you pass to mkfs.ubifs -m 2048 -e 126976 -c 3756 when building a NAND rootfs on your Linux host! Passing 131072 (128 KiB raw PEB size) by mistake produces a UBIFS image that ubiupdatevol immediately rejects at runtime.
Notice also why reserved_bad_pebs equals 80 (20/1024 of the entire 4,096-PEB 512 MiB chip, not just the 3,840-PEB rootfs MTD partition!): Linux kernel UBI sizes its bad-block pool against total chip capacity because factory bad blocks cluster unpredictably.
learner@ksa:~/gl-e00/m05-l02gcc -std=c11 -Wall -Wextra -Werror verify.c -o verifylearner@ksa:~/gl-e00/m05-l02./verifySD_LAYOUT ivt=0x400 uboot_end=656384 part1_start=1048576 headroom_B=392192NAND_UBI leb_B=126976 bad_rsv_pebs=80 usable_lebs=3756 usable_MiB=454.8UUU_SEQ valid_sdp_then_fb=1 reversed_fb_first_rejected=1learner@ksa:~/gl-e00/m05-l02learner@ksa:~/gl-e00/m05-l02strace -e trace=write,exit_group ./verifywrite(1, "SD_LAYOUT ivt=0x400 uboot_end=65"..., 204) = 204exit_group(0) = ?+++ exited with 0 +++Provisioning and Flash-Wear Hazards on eMMC and NAND
Keep your host udev rules from Module 1 updated for both UUU USB IDs (15a2:0080 NXP SDP HID and 0525:a4a5 / 1b67:4fff U-Boot Fastboot gadget) so uuu runs reliably without erratic USB permission drops mid-script when the board re-enumerates between SDP: and FB:!
And when updating an existing UBI partition in the field, always use ubiformat or ubiupdatevol — never flash_erase + raw nandwrite, which wipes EC wear-leveling counters.
UUU Hangs at Waiting for Known USB Device Between SDP and FB:
- Symptom:
SDP: boot -f u-boot.imxreaches100%, thenuuustalls indefinitely waiting forFB:Fastboot enumeration. - Root Cause: Either the flashed
u-boot.imxlacksCONFIG_USB_FUNCTION_FASTBOOT/DCDmatching the board'sDDR3size, OR a Linux VM (VirtualBox/VMware) captured15a2:0080(SDP) but failed to auto-capture the new0525:a4a5(Fastboot) USB VID:PID on re-enumeration! - Fix: Add both NXP
SDP(15a2:0080) andU-BootFastboot(0525:a4a5) USB filters to your VM configuration and/etc/udev/rules.d/.
Forgetting bs=1K seek=1 When Writing u-boot.imx to SD Card:
- Symptom: Running
dd if=u-boot.imx of=/dev/sdbbootsU-Boot, yetlsblkandLinux kernelreport theSDcard'sMBRpartition table is completely gone! - Root Cause: Omitting
seek=1 bs=1K(seek=2 bs=512) writesu-boot.imxat byte0x000(LBA 0), overwriting the512-byteMBRAND placing theIVTat0x000instead of0x400! - Fix: Always include
bs=1K seek=1 conv=fsync(preserving bytes0..1023, includingLBA 0MBR), and verifyPartition 1starts at>= LBA 2048.
Guided Practice
Modify verify.c to test what happens when an oversized U-Boot + environment blob grows to 1,100 KiB while Partition 1 starts at LBA 2048 (1,024 KiB). Does sd_safe catch the 77 KiB overlap into the FAT32 Boot Sector?
Compute the minimum 4 MiB-aligned starting sector (LBA 8192) required to give U-Boot and redundant U-Boot environment sectors (env + env_redund) generous 4 MiB headroom.
Independent Practice
Write a C11 parser parse_mtdparts(const char *spec) for mtdparts=gpmi-nand:4m(boot),8m(kernel),1m(dtb),-(rootfs) on a 512 MiB (524,288 KiB) NAND chip that calculates the exact byte offset and PEB count (128 KiB/PEB) of every partition including the remaining -(rootfs) slice.
Confirm that 4 + 8 + 1 = 13 MiB leaves 499 MiB (3,992 PEBs) for rootfs with zero unaligned PEB remainders.
Verification Checks
? check 1 · Why does Linux kernel mount UBIFS over UBI + MTD on raw 512 MiB SLC NAND instead of formatting /dev/mtdblock4 directly as ext4?
- [x] Raw
SLC NANDhas no built-inFTL;ext4fails on factory/wear bad blocks and rapidly wears out fixed metadata eraseblocks withoutUBIlogical-to-physical remapping. - [ ]
ext4only supports64-bit processors and cannot compile on32-bitARMv7-A. - [ ]
GPMINANDtransfers512-byte sectors too fast for the Linux block layer. - [ ]
UBIFSis required byU-BootSDPUSB HID enumeration.
Answer: Raw SLC NAND has no built-in FTL; ext4 fails on factory/wear bad blocks and rapidly wears out fixed metadata eraseblocks without UBI logical-to-physical remapping.
Why: Unlike SD/eMMC (which hide bad blocks and wear leveling inside an on-chip FTL MCU), raw NAND requires MTD + UBI to manage bad blocks and erase counters.
Common misconception: Treating /dev/mtdblockN as a wear-leveled block device suitable for read-write ext4 or FAT32.
? check 2 · During UUU provisioning of a completely blank board (BOOT_MODE = 01), why are two distinct USB protocols (SDP: followed by FB:) used?
- [ ]
SDP:flashes the Linuxext4rootfs whileFB:burns OTP MAC-address fuses. - [ ]
SDP:runs overUART1at115200baud whileFB:runs over100 MbpsEthernet. - [ ]
SDP:is used only forSDcards andFB:is used only forSPINOR flash. - [x]
SDP:talks to the tiny on-chip mask Boot ROM to initializeDDR3(DCD) and startU-Bootin RAM;FB:then uses RAMU-Boot'sFastbootdriver to partition and flasheMMC/NAND.
Answer: SDP: talks to the tiny on-chip mask Boot ROM to initialize DDR3 (DCD) and start U-Boot in RAM; FB: then uses RAM U-Boot's Fastboot driver to partition and flash eMMC/NAND.
Why: The 96 KiB mask Boot ROM does not contain full Fastboot, sparse ext4, or UBI flashing stacks — bootstrapping U-Boot into DDR3 gives UUU full storage drivers in RAM.
Common misconception: Thinking the mask Boot ROM itself writes ext4 partitions directly during SDP:.
? check 3 · Retrieval check from Lesson 5.1: On an SD card (USDHC1), why do we write u-boot.imx with dd if=u-boot.imx of=/dev/sdX bs=1K seek=1 and start Partition 1 at LBA 2048?
- [ ]
FAT32requires Partition 1 to start below byte0x400. - [ ]
seek=1writes into the hiddenboot0hardware partition of anSDcard. - [x]
seek=1(0x400,LBA 2) preserves the512-byteMBRatLBA 0while placing theIVTwhere thei.MX6ULLBoot ROM reads it, andLBA 2048(1 MiB) preventsPartition 1from overwritingU-Boot. - [ ]
LBA 0andLBA 1are factory bad blocks on everySDcard.
Answer: seek=1 (0x400, LBA 2) preserves the 512-byte MBR at LBA 0 while placing the IVT where the i.MX6ULL Boot ROM reads it, and LBA 2048 (1 MiB) prevents Partition 1 from overwriting U-Boot.
Why: Standard SD cards lack eMMC's separate boot0 hardware area, so MBR (0x000), u-boot.imx (0x400), and Partition 1 (0x100000) share one LBA space without overlap.
Common misconception: Confusing SD card single-area layout with eMMC's dedicated mmcblkXboot0 hardware partition.
Summary
SD(USDHC1) andeMMC(USDHC2) embed an on-chip Flash Translation Layer (FTL) exposing512-byteLBAsectors, withi.MX6ULLIVTplaced at byte0x400(LBA 2) andeMMCproviding dedicatedboot0/boot1hardware partitions.- Raw
SLC NAND(GPMI+BCHECC) exposes physical eraseblocks (128 KiB) and factory/wear bad blocks directly without anFTL, requiringLinux kernelMTD, Bad Block Tables (BBT), andUBI/UBIFSrather thanFAT32/ext4. - With
BOOT_MODE[1:0] = 01,UUUStage 1 (SDP: boot -f u-boot.imx) uses the Boot ROM'sUSB_OTG1HID protocol to executeDCDDDR3init and runU-Bootdirectly in RAM. UUUStage 2 (FB:) speaksUSBFastbootto the RAM-residentU-Bootgadget to partition and programeMMC(boot0+GPT/MBR) orNAND(MTD/UBI) unattended.
Step sequence — frame strip: steps_m05_l02
Even a brand-new board with completely erased eMMC/NAND boots U-Boot into DDR3 in < 1 second via SDP.
reveals: step1
highlights: step1
Storing U-Boot in mmcblk1boot0 isolates bootloader updates from MBR/GPT re-partitioning in user space.
reveals: step2
highlights: step2
-raw2sparse avoids transferring gigabytes of unallocated ext4 zeros over USB 2.0 High-Speed.
reveals: step3
highlights: step3
FB: done verifies the final Fastboot ACK before you switch BOOT_MODE=10 to test standalone cold boot.
reveals: step4
highlights: step4
What you'll learn
- Diagnose warm-vs-cold reset nondeterminism and
printf("%lld")/LDRDData Abortcrashes caused by unzeroed.bssor4-byte-misalignedARMv7-Astack pointers. - Triage
U-BootRMII Ethernet PHY reset timing,NULLphydevData Aborttraps, and truncatedbootargsenvironment strings. - Implement a C11 bring-up fault-triage engine (
lab_m05_boot_fault_triage) decoding straps,AAPCS32/.bssstartup bounds, andVFSrootfs panic signatures.
Silent C Runtime Preconditions That Linux User Space Hid From You
When you run ./verify on an Ubuntu host, Linux kernel execve() and glibc _start quietly prepare a pristine C11 execution environment before main() runs: anonymous virtual pages backing .bss are guaranteed zeroed by the MMU, and the kernel aligns the initial user stack pointer to 16 bytes (x86_64) or 8 bytes (ARMv7-A). In bare-metal Cortex-A7 code (GL-E01..E02) or custom SPL, nobody does that unless your start.S and linker script do it explicitly!
Two classic bring-up ghosts follow immediately. First, if start.S forgets to zero __bss_start .. __bss_end, static int initialized; holds random DDR3 power-on charge (or leftover values from the previous warm reset!), making firmware work once and hang on reset. Second, setting ldr sp, =0x80200004 (4-byte aligned, NOT 8-byte aligned!) works fine for int math, then explodes with a Data Abort or prints corrupted garbage the instant you call printf("%llu", ticks) because ARMv7-A AAPCS32 aligns 64-bit va_arg parameters and LDRD/STRD doubleword loads on 8-byte stack boundaries!
Figure 5.3a. Every bring-up hang localizes cleanly to one boundary: POR straps, start.S ABI, U-Boot env/PHY, or Kernel VFS.
mental model: Bringing up bare-metal C or U-Boot without zeroing .bss and 8-byte-aligning SP is like moving into a lab bench without sweeping last week's loose wire clippings off the ESD mat: trivial 1-wire probes work by luck until a wide connector shorts across residual debris.
Where it stops working: Fixing startup assembly and bootargs resolves deterministic software contract bugs; unstable DDR3 calibration or brownout rails on VDD_SOC_IN require oscilloscope eye/rail checks.
definition (AAPCS32 8-Byte Stack Alignment): Defined by the Procedure Call Standard for the ARM Architecture (AAPCS32, section 6.2.1.2), this ABI rule requires SP mod 8 == 0 at every public function call interface so 64-bit integers (uint64_t), double floats, variadic va_list 8-byte arguments, and LDRD/STRD instructions execute at naturally aligned doubleword addresses without alignment traps.
- Step 1. bic sp, sp, #7 guarantees 8-byte alignment even if a symbol or linker expression shifts by 4 bytes.
- Step 2. PHY ID 0xFFFF means MDIO pull-up/pinmux is missing or the PHY is still held in hardware reset.
- Step 3. An unescaped semicolon inside setenv bootargs '...; root=/dev/nfs' runs root= as a U-Boot command!
- Step 4. Major 179 is MMC/SD; adding rootwait tells VFS to wait until USDHC finishes asynchronous probing.
Figure 5.3b. Zero .bss, enforce SP % 8 == 0 (bic sp,sp,#7), check bootargs length, and add rootwait on mmcblk.
Decoding U-Boot Data Aborts and Kernel VFS Panic Signatures
Once U-Boot reaches its console, two subtle configuration traps dominate network and kernel bring-up. First, on i.MX6ULL ENET1/ENET2 boards using LAN8720A or KSZ8081 RMII PHYs, if the Device Tree omits phy-reset-gpios / phy-reset-duration = <15> or mismatches reg = <0> vs <1> MDIO address, mdio list misses the PHY; older vendor patches that dereference phydev without a NULL check trigger a U-Boot pc : [<...>] data abort right inside ping or tftpboot! Second, inside setenv bootargs ..., forgetting quotes around ; or exceeding CONFIG_SYS_CBSIZE truncates the tail of the kernel command line silently.
When Linux kernel 6.12 panics with VFS: Unable to mount root fs on <dev>, read the (major, minor) pair literally rather than guessing! unknown-block(0,0) means the kernel had no block device for root= — either bootargs lost root=..., or root=/dev/nfs was passed to a kernel compiled without CONFIG_ROOT_NFS=y / ip=.... Conversely, unknown-block(179,2) (major 179 = mmcblk) happens when VFS runs before the asynchronous USDHC host controller finishes card detection — cured instantly by rootwait.
Figure 5.3b. Major number 179 identifies MMC/SD block devices; (0,0) indicates no block device matched root=.
| Observed Bring-Up Symptom | Exact Primary Signal | Underlying Root Cause | Deterministic Fix |
|---|---|---|---|
| Works on 1st download, fails after warm reset | Static globals non-zero at main() entry | start.S omitted .bss zero loop | Zero [__bss_start, __bss_end) before bl main |
int prints fine; printf("%lld", x) crashes/garbles | SP = 0x80200004 (SP & 7 == 4) | Violated AAPCS32 8-byte stack alignment | Execute bic sp, sp, #7 in start.S + ALIGN(8) in .lds |
U-Boot TFTP says PHY not found / Data Abort | mdio list empty or 0xFFFF | Missing RMII PHY GPIO reset pulse or wrong MDIO reg | Set phy-reset-gpios, >= 10 ms duration, verify MDIO addr 0/1 |
VFS: Unable to mount root fs on unknown-block(179,2) | mmc1: new high speed MMC card prints after panic! | VFS raced ahead of async USDHC card probe | Append rootwait rw rootfstype=ext4 to U-Boot bootargs |
learner@ksa:~/gl-e00/m05-l03$ bat -H 11 -H 27 armv7_bringup_guard.h File: armv7_bringup_guard.h /* SPDX-License-Identifier: GPL-2.0 */ #ifndef KSA_ARMV7_BRINGUP_GUARD_H #define KSA_ARMV7_BRINGUP_GUARD_H #include <stdbool.h> #include <stdint.h> /* * Reference ARMv7-A CRT0 startup sequence (start.S): * ldr sp, =_stack_top * bic sp, sp, #7 @ Enforce AAPCS32 8-byte stack alignment * ldr r0, =__bss_start * ldr r1, =__bss_end * mov r2, #0 * 1: cmp r0, r1 * strlo r2, [r0], #4 @ Requires 4-byte aligned __bss_start/__bss_end * blo 1b * bl main */ #define ARM_AAPCS32_SP_ALIGN 8U #define IMX_SD_IVT_OFFSET 0x400U #define LINUX_MMC_BLOCK_MAJOR 179U static inline bool armv7_crt0_bounds_valid(uint32_t sp, uint32_t bss_start, uint32_t bss_end) { if ((sp & (ARM_AAPCS32_SP_ALIGN - 1U)) != 0U) return false; if (bss_end < bss_start) return false; if (((bss_start | bss_end) & 0x3U) != 0U) return false; return true; } #endif /* KSA_ARMV7_BRINGUP_GUARD_H */- bic sp, sp, #7 clears bits [2:0] so 64-bit LDRD/STRD and variadic %lld calls stay 8-byte aligned.
- Checks 8-byte SP alignment alongside 4-byte word bounds required by strlo r2, [r0], #4.
bootz(U-Boot) / kernel-parameters(7)(7) GL-E00 Quick Reference bootz(U-Boot) / kernel-parameters(7)(7) U-Boot & Linux 6.12 ROOTFS BOOTARGS TEMPLATES # eMMC / SD ext4 boot (note mandatory 'rootwait'!) setenv bootargs 'console=ttymxc0,115200 root=/dev/mmcblk1p2 rootfstype=ext4 rw rootwait' # Raw SLC NAND UBIFS boot (note quotes protecting ';' in mtdparts if present!) setenv bootargs 'console=ttymxc0,115200 ubi.mtd=4 root=ubi0:rootfs rootfstype=ubifs rw' # NFSv3 network rootfs boot (requires CONFIG_ROOT_NFS=y and static Bench NIC!) setenv bootargs 'console=ttymxc0,115200 root=/dev/nfs nfsroot=192.168.10.1:/srv/nfs/rootfs,v3,tcp ip=192.168.10.50:192.168.10.1:192.168.10.1:255.255.255.0::eth0:off rw' Kernel Systems Academy Lesson 5.3 bootz(U-Boot) / kernel-parameters(7)(7) GL-E00 quick reference · full manual page: man 7 bootz(U-Boot) / kernel-parameters(7) Modeling AAPCS32 Stack Alignment and VFS Panic Triage in Host C11
In verify.c, we prove mathematically why an odd-word SP (0x80200004) corrupts AAPCS32 64-bit stack-argument offsets (ROUND_UP(offset, 8)), verify .bss 4-byte clear bounds so strlo r2, [r0], #4 never overwrites 1..3 bytes of .data/stack past __bss_end, and classify three canonical VFS panic scenarios.
Completing this walkthrough prepares you directly for lab_m05_boot_fault_triage, where you will repair and benchmark the full bring-up diagnostic library.
learner@ksa:~/gl-e00/m05-l03$ bat -H 10 -H 29 verify.c File: verify.c #define _POSIX_C_SOURCE 200809L #include <stdbool.h> #include <stdint.h> #include <stdio.h> #include <string.h> static uint32_t aapcs32_u64_stack_addr(uint32_t sp_at_call, uint32_t slot_off) { /* AAPCS32 aligns 8-byte stack args to 8-byte offset RELATIVE to SP (assumed % 8 == 0)! */ uint32_t rel_aligned = (slot_off + 7U) & ~7U; return sp_at_call + rel_aligned; } static const char *classify_vfs_panic(const char *bootargs, uint32_t major) { if (strstr(bootargs, "root=") == NULL) return "TRUNCATED_OR_MISSING_ROOT_ARG"; if (strstr(bootargs, "root=/dev/nfs") != NULL && major == 0U) return "MISSING_CONFIG_ROOT_NFS_OR_IP_ARG"; if (major == 179U && strstr(bootargs, "rootwait") == NULL) return "ASYNC_MMC_MISSING_ROOTWAIT"; return "CHECK_ROOTFSTYPE_OR_PARTUUID"; } int main(void) { uint32_t bad_sp = 0x80200004U; uint32_t fixed_sp = bad_sp & ~7U; /* bic sp, sp, #7 -> 0x80200000 */ uint32_t bad_u64_addr = aapcs32_u64_stack_addr(bad_sp, 4U); uint32_t good_u64_addr = aapcs32_u64_stack_addr(fixed_sp, 4U); const char *p_trunc = classify_vfs_panic("console=ttymxc0,115200", 0U); const char *p_nfs = classify_vfs_panic("console=ttymxc0,115200 root=/dev/nfs rw", 0U); const char *p_mmc = classify_vfs_panic("console=ttymxc0,115200 root=/dev/mmcblk1p2 rw", 179U); if ((bad_u64_addr & 7U) == 0U || (good_u64_addr & 7U) != 0U) return 1; printf("AAPCS32 bad_sp=0x%08X u64_addr=0x%08X(mod8=%u) fixed_sp=0x%08X u64_addr=0x%08X(mod8=%u)\n", bad_sp, bad_u64_addr, bad_u64_addr & 7U, fixed_sp, good_u64_addr, good_u64_addr & 7U); printf("VFS_TRIAGE case1=%s case2=%s case3=%s\n", p_trunc, p_nfs, p_mmc); return 0; }- Compiler aligns 64-bit arg offsets assuming entry SP % 8 == 0; if SP % 8 == 4, physical addr % 8 == 4!
- bic sp, sp, #7 (bad_sp & ~7U) restores 0x80200000 so every 8-byte stack slot lands on mod8 == 0.
Confirming 64-Bit Slot Misalignment and VFS Cause Isolation
Look at AAPCS32 in the execution capture: the compiler carefully rounded slot_off = 4 up to +8 assuming SP obeyed the ABI, yet because bad_sp started at 0x80200004, 0x80200004 + 8 = 0x8020000C (mod8 = 4!) — guaranteed to fault any alignment-checked LDRD! Applying bad_sp & ~7U (bic sp, sp, #7) places the uint64_t slot at 0x80200008 (mod8 = 0).
VFS_TRIAGE likewise separates truncated bootargs, NFS kernel-config/IP omissions, and missing rootwait on major 179 (mmcblk) without guesswork.
learner@ksa:~/gl-e00/m05-l03gcc -std=c11 -Wall -Wextra -Werror verify.c -o verifylearner@ksa:~/gl-e00/m05-l03./verifyAAPCS32 bad_sp=0x80200004 u64_addr=0x8020000C(mod8=4) fixed_sp=0x80200000 u64_addr=0x80200008(mod8=0)VFS_TRIAGE case1=TRUNCATED_OR_MISSING_ROOT_ARG case2=MISSING_CONFIG_ROOT_NFS_OR_IP_ARG case3=ASYNC_MMC_MISSING_ROOTWAITlearner@ksa:~/gl-e00/m05-l03learner@ksa:~/gl-e00/m05-l03strace -e trace=write,exit_group ./verifywrite(1, "AAPCS32 bad_sp=0x80200004 u64_ad"..., 222) = 222exit_group(0) = ?+++ exited with 0 +++Subtle Linker, U-Boot Semicolon, and DTB Address Collisions
Keep one habit across every bring-up session in GL-E01..GL-E07: whenever boot fails, scroll up from the panic line to find the earliest warning (mdio, regulator, mmc, nfs, or Kernel command line: ... printed near 0.000000). The kernel literally echoes the exact bootargs string it received from U-Boot near the top of dmesg!
Comparing Kernel command line: in dmesg against what you thought setenv bootargs set catches 90% of semicolon and truncation mistakes in five seconds.
Unquoted Semicolon in mtdparts Truncating bootargs Inside U-Boot:
- Symptom: Running
setenv bootargs console=ttymxc0,115200 mtdparts=gpmi-nand:4m(boot); root=ubi0:rootfsprintsUnknown command 'root=ubi0:rootfs'or silently dropsroot=! - Root Cause:
U-Boot's Hush shell treats an unquoted;as a command separator, endingsetenv bootargsearly and trying to execute the remainder as a shell command. - Fix: Always wrap the entire
bootargsvalue in single quotes (setenv bootargs '...') and verify the full stored value withprintenv bootargs.
Word-Loop .bss Clear Overwriting Adjacent Stack When __bss_end Is Unaligned:
- Symptom: Adding a single
static char flag;at the end of.bsscausesstart.Sto corrupt3bytes of the section immediately following__bss_end. - Root Cause: A
4-bytestrlo r2, [r0], #4loop writes a full32-bit word on its final iteration if__bss_end - __bss_startis not a multiple of4bytes. - Fix: Enforce
. = ALIGN(4); __bss_end = .;inside the linker script.bssoutput section and verify((bss_start | bss_end) & 3) == 0.
Guided Practice
Add a U-Boot memory-overlap check check_bootz_overlap(uint32_t zimg_addr, uint32_t zimg_len, uint32_t dtb_addr, uint32_t dtb_len) to verify.c: if an engineer loads a 9 MiB zImage at 0x80800000 (0x80800000 .. 0x81100000) and mistakenly loads .dtb at 0x81000000 instead of 0x83000000, what happens to the 0xD00DFEED FDT header?
Verify your overlap check catches zimg_addr + zimg_len > dtb_addr before bootz jumps into a corrupted Device Tree.
Independent Practice
Open labs/lab_m05_boot_fault_triage/ and inspect starter/core.c. Fix the three intentional bugs in decode_boot_straps(), validate_startup_abi(), and triage_vfs_boot_panic() (BMOD shift/mask, 8-byte AAPCS32 SP mask vs 4-byte mask, and major == 179 rootwait check).
Run sh check.sh to pass all 5/5 TAP version 13 checks and run ./files/lab_cli --bench to inspect CLOCK_MONOTONIC host diagnostic percentiles.
Verification Checks
? check 1 · A bare-metal ARMv7-A program initializes ldr sp, =0x80200004 in start.S. Simple GPIO LED loops run fine, yet calling snprintf(buf, sizeof(buf), "%llu", counter64) triggers a Data Abort or prints garbage. Why?
- [ ]
snprintfdynamically callsmalloc()on/dev/meminside bare-metal ROM. - [ ]
ARMv7-ACortex-A7hardware lacks64-bit integer addition instructions. - [ ]
0x80200004sits inside read-only Boot ROM oni.MX6ULL. - [x]
0x80200004is only4-byte aligned (SP % 8 == 4), violatingAAPCS32's8-byte public call-boundary stack alignment required for64-bit variadic slots andLDRD/STRD.
Answer: 0x80200004 is only 4-byte aligned (SP % 8 == 4), violating AAPCS32's 8-byte public call-boundary stack alignment required for 64-bit variadic slots and LDRD/STRD.
Why: 0x80200000+ is valid DDR3 RAM on i.MX6ULL, and 32-bit LDR/STR work at +4, so the SP % 8 != 0 bug stays dormant until 64-bit LDRD/va_arg runs.
Common misconception: Assuming 4-byte stack alignment suffices on 32-bit ARMv7-A just because registers are 32 bits wide.
? check 2 · Linux kernel 6.12 boots from eMMC and prints VFS: Unable to mount root fs on unknown-block(179,2), followed 40 ms later by mmc1: new high speed MMC card at address 0001. What is missing from U-Boot bootargs?
- [ ]
init=/bin/echo, which bypasses mounting the root filesystem. - [ ]
mem=32M, which slows down theCortex-A7CPU soeMMCfinishes first. - [x]
rootwait, which instructsVFSto wait for asynchronousMMC/SDcontroller probing before attempting to mount/dev/mmcblk1p2. - [ ]
no_root_squash, which disables UID65534mapping on localeMMCpartitions.
Answer: rootwait, which instructs VFS to wait for asynchronous MMC/SD controller probing before attempting to mount /dev/mmcblk1p2.
Why: Modern Linux kernel USDHC probing is asynchronous so boot doesn't stall; without rootwait, VFS tries to open major 179 (mmcblk1p2) before the partition exists!
Common misconception: Reformatting the eMMC card repeatedly when the kernel log shows mmc1 simply probed a few milliseconds after VFS.
? check 3 · Retrieval check from Lesson 4.2: When an ENET driver's probe() fails because the RMII PHY never responds on MDIO after clk_prepare_enable() and devm_platform_ioremap_resource(), what must its cleanup path ensure?
- [ ] Call
kfree()on stack-allocated local integers before returning. - [x] Unwind any non-
devmresources (such as disabling manually enabled clocks) in reverseLIFOorder and return a negative error code (-ENODEV) without storing a danglingphydevpointer. - [ ] Return
0anyway sopingcan dereferenceNULLphydevlater. - [ ] Leave the
ENETperipheral clock enabled permanently and panic the kernel.
Answer: Unwind any non-devm resources (such as disabling manually enabled clocks) in reverse LIFO order and return a negative error code (-ENODEV) without storing a dangling phydev pointer.
Why: Clean error return + LIFO clock teardown keeps hardware in a safe low-power state and prevents NULL dereference Data Aborts on later network operations.
Common misconception: Ignoring failed PHY attach during probe() and deferring NULL crashes into ndo_open().
1. Motivation
Early board bring-up failures rarely print polite stack traces: wrong BOOT_MODE switches produce total silence, 0x80200004 stacks crash only inside 64-bit printf, and missing rootwait panics VFS 40 ms before eMMC probes.
In this studio, you implement a deterministic C11 bring-up diagnostic engine that decodes hardware strap registers, validates AAPCS32/.bss/IVT invariants, and classifies VFS boot panics.
2. Learning objectives
- Extract
SRC_SBMR2[25:24](BMOD) andSRC_SBMR1(BOOT_CFG1/BOOT_CFG2) bitfields alongside3-wireCRTSCTSconsole deadlock detection. - Enforce
8-byteAAPCS32stack alignment (sp & 7 == 0),4-byte.bsssection bounds, and0x400SD/eMMCIVTplacement. - Classify
U-BootCONFIG_SYS_CBSIZEtruncation,NFSip=omissions, andmajor 179(mmcblk) missing-rootwaitVFSpanics.
3. Environment requirements
All automated verification steps run in unprivileged user space on a POSIX Linux host using gcc -std=c11 -Wall -Wextra -Werror and clock_gettime(CLOCK_MONOTONIC). Recorded transcripts in captures.json were generated on x86_64 running kernel 7.0.0-42-generic and prove protocol, state-machine, and memory invariants only. Physical bus timing, DMA cache coherency, and board peripheral behavior require target validation on Linux kernel 6.12 LTS (ARMv7-A Cortex-A7).
4. Required software and hardware
- Host workstation:
gcc(-std=c11 -Wall -Wextra -Werror), GNUmake,ar(binutils), and POSIX/bin/sh. - Target environment (optional hardware step, Section 13):
i.MX6ULLARMv7-Aboard (SRC_SBMR10x020D8004,SRC_SBMR20x020D801C) runningU-Boot2025.x andLinux kernel6.12.
5. Complete executable commands
learner@ksa:~/gl-e00/m05-l03$ bat script.sh File: script.sh make -B -C files ./files/lab_cli ./files/lab_cli --bench sh check.sh6. Annotated source code
files/core.c enforces the production invariants that starter/core.c breaks:
learner@ksa:~/gl-e00/m05-l03$ bat example.c File: example.c if ((sp_init & 0x7U) != 0U) errs |= STARTUP_ERR_SP_ALIGN8; if (((bss_start | bss_end) & 0x3U) != 0U) errs |= STARTUP_ERR_BSS_ALIGN4; if (ivt_offset != 0x400U) errs |= STARTUP_ERR_IVT_OFFSET;starter/core.c shifts sbmr2 by 16 instead of 24 (BMOD[25:24]), masks sp_init with 0x3U (4-byte alignment) instead of 0x7U (8-byte AAPCS32 alignment), and disables the missing-rootwait detector on major 179.
7. Expected output
Passing files/ run (sh check.sh, exit code 0):
learner@ksa:~/gl-e00/m05-l03$ bat listing.txt File: listing.txt TAP version 13 1..5 ok 1 - builds libcore.a and lab_cli cleanly with -std=c11 -Wall -Wextra -Werror ok 2 - archives core.o into libcore.a and links independent TAP verifier ok 3 - decodes SRC_SBMR2[25:24] BMOD and SRC_SBMR1 BOOT_CFG1 straps plus 3-wire CRTSCTS deadlock ok 4 - enforces ARMv7-A AAPCS32 8-byte SP alignment (sp & 0x7 == 0), 4-byte .bss bounds, and 0x400 IVT offset ok 5 - classifies truncated bootargs, missing NFS ip= config, and missing rootwait on major 179 mmcblk panics # pass 5/5CLI verification output (./files/lab_cli):
learner@ksa:~/gl-e00/m05-l03$ bat listing.txt File: listing.txt STRAPS emmc_target=3 tx_deadlocked=1 sdp_override_target=1 CRT0_ABI clean_flags=0x0 broken_flags=0xd VFS_PANIC mmc_no_rootwait_kind=3Defective starter/ run (exit code 1): emits FAIL: diagnostics on the broken contract assertions.
8. Explanation of observed behavior
Restoring (sbmr2 >> 24U) & 0x3U aligns with the i.MX6ULL System Reset Controller register map, (sp_init & 0x7U) != 0U rejects 0x80200004 odd-word stacks before LDRD faults occur, and checking strstr(bootargs, "rootwait") catches asynchronous USDHC boot races.
9. Experiment variations
- Near transfer: Add
QuadSPINOR (BOOT_CFG1[7:4] == 0x1) andECSPINOR (0x3withBOOT_CFG4) decoding todecode_boot_straps(). - Far transfer: Extend
triage_vfs_boot_panic()to validateubi.mtd=+rootfstype=ubifspairing for rawGPMISLC NANDboots.
10. Performance measurements
Recorded host benchmark (./files/lab_cli --bench, CLOCK_MONOTONIC, warmup=5, N=40 batches):
learner@ksa:~/gl-e00/m05-l03$ bat listing.txt File: listing.txt BENCH lab_m05_boot_fault_triage clock=CLOCK_MONOTONIC batches=40x500 p50_ns=12696 p95_ns=27228 p99_ns=52499 sink=3./files/lab_cli --bench measures in-memory C11 bitmask and bootargs classification speed using CLOCK_MONOTONIC (40 x 500 iterations); physical POR_B, MDIO PHY reset (>= 10 ms), and USDHC probe timings must be measured on target hardware.
11. Troubleshooting
| Symptom | Root cause | Fix |
|---|---|---|
Check 3 fails with sd=0 or sdp=5 | sbmr2 is shifted by 16 instead of 24, reading reserved zeroes instead of BMOD[25:24]. | Extract (sbmr2 >> 24U) & 0x3U in decode_boot_straps(). |
Check 4 fails with sp4=0x0 | 0x80200004 & 0x3U evaluates to 0, missing the 8-byte AAPCS32 alignment violation. | Test (sp_init & 0x7U) != 0U so any non-multiple of 8 sets STARTUP_ERR_SP_ALIGN8. |
Check 5 fails with wait=0 | The rootwait check on root_major == 179U was stubbed out. | Restore strstr(bootargs, "rootwait") == NULL returning VFS_FAULT_MMC_MISSING_ROOTWAIT. |
12. Guided questions
- Why does
decode_boot_straps()checkbmod(SRC_SBMR2[25:24]) BEFORE inspectingcfg1_hi(SRC_SBMR1[7:4])?
- *Hint 1:* What happens on physical hardware when
BOOT_CFGswitches stay set toeMMCwhile you flipBOOT_MODEto01forUUUflashing? - *Hint 2:*
BOOT_MODE = 01(Serial Downloader) and00(Fuses) override externalBOOT_CFGpins completely in the mask Boot ROM.
- Why does
triage_vfs_boot_panic()checkstrlen(bootargs) >= cbsize_limit - 1Ubefore checkingstrstr(bootargs, "root=")?
- *Hint 1:* Suppose a
1024-bytebootargsline hadroot=/dev/mmcblk1p2at byte1015, chopped off toroot=/debyCONFIG_SYS_CBSIZE. - *Hint 2:* Checking buffer-limit truncation first identifies why trailing arguments (
root=orrootwait) vanished instead of reporting a misleading syntax error.
13. Independent challenges
Implement check_bootz_regions(uint32_t zimg_start, uint32_t zimg_size, uint32_t dtb_start, uint32_t dtb_size) accounting for ARM zImage's ~4x in-place self-decompression expansion so .dtb placement too close above zImage (< 32 MiB gap) is flagged before Kernel_decompress overwrites the FDT!
14. Solutions and explanations
files/core.c decodes SRC_SBMR2[25:24] prior to SRC_SBMR1, enforces 8-byte SP (0x7U mask) + 4-byte .bss + 0x400 IVT invariants, and classifies CBSIZE truncation, NFS, and mmcblk rootwait panics across all 5/5 TAP checks.
Run locally in your terminal and check off each verification milestone.
Not started
Summary
- Bare-metal
ARMv7-Astart.Smust explicitly zero[__bss_start, __bss_end)before branching tomain()becauseDDR3powers up with random bit states that corrupt uninitialized C globals. - The
ARMv7-AAAPCS32ABI mandates8-byte stack alignment (SP mod 8 == 0, enforced viabic sp, sp, #7) at public call boundaries so64-bitLDRD/STRDandprintf("%lld")va_argslots do not fault or misalign. U-BootENETTFTPfailures andbootargstruncations stem from missing RMII PHY reset pulse/settle timing (>= 10 ms) or unescaped multi-linesetenv bootargsstrings exceeding console buffer limits.Kernel panic - not syncing: VFS: Unable to mount root fsencodes the exact failure stage:unknown-block(0,0)indicates missing/truncatedroot=orCONFIG_ROOT_NFS, whereasmmcblkerror -2withoutrootwaitindicates asynchronousUSDHCprobe race.
Step sequence — frame strip: steps_m05_l03
bic sp, sp, #7 guarantees 8-byte alignment even if a symbol or linker expression shifts by 4 bytes.
reveals: step1
highlights: step1
PHY ID 0xFFFF means MDIO pull-up/pinmux is missing or the PHY is still held in hardware reset.
reveals: step2
highlights: step2
An unescaped semicolon inside setenv bootargs '...; root=/dev/nfs' runs root= as a U-Boot command!
reveals: step3
highlights: step3
Major 179 is MMC/SD; adding rootwait tells VFS to wait until USDHC finishes asynchronous probing.
reveals: step4
highlights: step4
m06/
Cross-ABI ELF Auditing, Module Vermagic & Workbench Capstone
Audit 32-bit ARMv7-A hard-float ELF binaries (EM_ARM, EF_ARM_ABI_FLOAT_HARD, PT_INTERP, DT_NEEDED), diagnose Linux 6.12 .modinfo vermagic/CRC module rejections, and unify host pre-deployment verification in the GL-E00 Workbench Preflight Capstone.
What you'll learn
- Audit
52-byteElf32_Ehdrheaders ande_flagsbitmasks (0x05000400EABI5 hard-float vs0x05000200soft-float) before copying binaries to/srv/nfs/rootfs. - Diagnose why
./app: No such file or directory(ENOENT) occurs on an existing, executableARMbinary whenPT_INTERPis absent from the target rootfs. - Verify
DT_NEEDEDshared-library presence andGLIBC_2.xxversion ceilings against the target rootfs sysroot.
The Most Misleading Error Message in Embedded Linux Bring-Up
Picture this rite of passage: you cross-compile hello.c on your workstation, copy hello into /srv/nfs/rootfs/root/, verify ls -l ./hello shows -rwxr-xr-x 1 root root 9824, type ./hello on the ARMv7-A serial console, and the shell prints: -sh: ./hello: not found (or No such file or directory, errno = ENOENT = 2)! Engineers lose hours re-running chmod +x or blaming NFS caching on a file standing right in front of them.
Tracing Linux kernel fs/binfmt_elf.c explains every byte of what happened. First, if you accidentally compiled with host gcc (e_machine = EM_X86_64 = 62), elf_check_arch() rejects the header immediately with -ENOEXEC (Exec format error). Second, if you compiled with arm-linux-gnueabihf-gcc (EM_ARM = 40, EF_ARM_ABI_FLOAT_HARD = 0x400), elf_check_arch() passes, load_elf_binary() reads the PT_INTERP program header (/lib/ld-linux-armhf.so.3), calls open_exec() on that loader path inside your minimal BusyBox rootfs, gets -ENOENT because /lib was left empty, and returns -ENOENT to user space!
Figure 6.1a. execve() returns ENOEXEC when e_machine != EM_ARM, and returns ENOENT when PT_INTERP is missing in rootfs!
mental model: PT_INTERP inside a dynamically linked ELF executable works like a #! /bin/sh shebang line at the top of a script: if /bin/sh itself is missing from the rootfs, the kernel reports No such file or directory even though your script file is right there!
Where it stops working: Unlike text shebangs read as ASCII lines, PT_INTERP is a binary program-header table slice parsed only after fs/binfmt_elf.c validates e_machine (EM_ARM) and ELFCLASS32.
definition (PT_INTERP Program Header): An ELF program-header entry (p_type = 3) in dynamically linked executables storing the NUL-terminated filesystem path of the user-space runtime dynamic linker (such as /lib/ld-linux-armhf.so.3 on 32-bit ARM hard-float Linux) that the kernel maps and transfers initial control to before the application's own _start entry point runs.
- Step 1. Catching EM_X86_64 (62) or soft-float (0x200) on the host takes 5 milliseconds with readelf -h.
- Step 2. Note symlink chains: if ld-linux-armhf.so.3 -> ld-2.35.so, BOTH files must exist in rootfs/lib!
- Step 3. DT_NEEDED lists direct dependencies only (unlike ldd, it never executes foreign code).
- Step 4. Building against the SDK's target sysroot guarantees symbol versions never outrun target libc.so.6.
Figure 6.1b. Verify EM_ARM(40), e_flags 0x400 (hard-float), PT_INTERP in rootfs/lib, and matching sysroot glibc.
Inside the 52-Byte Elf32_Ehdr and VFPv3 Calling Convention
Every 32-bit ARM executable starts with a fixed 52-byte Elf32_Ehdr structure that you can parse directly in C without external libraries: bytes 0..3 hold 0x7F, 'E', 'L', 'F'; byte 4 (EI_CLASS) is 1 (ELFCLASS32); byte 5 (EI_DATA) is 1 (ELFDATA2LSB little-endian); uint16_t e_type at 0x10 is 2 (ET_EXEC) or 3 (ET_DYN PIE); uint16_t e_machine at 0x12 is 40 (EM_ARM); and uint32_t e_flags at 0x24 holds 0x05000400 (EF_ARM_EABI_VER5 | EF_ARM_ABI_FLOAT_HARD).
Why are armel (0x200 soft-float) and armhf (0x400 hard-float) mutually incompatible at the binary interface? Under AAPCS base (soft/softfp), double calc(double a, double b) passes a in integer core registers r0:r1 and b in r2:r3. Under AAPCS-VFP (hard, -mfloat-abi=hard -mfpu=neon-vfpv4 on Cortex-A7), a passes in hardware VFP register d0 and b in d1! If an armhf caller jumped into a softfp libm.so, sin(1.57) would read uninitialized junk from r0:r1 — which is why Debian/Linux assigns them completely separate PT_INTERP paths!
Figure 6.1b. Byte offsets 0x00..0x27 of Elf32_Ehdr expose architecture, endianness, EABI version, and VFP float ABI.
| Build Mistake | Elf32_Ehdr / PT_INTERP State | Target Shell Error | Exact Fix |
|---|---|---|---|
Compiled with gcc instead of $(CROSS_COMPILE)gcc | ELFCLASS64, e_machine = 62 (EM_X86_64) | ./app: Exec format error (ENOEXEC) | Compile with arm-linux-gnueabihf-gcc (CC=$(CROSS_COMPILE)gcc) |
Compiled with arm-linux-gnueabi-gcc (soft) | e_flags & 0x200, PT_INTERP = /lib/ld-linux.so.3 | ./app: No such file or directory (ENOENT) | Switch to arm-linux-gnueabihf-gcc (-mfloat-abi=hard) |
Minimal BusyBox rootfs missing /lib/ld-*.so* | PT_INTERP = /lib/ld-linux-armhf.so.3 absent in /srv/nfs/rootfs | ./app: No such file or directory (ENOENT) | Copy toolchain sysroot lib/ld-linux-armhf.so.3 + libc.so.6 (cp -a preserving symlinks!) or link -static |
Host cross-gcc (glibc 2.39) vs target (glibc 2.35) | .gnu.version_r demands GLIBC_2.38 | libc.so.6: version 'GLIBC_2.38' not found | Compile against the target rootfs SDK --sysroot |
learner@ksa:~/gl-e00/m06-l01$ bat -H 18 -H 38 elf32_armhf_contract.h File: elf32_armhf_contract.h /* SPDX-License-Identifier: GPL-2.0 */ #ifndef KSA_ELF32_ARMHF_CONTRACT_H #define KSA_ELF32_ARMHF_CONTRACT_H #include <stdint.h> #define KSA_ELFCLASS32 1U #define KSA_ELFDATA2LSB 1U #define KSA_ET_REL 1U #define KSA_ET_EXEC 2U #define KSA_ET_DYN 3U #define KSA_EM_ARM 40U #define KSA_EM_X86_64 62U #define KSA_PT_INTERP 3U #define KSA_EF_ARM_EABI_VER5 0x05000000U #define KSA_EF_ARM_ABI_FLOAT_SOFT 0x00000200U #define KSA_EF_ARM_ABI_FLOAT_HARD 0x00000400U #define KSA_ARMHF_INTERP_PATH "/lib/ld-linux-armhf.so.3" struct ksa_elf32_ehdr { uint8_t e_ident[16]; uint16_t e_type; uint16_t e_machine; uint32_t e_version; uint32_t e_entry; uint32_t e_phoff; uint32_t e_shoff; uint32_t e_flags; uint16_t e_ehsize; uint16_t e_phentsize; uint16_t e_phnum; uint16_t e_shentsize; uint16_t e_shnum; uint16_t e_shstrndx; }; _Static_assert(sizeof(struct ksa_elf32_ehdr) == 52U, "Elf32_Ehdr is exactly 52 bytes"); struct ksa_elf32_phdr { uint32_t p_type; uint32_t p_offset; uint32_t p_vaddr; uint32_t p_paddr; uint32_t p_filesz; uint32_t p_memsz; uint32_t p_flags; uint32_t p_align; }; #endif /* KSA_ELF32_ARMHF_CONTRACT_H */- EF_ARM_ABI_FLOAT_HARD (0x400) marks VFP register argument passing paired with /lib/ld-linux-armhf.so.3.
- 52-byte Elf32_Ehdr matches the SVR4 / ARM EABI specification identically on LP64 and ILP32 hosts.
elf(5) / readelf(1)(5) GL-E00 Quick Reference elf(5) / readelf(1)(5) SYNOPSIS arm-linux-gnueabihf-readelf -h -l -d -V target_app file target_app DIAGNOSTIC COMMANDS readelf -h app Verify Class: ELF32, Machine: ARM, Flags: Version5 EABI, hard-float ABI. readelf -l app Inspect INTERP header -> [Requesting program interpreter: /lib/ld-linux-armhf.so.3]. readelf -d app List direct (NEEDED) shared libraries without running host ldd! cp -a sysroot/lib/* Always use -a (archive/no-dereference) when populating rootfs/lib symlinks! Kernel Systems Academy Lesson 6.1 elf(5) / readelf(1)(5) GL-E00 quick reference · full manual page: man 5 elf(5) / readelf(1) Simulating fs/binfmt_elf.c Architecture and PT_INTERP Checks in C11
In verify.c, we synthesize three compact binary ELF images in memory — an EM_X86_64 accidental host build, a soft-float armel build (/lib/ld-linux.so.3), and a clean armhf (0x05000400) build (/lib/ld-linux-armhf.so.3) — and run them through an exact C11 model of fs/binfmt_elf.c's execve() validator against an armhf rootfs.
Watching -ENOEXEC (-8) vs -ENOENT (-2) emerge from 50 lines of C11 makes the No such file or directory mystery unforgettable.
learner@ksa:~/gl-e00/m06-l01$ bat -H 56 -H 63 verify.c File: verify.c #define _POSIX_C_SOURCE 200809L #include <errno.h> #include <stdint.h> #include <stdio.h> #include <string.h> struct mini_ehdr { uint8_t ident[16]; uint16_t type; uint16_t machine; uint32_t version, entry, phoff, shoff, flags; uint16_t ehsize, phentsize, phnum, shentsize, shnum, shstrndx; }; struct mini_phdr { uint32_t type, offset, vaddr, paddr, filesz, memsz, flags, align; }; static size_t build_test_elf(uint8_t *buf, uint8_t cls, uint16_t mach, uint32_t eflags, const char *interp) { struct mini_ehdr eh = {0}; struct mini_phdr ph = {0}; size_t ilen = strlen(interp) + 1U; memcpy(eh.ident, "\x7f" "ELF", 4U); eh.ident[4] = cls; eh.ident[5] = 1U; /* LSB */ eh.type = 2U; /* ET_EXEC */ eh.machine = mach; eh.version = 1U; eh.phoff = (uint32_t)sizeof(eh); eh.flags = eflags; eh.ehsize = (uint16_t)sizeof(eh); eh.phentsize = (uint16_t)sizeof(ph); eh.phnum = 1U; ph.type = 3U; /* PT_INTERP */ ph.offset = (uint32_t)(sizeof(eh) + sizeof(ph)); ph.filesz = (uint32_t)ilen; ph.memsz = (uint32_t)ilen; memcpy(buf, &eh, sizeof(eh)); memcpy(buf + sizeof(eh), &ph, sizeof(ph)); memcpy(buf + sizeof(eh) + sizeof(ph), interp, ilen); return sizeof(eh) + sizeof(ph) + ilen; } static int sim_arm_binfmt_elf(const uint8_t *img, size_t len, const char *rootfs_interp) { struct mini_ehdr eh; struct mini_phdr ph; if (len < sizeof(eh) || memcmp(img, "\x7f" "ELF", 4U) != 0) return -ENOEXEC; memcpy(&eh, img, sizeof(eh)); if (eh.ident[4] != 1U || eh.machine != 40U) return -ENOEXEC; if (eh.phnum >= 1U && eh.phoff + sizeof(ph) <= len) { memcpy(&ph, img + eh.phoff, sizeof(ph)); if (ph.type == 3U && ph.offset + ph.filesz <= len) { const char *req = (const char *)(img + ph.offset); if (strcmp(req, rootfs_interp) != 0) return -ENOENT; /* open_exec(PT_INTERP) failed! */ } } return ((eh.flags & 0x400U) != 0U) ? 0 : -EINVAL; } int main(void) { uint8_t img_x64[160], img_soft[160], img_hf[160]; size_t n1 = build_test_elf(img_x64, 2U, 62U, 0U, "/lib64/ld-linux-x86-64.so.2"); size_t n2 = build_test_elf(img_soft, 1U, 40U, 0x05000200U, "/lib/ld-linux.so.3"); size_t n3 = build_test_elf(img_hf, 1U, 40U, 0x05000400U, "/lib/ld-linux-armhf.so.3"); int r_x64 = sim_arm_binfmt_elf(img_x64, n1, "/lib/ld-linux-armhf.so.3"); int r_soft = sim_arm_binfmt_elf(img_soft, n2, "/lib/ld-linux-armhf.so.3"); int r_hf = sim_arm_binfmt_elf(img_hf, n3, "/lib/ld-linux-armhf.so.3"); if (r_x64 != -ENOEXEC || r_soft != -ENOENT || r_hf != 0) return 1; printf("BINFMT_ELF x86_64_rc=%d(ENOEXEC) armel_rc=%d(ENOENT_missing_interp) armhf_rc=%d(OK)\n", r_x64, r_soft, r_hf); return 0; }- Wrong ELF class or e_machine != 40 (EM_ARM) fails elf_check_arch() immediately with -ENOEXEC (-8).
- Valid EM_ARM header whose PT_INTERP path is absent from rootfs returns -ENOENT (-2) from execve()!
Tracing Exact Return Codes (-ENOEXEC vs -ENOENT)
Notice how cleanly BINFMT_ELF separates -8 (-ENOEXEC, Exec format error) on the EM_X86_64 image from -2 (-ENOENT, No such file or directory) on the EM_ARM image requesting /lib/ld-linux.so.3 on an armhf-only rootfs.
Whenever a target shell reports not found or No such file or directory on a binary you know exists, run readelf -l binary | grep interpreter on your host — 99% of the time, either PT_INTERP or its symlink target (ld-2.xx.so) is missing in rootfs/lib/.
learner@ksa:~/gl-e00/m06-l01gcc -std=c11 -Wall -Wextra -Werror verify.c -o verifylearner@ksa:~/gl-e00/m06-l01./verifyBINFMT_ELF x86_64_rc=-8(ENOEXEC) armel_rc=-2(ENOENT_missing_interp) armhf_rc=0(OK)learner@ksa:~/gl-e00/m06-l01learner@ksa:~/gl-e00/m06-l01strace -e trace=write,exit_group ./verifywrite(1, "BINFMT_ELF x86_64_rc=-8(ENOEXEC)"..., 83) = 83exit_group(0) = ?+++ exited with 0 +++Symlink Dereferencing and Cross-ldd Security/Diagnostic Traps
When building minimal BusyBox root filesystems (GL-E03), copy shared libraries from your cross-toolchain's libc/lib/ using cp -a (--archive, which implies -d --no-dereference) rather than plain cp -r! Plain cp duplicates multi-megabyte .so files three times (libc.so.6, libc-2.35.so, etc.) or drops relative symlink targets.
Keep one tiny -static diagnostic binary on /bin during early bring-up so you can always test kernel execve() independently of /lib.
Running Host x86_64 ldd on Cross-Compiled ARM Binaries:
- Symptom: Running
ldd ./arm_appon Ubuntu printsnot a dynamic executableeven thoughfile ./arm_appsaysdynamically linked! - Root Cause:
lddworks by invoking the host's dynamic linker (ld-linux-x86-64.so.2) withLD_TRACE_LOADED_OBJECTS=1, which cannot load32-bitEM_ARMbinaries (and is unsafe on untrusted ELFs). - Fix: Never use host
lddon cross-binaries; always usearm-linux-gnueabihf-readelf -d ./arm_appandreadelf -l ./arm_app.
Copying ld-linux-armhf.so.3 Symlink Without Its Underlying Target File:
- Symptom:
ls /srv/nfs/rootfs/lib/ld-linux-armhf.so.3appears in directory listings, yet./appon the target STILL fails withNo such file or directory(ENOENT)! - Root Cause: On toolchains where
ld-linux-armhf.so.3is a symbolic link pointing told-2.35.so(or/usr/arm-linux-gnueabihf/lib/...absolute host path!), a dangling symlink causesopen_exec()inside the target's root namespace to return-ENOENT. - Fix: Inspect
ls -la rootfs/lib/to verify every symlink is relative (-> ld-2.35.so) and its target regular file exists insiderootfs/lib/.
Guided Practice
Extend sim_arm_binfmt_elf() in verify.c to validate buffer-overflow-safe PT_INTERP NUL termination (memchr(img + ph.offset, '\0', ph.filesz) != NULL). What would happen inside a naive C host tool if a corrupted or truncated ELF file had ph.filesz = 24 with no '\0' byte before ph.offset + ph.filesz?
Verify that strcmp(req, ...) without a bounded memchr check reads past img + len, and test your fix with a synthetic non-NUL-terminated PT_INTERP payload.
Independent Practice
Inspect your host's own ./verify binary by writing a 35-line C11 program dump_self_elf.c that opens "./verify" with fopen("./verify", "rb"), reads the first 64 bytes, and prints EI_CLASS, EI_DATA, and uint16_t e_machine at offset 0x12.
Verify that on x86_64 Linux it prints EI_CLASS=2 (ELF64) and e_machine=62 (EM_X86_64), contrasting directly against EI_CLASS=1 and e_machine=40.
Verification Checks
? check 1 · On your ARMv7-A target console, ls -l /root/sensor_daemon shows -rwxr-xr-x 1 root root 18420, yet running /root/sensor_daemon prints -sh: /root/sensor_daemon: No such file or directory (ENOENT). What is the primary root cause?
- [x] The binary's
PT_INTERPdynamic linker (e.g.,/lib/ld-linux-armhf.so.3or its symlink target) is missing from the target root filesystem. - [ ] The binary was compiled with host
x86_64gcc(e_machine = 62). - [ ] The file lacks read permission (
0400) forUID 0. - [ ]
NFSmounted the root filesystem withoutno_root_squash.
Answer: The binary's PT_INTERP dynamic linker (e.g., /lib/ld-linux-armhf.so.3 or its symlink target) is missing from the target root filesystem.
Why: An x86_64 binary fails earlier with ENOEXEC (Exec format error); ENOENT on an existing executable is fs/binfmt_elf.c failing open_exec() on PT_INTERP!
Common misconception: Assuming No such file or directory from execve() can only refer to the executable path itself, rather than its PT_INTERP interpreter.
? check 2 · What distinguishes EF_ARM_ABI_FLOAT_HARD (0x400, armhf) from EF_ARM_ABI_FLOAT_SOFT (0x200, armel) at function call boundaries?
- [ ]
armhfuses64-bit pointers (ELFCLASS64), whereasarmeluses32-bit pointers. - [ ]
armhfruns big-endian (ELFDATA2MSB), whereasarmelruns little-endian. - [ ]
armhflinks all libraries statically without aPT_INTERPheader. - [x]
armhfpasses floating-point arguments directly inVFP/NEONhardware registers (s0..s15/d0..d7), whereasarmelpasses them in integer core registers (r0..r3) or on the stack.
Answer: armhf passes floating-point arguments directly in VFP/NEON hardware registers (s0..s15 / d0..d7), whereas armel passes them in integer core registers (r0..r3) or on the stack.
Why: Because armhf and armel place float/double parameters in completely different register banks, mixing them corrupts arguments immediately — so Linux separates their ABIs and dynamic linkers.
Common misconception: Thinking -mfloat-abi=hard only changes internal arithmetic instructions without changing the public function-call register ABI.
? check 3 · Why should you inspect an ARM cross-binary's shared-library dependencies with arm-linux-gnueabihf-readelf -d app rather than host ldd app?
- [ ]
readelf -dautomatically downloads missing.sofiles fromAPT. - [ ] ISO C11 binaries do not contain
.dynamicsections. - [x] Host
lddinvokes thex86_64dynamic linker, failing on foreignEM_ARMbinaries, whereasreadelf -dparses.dynamicDT_NEEDEDrecords safely as static data. - [ ]
ldddeletes.symtabdebug symbols from unstrippedARMbinaries.
Answer: Host ldd invokes the x86_64 dynamic linker, failing on foreign EM_ARM binaries, whereas readelf -d parses .dynamic DT_NEEDED records safely as static data.
Why: readelf is pure static binary inspection — architecture-independent, deterministic, and safe inside automated build/CI preflight gates.
Common misconception: Expecting host ldd to work cross-architecture.
Summary
- A valid
ARMv7-ALinux user-space binary carriesELFmagic0x7F 'E' 'L' 'F',EI_CLASS = ELFCLASS32 (1),e_machine = EM_ARM (40), ande_flagsbitEF_ARM_ABI_FLOAT_HARD (0x400). - Executing an
EM_ARM (40)binary on anx86_64host failself_check_arch()withENOEXEC(Exec format error), whereas executing anarmhfbinary on anARMrootfs missing itsPT_INTERP(/lib/ld-linux-armhf.so.3) makesexecve()returnENOENT(No such file or directory). - Mixing soft-float (
EF_ARM_ABI_FLOAT_SOFT = 0x200,r0..r3float passing) with hard-float (0x400,VFPv3s0..s15/d0..d7registers) breaks calling conventions and requests incompatible/lib/ld-linux.so.3vs/lib/ld-linux-armhf.so.3loaders. DT_NEEDEDentries and.gnu.version_rtags (GLIBC_2.xx) bind binaries to the sysroot's minimumglibcversion; compiling with a newer host cross-toolchain than the target rootfs fails inld.soat launch.
Step sequence — frame strip: steps_m06_l01
Catching EM_X86_64 (62) or soft-float (0x200) on the host takes 5 milliseconds with readelf -h.
reveals: step1
highlights: step1
Note symlink chains: if ld-linux-armhf.so.3 -> ld-2.35.so, BOTH files must exist in rootfs/lib!
reveals: step2
highlights: step2
DT_NEEDED lists direct dependencies only (unlike ldd, it never executes foreign code).
reveals: step3
highlights: step3
Building against the SDK's target sysroot guarantees symbol versions never outrun target libc.so.6.
reveals: step4
highlights: step4
What you'll learn
- Inspect
.ko.modinfosections (modinfo drv.ko) to verifyvermagicrelease,SMP/preempt,ARMv7,p2v8, andlicense=GPLfields. - Differentiate
insmod-ENOEXEC(Invalid module format) from-ENOENT(Unknown symbol in module) usingCONFIG_PRINTK_TIME=ydmesglogs. - Audit out-of-tree Kbuild
Makefilesto prevent host-uname -rKDIRcontamination andCONFIG_LOCALVERSION_AUTO-dirtyversion skew.
Why Kernel Modules Carry Zero Binary Compatibility Across Kernel Builds
A Hello World user-space ARM binary compiled ten years ago still runs unmodified on Linux kernel 6.12 because user space crosses swi/svc #0 with stable integer syscall numbers. Loadable kernel modules (.ko, ELF ET_REL relocatable objects) enjoy zero such insulation: once finit_module() relocates drv.ko into kernel virtual memory, its instructions dereference struct file, struct device, and spinlock_t directly in SVC (PL1) privileged mode!
Enabling CONFIG_PREEMPT_RT or CONFIG_DEBUG_SPINLOCK changes the byte size of spinlock_t inside every kernel struct. To prevent silent Ring 0 heap corruption, Kbuild bakes a vermagic= string into every .ko's .modinfo section — e.g., 6.12.0-ksa SMP preempt mod_unload modversions ARMv7 p2v8 — and finit_module() rejects any mismatch with -ENOEXEC (Invalid module format), logging the exact diff to dmesg!
Figure 6.2a. insmod prints only a generic errno string; the exact mismatched vermagic token or symbol prints in dmesg!
mental model: A user-space binary talks to the kernel across a standardized wall socket (syscall ABI lasts decades), whereas a .ko kernel module plugs directly onto the live CPU backplane bus — if a single struct pin shifted by 4 bytes, vermagic refuses insertion before privileged memory explodes.
Where it stops working: Matching vermagic strings proves build-configuration identity, NOT driver bug freedom; force-removing vermagic checks (modprobe --force) risks immediate Oops kernel memory corruption!
definition ( (.modinfo)): A NUL-terminated key-value entry (vermagic=...) generated by scripts/mod/modpost into a loadable .ko module's .modinfo ELF section that concatenates UTS_RELEASE with ABI-critical Kconfig tokens (SMP, preempt, mod_unload, modversions, ARMv7, p2v8) so finit_module() can verify structural binary compatibility with the running kernel.
- Step 1. Never let an embedded driver Makefile fall back silently to /lib/modules/$(shell uname -r)/build!
- Step 2. Check three lines every time: license: GPL, vermagic: <release> ... ARMv7 p2v8, and depends:.
- Step 3. Raw insmod does NOT load 'depends:' modules automatically; modprobe consults modules.dep!
- Step 4. Without timestamps, engineers frequently debug a stale dmesg error from 20 minutes ago!
Figure 6.2b. Pin KDIR + ARCH=arm + CROSS_COMPILE, verify modinfo vermagic == target uname -r, and read timestamped dmesg.
Inside .modinfo NUL Records, __versions CRCs, and KDIR Traps
Open any .ko file in a hex viewer or objdump -s -j .modinfo drv.ko and you will find a flat array of NUL-terminated ('\0') ASCII key=value strings: license=GPL\0, depends=regmap-i2c\0, vermagic=6.12.0-ksa SMP preempt mod_unload ARMv7 p2v8 \0 (note the trailing space before '\0' placed by <linux/vermagic.h>!). Notice the token p2v8: on 32-bit ARMv7-A, CONFIG_ARM_PATCH_PHYS_VIRT patches virt_to_phys() instructions at boot with 8-bit rotated constants, so loading a non-p2v8 module would compute bogus DMA physical addresses!
When CONFIG_MODVERSIONS=y is enabled, genksyms hashes the expanded C AST of every EXPORT_SYMBOL function into a 32-bit CRC stored inside the .ko's __versions section (struct modversion_info: crc + name[56]). Even if UTS_RELEASE strings match, editing a kernel header struct changes module_layout or kmalloc CRCs, triggering disagrees about version of symbol ... (-ENOEXEC). Meanwhile, editing a single tracked file in the kernel git repo when CONFIG_LOCALVERSION_AUTO=y appends -g<hash>-dirty to UTS_RELEASE, breaking vermagic until both zImage and .ko are rebuilt/deployed together!
Figure 6.2b. Every .modinfo tag is a simple NUL-terminated ASCII key=value string readable on any host without ARM hardware.
insmod User-Space Error | dmesg Kernel Log Line | Exact Cause | Clean Engineering Fix |
|---|---|---|---|
Invalid module format (-ENOEXEC) | version magic '6.12.0-dirty ...' should be '6.12.0 ...' | KDIR gained uncommitted changes (LOCALVERSION_AUTO) after zImage flashed | Commit/clean KDIR or deploy matching zImage + .ko build pair |
Invalid module format (-ENOEXEC) | not an Elf32_Ehdr / wrong architecture | Makefile omitted ARCH=arm or defaulted KDIR to host /lib/modules/$(uname -r) | Require explicit KDIR + ARCH=arm CROSS_COMPILE=arm-linux-gnueabihf- |
Invalid module format (-ENOEXEC) | disagrees about version of symbol module_layout | Kernel .config / struct headers changed (MODVERSIONS CRC mismatch) | Run make clean && make in out-of-tree driver against updated KDIR |
Unknown symbol in module (-ENOENT) | Unknown symbol regmap_init_i2c (err -2) or GPL-incompatible | Prerequisite regmap-i2c.ko not loaded, CONFIG_REGMAP_I2C=n, or missing GPL license | Add MODULE_LICENSE("GPL"), enable CONFIG_*, or run depmod -a && modprobe |
learner@ksa:~/gl-e00/m06-l02$ bat -H 4 -H 20 modinfo_vermagic_layout.c File: modinfo_vermagic_layout.c // SPDX-License-Identifier: GPL-2.0 /* * Out-of-tree Kbuild invocation contract (never fallback to host uname -r!): * make -C $(KDIR) M=$(PWD) ARCH=arm CROSS_COMPILE=arm-linux-gnueabihf- modules * * Inside the resulting .ko, modpost emits .modinfo and optional __versions: */ #include <stdint.h> struct ksa_modversion_info { uint32_t crc; char name[64 - sizeof(uint32_t)]; }; /* Representative NUL-separated .modinfo section payload inside sensor_drv.ko */ static const char sample_modinfo_blob[] = "license=GPL\0" "description=KSA I2C Sensor Driver\0" "depends=regmap-i2c\0" "vermagic=6.12.0-ksa SMP preempt mod_unload modversions ARMv7 p2v8 \0"; static const struct ksa_modversion_info sample_versions[] = { { 0x8f3a1204U, "module_layout" }, { 0x41c90e11U, "__regmap_init_i2c" }, };- Explicit ARCH=arm and target KDIR prevent host x86_64 kernel headers from polluting the build.
- Every .modinfo attribute is a NUL-delimited ASCII key=value record checked by finit_module().
modinfo(8) / finit_module(2) / depmod(8)(8) GL-E00 Quick Reference modinfo(8) / finit_module(2) / depmod(8)(8) SYNOPSIS /sbin/modinfo drv.ko # Inspect vermagic, license, depends, parm on x86_64 host! depmod -a -b /srv/nfs/rootfs 6.12.0-ksa # Build /lib/modules/6.12.0-ksa/modules.dep on host dmesg -T | tail -n 15 # Or monotonic [sec.usec] via CONFIG_PRINTK_TIME=y RETURN ERRORS (finit_module) ENOEXEC (Invalid module format) ELF arch mismatch, vermagic string mismatch, or __versions CRC mismatch. ENOENT (Unknown symbol/param) Unloaded dependency .ko, disabled CONFIG_*, bad module param, or GPL block. Kernel Systems Academy Lesson 6.2 modinfo(8) / finit_module(2) / depmod(8)(8) GL-E00 quick reference · full manual page: man 8 modinfo(8) / finit_module(2) / depmod(8) Parsing .modinfo NUL Blobs and Symbol CRCs in Host C11
Because .modinfo is simply a contiguous byte slice of NUL-terminated key=value strings inside the .ko file, we can write a zero-dependency C11 auditor (verify.c) that extracts vermagic= and license=, compares them against a running utsname release + required ARMv7 p2v8 flags, checks __versions CRC32 hashes, and formats timestamped dmesg diagnostics matching Linux kernel 6.12.
This exact .modinfo scanner becomes the second pillar of our Module 6 preflight capstone.
learner@ksa:~/gl-e00/m06-l02$ bat -H 33 -H 40 verify.c File: verify.c #define _POSIX_C_SOURCE 200809L #include <errno.h> #include <stdbool.h> #include <stdint.h> #include <stdio.h> #include <string.h> static const char *find_modinfo_val(const char *blob, size_t len, const char *key) { size_t klen = strlen(key); size_t pos = 0U; while (pos < len) { const char *entry = blob + pos; size_t rem = len - pos; const char *nul = memchr(entry, '\0', rem); if (!nul) break; if ((size_t)(nul - entry) > klen && strncmp(entry, key, klen) == 0 && entry[klen] == '=') return entry + klen + 1U; pos = (size_t)(nul - blob) + 1U; } return NULL; } static int sim_finit_module(const char *blob, size_t len, const char *uts_rel, uint32_t mod_crc, uint32_t kern_crc, bool dep_loaded) { const char *vm = find_modinfo_val(blob, len, "vermagic"); const char *lic = find_modinfo_val(blob, len, "license"); size_t rlen = strlen(uts_rel); if (!vm || strncmp(vm, uts_rel, rlen) != 0 || vm[rlen] != ' ') return -ENOEXEC; if (strstr(vm, "ARMv7") == NULL || strstr(vm, "p2v8") == NULL) return -ENOEXEC; if (mod_crc != kern_crc) return -ENOEXEC; if (!lic || strncmp(lic, "GPL", 3U) != 0 || !dep_loaded) return -ENOENT; return 0; } int main(void) { static const char ok_ko[] = "license=GPL\0vermagic=6.12.0-ksa SMP preempt mod_unload ARMv7 p2v8 \0"; static const char dirty_ko[] = "license=GPL\0vermagic=6.12.0-ksa-dirty SMP preempt mod_unload ARMv7 p2v8 \0"; static const char prop_ko[] = "license=Proprietary\0vermagic=6.12.0-ksa SMP preempt mod_unload ARMv7 p2v8 \0"; int r_ok = sim_finit_module(ok_ko, sizeof(ok_ko) - 1U, "6.12.0-ksa", 0x1A2B3C4DU, 0x1A2B3C4DU, true); int r_dirty = sim_finit_module(dirty_ko, sizeof(dirty_ko) - 1U, "6.12.0-ksa", 0x1A2B3C4DU, 0x1A2B3C4DU, true); int r_crc = sim_finit_module(ok_ko, sizeof(ok_ko) - 1U, "6.12.0-ksa", 0xDEADBEEFU, 0x1A2B3C4DU, true); int r_gpl = sim_finit_module(prop_ko, sizeof(prop_ko) - 1U, "6.12.0-ksa", 0x1A2B3C4DU, 0x1A2B3C4DU, true); if (r_ok != 0 || r_dirty != -ENOEXEC || r_crc != -ENOEXEC || r_gpl != -ENOENT) return 1; printf("[ 142.810412] MOD_CHECK ok=%d dirty=%d(ENOEXEC) bad_crc=%d(ENOEXEC) non_gpl=%d(ENOENT)\n", r_ok, r_dirty, r_crc, r_gpl); return 0; }- Checks vm[rlen] == ' ' token boundary so '6.12.0-ksa-dirty' never sneaks past '6.12.0-ksa'!
- Separates vermagic/CRC -ENOEXEC (-8) from missing-dependency or GPL-only symbol -ENOENT (-2).
Observing Token-Boundary Release Checks and Errno Separation
Notice line 33 of verify.c: strncmp(vm, uts_rel, rlen) == 0 && vm[rlen] == ' '! Because 6.12.0-ksa is a prefix of 6.12.0-ksa-dirty, a sloppy strncmp-only check would falsely approve dirty_ko on the host, only for finit_module() on the board to reject it with -ENOEXEC! Requiring the space delimiter right after <release> catches -dirty and -rc1 suffixes with 100% precision.
Notice also the [ 142.810412] prefix format: enabling CONFIG_PRINTK_TIME=y in your kernel config gives every dmesg event microsecond-resolution ordering.
learner@ksa:~/gl-e00/m06-l02gcc -std=c11 -Wall -Wextra -Werror verify.c -o verifylearner@ksa:~/gl-e00/m06-l02./verify[ 142.810412] MOD_CHECK ok=0 dirty=-8(ENOEXEC) bad_crc=-8(ENOEXEC) non_gpl=-2(ENOENT)learner@ksa:~/gl-e00/m06-l02learner@ksa:~/gl-e00/m06-l02strace -e trace=write,exit_group ./verifywrite(1, "[ 142.810412] MOD_CHECK ok=0 di"..., 87) = 87exit_group(0) = ?+++ exited with 0 +++Makefile KDIR Defaults and insmod-vs-modprobe Confusion
Adopt two permanent rules for every driver Makefile you write in GL-E04..GL-E07. First, fail fast with $(error KDIR is not set) if KDIR is missing or does not contain include/config/kernel.release — never default KDIR ?= /lib/modules/$(shell uname -r)/build in an embedded repository!
Second, install modules via make -C $(KDIR) M=$(PWD) INSTALL_MOD_PATH=/srv/nfs/rootfs modules_install so Kbuild places .ko files under /lib/modules/<release>/updates/ and runs depmod automatically.
Silent -dirty Suffix Added by Uncommitted DTS Edit in KDIR:
- Symptom: You tweak
1line in an.dtsfile insideKDIR, copy the new.dtb, then build a new.ko— andinsmodrejects the.kowithversion magic '6.12.0-dirty ...' should be '6.12.0 ...'! - Root Cause: With
CONFIG_LOCALVERSION_AUTO=y,scripts/setlocalversioninspectsgit statusinKDIR; modifying any tracked file appends-dirtytoinclude/config/kernel.releaseused by.kobuilds while the runningzImageon the board was built when the tree was clean! - Fix: Either commit changes cleanly, disable
CONFIG_LOCALVERSION_AUTO(# CONFIG_LOCALVERSION_AUTO is not set) during iterative bring-up, or redeployzImagealongside modules.
Using raw insmod on a Driver Depending on Industrial I/O or Regmap Modules:
- Symptom:
insmod ./ap3216c.kofails withUnknown symbol __iio_device_register (err -2)even thoughindustrialio.koexists under/lib/modules/. - Root Cause:
insmodloads only the single file path passed to it and never readsmodules.depto load prerequisite modules first. - Fix: Run
depmod -aonce after installing.kofiles and load modules by name withmodprobe ap3216c(which loadsindustrialio.koautomatically).
Guided Practice
Extend verify.c to extract and parse the comma-separated depends= field from a .modinfo blob (e.g., "depends=industrialio,regmap-i2c\0") and print the exact ordered list of prerequisite modules that modprobe must load before finit_module().
Test your parser on both an empty "depends=\0" module (0 prerequisites) and a 2-dependency sensor module.
Independent Practice
Write a 12-line out-of-tree Kbuild Makefile snippet guarded by ifeq ($(KERNELRELEASE),) that aborts with $(error Set KDIR to configured ARMv7 Linux 6.12 tree) whenever KDIR is unset, and prints the target kernel's $(shell cat $(KDIR)/include/config/kernel.release) before invoking $(MAKE) -C $(KDIR) M=$(CURDIR) ARCH=arm.
Verify with make -n on a dummy directory containing include/config/kernel.release that missing KDIR fails cleanly instead of touching /lib/modules/$(uname -r).
Verification Checks
? check 1 · insmod ./led_drv.ko fails on your i.MX6ULL board with insmod: ERROR: could not insert module ./led_drv.ko: Invalid module format (ENOEXEC). Where is the exact mismatched field printed, and what is the most common cause?
- [ ]
/var/log/apt/history.logprints a missing/lib/ld-linux-armhf.so.3PT_INTERPerror. - [ ]
Invalid module formatmeans/dev/led0character device node was not created withmknodyet. - [ ]
ENOEXECmeanschmod +x led_drv.kowas omitted on theNFSserver. - [x]
dmesg | tailprints the exactversion magic '...' should be '...'mismatch, typically caused by building against the wrongKDIRor a-dirtyUTS_RELEASEskew.
Answer: dmesg | tail prints the exact version magic '...' should be '...' mismatch, typically caused by building against the wrong KDIR or a -dirty UTS_RELEASE skew.
Why: Kernel modules are read via file descriptor (open + finit_module), never execve()d, so +x permissions and PT_INTERP are irrelevant; dmesg logs the exact vermagic or CRC rejection.
Common misconception: Running chmod +x on .ko files or guessing blindly without checking dmesg | tail.
? check 2 · Why does omitting MODULE_LICENSE("GPL") cause insmod to fail with Unknown symbol gpiod_get (err -2) (-ENOENT) in a Linux kernel 6.12 GPIO driver?
- [ ] Non-GPL modules are compiled as
64-bitEM_X86_64objects automatically. - [ ]
gpiod_getlives in user-spacelibgpiod.sorather thanvmlinux. - [x]
gpiod_getis exported viaEXPORT_SYMBOL_GPL(), whichresolve_symbol()hides from modules lacking aGPL-compatible.modinfolicense=tag. - [ ] The C11 compiler refuses to emit object code unless
MODULE_LICENSEappears on line 1.
Answer: gpiod_get is exported via EXPORT_SYMBOL_GPL(), which resolve_symbol() hides from modules lacking a GPL-compatible .modinfo license= tag.
Why: Core modern driver subsystems (gpiod, regmap, platform_driver, devm_*) use EXPORT_SYMBOL_GPL; dmesg explicitly logs module_name: module license 'unspecified' taints kernel and Unknown symbol ... (err -2).
Common misconception: Assuming Unknown symbol always means a Kconfig option is disabled, overlooking missing MODULE_LICENSE("GPL").
? check 3 · Retrieval check from Lesson 6.1: Can /sbin/modinfo ./drv.ko on your x86_64 Linux workstation inspect an ARMv7-A (EM_ARM) kernel module?
- [ ] No —
.modinfois encrypted with the target board's OTP fuse key. - [x] Yes —
modinfosimply parses the staticELF.modinfoNUL-delimited byte section without executingARMinstructions. - [ ] No —
modinfoloads the.kointo the hostx86_64kernel viafinit_module()to query it. - [ ] Only if
qemu-arm-staticis registered inbinfmt_misc.
Answer: Yes — modinfo simply parses the static ELF .modinfo NUL-delimited byte section without executing ARM instructions.
Why: Just like readelf, modinfo is a pure file parser that reads .modinfo strings directly on the host — making pre-deployment vermagic checks trivial in CI/Makefiles!
Common misconception: Waiting until a .ko is copied to the board to discover its vermagic does not match uname -r.
Summary
- During
finit_module(),Linux kernelcheck_modinfo()compares.modinfovermagic=<release> SMP preempt mod_unload ARMv7 p2v8againstutsname()->releaseand compile-time kernel tokens. - When
insmodfails with-ENOEXEC(Invalid module format), timestampeddmesg(CONFIG_PRINTK_TIME=y) reveals exactversion magicrelease/flag drift (such as-dirtyor wrong hostKDIR) orCONFIG_MODVERSIONSsymbolCRCdisagreement. - When
insmodfails with-ENOENT(Unknown symbol in module, or unknown parameter), an exported dependency.kois unloaded (resolved viadepmod -a+modprobe), aCONFIG_*subsystem is disabled, orMODULE_LICENSE("GPL")was omitted for anEXPORT_SYMBOL_GPLsymbol. - Out-of-tree driver
Makefilesmust pointKDIRat the exact configured/builtARMv7-ALinux kernel6.12 tree (ARCH=arm CROSS_COMPILE=arm-linux-gnueabihf-), never/lib/modules/$(uname -r)/build.
Step sequence — frame strip: steps_m06_l02
Never let an embedded driver Makefile fall back silently to /lib/modules/$(shell uname -r)/build!
reveals: step1
highlights: step1
Check three lines every time: license: GPL, vermagic: <release> ... ARMv7 p2v8, and depends:.
reveals: step2
highlights: step2
Raw insmod does NOT load 'depends:' modules automatically; modprobe consults modules.dep!
reveals: step3
highlights: step3
Without timestamps, engineers frequently debug a stale dmesg error from 20 minutes ago!
reveals: step4
highlights: step4
What you'll learn
- Verify
ARMzImage(0x016F2818at offset0x24, little-endian) and FlattenedDevice Tree.dtb(0xD00DFEEDat offset0x00, big-endian) binary headers prior toTFTPexport. - Integrate
ELF32armhfPT_INTERProotfs checks and.modinfovermagictoken-boundary audits into a single zero-false-positive pipeline. - Complete the GL-E00 Capstone Studio (
lab_m06_workbench_preflight_capstone) and measureCLOCK_MONOTONIChost preflight throughput.
Closing the Loop Across All Six GL-E00 Workbench Foundations
Over six modules, you have dismantled every host-side failure mode that trips up embedded Linux engineers before they write a single line of ARMv7-A bare-metal or driver code: VM bridges & udev rules (M01), FHS permissions, numeric-owner tarballs & LBA 2 IVT offsets (M02), APT, dual-NIC routing, TFTP & NFS no_root_squash (M03), Linux kernel CodingStyle & LIFO goto C11 hygiene (M04), 115200 8N1 consoles, BOOT_MODE straps, UUU & AAPCS32/VFS triage (M05), and ELF32/vermagic ABI contracts (M06).
Production BSP teams never rely on human memory to check all of these before copying files into /srv/tftp and /srv/nfs/rootfs. Instead, a deploy-check target runs a deterministic preflight gate on the Linux host that inspects the actual binary headers of zImage, .dtb, user-space ELF executables, and .ko modules — rejecting mismatched artifacts in < 1 ms!
Figure 6.3a. Every artifact entering /srv/tftp and /srv/nfs/rootfs is header-verified on the host before the board reboots.
mental model: A host preflight gate works like an avionics pre-takeoff checklist at the hangar door: catching a mismatched fuel grade, unlocked hatch, or missing chart in 2 milliseconds on the ground beats debugging a flameout 30 seconds after liftoff over a 115200 radio.
Where it stops working: Host preflight auditing proves binary ABI, magic headers, PT_INTERP closure, and vermagic alignment 100%, whereas electrical pinmux contention, IRQ latency, and bus waveforms still require live verification on the i.MX6ULL board.
definition (Flattened Device Tree (FDT) Magic (0xD00DFEED)): The mandatory big-endian 32-bit magic number (0xD0, 0x0D, 0xFE, 0xED at byte offset 0x00 of struct fdt_header) emitted by the Device Tree compiler (dtc -I dts -O dtb) that U-Boot's bootz command and Linux kernel early boot inspect before parsing board hardware topology.
- Step 1. Note the endianness contrast: ARM zImage magic is little-endian, whereas FDT .dtb headers are big-endian!
- Step 2. Rejecting x86_64, soft-float, and missing-interpreter binaries eliminates target execve surprises.
- Step 3. Comparing against the staged kernel's release file guarantees zImage and .ko never drift apart.
- Step 4. Your workbench is now ready for bare-metal ARMv7-A (GL-E01) through Linux 6.12 drivers (GL-E04..E07).
Figure 6.3b. Audit zImage (0x016F2818), FDT (0xD00DFEED), ELF32 armhf PT_INTERP, and .ko vermagic before boot!
Binary Magic Signatures Across zImage, FDT .dtb, ELF32, and .ko
Notice a subtle endianness detail when inspecting /srv/tftp boot artifacts in C11 on a little-endian x86_64 host! Inside an ARM 32-bit zImage (arch/arm/boot/compressed/head.S), offset 0x24 stores the little-endian 32-bit magic 0x016F2818 (bytes 18 28 6F 01), followed at 0x28 and 0x2C by compressed start/end offsets. Conversely, the Flattened Device Tree specification (devicetree.org) stores all fdt_header integers in network big-endian byte order: bytes 0..3 are D0 0D FE ED (0xD00DFEED), and bytes 4..7 hold big-endian totalsize!
Reading uint32_t endianness explicitly via byte shifts (((uint32_t)b[0] << 24) | ... for big-endian FDT, (uint32_t)b[0] | ((uint32_t)b[1] << 8) ... for little-endian zImage and ELF32) avoids unaligned-pointer UB (Undefined Behavior in ISO C11) AND works identically regardless of host CPU endianness!
Figure 6.3b. Byte-shift endian readers parse zImage (LE), FDT .dtb (BE), and ELF32 (LE) without alignment Undefined Behavior.
| Staged Artifact | Offset & Endianness | Expected Signature | Failure Caught on Host |
|---|---|---|---|
/srv/tftp/zImage | Offset 0x24, Little-Endian | 0x016F2818 (end > start) | Copying uncompressed Image, uImage, or x86 bzImage to bootz |
/srv/tftp/board.dtb | Offset 0x00, Big-Endian | 0xD00DFEED (totalsize <= file_len) | Copying uncompiled ASCII .dts or truncated TFTP file (Bad Linux ARM zImage/FDT!) |
rootfs/usr/bin/* | Elf32_Ehdr (0x00..0x33), LE | CLASS32, EM_ARM(40), 0x400, valid PT_INTERP | Host gcc (ENOEXEC), gnueabi soft-float, or missing /lib/ld-linux-armhf.so.3 (ENOENT) |
rootfs/lib/modules/**/*.ko | .modinfo NUL strings | license=GPL* & vermagic=<rel> ... ARMv7 p2v8 | KDIR host contamination or -dirty release mismatch (Invalid module format) |
learner@ksa:~/gl-e00/m06-l03$ bat -H 11 -H 19 workbench_preflight_manifest.h File: workbench_preflight_manifest.h /* SPDX-License-Identifier: GPL-2.0 */ #ifndef KSA_WORKBENCH_PREFLIGHT_MANIFEST_H #define KSA_WORKBENCH_PREFLIGHT_MANIFEST_H #include <stdint.h> #define ARM_ZIMAGE_MAGIC_OFFSET 0x24U #define ARM_ZIMAGE_MAGIC_LE 0x016F2818U #define FDT_MAGIC_BE 0xD00DFEEDU static inline uint32_t ksa_read_le32(const uint8_t *p) { return (uint32_t)p[0] | ((uint32_t)p[1] << 8U) | ((uint32_t)p[2] << 16U) | ((uint32_t)p[3] << 24U); } static inline uint32_t ksa_read_be32(const uint8_t *p) { return ((uint32_t)p[0] << 24U) | ((uint32_t)p[1] << 16U) | ((uint32_t)p[2] << 8U) | (uint32_t)p[3]; } #endif /* KSA_WORKBENCH_PREFLIGHT_MANIFEST_H */- Byte-shift little-endian reader safely extracts ARM zImage 0x016F2818 without unaligned pointer casts.
- Big-endian reader decodes FDT 0xD00DFEED magic and totalsize directly from raw .dtb bytes.
dtc(1) / mkimage(1) / file(1)(1) GL-E00 Quick Reference dtc(1) / mkimage(1) / file(1)(1) SYNOPSIS dtc -I dts -O dtb -o imx6ull-board.dtb imx6ull-board.dts dtc -I dtb -O dts imx6ull-board.dtb | head -n 25 # Decompile binary .dtb back to readable DTS! file /srv/tftp/zImage /srv/tftp/imx6ull-board.dtb PRE-DEPLOYMENT CHECKLIST (GL-E00 -> GL-E01..E07) 1. /srv/tftp/zImage 'ARM OpenFirmware FORTH' / 'Linux kernel ARM boot executable zImage (little-endian)' 2. /srv/tftp/*.dtb 'Device Tree Blob version 17' (0xD00DFEED big-endian) 3. /srv/nfs/rootfs UID 0:0 ownership, /etc/exports has (rw,sync,no_root_squash,no_subtree_check) 4. Staged ELFs & .ko EM_ARM(40) + hard-float(0x400) + /lib/ld-linux-armhf.so.3 + matching vermagic Kernel Systems Academy Lesson 6.3 dtc(1) / mkimage(1) / file(1)(1) GL-E00 quick reference · full manual page: man 1 dtc(1) / mkimage(1) / file(1) Running the Unified Boot-Blob, ELF32, and Vermagic Gate in C11
In verify.c, we assemble a mini end-to-end staging check validating ARM zImage (0x016F2818 LE at 0x24) and .dtb (0xD00DFEED BE at 0x00 + totalsize), rejecting an ASCII .dts file accidentally copied as .dtb, and confirming clean alignment across all four deployment gates.
Then step into lab_m06_workbench_preflight_capstone to complete your full C11 pre-deployment auditor across ELF32 armhf, .modinfo vermagic, and zImage/.dtb blobs!
learner@ksa:~/gl-e00/m06-l03$ bat -H 21 -H 25 verify.c File: verify.c #define _POSIX_C_SOURCE 200809L #include <stdbool.h> #include <stdint.h> #include <stdio.h> #include <string.h> static uint32_t rd_le32(const uint8_t *p) { return (uint32_t)p[0] | ((uint32_t)p[1] << 8U) | ((uint32_t)p[2] << 16U) | ((uint32_t)p[3] << 24U); } static uint32_t rd_be32(const uint8_t *p) { return ((uint32_t)p[0] << 24U) | ((uint32_t)p[1] << 16U) | ((uint32_t)p[2] << 8U) | (uint32_t)p[3]; } static bool check_zimage_dtb(const uint8_t *zimg, size_t zlen, const uint8_t *dtb, size_t dlen) { if (zlen < 0x30U || rd_le32(zimg + 0x24U) != 0x016F2818U) return false; if (rd_le32(zimg + 0x2CU) <= rd_le32(zimg + 0x28U)) return false; if (dlen < 40U || rd_be32(dtb) != 0xD00DFEEDU) return false; uint32_t fdt_size = rd_be32(dtb + 4U); return fdt_size >= 40U && fdt_size <= dlen; } int main(void) { uint8_t zimg[64] = {0}; uint8_t dtb_ok[64] = {0}; const uint8_t dts_text[64] = "/dts-v1/;\n/ { compatible = \"ksa,board\"; };\n"; /* Populate LE zImage magic 0x016F2818 @ 0x24, start=0, end=0x400000 */ zimg[0x24] = 0x18U; zimg[0x25] = 0x28U; zimg[0x26] = 0x6FU; zimg[0x27] = 0x01U; zimg[0x2E] = 0x40U; /* Populate BE FDT magic 0xD00DFEED @ 0x00, totalsize = 64 (0x00000040) @ 0x04 */ dtb_ok[0] = 0xD0U; dtb_ok[1] = 0x0DU; dtb_ok[2] = 0xFEU; dtb_ok[3] = 0xEDU; dtb_ok[7] = 64U; bool valid_pair = check_zimage_dtb(zimg, sizeof(zimg), dtb_ok, sizeof(dtb_ok)); bool text_dts_rejected = !check_zimage_dtb(zimg, sizeof(zimg), dts_text, sizeof(dts_text)); if (!valid_pair || !text_dts_rejected) return 1; printf("PREFLIGHT_BLOBS zimage_magic=0x%08X fdt_magic=0x%08X valid_pair=%d dts_text_rejected=%d\n", rd_le32(zimg + 0x24U), rd_be32(dtb_ok), valid_pair ? 1 : 0, text_dts_rejected ? 1 : 0); return 0; }- Verifies little-endian ARM zImage magic 0x016F2818 at 0x24 and non-empty compressed payload span.
- Verifies big-endian FDT magic 0xD00DFEED and ensures totalsize fits inside the downloaded file.
Confirming Little-Endian zImage and Big-Endian FDT Validation
Notice how check_zimage_dtb() rejects dts_text instantaneously because ASCII "/dts" (0x2F647473) != 0xD00DFEED, AND checks fdt_size <= dlen so a half-written or truncated TFTP .dtb file never reaches bootz.
Combined with ELF32 armhf PT_INTERP and .ko vermagic checks in the Capstone Lab, your host build script can validate an entire embedded release directory in microseconds.
learner@ksa:~/gl-e00/m06-l03gcc -std=c11 -Wall -Wextra -Werror verify.c -o verifylearner@ksa:~/gl-e00/m06-l03./verifyPREFLIGHT_BLOBS zimage_magic=0x016F2818 fdt_magic=0xD00DFEED valid_pair=1 dts_text_rejected=1learner@ksa:~/gl-e00/m06-l03learner@ksa:~/gl-e00/m06-l03strace -e trace=write,exit_group ./verifywrite(1, "PREFLIGHT_BLOBS zimage_magic=0x0"..., 94) = 94exit_group(0) = ?+++ exited with 0 +++Common Deployment Mismatches Between bootz, bootm, and FDT
With GL-E00 complete, you own a repeatable, first-principles Linux embedded engineering workbench: isolated dual-NIC TFTP/NFS networking, udev-stabilized USB/serial tools, Linux kernel CodingStyle C11 discipline, 115200 8N1 + UUU bring-up fluency, and automated ELF32/vermagic/FDT preflight gates.
Carry this preflight mindset straight into GL-E01 (imx6ull-baremetal-core), where you will write ARMv7-A startup assembly, IVT/DCD headers, and bare-metal drivers from reset vector 0x00000000.
Passing zImage to U-Boot bootm Instead of bootz (or Vice Versa):
- Symptom:
U-BootprintsWrong Image Format for bootm command / ERROR: can't get kernel image!right aftertftp 80800000 zImagesucceeds. - Root Cause:
bootmexpects a legacy64-byteuImageheader (0x27051956magic frommkimage) orFITimage, whereasbootzboots a rawARMzImage(0x016F2818at0x24) directly! - Fix: Always pair
ARM32-bitzImagewithbootz 0x80800000 - 0x83000000(note the-placeholder when no separateinitramfsis used).
Decompiling or Editing the Wrong .dtb File in arch/arm/boot/dts/nxp/imx/:
- Symptom: You modify a
Device Tree.dtsfile and runmake dtbs, yet/proc/device-tree/on the booted board shows zero changes! - Root Cause:
Linux kernel6.12 organizesARMvendor DTs underarch/arm/boot/dts/nxp/imx/; copying from a stale top-level build directory or editing an.dtsinot#included by your board's.dtsdeploys the old blob. - Fix: Run
dtc -I dtb -O dts /srv/tftp/board.dtb | grep -A4 your_nodeon the staged/srv/tftpfile before rebooting the board!
Guided Practice
Extend check_zimage_dtb() in verify.c to also reject legacy uImage headers (0x27051956 big-endian at offset 0x00) with a specific diagnostic advising the operator to switch from bootz to bootm or deploy arch/arm/boot/zImage.
Test all three cases (zImage, uImage, and truncated .dtb where fdt_size = 4096 on a 512-byte file) and confirm zero false positives.
Independent Practice
Open labs/lab_m06_workbench_preflight_capstone/ and examine starter/core.c. Repair all three intentional preflight defects: (1) reject soft-float 0x200 so EF_ARM_ABI_FLOAT_HARD (0x400) is strictly required, (2) verify PT_INTERP matches rootfs_interp (no silent pass when rootfs_interp is missing!), and (3) enforce exact token-boundary vermagic release matching (vm[rlen] == ' ') so -dirty modules are caught.
Run sh check.sh (5/5 TAP version 13 checks passing) and ./files/lab_cli --bench to complete the GL-E00 Workbench Preflight Capstone!
Verification Checks
? check 1 · Why must a C11 preflight tool read ARM zImage magic (0x016F2818 at 0x24) as little-endian while reading .dtb magic (0xD00DFEED at 0x00) as big-endian?
- [ ]
U-Bootswitches theCortex-A7CPU into big-endianBE8mode before parsing.dtb. - [ ]
zImageis big-endian onx86_64hosts and little-endian onARMhosts. - [x]
32-bitARMv7-AzImageheaders are little-endian, whereas the FlattenedDevice Tree(FDT) specification mandates network big-endian fields instruct fdt_header. - [ ]
dtcencrypts.dtbfiles by reversing byte order on odd-numbered kilobytes.
Answer: 32-bit ARMv7-A zImage headers are little-endian, whereas the Flattened Device Tree (FDT) specification mandates network big-endian fields in struct fdt_header.
Why: File format endianness is an intrinsic property of the binary specification: ARM Linux zImage/ELF32 are little-endian; FDT .dtb headers/cells are always big-endian.
Common misconception: Casting *(uint32_t *)dtb_buf == 0xD00DFEED directly on a little-endian x86_64 host (which sees 0xEDFE0DD0!).
? check 2 · In bootz 0x80800000 - 0x83000000, what does the middle hyphen (-) represent to U-Boot?
- [ ] Skip loading
Device Treeand use legacy board-file ATAGs. - [x] No separate
initrd/initramfsRAM-disk address is provided, soU-Bootpasses0x83000000(the third argument) directly inr2as the physicalDevice Treeblob address. - [ ] Subtract
0x83000000from0x80800000to compute kernel image size. - [ ] Boot the kernel in read-only single-user maintenance mode.
Answer: No separate initrd/initramfs RAM-disk address is provided, so U-Boot passes 0x83000000 (the third argument) directly in r2 as the physical Device Tree blob address.
Why: bootz <kernel_addr> [<initrd_addr>[:<size>] | -] [<fdt_addr>] uses - to omit initrd when fdt_addr is supplied.
Common misconception: Omitting the - (bootz 0x80800000 0x83000000), which makes U-Boot mistake your .dtb for a corrupted initrd!
? check 3 · Retrieval check from Lesson 6.2: Why must a preflight vermagic checker verify vm[strlen(expected_rel)] == ' ' in addition to strncmp(vm, expected_rel, strlen(expected_rel)) == 0?
- [x] Without checking the trailing space delimiter,
6.12.0-ksa-dirtyfalsely matches prefix6.12.0-ksaon the host and then failsfinit_module()with-ENOEXECon the board! - [ ] ISO C11
strncmpcrashes if both strings do not contain an ASCII space. - [ ]
Linux kernelvermagicstrings placeARMv7before the release number. - [ ]
modinfostrips-dirtyautomatically unless a space check is added.
Answer: Without checking the trailing space delimiter, 6.12.0-ksa-dirty falsely matches prefix 6.12.0-ksa on the host and then fails finit_module() with -ENOEXEC on the board!
Why: Prefix-only strncmp("6.12.0-ksa-dirty ...", "6.12.0-ksa", 10) returns 0, letting -dirty skew slip right past an incomplete preflight script!
Common misconception: Using strncmp with strlen(prefix) when testing exact token equality.
1. Motivation
Deploying unverified cross-build outputs into /srv/tftp and /srv/nfs/rootfs turns single-line build mistakes — an uncompiled .dts, a soft-float 0x200 tool, a missing /lib/ld-linux-armhf.so.3 symlink, or a -dirty .ko — into bewildering target boot failures.
In this GL-E00 Capstone Project, you build a complete C11 binary preflight gate that validates every boot, user-space, and kernel-module artifact in microseconds before target deployment.
2. Learning objectives
- Verify
ARMzImage(0x016F2818LE) and FlattenedDevice Tree.dtb(0xD00DFEEDBE +totalsize) headers safely inpreflight_boot_blobs(). - Audit
52-byteElf32_Ehdr+Elf32_Phdrbounds,EM_ARM (40),EF_ARM_ABI_FLOAT_HARD (0x400), andPT_INTERProotfs resolution inpreflight_elf32_armhf(). - Enforce
GPLmodule licensing,ARMv7 p2v8architecture flags, and exact token-boundedUTS_RELEASEmatching inpreflight_ko_modinfo().
3. Environment requirements
All automated verification steps run in unprivileged user space on a POSIX Linux host using gcc -std=c11 -Wall -Wextra -Werror and clock_gettime(CLOCK_MONOTONIC). Recorded transcripts in captures.json were generated on x86_64 running kernel 7.0.0-42-generic and prove protocol, state-machine, and memory invariants only. Physical bus timing, DMA cache coherency, and board peripheral behavior require target validation on Linux kernel 6.12 LTS (ARMv7-A Cortex-A7).
4. Required software and hardware
- Host workstation:
gcc(-std=c11 -Wall -Wextra -Werror), GNUmake,ar(binutils), and POSIX/bin/sh. - Target environment (optional hardware step, Section 13): Complete
GL-E00Linux host/srv/tftp+/srv/nfs/rootfsbench servingi.MX6ULLARMv7-AU-Boot2025.x andLinux kernel6.12.
5. Complete executable commands
learner@ksa:~/gl-e00/m06-l03$ bat script.sh File: script.sh make -B -C files ./files/lab_cli ./files/lab_cli --bench sh check.sh6. Annotated source code
files/core.c enforces the production invariants that starter/core.c breaks:
learner@ksa:~/gl-e00/m06-l03$ bat example.c File: example.c eflags = rd_le32(elf + 0x24U); if ((eflags & 0x00000400U) == 0U || (eflags & 0x00000200U) != 0U) return PREFLIGHT_ERR_FLOAT_ABI; /* ... */ if (!vm || strncmp(vm, expected_release, rlen) != 0 || vm[rlen] != ' ') return PREFLIGHT_ERR_VERMAGIC_RELEASE;starter/core.c masks eflags with 0x600 (accepting soft-float 0x200 binaries!), ignores rootfs_available_interp when checking PT_INTERP, and omits vm[rlen] != ' ' (allowing 6.12.0-ksa-dirty modules to slip past 6.12.0-ksa!).
7. Expected output
Passing files/ run (sh check.sh, exit code 0):
learner@ksa:~/gl-e00/m06-l03$ bat listing.txt File: listing.txt TAP version 13 1..5 ok 1 - builds libcore.a and lab_cli cleanly with -std=c11 -Wall -Wextra -Werror ok 2 - archives core.o into libcore.a and links independent TAP verifier ok 3 - validates little-endian ARM zImage (0x016F2818 @ 0x24) and big-endian FDT .dtb (0xD00DFEED @ 0x00) ok 4 - rejects x86_64 ELFs, soft-float 0x200 binaries, and missing rootfs PT_INTERP dynamic linkers ok 5 - enforces GPL license, ARMv7 p2v8 tokens, and exact token-bounded vermagic release (rejecting -dirty) # pass 5/5CLI verification output (./files/lab_cli):
learner@ksa:~/gl-e00/m06-l03$ bat listing.txt File: listing.txt CAPSTONE_BLOBS status=0 CAPSTONE_ELF armhf_ok=0 softfloat_err=4 missing_interp_err=5 CAPSTONE_KO clean_ok=0 dirty_err=6Defective starter/ run (exit code 1): emits FAIL: diagnostics on the broken contract assertions.
8. Explanation of observed behavior
When all three checks are tightened, preflight_elf32_armhf() guarantees VFP hard-float register ABI compatibility and /lib/ld-linux-armhf.so.3 presence, preflight_ko_modinfo() blocks -dirty and non-ARMv7/p2v8 modules prior to finit_module(), and preflight_boot_blobs() guards bootz against malformed kernel/DTB files.
9. Experiment variations
- Near transfer: Extend
preflight_elf32_armhf()to accept static binaries (ET_EXECwith zeroPT_INTERPheaders when-staticis explicitly allowed via flag). - Far transfer: Walk
/srv/nfs/rootfsrecursively with POSIXnftw()to audit every executable and.kofile in a single host CLI command.
10. Performance measurements
Recorded host benchmark (./files/lab_cli --bench, CLOCK_MONOTONIC, warmup=5, N=40 batches):
learner@ksa:~/gl-e00/m06-l03$ bat listing.txt File: listing.txt BENCH lab_m06_workbench_preflight_capstone clock=CLOCK_MONOTONIC batches=40x500 p50_ns=37127 p95_ns=38508 p99_ns=41995 sink=0./files/lab_cli --bench records CLOCK_MONOTONIC host execution time across 40 x 500 complete 3-stage preflight sweeps (zImage/.dtb + ELF32 + .modinfo), demonstrating sub-millisecond CI/Makefile overhead on the host workstation.
11. Troubleshooting
| Symptom | Root cause | Fix |
|---|---|---|
Check 4 fails on e_sf (soft-float not rejected) | 0x05000200 & 0x600 is non-zero, letting EF_ARM_ABI_FLOAT_SOFT pass. | Require (eflags & 0x400U) != 0U && (eflags & 0x200U) == 0U. |
Check 4 fails when rootfs_available_interp is NULL | PT_INTERP string was never compared against rootfs_available_interp. | Return PREFLIGHT_ERR_MISSING_INTERP if !rootfs_available_interp or strcmp != 0. |
Check 5 fails on ko_dirty | strncmp(vm, "6.12.0-ksa", 10) returns 0 on "6.12.0-ksa-dirty ...". | Require vm[rlen] == ' ' immediately after the expected release string. |
12. Guided questions
- Why does
preflight_elf32_armhf()verifymemchr(elf + ioff, '\0', isz) != NULLBEFORE callingstrcmp((const char *)(elf + ioff), ...)?
- *Hint 1:* What if a corrupted or fuzz-crafted
ELFbinary hasPT_INTERPp_filesz = 24filled with non-zero bytes up to the end ofelf? - *Hint 2:*
strcmpscans until it hits'\0';memchr(..., '\0', isz)proves a NUL terminator exists inside the bounds-checked[ioff, ioff + isz)slice first!
- Why do
rd_le32()andrd_be32()assembleuint32_tvalues fromuint8_tbyte shifts instead of casting*(const uint32_t *)(buf + offset)?
- *Hint 1:* What does ISO C11 say when
buf + offsetis not4-byte aligned or aliases acharbuffer? - *Hint 2:* Direct
uint32_t *casts risk alignment faults/Undefined Behavior and silently depend on host CPU endianness, whereas byte shifts are 100% portable C11.
13. Independent challenges
Extend preflight_ko_modinfo() to parse depends=<mod1>,<mod2> from .modinfo and verify against a caller-supplied array of staged .ko module names that every prerequisite module is present under /srv/nfs/rootfs/lib/modules/<release>/ before depmod -a runs.
14. Solutions and explanations
The reference files/core.c combines endian-explicit zImage/FDT header checks, bounds-safe ELF32 armhf (0x400) + PT_INTERP verification, and token-bounded .modinfo vermagic/GPL validation to pass 5/5 TAP checks cleanly.
Run locally in your terminal and check off each verification milestone.
Not started
Summary
- A complete embedded workbench preflight gate validates boot blobs (
ARMzImagemagic0x016F2818at0x24and big-endianDevice Tree.dtbmagic0xD00DFEEDat0x00), user-spaceELF32armhfbinaries, and.kovermagicbefore target deployment. - Every staged target executable must satisfy
ELFCLASS32,EM_ARM (40),EF_ARM_ABI_FLOAT_HARD (0x400), and physical existence of itsPT_INTERPloader andDT_NEEDEDlibraries inside/srv/nfs/rootfs. - Every staged
.komodule under/srv/nfs/rootfs/lib/modules/<release>/must carrylicense=GPL*and avermagicmatching<release>on an exact token boundary plusARMv7 p2v8. - Executing deterministic binary preflight checks on the Linux host turns
30-second reboot-and-panic mysteries into sub-millisecond build-time diagnostics with zero target flash wear.
Step sequence — frame strip: steps_m06_l03
Note the endianness contrast: ARM zImage magic is little-endian, whereas FDT .dtb headers are big-endian!
reveals: step1
highlights: step1
Rejecting x86_64, soft-float, and missing-interpreter binaries eliminates target execve surprises.
reveals: step2
highlights: step2
Comparing against the staged kernel's release file guarantees zImage and .ko never drift apart.
reveals: step3
highlights: step3
Your workbench is now ready for bare-metal ARMv7-A (GL-E01) through Linux 6.12 drivers (GL-E04..E07).
reveals: step4
highlights: step4