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): Waechter Runde 2, drei Blocker behoben

purple51dff7ea360f
diff --git a/scripts/__fixtures__/win-isa/fake-address-as-constant-own-code.disasm.txt b/scripts/__fixtures__/win-isa/fake-address-as-constant-own-code.disasm.txt
new file mode 100644
index 00000000..2f6b46f4
--- /dev/null
+++ b/scripts/__fixtures__/win-isa/fake-address-as-constant-own-code.disasm.txt
@@ -0,0 +1,13 @@
+Dump of file fixture: Opus's fake-green pattern F (review-waechter-windows.md
+N1). The isa flag's ADDRESS is used only as a bare immediate constant
+("mov rax,<isa>h", no brackets, never dereferenced), followed by an
+unrelated je and then the hit. The old dominance check matched the isa
+address as a plain substring of the instruction text, with no requirement
+that it actually be dereferenced; this fixture must come out UNPROTECTED,
+because the flag's VALUE was never read at all.
+
+ 0000000180070000: 48 B8 98 98 09 80 01 00 00 00 mov rax,0000000180099898h
+ 0000000180070010: 48 85 C0 test rax,rax
+ 0000000180070014: 74 1A je 0000000180070030
+ 0000000180070020: C5 F9 6E D8 vmovd xmm3,eax
+ 0000000180070030: C3 ret
diff --git a/scripts/__fixtures__/win-isa/fake-address-as-constant-own-code.map.txt b/scripts/__fixtures__/win-isa/fake-address-as-constant-own-code.map.txt
new file mode 100644
index 00000000..cdda3483
--- /dev/null
+++ b/scripts/__fixtures__/win-isa/fake-address-as-constant-own-code.map.txt
@@ -0,0 +1,5 @@
+ Static symbols
+
+ 0001:00000000 fake_address_as_constant_kernel 0000000180070000 f ggml-fake-red.obj
+ 0001:00000100 fake_address_as_constant_kernel_end 0000000180070100 f ggml-fake-red.obj
+ 0003:00000010 __isa_available 0000000180099898 MSVCRT:cpu_disp.obj
diff --git a/scripts/__fixtures__/win-isa/fake-unrelated-jump-own-code.disasm.txt b/scripts/__fixtures__/win-isa/fake-unrelated-jump-own-code.disasm.txt
new file mode 100644
index 00000000..e0769621
--- /dev/null
+++ b/scripts/__fixtures__/win-isa/fake-unrelated-jump-own-code.disasm.txt
@@ -0,0 +1,14 @@
+Dump of file fixture: Opus's fake-green pattern A (review-waechter-windows.md
+N1). An own-code object with a genuine isa-flag read (left over from an
+earlier, unrelated loop), then an UNRELATED null-pointer test whose jump
+also happens to land past the hit, then an unconditional VEX instruction.
+The old dominance check ("some isa read before the hit, some conditional
+jump landing after it") accepted this; it must come out UNPROTECTED, because
+the jump that actually reaches past the hit never evaluates the isa flag at
+all.
+
+ 0000000180060000: 8B 0D BC 19 07 00 mov ecx,dword ptr [0000000180099898h]
+ 0000000180060010: 48 85 C0 test rax,rax
+ 0000000180060014: 74 1A je 0000000180060030
+ 0000000180060020: C5 F9 6E D8 vmovd xmm3,eax
+ 0000000180060030: C3 ret
diff --git a/scripts/__fixtures__/win-isa/fake-unrelated-jump-own-code.map.txt b/scripts/__fixtures__/win-isa/fake-unrelated-jump-own-code.map.txt
new file mode 100644
index 00000000..98eb129f
--- /dev/null
+++ b/scripts/__fixtures__/win-isa/fake-unrelated-jump-own-code.map.txt
@@ -0,0 +1,5 @@
+ Static symbols
+
+ 0001:00000000 fake_unrelated_jump_kernel 0000000180060000 f ggml-fake-red.obj
+ 0001:00000100 fake_unrelated_jump_kernel_end 0000000180060100 f ggml-fake-red.obj
+ 0003:00000010 __isa_available 0000000180099898 MSVCRT:cpu_disp.obj
diff --git a/scripts/build-llama-flags.test.mjs b/scripts/build-llama-flags.test.mjs
new file mode 100644
index 00000000..0090c6ec
--- /dev/null
+++ b/scripts/build-llama-flags.test.mjs
@@ -0,0 +1,53 @@
+// BL1 (review-waechter-windows.md): scripts/build-llama.sh's Windows MSVC
+// linker-map flag must be spelled "-MAP", not "/MAP". Measured on the real
+// box: MSYS/Git-Bash rewrites an argv entry that looks like a Unix absolute
+// path ("/MAP") into a native Windows path before the (unquoted) cmake
+// invocation ever sees it, so the old spelling never produced a .map file
+// at all, and verify-sidecar-isa.sh's Windows guard died with "no .map file
+// found" the very first time this script's committed form actually ran.
+// This test cannot reproduce the MSYS argv rewriting itself (that only
+// happens on a real Windows Git-Bash), so it checks the one thing runnable
+// everywhere: the flag scripts/build-llama.sh actually emits. The real
+// proof that the fix holds is a real Windows rebuild, see
+// lu-301/bau/waechter-windows.md "Runde 2".
+//
+// Run with: node --test scripts/build-llama-flags.test.mjs
+import { test } from 'node:test';
+import assert from 'node:assert/strict';
+import { execFileSync } from 'node:child_process';
+import { fileURLToPath } from 'node:url';
+import { dirname, join } from 'node:path';
+
+const HERE = dirname(fileURLToPath(import.meta.url));
+const SCRIPT = join(HERE, 'build-llama.sh');
+
+function cmakeFlagsFor(triple) {
+ // Source the script (never runs main(), see build-llama.sh's own
+ // `[ "${BASH_SOURCE[0]}" = "${0}" ]` guard: under `bash -c "source ..."`,
+ // BASH_SOURCE[0] is the sourced file but $0 stays "bash", so they never
+ // match) purely to reach the pure `cmake_flags_for` function.
+ return execFileSync('bash', ['-c', `source "${SCRIPT}"; cmake_flags_for "${triple}"`], {
+ encoding: 'utf8',
+ }).trim();
+}
+
+test('BL1: the Windows MSVC linker-map flags use -MAP, not /MAP', () => {
+ const flags = cmakeFlagsFor('x86_64-pc-windows-msvc');
+ assert.match(
+ flags,
+ /-DCMAKE_SHARED_LINKER_FLAGS=-MAP\b/,
+ 'a leading slash ("/MAP") is a Unix absolute path as far as MSYS/Git-Bash argv rewriting is concerned and is silently turned into a native filesystem path before cmake/link.exe ever sees it (measured on the box: "/MAP" becomes "C:/Program Files/Git/MAP"), so the linker never receives the flag and produces no .map file at all',
+ );
+ assert.match(flags, /-DCMAKE_EXE_LINKER_FLAGS=-MAP\b/);
+});
+
+test('BL1: no leading-slash /MAP survives anywhere in the Windows linker flags', () => {
+ const flags = cmakeFlagsFor('x86_64-pc-windows-msvc');
+ assert.doesNotMatch(flags, /LINKER_FLAGS=\/MAP\b/, 'BL1 would recur if either linker-flags variable used the leading-slash spelling again');
+});
+
+test('mac and Linux cmake flags are untouched by the Windows -MAP fix', () => {
+ assert.doesNotMatch(cmakeFlagsFor('aarch64-apple-darwin'), /MAP/);
+ assert.doesNotMatch(cmakeFlagsFor('x86_64-apple-darwin'), /MAP/);
+ assert.doesNotMatch(cmakeFlagsFor('x86_64-unknown-linux-gnu'), /MAP/);
+});
diff --git a/scripts/build-llama.sh b/scripts/build-llama.sh
index 11815c5f..e44fd866 100755
--- a/scripts/build-llama.sh
+++ b/scripts/build-llama.sh
@@ -127,19 +127,27 @@ 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)
- # /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" ;;
+ # -MAP, not /MAP (review-waechter-windows.md BL1): 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). MSYS/Git-Bash rewrites an
+ # ARGV entry that looks like a Unix absolute path ("/MAP") into a native
+ # Windows path before the (unquoted) cmake invocation in build_triple
+ # below ever sees it, on the command line just as much as in an
+ # environment variable: measured on the box, `cmd //c echo
+ # -DCMAKE_SHARED_LINKER_FLAGS=/MAP` comes back as
+ # `-DCMAKE_SHARED_LINKER_FLAGS=C:/Program Files/Git/MAP`, so the linker
+ # never received /MAP at all and produced no .map file (an earlier
+ # version of this comment claimed the cmake command line was exempt
+ # from that rewriting; it measured that only against a Windows CI
+ # workflow log that had been produced with a manual override, and the
+ # claim was wrong). link.exe accepts the single-dash spelling exactly
+ # the same way (`cmd //c echo -DCMAKE_SHARED_LINKER_FLAGS=-MAP` passes
+ # through unchanged, since "-MAP" does not look like a Unix path to
+ # MSYS's argv rewriter), so use that instead of 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).
+ 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 e6fc8a0e..9a44f0e8 100755
--- a/scripts/verify-sidecar-isa.sh
+++ b/scripts/verify-sidecar-isa.sh
@@ -28,6 +28,30 @@
# companions directory (a partial build, or a future cmake refactor that
# drops a name this project still assumes).
#
+# TOOLSET PIN (review-waechter-windows.md N7): the Windows branch below
+# trusts a specific, hand-disassembled CRT/STL allowlist
+# (msvcprt:vector_algorithms.obj and the wmemcmp/memcmp fast path, see
+# win-isa-guard.mjs isAllowlisted) rather than re-deriving it from source on
+# every run. That trust is pinned to a Major.Minor MSVC LINKER version
+# (WINDOWS_REVIEWED_LINKER_VERSIONS below, currently "14.44", i.e. MSVC
+# 19.44.35222.0 / VS 2022 17.14, lu-301/bau/review-k1-avx.md section 3) and
+# check_toolset_version turns the guard red the moment a build used a
+# different one, rather than silently keep trusting an allowlist nobody
+# re-checked. To clear a red toolset-pin failure: re-run the Opus-style
+# manual disassembly review (dumpbin /disasm against the new toolset's
+# msvcprt:vector_algorithms.obj and wmemcmp/common.obj, unicode.obj,
+# ggml-backend-reg.obj, server-context.obj — the exact objects
+# win-isa-guard.mjs's isAllowlisted trusts, see WMEMCMP_MEMCMP_HOST_OBJECTS
+# there) to confirm the new toolset's CRT/STL fast paths are still
+# self-guarded by __isa_enabled/_Avx2WmemEnabled the same way, then add the
+# new linker Major.Minor to WINDOWS_REVIEWED_LINKER_VERSIONS. Realistically
+# this is not a rare event: windows-latest pulls a new MSVC patch release on
+# roughly a one-to-two-month cadence, so expect this pin to need bumping on
+# that cadence, most visibly in a release run — it is a planned, periodic
+# cost of trusting a hand-reviewed allowlist rather than a rare emergency,
+# and the sidecar build cache (keyed on hashFiles('scripts/build-llama.sh'))
+# only defers it, it does not remove it.
+#
# Usage: scripts/verify-sidecar-isa.sh <triple>
set -euo pipefail
@@ -329,17 +353,56 @@ if [[ "$TRIPLE" == *-windows-* ]]; then
# 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.
+ #
+ # N5 (review-waechter-windows.md): the exclusion list used to be a SECOND,
+ # independently hand-written copy of the high-tier variant names, free to
+ # drift away from EXPECTED_VARIANTS above (a future MSVC/llama.cpp adding
+ # e.g. a "zen4" or "sapphirerapids" MSVC variant would fall into neither
+ # list and get treated, wrongly, as a must-be-protected baseline module).
+ # Derived from EXPECTED_VARIANTS instead, so there is exactly one place
+ # that names the CPU-tier ladder.
+ windows_high_tier_variants() {
+ local v
+ for v in "${EXPECTED_VARIANTS[@]}"; do
+ case "$v" in
+ x64 | sse42) continue ;;
+ *) printf '%s\n' "$v" ;;
+ esac
+ done
+ }
+
+ # N4 (review-waechter-windows.md): every non-CPU-tier-variant module this
+ # pinned llama.cpp checkout is known to produce for
+ # x86_64-pc-windows-msvc, read off the real box build
+ # (lu-301/bau/waechter-windows.md's beweis run). This is deliberately NOT
+ # "whatever the glob happens to find today": the module-count check below
+ # fails RED, with a message asking a human to classify it, both when a
+ # module in this list goes missing and when the companions directory
+ # contains a Windows .dll that is neither in this list nor one of the
+ # excluded high-CPU-tier variants — an unclassified module could just as
+ # easily be a brand-new unconditional-AVX CPU tier (which MUST be
+ # excluded) as an ordinary new base module (which MUST be
+ # dominance-checked), and guessing either way defeats the point of this
+ # guard.
+ EXPECTED_BASE_WINDOWS_MODULES=(
+ ggml.dll ggml-base.dll ggml-cpu-sse42.dll ggml-cpu-x64.dll ggml-vulkan.dll
+ llama.dll llama-common.dll llama-server-impl.dll mtmd.dll
+ )
+
list_windows_modules_to_check() {
- local f base
+ local f base excluded v
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
+ excluded=""
+ while IFS= read -r v; do
+ [ -n "$v" ] || continue
+ if [ "$base" = "ggml-cpu-${v}.dll" ]; then
+ excluded=1
+ break
+ fi
+ done < <(windows_high_tier_variants)
+ [ -n "$excluded" ] && continue
printf '%s\n' "$f"
done
}
@@ -358,13 +421,21 @@ if [[ "$TRIPLE" == *-windows-* ]]; then
# 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}"
+ # N3 (review-waechter-windows.md): this used to fall back to
+ # llama-server.map for ANY stem whose own exact map was missing, not just
+ # for the exe. That is not a harmless convenience: a module checked
+ # against the WRONG map either resolves every hit to garbage
+ # `fn=$R000000 obj=*` names (still red, but for an unrelated, confusing
+ # reason) or, worse, a module with genuinely NO VEX/EVEX hits of its own
+ # can pass vacuously against a map that was never its own. There is no
+ # legitimate case left for a fallback: the exe's own call site below
+ # already asks for stem "llama-server" directly, which this exact-match
+ # lookup already serves without any special-casing. A missing map for any
+ # module, exe included, must be a hard failure naming that exact module,
+ # not a silent substitution.
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"
+ local stem="$1"
+ find "$WIN_BUILD_DIR" -type f -iname "${stem}.map" -print -quit 2>/dev/null
}
NODE_BIN="$(command -v node || true)"
@@ -373,6 +444,34 @@ if [[ "$TRIPLE" == *-windows-* ]]; then
WIN_GUARD="$SCRIPT_DIR/win-isa-guard.mjs"
[ -f "$WIN_GUARD" ] || vdie "$WIN_GUARD missing"
+ # N4: gather the set of base modules this run is ABOUT to check before
+ # running a single dumpbin invocation, so a drift between what is on disk
+ # and EXPECTED_BASE_WINDOWS_MODULES is reported as one clear message
+ # instead of an empty pass or a confusing per-file failure.
+ checked_base_modules=()
+ while IFS= read -r f; do
+ [ -n "$f" ] || continue
+ checked_base_modules+=("$(basename "$f")")
+ done < <(list_windows_modules_to_check)
+
+ for base in "${checked_base_modules[@]}"; do
+ known=""
+ for expected in "${EXPECTED_BASE_WINDOWS_MODULES[@]}"; do
+ if [ "$base" = "$expected" ]; then known=1; break; fi
+ done
+ [ -n "$known" ] || vdie "unexpected Windows module '$base' found in $COMPANIONS_DIR: it is neither a known base module (EXPECTED_BASE_WINDOWS_MODULES in verify-sidecar-isa.sh) nor one of the excluded high-CPU-tier variants (EXPECTED_VARIANTS minus x64/sse42, see windows_high_tier_variants). Classify it before this guard can trust it: add it to EXPECTED_BASE_WINDOWS_MODULES if it is a new base module that must be dominance-checked like the rest of own code, or to EXPECTED_VARIANTS if it is a new higher CPU tier that is allowed unconditional AVX by design"
+ done
+ for expected in "${EXPECTED_BASE_WINDOWS_MODULES[@]}"; do
+ found=""
+ for base in "${checked_base_modules[@]}"; do
+ if [ "$base" = "$expected" ]; then found=1; break; fi
+ done
+ [ -n "$found" ] || vdie "expected base Windows module '$expected' (EXPECTED_BASE_WINDOWS_MODULES) not found in $COMPANIONS_DIR, or it was wrongly excluded as a high-CPU-tier variant; build first, or fix windows_high_tier_variants/EXPECTED_VARIANTS if it now overlaps"
+ done
+ [ "${#checked_base_modules[@]}" -eq "${#EXPECTED_BASE_WINDOWS_MODULES[@]}" ] \
+ || vdie "checked ${#checked_base_modules[@]} Windows module(s) but expected exactly ${#EXPECTED_BASE_WINDOWS_MODULES[@]} (${EXPECTED_BASE_WINDOWS_MODULES[*]}); list_windows_modules_to_check's glob may have run empty or duplicated a name, which would otherwise pass this guard vacuously green"
+ vlog "module coverage: ${#checked_base_modules[@]} base module(s) match EXPECTED_BASE_WINDOWS_MODULES exactly"
+
win_fail_count=0
while IFS= read -r f; do
[ -n "$f" ] || continue
@@ -380,7 +479,7 @@ if [[ "$TRIPLE" == *-windows-* ]]; then
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"
+ 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"
@@ -391,7 +490,9 @@ if [[ "$TRIPLE" == *-windows-* ]]; then
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).
+ # basename, hence the explicit stem "llama-server" below; N3 removed the
+ # fallback this comment used to point at, find_map_for is exact-match only
+ # now).
exe_name="$(out_name_for "$TRIPLE")"
exe_path="$BIN_DIR/$exe_name"
if [ -f "$exe_path" ]; then
@@ -415,6 +516,14 @@ if [[ "$TRIPLE" == *-windows-* ]]; then
# 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.
+ #
+ # This control already satisfies B2's "exact code, not just any nonzero"
+ # principle by construction: `grep -qE` only ever exits 0 (a real match)
+ # or nonzero (no match, or a grep error), there is no third "crashed for
+ # an unrelated reason but still looks like the expected failure" case the
+ # way a node subprocess has, so a plain `if ! grep ...; then vdie; fi` is
+ # already as strict as B2 asks the negative and red-probe controls below
+ # to become explicitly.
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")"
@@ -430,16 +539,36 @@ if [[ "$TRIPLE" == *-windows-* ]]; then
# 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.
+ #
+ # B2 (review-waechter-windows.md): "any nonzero exit means the rule caught
+ # something" and "exit 0 means correctly caught" both silently accept
+ # OTHER failure modes for the wrong reason: a crash from a missing/renamed
+ # fixture, a bad CLI argument, or a future win-isa-guard.mjs change can
+ # exit 1 too (an uncaught readFileSync throw is exit code 1, same as a
+ # deliberate "FAIL (negative control)"), and would be reported here as
+ # "the rule went soft" while never having run the decision logic at all.
+ # Require the EXACT expected exit code (0 for this control: found at least
+ # one UNPROTECTED hit) AND the exact expected message in stdout, the same
+ # principle the red-probe check below already needs.
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
+ neg_out_tmp="$(mktemp)"
+ neg_err_tmp="$(mktemp)"
+ neg_status=0
+ "$NODE_BIN" "$WIN_GUARD" check --module ggml-cpu-haswell.dll --disasm "$haswell_disasm_tmp" --map "$haswell_map" --expect-unprotected \
+ >"$neg_out_tmp" 2>"$neg_err_tmp" || neg_status=$?
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)"
+ if [ "$neg_status" -eq 0 ] && grep -q 'OK (negative control):' "$neg_out_tmp"; then
+ vlog "negative control: ggml-cpu-haswell.dll correctly shows at least one UNPROTECTED own-code hit (the rule still catches something)"
+ else
+ vdie "negative control did NOT pass cleanly (exit=$neg_status, expected exit=0 with 'OK (negative control):' in stdout); this is either the allowlist/dominance rule having gone soft (review-k1-avx.md R4) or the check crashing for an unrelated reason (missing map, bad args, a win-isa-guard.mjs regression) — both must be treated as red rather than guessed apart. stdout:
+$(cat "$neg_out_tmp")
+stderr:
+$(cat "$neg_err_tmp")"
+ fi
+ rm -f "$neg_out_tmp" "$neg_err_tmp"
# R4, control 3/3 (the artificial red probe): a checked-in fixture pair
# (scripts/__fixtures__/win-isa/unprotected-own-code.*) that is an
@@ -449,14 +578,37 @@ if [[ "$TRIPLE" == *-windows-* ]]; then
# 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).
+ #
+ # BLOCKER B2 (review-waechter-windows.md): the old check accepted ANY
+ # nonzero exit code as "correctly came out RED", including exit 2 (bad
+ # CLI usage) or a crash from a missing/moved fixture file (an uncaught
+ # readFileSync throw exits 1, same code as a deliberate FAIL) — exactly
+ # the class of bug that let the entry-point regression this project
+ # already hit once (lu-301/bau/waechter-windows.md) go unnoticed. Require
+ # the EXACT expected exit code (1) AND grep stdout for the exact expected
+ # verdict text, the same way win-isa-guard.test.mjs's own spawnSync
+ # regression test already does.
RED_PROBE_DIR="$SCRIPT_DIR/__fixtures__/win-isa"
- if ! "$NODE_BIN" "$WIN_GUARD" check --module "red-probe" \
+ red_out_tmp="$(mktemp)"
+ red_err_tmp="$(mktemp)"
+ red_status=0
+ # --min-lines 0: this fixture is deliberately a handful of lines (it tests
+ # the decision LOGIC, not a real disassembly), so N2's parse-count guard
+ # (which exists to catch a real module silently failing to disassemble at
+ # all) must not fire on it for an unrelated reason.
+ "$NODE_BIN" "$WIN_GUARD" check --module "red-probe" --min-lines 0 \
--disasm "$RED_PROBE_DIR/unprotected-own-code.disasm.txt" \
- --map "$RED_PROBE_DIR/unprotected-own-code.map.txt"; then
+ --map "$RED_PROBE_DIR/unprotected-own-code.map.txt" \
+ >"$red_out_tmp" 2>"$red_err_tmp" || red_status=$?
+ if [ "$red_status" -eq 1 ] && grep -q 'UNPROTECTED' "$red_out_tmp"; 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"
+ vdie "red probe FAILED TO GO RED as expected (exit=$red_status, expected exit=1 with 'UNPROTECTED' in stdout): scripts/__fixtures__/win-isa/unprotected-own-code.* (an own-code VEX hit with no preceding isa check at all) either was accepted by the decision logic, or the check crashed for an unrelated reason (missing fixture, bad args) instead of actually running it — both are red. stdout:
+$(cat "$red_out_tmp")
+stderr:
+$(cat "$red_err_tmp")"
fi
+ rm -f "$red_out_tmp" "$red_err_tmp"
# Toolset pin, checked once against the exe (present after a real build).
if [ -f "$exe_path" ]; then
diff --git a/scripts/win-isa-guard.mjs b/scripts/win-isa-guard.mjs
index 4b28c5b5..1249735e 100644
--- a/scripts/win-isa-guard.mjs
+++ b/scripts/win-isa-guard.mjs
@@ -58,6 +58,31 @@
// 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.
+//
+// SCOPE, STATED HONESTLY (review-waechter-windows.md N6): this guard proves
+// "no unprotected VEX/EVEX instruction", i.e. AVX-and-above. It does NOT
+// prove "runs on every x86-64 CPU". A legacy-encoded instruction above the
+// x86-64 baseline (POPCNT, LZCNT, TZCNT, the SSE4.2 string/CRC32 ops) is not
+// VEX/EVEX-coded and would pass through unnoticed even if compiled in
+// unconditionally, and would fault with the identical 0xC000001D on the same
+// customer machine. For K1 as reported this residual gap is accepted, not
+// closed:
+// - BMI1/BMI2 (ANDN, BEXTR, BZHI, PDEP, PEXT, ...) do NOT need separate
+// handling: they are VEX-encoded instructions (VEX.LZ.0F38, per the
+// Intel SDM), so the existing 0xC4/0xC5/0x62 first-byte check already
+// covers them.
+// - POPCNT/LZCNT/TZCNT were checked for cheap opcode-byte coverage and
+// rejected: their real encoding is a mandatory 0xF3 prefix followed by a
+// 0F-map opcode (F3 0F B8 for POPCNT, F3 0F BD for LZCNT, F3 0F BC for
+// TZCNT). Unlike 0xC4/0xC5/0x62, a leading 0xF3 byte is NOT unambiguous
+// in 64-bit code: it is the ordinary REP/REPE prefix and the mandatory
+// prefix for a large family of unrelated scalar SSE instructions
+// (MOVSS, CVTSI2SS, ADDSS, ...), so a first-byte-only rule would flag
+// huge numbers of ordinary SSE instructions as false positives, and a
+// rule that also inspects the trailing 0F B8/BD/BC bytes stops being a
+// one-byte structural check and starts being exactly the kind of
+// multi-byte, easy-to-get-subtly-wrong decoder this rewrite was meant to
+// avoid. Not implemented; flagged here rather than silently dropped.
import { readFileSync, realpathSync } from 'node:fs';
import { fileURLToPath } from 'node:url';
@@ -183,11 +208,53 @@ export function findIsaSymbolVAs(symbols) {
// 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.
+//
+// review-waechter-windows.md BL3: the wmemcmp/memcmp part of this allowlist
+// used to be a bare case-insensitive \b...\b REGEX against the owning
+// symbol's NAME ALONE, with no condition on the owning OBJECT at all. That is
+// both too loose (a substring match: a C++ namespace or class literally
+// called "memcmp" anywhere in a mangled name, e.g.
+// "?fast@memcmp@ggml@@YAXXZ" in an ENTIRELY UNRELATED, unguarded own-code
+// object such as ggml-cpu.obj, matched and was waved through as ALLOWED_CRT)
+// and not what R3.1 as reviewed actually verified: in the real Windows build
+// wmemcmp's CRT COMDAT gets attributed by the linker to whichever OWN object
+// first references it (that is *why* it shows up in "own" objects at all,
+// not because this project wrote it), and the objects that happened to do so
+// were hand-checked one by one, not "any object with this name in it
+// somewhere". So the rule now requires BOTH an EXACT (not substring, not
+// regex) match on the symbol name AND that the owning object is one of the
+// specific objects that match was verified against
+// (WMEMCMP_MEMCMP_HOST_OBJECTS below). A symbol named exactly "memcmp"
+// sitting in some other object is not covered by that verification and must
+// fall through to the ordinary own-code dominance check like everything
+// else.
+const WMEMCMP_MEMCMP_HOST_OBJECTS = new Set([
+ 'common.obj',
+ 'unicode.obj',
+ 'ggml-backend-reg.obj',
+ 'server-context.obj',
+]);
+
+// A .map Lib:Object field can carry a "Lib:Object" form (e.g.
+// "msvcprt:vector_algorithms.obj") or a bare "Object" form (the common case
+// for this project's own objects, e.g. "common.obj"). Only the part after
+// the last colon is ever a plain filename; strip a library prefix if present
+// so the allowlist compares against the same shape in either case.
+function objectBaseName(obj) {
+ const idx = obj.lastIndexOf(':');
+ return idx === -1 ? obj : obj.slice(idx + 1);
+}
+
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;
+ if (
+ (owner.name === 'wmemcmp' || owner.name === 'memcmp') &&
+ WMEMCMP_MEMCMP_HOST_OBJECTS.has(objectBaseName(owner.obj))
+ ) {
+ return true;
+ }
return false;
}
@@ -195,43 +262,118 @@ 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.
+// A genuine isa-flag READ dereferences the address in memory (dumpbin prints
+// that as "... [<hex>h]", the bracket is the actual load); a line that merely
+// mentions the same hex digits as an immediate constant (e.g. "mov
+// rax,0000000180099898h", no brackets — Opus's fake-green pattern F in
+// review-waechter-windows.md N1) never touches the flag's value at all and
+// must not count.
+function isaBracketMatch(text, isaHexes) {
+ for (const hex of isaHexes) {
+ const re = new RegExp(`\\[\\s*0*${hex}h?\\s*\\]`, 'i');
+ if (re.test(text)) return true;
+ }
+ return false;
+}
+
+// If this line LOADS the isa flag into a register ("mov ecx,dword ptr
+// [<isa>h]" / "movzx eax,byte ptr [<isa>h]"), return that register's name so
+// the next step can require the guarding compare to use the SAME register,
+// not an unrelated one. Returns null for a line that reads the flag directly
+// into a comparison (e.g. "cmp dword ptr [<isa>h],5"): there is no
+// intermediate register to track there.
+function movLoadDestRegister(text) {
+ const m = /^\s*mov(?:zx)?\s+(\w+)\s*,\s*(?:byte|word|dword|qword)\s+ptr/i.exec(text);
+ return m ? m[1].toLowerCase() : null;
+}
+
+function isCompareMnemonic(mnemonic) {
+ return mnemonic === 'cmp' || mnemonic === 'test';
+}
+
+// True when `text`'s FIRST operand is exactly `reg` (word-bounded, so "cl"
+// does not accidentally match inside "rcl" and "eax" does not match "reax").
+function firstOperandIsRegister(text, reg) {
+ const re = new RegExp(`^\\s*\\S+\\s+${reg}\\b`, 'i');
+ return re.test(text);
+}
+
+// R3.2: the dominance approximation for "own code". review-waechter-windows.md
+// N1: the original version only checked "an isa-flag read happened somewhere
+// before the hit" and "SOME conditional jump between that read and the hit
+// lands past it", with no requirement that the jump actually evaluate the
+// flag it read. Two fake-green shapes exploited exactly that gap:
+// A) an isa-flag read (left over from an earlier, unrelated loop),
+// followed by an unrelated null-pointer test whose jump also happens to
+// land past the hit, followed by an unconditional AVX block;
+// F) the isa flag's ADDRESS used only as a bare immediate constant (never
+// dereferenced), with an unrelated jump and then the hit.
+// Closed by requiring the conditional jump to sit IMMEDIATELY after a
+// cmp/test instruction (no other instruction between them) that is itself
+// bound to the isa-flag read: either the read line directly compares the
+// flag's memory location (no intermediate register), or the read loads the
+// flag into a register and that SAME register is the compare's first
+// operand. Verified against the real Fundstelle 2a shape (mov ecx,dword ptr
+// [isa] / cmp ecx,5 / jl) in the fixtures and the unit tests below; the two
+// fake-green shapes are checked-in fixtures that must come out UNPROTECTED
+// (scripts/__fixtures__/win-isa/fake-*-own-code.*).
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;
+
+ // Collect every REAL (bracket-dereferenced) isa-flag read before the hit,
+ // in order; try each as a candidate, closest-to-the-hit first, since that
+ // is the one most likely to actually guard this specific hit.
+ const reads = [];
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 (isaBracketMatch(line.text, isaHexes)) reads.push(line);
}
- if (!checkLine) {
+ if (reads.length === 0) {
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());
+
+ for (let i = reads.length - 1; i >= 0; i -= 1) {
+ const readLine = reads[i];
+ const readIdx = linesSortedByAddr.indexOf(readLine);
+ const destReg = movLoadDestRegister(readLine.text);
+
+ let compareLine = null;
+ if (destReg === null && isCompareMnemonic(readLine.mnemonic)) {
+ // The read line itself is the compare (e.g. "cmp dword ptr [isa],5").
+ compareLine = readLine;
+ } else if (destReg !== null) {
+ // Find the first cmp/test AFTER the load, before the hit, whose first
+ // operand is the register the load just wrote.
+ for (let j = readIdx + 1; j < linesSortedByAddr.length; j += 1) {
+ const cand = linesSortedByAddr[j];
+ if (cand.addr >= hitAddr) break;
+ if (isCompareMnemonic(cand.mnemonic) && firstOperandIsRegister(cand.text, destReg)) {
+ compareLine = cand;
+ break;
+ }
+ }
+ }
+ if (!compareLine) continue;
+
+ const compareIdx = linesSortedByAddr.indexOf(compareLine);
+ const jumpLine = linesSortedByAddr[compareIdx + 1];
+ if (!jumpLine || jumpLine.addr >= hitAddr) continue;
+ if (!/^j/.test(jumpLine.mnemonic) || jumpLine.mnemonic === 'jmp') continue;
+ const m = /([0-9A-Fa-f]{6,16})h?\s*$/.exec(jumpLine.text.trim());
if (!m) continue;
const target = parseInt(m[1], 16);
if (target > hitAddr && target <= functionEnd) {
- return { protected: true, checkLine, jumpLine: line };
+ return { protected: true, checkLine: readLine, compareLine, jumpLine };
}
}
+
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`,
+ reason: `an isa-flag read exists before the hit, but no conditional jump immediately following a cmp/test bound to that same read lands past the hit inside the function (review-waechter-windows.md N1)`,
};
}
@@ -268,6 +410,7 @@ export function evaluateModule({ moduleName, disasmText, mapText }) {
return {
moduleName,
+ lineCount: lines.length,
symbolCount: symbols.length,
hitCount: hits.length,
ownedHitCount: ownedHits,
@@ -288,7 +431,7 @@ function formatVerdict(v) {
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.stderr.write('usage: win-isa-guard.mjs check --module <name> --disasm <file> --map <file> [--expect-unprotected] [--min-symbols N] [--min-lines N]\n');
process.exit(2);
}
const args = {};
@@ -314,11 +457,29 @@ function main(argv) {
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`);
+ // N2 (review-waechter-windows.md): a disasm dump the parser cannot make
+ // sense of at all (wrong dumpbin flags, an encoding surprise, a future
+ // dumpbin/objdump output-format change, a parser regression) yields ZERO
+ // parsed instruction lines and therefore zero VEX/EVEX hits, which the
+ // pre-existing checks read as "OK, no unprotected VEX/EVEX in own code" —
+ // a clean pass for exactly the wrong reason. A real module's dumpbin
+ // /disasm dump is thousands of lines at minimum (the smallest real module
+ // measured on the box, the exe itself, still produced far more than this);
+ // 40 is deliberately far below any real module and only meant to catch
+ // "the parser understood nothing", not to be a tight bound. Fixtures for
+ // the decision logic itself (crt-allowed, protected-own-code, the red
+ // probe) are deliberately tiny and pass --min-lines 0 explicitly, see
+ // verify-sidecar-isa.sh.
+ const minLines = args['min-lines'] !== undefined ? parseInt(args['min-lines'], 10) : 40;
+ process.stdout.write(`[win-isa-guard] ${result.moduleName}: ${result.lineCount} disasm line(s) parsed, ${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.lineCount < minLines) {
+ process.stderr.write(`[win-isa-guard] FAIL: ${result.moduleName}: only ${result.lineCount} disassembled instruction line(s) were parsed out of the dumpbin/objdump output (need >= ${minLines}); this almost always means the parser did not recognise the disassembler's output format at all (wrong flags, an encoding surprise, a tool/output-format change) rather than a genuinely tiny binary, and a hitCount of 0 from a parser this broken is not proof of anything (review-waechter-windows.md N2)\n`);
+ process.exit(1);
+ }
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);
diff --git a/scripts/win-isa-guard.test.mjs b/scripts/win-isa-guard.test.mjs
index 80c42f6f..f2c601ec 100644
--- a/scripts/win-isa-guard.test.mjs
+++ b/scripts/win-isa-guard.test.mjs
@@ -4,7 +4,7 @@
// 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 { readFileSync, writeFileSync, rmSync } from 'node:fs';
import { fileURLToPath } from 'node:url';
import { dirname, join } from 'node:path';
import { spawnSync } from 'node:child_process';
@@ -81,13 +81,34 @@ test('findOwner: largest symbol address <= target, function end is the next symb
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', () => {
+test('isAllowlisted: msvcprt:vector_algorithms.obj, MSVCRT:*, and wmemcmp/memcmp bound to a known host object 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: 'common.obj', name: 'wmemcmp' }), true);
+ assert.equal(isAllowlisted({ obj: 'unicode.obj', name: 'memcmp' }), true);
+ assert.equal(isAllowlisted({ obj: 'ggml-backend-reg.obj', name: 'wmemcmp' }), true);
+ assert.equal(isAllowlisted({ obj: 'server-context.obj', name: 'wmemcmp' }), true);
assert.equal(isAllowlisted({ obj: 'ggml-quants.obj', name: 'iq2xs_init_impl$omp$1' }), false);
});
+test('BL3 (review-waechter-windows.md): a mangled name containing "memcmp" as a mere substring is NOT allowlisted', () => {
+ // Opus's counter-example: a C++ namespace/function literally called
+ // "memcmp" inside an unrelated, unguarded own-code object. The old
+ // \bmemcmp\b regex matched this via the word boundaries around "@memcmp@"
+ // and waved it through as ALLOWED_CRT even though ggml-cpu.obj was never
+ // reviewed and never carries a self-guarding CRT dispatch.
+ assert.equal(isAllowlisted({ obj: 'ggml-cpu.obj', name: '?fast@memcmp@ggml@@YAXXZ' }), false);
+});
+
+test('BL3: exact name "memcmp"/"wmemcmp" in an object OUTSIDE the reviewed host list is NOT allowlisted', () => {
+ // Even an EXACT name match must still be bound to one of the specific
+ // objects review-k1-avx.md actually verified; a symbol named exactly
+ // "memcmp" turning up in some other object was never checked and must
+ // fall through to the ordinary dominance check like any other own code.
+ assert.equal(isAllowlisted({ obj: 'ggml-cpu.obj', name: 'memcmp' }), false);
+ assert.equal(isAllowlisted({ obj: 'ggml-cpu.obj', name: 'wmemcmp' }), 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]',
@@ -109,6 +130,62 @@ test('checkDominance: an isa read with no bounding jump is NOT protected', () =>
assert.equal(dom.protected, false);
});
+test('N1 (review-waechter-windows.md): an isa read followed by an UNRELATED conditional jump that happens to land past the hit is NOT protected', () => {
+ // Fake-green pattern A: the isa read is real, but the jump that reaches
+ // past the hit comes from a completely different comparison (here, on a
+ // different register) that never looked at the isa flag.
+ const lines = parseDisasmLines([
+ ' 0000000180060000: 8B 0D BC 19 07 00 mov ecx,dword ptr [0000000180099898h]',
+ ' 0000000180060010: 48 85 C0 test rax,rax',
+ ' 0000000180060014: 74 1A je 0000000180060030',
+ ' 0000000180060020: C5 F9 6E D8 vmovd xmm3,eax',
+ ].join('\n'));
+ const dom = checkDominance(lines, [0x180099898], 0x180060000, 0x180060100, 0x180060020);
+ assert.equal(dom.protected, false);
+});
+
+test('N1: the isa ADDRESS used only as a bare immediate (never dereferenced) does not count as a read', () => {
+ // Fake-green pattern F: the isa flag's address appears in the instruction
+ // text, but only as a constant loaded into a register, never dereferenced,
+ // so the flag's actual value is never inspected.
+ const lines = parseDisasmLines([
+ ' 0000000180070000: 48 B8 98 98 09 80 01 00 00 00 mov rax,0000000180099898h',
+ ' 0000000180070010: 48 85 C0 test rax,rax',
+ ' 0000000180070014: 74 1A je 0000000180070030',
+ ' 0000000180070020: C5 F9 6E D8 vmovd xmm3,eax',
+ ].join('\n'));
+ const dom = checkDominance(lines, [0x180099898], 0x180070000, 0x180070100, 0x180070020);
+ assert.equal(dom.protected, false);
+});
+
+test('N1: the conditional jump must immediately follow the bound cmp/test, not merely appear somewhere after it', () => {
+ const lines = parseDisasmLines([
+ ' 0000000180027ED6: 8B 0D BC 19 07 00 mov ecx,dword ptr [0000000180099898h]',
+ ' 0000000180027F7E: 83 F9 05 cmp ecx,5',
+ ' 0000000180027F80: 48 85 C0 test rax,rax',
+ ' 0000000180027F81: 7C 40 jl 0000000180027FC3',
+ ' 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, 'an unrelated instruction between the cmp and the jump breaks the "immediately follows" requirement');
+});
+
+test('fixture: fake-unrelated-jump-own-code (Opus pattern A) MUST come out UNPROTECTED', () => {
+ const { disasmText, mapText } = loadFixture('fake-unrelated-jump-own-code');
+ const result = evaluateModule({ moduleName: 'fake-unrelated-jump-own-code', disasmText, mapText });
+ assert.equal(result.hitCount, 1);
+ assert.equal(result.unprotected.length, 1);
+ assert.equal(result.verdicts[0].verdict, 'UNPROTECTED');
+});
+
+test('fixture: fake-address-as-constant-own-code (Opus pattern F) MUST come out UNPROTECTED', () => {
+ const { disasmText, mapText } = loadFixture('fake-address-as-constant-own-code');
+ const result = evaluateModule({ moduleName: 'fake-address-as-constant-own-code', disasmText, mapText });
+ assert.equal(result.hitCount, 1);
+ assert.equal(result.unprotected.length, 1);
+ assert.equal(result.verdicts[0].verdict, 'UNPROTECTED');
+});
+
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',
@@ -158,6 +235,12 @@ test('CLI: the script actually runs main() as a real subprocess and exits 1 on t
script,
'check',
'--module', 'red-probe',
+ // The fixture is deliberately a handful of lines (N2's own parse-count
+ // guard would otherwise trip on it too, for an unrelated reason); this
+ // test is specifically about the entry-point/exit-code regression, not
+ // about N2, so disable that guard explicitly rather than relying on it
+ // happening to fail for the right reason anyway.
+ '--min-lines', '0',
'--disasm', join(FIXTURES, 'unprotected-own-code.disasm.txt'),
'--map', join(FIXTURES, 'unprotected-own-code.map.txt'),
], { encoding: 'utf8' });
@@ -165,6 +248,45 @@ test('CLI: the script actually runs main() as a real subprocess and exits 1 on t
assert.match(result.stdout, /UNPROTECTED/);
});
+test('N2 (review-waechter-windows.md): evaluateModule reports lineCount so the CLI can fail closed on an unparsed disasm dump', () => {
+ const disasmText = [
+ ' 0000000180000000: C5 F9 6E D8 vmovd xmm3,eax',
+ ' 0000000180000010: 48 89 5C 24 08 mov qword ptr [rsp+8],rbx',
+ ].join('\n');
+ const result = evaluateModule({ moduleName: 'tiny', disasmText, mapText: '' });
+ assert.equal(result.lineCount, 2);
+});
+
+test('N2: the CLI FAILS a disasm dump with too few parsed lines by default, even with zero hits', () => {
+ const script = join(HERE, 'win-isa-guard.mjs');
+ const emptyDisasm = join(HERE, '__fixtures__', 'win-isa', '.tmp-empty.disasm.txt');
+ const emptyMap = join(HERE, '__fixtures__', 'win-isa', '.tmp-empty.map.txt');
+ writeFileSync(emptyDisasm, 'Dump of file: nothing the parser recognises, no address-anchored lines at all.\n');
+ writeFileSync(emptyMap, ' Static symbols\n\n 0001:00000000 x 0000000180000000 f a.obj\n');
+ try {
+ const result = spawnSync(process.execPath, [
+ script, 'check', '--module', 'unparsed', '--disasm', emptyDisasm, '--map', emptyMap,
+ ], { encoding: 'utf8' });
+ assert.equal(result.status, 1, `expected exit 1 (too few parsed lines), got ${result.status}. stdout:\n${result.stdout}`);
+ assert.match(result.stderr, /only 0 disassembled instruction line\(s\)/);
+ } finally {
+ rmSync(emptyDisasm, { force: true });
+ rmSync(emptyMap, { force: true });
+ }
+});
+
+test('N2: --min-lines 0 lets a deliberately tiny fixture (the red probe) skip the parse-count check', () => {
+ const script = join(HERE, 'win-isa-guard.mjs');
+ const result = spawnSync(process.execPath, [
+ script, 'check', '--module', 'red-probe', '--min-lines', '0',
+ '--disasm', join(FIXTURES, 'unprotected-own-code.disasm.txt'),
+ '--map', join(FIXTURES, 'unprotected-own-code.map.txt'),
+ ], { encoding: 'utf8' });
+ assert.equal(result.status, 1, 'still fails, but for the real reason (UNPROTECTED), not the line-count guard');
+ assert.match(result.stdout, /UNPROTECTED/);
+ assert.doesNotMatch(result.stderr, /disassembled instruction line/);
+});
+
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: '' });