interplane.Get Omega
Read in your language

CUDApp

CUDA++: AIEN’s GPU machine-code toolchain, runtime and driver client for NVIDIA GPUs without the CUDA toolkit. Hardware coverage and driver replacement limits are explicit.

Brought by drakestapleton

Delegated swap builds a trusted tree; elementwise tail length is host-gated

open 495414b7b528923a #3 · opened 2026-11-15 17:54 UTC

Imported from GitHub drakestapleton/CUDApp#3, by drakestapleton

Base e22417fe3e66095eac99557a37eaf4bd2ceb72a7 · Head 87b154d338d31b8ef891fd76b3382c5d1ef8978c

drakestapleton wrote on 2026-11-15 17:54 UTC

Purpose and scope

Two Codex Security drafts on the GitHub mirror (#1 privileged swap helper, #2 elementwise tail overwrite) were reviewed against forge HEAD e22417fe3e66095eac99557a37eaf4bd2ceb72a7. The mirror HEAD ce03c88 is behind that forge commit and still has the elementwise bug. This branch is two commits on top of the forge commit. Apply the format-patch series to the forge. Do not merge this pull request into the mirror's main.

GitHub #1 and #2 should be closed in favor of this series. Neither draft was merged.

Finding 1, real: delegated swap/cudapp runs caller-selected Kbuild as root

Severity: high where a sudoers rule names only this script. A user who already has unrestricted sudo is not escalated further.

swap/cudapp is the same blob on the forge and the mirror. With --yes, a non-root caller re-execs sudo "$0" swap ... without -E. A script-only sudoers rule rejects environment assignments (BASH_ENV, SUDO_UID, CUDAPP_DRIVER_SRC, sudo -E) and still accepts arguments. Root then copied --driver-src / CUDAPP_DRIVER_SRC and ran make -C "$KDIR". That Kbuild executes as root. Reproduced with a fake make and a fake machine root: the attacker Kbuild's first line was logged and aien_gpu.ko was installed.

Codex #1 pins /usr/src/aien-gpu and refuses --driver-src. It still forwards --kdir, so make -C that directory remains caller-selected. It also leaves CUDAPP_KDIR and a sudo CUDAPP_ROOT in play, and it describes the tree as immutable without chattr.

This commit (1d2d3b93d891514f000ccf585cf668062ddc7207), swap/cudapp and tests/swap/test_swap_cli.sh:

  • A delegated kernel or all swap (SUDO_UID set to a non-root user) refuses --driver-src, --kdir, CUDAPP_DRIVER_SRC, CUDAPP_KDIR, and CUDAPP_ROOT when the process is actually root.
  • It builds /usr/src/aien-gpu against /lib/modules/$(uname -r)/build.
  • Every real component is owned by root and not group/other-writable. GNU ls + (an ACL) is refused. The module source may contain no symlink.
  • /lib → usr/lib and the kernel build symlink are followed when the link is owned by root and the resolved directory stays under /lib/modules, /usr/lib/modules, or /usr/src.
  • make and cc come from a fixed PATH. Those directories and the resolved binaries must be root-owned and not group/other-writable. The delegated make runs under env -i.
  • A direct root shell (SUDO_UID unset) can still pass --driver-src and --kdir.

The sudoers rule must name a root-owned copy of the script, mode 755, and must not grant SETENV. With SETENV, BASH_ENV runs before any line of the script. POSIX ACLs are detected via the ls + mark; getfacl is not installed here.

Finding 2, real on the mirror, already fixed on forge HEAD

Severity: high memory safety on mirror ce03c88 and on the forge before 97fc9eb3. Forge HEAD already stages each chunk from that chunk's record count.

run_1d planned the whole n once. Mode 2 sets the staged length to min(n, 131072) * 4. After the per-chunk plan calls were removed, the tail reused that length. For n=131073 the tail is 1 element (4 bytes) and the copy was 524288 bytes. The chip receipt evidence/elementwise-tail-chunk-20261112/ records SIGSEGV; evidence/chip-gates-shared-20261112/after-97fc9eb3/elementwise.txt records swiglu_131073 passing after 97fc9eb3.

Codex #2 patches the mirror line bytes=p[10], which is gone on the forge, so that diff does not apply. Its host test includes the .c file and never calls run_1d. Its chip-test edits change case sizes and need a GPU.

This commit (87b154d338d31b8ef891fd76b3382c5d1ef8978c) keeps the 97fc9eb3 length (rec[0] * 4, refused when the record exceeds the remaining count) and adds omega_gpu_elementwise_test_stage_bytes. The probe is listed only in docs/runtime/omega_runtime_api.internal. It does not open a device. Putting bytes = p[10] back makes make test-gpu-elementwise fail: the tail is reported as 524288. Restoring the per-chunk length passes.

tests/gpu_elementwise_test.c swiglu_131073 is the existing chip check. Re-run ./build/gpu_elementwise_test --out receipt.json on a DGX Spark GB10 (sm_121, open kernel module 580.173.02) inside an authorized GPU window to reconfirm. No new chip case was added.

Evidence on the exact commit

HEAD 87b154d338d31b8ef891fd76b3382c5d1ef8978c, parent 1d2d3b93d891514f000ccf585cf668062ddc7207, base e22417fe3e66095eac99557a37eaf4bd2ceb72a7. Host is Linux x86_64, gcc, no GPU. These rows are host checks, not a chip qualification.

  • bash tests/swap/test_swap_cli.sh — PASS, exit 0, swap cli: 121 passed, 0 failed. Includes the delegated refusals, a locked /lib → usr/lib build, an escaping /lib symlink, and sudo -n of the script (reaches "trusted aien_gpu source not found", no compiler-path failure, no /etc/modprobe.d/cudapp-swap-kernel.conf).
  • make test-gpu-elementwise — PASS, exit 0, PASS: 29 checks, 0 failed. The p[10] mutation failed first: FAIL: n=131073 stages a 524288-byte chunk then a 4-byte tail and the negative control (2 failed). The mutation is not in the commit.
  • make test-runtime-api — PASS, exit 0. The log's FAIL lines are the script's negative controls.
  • make test — NOT RUN. The full host suite is about an hour under qemu on this VM. The two affected targets above are the ones this change can break.
  • make test-native-artifact — NOT RUN.
  • make zero-cuda-gate — NOT RUN.
  • build/hello_gpu --sim — NOT RUN.
  • make doctor — NOT RUN. On this VM it is expected to print NOT READY (no NVIDIA module).
  • GB10 hardware tests — NOT RUN. No authorized GPU window. The elementwise overflow already has a chip receipt at 97fc9eb3. Confirm again with ./build/gpu_elementwise_test --out receipt.json on a GB10 before calling the tail fix newly qualified.

Correctness, compatibility and provenance

  • Negative controls: attacker Kbuild, writable and symlinked sources, a kdir symlink to a mode 777 tree, a /lib symlink that leaves the fixture, and the p[10] tail length.
  • The new symbol is a TEST ONLY hook in the internal list, not a public manifest entry. No README or ROADMAP status change. No Omega consumer ABI change.
  • No third-party or NVIDIA material added. SPDX headers on the touched sources are unchanged.
  • No secrets, private paths, or vendor binaries. The temporary sudoers probe user was removed.
  • Existing receipts were not edited.

Known limitations

Direct root (SUDO_UID unset) may still build a caller-selected tree; that is the administrator path. SETENV on the sudoers rule bypasses every in-script check via BASH_ENV. The format-patch series for the forge is 0001-swap-a-delegated-root-build-no-longer-runs-caller-se.patch and 0002-elementwise-host-gate-locks-the-1d-tail-chunk-at-its.patch, based on e22417fe. Nothing was pushed to https://interplane.io/drakestapleton/CUDApp.git.

<div><a href="https://cursor.com/agents/bc-e5ac067a-be50-5307-be64-e96ea21c50d1?cursor_ref=pr_footer&cursor_cta=open_in_web"><picture><source media="(prefers-color-scheme: dark)" srcset="https://cursor.com/assets/images/open-in-web-dark.png"><source media="(prefers-color-scheme: light)" srcset="https://cursor.com/assets/images/open-in-web-light.png"><img alt="Open in Web" width="114" height="28" src="https://cursor.com/assets/images/open-in-web-dark.png"></picture></a> <a href="https://cursor.com/background-agent?bcId=bc-e5ac067a-be50-5307-be64-e96ea21c50d1&cursor_ref=pr_footer&cursor_cta=open_in_cursor"><picture><source media="(prefers-color-scheme: dark)" srcset="https://cursor.com/assets/images/open-in-cursor-dark.png"><source media="(prefers-color-scheme: light)" srcset="https://cursor.com/assets/images/open-in-cursor-light.png"><img alt="Open in Cursor" width="131" height="28" src="https://cursor.com/assets/images/open-in-cursor-dark.png"></picture></a> </div>

Apply it

git checkout -b patch-495414b7b528923a e22417fe3e66095eac99557a37eaf4bd2ceb72a7
curl -fsSL https://interplane.io/drakestapleton/CUDApp/patches/495414b7b528923a.patch | git am

Raw patch (mbox) · Diff

Provenance

This proposal is imported from GitHub; it is not signed by its author. Its import statement and source record:

github-import 1
drakestapleton/CUDApp
3
87b154d338d31b8ef891fd76b3382c5d1ef8978c
{"kind":"github-import","owner":"drakestapleton","repo":"CUDApp","number":3,"url":"https://github.com/drakestapleton/CUDApp/pull/3","export_sha256":"47b9e2c453935cee8da188bd59c976ababe9290e5e88e31eaf77f752aade7d4c","imported_utc":"2026-11-18T16:39:25Z"}

Changes

diff --git a/docs/runtime/omega_runtime_api.internal b/docs/runtime/omega_runtime_api.internal
index 70eb77bf..b4b967c3 100644
--- a/docs/runtime/omega_runtime_api.internal
+++ b/docs/runtime/omega_runtime_api.internal
@@ -137,6 +137,7 @@ fn omega_gpu_elementwise_codegen_ir # kernel builder used by the library and its
 fn omega_gpu_elementwise_last_error # serving-daemon internals; aien-sovereign-core does not bind it; candidate EXPERIMENTAL
 fn omega_gpu_elementwise_test_set_mutant # TEST ONLY: test hook (mutant, simulator, split or counter) for the library's own batteries
 fn omega_gpu_elementwise_test_set_mutant_level # TEST ONLY: test hook (mutant, simulator, split or counter) for the library's own batteries
+fn omega_gpu_elementwise_test_stage_bytes # TEST ONLY: host probe of the 1d chunk byte count; does not launch
 fn omega_gpu_engine_test_force_block # TEST ONLY: a blocked process must stay blocked because the GPU may still be running
 fn omega_gpu_engine_test_reset_block # TEST ONLY: a blocked process must stay blocked because the GPU may still be running
 fn omega_gpu_engine_test_set_clock # TEST ONLY: a blocked process must stay blocked because the GPU may still be running
diff --git a/src/omega_gpu_elementwise_api.c b/src/omega_gpu_elementwise_api.c
index 53493b2c..38e851d4 100644
--- a/src/omega_gpu_elementwise_api.c
+++ b/src/omega_gpu_elementwise_api.c
@@ -1117,29 +1117,77 @@ int omega_gpu_rope_f32(uint32_t heads, uint32_t head_dim, const float *v,
     return rc;
 }
 
+/* Bytes this chunk may stage. rec[0] is this chunk's count (av_ew_rec caps a
+ * 1d chunk at 131072). The plan's p[10] is that cap for the whole n, so a
+ * shorter tail must not reuse it: swiglu_131073's last chunk is 4 bytes, and
+ * copying p[10] (524288) wrote past the caller's buffer (97fc9eb3). */
+static int ew_1d_extent(uint32_t remaining, uint64_t record_count, uint32_t *count, size_t *bytes) {
+    if (record_count == 0 || record_count > remaining || record_count > (uint64_t)SIZE_MAX / 4u)
+        return OMEGA_GPU_EW_BAD_ARGS;
+    *count = (uint32_t)record_count;
+    *bytes = (size_t)record_count * 4u;
+    return OMEGA_GPU_EW_OK;
+}
+
+/* TEST ONLY. When set, run_1d records each chunk's byte count and does not
+ * open the device or touch the caller buffers. The host gate reads it back. */
+static int g_stage_probe;
+static size_t g_stage_bytes[8];
+static uint32_t g_stage_n;
+
 static int run_1d(OmegaGpuEwOp op, uint32_t n, const void *a, const void *b, void *c, OmegaGpuEwInfo *info) {
     uint64_t t0 = now_ns();
     uint64_t p[16]={n};int plan_rc=ap_plan(AP_EW,2,p);
     if(plan_rc)return plan_rc;
     Slot *k = NULL;
-    int rc = begin(op, &k, info);
-    if (rc != OMEGA_GPU_EW_OK) return rc;
+    int rc = OMEGA_GPU_EW_OK;
+    int locked = 0;
+    if (!g_stage_probe) {
+        rc = begin(op, &k, info);
+        if (rc != OMEGA_GPU_EW_OK) return rc;
+        locked = 1;
+    }
     for (uint32_t i0 = 0; i0 < n && rc == OMEGA_GPU_EW_OK; ) {
         uint64_t rec[8];
         if (av_ew_rec(0, n - i0, 0, 0, rec)) { rc = OMEGA_GPU_EW_BAD_ARGS; break; }
-        uint32_t ni = (uint32_t)rec[0];
+        uint32_t ni = 0;
         uint32_t grid = (uint32_t)rec[1];
+        size_t bytes = 0;
+        if (ew_1d_extent(n - i0, rec[0], &ni, &bytes) != OMEGA_GPU_EW_OK) {
+            rc = OMEGA_GPU_EW_BAD_ARGS;
+            break;
+        }
         uint32_t params[4] = { ni, 0, 0, 0 };
-        size_t bytes = (size_t)ni * 4; /* this chunk's bytes: the plan's p[10] is not per chunk */
+        if (g_stage_probe) {
+            if (g_stage_n < (uint32_t)(sizeof g_stage_bytes / sizeof g_stage_bytes[0]))
+                g_stage_bytes[g_stage_n] = bytes;
+            g_stage_n++;
+            i0 += ni;
+            continue;
+        }
         rc = run_abc(k, (const uint8_t *)a + (size_t)i0 * 4, bytes, b ? (const uint8_t *)b + (size_t)i0 * 4 : a, bytes,
                      (uint8_t *)c + (size_t)i0 * 4, bytes, (uint32_t)rec[6], grid, params, info);
         i0 += ni;
     }
-    UNLOCK();
+    if (locked) UNLOCK();
     info_end(info, t0);
     return rc;
 }
 
+int omega_gpu_elementwise_test_stage_bytes(uint32_t n, size_t *bytes, uint32_t cap, uint32_t *nchunks) {
+    static const uint32_t dummy = 0;
+    if (!bytes || !nchunks || cap == 0 || n == 0) return OMEGA_GPU_EW_BAD_ARGS;
+    g_stage_n = 0;
+    g_stage_probe = 1;
+    int rc = run_1d(OMEGA_GPU_EW_EX2, n, &dummy, NULL, (void *)&dummy, NULL);
+    g_stage_probe = 0;
+    if (rc != OMEGA_GPU_EW_OK) return rc;
+    if (g_stage_n > cap) return OMEGA_GPU_EW_TOO_LARGE;
+    for (uint32_t i = 0; i < g_stage_n; i++) bytes[i] = g_stage_bytes[i];
+    *nchunks = g_stage_n;
+    return OMEGA_GPU_EW_OK;
+}
+
 int omega_gpu_swiglu_f32(uint32_t n, const float *gate, const float *up, float *out, OmegaGpuEwInfo *info) {
     if (!gate || !up || !out) return OMEGA_GPU_EW_BAD_ARGS;
     return run_1d(OMEGA_GPU_EW_SWIGLU, n, gate, up, out, info);
diff --git a/src/omega_gpu_elementwise_api.h b/src/omega_gpu_elementwise_api.h
index 03e61e20..5276e767 100644
--- a/src/omega_gpu_elementwise_api.h
+++ b/src/omega_gpu_elementwise_api.h
@@ -170,6 +170,11 @@ void omega_gpu_elementwise_test_set_mutant(int op);
  * corrupted) that the next launch of `op` builds; lets a chip test observe what a missing
  * reconvergence does (the simulator must have flagged it first). */
 void omega_gpu_elementwise_test_set_mutant_level(int op, int level);
+/* TEST ONLY. Byte count run_1d stages for each chunk of an n-element call.
+ * Does not open a device or read the caller's buffers. bytes[i] is chunk i.
+ * The plan's full-chunk length is not reused for a shorter tail. */
+int omega_gpu_elementwise_test_stage_bytes(uint32_t n, size_t *bytes, uint32_t cap,
+                                           uint32_t *nchunks);
 
 const char *omega_gpu_elementwise_rc_name(int rc);
 void omega_gpu_elementwise_cache_clear(void);
diff --git a/swap/cudapp b/swap/cudapp
index be9baf39..7d52477a 100755
--- a/swap/cudapp
+++ b/swap/cudapp
@@ -19,13 +19,21 @@
 # tests/swap/test_swap_cli.sh runs every level against a fake machine root.
 #
 # Sources: --lib PATH (CUDA++ libcuda.so.1), --driver-src PATH (aien_gpu source), --kdir PATH (kernel build dir).
-# CUDAPP_LIB, CUDAPP_DRIVER_SRC and CUDAPP_KDIR give the defaults for an unprivileged run. Escalation runs
-# `sudo "$0" swap ...` WITHOUT -E and passes the resolved paths as these options, so a sudoers rule naming
-# this script cannot be steered by the caller's environment. Running as root on the real system, the library
-# must be a regular file inside this repository and the kernel build dir must live under /lib/modules or /usr/src.
-# The aien_gpu source is built as root by design (a kernel module is root-equivalent): point it at a tree
-# only root or you can write.
+# CUDAPP_LIB, CUDAPP_DRIVER_SRC and CUDAPP_KDIR are the defaults for a run that is not a delegated root build.
+# Escalation runs `sudo "$0" swap ...` WITHOUT -E. A sudoers rule that names only this script rejects the
+# caller's environment (BASH_ENV, SUDO_UID, CUDAPP_DRIVER_SRC, sudo -E); it still allows arguments. Those
+# arguments must not choose the tree make runs as root. A delegated kernel swap (SUDO_UID set to a non-root
+# user, or this script's own sudo re-entry) builds /usr/src/aien-gpu and /lib/modules/$(uname -r)/build.
+# Both must be owned by root and not writable by group or other, and neither may carry an ACL. The module
+# source must contain no symlink. /lib -> usr/lib and the kernel's build symlink are followed when the link
+# is owned by root and the resolved directory stays under /lib/modules, /usr/lib/modules or /usr/src.
+# make and cc are taken from a fixed PATH whose directories and resolved binaries are root-owned and
+# not group/other-writable, so a caller cannot plant a compiler via PATH, CC or MAKEFLAGS.
+# A root shell with SUDO_UID unset may still pass --driver-src and --kdir; a shell started by sudo keeps
+# SUDO_UID, so unset it before a custom-source build. Do not grant SETENV on the sudoers rule.
 set -u
+DRIVER_SRC_ENV_SET=0; [ "${CUDAPP_DRIVER_SRC+x}" = x ] && DRIVER_SRC_ENV_SET=1
+KDIR_ENV_SET=0; [ "${CUDAPP_KDIR+x}" = x ] && KDIR_ENV_SET=1
 ROOT=${CUDAPP_ROOT:-}
 STATE=$ROOT/var/lib/cudapp-swap
 SELF=$(readlink -f "$0")
@@ -46,6 +54,7 @@ INITRD=/boot/initrd.img-$KVER
 NV_MODULES="nvidia nvidia_uvm nvidia_modeset nvidia_drm"
 
 YES=0; REBOOT=0; HOLDERS_OK=0
+DRIVER_SRC_OPTION=0; KDIR_OPTION=0
 die()    { echo "cudapp: $*" >&2; exit 1; }
 refuse() { echo "REFUSED: $*" >&2; exit 3; }
 # A machine that schedules GPU work through spark-window (the invoking user has the tool) reboots only inside a window.
@@ -57,6 +66,198 @@ window_host() {
 }
 usage()  { sed -n '3,9p' "$0" | sed 's/^# \{0,1\}//' >&2; exit 2; }
 sha()    { if [ -e "$1" ] || [ -L "$1" ]; then sha256sum < "$1" | cut -d' ' -f1; else echo -; fi; }
+# sudo sets SUDO_UID itself. A sudoers rule without SETENV rejects `sudo SUDO_UID=...`; do not trust a
+# value the caller could have kept only when SETENV is granted (that grant also allows BASH_ENV).
+sudo_origin() { [ -n "${SUDO_UID:-}" ] && [ "$SUDO_UID" != 0 ]; }
+caller_selected_build() {
+    [ "$DRIVER_SRC_OPTION" -eq 1 ] || [ "$KDIR_OPTION" -eq 1 ] || \
+        [ "$DRIVER_SRC_ENV_SET" -eq 1 ] || [ "$KDIR_ENV_SET" -eq 1 ]
+}
+delegated_build() {
+    case $level in kernel|all) ;; *) return 1;; esac
+    sudo_origin && { [ "$(id -u)" -eq 0 ] || [ -n "$ROOT" ]; }
+}
+# $1 path, $2 owner uid. A symlink's mode is ignored by the kernel, so only its owner is checked here.
+# An ACL can grant write without setting the mode bits, and this helper has no getfacl. GNU ls prints '+'
+# after the mode when an ACL is present ('.' is a security context and is left alone). Any ACL is refused.
+path_owner_mode() {
+    local p=$1 owner=$2 uid mode perm mark
+    [ -e "$p" ] || [ -L "$p" ] || refuse "trusted path does not exist: $p"
+    uid=$(stat -c %u "$p") || refuse "cannot stat $p"
+    [ "$uid" = "$owner" ] || refuse "trusted path is not owned by uid $owner: $p"
+    if [ -L "$p" ]; then return 0; fi
+    mode=$(stat -c %a "$p") || refuse "cannot stat $p"
+    perm=$((8#$mode & 8#022))
+    [ "$perm" -eq 0 ] || refuse "trusted path is writable by group or other: $p"
+    mark=$(ls -ld "$p" | awk '{print $1}') || refuse "cannot list $p"
+    case $mark in ??????????+*) refuse "trusted path has an ACL: $p";; esac
+}
+# Collapse "." and ".." without following symlinks.
+normalize() {
+    local in=$1 part out=
+    case $in in /*) ;; *) in=/$in;; esac
+    while [ "$in" != / ] && [ -n "$in" ]; do
+        in=${in#/}
+        part=${in%%/*}
+        if [ "$part" = "$in" ]; then in=; else in=${in#*/}; fi
+        case $part in
+            ''|.) ;;
+            ..) [ -n "$out" ] && out=${out%/*};;
+            *) out=$out/$part;;
+        esac
+    done
+    [ -n "$out" ] || out=/
+    printf '%s\n' "$out"
+}
+# Walk $1 up through $2 inclusive. No component may be a symlink.
+walk_owned() {
+    local p=$1 stop=$2 owner=$3
+    while :; do
+        [ ! -L "$p" ] || refuse "trusted path contains a symlink: $p"
+        path_owner_mode "$p" "$owner"
+        [ "$p" = "$stop" ] && break
+        [ "$p" = / ] && break
+        p=${p%/*}; [ -n "$p" ] || p=/
+    done
+}
+apply_delegated_sources() {
+    local owner stop src kd target shown
+    if sudo_origin && [ "$EUID" -eq 0 ] && [ -n "$ROOT" ]; then
+        refuse "CUDAPP_ROOT is refused for a delegated root swap"
+    fi
+    if caller_selected_build; then
+        refuse "a delegated kernel swap cannot take --driver-src, --kdir, CUDAPP_DRIVER_SRC or CUDAPP_KDIR; root uses /usr/src/aien-gpu and /lib/modules/<uname -r>/build"
+    fi
+    # The fixture tests are not root. A real delegated root build also pins make and cc.
+    if [ "$EUID" -eq 0 ]; then
+        require_trusted_make_path
+    fi
+    if [ -n "$ROOT" ]; then
+        stop=${ROOT%/}
+        owner=$(stat -c %u "$stop") || refuse "cannot stat the test machine root"
+        src=$stop/usr/src/aien-gpu
+        kd=$stop/lib/modules/$KVER/build
+    else
+        stop=/
+        owner=0
+        src=/usr/src/aien-gpu
+        kd=/lib/modules/$KVER/build
+    fi
+    [ -d "$src" ] || [ -L "$src" ] || refuse "trusted aien_gpu source not found at /usr/src/aien-gpu"
+    walk_owned "$src" "$stop" "$owner"
+    shown=$(find -P "$src" \( -type l -o ! -uid "$owner" -o -perm /022 -o ! \( -type f -o -type d \) \) -print -quit 2>/dev/null) || \
+        refuse "cannot inspect trusted aien_gpu source at /usr/src/aien-gpu"
+    [ -z "$shown" ] || refuse "trusted aien_gpu source must contain no symlink, be owned by uid $owner, and not be writable by group or other: $shown"
+    [ -f "$src/Kbuild" ] && [ ! -L "$src/Kbuild" ] || refuse "trusted aien_gpu source has no regular Kbuild at /usr/src/aien-gpu"
+    while IFS= read -r shown; do
+        [ -n "$shown" ] || continue
+        refuse "trusted aien_gpu source has an ACL: $shown"
+    done < <(find -P "$src" \( -type f -o -type d \) -exec ls -ld {} + | awk 'substr($1, 11, 1) == "+" { print $NF; exit }')
+    # /lib is a symlink to usr/lib on a merged /usr, and the kernel build dir is often itself a symlink
+    # into /usr/src. Follow those links. Each link is owned by the trusted uid, and every real directory
+    # on the resolved path is owned by that uid and not group/other-writable. The result stays under the
+    # machine root, and on the real system under /lib/modules, /usr/lib/modules or /usr/src.
+    [ -e "$kd" ] || [ -L "$kd" ] || refuse "kernel headers for $KVER not found at /lib/modules/$KVER/build"
+    follow_trusted "$kd" "$stop" "$owner"
+    target=$RESOLVED
+    if [ -z "$ROOT" ]; then
+        case $target in /lib/modules/*|/usr/lib/modules/*|/usr/src/*) ;; *) refuse "kernel build dir $target is not under /lib/modules or /usr/src";; esac
+    fi
+    [ -d "$target" ] || refuse "kernel build dir $target is not a directory"
+    DRIVER_SRC=$src
+    KDIR=$target
+}
+# Resolve $1 by following symlinks. Sets RESOLVED. Components at or above $2 are the trust boundary
+# (the fixture root in a test, / on the machine) and are not walked. A link that leaves $2 is refused.
+follow_trusted() {
+    local path=$1 stop=$2 owner=$3
+    local rest cur part next link dest suffix old hops=0
+    if [ "$stop" = / ]; then
+        case $path in /*) ;; *) refuse "trusted path is outside the machine root: $path";; esac
+    else
+        case $path in
+            "$stop"|"$stop"/*) ;;
+            *) refuse "trusted path is outside the machine root: $path";;
+        esac
+    fi
+    if [ "$stop" = / ]; then
+        rest=${path#/}
+        cur=
+    else
+        path_owner_mode "$stop" "$owner"
+        rest=${path#"$stop"}
+        rest=${rest#/}
+        cur=$stop
+    fi
+    while [ -n "$rest" ]; do
+        part=${rest%%/*}
+        if [ "$part" = "$rest" ]; then rest=; else rest=${rest#*/}; fi
+        case $part in
+            ''|.) continue;;
+            ..)
+                if [ "$cur" = "$stop" ] || [ -z "$cur" ] || [ "$cur" = / ]; then
+                    refuse "trusted path climbs above its root: $path"
+                fi
+                cur=${cur%/*}
+                [ -n "$cur" ] || cur=/
+                continue;;
+        esac
+        if [ -z "$cur" ] || [ "$cur" = / ]; then next=/$part; else next=$cur/$part; fi
+        if [ -L "$next" ]; then
+            hops=$((hops + 1))
+            [ "$hops" -le 16 ] || refuse "trusted path has too many symlinks: $path"
+            path_owner_mode "$next" "$owner"
+            link=$(readlink "$next") || refuse "cannot read symlink $next"
+            case $link in
+                /*) dest=$link;;
+                *) dest=$(dirname "$next")/$link;;
+            esac
+            dest=$(normalize "$dest")
+            old=$rest
+            if [ "$stop" = / ]; then
+                rest=${dest#/}
+                cur=
+            else
+                case $dest in
+                    "$stop"|"$stop"/*) ;;
+                    *) refuse "trusted path resolves outside the machine root: $dest";;
+                esac
+                suffix=${dest#"$stop"}
+                suffix=${suffix#/}
+                rest=$suffix
+                cur=$stop
+            fi
+            if [ -n "$old" ]; then
+                if [ -n "$rest" ]; then rest=$rest/$old; else rest=$old; fi
+            fi
+            continue
+        fi
+        path_owner_mode "$next" "$owner"
+        cur=$next
+    done
+    [ -n "$cur" ] || cur=/
+    RESOLVED=$cur
+}
+# Directories and binaries a delegated root build may execute. Caller environment is not consulted.
+require_trusted_make_path() {
+    local d tool path dirs
+    TRUSTED_PATH_OK=
+    IFS=: read -r -a dirs <<'EOF'
+/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin
+EOF
+    for d in "${dirs[@]}"; do
+        [ -e "$d" ] || [ -L "$d" ] || continue
+        follow_trusted "$d" / 0
+        if [ -n "$TRUSTED_PATH_OK" ]; then TRUSTED_PATH_OK=$TRUSTED_PATH_OK:$RESOLVED
+        else TRUSTED_PATH_OK=$RESOLVED; fi
+    done
+    [ -n "$TRUSTED_PATH_OK" ] || refuse "no trusted directory on the make PATH"
+    for tool in make cc; do
+        path=$(PATH=$TRUSTED_PATH_OK command -v "$tool") || refuse "$tool is not on the trusted PATH"
+        follow_trusted "$path" / 0
+        [ -f "$RESOLVED" ] && [ ! -L "$RESOLVED" ] || refuse "$tool does not resolve to a regular file: $path"
+    done
+}
 
 # ---------------------------------------------------------------- facts
 gpu_ids() { # prints "vendor:device" of every NVIDIA PCI function
@@ -196,8 +397,15 @@ kernel_level() {
     backup_file "$MODDIR/aien_gpu.ko"; backup_file "$MODCONF"; backup_file "$MODLOAD"
     for m in "$ROOT"/lib/modules/$KVER/modules.*; do [ -e "$m" ] && backup_file "${m#$ROOT}"; done
     nv_in_initramfs && backup_file "$INITRD"
-    local B; B=$(mktemp -d) && cp -r "$DRIVER_SRC"/. "$B"/ || die "copy of driver source failed"
-    make -C "$KDIR" M="$B" modules > "$BK/build.log" 2>&1 || { cat "$BK/build.log" >&2; die "aien_gpu build failed (log $BK/build.log)"; }
+    local B; B=$(mktemp -d) && cp -a -- "$DRIVER_SRC"/. "$B"/ || die "copy of driver source failed"
+    # A delegated root build must not inherit CC, MAKEFLAGS or LD_PRELOAD from `sudo VAR=value`.
+    # sudoers without SETENV already rejects those assignments; this is the same boundary for make.
+    if [ "$EUID" -eq 0 ] && sudo_origin; then
+        env -i PATH="$TRUSTED_PATH_OK" HOME="${HOME:-/root}" \
+            make -C "$KDIR" M="$B" modules > "$BK/build.log" 2>&1 || { cat "$BK/build.log" >&2; die "aien_gpu build failed (log $BK/build.log)"; }
+    else
+        make -C "$KDIR" M="$B" modules > "$BK/build.log" 2>&1 || { cat "$BK/build.log" >&2; die "aien_gpu build failed (log $BK/build.log)"; }
+    fi
     local vm; vm=$(modinfo -F vermagic "$B/aien_gpu.ko" 2>/dev/null; modinfo "$B/aien_gpu.ko" 2>/dev/null | awk '/^vermagic/{print $2}')
     grep -q "$KVER" <<<"$vm" || die "built module vermagic '$vm' does not match running kernel $KVER"
     mkdir -p "$ROOT$MODDIR" && install -m 0644 "$B/aien_gpu.ko" "$ROOT$MODDIR/aien_gpu.ko" || die "module install failed"
@@ -254,7 +462,11 @@ while [ $# -gt 0 ]; do
         --in-spark-window) SPARK_WINDOW=1;;
         --lib|--driver-src|--kdir)
             [ $# -ge 2 ] && [ -n "$2" ] || usage
-            case $1 in --lib) LIB_SRC=$2;; --driver-src) DRIVER_SRC=$2;; --kdir) KDIR=$2;; esac
+            case $1 in
+                --lib) LIB_SRC=$2;;
+                --driver-src) DRIVER_SRC=$2; DRIVER_SRC_OPTION=1;;
+                --kdir) KDIR=$2; KDIR_OPTION=1;;
+            esac
             shift;;
         *) usage;;
     esac
@@ -262,13 +474,24 @@ while [ $# -gt 0 ]; do
 done
 case $level in status|user|kernel|all|back) ;; *) usage;; esac
 if [ $YES -eq 1 ] && [ -z "$ROOT" ] && [ "$(id -u)" -ne 0 ]; then
-    # No -E: root gets a clean environment; the three sources travel as explicit, resolved arguments.
+    # No -E: root gets a clean environment. The module source and the kernel build dir are chosen
+    # again in the root process; they are not arguments a delegated caller can set.
+    case $level in
+        kernel|all)
+            if caller_selected_build; then
+                refuse "a delegated kernel swap cannot take --driver-src, --kdir, CUDAPP_DRIVER_SRC or CUDAPP_KDIR; root uses /usr/src/aien-gpu and /lib/modules/<uname -r>/build"
+            fi
+            ;;
+    esac
     set -- --yes
     [ $REBOOT -eq 1 ] && set -- "$@" --reboot
     [ $HOLDERS_OK -eq 1 ] && set -- "$@" --holders-ok
     [ -n "${SPARK_WINDOW:-}" ] && set -- "$@" --in-spark-window
-    exec sudo "$SELF" swap "$level" "$@" --lib "$(readlink -m "$LIB_SRC")" \
-        --driver-src "$(readlink -m "$DRIVER_SRC")" --kdir "$(readlink -m "$KDIR")"
+    case $level in user|all) set -- "$@" --lib "$(readlink -m "$LIB_SRC")";; esac
+    exec sudo "$SELF" swap "$level" "$@"
+fi
+if delegated_build; then
+    apply_delegated_sources
 fi
 # As root on the real system, refuse sources outside the places a root install may read from.
 if [ -z "$ROOT" ] && [ "$(id -u)" -eq 0 ]; then
diff --git a/tests/gpu_elementwise_test.c b/tests/gpu_elementwise_test.c
index 59b3c5fd..5c40b283 100644
--- a/tests/gpu_elementwise_test.c
+++ b/tests/gpu_elementwise_test.c
@@ -112,6 +112,23 @@ static int sm121dis_check(OmegaGpuEwOp op, const char *name, const char *const *
 }
 
 static void host_only(void) {
+    /* swiglu_131073's tail is one element. Staging the plan's p[10] (524288 bytes)
+     * wrote past the caller buffer; the chunk's own length is 4. No device. */
+    {
+        size_t b[4] = {0};
+        uint32_t nch = 99;
+        CHECK(omega_gpu_elementwise_test_stage_bytes(131073, b, 4, &nch) == OMEGA_GPU_EW_OK
+              && nch == 2 && b[0] == 524288u && b[1] == 4u,
+              "n=131073 stages a 524288-byte chunk then a 4-byte tail (chunks %u %zu %zu)", nch, b[0], b[1]);
+        CHECK(b[1] != 524288u, "negative control: the tail is not the plan's full-chunk length");
+        nch = 99;
+        CHECK(omega_gpu_elementwise_test_stage_bytes(131072, b, 4, &nch) == OMEGA_GPU_EW_OK
+              && nch == 1 && b[0] == 524288u, "a full chunk stages its own 524288 bytes (chunks %u %zu)", nch, b[0]);
+        nch = 99;
+        CHECK(omega_gpu_elementwise_test_stage_bytes(1, b, 4, &nch) == OMEGA_GPU_EW_OK
+              && nch == 1 && b[0] == 4u, "one element stages 4 bytes (chunks %u %zu)", nch, b[0]);
+        CHECK(omega_gpu_elementwise_test_stage_bytes(0, b, 4, &nch) == OMEGA_GPU_EW_BAD_ARGS, "n=0 stage probe refused");
+    }
     CHECK(omega_blackwell_verify_codegen_fixtures_fb1cut4() == 0, "word fixtures MUFU_EX2 / BAR_SYNC / LDS32 / STS32 (rc %d)", omega_blackwell_verify_codegen_fixtures_fb1cut4());
     float a[256] = {0}, b[256] = {0}, c[256] = {0};
     CHECK(omega_gpu_rmsnorm_f32(0, 128, a, b, 1e-5f, c, NULL) == OMEGA_GPU_EW_BAD_ARGS, "rows=0 refused");
diff --git a/tests/swap/test_swap_cli.sh b/tests/swap/test_swap_cli.sh
index 4013d95e..ec284184 100755
--- a/tests/swap/test_swap_cli.sh
+++ b/tests/swap/test_swap_cli.sh
@@ -168,7 +168,28 @@ check "escalation calls sudo" [ -s "$S/sudo.argv" ]
 check "escalation drops -E (no caller environment reaches root)" bash -c "! grep -qx -- '-E' '$S/sudo.argv'"
 check "escalation re-runs this script by absolute path" [ "$(sed -n 1p "$S/sudo.argv")" = "$(readlink -f "$TOOL")" ]
 check "escalation passes --lib as a resolved absolute path" grep -qx -- "$S/lib/libcuda.so.1" "$S/sudo.argv"
-check "escalation passes --kdir and --driver-src" bash -c "grep -qx -- --kdir '$S/sudo.argv' && grep -qx -- --driver-src '$S/sudo.argv'"
+check "user escalation does not pass --kdir or --driver-src" bash -c "! grep -qx -- --kdir '$S/sudo.argv' && ! grep -qx -- --driver-src '$S/sudo.argv'"
+: > "$S/sudo.argv"
+env -u CUDAPP_ROOT -u CUDAPP_DRIVER_SRC -u CUDAPP_KDIR PATH="$S/bin:$PATH" \
+    bash "$TOOL" swap kernel --yes > /dev/null 2>&1
+check "kernel escalation calls sudo" [ -s "$S/sudo.argv" ]
+check "kernel escalation does not pass --driver-src or --kdir" bash -c "! grep -qx -- --driver-src '$S/sudo.argv' && ! grep -qx -- --kdir '$S/sudo.argv'"
+: > "$S/sudo.argv"
+out=$(env -u CUDAPP_ROOT -u CUDAPP_DRIVER_SRC -u CUDAPP_KDIR PATH="$S/bin:$PATH" \
+    bash "$TOOL" swap kernel --yes --driver-src "$S/lib" 2>&1); rc=$?
+check "caller-selected driver source is refused before sudo (exit 3)" [ $rc -eq 3 ]
+check "refused driver source never reaches sudo" [ ! -s "$S/sudo.argv" ]
+check "driver-source refusal names the delegated swap" grep -q "delegated kernel swap" <<<"$out"
+: > "$S/sudo.argv"
+out=$(env -u CUDAPP_ROOT PATH="$S/bin:$PATH" CUDAPP_DRIVER_SRC="$S/lib" \
+    bash "$TOOL" swap kernel --yes 2>&1); rc=$?
+check "CUDAPP_DRIVER_SRC is refused before sudo (exit 3)" [ $rc -eq 3 ]
+check "refused CUDAPP_DRIVER_SRC never reaches sudo" [ ! -s "$S/sudo.argv" ]
+: > "$S/sudo.argv"
+out=$(env -u CUDAPP_ROOT -u CUDAPP_DRIVER_SRC PATH="$S/bin:$PATH" \
+    bash "$TOOL" swap all --yes --kdir "$S" 2>&1); rc=$?
+check "caller-selected kdir is refused before sudo (exit 3)" [ $rc -eq 3 ]
+check "refused kdir never reaches sudo" [ ! -s "$S/sudo.argv" ]
 # 12. as root on the real system (fake id prints 0): sources outside the allowed places are refused before any level runs
 printf '#!/bin/bash\necho 0\n' > "$S/bin/id"
 out=$(env -u CUDAPP_ROOT PATH="$S/bin:$PATH" bash "$TOOL" swap user --lib "$S/lib/libcuda.so.1" 2>&1); rc=$?
@@ -194,5 +215,153 @@ check "differing installed library rolled back" [ "$before" = "$(tree_hash "$R")
 rm "$R/fakebin/install"; out=$(run swap user --yes 2>&1)
 check "installed sha256 recorded next to the backup" bash -c "grep -q \"\$(sha256sum < '$R/build/libcuda.so.1' | cut -d' ' -f1)  /usr/lib/cudapp/libcuda.so.1\" '$R'/var/lib/cudapp-swap/backup-*-user/installed.sha256"
 
+# 14. Delegated kernel build (SUDO_UID set, fake machine root). Root must build /usr/src/aien-gpu
+#     and the running kernel's build dir, never the caller's tree. Ownership in the fixture is
+#     the test uid, which stands in for uid 0.
+lock_tree() { # $1 = trusted file or directory; drop group/other write on it and on ancestors inside $2
+    local p=$1 stop=$2
+    chmod -R u+rwX,go-w "$p"
+    while :; do
+        chmod u+rwx,go-w "$p"
+        [ "$p" = "$stop" ] && break
+        p=$(dirname "$p")
+    done
+}
+stage_make() { # record the Kbuild the module build actually consumed
+    local R=$1
+    printf '#!/bin/bash\necho "make $*" >> "%s/calls.log"\nfor a in "$@"; do case $a in M=*) d=${a#M=}; echo "KBUILD:$(head -1 "$d/Kbuild")" >> "%s/calls.log"; echo built > "$d/aien_gpu.ko";; esac; done\n' "$R" "$R" > "$R/fakebin/make"
+    chmod +x "$R/fakebin/make"
+}
+delegated() { # $1 = fake root; remaining args are the tool's
+    local R=$1; shift
+    env -u CUDAPP_DRIVER_SRC -u CUDAPP_KDIR PATH="$R/fakebin:$PATH" CUDAPP_ROOT="$R" \
+        CUDAPP_LIB="$R/build/libcuda.so.1" SUDO_UID=1000 SUDO_USER=fixture \
+        bash "$TOOL" "$@"
+}
+trusted_src() { # $1 = fake root. A locked tree whose Kbuild is not the attacker's.
+    local R=$1
+    mkdir -p "$R/usr/src/aien-gpu" "$R/attacker"
+    printf 'trusted-marker\nobj-m := aien_gpu.o\n' > "$R/usr/src/aien-gpu/Kbuild"
+    echo '/* trusted */' > "$R/usr/src/aien-gpu/aien_gpu.c"
+    printf 'attacker-marker\nobj-m := aien_gpu.o\n' > "$R/attacker/Kbuild"
+    echo '/* attacker */' > "$R/attacker/aien_gpu.c"
+    lock_tree "$R/usr/src/aien-gpu" "$R"
+}
+
+R=$T/r14a; mkroot "$R"; trusted_src "$R"; stage_make "$R"
+out=$(delegated "$R" swap kernel --yes --driver-src "$R/attacker" 2>&1); rc=$?
+check "delegated kernel swap refuses --driver-src (exit 3)" [ $rc -eq 3 ]
+check "delegated --driver-src refusal names the delegated swap" grep -q "delegated kernel swap" <<<"$out"
+check "delegated --driver-src runs no make" bash -c "! grep -q '^make ' '$R/calls.log' 2>/dev/null"
+check "delegated --driver-src does not install a module" [ ! -e "$R/lib/modules/$KVER/updates/cudapp/aien_gpu.ko" ]
+
+R=$T/r14b; mkroot "$R"; trusted_src "$R"; stage_make "$R"
+out=$(PATH="$R/fakebin:$PATH" CUDAPP_ROOT="$R" CUDAPP_LIB="$R/build/libcuda.so.1" \
+    CUDAPP_DRIVER_SRC="$R/attacker" SUDO_UID=1000 bash "$TOOL" swap kernel --yes 2>&1); rc=$?
+check "delegated kernel swap refuses CUDAPP_DRIVER_SRC (exit 3)" [ $rc -eq 3 ]
+check "delegated CUDAPP_DRIVER_SRC refusal names the delegated swap" grep -q "delegated kernel swap" <<<"$out"
+check "delegated CUDAPP_DRIVER_SRC runs no make" bash -c "! grep -q '^make ' '$R/calls.log' 2>/dev/null"
+
+R=$T/r14c; mkroot "$R"; trusted_src "$R"; stage_make "$R"
+out=$(delegated "$R" swap kernel --yes --kdir "$R/attacker" 2>&1); rc=$?
+check "delegated kernel swap refuses --kdir (exit 3)" [ $rc -eq 3 ]
+check "delegated --kdir refusal names the delegated swap" grep -q "delegated kernel swap" <<<"$out"
+check "delegated --kdir runs no make" bash -c "! grep -q '^make ' '$R/calls.log' 2>/dev/null"
+
+R=$T/r14d; mkroot "$R"; trusted_src "$R"; stage_make "$R"
+chmod o+w "$R/usr/src/aien-gpu/Kbuild"
+out=$(delegated "$R" swap kernel --yes 2>&1); rc=$?
+check "delegated kernel swap refuses a group-or-other-writable source file (exit 3)" [ $rc -eq 3 ]
+check "writable source refusal names the file mode" grep -q "writable" <<<"$out"
+check "writable source file runs no make" bash -c "! grep -q '^make ' '$R/calls.log' 2>/dev/null"
+
+R=$T/r14e; mkroot "$R"; trusted_src "$R"; stage_make "$R"
+rm "$R/usr/src/aien-gpu/aien_gpu.c"
+ln -s "$R/attacker/aien_gpu.c" "$R/usr/src/aien-gpu/aien_gpu.c"
+out=$(delegated "$R" swap kernel --yes 2>&1); rc=$?
+check "delegated kernel swap refuses a symlink in the source (exit 3)" [ $rc -eq 3 ]
+check "source symlink refusal names the symlink" grep -q "symlink" <<<"$out"
+check "source symlink runs no make" bash -c "! grep -q '^make ' '$R/calls.log' 2>/dev/null"
+
+R=$T/r14f; mkroot "$R"; trusted_src "$R"; stage_make "$R"
+rm -rf "$R/usr/src/aien-gpu"
+ln -s "$R/attacker" "$R/usr/src/aien-gpu"
+out=$(delegated "$R" swap kernel --yes 2>&1); rc=$?
+check "delegated kernel swap refuses a symlinked source directory (exit 3)" [ $rc -eq 3 ]
+check "symlinked source directory refusal names the symlink" grep -q "symlink" <<<"$out"
+
+R=$T/r14g; mkroot "$R"; trusted_src "$R"; stage_make "$R"
+chmod o+w "$R/usr/src"
+out=$(delegated "$R" swap kernel --yes 2>&1); rc=$?
+check "delegated kernel swap refuses a writable ancestor (exit 3)" [ $rc -eq 3 ]
+check "writable ancestor refusal names the mode" grep -q "writable" <<<"$out"
+check "writable ancestor runs no make" bash -c "! grep -q '^make ' '$R/calls.log' 2>/dev/null"
+
+R=$T/r14h; mkroot "$R"; trusted_src "$R"; stage_make "$R"
+rm -rf "$R/lib/modules/$KVER/build"
+mkdir -p "$R/attacker-kdir"
+chmod 777 "$R/attacker-kdir"
+echo 'attacker-makefile' > "$R/attacker-kdir/Makefile"
+ln -s "$R/attacker-kdir" "$R/lib/modules/$KVER/build"
+out=$(delegated "$R" swap kernel --yes 2>&1); rc=$?
+check "delegated kernel swap refuses a kdir symlink to a writable tree (exit 3)" [ $rc -eq 3 ]
+check "writable kdir refusal names the kdir" grep -Eq "writable|symlink" <<<"$out"
+check "writable kdir symlink runs no make" bash -c "! grep -q '^make ' '$R/calls.log' 2>/dev/null"
+
+R=$T/r14i; mkroot "$R"; trusted_src "$R"; stage_make "$R"
+rm -rf "$R/lib/modules/$KVER/build"
+mkdir -p "$R/usr/src/linux-headers"
+echo 'trusted-makefile' > "$R/usr/src/linux-headers/Makefile"
+lock_tree "$R/usr/src/linux-headers" "$R"
+ln -s "$R/usr/src/linux-headers" "$R/lib/modules/$KVER/build"
+# The symlink itself is mode 777 on Linux; its owner is the fixture uid. Parent stays locked.
+chown -h "$(id -u):$(id -g)" "$R/lib/modules/$KVER/build" 2>/dev/null || true
+out=$(delegated "$R" swap kernel --yes 2>&1); rc=$?
+check "delegated kernel swap accepts a locked kdir symlink (exit 0)" [ $rc -eq 0 ]
+check "delegated kdir symlink build consumed the trusted module source" grep -qx "KBUILD:trusted-marker" "$R/calls.log"
+check "delegated kdir symlink build did not consume the attacker source" bash -c "! grep -q 'KBUILD:attacker-marker' '$R/calls.log'"
+
+R=$T/r14j; mkroot "$R"; trusted_src "$R"; stage_make "$R"
+out=$(delegated "$R" swap kernel --yes 2>&1); rc=$?
+check "delegated kernel swap accepts a locked /usr/src/aien-gpu (exit 0)" [ $rc -eq 0 ]
+check "delegated build consumed the trusted Kbuild" grep -qx "KBUILD:trusted-marker" "$R/calls.log"
+check "delegated build did not consume the attacker Kbuild" bash -c "! grep -q 'KBUILD:attacker-marker' '$R/calls.log'"
+check "delegated build installed aien_gpu.ko" [ -f "$R/lib/modules/$KVER/updates/cudapp/aien_gpu.ko" ]
+
+# Ubuntu's /lib is a symlink to usr/lib. The kernel build dir is reached through that link.
+R=$T/r14k; mkroot "$R"; trusted_src "$R"; stage_make "$R"
+rm -rf "$R/lib"
+mkdir -p "$R/usr/lib/modules/$KVER" "$R/usr/src/linux-headers"
+echo 'trusted-makefile' > "$R/usr/src/linux-headers/Makefile"
+ln -s usr/lib "$R/lib"
+ln -s "$R/usr/src/linux-headers" "$R/usr/lib/modules/$KVER/build"
+lock_tree "$R/usr/lib/modules/$KVER" "$R"
+lock_tree "$R/usr/src/linux-headers" "$R"
+out=$(delegated "$R" swap kernel --yes 2>&1); rc=$?
+check "delegated kernel swap follows a /lib -> usr/lib symlink (exit 0)" [ $rc -eq 0 ]
+check "usr-merge build consumed the trusted module source" grep -qx "KBUILD:trusted-marker" "$R/calls.log"
+check "usr-merge build did not consume the attacker source" bash -c "! grep -q 'KBUILD:attacker-marker' '$R/calls.log'"
+check "usr-merge build installed aien_gpu.ko through the /lib symlink" [ -f "$R/usr/lib/modules/$KVER/updates/cudapp/aien_gpu.ko" ]
+
+R=$T/r14l; mkroot "$R"; trusted_src "$R"; stage_make "$R"
+rm -rf "$R/lib"
+mkdir -p "$T/escape/modules/$KVER/build"
+echo 'attacker-makefile' > "$T/escape/modules/$KVER/build/Makefile"
+ln -s "$T/escape" "$R/lib"
+out=$(delegated "$R" swap kernel --yes 2>&1); rc=$?
+check "delegated kernel swap refuses a /lib symlink that leaves the machine root (exit 3)" [ $rc -eq 3 ]
+check "escaping /lib symlink names the machine root" grep -q "outside the machine root" <<<"$out"
+check "escaping /lib symlink runs no make" bash -c "! grep -q '^make ' '$R/calls.log' 2>/dev/null"
+check "escaping /lib symlink did not consume the attacker makefile" bash -c "! grep -q 'attacker-makefile' '$R/calls.log' 2>/dev/null"
+
+# A real delegated root (sudo sets SUDO_UID) must accept this machine's compiler path and still
+# refuse before make, because /usr/src/aien-gpu is not installed here. Nothing is written.
+if sudo -n true 2>/dev/null; then
+    out=$(sudo -n env -u CUDAPP_ROOT -u CUDAPP_DRIVER_SRC -u CUDAPP_KDIR -u CUDAPP_LIB bash "$TOOL" swap kernel --yes 2>&1); rc=$?
+    check "delegated root refuses before any build on this machine (exit 3)" [ $rc -eq 3 ]
+    check "delegated root reached the trusted source check" grep -q "trusted aien_gpu source not found" <<<"$out"
+    check "delegated root did not report a compiler-path failure" bash -c "! grep -Eq 'make PATH|not on the trusted PATH|does not resolve' <<<"$out""
+fi
+
 echo "swap cli: $PASS passed, $FAIL failed"
 [ $FAIL -eq 0 ]