learner@ksa:~/gl-e00$

>_ Kernel Systems Academy

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.

6 modules18 lessons6 labsLinux 6.12 · C11
  1. m01/ Host Virtualization Bridges, PTY Streams & Shell Pipelines
  2. m02/ Filesystem Hierarchy, Permissions, Archives & Partition Guards
  3. m03/ APT Package Graphs, Dual-NIC Routing & TFTP/NFS Boot Bench
  4. m04/ Linux Kernel & Embedded C11 Coding Style & Defensive Hygiene
  5. m05/ Serial Consoles, Boot Straps, UUU Flashing & Bring-Up Triage
  6. m06/ Cross-ABI ELF Auditing, Module Vermagic & Workbench Capstone
GL-E00 · Linux Host Workbench, POSIX Shell, Network Boot & Embedded C Style1/561

m01/

>_ Kernel Systems Academy

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.

  1. 1.1 Linux Host & Hypervisor Bridges, USB Passthrough & udev Rules
  2. 1.2 Pseudoterminals (PTY), File-Descriptor Redirection & sudo PATH Isolation
  3. 1.3 Modal Text Editing, Tree Search Pipelines & Workbench Audit Studio

lab → Linux Workbench udev, dup2 Redirection & PATH Security Auditor

GL-E00 · Linux Host Workbench, POSIX Shell, Network Boot & Embedded C Style2/561

GL-E00 · 1.1 (m01-l01)

>_ Kernel Systems Academy

Linux Host & Hypervisor Bridges, USB Passthrough & udev Rules

free preview20 min

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).
GL-E00 · Linux Host Workbench, POSIX Shell, Network Boot & Embedded C Style3/561

GL-E00 · 1.1 (m01-l01)

>_ Kernel Systems Academy

Why Embedded Benches Break Inside Default Virtual Machine Settings

  • Desktop software engineers rarely notice whether their Linux virtual machine sits behind hypervisor Network…
GL-E00 · Linux Host Workbench, POSIX Shell, Network Boot & Embedded C Style4/561

GL-E00 · 1.1 (m01-l01)

>_ Kernel Systems Academy

Why Embedded Benches Break Inside Default Virtual Machine Settings

  • Switching the single virtual adapter to automatic Bridged mode creates a subtle trap on laptops.
GL-E00 · Linux Host Workbench, POSIX Shell, Network Boot & Embedded C Style5/561

GL-E00 · 1.1 (m01-l01)

>_ Kernel Systems Academy

Why Embedded Benches Break Inside Default Virtual Machine Settings

fig_m01_l01_a.svg

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.

GL-E00 · Linux Host Workbench, POSIX Shell, Network Boot & Embedded C Style6/561

GL-E00 · 1.1 (m01-l01)

>_ Kernel Systems Academy

Mental model

note: 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.

GL-E00 · Linux Host Workbench, POSIX Shell, Network Boot & Embedded C Style7/561

GL-E00 · 1.1 (m01-l01)

>_ Kernel Systems Academy

Extended Page Tables (EPT) and Netlink uevent

definition: 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.

GL-E00 · Linux Host Workbench, POSIX Shell, Network Boot & Embedded C Style8/561

GL-E00 · 1.1 (m01-l01)

>_ Kernel Systems Academy

Why Embedded Benches Break Inside Default Virtual Machine Settings

Verify hardware virtualization flags and assign two distinct virtual NICs: NAT for internet and a wired-only Bridge for the target board.

Separate NAT WAN from wired L2 bridges and bind USB permissions via udev == matchers.

GL-E00 · Linux Host Workbench, POSIX Shell, Network Boot & Embedded C Style9/561

GL-E00 · 1.1 (m01-l01)

>_ Kernel Systems Academy

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…
GL-E00 · Linux Host Workbench, POSIX Shell, Network Boot & Embedded C Style10/561

GL-E00 · 1.1 (m01-l01)

>_ Kernel Systems Academy

Inside KVM/VMware L2 Bridging and udev Operator Semantics

  • At the I/O boundary, udev rule syntax is unforgiving because C-like operators carry distinct state-machin…
GL-E00 · Linux Host Workbench, POSIX Shell, Network Boot & Embedded C Style11/561

GL-E00 · 1.1 (m01-l01)

>_ Kernel Systems Academy

Inside KVM/VMware L2 Bridging and udev Operator Semantics

fig_m01_l01_b.svg

Figure 1.1b: Exact operator distinction (== predicate vs = / += assignment) prevents silent wildcard matches and world-writable 0666 hazards.

GL-E00 · Linux Host Workbench, POSIX Shell, Network Boot & Embedded C Style12/561

GL-E00 · 1.1 (m01-l01)

>_ Kernel Systems Academy

99-embedded-bench.rules

learner@ksa: ~/gl-e00/m01-l01
learner@ksa:~/gl-e00/m01-l01$ bat 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"
GL-E00 · Linux Host Workbench, POSIX Shell, Network Boot & Embedded C Style13/561

GL-E00 · 1.1 (m01-l01)

>_ Kernel Systems Academy

udev

udev(7) at a glance — GL-E00
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"). Kernel Systems Academy                     m01-l01                     udev(7) GL-E00 quick reference · full manual page: man 7 udev 
GL-E00 · Linux Host Workbench, POSIX Shell, Network Boot & Embedded C Style14/561

GL-E00 · 1.1 (m01-l01)

>_ Kernel Systems Academy

Auditing VM Bridge Selection and udev Rules in Host C11

  • Before deploying workstation onboarding scripts across an engineering team, we can validate both hypervisor…
GL-E00 · Linux Host Workbench, POSIX Shell, Network Boot & Embedded C Style15/561

GL-E00 · 1.1 (m01-l01)

>_ Kernel Systems Academy

Auditing VM Bridge Selection and udev Rules in Host C11

  • Pay close attention to how audit_udev_line() distinguishes == match predicates from = assignments and…
GL-E00 · Linux Host Workbench, POSIX Shell, Network Boot & Embedded C Style16/561

GL-E00 · 1.1 (m01-l01)

>_ Kernel Systems Academy

verify.c

learner@ksa: ~/gl-e00/m01-l01
learner@ksa:~/gl-e00/m01-l01$ bat 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) {
GL-E00 · Linux Host Workbench, POSIX Shell, Network Boot & Embedded C Style17/561

GL-E00 · 1.1 (m01-l01)

>_ Kernel Systems Academy

Verifying Rule Diagnostics and System Call Output

  • Compile verify.c under strict -std=c11 -Wall -Wextra -Werror and inspect both stdout and the strace s…
GL-E00 · Linux Host Workbench, POSIX Shell, Network Boot & Embedded C Style18/561

GL-E00 · 1.1 (m01-l01)

>_ Kernel Systems Academy

Verifying Rule Diagnostics and System Call Output

learner@ksa: ~/gl-e00/m01-l01
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-l01
GL-E00 · Linux Host Workbench, POSIX Shell, Network Boot & Embedded C Style19/561

GL-E00 · 1.1 (m01-l01)

>_ Kernel Systems Academy

Verifying Rule Diagnostics and System Call Output

strace — learner@ksa: ~/gl-e00/m01-l01
learner@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 +++
GL-E00 · Linux Host Workbench, POSIX Shell, Network Boot & Embedded C Style20/561

GL-E00 · 1.1 (m01-l01)

>_ Kernel Systems Academy

Common Virtualization & USB Hotplug Failure Modes

  • A reliable embedded Linux workstation separates network planes and eliminates manual root interventions on…
GL-E00 · Linux Host Workbench, POSIX Shell, Network Boot & Embedded C Style21/561

GL-E00 · 1.1 (m01-l01)

>_ Kernel Systems Academy

Warning

warning: - Symptom: udevadm test reports zero matching rules even though both ATTRS{idVendor} and an interface-level ATTRS{bInterfaceNumber} exist in udevadm info -a. - Root Cause: systemd-udevd requires all ATTRS{...} predicates within a single rule to match on the same parent sysfs device node rather than cherry-picking attributes from two different ancestor levels. - Fix: Match SUBSYSTEM=="tty" at the leaf node and keep ATTRS{idVendor} plus ATTRS{idProduct} on the single usb-serial or usb_device parent, or use ENV{ID_VENDOR_ID}=="1a86" populated by usb_id.

GL-E00 · Linux Host Workbench, POSIX Shell, Network Boot & Embedded C Style22/561

GL-E00 · 1.1 (m01-l01)

>_ Kernel Systems Academy

Warning

warning: - Symptom: After running sudo minicom -s or sudo uuu, subsequent non-root runs fail to save configuration files or build artifacts in $HOME with Permission denied. - Root Cause: Invoking interactive tools under sudo preserves $HOME on many distributions while running as UID 0, creating root-owned dotfiles (~/.minirc.dfl) and masking missing dialout/plugdev group membership. - Fix: Fix /etc/udev/rules.d/ permissions to 0660 with GROUP="dialout" or GROUP="plugdev", add your user via sudo usermod -aG dialout,plugdev $USER, re-login so id -Gn shows the new groups, and chown any root-owned $HOME files back.

GL-E00 · Linux Host Workbench, POSIX Shell, Network Boot & Embedded C Style23/561

GL-E00 · 1.1 (m01-l01)

>_ Kernel Systems Academy

Guided Practice

  • Extend verify.c to parse an optional SYMLINK+="ttyBENCH0" token and reject rules that use `SYMLINK="tty…
GL-E00 · Linux Host Workbench, POSIX Shell, Network Boot & Embedded C Style24/561

GL-E00 · 1.1 (m01-l01)

>_ Kernel Systems Academy

Independent Practice

  • Write a two-rule udev snippet and matching C11 unit test for a dual-channel FT2232H (0403:6010) JTAG +…
GL-E00 · Linux Host Workbench, POSIX Shell, Network Boot & Embedded C Style25/561

GL-E00 · 1.1 (m01-l01)

>_ Kernel Systems Academy

Quick check

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?

Select an option or press R to reveal.

GL-E00 · Linux Host Workbench, POSIX Shell, Network Boot & Embedded C Style26/561

GL-E00 · 1.1 (m01-l01)

>_ Kernel Systems Academy

Quick check

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?

Select an option or press R to reveal.

GL-E00 · Linux Host Workbench, POSIX Shell, Network Boot & Embedded C Style27/561

GL-E00 · 1.1 (m01-l01)

>_ Kernel Systems Academy

Quick check

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?

Select an option or press R to reveal.

GL-E00 · Linux Host Workbench, POSIX Shell, Network Boot & Embedded C Style28/561

GL-E00 · 1.1 (m01-l01)

>_ Kernel Systems Academy

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.
GL-E00 · Linux Host Workbench, POSIX Shell, Network Boot & Embedded C Style29/561

GL-E00 · 1.1 (m01-l01)

>_ Kernel Systems Academy

Key takeaways

  • 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.
GL-E00 · Linux Host Workbench, POSIX Shell, Network Boot & Embedded C Style30/561

GL-E00 · 1.2 (m01-l02)

>_ Kernel Systems Academy

Pseudoterminals (PTY), File-Descriptor Redirection & sudo PATH Isolation

free preview20 min

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.
GL-E00 · Linux Host Workbench, POSIX Shell, Network Boot & Embedded C Style31/561

GL-E00 · 1.2 (m01-l02)

>_ Kernel Systems Academy

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…
GL-E00 · Linux Host Workbench, POSIX Shell, Network Boot & Embedded C Style32/561

GL-E00 · 1.2 (m01-l02)

>_ Kernel Systems Academy

Where Bytes and Signals Actually Go Inside a Terminal Window

  • Pressing Ctrl-C sends byte 0x03; n_tty intercepts it under ISIG mode and delivers SIGINT to the l…
GL-E00 · Linux Host Workbench, POSIX Shell, Network Boot & Embedded C Style33/561

GL-E00 · 1.2 (m01-l02)

>_ Kernel Systems Academy

Where Bytes and Signals Actually Go Inside a Terminal Window

  • Two daily build failures stem directly from how shells wire descriptors and environments around child proce…
GL-E00 · Linux Host Workbench, POSIX Shell, Network Boot & Embedded C Style34/561

GL-E00 · 1.2 (m01-l02)

>_ Kernel Systems Academy

Where Bytes and Signals Actually Go Inside a Terminal Window

fig_m01_l02_a.svg

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.

GL-E00 · Linux Host Workbench, POSIX Shell, Network Boot & Embedded C Style35/561

GL-E00 · 1.2 (m01-l02)

>_ Kernel Systems Academy

Mental model

note: 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.

GL-E00 · Linux Host Workbench, POSIX Shell, Network Boot & Embedded C Style36/561

GL-E00 · 1.2 (m01-l02)

>_ Kernel Systems Academy

Open File Description Sharing (dup2) and sudo secure_path

definition: 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.

GL-E00 · Linux Host Workbench, POSIX Shell, Network Boot & Embedded C Style37/561

GL-E00 · 1.2 (m01-l02)

>_ Kernel Systems Academy

Where Bytes and Signals Actually Go Inside a Terminal Window

Enable set -euo pipefail at the top of build and deployment scripts so downstream loggers like tee cannot mask compiler failures.

Order >log before 2>&1, set pipefail on build pipes, and never compile under sudo.

GL-E00 · Linux Host Workbench, POSIX Shell, Network Boot & Embedded C Style38/561

GL-E00 · 1.2 (m01-l02)

>_ Kernel Systems Academy

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,…
GL-E00 · Linux Host Workbench, POSIX Shell, Network Boot & Embedded C Style39/561

GL-E00 · 1.2 (m01-l02)

>_ Kernel Systems Academy

Kernel File Table Mechanics, Pipeline Exit Codes & sudoers Scrubbing

  • When chaining processes with | (make -j8 2>&1 | tee build.log), the shell creates an anonymous `pipe2()…
GL-E00 · Linux Host Workbench, POSIX Shell, Network Boot & Embedded C Style40/561

GL-E00 · 1.2 (m01-l02)

>_ Kernel Systems Academy

Kernel File Table Mechanics, Pipeline Exit Codes & sudoers Scrubbing

  • Finally, /etc/sudoers compiles Defaults secure_path="/usr/local/sbin:...:/bin".
GL-E00 · Linux Host Workbench, POSIX Shell, Network Boot & Embedded C Style41/561

GL-E00 · 1.2 (m01-l02)

>_ Kernel Systems Academy

Kernel File Table Mechanics, Pipeline Exit Codes & sudoers Scrubbing

fig_m01_l02_b.svg

Figure 1.2b: Sharing one struct file via dup2(1, 2) serializes f_pos offsets, while pipefail preserves left-hand compiler failures.

GL-E00 · Linux Host Workbench, POSIX Shell, Network Boot & Embedded C Style42/561

GL-E00 · 1.2 (m01-l02)

>_ Kernel Systems Academy

safe_cross_build.sh

learner@ksa: ~/gl-e00/m01-l02
learner@ksa:~/gl-e00/m01-l02#!/usr/bin/env bashset -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 rcmake 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>&1learner@ksa:~/gl-e00/m01-l02
GL-E00 · Linux Host Workbench, POSIX Shell, Network Boot & Embedded C Style43/561

GL-E00 · 1.2 (m01-l02)

>_ Kernel Systems Academy

dup2

dup2(2) at a glance — GL-E00
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 Kernel Systems Academy                     m01-l02                     dup2(2) GL-E00 quick reference · full manual page: man 2 dup2 
GL-E00 · Linux Host Workbench, POSIX Shell, Network Boot & Embedded C Style44/561

GL-E00 · 1.2 (m01-l02)

>_ Kernel Systems Academy

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 I…
GL-E00 · Linux Host Workbench, POSIX Shell, Network Boot & Embedded C Style45/561

GL-E00 · 1.2 (m01-l02)

>_ Kernel Systems Academy

Proving dup2() Redirection Order With Real Kernel Pipes in C11

  • We also test sudo secure_path scrubbing by verifying whether /opt/toolchains/arm/bin survives a reset…
GL-E00 · Linux Host Workbench, POSIX Shell, Network Boot & Embedded C Style46/561

GL-E00 · 1.2 (m01-l02)

>_ Kernel Systems Academy

verify.c

learner@ksa: ~/gl-e00/m01-l02
learner@ksa:~/gl-e00/m01-l02$ bat 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];
GL-E00 · Linux Host Workbench, POSIX Shell, Network Boot & Embedded C Style47/561

GL-E00 · 1.2 (m01-l02)

>_ Kernel Systems Academy

Inspecting Real pipe2() and dup2() Syscalls Under strace

  • Examine the captured shell output and strace trace below.
GL-E00 · Linux Host Workbench, POSIX Shell, Network Boot & Embedded C Style48/561

GL-E00 · 1.2 (m01-l02)

>_ Kernel Systems Academy

Inspecting Real pipe2() and dup2() Syscalls Under strace

learner@ksa: ~/gl-e00/m01-l02
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-l02
GL-E00 · Linux Host Workbench, POSIX Shell, Network Boot & Embedded C Style49/561

GL-E00 · 1.2 (m01-l02)

>_ Kernel Systems Academy

Inspecting Real pipe2() and dup2() Syscalls Under strace

strace — learner@ksa: ~/gl-e00/m01-l02
learner@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)                              = 2
GL-E00 · Linux Host Workbench, POSIX Shell, Network Boot & Embedded C Style50/561

GL-E00 · 1.2 (m01-l02)

>_ Kernel Systems Academy

Subtle Redirection, PTY Signal & sudo Build Traps

  • Understanding descriptor tables and line disciplines eliminates mysterious terminal behavior across both ho…
GL-E00 · Linux Host Workbench, POSIX Shell, Network Boot & Embedded C Style51/561

GL-E00 · 1.2 (m01-l02)

>_ Kernel Systems Academy

Warning

warning: - Symptom: While logged into a target board over a naive script (cat /dev/ttyUSB0), pressing Ctrl-C kills the local cat command on the host instead of stopping ping on the board. - Root Cause: The host shell's /dev/pts/N n_tty line discipline still has ISIG enabled, so 0x03 generates SIGINT locally on the host before ever reaching /dev/ttyUSB0. - Fix: Use a dedicated serial terminal (picocom -b 115200 /dev/ttyBENCH0 or minicom) that puts the local PTY into cfmakeraw() (~ISIG & ~ICANON & ~ECHO), forwarding 0x03 verbatim over UART and reserving an escape chord (Ctrl-A Ctrl-X) for host exit.

GL-E00 · Linux Host Workbench, POSIX Shell, Network Boot & Embedded C Style52/561

GL-E00 · 1.2 (m01-l02)

>_ Kernel Systems Academy

Warning

warning: - Symptom: Subsequent normal make invocations fail with Fatal error: can't create scripts/basic/.fixdep.d: Permission denied. - Root Cause: A single sudo make left .o, .cmd, and include/config/ directories owned by UID 0:0 inside your working tree, blocking unprivileged compiler updates. - Fix: Reclaim ownership once via sudo chown -R "$(id -u):$(id -g)" ., and never invoke sudo for menuconfig, zImage, dtbs, or modules builds.

GL-E00 · Linux Host Workbench, POSIX Shell, Network Boot & Embedded C Style53/561

GL-E00 · 1.2 (m01-l02)

>_ Kernel Systems Academy

