Modal Text Editing, Tree Search Pipelines & Workbench Audit Studio
Navigating an 80,000-file Linux kernel tree over headless SSH demands fluent modal editing without tab-damage accidents, NUL-safe tree search pipelines that never choke on whitespace or ARG_MAX limits, and automated host environment auditing.
What you'll learn
- Operate Vim across Normal, Insert, and Ex modes while auditing hard tabs with :set list in Makefiles and kernel configs.
- Construct NUL-delimited find -print0 | xargs -0 and grep -rn pipelines to locate Device Tree bindings and driver symbols safely.
- Implement a C11 workbench auditor verifying udev rules, dup2 redirection states, and colon-delimited PATH security invariants.
Surviving Headless Bring-Up Servers and 80,000-File Source Trees
Sooner or later every embedded engineer SSHes into a build server, a stripped Docker container, or a target BusyBox console where no GUI editor exists and /etc/fstab or a Device Tree source file needs an immediate surgical fix. vim (and BusyBox vi) models editing as an explicit finite-state machine (FSM): sessions always start in Normal mode where keys are motion and operator verbs (gg, G, /compatible, dd, ci", u).
Pressing i, a, or o enters Insert mode for raw text, Esc returns to Normal mode, and : enters Command-line (Ex) mode (:w, :q!, :%s/old/new/gc, :set list). Running :set list immediately exposes whether a Makefile recipe starts with a genuine 0x09 hard tab (^I) or spaces that trigger Makefile:14: *** missing separator. Stop.
Equally critical is searching huge trees (Linux kernel 6.12 exceeds 82,000 files) and auditing PATH strings safely. Naive shell loops like grep foo $(find . -name '*.c') overflow the kernel execve() ARG_MAX ceiling (E2BIG) and split filenames on spaces, while a single stray trailing colon in export PATH="/opt/arm/bin:$PATH:" silently adds . (the current working directory!) to command lookup!
Figure 1.3a. NUL (0x00) is the sole byte value illegal inside POSIX path components, making -print0 | xargs -0 immune to spaces and quotes.
mental model: Using newline-delimited find | xargs on arbitrary trees is like shipping parts in a crate where commas separate item names, even though product labels themselves can contain commas! Switching to find -print0 | xargs -0 seals each path with 0x00—a physical bulkhead byte that the Linux kernel VFS forbids inside any filename—while scanning PATH with strchr instead of strtok inspects every empty crate slot (::) rather than skipping past empty compartments.
Where it stops working: For interactive human queries in clean Git repositories, grep -rn --include='*.[ch]' or git grep -n avoids spawning find + xargs altogether by walking directory dentries inside a single process without building giant argv[] vectors.
definition (Empty PATH Segment (Implicit '.') and Vim Swap Recovery): Under historical POSIX.1 shell lookup rules, an empty colon-separated field in PATH—whether leading (:/usr/bin), adjacent (usr/bin::/bin), or trailing (/usr/bin:)—is interpreted as . (the current working directory). Writing export PATH="/opt/arm/bin:$PATH" when $PATH was unset expands to "/opt/arm/bin:", letting an untrusted source archive hijack make or ls! Meanwhile, vim protects active edits via .filename.swp journals; if an SSH link drops, inspect differences with vim -r filename before removing stale swap files.
- Step 1. Open target files directly at the diagnostic line (+42), run :set list in Ex mode to distinguish ^I tabs from spaces, and write atomically.
- Step 2. Search kernel subsystems by compatible string or symbol using grep -rn --include to skip compiled .o and .ko binaries.
- Step 3. Pipe find -print0 into xargs -0 -r whenever passing file lists to external tools across large directory trees.
- Step 4. Execute the Module 1 TAP-13 studio to verify all host workbench invariants and record CLOCK_MONOTONIC percentiles.
Figure 1.3b. Use :set list for tabs, -print0 | xargs -0 for paths, and strchr to audit PATH.
Inside Vim State Transitions, VFS Filename Bytes & C11 PATH Scanning
In Linux kernel fs/namei.c, path resolution splits strings solely on '/' (0x2F) and terminates C strings on '\0' (0x00); literally every other byte 0x01..0xFF (including ' ' 0x20, '\t' 0x09, and '\n' 0x0A) can legally exist inside an ext4 directory entry! That single kernel invariant explains why find ... -print0 paired with xargs -0 -r is mathematically lossless, whereas line-oriented pipelines break on embedded vendor drops containing spaces like Schematics Rev 1.2/.
Notice the classic C11 bug waiting inside our workbench PATH auditor: if an engineer uses strtok(buf, ":") to split PATH="/usr/bin::/bin", ISO C strtok() treats consecutive delimiters "::" as a single separator and returns only "/usr/bin" and "/bin", completely missing the empty segment ("" -> current directory .)! Scanning explicitly with strchr(cursor, ':') inspects seg_len == 0, catching leading :, interior ::, and trailing : every time—hence shell scripts must write PATH="/new/dir${PATH:+:$PATH}".
Figure 1.3b. Explicit colon-pointer scanning catches leading ':', interior '::', and trailing ':' hazards that C strtok() silently skips.
| Task | Fragile Command / Idiom | Production Command / Idiom | Defect Prevented | |
|---|---|---|---|---|
Prepend dir to PATH | export PATH="/opt/arm/bin:$PATH" | export PATH="/opt/arm/bin${PATH:+:$PATH}" | Avoids trailing : (CWD .) when PATH was unset/empty | |
| Bulk file search | grep -n foo $(find . -name '*.c') | `find . -type f -name '*.c' -print0 | xargs -0 -r grep -n foo` | Prevents execve E2BIG overflow and space/quote splitting |
| Targeted kernel search | grep -r foo . (scans .git & .o) | grep -rn --include='*.[ch]' foo drivers/ | Skips binary .o/.ko noise and prints exact file:line | |
| Makefile edit over SSH | Space-indented recipe + :q hang | vim Makefile -> :set list (^I) -> :wq | Eliminates missing separator tab errors |
learner@ksa:~/gl-e00/m01-l03$ bat -H 6 -H 14 tree_and_path_audit.sh File: tree_and_path_audit.sh #!/usr/bin/env bash set -euo pipefail # 1. Safe parameter expansion: appends :$PATH only when PATH is non-empty TOOLCHAIN_BIN="/opt/toolchains/arm-gnu-toolchain/bin" export PATH="${TOOLCHAIN_BIN}${PATH:+:${PATH}}" # 2. Reject any empty PATH segment (leading ':', '::', or trailing ':') case ":${PATH}:" in *::*) echo "FATAL: empty PATH segment (implicit CWD '.') detected" >&2; exit 1 ;; esac # 3. NUL-delimited search across Device Tree bindings and C headers find . -type f \( -name "*.dts*" -o -name "*.h" \) -print0 | xargs -0 -r grep -n "compatible"- ${PATH:+:${PATH}} expands to nothing if PATH is empty, preventing a trailing ':' current-directory hazard.
- -print0 paired with xargs -0 -r frames every path with NUL (0x00) and skips execution cleanly on zero matches.
xargs(1) GL-E00 Quick Reference xargs(1) NAME find, xargs, grep, vim - tree search pipelines and modal file editing SYNOPSIS find <dir> -type f -name "*.c" -print0 | xargs -0 -r grep -n "<pattern>" grep -rn --include="*.[ch]" "<pattern>" <dir>/ vim +<line> <file> (Normal: Esc, /pat, n, u, dd | Insert: i, a, o | Ex: :set list, :wq, :q!) FLAGS -print0 / -0 Use NUL (0x00) instead of whitespace/quotes as record separator. -r (--no-run-if-empty) Do not invoke command when input stream is empty. :set list Render hard tabs as ^I and end-of-line as $ inside vim. Kernel Systems Academy Lesson 1.3 xargs(1) GL-E00 quick reference · full manual page: man 1 xargs Verifying NUL-Delimited Streams and Colon-Exact PATH Parsing in C11
In verify.c, we test both halves of Lesson 1.3 directly in ISO C11. First, we write a real NUL-delimited (-print0) stream containing a path with embedded spaces ("boards/rev B/pin mux.c") into an unprivileged temporary file, read it back, and prove that 0x00 framing preserves all 3 filenames intact where whitespace splitting produces 5 broken fragments.
Second, we contrast audit_path_strchr() against count_strtok_segments() on "/usr/bin::/bin". Notice how strtok() silently reports 2 clean segments while strchr() catches the 0-length middle segment (rc = -2), giving you the exact pattern needed for the Module 1 graded lab studio.
learner@ksa:~/gl-e00/m01-l03$ bat -H 14 -H 40 verify.c File: verify.c #define _POSIX_C_SOURCE 200809L #include <fcntl.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <unistd.h> static int audit_path_strchr(const char *path_str, int *seg_count) { if (!path_str || path_str[0] == '\0') return -1; *seg_count = 0; const char *p = path_str; for (;;) { const char *colon = strchr(p, ':'); size_t len = colon ? (size_t)(colon - p) : strlen(p); (*seg_count)++; if (len == 0) return -2; /* Empty segment ('::', leading/trailing ':') -> CWD '.' */ if (p[0] != '/') return -3; /* Relative directory in PATH */ if (!colon) break; p = colon + 1; } return 0; } static int count_strtok_segments(const char *path_str) { char tmp[128]; snprintf(tmp, sizeof(tmp), "%s", path_str); int n = 0; char *save = NULL; for (char *t = strtok_r(tmp, ":", &save); t; t = strtok_r(NULL, ":", &save)) n++; return n; } int main(void) { char tmpl[] = "/tmp/ksa_print0_XXXXXX"; int fd = mkstemp(tmpl); if (fd < 0) return 1; static const char nul_stream[] = "drivers/tty/serial.c\0boards/rev B/pin mux.c\0include/linux/init.h\0"; size_t stream_len = sizeof(nul_stream) - 1; if (write(fd, nul_stream, stream_len) != (ssize_t)stream_len) { unlink(tmpl); close(fd); return 1; } lseek(fd, 0, SEEK_SET); char buf[128] = {0}; ssize_t r = read(fd, buf, sizeof(buf)); close(fd); unlink(tmpl); if (r != (ssize_t)stream_len) return 1; int nul_records = 0; for (ssize_t i = 0; i < r; ++i) { if (buf[i] == '\0') nul_records++; } const char *good_path = "/opt/toolchains/arm/bin:/usr/bin:/bin"; const char *bad_path = "/usr/bin::/bin"; int n_good = 0, n_bad = 0; int rc_good = audit_path_strchr(good_path, &n_good); int rc_bad = audit_path_strchr(bad_path, &n_bad); int strtok_seen = count_strtok_segments(bad_path); printf("print0_stream: bytes=%zd nul_records=%d second_record='%s'\n", r, nul_records, buf + strlen(buf) + 1); printf("path_audit: clean_rc=%d(segs=%d) double_colon_rc=%d strtok_blind_segs=%d\n", rc_good, n_good, rc_bad, strtok_seen); return (nul_records == 3 && rc_good == 0 && n_good == 3 && rc_bad == -2 && strtok_seen == 2) ? 0 : 1; }- strchr() measures exact distance to the next ':' so consecutive '::' yields len == 0 and returns -2 immediately.
- Writing and reading raw 0x00-terminated records preserves 'boards/rev B/pin mux.c' as one intact path.
Confirming NUL Framing and strtok Blindness Under strace
Check both the program output and the strace capture. verify creates /tmp/ksa_print0_XXXXXX via openat(), writes 65 bytes containing 3 NUL-terminated records (preserving spaces inside "boards/rev B/pin mux.c"), unlinks the scratch file cleanly, and proves that strtok_r sees only 2 segments on "/usr/bin::/bin" while audit_path_strchr catches the hidden len == 0 segment (rc = -2).
learner@ksa:~/gl-e00/m01-l03gcc -std=c11 -Wall -Wextra -Werror verify.c -o verifylearner@ksa:~/gl-e00/m01-l03./verifyprint0_stream: bytes=65 nul_records=3 second_record='boards/rev B/pin mux.c'path_audit: clean_rc=0(segs=3) double_colon_rc=-2 strtok_blind_segs=2learner@ksa:~/gl-e00/m01-l03learner@ksa:~/gl-e00/m01-l03strace -e trace=openat,read,write,unlinkat \./verifyopenat(AT_FDCWD, "/etc/ld.so.cache", O_RDONLY|O_CLOEXEC) = 3openat(AT_FDCWD, "/lib/x86_64-linux-gnu/libc.so.6", O_RDONLY|O_CLOEXEC) = 3read(3, "\177ELF\2\1\1\3\0\0\0\0\0\0\0\0\3\0>\0\1\0\0\0\220\243\2\0\0\0\0\0"..., 832) = 832openat(AT_FDCWD, "/tmp/ksa_print0_0GSgQx", O_RDWR|O_CREAT|O_EXCL, 0600) = 3write(3, "drivers/tty/serial.c\0boards/rev "..., 65) = 65read(3, "drivers/tty/serial.c\0boards/rev "..., 128) = 65write(1, "print0_stream: bytes=65 nul_reco"..., 147) = 147+++ exited with 0 +++Modal Editing and Tree-Pipeline Pitfalls
Fluency with modal editing, NUL-delimited search streams, and strict environment hygiene turns any headless Linux box into a predictable embedded workbench. Before moving on to Module 2's filesystem and partition-table mechanics, complete the graded lab_m01_shell_env_audit studio below.
Makefile 'missing separator' After Copy-Pasting From Browser or Terminal:
- Symptom:
makeaborts immediately on line 12 withMakefile:12: *** missing separator. Stop.even though indentation looks aligned. - Root Cause: Terminal mouse selection converted the leading
0x09hard tab (\t) into4or8ASCII spaces (0x20), which GNUmakerejects on recipe lines. - Fix: Open the
Makefileinvim, run:set listto verify whether lines begin with^I(tab) or spaces, and replace leading spaces on recipe lines with a literalTab(:set noexpandtab).
Deleting a Vim .swp File Without Checking Crash Recovery:
- Symptom:
vimwarnsSwap file ".board.dts.swp" already exists!and an engineer reflexively pressesD(Delete) or runsrm .*.swp, losing an hour of unsavedDevice Treeedits. - Root Cause: Either a second terminal window currently has
board.dtsopen (ps aux | grep vim), or a dropped SSH session left unsaved buffer deltas inside.board.dts.swp. - Fix: First check whether another live
vimPID owns the file; if none exists, open withvim -r board.dts, save to a recovery copy (:w board.dts.recovered), diff withdiff -u, and only then remove.board.dts.swp.
Guided Practice
Extend audit_path_strchr() in verify.c to accept an array of mode_t directory permission values corresponding to each PATH segment and return -4 if any directory has the world-writable 0002 bit set (for example /tmp with 01777), even when the sticky bit is present.
Independent Practice
Now open labs/lab_m01_shell_env_audit/ and repair all three defects in starter/core.c so sh check.sh passes 5/5 TAP version 13 checks and ./files/lab_cli --bench prints CLOCK_MONOTONIC percentiles.
Verification Checks
→ open standalone lab workbench
1. Motivation
Onboarding scripts for embedded Linux teams routinely break because one typo in /etc/udev/rules.d/ grants world-writable 0666 permissions or fails to match 15a2:0080, inverted 2>&1 >log redirection loses compiler errors, and an unguarded PATH append introduces an implicit . current-directory vulnerability. In this studio you repair a deterministic ISO C11 workbench auditor that enforces all three contracts before a host machine touches target hardware.
2. Learning objectives
- Enforce udev
==predicate syntax, 4-digit hexidVendor/idProductbounds, and non-world-writable!(mode & 0002)rules. - Model left-to-right POSIX
dup2(oldfd, newfd)descriptor routing across>build.log 2>&1and2>&1 >build.log. - Scan colon-delimited
PATHstrings via pointer arithmetic (strchr) to reject leading:, interior::, trailing:, and world-writable (0002) directories.
3. Environment requirements
All automated verification steps run in unprivileged user space on a POSIX Linux host using gcc -std=c11 -Wall -Wextra -Werror and clock_gettime(CLOCK_MONOTONIC). Recorded transcripts in captures.json were generated on x86_64 running kernel 7.0.0-42-generic and prove protocol, state-machine, and memory invariants only. Physical bus timing, DMA cache coherency, and board peripheral behavior require target validation on Linux kernel 6.12 LTS (ARMv7-A Cortex-A7).
4. Required software and hardware
- Host workstation:
gcc(-std=c11 -Wall -Wextra -Werror), GNUmake,ar(binutils), and POSIX/bin/sh. - Target environment (optional hardware step, Section 13):
ARMv7-ACortex-A7board connected viaCH340(1a86:7523) USB-UART console and USB OTGSDP(15a2:0080) recovery cable to verify/dev/ttyBENCH0symlink creation underudevadm.
5. Complete executable commands
learner@ksa:~/gl-e00/m01-l03$ bat script.sh File: script.sh make -B -C files ./files/lab_cli ./files/lab_cli --bench sh check.sh6. Annotated source code
files/core.c enforces the production invariants that starter/core.c breaks:
learner@ksa:~/gl-e00/m01-l03$ bat example.c File: example.c if ((m & 0002UL) != 0) return -5; /* Reject world-writable 0666 */ ... const char *colon = strchr(p, ':'); size_t len = colon ? (size_t)(colon - p) : strlen(p); if (len == 0) { out->empty_seg_index = (int)idx; return -2; /* Empty segment -> implicit '.' CWD hazard */ }starter/core.c contains three realistic defects: (1) ksa_audit_udev_rule() masks m & 0000UL and lets MODE="0666" slip through; (2) ksa_simulate_redir() ignores left-to-right dup2() order when log_first == 0; and (3) ksa_audit_path_env() fails to reject len == 0 empty :: or trailing : segments.
7. Expected output
Passing files/ run (sh check.sh, exit code 0):
learner@ksa:~/gl-e00/m01-l03$ bat listing.txt File: listing.txt TAP version 13 1..5 ok 1 - builds libcore.a and lab_cli cleanly with -std=c11 -Wall -Wextra -Werror ok 2 - archives core.o into libcore.a and links independent TAP verifier ok 3 - validates udev == predicates, hex4 VID:PID, and rejects world-writable MODE 0666 ok 4 - models left-to-right dup2 order distinguishing >log 2>&1 from 2>&1 >log ok 5 - audits colon-delimited PATH rejecting empty ::/trailing : and 0002 world-writable dirs # pass 5/5CLI verification output (./files/lab_cli):
learner@ksa:~/gl-e00/m01-l03$ bat listing.txt File: listing.txt udev_ch340: rc=0 mode=0660 redir_order: gt_log_2gt1=(1,1) 2gt1_gt_log=(1,0) path_audit: clean_rc=0(segs=3) double_colon_rc=-2(empty_idx=1)Defective starter/ run (exit code 1): emits FAIL: diagnostics on the broken contract assertions.
8. Explanation of observed behavior
When all three invariants are restored in files/core.c, sh check.sh compiles libcore.a cleanly under -std=c11 -Wall -Wextra -Werror, links the independent tests.c harness, and verifies all 5 TAP version 13 assertions (CH340 + 15a2:0080 udev rules, dup2 redirection order, and colon-exact PATH auditing).
9. Experiment variations
- Near transfer: Extend
ksa_audit_udev_rule()to rejectSYMLINK="..."(overwrite=) and requireSYMLINK+="..."(append+=) so custom bench aliases never wipe out/dev/serial/by-id/links. - Far transfer: Write a companion shell/C11 preflight tool that reads live
/etc/udev/rules.d/*.rulesandgetenv("PATH")+stat(2)on your workstation, failing CI if any directory inPATHis writable by group or other (st_mode & 0022).
10. Performance measurements
Recorded host benchmark (./files/lab_cli --bench, CLOCK_MONOTONIC, warmup=5, N=40 batches):
learner@ksa:~/gl-e00/m01-l03$ bat listing.txt File: listing.txt BENCH lab_m01_shell_env_audit clock=CLOCK_MONOTONIC warmup=5 samples=40 p50_ns=468 p95_ns=484 p99_ns=497 sink=0The CLOCK_MONOTONIC numbers above measure pure in-memory C11 rule and PATH parsing cost on the host CPU (p50 typically sub-microsecond per 3-call batch). Never extrapolate these host numbers to physical USB 2.0 enumeration (~tens of milliseconds) or systemd-udevd netlink worker fork latency.
11. Troubleshooting
| Symptom | Root cause | Fix |
|---|---|---|
not ok 3 - validates udev == predicates... | ksa_audit_udev_rule() still permits (m & 0002UL) != 0 (MODE="0666"). | Check (m & 0002UL) != 0 after strtoul(val, &end, 8) and return -5. |
not ok 4 - models left-to-right dup2 order... | log_first == 0 updates fd1 before copying fd1 into fd2. | In the else branch (2>&1 >log), set fd2 = fd1 (FD_TARGET_PTS) first, then fd1 = FD_TARGET_LOG. |
not ok 5 - audits colon-delimited PATH... | strtok() was used or len == 0 check is disabled, missing :: and trailing :. | Keep the strchr(p, ':') loop and return -2 whenever len == 0. |
12. Guided questions
- Why does
ksa_audit_path_env()reject/tmp(01777) when(dir_modes[idx] & 0002U) != 0even though/tmphas the sticky bit (01000) set?
- *Hint 1:* What does the sticky bit (
01000) prevent (unlink/renameof existing files), and what does0002(o+w) still allow any local user to create? - *Hint 2:* Any unprivileged user can still create a brand-new executable (such as a fake
arm-linux-gnueabihf-gccorsltypo binary) inside/tmpif it does not yet exist!
- Why does
strtoul(val, &end, 8)explicitly pass base8instead of base0when parsingMODE="0660"?
- *Hint 1:* What happens under base
0if someone writesMODE="660"without a leading'0'? - *Hint 2:* Base
0parses"660"as decimal660(01224octal!) instead of octal0660, whereasudevalways interpretsMODEstrings in base8.
13. Independent challenges
Add a ksa_audit_sudo_secure_path() function to core.c that compares a developer's cross-build PATH against /etc/sudoers secure_path, returning the exact list of stripped toolchain directories so an onboarding doctor CLI can explain why sudo make failed.
14. Solutions and explanations
The reference files/core.c validates == predicates and !(m & 0002UL) octal permissions in ksa_audit_udev_rule(), preserves strict left-to-right fd2 = fd1; fd1 = FD_TARGET_LOG; ordering in ksa_simulate_redir(0, ...), and scans raw : boundaries with strchr() in ksa_audit_path_env() to reject empty segments and world-writable directories.
Run locally in your terminal and check off each verification milestone.
Not started
Key takeaways
- 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.