Skip to content

The all-in-one local AI studio for your desktop: chat, image and video generation and a coding agent in one free, open source app. Windows and Linux. No Docker, no terminal, no cloud required.

fix(sidecar): Windows-ISA-Waechter auf Opcode-Byte-Regel umgebaut (K1)

purple65fbe632dc89
diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml
index fcca20ae..f21bde82 100644
--- a/.github/workflows/release.yml
+++ b/.github/workflows/release.yml
@@ -248,6 +248,15 @@ jobs:
esac
ls -la src-tauri/bin/
+ # review-k1-avx.md R1-R6: dumpbin.exe (the Windows half of the guard
+ # below) is not on PATH on a plain runner shell. Same reasoning as
+ # sidecar-windows.yml's identical step; keep the two in sync.
+ - name: Set up MSVC dev tools (dumpbin, for the K1 ISA guard)
+ if: matrix.platform == 'windows-latest'
+ uses: ilammy/msvc-dev-cmd@0b201ec74fa43914dc39ae48a89fd1d8cb592756 # v1.13.0
+ with:
+ arch: x64
+
# K1 (3.0.1): the guard against shipping a fixed x86-64-v3 binary again.
# Runs on the real build this lane just produced, on the real runner
# architecture (not emulated), so a regression here is the same failure
diff --git a/.github/workflows/sidecar-windows.yml b/.github/workflows/sidecar-windows.yml
index ac607898..9ef0bb06 100644
--- a/.github/workflows/sidecar-windows.yml
+++ b/.github/workflows/sidecar-windows.yml
@@ -73,6 +73,21 @@ jobs:
shell: bash
run: bash scripts/build-llama.sh x86_64-pc-windows-msvc
+ # review-k1-avx.md R1-R6: the Windows half of verify-sidecar-isa.sh
+ # needs dumpbin.exe, which is not on PATH on a plain runner shell (it
+ # lives under a versioned VC\Tools\MSVC directory that only a
+ # Developer Command Prompt adds). The guard's own find_dumpbin()
+ # locates it via vswhere as a fallback, but setting up the dev
+ # environment here is the same thing every other MSVC-toolchain step
+ # in this repo would need, so do it once, explicitly, rather than
+ # depend on that fallback matching whatever this runner image ships
+ # next. msvc-dev-cmd writes to GITHUB_PATH/GITHUB_ENV, which later
+ # `shell: bash` steps pick up the same as `shell: pwsh` ones.
+ - name: Set up MSVC dev tools (dumpbin, for the K1 ISA guard)
+ uses: ilammy/msvc-dev-cmd@0b201ec74fa43914dc39ae48a89fd1d8cb592756 # v1.13.0
+ with:
+ arch: x64
+
- name: Verify sidecar ISA layout (K1)
shell: bash
run: bash scripts/verify-sidecar-isa.sh x86_64-pc-windows-msvc
diff --git a/scripts/__fixtures__/win-isa/crt-allowed.disasm.txt b/scripts/__fixtures__/win-isa/crt-allowed.disasm.txt
new file mode 100644
index 00000000..3dbac752
--- /dev/null
+++ b/scripts/__fixtures__/win-isa/crt-allowed.disasm.txt
@@ -0,0 +1,9 @@
+Dump of file fixture: real pattern from review-k1-avx.md Fundstelle 1a
+(ggml-cpu-x64.dll, __std_find_trivial_impl). Deliberately carries NO
+__isa_available/__isa_enabled line at all, unlike protected-own-code.disasm.txt:
+this fixture exists to prove the CRT/STL allowlist (R3.1) accepts a
+msvcprt:vector_algorithms.obj hit on the object/function name alone, without
+needing (and without finding) a dominance-check jump, because the MSVC-STL's
+own dispatcher lives one call frame up, not inside this function.
+
+ 0000000180091F2B: C5 F9 6E D8 vmovd xmm3,eax
diff --git a/scripts/__fixtures__/win-isa/crt-allowed.map.txt b/scripts/__fixtures__/win-isa/crt-allowed.map.txt
new file mode 100644
index 00000000..b3a3b9c1
--- /dev/null
+++ b/scripts/__fixtures__/win-isa/crt-allowed.map.txt
@@ -0,0 +1,4 @@
+ Static symbols
+
+ 0001:00000000 ??$__std_find_trivial_impl@U_Find_traits_1@?A0x8417fefe@@E@?A0x8417fefe@@YAPEBXPEBX0E@Z 0000000180091f00 f msvcprt:vector_algorithms.obj
+ 0001:00000100 __std_find_trivial_1 0000000180092000 f msvcprt:vector_algorithms.obj
diff --git a/scripts/__fixtures__/win-isa/protected-own-code.disasm.txt b/scripts/__fixtures__/win-isa/protected-own-code.disasm.txt
new file mode 100644
index 00000000..3ddab84d
--- /dev/null
+++ b/scripts/__fixtures__/win-isa/protected-own-code.disasm.txt
@@ -0,0 +1,10 @@
+Dump of file fixture: protected own-code VEX, real pattern from
+review-k1-avx.md Fundstelle 2a (ggml-base.dll, iq2xs_init_impl$omp$1), trimmed
+to the lines the guard needs: the isa check, the guarding jl, the VEX hit,
+and the scalar fallback the jl targets.
+
+ 0000000180027ED6: 8B 0D BC 19 07 00 mov ecx,dword ptr [0000000180099898h]
+ 0000000180027F7E: 83 F9 05 cmp ecx,5
+ 0000000180027F81: 7C 40 jl 0000000180027FC3
+ 0000000180027F83: C4 C2 71 46 C2 vpsravd xmm0,xmm1,xmm10
+ 0000000180027FC3: 48 8D 94 24 88 00 lea rdx,[rsp+88h]
diff --git a/scripts/__fixtures__/win-isa/protected-own-code.map.txt b/scripts/__fixtures__/win-isa/protected-own-code.map.txt
new file mode 100644
index 00000000..d0728c8c
--- /dev/null
+++ b/scripts/__fixtures__/win-isa/protected-own-code.map.txt
@@ -0,0 +1,5 @@
+ Static symbols
+
+ 0001:00000000 iq2xs_init_impl$omp$1 0000000180027e10 f ggml-quants.obj
+ 0001:00000200 iq2xs_init_impl$omp$2 0000000180028010 f ggml-quants.obj
+ 0003:00000010 __isa_available 0000000180099898 MSVCRT:cpu_disp.obj
diff --git a/scripts/__fixtures__/win-isa/unprotected-own-code.disasm.txt b/scripts/__fixtures__/win-isa/unprotected-own-code.disasm.txt
new file mode 100644
index 00000000..0ba9ca99
--- /dev/null
+++ b/scripts/__fixtures__/win-isa/unprotected-own-code.disasm.txt
@@ -0,0 +1,12 @@
+Dump of file fixture: the artificial "rot probe" (review-k1-avx.md R4).
+Synthetic, not from a real build: an own-code object (ggml-fake-red.obj,
+not msvcprt/MSVCRT and not wmemcmp/memcmp) that reaches a VEX instruction
+with NO preceding __isa_available/__isa_enabled/_Avx2WmemEnabled load
+anywhere in the owning function. This must always come out RED: if a
+future change to the guard's decision logic ever lets this fixture pass,
+the allowlist or the dominance check has been loosened past the point
+review-k1-avx.md judged safe.
+
+ 0000000180050000: 48 89 5C 24 08 mov qword ptr [rsp+8],rbx
+ 0000000180050005: C5 F9 6E D8 vmovd xmm3,eax
+ 000000018005000A: C3 ret
diff --git a/scripts/__fixtures__/win-isa/unprotected-own-code.map.txt b/scripts/__fixtures__/win-isa/unprotected-own-code.map.txt
new file mode 100644
index 00000000..cd4ce0f2
--- /dev/null
+++ b/scripts/__fixtures__/win-isa/unprotected-own-code.map.txt
@@ -0,0 +1,5 @@
+ Static symbols
+
+ 0001:00000000 fake_unprotected_kernel 0000000180050000 f ggml-fake-red.obj
+ 0001:00000100 fake_unprotected_kernel_end 0000000180050100 f ggml-fake-red.obj
+ 0003:00000010 __isa_available 0000000180099898 MSVCRT:cpu_disp.obj
diff --git a/scripts/build-llama.sh b/scripts/build-llama.sh
index 393f6e3c..11815c5f 100755
--- a/scripts/build-llama.sh
+++ b/scripts/build-llama.sh
@@ -127,7 +127,19 @@ cmake_flags_for() {
x86_64-apple-darwin)
echo "$common -DBUILD_SHARED_LIBS=OFF -DGGML_METAL=ON -DGGML_METAL_EMBED_LIBRARY=ON -DCMAKE_OSX_ARCHITECTURES=x86_64" ;;
x86_64-pc-windows-msvc)
- echo "$common -DBUILD_SHARED_LIBS=ON -DGGML_BACKEND_DL=ON -DGGML_CPU_ALL_VARIANTS=ON -DGGML_VULKAN=ON" ;;
+ # /MAP (review-k1-avx.md R2): verify-sidecar-isa.sh's Windows ISA guard
+ # needs a linker map to turn a VEX/EVEX hit's address into an owning
+ # function and Lib:Object (the CRT/STL allowlist and the own-code
+ # dominance check both key off that). Set here, as a real linker flag,
+ # not via the LDFLAGS/MSYS2_ENV_CONV_EXCL environment-variable
+ # workaround the box bauer used to prove this out (e2e/k1-avx,
+ # 04-BOX-SIDECAR-AVX-BEFUND.md Schritt 1): that workaround only exists
+ # because MSYS bash rewrites an env VALUE that looks like a Unix path
+ # ("/MAP") before handing it to a native process, a trap this repo's
+ # own CI invocation (bash scripts/build-llama.sh ...) would hit again
+ # on every run if the flag lived in an env var instead of the cmake
+ # command line, where MSYS's argv rewriting does not apply the same way.
+ echo "$common -DBUILD_SHARED_LIBS=ON -DGGML_BACKEND_DL=ON -DGGML_CPU_ALL_VARIANTS=ON -DGGML_VULKAN=ON -DCMAKE_SHARED_LINKER_FLAGS=/MAP -DCMAKE_EXE_LINKER_FLAGS=/MAP" ;;
x86_64-unknown-linux-gnu)
# CMAKE_BUILD_RPATH_USE_ORIGIN=ON (BLOCKER B3): without it,
# CMAKE_BUILD_WITH_INSTALL_RPATH's OFF default still makes CMake write
diff --git a/scripts/verify-sidecar-isa.sh b/scripts/verify-sidecar-isa.sh
index ecd5601f..e6fc8a0e 100755
--- a/scripts/verify-sidecar-isa.sh
+++ b/scripts/verify-sidecar-isa.sh
@@ -228,7 +228,248 @@ if [[ "$TRIPLE" == *-linux-* ]]; then
[ -f "$exe_check_path" ] && check_no_absolute_build_rpath "$exe_check_path"
fi
-# --- The disassembler ------------------------------------------------------
+# --- Windows: opcode-byte VEX/EVEX guard (review-k1-avx.md, Opus final review) --
+#
+# The mnemonic-based rule below ("no mnemonic starting with v") is unusable
+# under MSVC: the MSVC-STL and CRT ship their own runtime-switched AVX2 fast
+# paths (msvcprt:vector_algorithms.obj, wmemcmp's _Avx2WmemEnabled path)
+# inside EVERY module they are statically linked into, and a plain mnemonic
+# grep also flags verr/verw/vmread instructions dumpbin/objdump disassembles
+# out of plain data bytes (review-k1-avx.md section "Zusatzbefund", the
+# vom Orchestrator vermutete Regelfehler). Neither is the K1 bug. The
+# Windows-only replacement (R1-R6 in review-k1-avx.md) lives in
+# scripts/win-isa-guard.mjs: it detects VEX/EVEX by opcode byte (exact, not
+# heuristic, in 64-bit code), resolves each hit's owning function from the
+# linker .map (hence /MAP in cmake_flags_for, R2), and only allows a hit
+# either through a named CRT/STL allowlist or through a same-function
+# isa-check-then-guarding-jump dominance check (R3). The Linux path below
+# this block is UNCHANGED: nm's symbol table plus objdump's mnemonic text is
+# sufficient there because Linux never links this project's own gcc-built
+# ggml/llama.cpp code against a runtime-dispatched CRT algorithm library the
+# way MSVC does.
+if [[ "$TRIPLE" == *-windows-* ]]; then
+
+ # R5: MSYS2_ARG_CONV_EXCL fixed in the disassembler function, not left to
+ # whatever the caller's environment happens to have. Without it MSYS bash
+ # rewrites "/disasm" etc. into a bogus Windows path before dumpbin ever
+ # sees it (review-k1-avx.md footnote; 04-BOX-SIDECAR-AVX-BEFUND.md hit the
+ # sibling case with an env VALUE, this is the same class of bug for an
+ # argv entry).
+ DUMPBIN_ARG_EXCL='/disasm;/nologo;/headers;/imports;/exports;/MAP'
+
+ # dumpbin is not on PATH on a plain shell (neither this repo's CI runner
+ # nor an un-elevated box shell): it lives under a versioned VC\Tools\MSVC
+ # directory that only a Developer Command Prompt (vcvars) or an explicit
+ # path adds. Locate it directly with vswhere (shipped with every VS
+ # Installer, including on GitHub's windows-latest image) rather than
+ # requiring every caller to have already run vcvars.
+ find_dumpbin() {
+ if command -v dumpbin >/dev/null 2>&1; then
+ command -v dumpbin
+ return 0
+ fi
+ local vswhere=""
+ if [ -x "/c/Program Files (x86)/Microsoft Visual Studio/Installer/vswhere.exe" ]; then
+ vswhere="/c/Program Files (x86)/Microsoft Visual Studio/Installer/vswhere.exe"
+ elif command -v vswhere.exe >/dev/null 2>&1; then
+ vswhere="$(command -v vswhere.exe)"
+ fi
+ [ -n "$vswhere" ] || return 1
+ local vsroot
+ vsroot="$("$vswhere" -latest -products '*' -requires Microsoft.VisualStudio.Component.VC.Tools.x86.x64 -property installationPath 2>/dev/null | tr -d '\r')"
+ [ -n "$vsroot" ] || return 1
+ # vswhere prints a native Windows path (backslashes, "C:\..."); bash's
+ # own path operations (find, globs) need the MSYS form.
+ local vsroot_unix
+ vsroot_unix="$(printf '%s' "$vsroot" | sed -E 's#\\#/#g; s#^([A-Za-z]):#/\L\1#')"
+ # Real depth below .../VC/Tools/MSVC is 5 (<version>/bin/Hostx64/x64/
+ # dumpbin.exe), measured on the box, not guessed; -maxdepth 4 silently
+ # found nothing there and made this whole helper return empty.
+ find "$vsroot_unix/VC/Tools/MSVC" -maxdepth 6 -type f -iname 'dumpbin.exe' -path '*Hostx64*x64*' 2>/dev/null | sort -V | tail -1
+ }
+
+ DUMPBIN="$(find_dumpbin || true)"
+ [ -n "$DUMPBIN" ] && [ -x "$DUMPBIN" ] \
+ || vdie "dumpbin.exe not found (checked PATH and vswhere's VC.Tools.x86.x64 workload); the Windows ISA guard needs the exact MSVC toolset dumpbin from review-k1-avx.md, install the VS Build Tools C++ workload, or run this from a Developer Command Prompt"
+ vlog "using dumpbin at $DUMPBIN"
+
+ dumpbin_run() {
+ MSYS2_ARG_CONV_EXCL="$DUMPBIN_ARG_EXCL" "$DUMPBIN" "$@"
+ }
+
+ # R5 continued: no `2>/dev/null` here, a dumpbin invocation that fails
+ # must turn the guard red with the real error, not silently hand the rest
+ # of the script an empty string that then vacuously "passes".
+ disassemble_windows() {
+ local file="$1"
+ dumpbin_run /nologo /disasm "$file"
+ }
+
+ # Toolset/linker version pin (R3, "Bewertung der Regel, ehrlich"): the
+ # CRT/STL allowlist trusts specific, hand-verified object files
+ # (msvcprt:vector_algorithms.obj, wmemcmp). A future MSVC toolset could in
+ # principle ship an unguarded fast path in the same object and this guard
+ # would not notice, so pin the toolset that was actually reviewed and go
+ # red, with a concrete next step, the moment the build uses a different one.
+ WINDOWS_REVIEWED_LINKER_VERSIONS="14.44"
+ check_toolset_version() {
+ local file="$1" hdr ver
+ hdr="$(dumpbin_run /nologo /headers "$file")" || vdie "dumpbin /headers failed on $file"
+ ver="$(grep -m1 -i 'linker version' <<<"$hdr" | grep -oE '[0-9]+\.[0-9]+' | head -1)"
+ [ -n "$ver" ] || vdie "could not read a linker version out of dumpbin /headers on $file"
+ case " $WINDOWS_REVIEWED_LINKER_VERSIONS " in
+ *" $ver "*)
+ vlog "$file: linker version $ver matches the reviewed MSVC toolset (19.44.35222.0, VS 2022 17.14, lu-301/bau/review-k1-avx.md)" ;;
+ *)
+ vdie "$file: linker version is $ver, not one of the reviewed toolsets ($WINDOWS_REVIEWED_LINKER_VERSIONS, MSVC 19.44.35222.0 / VS 2022 17.14, lu-301/bau/review-k1-avx.md section 3). A new toolset can change whether vector_algorithms.obj/wmemcmp still self-guard the way the CRT/STL allowlist assumes: re-run the Opus-style disassembly review against the new toolset before trusting it, then add its linker version to WINDOWS_REVIEWED_LINKER_VERSIONS here" ;;
+ esac
+ }
+
+ # R6: every module every CPU tier loads, not just the four the old rule
+ # checked. The higher CPU-tier variants (haswell and above) are explicitly
+ # EXEMPT here: they are allowed, by design, to contain unconditional AVX,
+ # that is the whole point of shipping more than one ggml-cpu-*.dll.
+ list_windows_modules_to_check() {
+ local f base
+ for f in "$COMPANIONS_DIR"/*.dll; do
+ [ -e "$f" ] || continue
+ base="$(basename "$f")"
+ case "$base" in
+ ggml-cpu-sandybridge.dll | ggml-cpu-haswell.dll | ggml-cpu-skylakex.dll | \
+ ggml-cpu-cannonlake.dll | ggml-cpu-cascadelake.dll | ggml-cpu-icelake.dll | \
+ ggml-cpu-alderlake.dll)
+ continue ;;
+ esac
+ printf '%s\n' "$f"
+ done
+ }
+
+ # R2: the .map CMAKE_*_LINKER_FLAGS=/MAP wrote lands in the build tree next
+ # to the DLL/exe cmake actually produced, not in the staged
+ # resources/companions directory (that directory only gets the files
+ # build-llama.sh's staging step copies out). The map's own basename always
+ # matches the module's basename without its extension; the exe is the one
+ # exception, its cmake TARGET is "llama-server" (build_triple's
+ # `--target llama-server`), not the renamed lu-llama-server-<triple> this
+ # script ships.
+ # Overridable only so this guard can be run against maps that were already
+ # copied out somewhere else (a proof run against a build this script did
+ # not itself produce, verifying a companions dir it only has read access
+ # to) without needing a real $CACHE_DIR/build-<triple> tree alongside it.
+ # A real invocation always uses the derived default.
+ WIN_BUILD_DIR="${WIN_MAP_DIR_OVERRIDE:-$CACHE_DIR/build-$TRIPLE}"
+ find_map_for() {
+ local stem="$1" hit
+ hit="$(find "$WIN_BUILD_DIR" -type f -iname "${stem}.map" -print -quit 2>/dev/null)"
+ if [ -z "$hit" ] && [ "$stem" != "llama-server" ]; then
+ hit="$(find "$WIN_BUILD_DIR" -type f -iname "llama-server.map" -print -quit 2>/dev/null)"
+ fi
+ printf '%s\n' "$hit"
+ }
+
+ NODE_BIN="$(command -v node || true)"
+ [ -n "$NODE_BIN" ] || vdie "node not found; scripts/win-isa-guard.mjs (the Windows VEX/EVEX-by-opcode-byte + .map ownership check, review-k1-avx.md R1-R3) needs it, and both this project's CI runners and the box already have it"
+
+ WIN_GUARD="$SCRIPT_DIR/win-isa-guard.mjs"
+ [ -f "$WIN_GUARD" ] || vdie "$WIN_GUARD missing"
+
+ win_fail_count=0
+ while IFS= read -r f; do
+ [ -n "$f" ] || continue
+ base="$(basename "$f")"
+ stem="${base%.dll}"
+ map_file="$(find_map_for "$stem")"
+ if [ -z "$map_file" ]; then
+ vdie "no .map file found for $f under $WIN_BUILD_DIR (stem '$stem'), /MAP did not produce one, or the build cache is stale; rebuild with scripts/build-llama.sh $TRIPLE first"
+ fi
+ disasm_tmp="$(mktemp)"
+ disassemble_windows "$f" > "$disasm_tmp"
+ if ! "$NODE_BIN" "$WIN_GUARD" check --module "$base" --disasm "$disasm_tmp" --map "$map_file"; then
+ win_fail_count=$((win_fail_count + 1))
+ fi
+ rm -f "$disasm_tmp"
+ done < <(list_windows_modules_to_check)
+
+ # exe itself, same treatment (out_name_for's stem never matches a .map
+ # basename, see find_map_for's llama-server fallback above).
+ exe_name="$(out_name_for "$TRIPLE")"
+ exe_path="$BIN_DIR/$exe_name"
+ if [ -f "$exe_path" ]; then
+ map_file="$(find_map_for "llama-server")"
+ if [ -z "$map_file" ]; then
+ vdie "no llama-server.map found under $WIN_BUILD_DIR for $exe_path"
+ fi
+ disasm_tmp="$(mktemp)"
+ disassemble_windows "$exe_path" > "$disasm_tmp"
+ if ! "$NODE_BIN" "$WIN_GUARD" check --module "$exe_name" --disasm "$disasm_tmp" --map "$map_file"; then
+ win_fail_count=$((win_fail_count + 1))
+ fi
+ rm -f "$disasm_tmp"
+ else
+ vlog "no exe found at $exe_path, skipping the exe-itself check (build first for the full check)"
+ fi
+
+ # R4, control 1/3 (positive control): independent of win-isa-guard.mjs, a
+ # raw opcode-byte grep straight on dumpbin's own output. haswell is the
+ # first AVX2 tier, so SOME VEX/EVEX byte pattern must show up, if it does
+ # not, dumpbin itself is not disassembling this file (wrong architecture,
+ # truncated output, a silently swallowed error), and every "no unprotected
+ # hit" result above is unproven, not passing.
+ haswell_file="$(find_variant_file haswell)"
+ [ -n "$haswell_file" ] || vdie "ggml-cpu-haswell.dll not found for the positive control"
+ haswell_disasm="$(disassemble_windows "$haswell_file")"
+ if ! grep -qE '^[[:space:]]*[0-9A-Fa-f]{6,16}:[[:space:]]+(C4|C5|62)[[:space:]]' <<<"$haswell_disasm"; then
+ vdie "$haswell_file (the haswell variant, which IS supposed to use AVX2) shows no VEX/EVEX opcode byte at all: dumpbin is not disassembling real code here, every result above is unproven"
+ fi
+ vlog "positive control: haswell ($haswell_file) shows VEX/EVEX opcode bytes, dumpbin is disassembling real code"
+
+ # R4, control 2/3 (negative control): haswell's OWN ggml compute kernels
+ # are unconditionally AVX2 by construction (that is the entire reason a
+ # haswell-tier DLL exists), win-isa-guard.mjs's full decision logic MUST
+ # therefore find at least one UNPROTECTED own-code hit in it. If it does
+ # not, the allowlist or the dominance check has been loosened into "allow
+ # everything", which a guard whose whole job is catching that must never
+ # do quietly.
+ haswell_map="$(find_map_for ggml-cpu-haswell)"
+ [ -n "$haswell_map" ] || vdie "no ggml-cpu-haswell.map found under $WIN_BUILD_DIR for the negative control"
+ haswell_disasm_tmp="$(mktemp)"
+ disassemble_windows "$haswell_file" > "$haswell_disasm_tmp"
+ if ! "$NODE_BIN" "$WIN_GUARD" check --module ggml-cpu-haswell.dll --disasm "$haswell_disasm_tmp" --map "$haswell_map" --expect-unprotected; then
+ rm -f "$haswell_disasm_tmp"
+ vdie "negative control failed: ggml-cpu-haswell.dll's own-code AVX2 kernels came out fully protected/allowed, which means the Windows ISA rule no longer catches anything (review-k1-avx.md R4)"
+ fi
+ rm -f "$haswell_disasm_tmp"
+ vlog "negative control: ggml-cpu-haswell.dll correctly shows at least one UNPROTECTED own-code hit (the rule still catches something)"
+
+ # R4, control 3/3 (the artificial red probe): a checked-in fixture pair
+ # (scripts/__fixtures__/win-isa/unprotected-own-code.*) that is an
+ # own-code VEX hit with NO preceding isa-availability check anywhere in
+ # its function, the shape the K1 bug actually was. This runs the
+ # decision LOGIC itself, not a real file, so it catches a future change to
+ # win-isa-guard.mjs that makes the rule pass vacuously even when no real
+ # DLL is available to test against (a Mac dev box has none of the above
+ # Windows files at all).
+ RED_PROBE_DIR="$SCRIPT_DIR/__fixtures__/win-isa"
+ if ! "$NODE_BIN" "$WIN_GUARD" check --module "red-probe" \
+ --disasm "$RED_PROBE_DIR/unprotected-own-code.disasm.txt" \
+ --map "$RED_PROBE_DIR/unprotected-own-code.map.txt"; then
+ vlog "red probe: unprotected-own-code fixture correctly came out RED"
+ else
+ vdie "red probe FAILED TO GO RED: scripts/__fixtures__/win-isa/unprotected-own-code.* (an own-code VEX hit with no preceding isa check at all) was accepted, the decision logic in win-isa-guard.mjs has a bug that lets an unprotected AVX instruction through"
+ fi
+
+ # Toolset pin, checked once against the exe (present after a real build).
+ if [ -f "$exe_path" ]; then
+ check_toolset_version "$exe_path"
+ fi
+
+ [ "$win_fail_count" -eq 0 ] || vdie "$win_fail_count Windows module(s) failed the VEX/EVEX ownership check"
+
+ vlog "OK: $TRIPLE sidecar, Windows opcode-byte VEX/EVEX guard passed on every loaded module, positive/negative/red-probe controls all correct"
+ exit 0
+fi
+
+# --- The disassembler (Linux only from here on) -----------------------------
# Every call site captures this function's stdout via `$(disassemble ...)`
# to get the disassembly text, so a diagnostic printed with plain vlog (which
diff --git a/scripts/win-isa-guard.mjs b/scripts/win-isa-guard.mjs
new file mode 100644
index 00000000..4b28c5b5
--- /dev/null
+++ b/scripts/win-isa-guard.mjs
@@ -0,0 +1,375 @@
+#!/usr/bin/env node
+//
+// win-isa-guard.mjs: the Windows-only half of the K1 (3.0.1) ISA guard.
+//
+// review-k1-avx.md (Opus, final review) found that verify-sidecar-isa.sh's
+// old rule ("no mnemonic starting with 'v' in the baseline") is not
+// holdable under MSVC: the MSVC-STL and CRT ship their own AVX2 fast paths
+// (vector_algorithms.obj, wmemcmp) inside every module they are linked
+// into, switched at runtime through __isa_available/__isa_enabled, and a
+// naive mnemonic grep cannot tell "linked in but runtime-guarded" apart
+// from "compiled in and unconditional" (the actual K1 bug). It also
+// produced flat false positives (verr/verw read out of data bytes
+// dumpbin/objdump happens to disassemble).
+//
+// This module implements Opus's replacement rule (R1-R3, R6):
+//
+// 1. Detect VEX/EVEX instructions by their OPCODE BYTE (0xC4, 0xC5, 0x62),
+// not by mnemonic spelling. In 64-bit code these three bytes are
+// unambiguous (the 32-bit-only meanings LDS/LES/BOUND do not exist in
+// long mode), so this is exact, not heuristic, and it makes verr/verw/
+// vmread false positives structurally impossible: their real opcode is
+// 0F 00 /4 and 0F 00 /5, first byte 0x0F, never 0xC4/0xC5/0x62.
+// 2. Resolve every hit's owning function from the linker .map file
+// (Publics by Value + Static symbols, both sections use the same row
+// shape: "<seg:off> <name> <VA> [f] [i] <Lib:Object>", and Lib:Object
+// is always the last whitespace token because no object/library name
+// in a .map file contains a space).
+// 3. Decide per hit:
+// - Lib:Object is msvcprt:vector_algorithms.obj, or starts with
+// "MSVCRT:", or the owning symbol is wmemcmp/memcmp: ALLOWED (CRT/STL
+// allowlist, R3.1). These carry their own runtime dispatch, verified
+// by hand in review-k1-avx.md; a naive "well it also needs a guard in
+// this function" rule would wrongly flag __std_find_trivial_impl
+// (checked in its OWN body) as fine but flag _Dispatch_pos /
+// _Make_bitmap (checked in their CALLER) as unprotected, which they
+// are not.
+// - Anything else ("own code": ggml-*.obj, llama-*.obj, common.obj,
+// server-*.obj, ggml-vulkan.obj) is ALLOWED only if, within the
+// owning function's address range, there is a read of
+// __isa_available / __isa_enabled / _Avx2WmemEnabled at an address
+// BEFORE the hit, and a conditional jump (any j-mnemonic except jmp)
+// between that read and the hit whose target lands AFTER the hit and
+// still inside the function (the block-skip shape the MSVC
+// auto-vectorizer and the STL dispatcher both emit). Anything else
+// is UNPROTECTED, RED.
+//
+// This is an approximation of a real control-flow graph, not one (R3,
+// "Bewertung der Regel, ehrlich"): it cannot see a function that reads the
+// ISA flag for an unrelated reason and then falls into unconditional AVX
+// anyway. The three controls in verify-sidecar-isa.sh's Windows branch
+// (positive: haswell has ANY hit at all; negative: haswell's OWN-CODE
+// kernels come out UNPROTECTED under this same decision logic, so the rule
+// has not been loosened into "allow everything"; red-probe: the fixtures in
+// scripts/__fixtures__/win-isa/ prove the decision function itself, not
+// just real files) exist to bound that risk, not to remove it.
+//
+// Deliberately dependency-free (no npm install step for a build guard) and
+// works on both dumpbin's Intel-syntax output (the box, and Windows CI once
+// a Developer Command Prompt is on PATH); see readTextFileAuto for the
+// encoding note.
+
+import { readFileSync, realpathSync } from 'node:fs';
+import { fileURLToPath } from 'node:url';
+
+// dumpbin redirected to a file from a plain `cmd`/`powershell` session can
+// come out UTF-16LE with a BOM depending on how the caller captured it
+// (Out-File's default vs. plain `>` redirection differ). Decode by BOM when
+// present instead of assuming UTF-8 and silently mangling every address.
+export function readTextFileAuto(path) {
+ const buf = readFileSync(path);
+ if (buf.length >= 2 && buf[0] === 0xff && buf[1] === 0xfe) {
+ return buf.slice(2).toString('utf16le');
+ }
+ if (buf.length >= 3 && buf[0] === 0xef && buf[1] === 0xbb && buf[2] === 0xbf) {
+ return buf.slice(3).toString('utf8');
+ }
+ return buf.toString('utf8');
+}
+
+// One disassembled instruction line: address, raw opcode bytes (as printed,
+// upper/lowercase not normalised here), and the mnemonic+operand text.
+// Continuation lines dumpbin emits for instructions that overflow the byte
+// column onto a second line (review-k1-avx.md R1) carry no address and are
+// simply not matched by either regex below, which is correct: the opcode's
+// FIRST byte, all that VEX/EVEX detection needs, is always on the anchored
+// line.
+const DUMPBIN_LINE = /^\s*([0-9A-Fa-f]{16}):\s+((?:[0-9A-Fa-f]{2}\s+)*[0-9A-Fa-f]{2})\s+(\S.*?)\s*$/;
+// GNU objdump on a PE/COFF x86_64 image also prints an absolute VA (not an
+// ELF-style section offset) followed by a tab, the raw byte column, a tab,
+// then the AT&T-syntax instruction, same shape, different separators.
+const OBJDUMP_LINE = /^\s*([0-9A-Fa-f]+):\t((?:[0-9A-Fa-f]{2}\s+)*[0-9A-Fa-f]{2})\s*\t(\S.*?)\s*$/;
+
+export function parseDisasmLines(text) {
+ const lines = [];
+ for (const raw of text.split(/\r?\n/)) {
+ const m = DUMPBIN_LINE.exec(raw) || OBJDUMP_LINE.exec(raw);
+ if (!m) continue;
+ const addr = parseInt(m[1], 16);
+ const bytes = m[2].trim().split(/\s+/);
+ const rest = m[3];
+ const spaceIdx = rest.search(/\s/);
+ const mnemonic = (spaceIdx === -1 ? rest : rest.slice(0, spaceIdx)).toLowerCase();
+ lines.push({ addr, bytes, text: rest, mnemonic, raw });
+ }
+ lines.sort((a, b) => a.addr - b.addr);
+ return lines;
+}
+
+// R1: VEX/EVEX are unambiguous by first opcode byte in 64-bit code.
+const VEX_EVEX_FIRST_BYTES = new Set(['c4', 'c5', '62']);
+
+export function isVexEvexHit(line) {
+ const first = (line.bytes[0] || '').toLowerCase();
+ return VEX_EVEX_FIRST_BYTES.has(first);
+}
+
+export function findVexEvexHits(lines) {
+ return lines.filter(isVexEvexHit);
+}
+
+// .map row: "<seg:off> <name> <VA 16 hex> [f] [i] <Lib:Object>". The
+// Lib:Object field is always the trailing whitespace-delimited token: no
+// object/library name in a linker map contains a space, decorated (mangled)
+// C++ names included.
+const MAP_ROW = /^\s*[0-9A-Fa-f]{4}:[0-9A-Fa-f]{8}\s+(\S+)\s+([0-9A-Fa-f]{16})\s+(.+?)\s*$/;
+
+export function parseMapSymbols(text) {
+ const symbols = [];
+ for (const raw of text.split(/\r?\n/)) {
+ const m = MAP_ROW.exec(raw);
+ if (!m) continue;
+ const name = m[1];
+ const va = parseInt(m[2], 16);
+ const tail = m[3].trim().split(/\s+/).filter((t) => t !== 'f' && t !== 'i');
+ const obj = tail[tail.length - 1] || '';
+ symbols.push({ name, va, obj });
+ }
+ symbols.sort((a, b) => a.va - b.va);
+ return symbols;
+}
+
+// Largest symbol address <= addr; "function end" is the next symbol's
+// address (Infinity if addr is the last symbol). This is R3's stated
+// approximation, not a real function-boundary table.
+export function findOwner(symbolsSortedByVa, addr) {
+ let lo = 0;
+ let hi = symbolsSortedByVa.length - 1;
+ let ownerIdx = -1;
+ while (lo <= hi) {
+ const mid = (lo + hi) >> 1;
+ if (symbolsSortedByVa[mid].va <= addr) {
+ ownerIdx = mid;
+ lo = mid + 1;
+ } else {
+ hi = mid - 1;
+ }
+ }
+ if (ownerIdx === -1) return null;
+ const owner = symbolsSortedByVa[ownerIdx];
+ const end = ownerIdx + 1 < symbolsSortedByVa.length ? symbolsSortedByVa[ownerIdx + 1].va : Infinity;
+ return { owner, functionStart: owner.va, functionEnd: end };
+}
+
+const ISA_SYMBOL_NAMES = new Set([
+ '__isa_available',
+ '__isa_enabled',
+ '_Avx2WmemEnabled',
+ '_Avx2WmemEnabledWeakValue',
+]);
+
+export function findIsaSymbolVAs(symbols) {
+ const vas = [];
+ for (const s of symbols) {
+ if (ISA_SYMBOL_NAMES.has(s.name)) vas.push(s.va);
+ }
+ return vas;
+}
+
+// R3.1: the CRT/STL allowlist. Named exactly, with the source it was
+// checked against, so a future reader can re-verify rather than trust this
+// comment: microsoft/STL, stl/src/vector_algorithms.cpp, _Use_avx2() is
+// `__isa_enabled & (1 << __ISA_AVAILABLE_AVX2)`; wmemcmp's fast path is
+// gated on the separate _Avx2WmemEnabled flag instead (same file family).
+// Reviewed against MSVC 19.44.35222.0 / VS 2022 17.14, see
+// checkToolsetVersion below and lu-301/bau/review-k1-avx.md section 3.
+export function isAllowlisted(owner) {
+ if (!owner) return false;
+ if (owner.obj === 'msvcprt:vector_algorithms.obj') return true;
+ if (owner.obj.startsWith('MSVCRT:')) return true;
+ if (/\bwmemcmp\b/i.test(owner.name) || /\bmemcmp\b/i.test(owner.name)) return true;
+ return false;
+}
+
+function hexVA(n) {
+ return n.toString(16).padStart(16, '0');
+}
+
+// R3.2: the dominance approximation for "own code". Looks for an isa-flag
+// read before the hit in the owning function, then a conditional jump
+// (mnemonic starts with j, is not jmp) between that read and the hit whose
+// target lands strictly after the hit and still inside the function, the
+// exact shape both Fundstelle 1a/1b (STL) and 2a-2d (ggml auto-vectorizer)
+// showed in review-k1-avx.md.
+export function checkDominance(linesSortedByAddr, isaVAs, functionStart, functionEnd, hitAddr) {
+ if (isaVAs.length === 0) {
+ return { protected: false, reason: 'no __isa_available/__isa_enabled/_Avx2WmemEnabled symbol found in this map at all' };
+ }
+ const isaHexes = isaVAs.map(hexVA);
+ let checkLine = null;
+ for (const line of linesSortedByAddr) {
+ if (line.addr < functionStart) continue;
+ if (line.addr >= hitAddr) break;
+ const upper = line.text.toUpperCase();
+ if (isaHexes.some((h) => upper.includes(h.toUpperCase()))) {
+ checkLine = line; // keep scanning: the closest-before check is fine, any is fine
+ }
+ }
+ if (!checkLine) {
+ return { protected: false, reason: 'no isa-flag read found before the hit in the owning function' };
+ }
+ for (const line of linesSortedByAddr) {
+ if (line.addr <= checkLine.addr) continue;
+ if (line.addr >= hitAddr) break;
+ if (!/^j/.test(line.mnemonic) || line.mnemonic === 'jmp') continue;
+ const m = /([0-9A-Fa-f]{6,16})h?\s*$/.exec(line.text.trim());
+ if (!m) continue;
+ const target = parseInt(m[1], 16);
+ if (target > hitAddr && target <= functionEnd) {
+ return { protected: true, checkLine, jumpLine: line };
+ }
+ }
+ return {
+ protected: false,
+ reason: `isa-flag read found at ${hexVA(checkLine.addr)} but no conditional jump between it and the hit lands past the hit inside the function`,
+ };
+}
+
+// Evaluate one module: disasm text + its own .map text. Returns one verdict
+// row per VEX/EVEX hit plus summary counts (used for the map-control, R4).
+export function evaluateModule({ moduleName, disasmText, mapText }) {
+ const lines = parseDisasmLines(disasmText);
+ const symbols = parseMapSymbols(mapText);
+ const isaVAs = findIsaSymbolVAs(symbols);
+ const hits = findVexEvexHits(lines);
+
+ const verdicts = [];
+ let ownedHits = 0;
+ for (const hit of hits) {
+ const found = findOwner(symbols, hit.addr);
+ if (!found) {
+ verdicts.push({ hit, verdict: 'UNKNOWN_OWNER', reason: 'no symbol at or before this address in the map' });
+ continue;
+ }
+ ownedHits += 1;
+ const { owner, functionStart, functionEnd } = found;
+ if (isAllowlisted(owner)) {
+ verdicts.push({ hit, owner, verdict: 'ALLOWED_CRT' });
+ continue;
+ }
+ const dom = checkDominance(lines, isaVAs, functionStart, functionEnd, hit.addr);
+ verdicts.push({
+ hit,
+ owner,
+ verdict: dom.protected ? 'ALLOWED_PROTECTED' : 'UNPROTECTED',
+ reason: dom.reason,
+ });
+ }
+
+ return {
+ moduleName,
+ symbolCount: symbols.length,
+ hitCount: hits.length,
+ ownedHitCount: ownedHits,
+ verdicts,
+ unprotected: verdicts.filter((v) => v.verdict === 'UNPROTECTED' || v.verdict === 'UNKNOWN_OWNER'),
+ };
+}
+
+function formatVerdict(v) {
+ const addr = hexVA(v.hit.addr);
+ const obj = v.owner ? v.owner.obj : '?';
+ const fn = v.owner ? v.owner.name : '?';
+ const base = `${addr}: ${v.hit.text} [${v.verdict}] fn=${fn} obj=${obj}`;
+ return v.reason ? `${base} (${v.reason})` : base;
+}
+
+// --- CLI ---------------------------------------------------------------
+function main(argv) {
+ const mode = argv[0];
+ if (mode !== 'check') {
+ process.stderr.write('usage: win-isa-guard.mjs check --module <name> --disasm <file> --map <file> [--expect-unprotected] [--min-symbols N]\n');
+ process.exit(2);
+ }
+ const args = {};
+ for (let i = 1; i < argv.length; i += 1) {
+ const a = argv[i];
+ if (a.startsWith('--')) {
+ const key = a.slice(2);
+ const next = argv[i + 1];
+ if (next === undefined || next.startsWith('--')) {
+ args[key] = true;
+ } else {
+ args[key] = next;
+ i += 1;
+ }
+ }
+ }
+ if (!args.module || !args.disasm || !args.map) {
+ process.stderr.write('missing --module/--disasm/--map\n');
+ process.exit(2);
+ }
+ const disasmText = readTextFileAuto(args.disasm);
+ const mapText = readTextFileAuto(args.map);
+ const result = evaluateModule({ moduleName: args.module, disasmText, mapText });
+
+ const minSymbols = args['min-symbols'] ? parseInt(args['min-symbols'], 10) : 1;
+ process.stdout.write(`[win-isa-guard] ${result.moduleName}: ${result.symbolCount} map symbols, ${result.hitCount} VEX/EVEX hit(s), ${result.ownedHitCount} resolved to an owner\n`);
+ for (const v of result.verdicts) {
+ process.stdout.write(`[win-isa-guard] ${formatVerdict(v)}\n`);
+ }
+
+ if (result.symbolCount < minSymbols) {
+ process.stderr.write(`[win-isa-guard] FAIL: ${result.moduleName}'s map yielded only ${result.symbolCount} symbol(s) (need >= ${minSymbols}); a map this empty means ownership resolution is silently useless (review-k1-avx.md R4 map-control)\n`);
+ process.exit(1);
+ }
+ if (result.hitCount > 0 && result.ownedHitCount === 0) {
+ process.stderr.write(`[win-isa-guard] FAIL: ${result.moduleName} has ${result.hitCount} VEX/EVEX hit(s) but NONE resolved to a named owner; the allowlist and dominance check cannot run at all (review-k1-avx.md R4 map-control)\n`);
+ process.exit(1);
+ }
+
+ if (args['expect-unprotected']) {
+ // Negative control (R4): this module is EXPECTED to contain at least one
+ // UNPROTECTED own-code hit (e.g. the haswell CPU variant, whose kernels
+ // are unconditionally AVX2 by construction). Its absence means the
+ // decision logic has been loosened into "allow everything".
+ const unprotectedOwn = result.verdicts.filter((v) => v.verdict === 'UNPROTECTED');
+ if (unprotectedOwn.length === 0) {
+ process.stderr.write(`[win-isa-guard] FAIL (negative control): ${result.moduleName} was expected to contain at least one UNPROTECTED own-code VEX/EVEX instruction (it is a CPU-tier variant with unconditional AVX kernels) but the guard found none; the allowlist or dominance rule has gone soft\n`);
+ process.exit(1);
+ }
+ process.stdout.write(`[win-isa-guard] OK (negative control): ${result.moduleName} correctly shows ${unprotectedOwn.length} UNPROTECTED own-code hit(s)\n`);
+ process.exit(0);
+ }
+
+ if (result.unprotected.length > 0) {
+ process.stderr.write(`[win-isa-guard] FAIL: ${result.moduleName} has ${result.unprotected.length} unprotected VEX/EVEX instruction(s) in own code\n`);
+ process.exit(1);
+ }
+ process.stdout.write(`[win-isa-guard] OK: ${result.moduleName}, no unprotected VEX/EVEX in own code\n`);
+ process.exit(0);
+}
+
+// Cross-platform "am I the entry script" check. The naive
+// `import.meta.url === 'file://' + process.argv[1]` comparison this used to
+// be is a string-format mismatch by construction on Windows: import.meta.url
+// is a URL ("file:///C:/foo/bar.mjs", forward slashes, percent-escaped) while
+// process.argv[1] is a native path ("C:\foo\bar.mjs", backslashes), the two
+// never compare equal there, so main() silently never ran and every `node
+// win-isa-guard.mjs check ...` invocation exited 0 having done nothing at
+// all (found running this exact guard against the real box build:
+// lu-301/bau/waechter-windows.md). Comparing two REAL filesystem paths
+// (both resolved through fs, neither a URL) works the same way on every
+// platform.
+function isEntryScript() {
+ if (!process.argv[1]) return false;
+ try {
+ return realpathSync(process.argv[1]) === realpathSync(fileURLToPath(import.meta.url));
+ } catch {
+ return false;
+ }
+}
+
+if (isEntryScript()) {
+ main(process.argv.slice(2));
+}
diff --git a/scripts/win-isa-guard.test.mjs b/scripts/win-isa-guard.test.mjs
new file mode 100644
index 00000000..80c42f6f
--- /dev/null
+++ b/scripts/win-isa-guard.test.mjs
@@ -0,0 +1,176 @@
+// Unit tests for scripts/win-isa-guard.mjs against small, checked-in fixture
+// excerpts (scripts/__fixtures__/win-isa/), not the multi-MB real dumpbin
+// dumps from lu-301/e2e/k1-avx/, which stay out of the repo. Run with:
+// node --test scripts/win-isa-guard.test.mjs
+import { test } from 'node:test';
+import assert from 'node:assert/strict';
+import { readFileSync } from 'node:fs';
+import { fileURLToPath } from 'node:url';
+import { dirname, join } from 'node:path';
+import { spawnSync } from 'node:child_process';
+
+import {
+ parseDisasmLines,
+ parseMapSymbols,
+ findVexEvexHits,
+ isVexEvexHit,
+ findOwner,
+ isAllowlisted,
+ checkDominance,
+ evaluateModule,
+} from './win-isa-guard.mjs';
+
+const HERE = dirname(fileURLToPath(import.meta.url));
+const FIXTURES = join(HERE, '__fixtures__', 'win-isa');
+
+function loadFixture(name) {
+ return {
+ disasmText: readFileSync(join(FIXTURES, `${name}.disasm.txt`), 'utf8'),
+ mapText: readFileSync(join(FIXTURES, `${name}.map.txt`), 'utf8'),
+ };
+}
+
+test('R1: VEX/EVEX detection is by opcode byte, not mnemonic spelling', () => {
+ const lines = parseDisasmLines([
+ ' 0000000180000000: C5 F9 6E D8 vmovd xmm3,eax',
+ ' 0000000180000004: C4 E3 65 18 DB 01 vinsertf128 ymm3,ymm3,xmm3,1',
+ ' 0000000180000010: 62 F2 F5 08 40 C6 vpmullq xmm0,xmm1,xmm6',
+ // verr/verw real opcode is 0F 00 /4 /5, first byte 0F, never C4/C5/62.
+ ' 0000000180000020: 0F 00 34 25 00 00 verr word ptr [0]',
+ ' 0000000180000030: 48 89 5C 24 08 mov qword ptr [rsp+8],rbx',
+ ].join('\n'));
+ assert.equal(lines.length, 5);
+ const hits = findVexEvexHits(lines);
+ assert.equal(hits.length, 3, 'exactly the three real VEX/EVEX lines, verr/verw and mov excluded');
+ assert.ok(hits.every((h) => isVexEvexHit(h)));
+});
+
+test('R1: a dumpbin continuation line (no address) is not parsed as its own instruction', () => {
+ // Real dumpbin wraps long instructions onto a second line with no leading
+ // address; that line must simply not match, not be mis-read as a hit.
+ const lines = parseDisasmLines([
+ ' 0000000180000000: 48 8D 05 00 00 00 00',
+ ' 00 lea rax,[rip]',
+ ].join('\n'));
+ assert.equal(lines.length, 1);
+ assert.equal(lines[0].addr, 0x180000000);
+});
+
+test('.map row parsing: Lib:Object is the trailing token, f/i flags are stripped', () => {
+ const symbols = parseMapSymbols([
+ ' 0001:00091000 __std_find_trivial_1 0000000180092000 f msvcprt:vector_algorithms.obj',
+ ' 0003:000001b8 __isa_available 00000001800b51b8 MSVCRT:cpu_disp.obj',
+ ' 0002:00020784 __NULL_IMPORT_DESCRIPTOR 00000001800b3784 ggml-base:ggml-base.dll',
+ ].join('\n'));
+ assert.equal(symbols.length, 3);
+ const find = symbols.find((s) => s.name === '__std_find_trivial_1');
+ assert.equal(find.obj, 'msvcprt:vector_algorithms.obj');
+ assert.equal(find.va, 0x180092000);
+ const isa = symbols.find((s) => s.name === '__isa_available');
+ assert.equal(isa.obj, 'MSVCRT:cpu_disp.obj');
+});
+
+test('findOwner: largest symbol address <= target, function end is the next symbol', () => {
+ const symbols = parseMapSymbols([
+ ' 0001:00000000 f_one 0000000180001000 f a.obj',
+ ' 0001:00000100 f_two 0000000180001100 f b.obj',
+ ].join('\n'));
+ const owned = findOwner(symbols, 0x180001050);
+ assert.equal(owned.owner.name, 'f_one');
+ assert.equal(owned.functionEnd, 0x180001100);
+ assert.equal(findOwner(symbols, 0x180000fff), null, 'address before every symbol has no owner');
+});
+
+test('isAllowlisted: msvcprt:vector_algorithms.obj, MSVCRT:*, and wmemcmp/memcmp are allowed; own code is not', () => {
+ assert.equal(isAllowlisted({ obj: 'msvcprt:vector_algorithms.obj', name: 'x' }), true);
+ assert.equal(isAllowlisted({ obj: 'MSVCRT:cpu_disp.obj', name: 'x' }), true);
+ assert.equal(isAllowlisted({ obj: 'ggml.obj', name: 'wmemcmp' }), true);
+ assert.equal(isAllowlisted({ obj: 'ggml-quants.obj', name: 'iq2xs_init_impl$omp$1' }), false);
+});
+
+test('checkDominance: finds the isa-read-then-guarding-jump shape (Fundstelle 2a pattern)', () => {
+ const lines = parseDisasmLines([
+ ' 0000000180027ED6: 8B 0D BC 19 07 00 mov ecx,dword ptr [0000000180099898h]',
+ ' 0000000180027F7E: 83 F9 05 cmp ecx,5',
+ ' 0000000180027F81: 7C 40 jl 0000000180027FC3',
+ ' 0000000180027F83: C4 C2 71 46 C2 vpsravd xmm0,xmm1,xmm10',
+ ' 0000000180027FC3: 48 8D 94 24 88 00 lea rdx,[rsp+88h]',
+ ].join('\n'));
+ const dom = checkDominance(lines, [0x180099898], 0x180027e10, 0x180028010, 0x180027f83);
+ assert.equal(dom.protected, true);
+});
+
+test('checkDominance: an isa read with no bounding jump is NOT protected', () => {
+ const lines = parseDisasmLines([
+ ' 0000000180027ED6: 8B 0D BC 19 07 00 mov ecx,dword ptr [0000000180099898h]',
+ ' 0000000180027F83: C4 C2 71 46 C2 vpsravd xmm0,xmm1,xmm10',
+ ].join('\n'));
+ const dom = checkDominance(lines, [0x180099898], 0x180027e10, 0x180028010, 0x180027f83);
+ assert.equal(dom.protected, false);
+});
+
+test('checkDominance: no isa symbol in the map at all is NOT protected', () => {
+ const lines = parseDisasmLines([
+ ' 0000000180027F83: C4 C2 71 46 C2 vpsravd xmm0,xmm1,xmm10',
+ ].join('\n'));
+ const dom = checkDominance(lines, [], 0x180027e10, 0x180028010, 0x180027f83);
+ assert.equal(dom.protected, false);
+});
+
+test('fixture: protected-own-code (real Fundstelle 2a pattern) -> ALLOWED_PROTECTED, zero unprotected', () => {
+ const { disasmText, mapText } = loadFixture('protected-own-code');
+ const result = evaluateModule({ moduleName: 'protected-own-code', disasmText, mapText });
+ assert.equal(result.hitCount, 1);
+ assert.equal(result.unprotected.length, 0);
+ assert.equal(result.verdicts[0].verdict, 'ALLOWED_PROTECTED');
+});
+
+test('fixture: crt-allowed (real Fundstelle 1a pattern, no isa read in-function) -> ALLOWED_CRT via allowlist', () => {
+ const { disasmText, mapText } = loadFixture('crt-allowed');
+ const result = evaluateModule({ moduleName: 'crt-allowed', disasmText, mapText });
+ assert.equal(result.hitCount, 1);
+ assert.equal(result.unprotected.length, 0);
+ assert.equal(result.verdicts[0].verdict, 'ALLOWED_CRT');
+});
+
+test('RED PROBE: unprotected-own-code MUST come out UNPROTECTED (review-k1-avx.md R4)', () => {
+ const { disasmText, mapText } = loadFixture('unprotected-own-code');
+ const result = evaluateModule({ moduleName: 'unprotected-own-code', disasmText, mapText });
+ assert.equal(result.hitCount, 1);
+ assert.equal(result.unprotected.length, 1, 'the red probe must never be silently allowed');
+ assert.equal(result.verdicts[0].verdict, 'UNPROTECTED');
+});
+
+test('CLI: the script actually runs main() as a real subprocess and exits 1 on the red probe', () => {
+ // Regression test for a real bug found running this exact guard on the
+ // Windows box (lu-301/bau/waechter-windows.md): the old entry-point check
+ // compared `import.meta.url` (a file:// URL, forward slashes) against
+ // `'file://' + process.argv[1]` (a native path, backslashes on Windows),
+ // never equal there, so main() silently never ran and `node
+ // win-isa-guard.mjs check ...` exited 0 having checked nothing at all,
+ // on every invocation. A plain function-level test that only imports the
+ // module (as every other test in this file does) cannot catch that class
+ // of bug, because import.meta.url never even enters the entry-point
+ // branch when the file is merely imported, it has to actually be run as
+ // node's entry script, hence a real subprocess here.
+ const script = join(HERE, 'win-isa-guard.mjs');
+ const result = spawnSync(process.execPath, [
+ script,
+ 'check',
+ '--module', 'red-probe',
+ '--disasm', join(FIXTURES, 'unprotected-own-code.disasm.txt'),
+ '--map', join(FIXTURES, 'unprotected-own-code.map.txt'),
+ ], { encoding: 'utf8' });
+ assert.equal(result.status, 1, `expected exit 1 (unprotected hit), got ${result.status}. stdout:\n${result.stdout}\nstderr:\n${result.stderr}`);
+ assert.match(result.stdout, /UNPROTECTED/);
+});
+
+test('map-control: a module with VEX/EVEX hits but zero map symbols cannot resolve any owner', () => {
+ const disasmText = ' 0000000180000000: C5 F9 6E D8 vmovd xmm3,eax';
+ const result = evaluateModule({ moduleName: 'empty-map', disasmText, mapText: '' });
+ assert.equal(result.symbolCount, 0);
+ assert.equal(result.hitCount, 1);
+ assert.equal(result.ownedHitCount, 0);
+ assert.equal(result.unprotected.length, 1, 'an unresolved owner must fail closed, not pass silently');
+ assert.equal(result.verdicts[0].verdict, 'UNKNOWN_OWNER');
+});