Guided Practice

  • Modify verify.c to add a third helper run_dual_open_case() that opens a temporary file twice (`fd_a = o…
GL-E00 · Linux Host Workbench, POSIX Shell, Network Boot & Embedded C Style54/561

GL-E00 · 1.2 (m01-l02)

>_ Kernel Systems Academy

Independent Practice

  • Write a POSIX C11 wrapper using fork(), pipe(), dup2(), and waitpid() that runs two child stages (`…
GL-E00 · Linux Host Workbench, POSIX Shell, Network Boot & Embedded C Style55/561

GL-E00 · 1.2 (m01-l02)

>_ Kernel Systems Academy

Quick check

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?

Select an option or press R to reveal.

GL-E00 · Linux Host Workbench, POSIX Shell, Network Boot & Embedded C Style56/561

GL-E00 · 1.2 (m01-l02)

>_ Kernel Systems Academy

Quick check

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?

Select an option or press R to reveal.

GL-E00 · Linux Host Workbench, POSIX Shell, Network Boot & Embedded C Style57/561

GL-E00 · 1.2 (m01-l02)

>_ Kernel Systems Academy

Quick check

Without set -o pipefail, what exit code ($?) does make -j8 zImage 2>&1 | tee build.log return when gcc aborts with a syntax error?

Select an option or press R to reveal.

GL-E00 · Linux Host Workbench, POSIX Shell, Network Boot & Embedded C Style58/561

GL-E00 · 1.2 (m01-l02)

>_ Kernel Systems Academy

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.
GL-E00 · Linux Host Workbench, POSIX Shell, Network Boot & Embedded C Style59/561

GL-E00 · 1.2 (m01-l02)

>_ Kernel Systems Academy

Key takeaways

  • 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.
GL-E00 · Linux Host Workbench, POSIX Shell, Network Boot & Embedded C Style60/561

GL-E00 · 1.3 (m01-l03)

>_ Kernel Systems Academy

Modal Text Editing, Tree Search Pipelines & Workbench Audit Studio

free preview20 minlab lab_m01_shell_env_audit

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.
GL-E00 · Linux Host Workbench, POSIX Shell, Network Boot & Embedded C Style61/561

GL-E00 · 1.3 (m01-l03)

>_ Kernel Systems Academy

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…
GL-E00 · Linux Host Workbench, POSIX Shell, Network Boot & Embedded C Style62/561

GL-E00 · 1.3 (m01-l03)

>_ Kernel Systems Academy

Surviving Headless Bring-Up Servers and 80,000-File Source Trees

  • Pressing i, a, or o enters Insert mode for raw text, Esc returns to Normal mode, and : enters…
GL-E00 · Linux Host Workbench, POSIX Shell, Network Boot & Embedded C Style63/561

GL-E00 · 1.3 (m01-l03)

>_ Kernel Systems Academy

Surviving Headless Bring-Up Servers and 80,000-File Source Trees

  • Equally critical is searching huge trees (Linux kernel 6.12 exceeds 82,000 files) and auditing PATH s…
GL-E00 · Linux Host Workbench, POSIX Shell, Network Boot & Embedded C Style64/561

GL-E00 · 1.3 (m01-l03)

>_ Kernel Systems Academy

Surviving Headless Bring-Up Servers and 80,000-File Source Trees

fig_m01_l03_a.svg

Figure 1.3a: NUL (0x00) is the sole byte value illegal inside POSIX path components, making -print0 | xargs -0 immune to spaces and quotes.

GL-E00 · Linux Host Workbench, POSIX Shell, Network Boot & Embedded C Style65/561

GL-E00 · 1.3 (m01-l03)

>_ Kernel Systems Academy

Mental model

note: 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.

GL-E00 · Linux Host Workbench, POSIX Shell, Network Boot & Embedded C Style66/561

GL-E00 · 1.3 (m01-l03)

>_ Kernel Systems Academy

Empty PATH Segment (Implicit '.') and Vim Swap Recovery

definition: 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.

GL-E00 · Linux Host Workbench, POSIX Shell, Network Boot & Embedded C Style67/561

GL-E00 · 1.3 (m01-l03)

>_ Kernel Systems Academy

Surviving Headless Bring-Up Servers and 80,000-File Source Trees

Open target files directly at the diagnostic line (+42), run :set list in Ex mode to distinguish ^I tabs from spaces, and write atomically.

Use :set list for tabs, -print0 | xargs -0 for paths, and strchr to audit PATH.

GL-E00 · Linux Host Workbench, POSIX Shell, Network Boot & Embedded C Style68/561

GL-E00 · 1.3 (m01-l03)

>_ Kernel Systems Academy

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 st…
GL-E00 · Linux Host Workbench, POSIX Shell, Network Boot & Embedded C Style69/561

GL-E00 · 1.3 (m01-l03)

>_ Kernel Systems Academy

Inside Vim State Transitions, VFS Filename Bytes & C11 PATH Scanning

  • Notice the classic C11 bug waiting inside our workbench PATH auditor: if an engineer uses `strtok(buf, ":…
GL-E00 · Linux Host Workbench, POSIX Shell, Network Boot & Embedded C Style70/561

GL-E00 · 1.3 (m01-l03)

>_ Kernel Systems Academy

Inside Vim State Transitions, VFS Filename Bytes & C11 PATH Scanning

fig_m01_l03_b.svg

Figure 1.3b: Explicit colon-pointer scanning catches leading ':', interior '::', and trailing ':' hazards that C strtok() silently skips.

GL-E00 · Linux Host Workbench, POSIX Shell, Network Boot & Embedded C Style71/561

GL-E00 · 1.3 (m01-l03)

>_ Kernel Systems Academy

tree_and_path_audit.sh

learner@ksa: ~/gl-e00/m01-l03
learner@ksa:~/gl-e00/m01-l03#!/usr/bin/env bashset -euo pipefail # 1. Safe parameter expansion: appends :$PATH only when PATH is non-emptyTOOLCHAIN_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 headersfind . -type f \( -name "*.dts*" -o -name "*.h" \) -print0 | xargs -0 -r grep -n "compatible"learner@ksa:~/gl-e00/m01-l03
GL-E00 · Linux Host Workbench, POSIX Shell, Network Boot & Embedded C Style72/561

GL-E00 · 1.3 (m01-l03)

>_ Kernel Systems Academy

xargs

xargs(1) at a glance — GL-E00
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                    m01-l03                     xargs(1) GL-E00 quick reference · full manual page: man 1 xargs 
GL-E00 · Linux Host Workbench, POSIX Shell, Network Boot & Embedded C Style73/561

GL-E00 · 1.3 (m01-l03)

>_ Kernel Systems Academy

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.
GL-E00 · Linux Host Workbench, POSIX Shell, Network Boot & Embedded C Style74/561

GL-E00 · 1.3 (m01-l03)

>_ Kernel Systems Academy

Verifying NUL-Delimited Streams and Colon-Exact PATH Parsing in C11

  • Second, we contrast audit_path_strchr() against count_strtok_segments() on "/usr/bin::/bin".
GL-E00 · Linux Host Workbench, POSIX Shell, Network Boot & Embedded C Style75/561

GL-E00 · 1.3 (m01-l03)

>_ Kernel Systems Academy

verify.c

learner@ksa: ~/gl-e00/m01-l03
learner@ksa:~/gl-e00/m01-l03$ bat 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);
GL-E00 · Linux Host Workbench, POSIX Shell, Network Boot & Embedded C Style76/561

GL-E00 · 1.3 (m01-l03)

>_ Kernel Systems Academy

Confirming NUL Framing and strtok Blindness Under strace

  • Check both the program output and the strace capture.
GL-E00 · Linux Host Workbench, POSIX Shell, Network Boot & Embedded C Style77/561

GL-E00 · 1.3 (m01-l03)

>_ Kernel Systems Academy

Confirming NUL Framing and strtok Blindness Under strace

learner@ksa: ~/gl-e00/m01-l03
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-l03
GL-E00 · Linux Host Workbench, POSIX Shell, Network Boot & Embedded C Style78/561

GL-E00 · 1.3 (m01-l03)

>_ Kernel Systems Academy

Confirming NUL Framing and strtok Blindness Under strace

strace — learner@ksa: ~/gl-e00/m01-l03
learner@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 +++
GL-E00 · Linux Host Workbench, POSIX Shell, Network Boot & Embedded C Style79/561

GL-E00 · 1.3 (m01-l03)

>_ Kernel Systems Academy

Modal Editing and Tree-Pipeline Pitfalls

  • Fluency with modal editing, NUL-delimited search streams, and strict environment hygiene turns any headless…
GL-E00 · Linux Host Workbench, POSIX Shell, Network Boot & Embedded C Style80/561

GL-E00 · 1.3 (m01-l03)

>_ Kernel Systems Academy

Warning

warning: - Symptom: make aborts immediately on line 12 with Makefile:12: *** missing separator. Stop. even though indentation looks aligned. - Root Cause: Terminal mouse selection converted the leading 0x09 hard tab (\t) into 4 or 8 ASCII spaces (0x20), which GNU make rejects on recipe lines. - Fix: Open the Makefile in vim, run :set list to verify whether lines begin with ^I (tab) or spaces, and replace leading spaces on recipe lines with a literal Tab (:set noexpandtab).

GL-E00 · Linux Host Workbench, POSIX Shell, Network Boot & Embedded C Style81/561

GL-E00 · 1.3 (m01-l03)

>_ Kernel Systems Academy

Warning

warning: - Symptom: vim warns Swap file ".board.dts.swp" already exists! and an engineer reflexively presses D (Delete) or runs rm .*.swp, losing an hour of unsaved Device Tree edits. - Root Cause: Either a second terminal window currently has board.dts open (ps aux | grep vim), or a dropped SSH session left unsaved buffer deltas inside .board.dts.swp. - Fix: First check whether another live vim PID owns the file; if none exists, open with vim -r board.dts, save to a recovery copy (:w board.dts.recovered), diff with diff -u, and only then remove .board.dts.swp.

GL-E00 · Linux Host Workbench, POSIX Shell, Network Boot & Embedded C Style82/561

GL-E00 · 1.3 (m01-l03)

>_ Kernel Systems Academy

Guided Practice

  • Extend audit_path_strchr() in verify.c to accept an array of mode_t directory permission values corre…
GL-E00 · Linux Host Workbench, POSIX Shell, Network Boot & Embedded C Style83/561

GL-E00 · 1.3 (m01-l03)

>_ Kernel Systems Academy

Independent Practice

  • Now open labs/lab_m01_shell_env_audit/ and repair all three defects in starter/core.c so sh check.sh…
GL-E00 · Linux Host Workbench, POSIX Shell, Network Boot & Embedded C Style84/561

GL-E00 · 1.3 (m01-l03)

>_ Kernel Systems Academy

Quick check

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?

Select an option or press R to reveal.

GL-E00 · Linux Host Workbench, POSIX Shell, Network Boot & Embedded C Style85/561

GL-E00 · 1.3 (m01-l03)

>_ Kernel Systems Academy

Quick check

In ISO C11, why is strtok(path_copy, ":") unsafe for auditing a PATH environment variable for current-working-directory (.) security hazards?

Select an option or press R to reveal.

GL-E00 · Linux Host Workbench, POSIX Shell, Network Boot & Embedded C Style86/561

GL-E00 · 1.3 (m01-l03)

>_ Kernel Systems Academy

Quick check

You open a broken Makefile in vim over SSH. Which command sequence enters Ex mode and makes hard tabs visible as ^I versus spaces?

Select an option or press R to reveal.

GL-E00 · Linux Host Workbench, POSIX Shell, Network Boot & Embedded C Style87/561

GL-E00 · 1.3 (m01-l03)

>_ Kernel Systems Academy

Lab: lab_m01_shell_env_audit

  • Onboarding scripts for embedded Linux teams routinely break because one typo in /etc/udev/rules.d/ grants…

Verify: ./check.sh exits 0.

GL-E00 · Linux Host Workbench, POSIX Shell, Network Boot & Embedded C Style88/561

GL-E00 · 1.3 (m01-l03)

>_ Kernel Systems Academy

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.
GL-E00 · Linux Host Workbench, POSIX Shell, Network Boot & Embedded C Style89/561

GL-E00 · 1.3 (m01-l03)

>_ Kernel Systems Academy

Key takeaways

  • 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.
GL-E00 · Linux Host Workbench, POSIX Shell, Network Boot & Embedded C Style90/561

m02/

>_ Kernel Systems Academy

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.

  1. 2.1 Linux Filesystem Hierarchy (FHS 3.0), Inode Links & Device Nodes
  2. 2.2 UID/GID Identity, Octal Mode Bits, Sticky Directories & Profile Safety
  3. 2.3 MBR/GPT Sector Offsets, Removable-Disk Guards & Numeric-Owner Rootfs Archives

lab → SD/eMMC Partition-Offset, Sticky Unlink & ustar Rootfs Verifier

GL-E00 · Linux Host Workbench, POSIX Shell, Network Boot & Embedded C Style91/561

GL-E00 · 2.1 (m02-l01)

>_ Kernel Systems Academy

Linux Filesystem Hierarchy (FHS 3.0), Inode Links & Device Nodes

free preview20 min

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.
GL-E00 · Linux Host Workbench, POSIX Shell, Network Boot & Embedded C Style92/561

GL-E00 · 2.1 (m02-l01)

>_ Kernel Systems Academy

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 expe…
GL-E00 · Linux Host Workbench, POSIX Shell, Network Boot & Embedded C Style93/561

GL-E00 · 2.1 (m02-l01)

>_ Kernel Systems Academy

Why Everything in Linux Looks Like a File Yet Lives in Different Worlds

  • Understanding how the Virtual Filesystem (VFS) binds names to inodes prevents two classic rootfs bugs.
GL-E00 · Linux Host Workbench, POSIX Shell, Network Boot & Embedded C Style94/561

GL-E00 · 2.1 (m02-l01)

>_ Kernel Systems Academy

Why Everything in Linux Looks Like a File Yet Lives in Different Worlds

fig_m02_l01_a.svg

Figure 2.1a: VFS unifies flash files, RAM tmpfs (/run), kernel pseudo-filesystems (/proc, /sys), and major:minor device nodes under one namespace.

GL-E00 · Linux Host Workbench, POSIX Shell, Network Boot & Embedded C Style95/561

GL-E00 · 2.1 (m02-l01)

>_ Kernel Systems Academy

Mental model

note: 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.

GL-E00 · Linux Host Workbench, POSIX Shell, Network Boot & Embedded C Style96/561

GL-E00 · 2.1 (m02-l01)

>_ Kernel Systems Academy

Inode Reference Count (st_nlink) and Device ID (dev_t st_rdev)

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

GL-E00 · Linux Host Workbench, POSIX Shell, Network Boot & Embedded C Style97/561

GL-E00 · 2.1 (m02-l01)

>_ Kernel Systems Academy

Why Everything in Linux Looks Like a File Yet Lives in Different Worlds

Inspect live mount types with findmnt so runtime logs and sockets go to /run (tmpfs) rather than wearing out raw flash.

Keep rootfs symlinks relative, check st_dev+st_ino for hard links, and read st_rdev on /dev.

GL-E00 · Linux Host Workbench, POSIX Shell, Network Boot & Embedded C Style98/561

GL-E00 · 2.1 (m02-l01)

>_ Kernel Systems Academy

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: `…
GL-E00 · Linux Host Workbench, POSIX Shell, Network Boot & Embedded C Style99/561

GL-E00 · 2.1 (m02-l01)

>_ Kernel Systems Academy

FHS 3.0 Layout, VFS Link Rules & Character/Block Major:Minor Numbers

  • At the VFS syscall layer, stat(path, &sb) follows symlinks to the terminal target (returning -1 with `E…
GL-E00 · Linux Host Workbench, POSIX Shell, Network Boot & Embedded C Style100/561

GL-E00 · 2.1 (m02-l01)

>_ Kernel Systems Academy

FHS 3.0 Layout, VFS Link Rules & Character/Block Major:Minor Numbers

fig_m02_l01_b.svg

Figure 2.1b: lstat() inspects the S_IFLNK inode directly instead of dereferencing host paths, catching broken rootfs links before flashing.

GL-E00 · Linux Host Workbench, POSIX Shell, Network Boot & Embedded C Style101/561

GL-E00 · 2.1 (m02-l01)

>_ Kernel Systems Academy

stage_fhs_rootfs.sh

learner@ksa: ~/gl-e00/m02-l01
learner@ksa:~/gl-e00/m02-l01#!/usr/bin/env bashset -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 directorywhile 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 ;; esacdone < <(find "${STAGE}" -type l -print0)learner@ksa:~/gl-e00/m02-l01
GL-E00 · Linux Host Workbench, POSIX Shell, Network Boot & Embedded C Style102/561

GL-E00 · 2.1 (m02-l01)

>_ Kernel Systems Academy

lstat

lstat(2) at a glance — GL-E00
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. Kernel Systems Academy                    m02-l01                     lstat(2) GL-E00 quick reference · full manual page: man 2 lstat 
GL-E00 · Linux Host Workbench, POSIX Shell, Network Boot & Embedded C Style103/561

GL-E00 · 2.1 (m02-l01)

>_ Kernel Systems Academy

Proving Hard Links, Dangling Symlinks & dev_t Encoding in C11

  • Let us verify these exact VFS behaviors on the Linux host in ISO C11.
GL-E00 · Linux Host Workbench, POSIX Shell, Network Boot & Embedded C Style104/561

GL-E00 · 2.1 (m02-l01)

>_ Kernel Systems Academy

Proving Hard Links, Dangling Symlinks & dev_t Encoding in C11

  • Notice how stat() on the dangling symlink fails with errno == ENOENT while lstat() succeeds and repor…
GL-E00 · Linux Host Workbench, POSIX Shell, Network Boot & Embedded C Style105/561

GL-E00 · 2.1 (m02-l01)

>_ Kernel Systems Academy

verify.c

learner@ksa: ~/gl-e00/m02-l01
learner@ksa:~/gl-e00/m02-l01$ bat 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;
GL-E00 · Linux Host Workbench, POSIX Shell, Network Boot & Embedded C Style106/561

GL-E00 · 2.1 (m02-l01)

>_ Kernel Systems Academy

Tracing linkat, symlinkat, and newfstatat Flags in strace

  • Inspect the strace capture closely: glibc translates stat() and lstat() into the same newfstatat()…
GL-E00 · Linux Host Workbench, POSIX Shell, Network Boot & Embedded C Style107/561

GL-E00 · 2.1 (m02-l01)

>_ Kernel Systems Academy

Tracing linkat, symlinkat, and newfstatat Flags in strace

learner@ksa: ~/gl-e00/m02-l01
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-l01
GL-E00 · Linux Host Workbench, POSIX Shell, Network Boot & Embedded C Style108/561

GL-E00 · 2.1 (m02-l01)

>_ Kernel Systems Academy

Tracing linkat, symlinkat, and newfstatat Flags in strace

strace — learner@ksa: ~/gl-e00/m02-l01
learner@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 +++
GL-E00 · Linux Host Workbench, POSIX Shell, Network Boot & Embedded C Style109/561

GL-E00 · 2.1 (m02-l01)

>_ Kernel Systems Academy

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…
GL-E00 · Linux Host Workbench, POSIX Shell, Network Boot & Embedded C Style110/561

GL-E00 · 2.1 (m02-l01)

>_ Kernel Systems Academy

Warning

warning: - Symptom: df -h reports 0 B free on /var, you run rm /var/log/daemon.log (2 GiB), ls shows the file is gone, yet df -h still reports 0 B free! - Root Cause: rm calls unlink(2), decrementing st_nlink from 1 to 0, but the running daemon still holds an open struct file descriptor (fd 3), so ext4 cannot free the blocks. - Fix: Identify the holder with lsof +L1 (open files with nlink < 1), then either truncate in place (: > /var/log/daemon.log before unlinking) or reload/restart the daemon (SIGHUP / systemctl kill -s HUP) so it closes fd 3.

GL-E00 · Linux Host Workbench, POSIX Shell, Network Boot & Embedded C Style111/561

GL-E00 · 2.1 (m02-l01)

>_ Kernel Systems Academy

Warning

warning: - Symptom: Copying a rootfs directory with cp -r turns /dev/null into a multi-megabyte regular file and converts 300 BusyBox symlinks into 300 full 1 MiB binary copies (300 MiB flash bloat!). - Root Cause: Plain cp -r dereferences symlinks and reads from character device nodes instead of preserving S_IFLNK and S_IFCHR metadata. - Fix: Always copy rootfs staging directories with cp -a (-dR --preserve=all) or rsync -aHAX, and keep /proc, /sys, /dev, and /run as empty mount-point directories in the image.

GL-E00 · Linux Host Workbench, POSIX Shell, Network Boot & Embedded C Style112/561

GL-E00 · 2.1 (m02-l01)

>_ Kernel Systems Academy

Guided Practice

  • Extend verify.c to open bb_path read-only (fd_hold = open(bb_path, O_RDONLY)), unlink both `hlink_pat…
GL-E00 · Linux Host Workbench, POSIX Shell, Network Boot & Embedded C Style113/561

GL-E00 · 2.1 (m02-l01)

>_ Kernel Systems Academy

Independent Practice

  • Write a C11 directory scanner using opendir(), readdir(), lstat(), and readlink() that walks a stag…
GL-E00 · Linux Host Workbench, POSIX Shell, Network Boot & Embedded C Style114/561

GL-E00 · 2.1 (m02-l01)

>_ Kernel Systems Academy

Quick check

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?

Select an option or press R to reveal.

GL-E00 · Linux Host Workbench, POSIX Shell, Network Boot & Embedded C Style115/561

GL-E00 · 2.1 (m02-l01)

>_ Kernel Systems Academy

Quick check

Why does ln /var/log/messages /home/backup/messages fail with Invalid cross-device link (EXDEV) when /var and /home are separate partitions?

Select an option or press R to reveal.

GL-E00 · Linux Host Workbench, POSIX Shell, Network Boot & Embedded C Style116/561

GL-E00 · 2.1 (m02-l01)

>_ Kernel Systems Academy

Quick check

What do the numbers 179, 2 represent in brw-rw---- 1 root disk 179, 2 Nov 24 01:00 /dev/mmcblk0p2?

Select an option or press R to reveal.

GL-E00 · Linux Host Workbench, POSIX Shell, Network Boot & Embedded C Style117/561

GL-E00 · 2.1 (m02-l01)

>_ Kernel Systems Academy

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.
GL-E00 · Linux Host Workbench, POSIX Shell, Network Boot & Embedded C Style118/561

GL-E00 · 2.1 (m02-l01)

>_ Kernel Systems Academy

Key takeaways

  • 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.
GL-E00 · Linux Host Workbench, POSIX Shell, Network Boot & Embedded C Style119/561

GL-E00 · 2.2 (m02-l02)

>_ Kernel Systems Academy

UID/GID Identity, Octal Mode Bits, Sticky Directories & Profile Safety

free preview20 min

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.
GL-E00 · Linux Host Workbench, POSIX Shell, Network Boot & Embedded C Style120/561

GL-E00 · 2.2 (m02-l02)

>_ Kernel Systems Academy

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.
GL-E00 · Linux Host Workbench, POSIX Shell, Network Boot & Embedded C Style121/561

GL-E00 · 2.2 (m02-l02)

>_ Kernel Systems Academy

Why 'chmod -R 777' and Naive /etc/profile Edits Destroy Workstations

  • Second, when adding an ARM cross-compiler permanently, an engineer edits /etc/profile and writes `expor…
GL-E00 · Linux Host Workbench, POSIX Shell, Network Boot & Embedded C Style122/561

GL-E00 · 2.2 (m02-l02)

>_ Kernel Systems Academy

Why 'chmod -R 777' and Naive /etc/profile Edits Destroy Workstations

fig_m02_l02_a.svg

Figure 2.2a: VFS checks owner, group, and other classes mutually exclusively (first match wins, never union!) alongside 04000/02000/01000 high bits.

GL-E00 · Linux Host Workbench, POSIX Shell, Network Boot & Embedded C Style123/561

GL-E00 · 2.2 (m02-l02)

>_ Kernel Systems Academy

Mental model

note: 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!

GL-E00 · Linux Host Workbench, POSIX Shell, Network Boot & Embedded C Style124/561

GL-E00 · 2.2 (m02-l02)

>_ Kernel Systems Academy

Sticky Bit (S_ISVTX / 01000) and Set-Group-ID Directory (S_ISGID / 02000)

definition: 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.

GL-E00 · Linux Host Workbench, POSIX Shell, Network Boot & Embedded C Style125/561

GL-E00 · 2.2 (m02-l02)

>_ Kernel Systems Academy

Why 'chmod -R 777' and Naive /etc/profile Edits Destroy Workstations

Query numeric and symbolic mode bits with stat -c '%a %A' to audit special high bits (4=setuid, 2=setgid, 1=sticky).

Avoid chmod 777; dir w+x + 01000 governs unlink; syntax-check profile.d via sh -n.

GL-E00 · Linux Host Workbench, POSIX Shell, Network Boot & Embedded C Style126/561

GL-E00 · 2.2 (m02-l02)

>_ Kernel Systems Academy

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 di…
GL-E00 · Linux Host Workbench, POSIX Shell, Network Boot & Embedded C Style127/561

GL-E00 · 2.2 (m02-l02)

>_ Kernel Systems Academy

12-Bit Mode Masks, First-Match Credential Evaluation & visudo Safety

  • Look closely at directory deletion: unlink("/shared/report.pdf") mutates /shared's directory entries, *…
GL-E00 · Linux Host Workbench, POSIX Shell, Network Boot & Embedded C Style128/561

GL-E00 · 2.2 (m02-l02)

>_ Kernel Systems Academy

12-Bit Mode Masks, First-Match Credential Evaluation & visudo Safety

fig_m02_l02_b.svg

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.

GL-E00 · Linux Host Workbench, POSIX Shell, Network Boot & Embedded C Style129/561

GL-E00 · 2.2 (m02-l02)

>_ Kernel Systems Academy

90-arm-toolchain.sh

learner@ksa: ~/gl-e00/m02-l02
learner@ksa:~/gl-e00/m02-l02# /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 PATHfilearner@ksa:~/gl-e00/m02-l02
GL-E00 · Linux Host Workbench, POSIX Shell, Network Boot & Embedded C Style130/561

GL-E00 · 2.2 (m02-l02)

>_ Kernel Systems Academy

chmod

chmod(2) at a glance — GL-E00
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                    m02-l02                     chmod(2) GL-E00 quick reference · full manual page: man 2 chmod 
GL-E00 · Linux Host Workbench, POSIX Shell, Network Boot & Embedded C Style131/561

GL-E00 · 2.2 (m02-l02)

>_ Kernel Systems Academy

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() sy…
GL-E00 · Linux Host Workbench, POSIX Shell, Network Boot & Embedded C Style132/561

GL-E00 · 2.2 (m02-l02)

>_ Kernel Systems Academy

Verifying umask, First-Match Triads & Sticky Unlink Rules in C11

  • Second, we temporarily set umask(0027), create a real scratch file with open(..., 0666) and scratch dir…
GL-E00 · Linux Host Workbench, POSIX Shell, Network Boot & Embedded C Style133/561

GL-E00 · 2.2 (m02-l02)

>_ Kernel Systems Academy

verify.c

learner@ksa: ~/gl-e00/m02-l02
learner@ksa:~/gl-e00/m02-l02$ bat 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);    }
GL-E00 · Linux Host Workbench, POSIX Shell, Network Boot & Embedded C Style134/561

GL-E00 · 2.2 (m02-l02)

>_ Kernel Systems Academy

Confirming Kernel umask Masking in strace

  • Observe the strace output: umask(027) returns the caller's previous mask, openat(..., 0666) and `mkdi…
GL-E00 · Linux Host Workbench, POSIX Shell, Network Boot & Embedded C Style135/561

GL-E00 · 2.2 (m02-l02)

>_ Kernel Systems Academy

Confirming Kernel umask Masking in strace

  • Notice one subtle contrast between openat() creation and explicit chmod()/fchmodat(): umask filters…
GL-E00 · Linux Host Workbench, POSIX Shell, Network Boot & Embedded C Style136/561

GL-E00 · 2.2 (m02-l02)

>_ Kernel Systems Academy

Confirming Kernel umask Masking in strace

learner@ksa: ~/gl-e00/m02-l02
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-l02
GL-E00 · Linux Host Workbench, POSIX Shell, Network Boot & Embedded C Style137/561

GL-E00 · 2.2 (m02-l02)

>_ Kernel Systems Academy

Confirming Kernel umask Masking in strace

strace — learner@ksa: ~/gl-e00/m02-l02
learner@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 +++
GL-E00 · Linux Host Workbench, POSIX Shell, Network Boot & Embedded C Style138/561

GL-E00 · 2.2 (m02-l02)

>_ Kernel Systems Academy

Desktop Login Loops, Bashisms in /etc/profile & sudo Lockouts

  • Respecting octal mode invariants keeps multi-user build servers and embedded root filesystems secure withou…
GL-E00 · Linux Host Workbench, POSIX Shell, Network Boot & Embedded C Style139/561

GL-E00 · 2.2 (m02-l02)

>_ Kernel Systems Academy

Warning

warning: - 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/lightdm Xsession sources /etc/profile and /etc/profile.d/*.sh using /bin/sh (dash), which aborts the entire session startup on non-POSIX bashisms ([[ ... ]], source, arrays) or a clobbered PATH. - Fix: Switch to a text virtual console with Ctrl-Alt-F3 (or SSH in), inspect ~/.xsession-errors or journalctl -b, validate /etc/profile.d/*.sh with dash -n, and ensure PATH retains /usr/bin:/bin.

GL-E00 · Linux Host Workbench, POSIX Shell, Network Boot & Embedded C Style140/561

GL-E00 · 2.2 (m02-l02)

>_ Kernel Systems Academy

Warning

warning: - Symptom: ls dir/ lists filenames mixed with ls: cannot access 'dir/foo': Permission denied and ?????????? stat columns, and cat dir/foo fails even though dir/foo is 0644! - Root Cause: Read (r, 04) on a directory permits getdents64() to read raw filename strings, but without execute/search (x, 01) the VFS refuses inode lookup (stat/open) on every child inside dir/. - Fix: Directories practically always pair r with x (0755 or 0750); use chmod -R a+X (capital X adds +x only to directories and already-executable files, leaving regular 0644 data files non-executable!).

GL-E00 · Linux Host Workbench, POSIX Shell, Network Boot & Embedded C Style141/561

GL-E00 · 2.2 (m02-l02)

>_ Kernel Systems Academy

Guided Practice

  • Test the difference between lowercase chmod -R a+x and uppercase chmod -R a+X on a scratch directory in…
GL-E00 · Linux Host Workbench, POSIX Shell, Network Boot & Embedded C Style142/561

GL-E00 · 2.2 (m02-l02)

>_ Kernel Systems Academy

Independent Practice

  • Extend verify.c with a `check_ssh_strict_modes(uint32_t home_mode, uint32_t ssh_dir_mode, uint32_t auth_k…
GL-E00 · Linux Host Workbench, POSIX Shell, Network Boot & Embedded C Style143/561

GL-E00 · 2.2 (m02-l02)

>_ Kernel Systems Academy

Quick check

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?

Select an option or press R to reveal.

GL-E00 · Linux Host Workbench, POSIX Shell, Network Boot & Embedded C Style144/561

GL-E00 · 2.2 (m02-l02)

>_ Kernel Systems Academy

Quick check

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

Select an option or press R to reveal.

GL-E00 · Linux Host Workbench, POSIX Shell, Network Boot & Embedded C Style145/561

GL-E00 · 2.2 (m02-l02)

>_ Kernel Systems Academy

Quick check

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?

Select an option or press R to reveal.

GL-E00 · Linux Host Workbench, POSIX Shell, Network Boot & Embedded C Style146/561

GL-E00 · 2.2 (m02-l02)

>_ Kernel Systems Academy

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.
GL-E00 · Linux Host Workbench, POSIX Shell, Network Boot & Embedded C Style147/561

GL-E00 · 2.2 (m02-l02)

>_ Kernel Systems Academy

Key takeaways

  • 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.
GL-E00 · Linux Host Workbench, POSIX Shell, Network Boot & Embedded C Style148/561

GL-E00 · 2.3 (m02-l03)

>_ Kernel Systems Academy

MBR/GPT Sector Offsets, Removable-Disk Guards & Numeric-Owner Rootfs Archives

free preview20 minlab lab_m02_perm_partition_guard

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.
GL-E00 · Linux Host Workbench, POSIX Shell, Network Boot & Embedded C Style149/561

GL-E00 · 2.3 (m02-l03)

>_ Kernel Systems Academy

Three Ways SD Card Flashing Goes Catastrophically Wrong

  • dd is affectionately nicknamed disk destroyer by kernel engineers for good reason: block devices (`/dev…
GL-E00 · Linux Host Workbench, POSIX Shell, Network Boot & Embedded C Style150/561

GL-E00 · 2.3 (m02-l03)

>_ Kernel Systems Academy

Three Ways SD Card Flashing Goes Catastrophically Wrong

  • Even when you select the right USB SD reader (/dev/sdb), omitting bs=1K seek=1 writes u-boot.imx at b…
GL-E00 · Linux Host Workbench, POSIX Shell, Network Boot & Embedded C Style151/561

GL-E00 · 2.3 (m02-l03)

>_ Kernel Systems Academy

Three Ways SD Card Flashing Goes Catastrophically Wrong

  • Once Partition 1 (FAT32 holding zImage + .dtb) and Partition 2 (ext4 rootfs) are formatted, a third…
GL-E00 · Linux Host Workbench, POSIX Shell, Network Boot & Embedded C Style152/561

GL-E00 · 2.3 (m02-l03)

>_ Kernel Systems Academy

Three Ways SD Card Flashing Goes Catastrophically Wrong

fig_m02_l03_a.svg

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.

GL-E00 · Linux Host Workbench, POSIX Shell, Network Boot & Embedded C Style153/561

GL-E00 · 2.3 (m02-l03)

>_ Kernel Systems Academy

Mental model

note: 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!

GL-E00 · Linux Host Workbench, POSIX Shell, Network Boot & Embedded C Style154/561

GL-E00 · 2.3 (m02-l03)

>_ Kernel Systems Academy

Image Vector Table (IVT @ 0x400) and POSIX ustar Numeric-Owner Header

definition: 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.

GL-E00 · Linux Host Workbench, POSIX Shell, Network Boot & Embedded C Style155/561

GL-E00 · 2.3 (m02-l03)

>_ Kernel Systems Academy

Three Ways SD Card Flashing Goes Catastrophically Wrong

Gate every raw flash script on /sys/block/<dev>/removable == 1 and zero active /proc/mounts entries.

Check removable==1, start p1 >= LBA 2048, flash with bs=1K seek=1, and --numeric-owner.

GL-E00 · Linux Host Workbench, POSIX Shell, Network Boot & Embedded C Style156/561

GL-E00 · 2.3 (m02-l03)

>_ Kernel Systems Academy

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.
GL-E00 · Linux Host Workbench, POSIX Shell, Network Boot & Embedded C Style157/561

GL-E00 · 2.3 (m02-l03)

>_ Kernel Systems Academy

Exact MBR + IVT Byte Offsets, GPT LBA-2 Collision & ustar Checksums

  • LBA 1 (0x200..0x3FF) is unused on MBR, whereas standard GPT places its header at LBA 1 and partitio…
GL-E00 · Linux Host Workbench, POSIX Shell, Network Boot & Embedded C Style158/561

GL-E00 · 2.3 (m02-l03)

>_ Kernel Systems Academy

Exact MBR + IVT Byte Offsets, GPT LBA-2 Collision & ustar Checksums

  • Inside a .tar rootfs archive, each 512-byte ustar block stores magic "ustar" at offset 257, `ui…
GL-E00 · Linux Host Workbench, POSIX Shell, Network Boot & Embedded C Style159/561

GL-E00 · 2.3 (m02-l03)

>_ Kernel Systems Academy

Exact MBR + IVT Byte Offsets, GPT LBA-2 Collision & ustar Checksums

fig_m02_l03_b.svg

Figure 2.3b: Byte-exact arithmetic proves 0x400 + uboot_bytes <= p1_lba_start * 512 and ustar uid/gid == 0 before hardware flashing.

GL-E00 · Linux Host Workbench, POSIX Shell, Network Boot & Embedded C Style160/561

GL-E00 · 2.3 (m02-l03)

>_ Kernel Systems Academy

flash_sdcard_safe.sh

learner@ksa: ~/gl-e00/m02-l03
learner@ksa:~/gl-e00/m02-l03#!/usr/bin/env bashset -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: dosstart=2048, size=131072, type=c, bootablelearner@ksa:~/gl-e00/m02-l03
GL-E00 · Linux Host Workbench, POSIX Shell, Network Boot & Embedded C Style161/561

GL-E00 · 2.3 (m02-l03)

>_ Kernel Systems Academy

dd

dd(1) at a glance — GL-E00
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                      m02-l03                      dd(1) GL-E00 quick reference · full manual page: man 1 dd 
GL-E00 · Linux Host Workbench, POSIX Shell, Network Boot & Embedded C Style162/561

GL-E00 · 2.3 (m02-l03)

>_ Kernel Systems Academy

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…
GL-E00 · Linux Host Workbench, POSIX Shell, Network Boot & Embedded C Style163/561

GL-E00 · 2.3 (m02-l03)

>_ Kernel Systems Academy

verify.c

learner@ksa: ~/gl-e00/m02-l03
learner@ksa:~/gl-e00/m02-l03$ bat 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);
GL-E00 · Linux Host Workbench, POSIX Shell, Network Boot & Embedded C Style164/561

GL-E00 · 2.3 (m02-l03)

>_ Kernel Systems Academy

Confirming Sector Boundary & ustar Header Rejections

  • Review the execution output: fixed non-removable disks (sda) fail immediately (-1), legacy LBA 63 par…
GL-E00 · Linux Host Workbench, POSIX Shell, Network Boot & Embedded C Style165/561

GL-E00 · 2.3 (m02-l03)

>_ Kernel Systems Academy

Confirming Sector Boundary & ustar Header Rejections

learner@ksa: ~/gl-e00/m02-l03
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-l03
GL-E00 · Linux Host Workbench, POSIX Shell, Network Boot & Embedded C Style166/561

GL-E00 · 2.3 (m02-l03)

>_ Kernel Systems Academy

Confirming Sector Boundary & ustar Header Rejections

strace — learner@ksa: ~/gl-e00/m02-l03
learner@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 +++
GL-E00 · Linux Host Workbench, POSIX Shell, Network Boot & Embedded C Style167/561

GL-E00 · 2.3 (m02-l03)

>_ Kernel Systems Academy

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-ow…
GL-E00 · Linux Host Workbench, POSIX Shell, Network Boot & Embedded C Style168/561

GL-E00 · 2.3 (m02-l03)

>_ Kernel Systems Academy

Warning

warning: - Symptom: dd prints 680240 bytes copied and returns to the shell prompt in 0.02 s, you pull the USB SD reader out, and the board refuses to boot or prints EXT4-fs error: bad magic. - Root Cause: Without conv=fsync (or oflag=direct / sync), write(2) copies sectors into the Linux kernel dirty page cache in host RAM while USB mass-storage writeback is still in flight! - Fix: Always append conv=fsync to raw dd invocations, and after copying files to mounted FAT32/ext4 partitions run sync && sudo umount /dev/sdX* and wait for umount to return before unplugging.

GL-E00 · Linux Host Workbench, POSIX Shell, Network Boot & Embedded C Style169/561

GL-E00 · 2.3 (m02-l03)

>_ Kernel Systems Academy

Warning

warning: - Symptom: Partitioning succeeds in gdisk, then running dd if=u-boot-dtb.imx of=/dev/sdb bs=1K seek=1 causes fdisk -l to report GPT PMBR size mismatch / corrupt primary GPT table! - Root Cause: Standard GPT places its Primary Header at LBA 1 (0x200) and its 128-entry Partition Array across LBA 2..33 (0x400..0x43FF)—the exact 0x400 byte offset where i.MX6ULL requires its IVT! - Fix: Use MBR (label: dos in sfdisk) on i.MX6ULL SD/eMMC boot media, or if GPT is mandatory, relocate the GPT partition entry array (--move-main-table in sgdisk -j 2048) past U-Boot.

GL-E00 · Linux Host Workbench, POSIX Shell, Network Boot & Embedded C Style170/561

GL-E00 · 2.3 (m02-l03)

>_ Kernel Systems Academy

Guided Practice

  • Calculate the maximum u-boot-dtb.imx file size (in bytes and KiB) that fits between byte 0x400 (1 KiB…
GL-E00 · Linux Host Workbench, POSIX Shell, Network Boot & Embedded C Style171/561

GL-E00 · 2.3 (m02-l03)

>_ Kernel Systems Academy

Independent Practice

  • Complete labs/lab_m02_perm_partition_guard/ by repairing starter/core.c so all 5 TAP version 13 che…
GL-E00 · Linux Host Workbench, POSIX Shell, Network Boot & Embedded C Style172/561

GL-E00 · 2.3 (m02-l03)

>_ Kernel Systems Academy

Quick check

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?

Select an option or press R to reveal.

GL-E00 · Linux Host Workbench, POSIX Shell, Network Boot & Embedded C Style173/561

GL-E00 · 2.3 (m02-l03)

>_ Kernel Systems Academy

Quick check

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?

Select an option or press R to reveal.

GL-E00 · Linux Host Workbench, POSIX Shell, Network Boot & Embedded C Style174/561

GL-E00 · 2.3 (m02-l03)

>_ Kernel Systems Academy

Quick check

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?

Select an option or press R to reveal.

GL-E00 · Linux Host Workbench, POSIX Shell, Network Boot & Embedded C Style175/561

GL-E00 · 2.3 (m02-l03)

>_ Kernel Systems Academy

Lab: lab_m02_perm_partition_guard

  • Automated BSP image-creation pipelines must guarantee three non-negotiable safety invariants: never write r…

Verify: ./check.sh exits 0.

GL-E00 · Linux Host Workbench, POSIX Shell, Network Boot & Embedded C Style176/561

GL-E00 · 2.3 (m02-l03)

>_ Kernel Systems Academy

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.
GL-E00 · Linux Host Workbench, POSIX Shell, Network Boot & Embedded C Style177/561

GL-E00 · 2.3 (m02-l03)

>_ Kernel Systems Academy

Key takeaways

  • 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.
GL-E00 · Linux Host Workbench, POSIX Shell, Network Boot & Embedded C Style178/561

m03/

>_ Kernel Systems Academy

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.

  1. 3.1 dpkg State Databases, Signed APT Repositories & Sysroot pkg-config Isolation
  2. 3.2 Multi-Homed Subnet Routing & RFC 1350 TFTP Kernel Delivery
  3. 3.3 NFSv3/NFSv4 Root Filesystem Exports, Firmware Staging & Network Boot Studio

lab → Dual-NIC FIB Router, RFC 1350 TFTP Framing & NFSv3 Bootargs Verifier

GL-E00 · Linux Host Workbench, POSIX Shell, Network Boot & Embedded C Style179/561

GL-E00 · 3.1 (m03-l01)

>_ Kernel Systems Academy

dpkg State Databases, Signed APT Repositories & Sysroot pkg-config Isolation

free preview20 min

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.
GL-E00 · Linux Host Workbench, POSIX Shell, Network Boot & Embedded C Style180/561

GL-E00 · 3.1 (m03-l01)

>_ Kernel Systems Academy

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 developm…
GL-E00 · Linux Host Workbench, POSIX Shell, Network Boot & Embedded C Style181/561

GL-E00 · 3.1 (m03-l01)

>_ Kernel Systems Academy

How Host Package Managers Help—and Quietly Sabotage—Cross-Compilation

  • Two traps hit embedded engineers immediately.
GL-E00 · Linux Host Workbench, POSIX Shell, Network Boot & Embedded C Style182/561

GL-E00 · 3.1 (m03-l01)

>_ Kernel Systems Academy

How Host Package Managers Help—and Quietly Sabotage—Cross-Compilation

fig_m03_l01_a.svg

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.

GL-E00 · Linux Host Workbench, POSIX Shell, Network Boot & Embedded C Style183/561

GL-E00 · 3.1 (m03-l01)

>_ Kernel Systems Academy

Mental model

note: 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!

GL-E00 · Linux Host Workbench, POSIX Shell, Network Boot & Embedded C Style184/561

GL-E00 · 3.1 (m03-l01)

>_ Kernel Systems Academy

Advisory Inode Lock (flock) and PKG_CONFIG_LIBDIR vs PKG_CONFIG_PATH

definition: 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.

GL-E00 · Linux Host Workbench, POSIX Shell, Network Boot & Embedded C Style185/561

GL-E00 · 3.1 (m03-l01)

>_ Kernel Systems Academy

How Host Package Managers Help—and Quietly Sabotage—Cross-Compilation

Use dpkg -S to identify which package owns a header or binary and dpkg -L to inspect installed utilities like mkimage.

Never rm dpkg locks; use fuser + dpkg --configure -a and PKG_CONFIG_LIBDIR.

GL-E00 · Linux Host Workbench, POSIX Shell, Network Boot & Embedded C Style186/561

GL-E00 · 3.1 (m03-l01)

>_ Kernel Systems Academy

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:…
GL-E00 · Linux Host Workbench, POSIX Shell, Network Boot & Embedded C Style187/561

GL-E00 · 3.1 (m03-l01)

>_ Kernel Systems Academy

Inside .deb Archives, flock() Lifetimes & Cross-Sysroot Flag Rewriting

  • Now trace what happens when cross-compiling an ALSA or DRM application for ARMv7-A against a staged s…
GL-E00 · Linux Host Workbench, POSIX Shell, Network Boot & Embedded C Style188/561

GL-E00 · 3.1 (m03-l01)

>_ Kernel Systems Academy

Inside .deb Archives, flock() Lifetimes & Cross-Sysroot Flag Rewriting

fig_m03_l01_b.svg

Figure 3.1b: Combining PKG_CONFIG_LIBDIR (search isolation) with PKG_CONFIG_SYSROOT_DIR (prefix rewriting) guarantees 100% EM_ARM header/library purity.

GL-E00 · Linux Host Workbench, POSIX Shell, Network Boot & Embedded C Style189/561

GL-E00 · 3.1 (m03-l01)

>_ Kernel Systems Academy

arm-pkg-config

learner@ksa: ~/gl-e00/m03-l01
learner@ksa:~/gl-e00/m03-l01#!/usr/bin/env bashset -euo pipefail : "${KSA_ARM_SYSROOT:?Set KSA_ARM_SYSROOT to your staged ARMv7 rootfs path}" unset PKG_CONFIG_PATHexport 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 "$@"learner@ksa:~/gl-e00/m03-l01
GL-E00 · Linux Host Workbench, POSIX Shell, Network Boot & Embedded C Style190/561

GL-E00 · 3.1 (m03-l01)

>_ Kernel Systems Academy

dpkg

dpkg(1) at a glance — GL-E00
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                     m03-l01                     dpkg(1) GL-E00 quick reference · full manual page: man 1 dpkg 
GL-E00 · Linux Host Workbench, POSIX Shell, Network Boot & Embedded C Style191/561

GL-E00 · 3.1 (m03-l01)

>_ Kernel Systems Academy

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 desc…
GL-E00 · Linux Host Workbench, POSIX Shell, Network Boot & Embedded C Style192/561

GL-E00 · 3.1 (m03-l01)

>_ Kernel Systems Academy

Testing Kernel flock() Contention and Sysroot Flag Isolation in C11

  • Next, rewrite_and_audit_cflags() models PKG_CONFIG_SYSROOT_DIR rewriting and inspects compiler/linker t…
GL-E00 · Linux Host Workbench, POSIX Shell, Network Boot & Embedded C Style193/561

GL-E00 · 3.1 (m03-l01)

>_ Kernel Systems Academy

verify.c

learner@ksa: ~/gl-e00/m03-l01
learner@ksa:~/gl-e00/m03-l01$ bat 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)) {
GL-E00 · Linux Host Workbench, POSIX Shell, Network Boot & Embedded C Style194/561

GL-E00 · 3.1 (m03-l01)

>_ Kernel Systems Academy

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…
GL-E00 · Linux Host Workbench, POSIX Shell, Network Boot & Embedded C Style195/561

GL-E00 · 3.1 (m03-l01)

>_ Kernel Systems Academy

Observing flock(LOCK_EX|LOCK_NB) = -1 EAGAIN in strace

learner@ksa: ~/gl-e00/m03-l01
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-l01
GL-E00 · Linux Host Workbench, POSIX Shell, Network Boot & Embedded C Style196/561

GL-E00 · 3.1 (m03-l01)

>_ Kernel Systems Academy

Observing flock(LOCK_EX|LOCK_NB) = -1 EAGAIN in strace

strace — learner@ksa: ~/gl-e00/m03-l01
learner@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 +++
GL-E00 · Linux Host Workbench, POSIX Shell, Network Boot & Embedded C Style197/561

GL-E00 · 3.1 (m03-l01)

>_ Kernel Systems Academy

Multiarch Conflicts and Deprecated apt-key Anti-Patterns

  • Keeping host package management clean and cross-build pkg-config strictly fenced inside $SYSROOT preven…
GL-E00 · Linux Host Workbench, POSIX Shell, Network Boot & Embedded C Style198/561

GL-E00 · 3.1 (m03-l01)

>_ Kernel Systems Academy

Warning

warning: - Symptom: apt update prints Key is stored in legacy trusted.gpg keyring or accepts unsigned Packages files over plain HTTP. - Root Cause: [trusted=yes] disables GPG verification completely, while /etc/apt/trusted.gpg trusts a third-party vendor's key to sign packages for every repository on the system (including linux-image-generic!). - Fix: Place the dearmored .gpg key in /etc/apt/keyrings/<vendor>.gpg (0644) and scope it strictly inside that single .sources entry using Signed-By: /etc/apt/keyrings/<vendor>.gpg.

GL-E00 · Linux Host Workbench, POSIX Shell, Network Boot & Embedded C Style199/561

GL-E00 · 3.1 (m03-l01)

>_ Kernel Systems Academy

Warning

warning: - Symptom: You pass --host=arm-linux-gnueabihf to ./configure, yet the build still pulls /usr/include from the x86_64 host. - Root Cause: Autotools looks for arm-linux-gnueabihf-pkg-config first; if no prefixed wrapper exists on PATH, it falls back to bare host pkg-config with default host PKG_CONFIG_LIBDIR! - Fix: Either save our arm-pkg-config wrapper onto PATH named arm-linux-gnueabihf-pkg-config (chmod 0755), or export PKG_CONFIG=/path/to/arm-pkg-config explicitly.

GL-E00 · Linux Host Workbench, POSIX Shell, Network Boot & Embedded C Style200/561

GL-E00 · 3.1 (m03-l01)

>_ Kernel Systems Academy

Guided Practice

  • Modify verify.c to open lpath a third time (fd3) after unlinking lpath while fd2 still holds…
GL-E00 · Linux Host Workbench, POSIX Shell, Network Boot & Embedded C Style201/561

GL-E00 · 3.1 (m03-l01)

>_ Kernel Systems Academy

Independent Practice

  • Write a C11 parser for /var/lib/dpkg/status stanzas (Package:, Status:, Architecture:) that flags a…
GL-E00 · Linux Host Workbench, POSIX Shell, Network Boot & Embedded C Style202/561

GL-E00 · 3.1 (m03-l01)

>_ Kernel Systems Academy

Quick check

Why does running sudo rm /var/lib/dpkg/lock-frontend when apt says Could not get lock risk corrupting /var/lib/dpkg/status?

Select an option or press R to reveal.

GL-E00 · Linux Host Workbench, POSIX Shell, Network Boot & Embedded C Style203/561

GL-E00 · 3.1 (m03-l01)

>_ Kernel Systems Academy

Quick check

When cross-compiling an ARMv7-A user-space daemon against $SYSROOT, why must you set PKG_CONFIG_LIBDIR instead of only PKG_CONFIG_PATH?

Select an option or press R to reveal.

GL-E00 · Linux Host Workbench, POSIX Shell, Network Boot & Embedded C Style204/561

GL-E00 · 3.1 (m03-l01)

>_ Kernel Systems Academy

Quick check

Which command identifies the exact installed Debian/Ubuntu package that placed /usr/bin/mkimage onto your workstation?

Select an option or press R to reveal.

GL-E00 · Linux Host Workbench, POSIX Shell, Network Boot & Embedded C Style205/561

GL-E00 · 3.1 (m03-l01)

>_ Kernel Systems Academy

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.
GL-E00 · Linux Host Workbench, POSIX Shell, Network Boot & Embedded C Style206/561

GL-E00 · 3.1 (m03-l01)

>_ Kernel Systems Academy

Key takeaways

  • 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.
GL-E00 · Linux Host Workbench, POSIX Shell, Network Boot & Embedded C Style207/561

GL-E00 · 3.2 (m03-l02)

>_ Kernel Systems Academy

Multi-Homed Subnet Routing & RFC 1350 TFTP Kernel Delivery

free preview20 min

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.
GL-E00 · Linux Host Workbench, POSIX Shell, Network Boot & Embedded C Style208/561

GL-E00 · 3.2 (m03-l02)

>_ Kernel Systems Academy

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 worki…
GL-E00 · Linux Host Workbench, POSIX Shell, Network Boot & Embedded C Style209/561

GL-E00 · 3.2 (m03-l02)

>_ Kernel Systems Academy

Why Plugging In Your Board's Ethernet Cable Suddenly Breaks Host Internet

  • Why?
GL-E00 · Linux Host Workbench, POSIX Shell, Network Boot & Embedded C Style210/561

GL-E00 · 3.2 (m03-l02)

>_ Kernel Systems Academy

Why Plugging In Your Board's Ethernet Cable Suddenly Breaks Host Internet

  • Adding a fake gateway on the wired bench dongle installs default via 192.168.10.1 metric 100, routing all…
GL-E00 · Linux Host Workbench, POSIX Shell, Network Boot & Embedded C Style211/561

GL-E00 · 3.2 (m03-l02)

>_ Kernel Systems Academy

Why Plugging In Your Board's Ethernet Cable Suddenly Breaks Host Internet

fig_m03_l02_a.svg

Figure 3.2a: An isolated point-to-point or bench-switch subnet needs only an on-link /24 prefix (ARP), never a default gateway.

GL-E00 · Linux Host Workbench, POSIX Shell, Network Boot & Embedded C Style212/561

GL-E00 · 3.2 (m03-l02)

>_ Kernel Systems Academy

Mental model

note: 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!

GL-E00 · Linux Host Workbench, POSIX Shell, Network Boot & Embedded C Style213/561

GL-E00 · 3.2 (m03-l02)

>_ Kernel Systems Academy

RFC 1350 Trivial File Transfer Protocol (TFTP) Lockstep Framing

definition: 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.

GL-E00 · Linux Host Workbench, POSIX Shell, Network Boot & Embedded C Style214/561

GL-E00 · 3.2 (m03-l02)

>_ Kernel Systems Academy

Why Plugging In Your Board's Ethernet Cable Suddenly Breaks Host Internet

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.

Omit gateway on bench NICs, pass bare names to --secure tftpd, and separate DTB by 40 MiB.

GL-E00 · Linux Host Workbench, POSIX Shell, Network Boot & Embedded C Style215/561

GL-E00 · 3.2 (m03-l02)

>_ Kernel Systems Academy

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.
GL-E00 · Linux Host Workbench, POSIX Shell, Network Boot & Embedded C Style216/561

GL-E00 · 3.2 (m03-l02)

>_ Kernel Systems Academy

RFC 1350 Wire Bytes, Exact-512B EOF Edge Case & DDR3 Load Map

  • What if board.dtb is exactly 32,768 bytes (64 * 512, size % 512 == 0)?
GL-E00 · Linux Host Workbench, POSIX Shell, Network Boot & Embedded C Style217/561

GL-E00 · 3.2 (m03-l02)

>_ Kernel Systems Academy

RFC 1350 Wire Bytes, Exact-512B EOF Edge Case & DDR3 Load Map

fig_m03_l02_b.svg

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.

GL-E00 · Linux Host Workbench, POSIX Shell, Network Boot & Embedded C Style218/561

GL-E00 · 3.2 (m03-l02)

>_ Kernel Systems Academy

99-bench-dual-nic.yaml

learner@ksa: ~/gl-e00/m03-l02
learner@ksa:~/gl-e00/m03-l02$ bat 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
GL-E00 · Linux Host Workbench, POSIX Shell, Network Boot & Embedded C Style219/561

GL-E00 · 3.2 (m03-l02)

>_ Kernel Systems Academy

in.tftpd

in.tftpd(8) at a glance — GL-E00
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                   m03-l02                   in.tftpd(8) GL-E00 quick reference · full manual page: man 8 in.tftpd 
GL-E00 · Linux Host Workbench, POSIX Shell, Network Boot & Embedded C Style220/561

GL-E00 · 3.2 (m03-l02)

>_ Kernel Systems Academy

Simulating Kernel FIB Longest-Prefix Lookup and RFC 1350 Framing in C11

  • In verify.c, we build two deterministic verifiers in ISO C11.
GL-E00 · Linux Host Workbench, POSIX Shell, Network Boot & Embedded C Style221/561

GL-E00 · 3.2 (m03-l02)

>_ Kernel Systems Academy

Simulating Kernel FIB Longest-Prefix Lookup and RFC 1350 Framing in C11

  • Second, run_tftp_codec() encodes a real big-endian RFC 1350 RRQ + DATA/ACK transfer for a 1,024-b…
GL-E00 · Linux Host Workbench, POSIX Shell, Network Boot & Embedded C Style222/561

GL-E00 · 3.2 (m03-l02)

>_ Kernel Systems Academy

verify.c

learner@ksa: ~/gl-e00/m03-l02
learner@ksa:~/gl-e00/m03-l02$ bat 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) {
GL-E00 · Linux Host Workbench, POSIX Shell, Network Boot & Embedded C Style223/561

GL-E00 · 3.2 (m03-l02)

>_ Kernel Systems Academy

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…
GL-E00 · Linux Host Workbench, POSIX Shell, Network Boot & Embedded C Style224/561

GL-E00 · 3.2 (m03-l02)

>_ Kernel Systems Academy

Verifying FIB Selection, 0-Byte TFTP EOF & DDR3 Separation

learner@ksa: ~/gl-e00/m03-l02
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-l02
GL-E00 · Linux Host Workbench, POSIX Shell, Network Boot & Embedded C Style225/561

GL-E00 · 3.2 (m03-l02)

>_ Kernel Systems Academy

Verifying FIB Selection, 0-Byte TFTP EOF & DDR3 Separation

strace — learner@ksa: ~/gl-e00/m03-l02
learner@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 +++
GL-E00 · Linux Host Workbench, POSIX Shell, Network Boot & Embedded C Style226/561

GL-E00 · 3.2 (m03-l02)

>_ Kernel Systems Academy

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…
GL-E00 · Linux Host Workbench, POSIX Shell, Network Boot & Embedded C Style227/561

GL-E00 · 3.2 (m03-l02)

>_ Kernel Systems Academy

Warning

warning: - Symptom: tcpdump shows RRQ arriving on UDP/69 and in.tftpd sending DATA block 1 from UDP/53104, yet ACK block 1 from the board is dropped by the host (ICMP port unreachable). - Root Cause: Because RFC 1350 switches from UDP/69 to an ephemeral server port (TID) on the first reply, a stateless firewall rule allowing only port 69 drops incoming ACK packets to 53104 unless nf_conntrack_tftp or 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).

GL-E00 · Linux Host Workbench, POSIX Shell, Network Boot & Embedded C Style228/561

GL-E00 · 3.2 (m03-l02)

>_ Kernel Systems Academy

Warning

warning: - Symptom: tftp 0x80800000 zImage succeeds, then bootm 0x80800000 - 0x83000000 fails with Wrong Image Format for bootm command / ERROR: can't get kernel image!. - Root Cause: bootm expects a legacy 64-byte mkimage uImage header (0x27051956 magic) or FIT image, whereas Kbuild make zImage produces a self-decompressing ARMv7 zImage (0x016F2818 magic at 0x24). - Fix: Use bootz 0x80800000 - 0x83000000 for ARMv7-A zImage (booti is for 64-bit ARM64 Image, and bootm is for uImage / FIT .itb images).

GL-E00 · Linux Host Workbench, POSIX Shell, Network Boot & Embedded C Style229/561

GL-E00 · 3.2 (m03-l02)

>_ Kernel Systems Academy

Guided Practice

  • Extend simulate_tftp_blocks() in verify.c to parse the RFC 1350 blksize option extension (RFC 2348, e…
GL-E00 · Linux Host Workbench, POSIX Shell, Network Boot & Embedded C Style230/561

GL-E00 · 3.2 (m03-l02)

>_ Kernel Systems Academy

Independent Practice

  • Add a check to fib_lookup() that scans the entire routing table before lookup and returns an error if two…
GL-E00 · Linux Host Workbench, POSIX Shell, Network Boot & Embedded C Style231/561

GL-E00 · 3.2 (m03-l02)

>_ Kernel Systems Academy

Quick check

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?

Select an option or press R to reveal.

GL-E00 · Linux Host Workbench, POSIX Shell, Network Boot & Embedded C Style232/561

GL-E00 · 3.2 (m03-l02)

>_ Kernel Systems Academy

Quick check

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

Select an option or press R to reveal.

GL-E00 · Linux Host Workbench, POSIX Shell, Network Boot & Embedded C Style233/561

GL-E00 · 3.2 (m03-l02)

>_ Kernel Systems Academy

Quick check

With TFTP_DIRECTORY="/srv/tftp" and TFTP_OPTIONS="--secure" in /etc/default/tftpd-hpa, which U-Boot command fetches /srv/tftp/zImage into DDR3?

Select an option or press R to reveal.

GL-E00 · Linux Host Workbench, POSIX Shell, Network Boot & Embedded C Style234/561

GL-E00 · 3.2 (m03-l02)

>_ Kernel Systems Academy

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.
GL-E00 · Linux Host Workbench, POSIX Shell, Network Boot & Embedded C Style235/561

GL-E00 · 3.2 (m03-l02)

>_ Kernel Systems Academy

Key takeaways

  • 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.
GL-E00 · Linux Host Workbench, POSIX Shell, Network Boot & Embedded C Style236/561

GL-E00 · 3.3 (m03-l03)

>_ Kernel Systems Academy

NFSv3/NFSv4 Root Filesystem Exports, Firmware Staging & Network Boot Studio

free preview20 minlab lab_m03_tftp_nfs_bootargs

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.
GL-E00 · Linux Host Workbench, POSIX Shell, Network Boot & Embedded C Style237/561

GL-E00 · 3.3 (m03-l03)

>_ Kernel Systems Academy

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 min…
GL-E00 · Linux Host Workbench, POSIX Shell, Network Boot & Embedded C Style238/561

GL-E00 · 3.3 (m03-l03)

>_ Kernel Systems Academy

Three-Second Driver Turnaround—and Why Modern Ubuntu Rejects Default nfsroot

  • Two notorious bugs trip up engineers on Ubuntu 22.04 and 24.04 LTS.
GL-E00 · Linux Host Workbench, POSIX Shell, Network Boot & Embedded C Style239/561

GL-E00 · 3.3 (m03-l03)

>_ Kernel Systems Academy

Three-Second Driver Turnaround—and Why Modern Ubuntu Rejects Default nfsroot

fig_m03_l03_a.svg

Figure 3.3a: Both sides of the wire must agree on protocol version (vers=3,tcp), subnet CIDR without spaces, and UID 0 preservation (no_root_squash).

GL-E00 · Linux Host Workbench, POSIX Shell, Network Boot & Embedded C Style240/561

GL-E00 · 3.3 (m03-l03)

>_ Kernel Systems Academy

Mental model

note: 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)!

GL-E00 · Linux Host Workbench, POSIX Shell, Network Boot & Embedded C Style241/561

GL-E00 · 3.3 (m03-l03)

>_ Kernel Systems Academy

Kernel IP Autoconfiguration (ip= 7-Tuple) and NFS Root Squashing

definition: 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.

GL-E00 · Linux Host Workbench, POSIX Shell, Network Boot & Embedded C Style242/561

GL-E00 · 3.3 (m03-l03)

>_ Kernel Systems Academy

Three-Second Driver Turnaround—and Why Modern Ubuntu Rejects Default nfsroot

Extract your target rootfs archive into /srv/nfs/rootfs using sudo tar --numeric-owner so UID 0 ownership is intact on disk.

Enable [nfsd] vers3=y, write cidr(rw,no_root_squash), and pin nfsroot=...,vers=3,tcp.

GL-E00 · Linux Host Workbench, POSIX Shell, Network Boot & Embedded C Style243/561

GL-E00 · 3.3 (m03-l03)

>_ Kernel Systems Academy

Inside /etc/exports Parsing, bootargs Tokenization & Deployment Trade-Offs

  • Why do embedded kernels prefer NFSv3 over NFSv4 for root=/dev/nfs?
GL-E00 · Linux Host Workbench, POSIX Shell, Network Boot & Embedded C Style244/561

GL-E00 · 3.3 (m03-l03)

>_ Kernel Systems Academy

Inside /etc/exports Parsing, bootargs Tokenization & Deployment Trade-Offs

  • Choosing the right transport across the engineering lifecycle is equally straightforward: use **TFTP + NFSv…
GL-E00 · Linux Host Workbench, POSIX Shell, Network Boot & Embedded C Style245/561

GL-E00 · 3.3 (m03-l03)

>_ Kernel Systems Academy

Inside /etc/exports Parsing, bootargs Tokenization & Deployment Trade-Offs

fig_m03_l03_b.svg

Figure 3.3b: Cross-checking /etc/exports against U-Boot bootargs catches path mismatches, missing vers=3,tcp, and subnet typos before power-on.

GL-E00 · Linux Host Workbench, POSIX Shell, Network Boot & Embedded C Style246/561

GL-E00 · 3.3 (m03-l03)

>_ Kernel Systems Academy

nfs_bench_setup.conf

learner@ksa: ~/gl-e00/m03-l03
learner@ksa:~/gl-e00/m03-l03$ bat 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'
GL-E00 · Linux Host Workbench, POSIX Shell, Network Boot & Embedded C Style247/561

GL-E00 · 3.3 (m03-l03)

>_ Kernel Systems Academy

exports

exports(5) at a glance — GL-E00
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                   m03-l03                    exports(5) GL-E00 quick reference · full manual page: man 5 exports 
GL-E00 · Linux Host Workbench, POSIX Shell, Network Boot & Embedded C Style248/561

GL-E00 · 3.3 (m03-l03)

>_ Kernel Systems Academy

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 cr…
GL-E00 · Linux Host Workbench, POSIX Shell, Network Boot & Embedded C Style249/561

GL-E00 · 3.3 (m03-l03)

>_ Kernel Systems Academy

Cross-Checking /etc/exports Against Kernel nfsroot= bootargs in C11

  • Notice how bitwise subnet verification ((srv_ip & mask) == (net_ip & mask)) converts dotted-quad IPv4 str…
GL-E00 · Linux Host Workbench, POSIX Shell, Network Boot & Embedded C Style250/561

GL-E00 · 3.3 (m03-l03)

>_ Kernel Systems Academy

verify.c

learner@ksa: ~/gl-e00/m03-l03
learner@ksa:~/gl-e00/m03-l03$ bat 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;    }
GL-E00 · Linux Host Workbench, POSIX Shell, Network Boot & Embedded C Style251/561

GL-E00 · 3.3 (m03-l03)

>_ Kernel Systems Academy

Confirming /etc/exports Whitespace & vers=3,tcp Rejections

  • Inspect the execution output: the matched /etc/exports + vers=3,tcp bootargs contract returns `valid=…
GL-E00 · Linux Host Workbench, POSIX Shell, Network Boot & Embedded C Style252/561

GL-E00 · 3.3 (m03-l03)

>_ Kernel Systems Academy

Confirming /etc/exports Whitespace & vers=3,tcp Rejections

  • While this host C11 verifier proves lexical and subnet consistency across host and U-Boot configuration f…
GL-E00 · Linux Host Workbench, POSIX Shell, Network Boot & Embedded C Style253/561

GL-E00 · 3.3 (m03-l03)

>_ Kernel Systems Academy

Confirming /etc/exports Whitespace & vers=3,tcp Rejections

learner@ksa: ~/gl-e00/m03-l03
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-l03
GL-E00 · Linux Host Workbench, POSIX Shell, Network Boot & Embedded C Style254/561

GL-E00 · 3.3 (m03-l03)

>_ Kernel Systems Academy

Confirming /etc/exports Whitespace & vers=3,tcp Rejections

strace — learner@ksa: ~/gl-e00/m03-l03
learner@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 +++
GL-E00 · Linux Host Workbench, POSIX Shell, Network Boot & Embedded C Style255/561

GL-E00 · 3.3 (m03-l03)

>_ Kernel Systems Academy

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…
GL-E00 · Linux Host Workbench, POSIX Shell, Network Boot & Embedded C Style256/561

GL-E00 · 3.3 (m03-l03)

>_ Kernel Systems Academy

Warning

warning: - Symptom: Kernel prints VFS: Mounted root (nfs filesystem) on device 0:15, /sbin/init starts services, and two seconds later the console freezes with nfs: server 192.168.10.10 not responding, still trying! - Root Cause: A user-space network daemon inside the target rootfs (connman, NetworkManager, or ifupdown DHCP on eth0) flushed eth0'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 ignore eth0 (ConnMan -I eth0 or CriticalConnection=true / KeepConfiguration=yes in systemd-networkd).

GL-E00 · Linux Host Workbench, POSIX Shell, Network Boot & Embedded C Style257/561

GL-E00 · 3.3 (m03-l03)

>_ Kernel Systems Academy

Warning

warning: - Symptom: You opened TCP/2049 (nfs) in ufw, yet U-Boot TFTP succeeds and kernel NFSv3 root mount times out. - Root Cause: Unlike NFSv4 (single port 2049), NFSv3 first queries rpcbind (portmapper on TCP/UDP 111) to discover rpc.mountd's port (MOUNTv3 handshake) before opening TCP/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 static rpc.mountd port in /etc/nfs.conf ([mountd] port=20048) alongside 111 and 2049.

GL-E00 · Linux Host Workbench, POSIX Shell, Network Boot & Embedded C Style258/561

GL-E00 · 3.3 (m03-l03)

>_ Kernel Systems Academy

Guided Practice

  • Extend audit_nfs_contract() in verify.c to parse the ip= 7-tuple (ip=<client>:<srv>:<gw>:<mask>:...…
GL-E00 · Linux Host Workbench, POSIX Shell, Network Boot & Embedded C Style259/561

GL-E00 · 3.3 (m03-l03)

>_ Kernel Systems Academy

Independent Practice

  • Open labs/lab_m03_tftp_nfs_bootargs/ and fix all three bugs in starter/core.c so sh check.sh passes `…
GL-E00 · Linux Host Workbench, POSIX Shell, Network Boot & Embedded C Style260/561

GL-E00 · 3.3 (m03-l03)

>_ Kernel Systems Academy

Quick check

What does /srv/nfs/rootfs 192.168.10.0/24 (rw,sync,no_root_squash) (notice the space before () actually configure in /etc/exports?

Select an option or press R to reveal.

GL-E00 · Linux Host Workbench, POSIX Shell, Network Boot & Embedded C Style261/561

GL-E00 · 3.3 (m03-l03)

>_ Kernel Systems Academy

Quick check

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?

Select an option or press R to reveal.

GL-E00 · Linux Host Workbench, POSIX Shell, Network Boot & Embedded C Style262/561

GL-E00 · 3.3 (m03-l03)

>_ Kernel Systems Academy

Quick check

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?

Select an option or press R to reveal.

GL-E00 · Linux Host Workbench, POSIX Shell, Network Boot & Embedded C Style263/561

GL-E00 · 3.3 (m03-l03)

>_ Kernel Systems Academy

Lab: lab_m03_tftp_nfs_bootargs

  • A broken network-boot bench silently wastes hours of board bring-up: one stray gateway4 on the USB-Ethern…

Verify: ./check.sh exits 0.

GL-E00 · Linux Host Workbench, POSIX Shell, Network Boot & Embedded C Style264/561

GL-E00 · 3.3 (m03-l03)

>_ Kernel Systems Academy

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.
GL-E00 · Linux Host Workbench, POSIX Shell, Network Boot & Embedded C Style265/561

GL-E00 · 3.3 (m03-l03)

>_ Kernel Systems Academy

Key takeaways

  • 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.
GL-E00 · Linux Host Workbench, POSIX Shell, Network Boot & Embedded C Style266/561

m04/

>_ Kernel Systems Academy

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.

  1. 4.1 Indentation, Braces, Operator Spacing & Why-Not-How Comments
  2. 4.2 Snake-Case Naming, Antonym Symmetry, Static Linkage & Centralized goto Unwind
  3. 4.3 Single-Purpose Variables, Fixed-Width Types & Defensive do-while(0) Macros

lab → Kernel C11 Macro Safety, Static Linkage & LIFO Unwind Auditor

GL-E00 · Linux Host Workbench, POSIX Shell, Network Boot & Embedded C Style267/561

GL-E00 · 4.1 (m04-l01)

>_ Kernel Systems Academy

Indentation, Braces, Operator Spacing & Why-Not-How Comments

free preview20 min

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.
GL-E00 · Linux Host Workbench, POSIX Shell, Network Boot & Embedded C Style268/561

GL-E00 · 4.1 (m04-l01)

>_ Kernel Systems Academy

Visual Nesting Alarms and Asymmetric Brace Placement

  • Code inside a bootloader or Linux kernel driver is written once and audited hundreds of times during brin…
GL-E00 · Linux Host Workbench, POSIX Shell, Network Boot & Embedded C Style269/561

GL-E00 · 4.1 (m04-l01)

>_ Kernel Systems Academy

Visual Nesting Alarms and Asymmetric Brace Placement

  • The Linux kernel CodingStyle uses 8-column hard tabs ('\t') deliberately as a structural complexity…
GL-E00 · Linux Host Workbench, POSIX Shell, Network Boot & Embedded C Style270/561

GL-E00 · 4.1 (m04-l01)

>_ Kernel Systems Academy

Visual Nesting Alarms and Asymmetric Brace Placement

fig_m04_l01_a.svg

Figure 4.1a: 8-column tabs expose excessive cyclomatic nesting early so drivers refactor into flat guard clauses.

GL-E00 · Linux Host Workbench, POSIX Shell, Network Boot & Embedded C Style271/561

GL-E00 · 4.1 (m04-l01)

>_ Kernel Systems Academy

Mental model

note: 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.

GL-E00 · Linux Host Workbench, POSIX Shell, Network Boot & Embedded C Style272/561

GL-E00 · 4.1 (m04-l01)

>_ Kernel Systems Academy

8-Column Tab Complexity Alarm

definition: 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.

GL-E00 · Linux Host Workbench, POSIX Shell, Network Boot & Embedded C Style273/561

GL-E00 · 4.1 (m04-l01)

>_ Kernel Systems Academy

Visual Nesting Alarms and Asymmetric Brace Placement

Hard tabs advance to multiples of 8 columns, making >3 nested levels immediately obvious.

Use 8-col tabs, K&R control braces, identifier-bound *stars, and why-not-how comments.

GL-E00 · Linux Host Workbench, POSIX Shell, Network Boot & Embedded C Style274/561

GL-E00 · 4.1 (m04-l01)

>_ Kernel Systems Academy

Brace Geometry, Operator Spacing, and Fallthrough Discipline

  • Every token spacing rule in CodingStyle eliminates a concrete visual ambiguity.
GL-E00 · Linux Host Workbench, POSIX Shell, Network Boot & Embedded C Style275/561

GL-E00 · 4.1 (m04-l01)

>_ Kernel Systems Academy

Brace Geometry, Operator Spacing, and Fallthrough Discipline

  • In C grammar, the pointer * modifier binds to the declarator, not the type specifier.
GL-E00 · Linux Host Workbench, POSIX Shell, Network Boot & Embedded C Style276/561

GL-E00 · 4.1 (m04-l01)

>_ Kernel Systems Academy

Brace Geometry, Operator Spacing, and Fallthrough Discipline

fig_m04_l01_b.svg

Figure 4.1b: Declarator-bound stars and compiler-checked fallthrough attributes turn style rules into bug prevention.

GL-E00 · Linux Host Workbench, POSIX Shell, Network Boot & Embedded C Style277/561

GL-E00 · 4.1 (m04-l01)

>_ Kernel Systems Academy

coding_style_irq.c

learner@ksa: ~/gl-e00/m04-l01
learner@ksa:~/gl-e00/m04-l01$ bat 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
GL-E00 · Linux Host Workbench, POSIX Shell, Network Boot & Embedded C Style278/561

GL-E00 · 4.1 (m04-l01)

>_ Kernel Systems Academy

checkpatch.pl / CodingStyle

checkpatch.pl / CodingStyle(7) at a glance — GL-E00
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         m04-l01          checkpatch.pl / CodingStyle(7) GL-E00 quick reference · full manual page: man 7 checkpatch.pl / CodingStyle 
GL-E00 · Linux Host Workbench, POSIX Shell, Network Boot & Embedded C Style279/561

GL-E00 · 4.1 (m04-l01)

>_ Kernel Systems Academy

Host C11 Style Scanner for Tabs, Stars, and Fallthroughs

  • Before running scripts/checkpatch.pl against a full driver tree, understanding how each lexical check wor…
GL-E00 · Linux Host Workbench, POSIX Shell, Network Boot & Embedded C Style280/561

GL-E00 · 4.1 (m04-l01)

>_ Kernel Systems Academy

Host C11 Style Scanner for Tabs, Stars, and Fallthroughs

  • This host verification binary runs in unprivileged user space under gcc -std=c11 -Wall -Wextra -Werror an…
GL-E00 · Linux Host Workbench, POSIX Shell, Network Boot & Embedded C Style281/561

GL-E00 · 4.1 (m04-l01)

>_ Kernel Systems Academy

verify.c

learner@ksa: ~/gl-e00/m04-l01
learner@ksa:~/gl-e00/m04-l01$ bat 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;    };
GL-E00 · Linux Host Workbench, POSIX Shell, Network Boot & Embedded C Style282/561

GL-E00 · 4.1 (m04-l01)

>_ Kernel Systems Academy

Verifying Compiler Diagnostics and Tab-Stop Telemetry

  • Compiling verify.c under gcc -std=c11 -Wall -Wextra -Werror exercises GCC's built-in `-Wmisleading-inde…
GL-E00 · Linux Host Workbench, POSIX Shell, Network Boot & Embedded C Style283/561

GL-E00 · 4.1 (m04-l01)

>_ Kernel Systems Academy

Verifying Compiler Diagnostics and Tab-Stop Telemetry

  • Simultaneously, FLAWED_LINE flags leading-space indentation, sizeof ( spacing, and type-attached `char*…
GL-E00 · Linux Host Workbench, POSIX Shell, Network Boot & Embedded C Style284/561

GL-E00 · 4.1 (m04-l01)

>_ Kernel Systems Academy

Verifying Compiler Diagnostics and Tab-Stop Telemetry

learner@ksa: ~/gl-e00/m04-l01
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-l01
GL-E00 · Linux Host Workbench, POSIX Shell, Network Boot & Embedded C Style285/561

GL-E00 · 4.1 (m04-l01)

>_ Kernel Systems Academy

Verifying Compiler Diagnostics and Tab-Stop Telemetry

strace — learner@ksa: ~/gl-e00/m04-l01
learner@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 +++
GL-E00 · Linux Host Workbench, POSIX Shell, Network Boot & Embedded C Style286/561

GL-E00 · 4.1 (m04-l01)

>_ Kernel Systems Academy

Formatting Traps That Disguise Control-Flow and Type Bugs

  • Treat style conformance as a zero-noise baseline for code review.
GL-E00 · Linux Host Workbench, POSIX Shell, Network Boot & Embedded C Style287/561

GL-E00 · 4.1 (m04-l01)

>_ Kernel Systems Academy

Formatting Traps That Disguise Control-Flow and Type Bugs

  • Pair .editorconfig / .clang-format (UseTab: Always, IndentWidth: 8, TabWidth: 8) with compiler wa…
GL-E00 · Linux Host Workbench, POSIX Shell, Network Boot & Embedded C Style288/561

GL-E00 · 4.1 (m04-l01)

>_ Kernel Systems Academy

Warning

warning: - Symptom: Adding a pr_debug() trace line to an else clause causes the subsequent operational statement to execute unconditionally on both true and false paths. - Root Cause: Leaving one branch of an if/else unbraced when the sibling branch spans multiple lines invites human edit errors that GCC only catches if indentation happens to remain consistent. - Fix: Place K&R { ... } braces around every branch of an if/else if/else chain whenever any single branch requires more than one line or statement.

GL-E00 · Linux Host Workbench, POSIX Shell, Network Boot & Embedded C Style289/561

GL-E00 · 4.1 (m04-l01)

>_ Kernel Systems Academy

Warning

warning: - Symptom: Declaration uint8_t* rx_buf, tx_buf; fails with invalid type conversion or truncates a 32-bit buffer address into an 8-bit byte when assigning tx_buf. - Root Cause: C grammar binds * to the individual declarator (*rx_buf), not the base type (uint8_t), so tx_buf is silently allocated as a scalar uint8_t. - Fix: Always attach * to the variable identifier (uint8_t *rx_buf, *tx_buf;) and prefer one initialized pointer declaration per line.

GL-E00 · Linux Host Workbench, POSIX Shell, Network Boot & Embedded C Style290/561

GL-E00 · 4.1 (m04-l01)

>_ Kernel Systems Academy

Guided Practice

  • Extend scan_style_line() in verify.c to flag lines whose expanded visual_cols exceed 80 characters…
GL-E00 · Linux Host Workbench, POSIX Shell, Network Boot & Embedded C Style291/561

GL-E00 · 4.1 (m04-l01)

>_ Kernel Systems Academy

Guided Practice

  • Recompile with gcc -std=c11 -Wall -Wextra -Werror verify.c -o verify and test two inputs: a 92-column a…
GL-E00 · Linux Host Workbench, POSIX Shell, Network Boot & Embedded C Style292/561

GL-E00 · 4.1 (m04-l01)

>_ Kernel Systems Academy

Independent Practice

  • Write a multi-line scanner function check_switch_fallthrough(const char **lines, size_t n) that inspects…
GL-E00 · Linux Host Workbench, POSIX Shell, Network Boot & Embedded C Style293/561

GL-E00 · 4.1 (m04-l01)

>_ Kernel Systems Academy

Independent Practice

  • Verify your scanner against three synthetic switch blocks: a clean break;-terminated case, an empty sta…
GL-E00 · Linux Host Workbench, POSIX Shell, Network Boot & Embedded C Style294/561

GL-E00 · 4.1 (m04-l01)

>_ Kernel Systems Academy

Quick check

Why does Linux kernel CodingStyle specify 8-column hard tabs rather than 2-space indentation?

Select an option or press R to reveal.

GL-E00 · Linux Host Workbench, POSIX Shell, Network Boot & Embedded C Style295/561

GL-E00 · 4.1 (m04-l01)

>_ Kernel Systems Academy

Quick check

Which allocation pattern follows Linux kernel CodingStyle and survives changing the struct type of struct sai_priv *priv without introducing a heap size mismatch?

Select an option or press R to reveal.

GL-E00 · Linux Host Workbench, POSIX Shell, Network Boot & Embedded C Style296/561

GL-E00 · 4.1 (m04-l01)

>_ Kernel Systems Academy

Quick check

Why does CodingStyle permit a single-line pr_err("...") string literal to exceed 80 columns rather than breaking it into concatenated fragments?

Select an option or press R to reveal.

GL-E00 · Linux Host Workbench, POSIX Shell, Network Boot & Embedded C Style297/561

GL-E00 · 4.1 (m04-l01)

>_ Kernel Systems Academy

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).
GL-E00 · Linux Host Workbench, POSIX Shell, Network Boot & Embedded C Style298/561

GL-E00 · 4.1 (m04-l01)

>_ Kernel Systems Academy

Key takeaways

  • 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).
GL-E00 · Linux Host Workbench, POSIX Shell, Network Boot & Embedded C Style299/561

GL-E00 · 4.2 (m04-l02)

>_ Kernel Systems Academy

Snake-Case Naming, Antonym Symmetry, Static Linkage & Centralized goto Unwind

free preview25 min

What you'll learn

  • Enforce static internal linkage (STB_LOCAL) and subsystem-prefixed snake_case antonym 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 reverse LIFO order.
GL-E00 · Linux Host Workbench, POSIX Shell, Network Boot & Embedded C Style300/561

GL-E00 · 4.2 (m04-l02)

>_ Kernel Systems Academy

Symbol Namespace Isolation and Antonym Lifecycle Symmetry

  • In a monolithic Linux kernel image or multi-file embedded firmware archive, all non-static functions an…
GL-E00 · Linux Host Workbench, POSIX Shell, Network Boot & Embedded C Style301/561

GL-E00 · 4.2 (m04-l02)

>_ Kernel Systems Academy

Symbol Namespace Isolation and Antonym Lifecycle Symmetry

  • Equally critical is antonym symmetry across resource pairs: alloc pairs with free, register with `unr…
GL-E00 · Linux Host Workbench, POSIX Shell, Network Boot & Embedded C Style302/561

GL-E00 · 4.2 (m04-l02)

>_ Kernel Systems Academy

Symbol Namespace Isolation and Antonym Lifecycle Symmetry

fig_m04_l02_a.svg

Figure 4.2a: Forward-only goto labels unwind strictly the prefix of resources that succeeded before the error.

GL-E00 · Linux Host Workbench, POSIX Shell, Network Boot & Embedded C Style303/561

GL-E00 · 4.2 (m04-l02)

>_ Kernel Systems Academy

Mental model

note: 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.

GL-E00 · Linux Host Workbench, POSIX Shell, Network Boot & Embedded C Style304/561

GL-E00 · 4.2 (m04-l02)

>_ Kernel Systems Academy

Centralized LIFO goto Unwind

definition: 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.

GL-E00 · Linux Host Workbench, POSIX Shell, Network Boot & Embedded C Style305/561

GL-E00 · 4.2 (m04-l02)

>_ Kernel Systems Academy

Symbol Namespace Isolation and Antonym Lifecycle Symmetry

STB_LOCAL symbols never collide across driver objects and let GCC inline single-caller helpers.

Mark internal helpers static (STB_LOCAL) and unwind partial probes in strict LIFO order.

GL-E00 · Linux Host Workbench, POSIX Shell, Network Boot & Embedded C Style306/561

GL-E00 · 4.2 (m04-l02)

>_ Kernel Systems Academy

ELF Symbol Tables and Reverse-Cascade Error Labels

  • Inspecting a compiled object with nm or readelf -s reveals the binary consequence of static: global f…
GL-E00 · Linux Host Workbench, POSIX Shell, Network Boot & Embedded C Style307/561

GL-E00 · 4.2 (m04-l02)

>_ Kernel Systems Academy

ELF Symbol Tables and Reverse-Cascade Error Labels

  • Inside probe(), name each unwind label after the action it performs (err_free_ring:, `err_unmap_io:…
GL-E00 · Linux Host Workbench, POSIX Shell, Network Boot & Embedded C Style308/561

GL-E00 · 4.2 (m04-l02)

>_ Kernel Systems Academy

ELF Symbol Tables and Reverse-Cascade Error Labels

fig_m04_l02_b.svg

Figure 4.2b: Action-named labels (err_free_ring) verify at the jump site which live resource unrolls first.

GL-E00 · Linux Host Workbench, POSIX Shell, Network Boot & Embedded C Style309/561

GL-E00 · 4.2 (m04-l02)

>_ Kernel Systems Academy

probe_lifo_unwind.c

learner@ksa: ~/gl-e00/m04-l02
learner@ksa:~/gl-e00/m04-l02$ bat 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);
GL-E00 · Linux Host Workbench, POSIX Shell, Network Boot & Embedded C Style310/561

GL-E00 · 4.2 (m04-l02)

>_ Kernel Systems Academy

nm(1) / CodingStyle Ch.4,6,7

nm(1) / CodingStyle Ch.4,6,7(1) at a glance — GL-E00
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         m04-l02         nm(1) / CodingStyle Ch.4,6,7(1) GL-E00 quick reference · full manual page: man 1 nm(1) / CodingStyle Ch.4,6,7 
GL-E00 · Linux Host Workbench, POSIX Shell, Network Boot & Embedded C Style311/561

GL-E00 · 4.2 (m04-l02)

>_ Kernel Systems Academy

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 determi…
GL-E00 · Linux Host Workbench, POSIX Shell, Network Boot & Embedded C Style312/561

GL-E00 · 4.2 (m04-l02)

>_ Kernel Systems Academy

Fault-Injecting LIFO Unwind Versus Early-Return Leaks in C11

  • We sweep fail_step from 1 through 4 plus the 0 (no-fault) path, contrasting a naive early-return fu…
GL-E00 · Linux Host Workbench, POSIX Shell, Network Boot & Embedded C Style313/561

GL-E00 · 4.2 (m04-l02)

>_ Kernel Systems Academy

verify.c

learner@ksa: ~/gl-e00/m04-l02
learner@ksa:~/gl-e00/m04-l02$ bat 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;    };
GL-E00 · Linux Host Workbench, POSIX Shell, Network Boot & Embedded C Style314/561

GL-E00 · 4.2 (m04-l02)

>_ Kernel Systems Academy

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 dec…
GL-E00 · Linux Host Workbench, POSIX Shell, Network Boot & Embedded C Style315/561

GL-E00 · 4.2 (m04-l02)

>_ Kernel Systems Academy

Confirming Zero Leaks Across All Four Fault Injection Points

  • In the execution output, FAULT_STEP=1..4 releases 0, 1, 2, 3 resources respectively, always terminating…
GL-E00 · Linux Host Workbench, POSIX Shell, Network Boot & Embedded C Style316/561

GL-E00 · 4.2 (m04-l02)

>_ Kernel Systems Academy

Confirming Zero Leaks Across All Four Fault Injection Points

learner@ksa: ~/gl-e00/m04-l02
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-l02
GL-E00 · Linux Host Workbench, POSIX Shell, Network Boot & Embedded C Style317/561

GL-E00 · 4.2 (m04-l02)

>_ Kernel Systems Academy

Confirming Zero Leaks Across All Four Fault Injection Points

strace — learner@ksa: ~/gl-e00/m04-l02
learner@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 +++
GL-E00 · Linux Host Workbench, POSIX Shell, Network Boot & Embedded C Style318/561

GL-E00 · 4.2 (m04-l02)

>_ Kernel Systems Academy

Classic Unwind Ordering and Missing-Return Disasters

  • A driver's remove() callback must mirror the exact same LIFO order as probe()'s err_* tail, plu…
GL-E00 · Linux Host Workbench, POSIX Shell, Network Boot & Embedded C Style319/561

GL-E00 · 4.2 (m04-l02)

>_ Kernel Systems Academy

Classic Unwind Ordering and Missing-Return Disasters

  • In modern Linux kernel 6.12 code, devm_* managed APIs and <linux/cleanup.h> (guard(mutex)) automate…
GL-E00 · Linux Host Workbench, POSIX Shell, Network Boot & Embedded C Style320/561

GL-E00 · 4.2 (m04-l02)

>_ Kernel Systems Academy

Warning

warning: - Symptom: probe() initializes hardware cleanly and returns 0, yet the device immediately faults or hangs on first open() because clocks are off and buffers are freed. - Root Cause: Omitting return 0; before err_free_ring: causes the happy path (where rc == 0 from the last helper call!) to fall straight through the cleanup cascade and still return rc (0)! - Fix: Always place an explicit return 0; separated by a blank line directly above the top err_* label, and verify happy-path live_mask state in unit tests.

GL-E00 · Linux Host Workbench, POSIX Shell, Network Boot & Embedded C Style321/561

GL-E00 · 4.2 (m04-l02)

>_ Kernel Systems Academy

Warning

warning: - Symptom: Unloading a module or failing late in probe() triggers an imprecise external abort on ARMv7-A or a use-after-free inside the interrupt handler. - Root Cause: Disabling peripheral clocks before unmapping/stopping registers, or freeing rx_ring before calling free_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.

GL-E00 · Linux Host Workbench, POSIX Shell, Network Boot & Embedded C Style322/561

GL-E00 · 4.2 (m04-l02)

>_ Kernel Systems Academy

Guided Practice

  • Add a fifth resource RES_DEVNODE = 1U << 4 (cdev_add) at the end of probe_lifo() in verify.c, along…
GL-E00 · Linux Host Workbench, POSIX Shell, Network Boot & Embedded C Style323/561

GL-E00 · 4.2 (m04-l02)

>_ Kernel Systems Academy

Guided Practice

  • Verify that fail_step = 5 jumps to a new err_unreg_irq: label above err_free_ring:, releasing 4 res…
GL-E00 · Linux Host Workbench, POSIX Shell, Network Boot & Embedded C Style324/561

GL-E00 · 4.2 (m04-l02)

>_ Kernel Systems Academy

Independent Practice

  • Temporarily remove static from probe_lifo in verify.c and run `gcc -std=c11 -Wall -Wextra -Wmissing-p…
GL-E00 · Linux Host Workbench, POSIX Shell, Network Boot & Embedded C Style325/561

GL-E00 · 4.2 (m04-l02)

>_ Kernel Systems Academy

Independent Practice

  • Confirm that record_rel and probe_lifo carry lowercase t (STB_LOCAL) while only main carries uppe…
GL-E00 · Linux Host Workbench, POSIX Shell, Network Boot & Embedded C Style326/561

GL-E00 · 4.2 (m04-l02)

>_ Kernel Systems Academy

Quick check

In probe() acquiring (1) clk_enable -> (2) ioremap -> (3) dma_alloc -> (4) request_irq, which label must a failure in request_irq() jump to?

Select an option or press R to reveal.

GL-E00 · Linux Host Workbench, POSIX Shell, Network Boot & Embedded C Style327/561

GL-E00 · 4.2 (m04-l02)

>_ Kernel Systems Academy

Quick check

What is the binary effect in the ELF object file when you mark a file-private C helper static?

Select an option or press R to reveal.

GL-E00 · Linux Host Workbench, POSIX Shell, Network Boot & Embedded C Style328/561

GL-E00 · 4.2 (m04-l02)

>_ Kernel Systems Academy

Quick check

Retrieval check from Lesson 4.1: Why should err_* labels be named err_free_ring: rather than numbered err1:, err2:?

Select an option or press R to reveal.

GL-E00 · Linux Host Workbench, POSIX Shell, Network Boot & Embedded C Style329/561

GL-E00 · 4.2 (m04-l02)

>_ Kernel Systems Academy

Summary

  • Kernel C11 uses lowercase snake_case identifiers 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 static so the compiler emits ELF STB_LOCAL linkage, 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.
GL-E00 · Linux Host Workbench, POSIX Shell, Network Boot & Embedded C Style330/561

GL-E00 · 4.2 (m04-l02)

>_ Kernel Systems Academy

Key takeaways

  • Every file-private function and module variable must be declared static so the compiler emits ELF STB_LOCAL linkage, 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.
GL-E00 · Linux Host Workbench, POSIX Shell, Network Boot & Embedded C Style331/561

GL-E00 · 4.3 (m04-l03)

>_ Kernel Systems Academy

Single-Purpose Variables, Fixed-Width Types & Defensive do-while(0) Macros

free preview20 minlab lab_m04_c_style_auditor

What you'll learn

  • Replace multi-purpose temp variables and long-sized hardware fields with single-purpose <stdint.h> declarations.
  • Analyze preprocessor token-pasting and precedence hazards to choose between static inline functions and fully parenthesized macros.
  • Implement a C11 static-hygiene and LIFO unwind auditor verifying macro parenthesization, do { ... } while (0) wrapping, and zero hidden control-flow jumps.
GL-E00 · Linux Host Workbench, POSIX Shell, Network Boot & Embedded C Style332/561

GL-E00 · 4.3 (m04-l03)

>_ Kernel Systems Academy

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.
GL-E00 · Linux Host Workbench, POSIX Shell, Network Boot & Embedded C Style333/561

GL-E00 · 4.3 (m04-l03)

>_ Kernel Systems Academy

Single-Purpose Locals, LP64/ILP32 Widths, and Inline Type Safety

  • Second, unsigned long changes width between your x86_64 workstation (LP64: 8 bytes) and your `ARMv7…
GL-E00 · Linux Host Workbench, POSIX Shell, Network Boot & Embedded C Style334/561

GL-E00 · 4.3 (m04-l03)

>_ Kernel Systems Academy

Single-Purpose Locals, LP64/ILP32 Widths, and Inline Type Safety

fig_m04_l03_a.svg

Figure 4.3a: Textual macro substitution occurs before C parsing; parentheses and do-while(0) preserve AST structure.

GL-E00 · Linux Host Workbench, POSIX Shell, Network Boot & Embedded C Style335/561

GL-E00 · 4.3 (m04-l03)

>_ Kernel Systems Academy

Mental model

note: 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.

GL-E00 · Linux Host Workbench, POSIX Shell, Network Boot & Embedded C Style336/561

GL-E00 · 4.3 (m04-l03)

>_ Kernel Systems Academy

do { ... } while (0) Macro Idiom

definition: 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.

GL-E00 · Linux Host Workbench, POSIX Shell, Network Boot & Embedded C Style337/561

GL-E00 · 4.3 (m04-l03)

>_ Kernel Systems Academy

Single-Purpose Locals, LP64/ILP32 Widths, and Inline Type Safety

_Static_assert(sizeof(struct desc) == 8, ...) catches accidental LP64 pointer/long fields at compile time.

Use uint32_t for register structs, static inline for functions, and do-while(0) for multi-stmt macros.

GL-E00 · Linux Host Workbench, POSIX Shell, Network Boot & Embedded C Style338/561

GL-E00 · 4.3 (m04-l03)

>_ Kernel Systems Academy

Anatomy of Preprocessor Substitution Hazards

  • The C preprocessor (cpp) knows nothing about C expressions, statements, or types — it performs blind toke…
GL-E00 · Linux Host Workbench, POSIX Shell, Network Boot & Embedded C Style339/561

GL-E00 · 4.3 (m04-l03)

>_ Kernel Systems Academy

Anatomy of Preprocessor Substitution Hazards

  • Now consider #define ACK_BOTH(a, b) *(a) = 1; *(b) = 1; used inside if (irq) ACK_BOTH(r1, r2);: after e…
GL-E00 · Linux Host Workbench, POSIX Shell, Network Boot & Embedded C Style340/561

GL-E00 · 4.3 (m04-l03)

>_ Kernel Systems Academy

Anatomy of Preprocessor Substitution Hazards

fig_m04_l03_b.svg

Figure 4.3b: Host x86_64 LP64 makes sizeof(long)==8 while ARMv7-A ILP32 makes sizeof(long)==4; uint32_t stays 4 everywhere.

GL-E00 · Linux Host Workbench, POSIX Shell, Network Boot & Embedded C Style341/561

GL-E00 · 4.3 (m04-l03)

>_ Kernel Systems Academy

mmio_defensive_macros.h

learner@ksa: ~/gl-e00/m04-l03
learner@ksa:~/gl-e00/m04-l03$ bat 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;
GL-E00 · Linux Host Workbench, POSIX Shell, Network Boot & Embedded C Style342/561

GL-E00 · 4.3 (m04-l03)

>_ Kernel Systems Academy

stdint.h(0p) / C11 _Static_assert

stdint.h(0p) / C11 _Static_assert(3) at a glance — GL-E00
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      m04-l03       stdint.h(0p) / C11 _Static_assert(3) GL-E00 quick reference · full manual page: man 3 stdint.h(0p) / C11 _Static_assert 
GL-E00 · Linux Host Workbench, POSIX Shell, Network Boot & Embedded C Style343/561

GL-E00 · 4.3 (m04-l03)

>_ Kernel Systems Academy

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)…
GL-E00 · Linux Host Workbench, POSIX Shell, Network Boot & Embedded C Style344/561

GL-E00 · 4.3 (m04-l03)

>_ Kernel Systems Academy

Proving Macro Precedence, Side-Effect, and Width Invariants in C11

  • Passing these assertions sets up lab_m04_c_style_auditor, where you will build a reusable C11 static-…
GL-E00 · Linux Host Workbench, POSIX Shell, Network Boot & Embedded C Style345/561

GL-E00 · 4.3 (m04-l03)

>_ Kernel Systems Academy

verify.c

learner@ksa: ~/gl-e00/m04-l03
learner@ksa:~/gl-e00/m04-l03$ bat 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) \
GL-E00 · Linux Host Workbench, POSIX Shell, Network Boot & Embedded C Style346/561

GL-E00 · 4.3 (m04-l03)

>_ Kernel Systems Academy

Inspecting LP64 Host Widths and Precedence Bitmasks

  • Observe the recorded host output: on x86_64 Linux, sizeof(unsigned long) is 8 bytes while `sizeof(str…
GL-E00 · Linux Host Workbench, POSIX Shell, Network Boot & Embedded C Style347/561

GL-E00 · 4.3 (m04-l03)

>_ Kernel Systems Academy

Inspecting LP64 Host Widths and Precedence Bitmasks

  • Equally stark is MACRO_PARENS: ~BAD_SHIFT(3) silently cleared bits 0..2 (0xFFFFFFF0) instead of cle…
GL-E00 · Linux Host Workbench, POSIX Shell, Network Boot & Embedded C Style348/561

GL-E00 · 4.3 (m04-l03)

>_ Kernel Systems Academy

Inspecting LP64 Host Widths and Precedence Bitmasks

learner@ksa: ~/gl-e00/m04-l03
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-l03
GL-E00 · Linux Host Workbench, POSIX Shell, Network Boot & Embedded C Style349/561

GL-E00 · 4.3 (m04-l03)

>_ Kernel Systems Academy

Inspecting LP64 Host Widths and Precedence Bitmasks

strace — learner@ksa: ~/gl-e00/m04-l03
learner@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 +++
GL-E00 · Linux Host Workbench, POSIX Shell, Network Boot & Embedded C Style350/561

GL-E00 · 4.3 (m04-l03)

>_ Kernel Systems Academy

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 int…
GL-E00 · Linux Host Workbench, POSIX Shell, Network Boot & Embedded C Style351/561

GL-E00 · 4.3 (m04-l03)

>_ Kernel Systems Academy

Hidden Macro Control Flow and Side-Effect Double Reads

  • Whenever a macro must exist, audit three things mechanically: inner (param) parentheses, outer (...) or…
GL-E00 · Linux Host Workbench, POSIX Shell, Network Boot & Embedded C Style352/561

GL-E00 · 4.3 (m04-l03)

>_ Kernel Systems Academy

Warning

warning: - Symptom: Reading an I2C or UART receive FIFO inside CLAMP(*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 multiple volatile MMIO read cycles that pop distinct bytes from the hardware FIFO. - Fix: Replace value macros with a static inline C11 function, or read the volatile register once into a single-purpose uint32_t sample local variable first.

GL-E00 · Linux Host Workbench, POSIX Shell, Network Boot & Embedded C Style353/561

GL-E00 · 4.3 (m04-l03)

>_ Kernel Systems Academy

Warning

warning: - Symptom: After an intermittent I2C NAK error, every subsequent thread opening the device hangs forever inside mutex_lock() (D uninterruptible sleep in ps). - Root Cause: Calling CHECK_RET(i2c_xfer(...)); between mutex_lock(&dev->lock) and mutex_unlock(&dev->lock) executed a hidden return rc; inside the macro, bypassing goto 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.

GL-E00 · Linux Host Workbench, POSIX Shell, Network Boot & Embedded C Style354/561

GL-E00 · 4.3 (m04-l03)

>_ Kernel Systems Academy

Guided Practice

  • In verify.c, add a second broken macro #define BAD_ADD_OFFSET(x) (x) + 0x10U (note inner parameter pare…
GL-E00 · Linux Host Workbench, POSIX Shell, Network Boot & Embedded C Style355/561

GL-E00 · 4.3 (m04-l03)

>_ Kernel Systems Academy

Guided Practice

  • Verify that BAD_ADD_OFFSET(4U) * 2U evaluates to 4 + 32 = 36 instead of (4 + 16) * 2 = 40, confirming…
GL-E00 · Linux Host Workbench, POSIX Shell, Network Boot & Embedded C Style356/561

GL-E00 · 4.3 (m04-l03)

>_ Kernel Systems Academy

Independent Practice

  • Open labs/lab_m04_c_style_auditor/ and inspect starter/core.c alongside tests.c.
GL-E00 · Linux Host Workbench, POSIX Shell, Network Boot & Embedded C Style357/561

GL-E00 · 4.3 (m04-l03)

>_ Kernel Systems Academy

Independent Practice

  • Run sh check.sh to confirm 5/5 TAP version 13 checks pass, then run ./files/lab_cli --bench to reco…
GL-E00 · Linux Host Workbench, POSIX Shell, Network Boot & Embedded C Style358/561

GL-E00 · 4.3 (m04-l03)

>_ Kernel Systems Academy

Quick check

Why does #define ACK_IRQ(a, b) { *(a) = 1; *(b) = 1; } fail to compile inside if (pending) ACK_IRQ(r0, r1); else count++;?

Select an option or press R to reveal.

GL-E00 · Linux Host Workbench, POSIX Shell, Network Boot & Embedded C Style359/561

GL-E00 · 4.3 (m04-l03)

>_ Kernel Systems Academy

Quick check

Why is unsigned long unsafe inside a shared DMA buffer-descriptor struct compiled in both x86_64 host tests and ARMv7-A firmware?

Select an option or press R to reveal.

GL-E00 · Linux Host Workbench, POSIX Shell, Network Boot & Embedded C Style360/561

GL-E00 · 4.3 (m04-l03)

>_ Kernel Systems Academy

Quick check

Retrieval check from Lesson 4.2: Why are macros like #define TRY_CALL(expr) if ((expr) < 0) return -EIO banned in Linux kernel C?

Select an option or press R to reveal.

GL-E00 · Linux Host Workbench, POSIX Shell, Network Boot & Embedded C Style361/561

GL-E00 · 4.3 (m04-l03)

>_ Kernel Systems Academy

Lab: lab_m04_c_style_auditor

  • Production kernel patches fail review immediately when macros hide return jumps, private helpers omit `st…

Verify: ./check.sh exits 0.

GL-E00 · Linux Host Workbench, POSIX Shell, Network Boot & Embedded C Style362/561

GL-E00 · 4.3 (m04-l03)

>_ Kernel Systems Academy

Summary

  • Hardware register layouts and wire headers must use <stdint.h> fixed-width types (uint8_t, uint16_t, uint32_t, uint64_t) because unsigned long is 64 bits on x86_64 (LP64) and 32 bits on ARMv7-A (ILP32).
  • Typed const values, enum constants, and static inline functions are preferred over #define macros 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 in do { ... } while (0) without a trailing semicolon.
  • Macros must never hide control-flow exits (return, goto, break) because invisible jumps bypass caller spinlocks and centralized goto cleanup spines.
GL-E00 · Linux Host Workbench, POSIX Shell, Network Boot & Embedded C Style363/561

GL-E00 · 4.3 (m04-l03)

>_ Kernel Systems Academy

Key takeaways

  • Typed const values, enum constants, and static inline functions are preferred over #define macros 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 in do { ... } while (0) without a trailing semicolon.
  • Macros must never hide control-flow exits (return, goto, break) because invisible jumps bypass caller spinlocks and centralized goto cleanup spines.
GL-E00 · Linux Host Workbench, POSIX Shell, Network Boot & Embedded C Style364/561

m05/

>_ Kernel Systems Academy

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.

  1. 5.1 UART Console Framing (115200 8N1), Flow-Control Deadlocks & Boot-Mode Straps
  2. 5.2 SD, eMMC & Raw NAND Storage Topologies and UUU Provisioning
  3. 5.3 Bare-Metal & Bootloader Bring-Up Fault Triage

lab → i.MX6ULL Boot-Strap Decoder, AAPCS32/.bss Guard & VFS Panic Triage Engine

GL-E00 · Linux Host Workbench, POSIX Shell, Network Boot & Embedded C Style365/561

GL-E00 · 5.1 (m05-l01)

>_ Kernel Systems Academy

UART Console Framing (115200 8N1), Flow-Control Deadlocks & Boot-Mode Straps

free preview20 min

What you'll learn

  • Calculate 115200 8N1 bit-cell duration (8.68 us), frame throughput, and receiver oversampling clock-drift tolerance.
  • Diagnose asymmetric RX-works / TX-dead serial console hangs caused by CRTSCTS or IXON flags in POSIX termios.
  • Decode i.MX6ULL SRC_SBMR2 (BOOT_MODE[1:0]) and SRC_SBMR1 (BOOT_CFG1) register bitmasks to select USB SDP, SD, eMMC, or NAND boot.
GL-E00 · Linux Host Workbench, POSIX Shell, Network Boot & Embedded C Style366/561

GL-E00 · 5.1 (m05-l01)

>_ Kernel Systems Academy

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 exis…
GL-E00 · Linux Host Workbench, POSIX Shell, Network Boot & Embedded C Style367/561

GL-E00 · 5.1 (m05-l01)

>_ Kernel Systems Academy

Asynchronous 8N1 Timing and the Classic Frozen-Keyboard Trap

  • Nearly every engineer hits the same baffling symptom on day one: U-Boot prints its countdown (`Hit any ke…
GL-E00 · Linux Host Workbench, POSIX Shell, Network Boot & Embedded C Style368/561

GL-E00 · 5.1 (m05-l01)

>_ Kernel Systems Academy

Asynchronous 8N1 Timing and the Classic Frozen-Keyboard Trap

fig_m05_l01_a.svg

Figure 5.1a: 3-wire debug consoles omit RTS#/CTS#; enabling CRTSCTS blocks only host TX while target RX keeps streaming.

GL-E00 · Linux Host Workbench, POSIX Shell, Network Boot & Embedded C Style369/561

GL-E00 · 5.1 (m05-l01)

>_ Kernel Systems Academy

Mental model

note: 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.

GL-E00 · Linux Host Workbench, POSIX Shell, Network Boot & Embedded C Style370/561

GL-E00 · 5.1 (m05-l01)

>_ Kernel Systems Academy

BOOT_MODE & BOOT_CFG Strap Pins

definition: 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.

GL-E00 · Linux Host Workbench, POSIX Shell, Network Boot & Embedded C Style371/561

GL-E00 · 5.1 (m05-l01)

>_ Kernel Systems Academy

Asynchronous 8N1 Timing and the Classic Frozen-Keyboard Trap

Missing dialout membership returns EACCES on /dev/ttyUSB0 before baud configuration even runs.

Disable CRTSCTS on 3-wire 115200 8N1 consoles; set BOOT_MODE=01 for USB SDP or 10 for flash boot.

GL-E00 · Linux Host Workbench, POSIX Shell, Network Boot & Embedded C Style372/561

GL-E00 · 5.1 (m05-l01)

>_ Kernel Systems Academy

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 K…
GL-E00 · Linux Host Workbench, POSIX Shell, Network Boot & Embedded C Style373/561

GL-E00 · 5.1 (m05-l01)

>_ Kernel Systems Academy

i.MX6ULL Reset Strap Latches (SRC_SBMR1 and SRC_SBMR2)

  • During development, boards expose BOOT_MODE[1:0] on a 2-pole DIP switch rather than burning one-time-prog…
GL-E00 · Linux Host Workbench, POSIX Shell, Network Boot & Embedded C Style374/561

GL-E00 · 5.1 (m05-l01)

>_ Kernel Systems Academy

i.MX6ULL Reset Strap Latches (SRC_SBMR1 and SRC_SBMR2)

fig_m05_l01_b.svg

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!

GL-E00 · Linux Host Workbench, POSIX Shell, Network Boot & Embedded C Style375/561

GL-E00 · 5.1 (m05-l01)

>_ Kernel Systems Academy

imx6ull_sbmr_uart.h

learner@ksa: ~/gl-e00/m05-l01
learner@ksa:~/gl-e00/m05-l01$ bat 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
GL-E00 · Linux Host Workbench, POSIX Shell, Network Boot & Embedded C Style376/561

GL-E00 · 5.1 (m05-l01)

>_ Kernel Systems Academy

picocom(1) / termios(3)

picocom(1) / termios(3)(1) at a glance — GL-E00
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           m05-l01            picocom(1) / termios(3)(1) GL-E00 quick reference · full manual page: man 1 picocom(1) / termios(3) 
GL-E00 · Linux Host Workbench, POSIX Shell, Network Boot & Embedded C Style377/561

GL-E00 · 5.1 (m05-l01)

>_ Kernel Systems Academy

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 `16…
GL-E00 · Linux Host Workbench, POSIX Shell, Network Boot & Embedded C Style378/561

GL-E00 · 5.1 (m05-l01)

>_ Kernel Systems Academy

Calculating 8N1 Timing Margins and Decoding SRC Strap Registers in C11

  • Running this model on our host proves exact bitmask extraction and termios flag invariants before probing…
GL-E00 · Linux Host Workbench, POSIX Shell, Network Boot & Embedded C Style379/561

GL-E00 · 5.1 (m05-l01)

>_ Kernel Systems Academy

verify.c

learner@ksa: ~/gl-e00/m05-l01
learner@ksa:~/gl-e00/m05-l01$ bat 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)
GL-E00 · Linux Host Workbench, POSIX Shell, Network Boot & Embedded C Style380/561

GL-E00 · 5.1 (m05-l01)

>_ Kernel Systems Academy

Validating Bit Timing and Strap Override Precedence

  • Look closely at the fourth decode_imx_boot() call in STRAPS: even when SRC_SBMR1 still holds `0x00000…
GL-E00 · Linux Host Workbench, POSIX Shell, Network Boot & Embedded C Style381/561

GL-E00 · 5.1 (m05-l01)

>_ Kernel Systems Academy

Validating Bit Timing and Strap Override Precedence

  • UART_8N1 also confirms why dumping 1 MiB of hex over 115200 UART takes over 90 seconds (`11,520 B…
GL-E00 · Linux Host Workbench, POSIX Shell, Network Boot & Embedded C Style382/561

GL-E00 · 5.1 (m05-l01)

>_ Kernel Systems Academy

Validating Bit Timing and Strap Override Precedence

learner@ksa: ~/gl-e00/m05-l01
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-l01
GL-E00 · Linux Host Workbench, POSIX Shell, Network Boot & Embedded C Style383/561

GL-E00 · 5.1 (m05-l01)

>_ Kernel Systems Academy

Validating Bit Timing and Strap Override Precedence

strace — learner@ksa: ~/gl-e00/m05-l01
learner@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 +++
GL-E00 · Linux Host Workbench, POSIX Shell, Network Boot & Embedded C Style384/561

GL-E00 · 5.1 (m05-l01)

>_ Kernel Systems Academy

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…
GL-E00 · Linux Host Workbench, POSIX Shell, Network Boot & Embedded C Style385/561

GL-E00 · 5.1 (m05-l01)

>_ Kernel Systems Academy

Boot-Strap Contention and Serial Console Failure Modes

  • If RX prints normally while TX ignores keystrokes, clear CRTSCTS and IXON first.
GL-E00 · Linux Host Workbench, POSIX Shell, Network Boot & Embedded C Style386/561

GL-E00 · 5.1 (m05-l01)

>_ Kernel Systems Academy

Warning

warning: - Symptom: Flashing U-Boot to eMMC via UUU succeeds 100%, yet pressing the reset button produces zero characters on UART1. - Root Cause: With BOOT_MODE[1:0] still set to 01 (Serial Downloader), the i.MX6ULL Boot ROM never reads eMMC and outputs nothing on UART1 — it silently enumerates USB_OTG1 waiting for another SDP host command. - Fix: Switch BOOT_MODE[1:0] back to 10 (Internal Boot), verify BOOT_CFG selects eMMC/NAND/SD, and trigger a full POR_B power-on reset.

GL-E00 · Linux Host Workbench, POSIX Shell, Network Boot & Embedded C Style387/561

GL-E00 · 5.1 (m05-l01)

>_ Kernel Systems Academy

Warning

warning: - Symptom: Board boots reliably from SD card when bare, then stops booting completely the instant an external RGB LCD panel or peripheral hat is plugged into the LCD_DATA header. - Root Cause: The i.MX6ULL multiplexes BOOT_CFG1/2/4 onto LCD_DATA00..23 during POR_B; external pull-ups or powered back-feeding on the LCD cable override weak 10 kOhm board strap resistors and select a non-existent boot device. - Fix: Isolate LCD_DATA peripheral loads until POR_B deasserts, strengthen strap resistors per hardware design guidelines, or burn BT_FUSE_SEL + boot fuses for production boards.

GL-E00 · Linux Host Workbench, POSIX Shell, Network Boot & Embedded C Style388/561

GL-E00 · 5.1 (m05-l01)

>_ Kernel Systems Academy

Guided Practice

  • Extend verify.c to compute receiver sampling drift at bit 9.5 (middle of the Stop bit, 9.5 bit period…
GL-E00 · Linux Host Workbench, POSIX Shell, Network Boot & Embedded C Style389/561

GL-E00 · 5.1 (m05-l01)

>_ Kernel Systems Academy

Guided Practice

  • Print the cumulative drift in microseconds and verify that 5.20% > 4.76% (0.5 / 10.5) triggers a Stop-b…
GL-E00 · Linux Host Workbench, POSIX Shell, Network Boot & Embedded C Style390/561

GL-E00 · 5.1 (m05-l01)

>_ Kernel Systems Academy

Independent Practice

  • Write a C11 helper check_termios_3wire_safe(uint32_t c_cflag, uint32_t c_iflag) using <termios.h> const…
GL-E00 · Linux Host Workbench, POSIX Shell, Network Boot & Embedded C Style391/561

GL-E00 · 5.1 (m05-l01)

>_ Kernel Systems Academy

Independent Practice

  • Test it on a cfmakeraw(&tio) struct before and after masking CRTSCTS to verify whether cfmakeraw alon…
GL-E00 · Linux Host Workbench, POSIX Shell, Network Boot & Embedded C Style392/561

GL-E00 · 5.1 (m05-l01)

>_ Kernel Systems Academy

Quick check

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?

Select an option or press R to reveal.

GL-E00 · Linux Host Workbench, POSIX Shell, Network Boot & Embedded C Style393/561

GL-E00 · 5.1 (m05-l01)

>_ Kernel Systems Academy

Quick check

How long does a single byte take on the wire at 115200 8N1, and what is the maximum continuous byte rate?

Select an option or press R to reveal.

GL-E00 · Linux Host Workbench, POSIX Shell, Network Boot & Embedded C Style394/561

GL-E00 · 5.1 (m05-l01)

>_ Kernel Systems Academy

Quick check

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?

Select an option or press R to reveal.

GL-E00 · Linux Host Workbench, POSIX Shell, Network Boot & Embedded C Style395/561

GL-E00 · 5.1 (m05-l01)

>_ Kernel Systems Academy

Summary

  • At 115200 8N1, each asynchronous frame carries 10 bit cells (1 Start, 8 LSB-first data, 0 parity, 1 Stop) at 8.68 us/bit (86.81 us/frame, 11,520 bytes/s max).
  • Leaving hardware flow control (CRTSCTS) enabled in minicom or picocom on a 3-wire (TX/RX/GND) USB-TTL bridge blocks host keyboard TX waiting on unasserted CTS# while target RX prints normally.
  • At POR_B reset release, the i.MX6ULL Boot ROM samples BOOT_MODE[1:0] (SRC_SBMR2[25:24]): 10 selects Internal Boot via BOOT_CFG straps, 01 enters USB_OTG1 Serial Downloader (SDP), and 00 boots from eFUSEs.
  • Under Internal Boot (BOOT_MODE = 10), BOOT_CFG1[7:4] (SRC_SBMR1[7:4] sampled from LCD_DATA pins) selects SD (USDHC1), eMMC (USDHC2), or raw NAND (GPMI).
GL-E00 · Linux Host Workbench, POSIX Shell, Network Boot & Embedded C Style396/561

GL-E00 · 5.1 (m05-l01)

>_ Kernel Systems Academy

Key takeaways

  • Leaving hardware flow control (CRTSCTS) enabled in minicom or picocom on a 3-wire (TX/RX/GND) USB-TTL bridge blocks host keyboard TX waiting on unasserted CTS# while target RX prints normally.
  • At POR_B reset release, the i.MX6ULL Boot ROM samples BOOT_MODE[1:0] (SRC_SBMR2[25:24]): 10 selects Internal Boot via BOOT_CFG straps, 01 enters USB_OTG1 Serial Downloader (SDP), and 00 boots from eFUSEs.
  • Under Internal Boot (BOOT_MODE = 10), BOOT_CFG1[7:4] (SRC_SBMR1[7:4] sampled from LCD_DATA pins) selects SD (USDHC1), eMMC (USDHC2), or raw NAND (GPMI).
GL-E00 · Linux Host Workbench, POSIX Shell, Network Boot & Embedded C Style397/561

GL-E00 · 5.2 (m05-l02)

>_ Kernel Systems Academy

SD, eMMC & Raw NAND Storage Topologies and UUU Provisioning

free preview20 min

What you'll learn

  • Contrast SD/eMMC 512-byte LBA + boot0 hardware partitions against raw SLC NAND eraseblock, page/OOB, MTD, and UBI/UBIFS geometry.
  • Analyze why placing FAT32 or ext4 directly onto raw NAND fails immediately due to factory bad blocks and missing wear leveling.
  • Trace UUU provisioning scripts from SDP: Boot ROM DCD + DDR3 download into FB: U-Boot Fastboot flash commands.
GL-E00 · Linux Host Workbench, POSIX Shell, Network Boot & Embedded C Style398/561

GL-E00 · 5.2 (m05-l02)

>_ Kernel Systems Academy

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…
GL-E00 · Linux Host Workbench, POSIX Shell, Network Boot & Embedded C Style399/561

GL-E00 · 5.2 (m05-l02)

>_ Kernel Systems Academy

Managed FTL Block Flash Versus Raw SLC NAND Geometry

  • SD cards and eMMC packages integrate a dedicated controller running a Flash Translation Layer (FTL).
GL-E00 · Linux Host Workbench, POSIX Shell, Network Boot & Embedded C Style400/561

GL-E00 · 5.2 (m05-l02)

>_ Kernel Systems Academy

Managed FTL Block Flash Versus Raw SLC NAND Geometry

  • Raw SLC NAND has zero internal controller: the i.MX6ULL GPMI and BCH engines drive raw 2 KiB…
GL-E00 · Linux Host Workbench, POSIX Shell, Network Boot & Embedded C Style401/561

GL-E00 · 5.2 (m05-l02)

>_ Kernel Systems Academy

Managed FTL Block Flash Versus Raw SLC NAND Geometry

fig_m05_l02_a.svg

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.

GL-E00 · Linux Host Workbench, POSIX Shell, Network Boot & Embedded C Style402/561

GL-E00 · 5.2 (m05-l02)

>_ Kernel Systems Academy

Mental model

note: 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.

GL-E00 · Linux Host Workbench, POSIX Shell, Network Boot & Embedded C Style403/561

GL-E00 · 5.2 (m05-l02)

>_ Kernel Systems Academy

UBI (Unsorted Block Images)

definition: 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.

GL-E00 · Linux Host Workbench, POSIX Shell, Network Boot & Embedded C Style404/561

GL-E00 · 5.2 (m05-l02)

>_ Kernel Systems Academy

Managed FTL Block Flash Versus Raw SLC NAND Geometry

Even a brand-new board with completely erased eMMC/NAND boots U-Boot into DDR3 in < 1 second via SDP.

Keep LBA 2..2047 clear on SD, use boot0 on eMMC, use UBI/UBIFS on raw NAND, and stream via UUU SDP->FB.

GL-E00 · Linux Host Workbench, POSIX Shell, Network Boot & Embedded C Style405/561

GL-E00 · 5.2 (m05-l02)

>_ Kernel Systems Academy

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!
GL-E00 · Linux Host Workbench, POSIX Shell, Network Boot & Embedded C Style406/561

GL-E00 · 5.2 (m05-l02)

>_ Kernel Systems Academy

eMMC Partition Offsets Versus NAND FCB, MTD, and LEB Sizing

  • On 512 MiB SLC NAND (4,096 PEBs x 128 KiB, 64 pages/block x 2,048 B + 64 B OOB), block 0…
GL-E00 · Linux Host Workbench, POSIX Shell, Network Boot & Embedded C Style407/561

GL-E00 · 5.2 (m05-l02)

>_ Kernel Systems Academy

eMMC Partition Offsets Versus NAND FCB, MTD, and LEB Sizing

fig_m05_l02_b.svg

Figure 5.2b: UBI consumes 2 NAND pages (EC + VID headers = 4 KiB on 2 KiB-page SLC NAND) per 128 KiB physical eraseblock.

GL-E00 · Linux Host Workbench, POSIX Shell, Network Boot & Embedded C Style408/561

GL-E00 · 5.2 (m05-l02)

>_ Kernel Systems Academy

emmc_nand_provision.uuu

learner@ksa: ~/gl-e00/m05-l02
learner@ksa:~/gl-e00/m05-l02uuu_version 1.4.182 # Stage 1: Stream U-Boot (+ IVT/DCD) over USB OTG1 HID SDP into DDR3 RAMSDP: boot -f u-boot-imx6ull-14x14-evk-emmc.imx # Stage 2: RAM U-Boot runs USB Fastboot gadget on OTG1FB: ucmd setenv fastboot_dev mmcFB: ucmd setenv mmcdev 1FB: ucmd mmc dev 1 # Program U-Boot into dedicated eMMC boot0 hardware partition & enable boot0FB: flash bootloader u-boot-imx6ull-14x14-evk-emmc.imxFB: ucmd mmc partconf 1 1 1 0learner@ksa:~/gl-e00/m05-l02
GL-E00 · Linux Host Workbench, POSIX Shell, Network Boot & Embedded C Style409/561

GL-E00 · 5.2 (m05-l02)

>_ Kernel Systems Academy

uuu(1) / ubiattach(8)

uuu(1) / ubiattach(8)(1) at a glance — GL-E00
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            m05-l02             uuu(1) / ubiattach(8)(1) GL-E00 quick reference · full manual page: man 1 uuu(1) / ubiattach(8) 
GL-E00 · Linux Host Workbench, POSIX Shell, Network Boot & Embedded C Style410/561

GL-E00 · 5.2 (m05-l02)

>_ Kernel Systems Academy

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…
GL-E00 · Linux Host Workbench, POSIX Shell, Network Boot & Embedded C Style411/561

GL-E00 · 5.2 (m05-l02)

>_ Kernel Systems Academy

Verifying LBA Headroom, UBI LEB Overhead, and UUU Ordering in C11

  • All geometry math executes deterministically in host C11; actual USB SDP enumeration and GPMI BCH E…
GL-E00 · Linux Host Workbench, POSIX Shell, Network Boot & Embedded C Style412/561

GL-E00 · 5.2 (m05-l02)

>_ Kernel Systems Academy

verify.c

learner@ksa: ~/gl-e00/m05-l02
learner@ksa:~/gl-e00/m05-l02$ bat 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)
GL-E00 · Linux Host Workbench, POSIX Shell, Network Boot & Embedded C Style413/561

GL-E00 · 5.2 (m05-l02)

>_ Kernel Systems Academy

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…
GL-E00 · Linux Host Workbench, POSIX Shell, Network Boot & Embedded C Style414/561

GL-E00 · 5.2 (m05-l02)

>_ Kernel Systems Academy

Checking Partition Headroom and mkfs.ubifs Parameters

  • Notice also why reserved_bad_pebs equals 80 (20/1024 of the entire 4,096-PEB 512 MiB chip, no…
GL-E00 · Linux Host Workbench, POSIX Shell, Network Boot & Embedded C Style415/561

GL-E00 · 5.2 (m05-l02)

>_ Kernel Systems Academy

Checking Partition Headroom and mkfs.ubifs Parameters

learner@ksa: ~/gl-e00/m05-l02
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-l02
GL-E00 · Linux Host Workbench, POSIX Shell, Network Boot & Embedded C Style416/561

GL-E00 · 5.2 (m05-l02)

>_ Kernel Systems Academy

Checking Partition Headroom and mkfs.ubifs Parameters

strace — learner@ksa: ~/gl-e00/m05-l02
learner@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 +++
GL-E00 · Linux Host Workbench, POSIX Shell, Network Boot & Embedded C Style417/561

GL-E00 · 5.2 (m05-l02)

>_ Kernel Systems Academy

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 `05…
GL-E00 · Linux Host Workbench, POSIX Shell, Network Boot & Embedded C Style418/561

GL-E00 · 5.2 (m05-l02)

>_ Kernel Systems Academy

Provisioning and Flash-Wear Hazards on eMMC and NAND

  • And when updating an existing UBI partition in the field, always use ubiformat or ubiupdatevol — neve…
GL-E00 · Linux Host Workbench, POSIX Shell, Network Boot & Embedded C Style419/561

GL-E00 · 5.2 (m05-l02)

>_ Kernel Systems Academy

Warning

warning: - Symptom: SDP: boot -f u-boot.imx reaches 100%, then uuu stalls indefinitely waiting for FB: Fastboot enumeration. - Root Cause: Either the flashed u-boot.imx lacks CONFIG_USB_FUNCTION_FASTBOOT / DCD matching the board's DDR3 size, OR a Linux VM (VirtualBox/VMware) captured 15a2:0080 (SDP) but failed to auto-capture the new 0525:a4a5 (Fastboot) USB VID:PID on re-enumeration! - Fix: Add both NXP SDP (15a2:0080) and U-Boot Fastboot (0525:a4a5) USB filters to your VM configuration and /etc/udev/rules.d/.

GL-E00 · Linux Host Workbench, POSIX Shell, Network Boot & Embedded C Style420/561

GL-E00 · 5.2 (m05-l02)

>_ Kernel Systems Academy

Warning

warning: - Symptom: Running dd if=u-boot.imx of=/dev/sdb boots U-Boot, yet lsblk and Linux kernel report the SD card's MBR partition table is completely gone! - Root Cause: Omitting seek=1 bs=1K (seek=2 bs=512) writes u-boot.imx at byte 0x000 (LBA 0), overwriting the 512-byte MBR AND placing the IVT at 0x000 instead of 0x400! - Fix: Always include bs=1K seek=1 conv=fsync (preserving bytes 0..1023, including LBA 0 MBR), and verify Partition 1 starts at >= LBA 2048.

GL-E00 · Linux Host Workbench, POSIX Shell, Network Boot & Embedded C Style421/561

GL-E00 · 5.2 (m05-l02)

>_ Kernel Systems Academy

Guided Practice

  • Modify verify.c to test what happens when an oversized U-Boot + environment blob grows to 1,100 KiB w…
GL-E00 · Linux Host Workbench, POSIX Shell, Network Boot & Embedded C Style422/561

GL-E00 · 5.2 (m05-l02)

>_ Kernel Systems Academy

Guided Practice

  • Compute the minimum 4 MiB-aligned starting sector (LBA 8192) required to give U-Boot and redundant `U…
GL-E00 · Linux Host Workbench, POSIX Shell, Network Boot & Embedded C Style423/561

GL-E00 · 5.2 (m05-l02)

>_ Kernel Systems Academy

Independent Practice

  • Write a C11 parser parse_mtdparts(const char *spec) for `mtdparts=gpmi-nand:4m(boot),8m(kernel),1m(dtb),-…
GL-E00 · Linux Host Workbench, POSIX Shell, Network Boot & Embedded C Style424/561

GL-E00 · 5.2 (m05-l02)

>_ Kernel Systems Academy

Independent Practice

  • Confirm that 4 + 8 + 1 = 13 MiB leaves 499 MiB (3,992 PEBs) for rootfs with zero unaligned PEB…
GL-E00 · Linux Host Workbench, POSIX Shell, Network Boot & Embedded C Style425/561

GL-E00 · 5.2 (m05-l02)

>_ Kernel Systems Academy

Quick check

Why does Linux kernel mount UBIFS over UBI + MTD on raw 512 MiB SLC NAND instead of formatting /dev/mtdblock4 directly as ext4?

Select an option or press R to reveal.

GL-E00 · Linux Host Workbench, POSIX Shell, Network Boot & Embedded C Style426/561

GL-E00 · 5.2 (m05-l02)

>_ Kernel Systems Academy

Quick check

During UUU provisioning of a completely blank board (BOOT_MODE = 01), why are two distinct USB protocols (SDP: followed by FB:) used?

Select an option or press R to reveal.

GL-E00 · Linux Host Workbench, POSIX Shell, Network Boot & Embedded C Style427/561

GL-E00 · 5.2 (m05-l02)

>_ Kernel Systems Academy

Quick check

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?

Select an option or press R to reveal.

GL-E00 · Linux Host Workbench, POSIX Shell, Network Boot & Embedded C Style428/561

GL-E00 · 5.2 (m05-l02)

>_ Kernel Systems Academy

Summary

  • SD (USDHC1) and eMMC (USDHC2) embed an on-chip Flash Translation Layer (FTL) exposing 512-byte LBA sectors, with i.MX6ULL IVT placed at byte 0x400 (LBA 2) and eMMC providing dedicated boot0/boot1 hardware partitions.
  • Raw SLC NAND (GPMI + BCH ECC) exposes physical eraseblocks (128 KiB) and factory/wear bad blocks directly without an FTL, requiring Linux kernel MTD, Bad Block Tables (BBT), and UBI/UBIFS rather than FAT32/ext4.
  • With BOOT_MODE[1:0] = 01, UUU Stage 1 (SDP: boot -f u-boot.imx) uses the Boot ROM's USB_OTG1 HID protocol to execute DCD DDR3 init and run U-Boot directly in RAM.
  • UUU Stage 2 (FB:) speaks USB Fastboot to the RAM-resident U-Boot gadget to partition and program eMMC (boot0 + GPT/MBR) or NAND (MTD/UBI) unattended.
GL-E00 · Linux Host Workbench, POSIX Shell, Network Boot & Embedded C Style429/561

GL-E00 · 5.2 (m05-l02)

>_ Kernel Systems Academy

Key takeaways

  • Raw SLC NAND (GPMI + BCH ECC) exposes physical eraseblocks (128 KiB) and factory/wear bad blocks directly without an FTL, requiring Linux kernel MTD, Bad Block Tables (BBT), and UBI/UBIFS rather than FAT32/ext4.
  • With BOOT_MODE[1:0] = 01, UUU Stage 1 (SDP: boot -f u-boot.imx) uses the Boot ROM's USB_OTG1 HID protocol to execute DCD DDR3 init and run U-Boot directly in RAM.
  • UUU Stage 2 (FB:) speaks USB Fastboot to the RAM-resident U-Boot gadget to partition and program eMMC (boot0 + GPT/MBR) or NAND (MTD/UBI) unattended.
GL-E00 · Linux Host Workbench, POSIX Shell, Network Boot & Embedded C Style430/561

GL-E00 · 5.3 (m05-l03)

>_ Kernel Systems Academy

Bare-Metal & Bootloader Bring-Up Fault Triage

free preview20 minlab lab_m05_boot_fault_triage

What you'll learn

  • Diagnose warm-vs-cold reset nondeterminism and printf("%lld") / LDRD Data Abort crashes caused by unzeroed .bss or 4-byte-misaligned ARMv7-A stack pointers.
  • Triage U-Boot RMII Ethernet PHY reset timing, NULL phydev Data Abort traps, and truncated bootargs environment strings.
  • Implement a C11 bring-up fault-triage engine (lab_m05_boot_fault_triage) decoding straps, AAPCS32/.bss startup bounds, and VFS rootfs panic signatures.
GL-E00 · Linux Host Workbench, POSIX Shell, Network Boot & Embedded C Style431/561

GL-E00 · 5.3 (m05-l03)

>_ Kernel Systems Academy

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…
GL-E00 · Linux Host Workbench, POSIX Shell, Network Boot & Embedded C Style432/561

GL-E00 · 5.3 (m05-l03)

>_ Kernel Systems Academy

Silent C Runtime Preconditions That Linux User Space Hid From You

  • Two classic bring-up ghosts follow immediately.
GL-E00 · Linux Host Workbench, POSIX Shell, Network Boot & Embedded C Style433/561

GL-E00 · 5.3 (m05-l03)

>_ Kernel Systems Academy

Silent C Runtime Preconditions That Linux User Space Hid From You

fig_m05_l03_a.svg

Figure 5.3a: Every bring-up hang localizes cleanly to one boundary: POR straps, start.S ABI, U-Boot env/PHY, or Kernel VFS.

GL-E00 · Linux Host Workbench, POSIX Shell, Network Boot & Embedded C Style434/561

GL-E00 · 5.3 (m05-l03)

>_ Kernel Systems Academy

Mental model

note: 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.

GL-E00 · Linux Host Workbench, POSIX Shell, Network Boot & Embedded C Style435/561

GL-E00 · 5.3 (m05-l03)

>_ Kernel Systems Academy

AAPCS32 8-Byte Stack Alignment

definition: 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.

GL-E00 · Linux Host Workbench, POSIX Shell, Network Boot & Embedded C Style436/561

GL-E00 · 5.3 (m05-l03)

>_ Kernel Systems Academy

Silent C Runtime Preconditions That Linux User Space Hid From You

bic sp, sp, #7 guarantees 8-byte alignment even if a symbol or linker expression shifts by 4 bytes.

Zero .bss, enforce SP % 8 == 0 (bic sp,sp,#7), check bootargs length, and add rootwait on mmcblk.

GL-E00 · Linux Host Workbench, POSIX Shell, Network Boot & Embedded C Style437/561

GL-E00 · 5.3 (m05-l03)

>_ Kernel Systems Academy

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.
GL-E00 · Linux Host Workbench, POSIX Shell, Network Boot & Embedded C Style438/561

GL-E00 · 5.3 (m05-l03)

>_ Kernel Systems Academy

Decoding U-Boot Data Aborts and Kernel VFS Panic Signatures

  • When Linux kernel 6.12 panics with VFS: Unable to mount root fs on <dev>, read the (major, minor) pai…
GL-E00 · Linux Host Workbench, POSIX Shell, Network Boot & Embedded C Style439/561

GL-E00 · 5.3 (m05-l03)

>_ Kernel Systems Academy

Decoding U-Boot Data Aborts and Kernel VFS Panic Signatures

fig_m05_l03_b.svg

Figure 5.3b: Major number 179 identifies MMC/SD block devices; (0,0) indicates no block device matched root=.

GL-E00 · Linux Host Workbench, POSIX Shell, Network Boot & Embedded C Style440/561

GL-E00 · 5.3 (m05-l03)

>_ Kernel Systems Academy

armv7_bringup_guard.h

learner@ksa: ~/gl-e00/m05-l03
learner@ksa:~/gl-e00/m05-l03$ bat 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
GL-E00 · Linux Host Workbench, POSIX Shell, Network Boot & Embedded C Style441/561

GL-E00 · 5.3 (m05-l03)

>_ Kernel Systems Academy

bootz(U-Boot) / kernel-parameters(7)

bootz(U-Boot) / kernel-parameters(7)(7) at a glance — GL-E00
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     m05-l03     bootz(U-Boot) / kernel-parameters(7)(7) GL-E00 quick reference · full manual page: man 7 bootz(U-Boot) / kernel-parameters(7) 
GL-E00 · Linux Host Workbench, POSIX Shell, Network Boot & Embedded C Style442/561

GL-E00 · 5.3 (m05-l03)

>_ Kernel Systems Academy

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 stac…
GL-E00 · Linux Host Workbench, POSIX Shell, Network Boot & Embedded C Style443/561

GL-E00 · 5.3 (m05-l03)

>_ Kernel Systems Academy

Modeling AAPCS32 Stack Alignment and VFS Panic Triage in Host C11

  • Completing this walkthrough prepares you directly for lab_m05_boot_fault_triage, where you will repai…
GL-E00 · Linux Host Workbench, POSIX Shell, Network Boot & Embedded C Style444/561

GL-E00 · 5.3 (m05-l03)

>_ Kernel Systems Academy

verify.c

learner@ksa: ~/gl-e00/m05-l03
learner@ksa:~/gl-e00/m05-l03$ bat 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)
GL-E00 · Linux Host Workbench, POSIX Shell, Network Boot & Embedded C Style445/561

GL-E00 · 5.3 (m05-l03)

>_ Kernel Systems Academy

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 assumi…
GL-E00 · Linux Host Workbench, POSIX Shell, Network Boot & Embedded C Style446/561

GL-E00 · 5.3 (m05-l03)

>_ Kernel Systems Academy

Confirming 64-Bit Slot Misalignment and VFS Cause Isolation

  • VFS_TRIAGE likewise separates truncated bootargs, NFS kernel-config/IP omissions, and missing `rootwa…
GL-E00 · Linux Host Workbench, POSIX Shell, Network Boot & Embedded C Style447/561

GL-E00 · 5.3 (m05-l03)

>_ Kernel Systems Academy

Confirming 64-Bit Slot Misalignment and VFS Cause Isolation

learner@ksa: ~/gl-e00/m05-l03
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-l03
GL-E00 · Linux Host Workbench, POSIX Shell, Network Boot & Embedded C Style448/561

GL-E00 · 5.3 (m05-l03)

>_ Kernel Systems Academy

Confirming 64-Bit Slot Misalignment and VFS Cause Isolation

strace — learner@ksa: ~/gl-e00/m05-l03
learner@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 +++
GL-E00 · Linux Host Workbench, POSIX Shell, Network Boot & Embedded C Style449/561

GL-E00 · 5.3 (m05-l03)

>_ Kernel Systems Academy

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 t…
GL-E00 · Linux Host Workbench, POSIX Shell, Network Boot & Embedded C Style450/561

GL-E00 · 5.3 (m05-l03)

>_ Kernel Systems Academy

Subtle Linker, U-Boot Semicolon, and DTB Address Collisions

  • Comparing Kernel command line: in dmesg against what you thought setenv bootargs set catches 90%…
GL-E00 · Linux Host Workbench, POSIX Shell, Network Boot & Embedded C Style451/561

GL-E00 · 5.3 (m05-l03)

>_ Kernel Systems Academy

Warning

warning: - Symptom: Running setenv bootargs console=ttymxc0,115200 mtdparts=gpmi-nand:4m(boot); root=ubi0:rootfs prints Unknown command 'root=ubi0:rootfs' or silently drops root=! - Root Cause: U-Boot's Hush shell treats an unquoted ; as a command separator, ending setenv bootargs early and trying to execute the remainder as a shell command. - Fix: Always wrap the entire bootargs value in single quotes (setenv bootargs '...') and verify the full stored value with printenv bootargs.

GL-E00 · Linux Host Workbench, POSIX Shell, Network Boot & Embedded C Style452/561

GL-E00 · 5.3 (m05-l03)

>_ Kernel Systems Academy

Warning

warning: - Symptom: Adding a single static char flag; at the end of .bss causes start.S to corrupt 3 bytes of the section immediately following __bss_end. - Root Cause: A 4-byte strlo r2, [r0], #4 loop writes a full 32-bit word on its final iteration if __bss_end - __bss_start is not a multiple of 4 bytes. - Fix: Enforce . = ALIGN(4); __bss_end = .; inside the linker script .bss output section and verify ((bss_start | bss_end) & 3) == 0.

GL-E00 · Linux Host Workbench, POSIX Shell, Network Boot & Embedded C Style453/561

GL-E00 · 5.3 (m05-l03)

>_ Kernel Systems Academy

Guided Practice

  • Add a U-Boot memory-overlap check `check_bootz_overlap(uint32_t zimg_addr, uint32_t zimg_len, uint32_t dt…
GL-E00 · Linux Host Workbench, POSIX Shell, Network Boot & Embedded C Style454/561

GL-E00 · 5.3 (m05-l03)

>_ Kernel Systems Academy

Guided Practice

  • Verify your overlap check catches zimg_addr + zimg_len > dtb_addr before bootz jumps into a corrupted `…
GL-E00 · Linux Host Workbench, POSIX Shell, Network Boot & Embedded C Style455/561

GL-E00 · 5.3 (m05-l03)

>_ Kernel Systems Academy

Independent Practice

  • Open labs/lab_m05_boot_fault_triage/ and inspect starter/core.c.
GL-E00 · Linux Host Workbench, POSIX Shell, Network Boot & Embedded C Style456/561

GL-E00 · 5.3 (m05-l03)

>_ Kernel Systems Academy

Independent Practice

  • Run sh check.sh to pass all 5/5 TAP version 13 checks and run ./files/lab_cli --bench to inspect `C…
GL-E00 · Linux Host Workbench, POSIX Shell, Network Boot & Embedded C Style457/561

GL-E00 · 5.3 (m05-l03)

>_ Kernel Systems Academy

Quick check

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?

Select an option or press R to reveal.

GL-E00 · Linux Host Workbench, POSIX Shell, Network Boot & Embedded C Style458/561

GL-E00 · 5.3 (m05-l03)

>_ Kernel Systems Academy

Quick check

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?

Select an option or press R to reveal.

GL-E00 · Linux Host Workbench, POSIX Shell, Network Boot & Embedded C Style459/561

GL-E00 · 5.3 (m05-l03)

>_ Kernel Systems Academy

Quick check

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?

Select an option or press R to reveal.

GL-E00 · Linux Host Workbench, POSIX Shell, Network Boot & Embedded C Style460/561

GL-E00 · 5.3 (m05-l03)

>_ Kernel Systems Academy

Lab: lab_m05_boot_fault_triage

  • Early board bring-up failures rarely print polite stack traces: wrong BOOT_MODE switches produce total si…

Verify: ./check.sh exits 0.

GL-E00 · Linux Host Workbench, POSIX Shell, Network Boot & Embedded C Style461/561

GL-E00 · 5.3 (m05-l03)

>_ Kernel Systems Academy

Summary

  • Bare-metal ARMv7-A start.S must explicitly zero [__bss_start, __bss_end) before branching to main() because DDR3 powers up with random bit states that corrupt uninitialized C globals.
  • The ARMv7-A AAPCS32 ABI mandates 8-byte stack alignment (SP mod 8 == 0, enforced via bic sp, sp, #7) at public call boundaries so 64-bit LDRD/STRD and printf("%lld") va_arg slots do not fault or misalign.
  • U-Boot ENET TFTP failures and bootargs truncations stem from missing RMII PHY reset pulse/settle timing (>= 10 ms) or unescaped multi-line setenv bootargs strings exceeding console buffer limits.
  • Kernel panic - not syncing: VFS: Unable to mount root fs encodes the exact failure stage: unknown-block(0,0) indicates missing/truncated root= or CONFIG_ROOT_NFS, whereas mmcblk error -2 without rootwait indicates asynchronous USDHC probe race.
GL-E00 · Linux Host Workbench, POSIX Shell, Network Boot & Embedded C Style462/561

GL-E00 · 5.3 (m05-l03)

>_ Kernel Systems Academy

Key takeaways

  • The ARMv7-A AAPCS32 ABI mandates 8-byte stack alignment (SP mod 8 == 0, enforced via bic sp, sp, #7) at public call boundaries so 64-bit LDRD/STRD and printf("%lld") va_arg slots do not fault or misalign.
  • U-Boot ENET TFTP failures and bootargs truncations stem from missing RMII PHY reset pulse/settle timing (>= 10 ms) or unescaped multi-line setenv bootargs strings exceeding console buffer limits.
  • Kernel panic - not syncing: VFS: Unable to mount root fs encodes the exact failure stage: unknown-block(0,0) indicates missing/truncated root= or CONFIG_ROOT_NFS, whereas mmcblk error -2 without rootwait indicates asynchronous USDHC probe race.
GL-E00 · Linux Host Workbench, POSIX Shell, Network Boot & Embedded C Style463/561

m06/

>_ Kernel Systems Academy

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.

  1. 6.1 ELF32 Cross-ABI Auditing, VFP Hard-Float Traps & Missing PT_INTERP ENOENT
  2. 6.2 Kernel Module vermagic, modversions CRCs & Timestamped dmesg Triage
  3. 6.3 End-to-End Embedded Workbench Preflight Capstone

lab → GL-E00 Capstone: Cross-ABI ELF32, PT_INTERP, Vermagic & Boot-Blob Preflight Gate

GL-E00 · Linux Host Workbench, POSIX Shell, Network Boot & Embedded C Style464/561

GL-E00 · 6.1 (m06-l01)

>_ Kernel Systems Academy

ELF32 Cross-ABI Auditing, VFP Hard-Float Traps & Missing PT_INTERP ENOENT

free preview25 min

What you'll learn

  • Audit 52-byte Elf32_Ehdr headers and e_flags bitmasks (0x05000400 EABI5 hard-float vs 0x05000200 soft-float) before copying binaries to /srv/nfs/rootfs.
  • Diagnose why ./app: No such file or directory (ENOENT) occurs on an existing, executable ARM binary when PT_INTERP is absent from the target rootfs.
  • Verify DT_NEEDED shared-library presence and GLIBC_2.xx version ceilings against the target rootfs sysroot.
GL-E00 · Linux Host Workbench, POSIX Shell, Network Boot & Embedded C Style465/561

GL-E00 · 6.1 (m06-l01)

>_ Kernel Systems Academy

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/…
GL-E00 · Linux Host Workbench, POSIX Shell, Network Boot & Embedded C Style466/561

GL-E00 · 6.1 (m06-l01)

>_ Kernel Systems Academy

The Most Misleading Error Message in Embedded Linux Bring-Up

  • Tracing Linux kernel fs/binfmt_elf.c explains every byte of what happened.
GL-E00 · Linux Host Workbench, POSIX Shell, Network Boot & Embedded C Style467/561

GL-E00 · 6.1 (m06-l01)

>_ Kernel Systems Academy

The Most Misleading Error Message in Embedded Linux Bring-Up

fig_m06_l01_a.svg

Figure 6.1a: execve() returns ENOEXEC when e_machine != EM_ARM, and returns ENOENT when PT_INTERP is missing in rootfs!

GL-E00 · Linux Host Workbench, POSIX Shell, Network Boot & Embedded C Style468/561

GL-E00 · 6.1 (m06-l01)

>_ Kernel Systems Academy

Mental model

note: 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.

GL-E00 · Linux Host Workbench, POSIX Shell, Network Boot & Embedded C Style469/561

GL-E00 · 6.1 (m06-l01)

>_ Kernel Systems Academy

PT_INTERP Program Header

definition: 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.

GL-E00 · Linux Host Workbench, POSIX Shell, Network Boot & Embedded C Style470/561

GL-E00 · 6.1 (m06-l01)

>_ Kernel Systems Academy

The Most Misleading Error Message in Embedded Linux Bring-Up

Catching EM_X86_64 (62) or soft-float (0x200) on the host takes 5 milliseconds with readelf -h.

Verify EM_ARM(40), e_flags 0x400 (hard-float), PT_INTERP in rootfs/lib, and matching sysroot glibc.

GL-E00 · Linux Host Workbench, POSIX Shell, Network Boot & Embedded C Style471/561

GL-E00 · 6.1 (m06-l01)

>_ Kernel Systems Academy

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 dir…
GL-E00 · Linux Host Workbench, POSIX Shell, Network Boot & Embedded C Style472/561

GL-E00 · 6.1 (m06-l01)

>_ Kernel Systems Academy

Inside the 52-Byte Elf32_Ehdr and VFPv3 Calling Convention

  • Why are armel (0x200 soft-float) and armhf (0x400 hard-float) mutually incompatible at the binary i…
GL-E00 · Linux Host Workbench, POSIX Shell, Network Boot & Embedded C Style473/561

GL-E00 · 6.1 (m06-l01)

>_ Kernel Systems Academy

Inside the 52-Byte Elf32_Ehdr and VFPv3 Calling Convention

fig_m06_l01_b.svg

Figure 6.1b: Byte offsets 0x00..0x27 of Elf32_Ehdr expose architecture, endianness, EABI version, and VFP float ABI.

GL-E00 · Linux Host Workbench, POSIX Shell, Network Boot & Embedded C Style474/561

GL-E00 · 6.1 (m06-l01)

>_ Kernel Systems Academy

elf32_armhf_contract.h

learner@ksa: ~/gl-e00/m06-l01
learner@ksa:~/gl-e00/m06-l01$ bat 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
GL-E00 · Linux Host Workbench, POSIX Shell, Network Boot & Embedded C Style475/561

GL-E00 · 6.1 (m06-l01)

>_ Kernel Systems Academy

elf(5) / readelf(1)

elf(5) / readelf(1)(5) at a glance — GL-E00
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             m06-l01              elf(5) / readelf(1)(5) GL-E00 quick reference · full manual page: man 5 elf(5) / readelf(1) 
GL-E00 · Linux Host Workbench, POSIX Shell, Network Boot & Embedded C Style476/561

GL-E00 · 6.1 (m06-l01)

>_ Kernel Systems Academy

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 b…
GL-E00 · Linux Host Workbench, POSIX Shell, Network Boot & Embedded C Style477/561

GL-E00 · 6.1 (m06-l01)

>_ Kernel Systems Academy

Simulating fs/binfmt_elf.c Architecture and PT_INTERP Checks in C11

  • Watching -ENOEXEC (-8) vs -ENOENT (-2) emerge from 50 lines of C11 makes the `No such file or dir…
GL-E00 · Linux Host Workbench, POSIX Shell, Network Boot & Embedded C Style478/561

GL-E00 · 6.1 (m06-l01)

>_ Kernel Systems Academy

verify.c

learner@ksa: ~/gl-e00/m06-l01
learner@ksa:~/gl-e00/m06-l01$ bat 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;    };
GL-E00 · Linux Host Workbench, POSIX Shell, Network Boot & Embedded C Style479/561

GL-E00 · 6.1 (m06-l01)

>_ Kernel Systems Academy

Tracing Exact Return Codes (-ENOEXEC vs -ENOENT)

  • Notice how cleanly BINFMT_ELF separates -8 (-ENOEXEC, Exec format error) on the EM_X86_64 image f…
GL-E00 · Linux Host Workbench, POSIX Shell, Network Boot & Embedded C Style480/561

GL-E00 · 6.1 (m06-l01)

>_ Kernel Systems Academy

Tracing Exact Return Codes (-ENOEXEC vs -ENOENT)

  • Whenever a target shell reports not found or No such file or directory on a binary you know exists, run…
GL-E00 · Linux Host Workbench, POSIX Shell, Network Boot & Embedded C Style481/561

GL-E00 · 6.1 (m06-l01)

>_ Kernel Systems Academy

Tracing Exact Return Codes (-ENOEXEC vs -ENOENT)

learner@ksa: ~/gl-e00/m06-l01
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-l01
GL-E00 · Linux Host Workbench, POSIX Shell, Network Boot & Embedded C Style482/561

GL-E00 · 6.1 (m06-l01)

>_ Kernel Systems Academy

Tracing Exact Return Codes (-ENOEXEC vs -ENOENT)

strace — learner@ksa: ~/gl-e00/m06-l01
learner@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 +++
GL-E00 · Linux Host Workbench, POSIX Shell, Network Boot & Embedded C Style483/561

GL-E00 · 6.1 (m06-l01)

>_ Kernel Systems Academy

Symlink Dereferencing and Cross-ldd Security/Diagnostic Traps

  • When building minimal BusyBox root filesystems (GL-E03), copy shared libraries from your cross-toolchain'…
GL-E00 · Linux Host Workbench, POSIX Shell, Network Boot & Embedded C Style484/561

GL-E00 · 6.1 (m06-l01)

>_ Kernel Systems Academy

Symlink Dereferencing and Cross-ldd Security/Diagnostic Traps

  • Keep one tiny -static diagnostic binary on /bin during early bring-up so you can always test kernel `ex…
GL-E00 · Linux Host Workbench, POSIX Shell, Network Boot & Embedded C Style485/561

GL-E00 · 6.1 (m06-l01)

>_ Kernel Systems Academy

Warning

warning: - Symptom: Running ldd ./arm_app on Ubuntu prints not a dynamic executable even though file ./arm_app says dynamically linked! - Root Cause: ldd works by invoking the host's dynamic linker (ld-linux-x86-64.so.2) with LD_TRACE_LOADED_OBJECTS=1, which cannot load 32-bit EM_ARM binaries (and is unsafe on untrusted ELFs). - Fix: Never use host ldd on cross-binaries; always use arm-linux-gnueabihf-readelf -d ./arm_app and readelf -l ./arm_app.

GL-E00 · Linux Host Workbench, POSIX Shell, Network Boot & Embedded C Style486/561

GL-E00 · 6.1 (m06-l01)

>_ Kernel Systems Academy

Warning

warning: - Symptom: ls /srv/nfs/rootfs/lib/ld-linux-armhf.so.3 appears in directory listings, yet ./app on the target STILL fails with No such file or directory (ENOENT)! - Root Cause: On toolchains where ld-linux-armhf.so.3 is a symbolic link pointing to ld-2.35.so (or /usr/arm-linux-gnueabihf/lib/... absolute host path!), a dangling symlink causes open_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 inside rootfs/lib/.

GL-E00 · Linux Host Workbench, POSIX Shell, Network Boot & Embedded C Style487/561

GL-E00 · 6.1 (m06-l01)

>_ Kernel Systems Academy

Guided Practice

  • Extend sim_arm_binfmt_elf() in verify.c to validate buffer-overflow-safe PT_INTERP NUL termination (`…
GL-E00 · Linux Host Workbench, POSIX Shell, Network Boot & Embedded C Style488/561

GL-E00 · 6.1 (m06-l01)

>_ Kernel Systems Academy

Guided Practice

  • Verify that strcmp(req, ...) without a bounded memchr check reads past img + len, and test your fix w…
GL-E00 · Linux Host Workbench, POSIX Shell, Network Boot & Embedded C Style489/561

GL-E00 · 6.1 (m06-l01)

>_ Kernel Systems Academy

Independent Practice

  • Inspect your host's own ./verify binary by writing a 35-line C11 program dump_self_elf.c that opens `…
GL-E00 · Linux Host Workbench, POSIX Shell, Network Boot & Embedded C Style490/561

GL-E00 · 6.1 (m06-l01)

>_ Kernel Systems Academy

Independent Practice

  • Verify that on x86_64 Linux it prints EI_CLASS=2 (ELF64) and e_machine=62 (EM_X86_64), contrasting di…
GL-E00 · Linux Host Workbench, POSIX Shell, Network Boot & Embedded C Style491/561

GL-E00 · 6.1 (m06-l01)

>_ Kernel Systems Academy

Quick check

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?

Select an option or press R to reveal.

GL-E00 · Linux Host Workbench, POSIX Shell, Network Boot & Embedded C Style492/561

GL-E00 · 6.1 (m06-l01)

>_ Kernel Systems Academy

Quick check

What distinguishes EF_ARM_ABI_FLOAT_HARD (0x400, armhf) from EF_ARM_ABI_FLOAT_SOFT (0x200, armel) at function call boundaries?

Select an option or press R to reveal.

GL-E00 · Linux Host Workbench, POSIX Shell, Network Boot & Embedded C Style493/561

GL-E00 · 6.1 (m06-l01)

>_ Kernel Systems Academy

Quick check

Why should you inspect an ARM cross-binary's shared-library dependencies with arm-linux-gnueabihf-readelf -d app rather than host ldd app?

Select an option or press R to reveal.

GL-E00 · Linux Host Workbench, POSIX Shell, Network Boot & Embedded C Style494/561

GL-E00 · 6.1 (m06-l01)

>_ Kernel Systems Academy

Summary

  • A valid ARMv7-A Linux user-space binary carries ELF magic 0x7F 'E' 'L' 'F', EI_CLASS = ELFCLASS32 (1), e_machine = EM_ARM (40), and e_flags bit EF_ARM_ABI_FLOAT_HARD (0x400).
  • Executing an EM_ARM (40) binary on an x86_64 host fails elf_check_arch() with ENOEXEC (Exec format error), whereas executing an armhf binary on an ARM rootfs missing its PT_INTERP (/lib/ld-linux-armhf.so.3) makes execve() return ENOENT (No such file or directory).
  • Mixing soft-float (EF_ARM_ABI_FLOAT_SOFT = 0x200, r0..r3 float passing) with hard-float (0x400, VFPv3 s0..s15 / d0..d7 registers) breaks calling conventions and requests incompatible /lib/ld-linux.so.3 vs /lib/ld-linux-armhf.so.3 loaders.
  • DT_NEEDED entries and .gnu.version_r tags (GLIBC_2.xx) bind binaries to the sysroot's minimum glibc version; compiling with a newer host cross-toolchain than the target rootfs fails in ld.so at launch.
GL-E00 · Linux Host Workbench, POSIX Shell, Network Boot & Embedded C Style495/561

GL-E00 · 6.1 (m06-l01)

>_ Kernel Systems Academy

Key takeaways

  • Executing an EM_ARM (40) binary on an x86_64 host fails elf_check_arch() with ENOEXEC (Exec format error), whereas executing an armhf binary on an ARM rootfs missing its PT_INTERP (/lib/ld-linux-armhf.so.3) makes execve() return ENOENT (No such file or directory).
  • Mixing soft-float (EF_ARM_ABI_FLOAT_SOFT = 0x200, r0..r3 float passing) with hard-float (0x400, VFPv3 s0..s15 / d0..d7 registers) breaks calling conventions and requests incompatible /lib/ld-linux.so.3 vs /lib/ld-linux-armhf.so.3 loaders.
  • DT_NEEDED entries and .gnu.version_r tags (GLIBC_2.xx) bind binaries to the sysroot's minimum glibc version; compiling with a newer host cross-toolchain than the target rootfs fails in ld.so at launch.
GL-E00 · Linux Host Workbench, POSIX Shell, Network Boot & Embedded C Style496/561

GL-E00 · 6.2 (m06-l02)

>_ Kernel Systems Academy

Kernel Module vermagic, modversions CRCs & Timestamped dmesg Triage

free preview20 min

What you'll learn

  • Inspect .ko .modinfo sections (modinfo drv.ko) to verify vermagic release, SMP/preempt, ARMv7, p2v8, and license=GPL fields.
  • Differentiate insmod -ENOEXEC (Invalid module format) from -ENOENT (Unknown symbol in module) using CONFIG_PRINTK_TIME=y dmesg logs.
  • Audit out-of-tree Kbuild Makefiles to prevent host-uname -r KDIR contamination and CONFIG_LOCALVERSION_AUTO -dirty version skew.
GL-E00 · Linux Host Workbench, POSIX Shell, Network Boot & Embedded C Style497/561

GL-E00 · 6.2 (m06-l02)

>_ Kernel Systems Academy

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…
GL-E00 · Linux Host Workbench, POSIX Shell, Network Boot & Embedded C Style498/561

GL-E00 · 6.2 (m06-l02)

>_ Kernel Systems Academy

Why Kernel Modules Carry Zero Binary Compatibility Across Kernel Builds

  • Enabling CONFIG_PREEMPT_RT or CONFIG_DEBUG_SPINLOCK changes the byte size of spinlock_t inside every…
GL-E00 · Linux Host Workbench, POSIX Shell, Network Boot & Embedded C Style499/561

GL-E00 · 6.2 (m06-l02)

>_ Kernel Systems Academy

Why Kernel Modules Carry Zero Binary Compatibility Across Kernel Builds

fig_m06_l02_a.svg

Figure 6.2a: insmod prints only a generic errno string; the exact mismatched vermagic token or symbol prints in dmesg!

GL-E00 · Linux Host Workbench, POSIX Shell, Network Boot & Embedded C Style500/561

GL-E00 · 6.2 (m06-l02)

>_ Kernel Systems Academy

Mental model

note: 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!

GL-E00 · Linux Host Workbench, POSIX Shell, Network Boot & Embedded C Style501/561

GL-E00 · 6.2 (m06-l02)

>_ Kernel Systems Academy

Module vermagic (.modinfo)

definition: 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.

GL-E00 · Linux Host Workbench, POSIX Shell, Network Boot & Embedded C Style502/561

GL-E00 · 6.2 (m06-l02)

>_ Kernel Systems Academy

Why Kernel Modules Carry Zero Binary Compatibility Across Kernel Builds

Never let an embedded driver Makefile fall back silently to /lib/modules/$(shell uname -r)/build!

Pin KDIR + ARCH=arm + CROSS_COMPILE, verify modinfo vermagic == target uname -r, and read timestamped dmesg.

GL-E00 · Linux Host Workbench, POSIX Shell, Network Boot & Embedded C Style503/561

GL-E00 · 6.2 (m06-l02)

>_ Kernel Systems Academy

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 NU…
GL-E00 · Linux Host Workbench, POSIX Shell, Network Boot & Embedded C Style504/561

GL-E00 · 6.2 (m06-l02)

>_ Kernel Systems Academy

Inside .modinfo NUL Records, __versions CRCs, and KDIR Traps

  • When CONFIG_MODVERSIONS=y is enabled, genksyms hashes the expanded C AST of every EXPORT_SYMBOL funct…
GL-E00 · Linux Host Workbench, POSIX Shell, Network Boot & Embedded C Style505/561

GL-E00 · 6.2 (m06-l02)

>_ Kernel Systems Academy

Inside .modinfo NUL Records, __versions CRCs, and KDIR Traps

fig_m06_l02_b.svg

Figure 6.2b: Every .modinfo tag is a simple NUL-terminated ASCII key=value string readable on any host without ARM hardware.

GL-E00 · Linux Host Workbench, POSIX Shell, Network Boot & Embedded C Style506/561

GL-E00 · 6.2 (m06-l02)

>_ Kernel Systems Academy

modinfo_vermagic_layout.c

learner@ksa: ~/gl-e00/m06-l02
learner@ksa:~/gl-e00/m06-l02$ bat 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)];    };
GL-E00 · Linux Host Workbench, POSIX Shell, Network Boot & Embedded C Style507/561

GL-E00 · 6.2 (m06-l02)

>_ Kernel Systems Academy

modinfo(8) / finit_module(2) / depmod(8)

modinfo(8) / finit_module(2) / depmod(8)(8) at a glance — GL-E00
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   m06-l02   modinfo(8) / finit_module(2) / depmod(8)(8) GL-E00 quick reference · full manual page: man 8 modinfo(8) / finit_module(2) / depmod(8) 
GL-E00 · Linux Host Workbench, POSIX Shell, Network Boot & Embedded C Style508/561

GL-E00 · 6.2 (m06-l02)

>_ Kernel Systems Academy

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…
GL-E00 · Linux Host Workbench, POSIX Shell, Network Boot & Embedded C Style509/561

GL-E00 · 6.2 (m06-l02)

>_ Kernel Systems Academy

Parsing .modinfo NUL Blobs and Symbol CRCs in Host C11

  • This exact .modinfo scanner becomes the second pillar of our Module 6 preflight capstone.
GL-E00 · Linux Host Workbench, POSIX Shell, Network Boot & Embedded C Style510/561

GL-E00 · 6.2 (m06-l02)

>_ Kernel Systems Academy

verify.c

learner@ksa: ~/gl-e00/m06-l02
learner@ksa:~/gl-e00/m06-l02$ bat 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;
GL-E00 · Linux Host Workbench, POSIX Shell, Network Boot & Embedded C Style511/561

GL-E00 · 6.2 (m06-l02)

>_ Kernel Systems Academy

Observing Token-Boundary Release Checks and Errno Separation

  • Notice line 33 of verify.c: strncmp(vm, uts_rel, rlen) == 0 && vm[rlen] == ' '!
GL-E00 · Linux Host Workbench, POSIX Shell, Network Boot & Embedded C Style512/561

GL-E00 · 6.2 (m06-l02)

>_ Kernel Systems Academy

Observing Token-Boundary Release Checks and Errno Separation

  • Notice also the [ 142.810412] prefix format: enabling CONFIG_PRINTK_TIME=y in your kernel config gives…
GL-E00 · Linux Host Workbench, POSIX Shell, Network Boot & Embedded C Style513/561

GL-E00 · 6.2 (m06-l02)

>_ Kernel Systems Academy

Observing Token-Boundary Release Checks and Errno Separation

learner@ksa: ~/gl-e00/m06-l02
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-l02
GL-E00 · Linux Host Workbench, POSIX Shell, Network Boot & Embedded C Style514/561

GL-E00 · 6.2 (m06-l02)

>_ Kernel Systems Academy

Observing Token-Boundary Release Checks and Errno Separation

strace — learner@ksa: ~/gl-e00/m06-l02
learner@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 +++
GL-E00 · Linux Host Workbench, POSIX Shell, Network Boot & Embedded C Style515/561

GL-E00 · 6.2 (m06-l02)

>_ Kernel Systems Academy

Makefile KDIR Defaults and insmod-vs-modprobe Confusion

  • Adopt two permanent rules for every driver Makefile you write in GL-E04..GL-E07.
GL-E00 · Linux Host Workbench, POSIX Shell, Network Boot & Embedded C Style516/561

GL-E00 · 6.2 (m06-l02)

>_ Kernel Systems Academy

Makefile KDIR Defaults and insmod-vs-modprobe Confusion

  • Second, install modules via make -C $(KDIR) M=$(PWD) INSTALL_MOD_PATH=/srv/nfs/rootfs modules_install so…
GL-E00 · Linux Host Workbench, POSIX Shell, Network Boot & Embedded C Style517/561

GL-E00 · 6.2 (m06-l02)

>_ Kernel Systems Academy

Warning

warning: - Symptom: You tweak 1 line in an .dts file inside KDIR, copy the new .dtb, then build a new .ko — and insmod rejects the .ko with version magic '6.12.0-dirty ...' should be '6.12.0 ...'! - Root Cause: With CONFIG_LOCALVERSION_AUTO=y, scripts/setlocalversion inspects git status in KDIR; modifying any tracked file appends -dirty to include/config/kernel.release used by .ko builds while the running zImage on 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 redeploy zImage alongside modules.

GL-E00 · Linux Host Workbench, POSIX Shell, Network Boot & Embedded C Style518/561

GL-E00 · 6.2 (m06-l02)

>_ Kernel Systems Academy

Warning

warning: - Symptom: insmod ./ap3216c.ko fails with Unknown symbol __iio_device_register (err -2) even though industrialio.ko exists under /lib/modules/. - Root Cause: insmod loads only the single file path passed to it and never reads modules.dep to load prerequisite modules first. - Fix: Run depmod -a once after installing .ko files and load modules by name with modprobe ap3216c (which loads industrialio.ko automatically).

GL-E00 · Linux Host Workbench, POSIX Shell, Network Boot & Embedded C Style519/561

GL-E00 · 6.2 (m06-l02)

>_ Kernel Systems Academy

Guided Practice

  • Extend verify.c to extract and parse the comma-separated depends= field from a .modinfo blob (e.g., `…
GL-E00 · Linux Host Workbench, POSIX Shell, Network Boot & Embedded C Style520/561

GL-E00 · 6.2 (m06-l02)

>_ Kernel Systems Academy

Guided Practice

  • Test your parser on both an empty "depends=\0" module (0 prerequisites) and a 2-dependency sensor mod…
GL-E00 · Linux Host Workbench, POSIX Shell, Network Boot & Embedded C Style521/561

GL-E00 · 6.2 (m06-l02)

>_ Kernel Systems Academy

Independent Practice

  • Write a 12-line out-of-tree Kbuild Makefile snippet guarded by ifeq ($(KERNELRELEASE),) that aborts w…
GL-E00 · Linux Host Workbench, POSIX Shell, Network Boot & Embedded C Style522/561

GL-E00 · 6.2 (m06-l02)

>_ Kernel Systems Academy

Independent Practice

  • Verify with make -n on a dummy directory containing include/config/kernel.release that missing KDIR f…
GL-E00 · Linux Host Workbench, POSIX Shell, Network Boot & Embedded C Style523/561

GL-E00 · 6.2 (m06-l02)

>_ Kernel Systems Academy

Quick check

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?

Select an option or press R to reveal.

GL-E00 · Linux Host Workbench, POSIX Shell, Network Boot & Embedded C Style524/561

GL-E00 · 6.2 (m06-l02)

>_ Kernel Systems Academy

Quick check

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?

Select an option or press R to reveal.

GL-E00 · Linux Host Workbench, POSIX Shell, Network Boot & Embedded C Style525/561

GL-E00 · 6.2 (m06-l02)

>_ Kernel Systems Academy

Quick check

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?

Select an option or press R to reveal.

GL-E00 · Linux Host Workbench, POSIX Shell, Network Boot & Embedded C Style526/561

GL-E00 · 6.2 (m06-l02)

>_ Kernel Systems Academy

Summary

  • During finit_module(), Linux kernel check_modinfo() compares .modinfo vermagic=<release> SMP preempt mod_unload ARMv7 p2v8 against utsname()->release and compile-time kernel tokens.
  • When insmod fails with -ENOEXEC (Invalid module format), timestamped dmesg (CONFIG_PRINTK_TIME=y) reveals exact version magic release/flag drift (such as -dirty or wrong host KDIR) or CONFIG_MODVERSIONS symbol CRC disagreement.
  • When insmod fails with -ENOENT (Unknown symbol in module, or unknown parameter), an exported dependency .ko is unloaded (resolved via depmod -a + modprobe), a CONFIG_* subsystem is disabled, or MODULE_LICENSE("GPL") was omitted for an EXPORT_SYMBOL_GPL symbol.
  • Out-of-tree driver Makefiles must point KDIR at the exact configured/built ARMv7-A Linux kernel 6.12 tree (ARCH=arm CROSS_COMPILE=arm-linux-gnueabihf-), never /lib/modules/$(uname -r)/build.
GL-E00 · Linux Host Workbench, POSIX Shell, Network Boot & Embedded C Style527/561

GL-E00 · 6.2 (m06-l02)

>_ Kernel Systems Academy

Key takeaways

  • When insmod fails with -ENOEXEC (Invalid module format), timestamped dmesg (CONFIG_PRINTK_TIME=y) reveals exact version magic release/flag drift (such as -dirty or wrong host KDIR) or CONFIG_MODVERSIONS symbol CRC disagreement.
  • When insmod fails with -ENOENT (Unknown symbol in module, or unknown parameter), an exported dependency .ko is unloaded (resolved via depmod -a + modprobe), a CONFIG_* subsystem is disabled, or MODULE_LICENSE("GPL") was omitted for an EXPORT_SYMBOL_GPL symbol.
  • Out-of-tree driver Makefiles must point KDIR at the exact configured/built ARMv7-A Linux kernel 6.12 tree (ARCH=arm CROSS_COMPILE=arm-linux-gnueabihf-), never /lib/modules/$(uname -r)/build.
GL-E00 · Linux Host Workbench, POSIX Shell, Network Boot & Embedded C Style528/561

GL-E00 · 6.3 (m06-l03)

>_ Kernel Systems Academy

End-to-End Embedded Workbench Preflight Capstone

free preview20 minlab lab_m06_workbench_preflight_capstone

What you'll learn

  • Verify ARM zImage (0x016F2818 at offset 0x24, little-endian) and Flattened Device Tree .dtb (0xD00DFEED at offset 0x00, big-endian) binary headers prior to TFTP export.
  • Integrate ELF32 armhf PT_INTERP rootfs checks and .modinfo vermagic token-boundary audits into a single zero-false-positive pipeline.
  • Complete the GL-E00 Capstone Studio (lab_m06_workbench_preflight_capstone) and measure CLOCK_MONOTONIC host preflight throughput.
GL-E00 · Linux Host Workbench, POSIX Shell, Network Boot & Embedded C Style529/561

GL-E00 · 6.3 (m06-l03)

>_ Kernel Systems Academy

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 b…
GL-E00 · Linux Host Workbench, POSIX Shell, Network Boot & Embedded C Style530/561

GL-E00 · 6.3 (m06-l03)

>_ Kernel Systems Academy

Closing the Loop Across All Six GL-E00 Workbench Foundations

  • Production BSP teams never rely on human memory to check all of these before copying files into /srv/tftp…
GL-E00 · Linux Host Workbench, POSIX Shell, Network Boot & Embedded C Style531/561

GL-E00 · 6.3 (m06-l03)

>_ Kernel Systems Academy

Closing the Loop Across All Six GL-E00 Workbench Foundations

fig_m06_l03_a.svg

Figure 6.3a: Every artifact entering /srv/tftp and /srv/nfs/rootfs is header-verified on the host before the board reboots.

GL-E00 · Linux Host Workbench, POSIX Shell, Network Boot & Embedded C Style532/561

GL-E00 · 6.3 (m06-l03)

>_ Kernel Systems Academy

Mental model

note: 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.

GL-E00 · Linux Host Workbench, POSIX Shell, Network Boot & Embedded C Style533/561

GL-E00 · 6.3 (m06-l03)

>_ Kernel Systems Academy

Flattened Device Tree (FDT) Magic (0xD00DFEED)

definition: 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.

GL-E00 · Linux Host Workbench, POSIX Shell, Network Boot & Embedded C Style534/561

GL-E00 · 6.3 (m06-l03)

>_ Kernel Systems Academy

Closing the Loop Across All Six GL-E00 Workbench Foundations

Note the endianness contrast: ARM zImage magic is little-endian, whereas FDT .dtb headers are big-endian!

Audit zImage (0x016F2818), FDT (0xD00DFEED), ELF32 armhf PT_INTERP, and .ko vermagic before boot!

GL-E00 · Linux Host Workbench, POSIX Shell, Network Boot & Embedded C Style535/561

GL-E00 · 6.3 (m06-l03)

>_ Kernel Systems Academy

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…
GL-E00 · Linux Host Workbench, POSIX Shell, Network Boot & Embedded C Style536/561

GL-E00 · 6.3 (m06-l03)

>_ Kernel Systems Academy

Binary Magic Signatures Across zImage, FDT .dtb, ELF32, and .ko

  • Reading uint32_t endianness explicitly via byte shifts (((uint32_t)b[0] << 24) | ... for big-endian FDT…
GL-E00 · Linux Host Workbench, POSIX Shell, Network Boot & Embedded C Style537/561

GL-E00 · 6.3 (m06-l03)

>_ Kernel Systems Academy

Binary Magic Signatures Across zImage, FDT .dtb, ELF32, and .ko

fig_m06_l03_b.svg

Figure 6.3b: Byte-shift endian readers parse zImage (LE), FDT .dtb (BE), and ELF32 (LE) without alignment Undefined Behavior.

GL-E00 · Linux Host Workbench, POSIX Shell, Network Boot & Embedded C Style538/561

GL-E00 · 6.3 (m06-l03)

>_ Kernel Systems Academy

workbench_preflight_manifest.h

learner@ksa: ~/gl-e00/m06-l03
learner@ksa:~/gl-e00/m06-l03$ bat 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) |
GL-E00 · Linux Host Workbench, POSIX Shell, Network Boot & Embedded C Style539/561

GL-E00 · 6.3 (m06-l03)

>_ Kernel Systems Academy

dtc(1) / mkimage(1) / file(1)

dtc(1) / mkimage(1) / file(1)(1) at a glance — GL-E00
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        m06-l03         dtc(1) / mkimage(1) / file(1)(1) GL-E00 quick reference · full manual page: man 1 dtc(1) / mkimage(1) / file(1) 
GL-E00 · Linux Host Workbench, POSIX Shell, Network Boot & Embedded C Style540/561

GL-E00 · 6.3 (m06-l03)

>_ Kernel Systems Academy

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 `0…
GL-E00 · Linux Host Workbench, POSIX Shell, Network Boot & Embedded C Style541/561

GL-E00 · 6.3 (m06-l03)

>_ Kernel Systems Academy

Running the Unified Boot-Blob, ELF32, and Vermagic Gate in C11

  • Then step into lab_m06_workbench_preflight_capstone to complete your full C11 pre-deployment auditor…
GL-E00 · Linux Host Workbench, POSIX Shell, Network Boot & Embedded C Style542/561

GL-E00 · 6.3 (m06-l03)

>_ Kernel Systems Academy

verify.c

learner@ksa: ~/gl-e00/m06-l03
learner@ksa:~/gl-e00/m06-l03$ bat 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)    {
GL-E00 · Linux Host Workbench, POSIX Shell, Network Boot & Embedded C Style543/561

GL-E00 · 6.3 (m06-l03)

>_ Kernel Systems Academy

Confirming Little-Endian zImage and Big-Endian FDT Validation

  • Notice how check_zimage_dtb() rejects dts_text instantaneously because ASCII "/dts" (0x2F647473) !=…
GL-E00 · Linux Host Workbench, POSIX Shell, Network Boot & Embedded C Style544/561

GL-E00 · 6.3 (m06-l03)

>_ Kernel Systems Academy

Confirming Little-Endian zImage and Big-Endian FDT Validation

  • Combined with ELF32 armhf PT_INTERP and .ko vermagic checks in the Capstone Lab, your host build…
GL-E00 · Linux Host Workbench, POSIX Shell, Network Boot & Embedded C Style545/561

GL-E00 · 6.3 (m06-l03)

>_ Kernel Systems Academy

Confirming Little-Endian zImage and Big-Endian FDT Validation

learner@ksa: ~/gl-e00/m06-l03
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-l03
GL-E00 · Linux Host Workbench, POSIX Shell, Network Boot & Embedded C Style546/561

GL-E00 · 6.3 (m06-l03)

>_ Kernel Systems Academy

Confirming Little-Endian zImage and Big-Endian FDT Validation

strace — learner@ksa: ~/gl-e00/m06-l03
learner@ksa:~/gl-e00/m06-l03strace -e trace=write,exit_group ./verifywrite(1, "PREFLIGHT_BLOBS zimage_magic=0x0"..., 94) = 94exit_group(0)                           = ?+++ exited with 0 +++
GL-E00 · Linux Host Workbench, POSIX Shell, Network Boot & Embedded C Style547/561

GL-E00 · 6.3 (m06-l03)

>_ Kernel Systems Academy

Common Deployment Mismatches Between bootz, bootm, and FDT

  • With GL-E00 complete, you own a repeatable, first-principles Linux embedded engineering workbench: isolat…
GL-E00 · Linux Host Workbench, POSIX Shell, Network Boot & Embedded C Style548/561

GL-E00 · 6.3 (m06-l03)

>_ Kernel Systems Academy

Common Deployment Mismatches Between bootz, bootm, and FDT

  • Carry this preflight mindset straight into GL-E01 (imx6ull-baremetal-core), where you will write `A…
GL-E00 · Linux Host Workbench, POSIX Shell, Network Boot & Embedded C Style549/561

GL-E00 · 6.3 (m06-l03)

>_ Kernel Systems Academy

Warning

warning: - Symptom: U-Boot prints Wrong Image Format for bootm command / ERROR: can't get kernel image! right after tftp 80800000 zImage succeeds. - Root Cause: bootm expects a legacy 64-byte uImage header (0x27051956 magic from mkimage) or FIT image, whereas bootz boots a raw ARM zImage (0x016F2818 at 0x24) directly! - Fix: Always pair ARM 32-bit zImage with bootz 0x80800000 - 0x83000000 (note the - placeholder when no separate initramfs is used).

GL-E00 · Linux Host Workbench, POSIX Shell, Network Boot & Embedded C Style550/561

GL-E00 · 6.3 (m06-l03)

>_ Kernel Systems Academy

Warning

warning: - Symptom: You modify a Device Tree .dts file and run make dtbs, yet /proc/device-tree/ on the booted board shows zero changes! - Root Cause: Linux kernel 6.12 organizes ARM vendor DTs under arch/arm/boot/dts/nxp/imx/; copying from a stale top-level build directory or editing an .dtsi not #included by your board's .dts deploys the old blob. - Fix: Run dtc -I dtb -O dts /srv/tftp/board.dtb | grep -A4 your_node on the staged /srv/tftp file before rebooting the board!

GL-E00 · Linux Host Workbench, POSIX Shell, Network Boot & Embedded C Style551/561

GL-E00 · 6.3 (m06-l03)

>_ Kernel Systems Academy

Guided Practice

  • Extend check_zimage_dtb() in verify.c to also reject legacy uImage headers (0x27051956 big-endian a…
GL-E00 · Linux Host Workbench, POSIX Shell, Network Boot & Embedded C Style552/561

GL-E00 · 6.3 (m06-l03)

>_ Kernel Systems Academy

Guided Practice

  • Test all three cases (zImage, uImage, and truncated .dtb where fdt_size = 4096 on a 512-byte file…
GL-E00 · Linux Host Workbench, POSIX Shell, Network Boot & Embedded C Style553/561

GL-E00 · 6.3 (m06-l03)

>_ Kernel Systems Academy

Independent Practice

  • Open labs/lab_m06_workbench_preflight_capstone/ and examine starter/core.c.
GL-E00 · Linux Host Workbench, POSIX Shell, Network Boot & Embedded C Style554/561

GL-E00 · 6.3 (m06-l03)

>_ Kernel Systems Academy

Independent Practice

  • Run sh check.sh (5/5 TAP version 13 checks passing) and ./files/lab_cli --bench to complete the **G…
GL-E00 · Linux Host Workbench, POSIX Shell, Network Boot & Embedded C Style555/561

GL-E00 · 6.3 (m06-l03)

>_ Kernel Systems Academy

Quick check

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?

Select an option or press R to reveal.

GL-E00 · Linux Host Workbench, POSIX Shell, Network Boot & Embedded C Style556/561

GL-E00 · 6.3 (m06-l03)

>_ Kernel Systems Academy

Quick check

In bootz 0x80800000 - 0x83000000, what does the middle hyphen (-) represent to U-Boot?

Select an option or press R to reveal.

GL-E00 · Linux Host Workbench, POSIX Shell, Network Boot & Embedded C Style557/561

GL-E00 · 6.3 (m06-l03)

>_ Kernel Systems Academy

Quick check

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?

Select an option or press R to reveal.

GL-E00 · Linux Host Workbench, POSIX Shell, Network Boot & Embedded C Style558/561

GL-E00 · 6.3 (m06-l03)

>_ Kernel Systems Academy

Lab: lab_m06_workbench_preflight_capstone

  • Deploying unverified cross-build outputs into /srv/tftp and /srv/nfs/rootfs turns single-line build mis…

Verify: ./check.sh exits 0.

GL-E00 · Linux Host Workbench, POSIX Shell, Network Boot & Embedded C Style559/561

GL-E00 · 6.3 (m06-l03)

>_ Kernel Systems Academy

Summary

  • A complete embedded workbench preflight gate validates boot blobs (ARM zImage magic 0x016F2818 at 0x24 and big-endian Device Tree .dtb magic 0xD00DFEED at 0x00), user-space ELF32 armhf binaries, and .ko vermagic before target deployment.
  • Every staged target executable must satisfy ELFCLASS32, EM_ARM (40), EF_ARM_ABI_FLOAT_HARD (0x400), and physical existence of its PT_INTERP loader and DT_NEEDED libraries inside /srv/nfs/rootfs.
  • Every staged .ko module under /srv/nfs/rootfs/lib/modules/<release>/ must carry license=GPL* and a vermagic matching <release> on an exact token boundary plus ARMv7 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.
GL-E00 · Linux Host Workbench, POSIX Shell, Network Boot & Embedded C Style560/561

GL-E00 · 6.3 (m06-l03)

>_ Kernel Systems Academy

Key takeaways

  • Every staged target executable must satisfy ELFCLASS32, EM_ARM (40), EF_ARM_ABI_FLOAT_HARD (0x400), and physical existence of its PT_INTERP loader and DT_NEEDED libraries inside /srv/nfs/rootfs.
  • Every staged .ko module under /srv/nfs/rootfs/lib/modules/<release>/ must carry license=GPL* and a vermagic matching <release> on an exact token boundary plus ARMv7 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.
GL-E00 · Linux Host Workbench, POSIX Shell, Network Boot & Embedded C Style561/561

slides — overview

cover

m01/ Host Virtualization Bridges, PTY Streams & Shell Pipelines

m02/ Filesystem Hierarchy, Permissions, Archives & Partition Guards

m03/ APT Package Graphs, Dual-NIC Routing & TFTP/NFS Boot Bench

m04/ Linux Kernel & Embedded C11 Coding Style & Defensive Hygiene

m05/ Serial Consoles, Boot Straps, UUU Flashing & Bring-Up Triage

m06/ Cross-ABI ELF Auditing, Module Vermagic & Workbench Capstone

search — fzf

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

keyboard shortcuts — less

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

figure