okami.mom/strata

git clone https://git.nkp.pet/okami.mom/strata

Niko1221Merge f-0216-cpu into f-0216-allf2eedfe9f

main
11.9 KiB225 linesraw
1#!/usr/bin/env python3
2"""Check that no code reachable on an AVX2-only CPU can contain wider-ISA instructions (#795).
3
4Strata compiles a few translation units for AVX-512 (expert.cpp, iq_avx512.cpp) and some for AVX2 + AVX-VNNI
5(q2_avx2.cpp, iq_avx2.cpp); the engine picks them at run time.  Two things go wrong when that is done carelessly,
6and both end in an illegal instruction on the CPU that lacks the feature:
7
8  * a function that every CPU runs (a probe, a "supported?" helper, a startup flag) sits in a wide-ISA file, so the
9    compiler may use the wide ISA in it;
10  * an inline function or template instantiation (std::, a shared header) compiled in a wide-ISA file is emitted as a
11    COMDAT / weak symbol, and the linker keeps THAT copy for every caller in the program.
12
13The check disassembles a linked binary, finds every function that holds an AVX-512 (EVEX) or AVX-VNNI / VAES /
14GFNI / SHA instruction, and fails unless the function is one of the kernels meant to be reached only behind a CPU
15check: internal linkage (anonymous namespace) or a named public kernel entry point below, defined in a wide-ISA
16object file, and not a weak / COMDAT symbol.  MSVC's own auto-vectorizer guard (`cmp [__isa_available], 6`) is accepted.
17
18  Linux : check_isa_guard.py libstrata_kernels_cpu.a  (needs objdump and nm from binutils)
19  Windows: check_isa_guard.py EXE --map EXE.map      (link with /MAP; needs `pip install capstone pefile`)
20
21Exit 0 = clean, 1 = a violation, 77 = cannot run here (tools missing; ctest SKIP_RETURN_CODE).
22"""
23import argparse
24import bisect
25import re
26import shutil
27import subprocess
28import sys
29
30# Public functions of the wide-ISA files that are wide on purpose: every caller tests the CPU first
31# (cpu_avx512_ok / cpu_avxvnni_ok), or reaches them only after cpu_require_expert_support().
32WIDE_PUBLIC = {
33    "nvfp4_512_gu_rows", "nvfp4_512_rows",   # NVFP4 (native_expert.cpp: both behind cpu_avx512_ok())
34    "act_quant_q8_1", "q2_0_gguf_rows_multi", "s2_expert_vnni", "s2_expert_vnni_q", "s2_expert_gu_rows",
35    "s2_expert_down_rows", "s2_expert_gu_rows_multi", "s2_expert_down_rows_multi", "s2_expert_vnni_multi",
36    "s2_expert_scalar", "iq512_gu_rows", "iq512_rows", "iq256_gu_rows", "iq256_rows", "iq256_gu_rows_v",
37    "iq256_rows_v", "iq4nl256_down_rows", "iq4nl256_down_rows_v", "q2_0_gguf_rows_multi_avx2",
38    "q2_0_gguf_rows_multi_avx2_v", "q2_0_gguf_rows_multi_avx2_legacy", "q2_0_gguf_rows_multi_avx2_bitplane",
39    "act_quant_q8_1_avx2", "q8k_quant_avx2", "kq256_gu_rows", "kq256_rows", "bf16_rows_dot_multi",
40    "tq_rows_avx512", "q50_512_down_rows", "iq512_fused_gu_rows", "iq512_reference_gu_rows", "iq512x_rows",                        # trellis rows (tq_cpu.cpp: behind cpu_avx512_ok())
41}
42WIDE_OBJECTS = ("expert.cpp", "iq_avx512.cpp", "iq_avx2.cpp", "q2_avx2.cpp", "kq_avx2.cpp", "nvfp4_avx512.cpp", "tq_avx512.cpp")
43# Also compiled above the baseline (AVX2/FMA for nvfp4_avx2, AVX for the older CPUs' rows) and reached only behind a CPU
44# check.  STATIC INITIALISERS in any of these run on EVERY CPU at program start (#2324: nvfp4_avx2.cpp / nvfp4_avx512.cpp
45# built a table in a constructor, the compiler used AVX/FMA for it, and a Westmere / Sandy Bridge Xeon died with an
46# illegal instruction before main, with nothing in the log).  The initialisers must not exist: constexpr tables, or
47# function-local statics read behind the CPU check.
48INIT_FREE_OBJECTS = WIDE_OBJECTS + ("nvfp4_avx2.cpp", "kq_avx1.cpp", "q2_avx1.cpp", "iq_avx1.cpp")
49
50# An instruction is "wide" if it is EVEX encoded (first byte 0x62 in 64-bit mode), or one of these VEX / legacy
51# extensions that an AVX2 CPU may lack.  AVX-VNNI is VEX encoded (vpdpbusd, vpdpwssd ...).
52WIDE_MNEMONIC = re.compile(r"^(vpdp|vgf2p8|vaes|vpclmul|sha(1|256)|vp2intersect|vpmadd52|vcvtne|vbcstnebf16|vsha512|vsm[34]|tdp|ldtilecfg)")
53WIDE_OPERAND = re.compile(r"\bzmm|\bk[0-7]\b|[xy]mm(1[6-9]|2\d|3[01])\b|\{k[0-7]\}")
54
55
56def is_wide(raw0, mnemonic, ops):
57    return raw0 == 0x62 or WIDE_MNEMONIC.match(mnemonic) is not None or WIDE_OPERAND.search(ops) is not None
58
59
60def judge(name, obj, wide_text, guarded, weak, is_elf):
61    """Returns None if this wide function is allowed, else the reason."""
62    if guarded:
63        return None
64    if name.startswith("?"):                            # MSVC decorated: ?name@scope@...
65        base = re.match(r"\?+(?:\$)?([^@$?]+)", name).group(1) if re.match(r"\?+(?:\$)?([^@$?]+)", name) else name
66    else:                                               # demangled ELF names carry the argument list
67        base = re.sub(r"\(.*$", "", name)
68        base = re.sub(r"<.*$", "", base).split("::")[-1]
69    anon = ("(anonymous namespace)" in name) or ("?A0x" in name)
70    if weak:
71        return "weak / COMDAT symbol: the linker may pick this wide copy for every caller (ODR)"
72    if obj is not None and not any(obj.endswith(o + ".obj") or obj.endswith(o + ".o") or o in obj for o in WIDE_OBJECTS):
73        return "wide-ISA code outside the wide-ISA translation units (object %s)" % obj
74    if anon or base in WIDE_PUBLIC:
75        return None
76    return "wide-ISA code in an unlisted public function"
77
78
79# ---------------------------------------------------------------- ELF
80def run_elf(path):
81    """An archive (libstrata_kernels_cpu.a), an object or a linked binary.  Give it the archive: a linked binary also
82    holds ggml-cpu, which a Linux source build compiles for the build machine (-march=native) on purpose."""
83    for tool in ("objdump", "nm"):
84        if shutil.which(tool) is None:
85            print("check_isa_guard: %s not found" % tool)
86            return 77
87    nm = subprocess.run(["nm", "-C", "--defined-only", path], capture_output=True, text=True, check=True).stdout
88    weak, obj = set(), None
89    for line in nm.splitlines():
90        m = re.match(r"^(\S+\.o):$", line)
91        if m:
92            obj = m.group(1)
93            continue
94        m = re.match(r"^[0-9a-f]+ ([A-Za-z]) (.*)$", line)
95        if m and m.group(2) and m.group(1) in "WVwu":
96            weak.add((obj, m.group(2)))
97    dis = subprocess.run(["objdump", "-d", "-C", "-w", "--no-addresses", path], capture_output=True, text=True,
98                         check=True).stdout
99    obj, cur, wide, funcs, inits = None, None, {}, 0, {}
100    for line in dis.splitlines():
101        m = re.match(r"^(\S+\.o):\s+file format", line)
102        if m:
103            obj = m.group(1)
104            continue
105        m = re.match(r"^(?:[0-9a-f]+ )?<(.*)>:$", line.strip())
106        if m:
107            cur = m.group(1)
108            funcs += 1
109            continue
110        if cur is None or "\t" not in line:
111            continue
112        parts = line.split("\t")
113        if len(parts) < 3:
114            continue
115        raw = parts[1].split()
116        text = parts[2].strip().split(None, 1)
117        if not raw or not text:
118            continue
119        ops = text[1] if len(text) > 1 else ""
120        if is_wide(int(raw[0], 16), text[0], ops):
121            e = wide.setdefault((obj, cur), [0, text[0]])
122            e[0] += 1
123        # a static initialiser of a wide-ISA / older-CPU object: any VEX / EVEX encoding is an illegal instruction on a
124        # CPU without AVX (or FMA, AVX2), and the initialiser runs before main
125        if cur.startswith("_GLOBAL__sub_I_") and obj and any(obj.endswith(o + ".o") for o in INIT_FREE_OBJECTS) and                 (int(raw[0], 16) in (0xC4, 0xC5, 0x62) or (text[0].startswith("v") and text[0] not in ("verr", "verw"))):
126            e = inits.setdefault((obj, cur), [0, text[0]])
127            e[0] += 1
128    bad = []
129    for (obj, name), (n, first) in sorted(wide.items(), key=lambda kv: (kv[0][0] or "", kv[0][1])):
130        # .isra / .part / .cold clones belong to the function they were split from
131        root = re.sub(r"( \[clone [^\]]*\])+$", "", name)
132        is_weak = (obj, name) in weak or (obj, root) in weak
133        why = judge(root, obj, "", False, is_weak, True)
134        if why:
135            bad.append((name, n, first, why + (" [%s]" % obj if obj else "")))
136    for (o, name), (n, first) in sorted(inits.items()):
137        bad.append((name, n, first, "static initialiser holding AVX-class instructions in a wide-ISA / older-CPU object: it "
138                    "runs on every CPU at program start (#2324) [%s]" % o))
139    return report(path, funcs, {k[1]: v for k, v in wide.items()}, bad)
140
141
142# ---------------------------------------------------------------- PE
143def run_pe(path, mapf):
144    try:
145        import pefile
146        from capstone import Cs, CS_ARCH_X86, CS_MODE_64
147    except ImportError:
148        print("check_isa_guard: pip install capstone pefile to check a PE binary")
149        return 77
150    base_sym, isa_rva = {}, None
151    pe = pefile.PE(path)
152    image_base = pe.OPTIONAL_HEADER.ImageBase
153    for line in open(mapf, errors="replace"):
154        m = re.match(r"\s*0001:[0-9a-f]+\s+(\S+)\s+([0-9a-f]{16})\s+(?:f i|f)?\s*(\S+)\s*$", line)
155        if m:
156            rva = int(m.group(2), 16) - image_base
157            base_sym[rva] = (m.group(1), m.group(3))
158    for line in open(mapf, errors="replace"):
159        m = re.match(r"\s*0003:[0-9a-f]+\s+__isa_available\s+([0-9a-f]{16})", line)
160        if m:
161            isa_rva = int(m.group(1), 16) - image_base
162    starts = sorted(base_sym)
163    text = [s for s in pe.sections if s.Name.startswith(b".text")][0]
164    funcs = sorted((e.struct.BeginAddress, e.struct.EndAddress) for e in pe.DIRECTORY_ENTRY_EXCEPTION)
165    md = Cs(CS_ARCH_X86, CS_MODE_64)
166    wide, nfun = {}, 0
167    for b, e in funcs:
168        if not (text.VirtualAddress <= b < text.VirtualAddress + text.Misc_VirtualSize):
169            continue
170        nfun += 1
171        n, first, guarded = 0, None, False
172        for ins in md.disasm(pe.get_data(b, e - b), b):
173            if isa_rva is not None and "[rip" in ins.op_str:
174                m = re.search(r"\[rip ([+-]) 0x([0-9a-f]+)\]", ins.op_str)
175                if m:                    # the function reads __isa_available: MSVC's own run-time guard for its vectorizer
176                    disp = int(m.group(2), 16) * (1 if m.group(1) == "+" else -1)
177                    guarded = guarded or ins.address + ins.size + disp == isa_rva
178            if is_wide(ins.bytes[0], ins.mnemonic, ins.op_str):
179                n += 1
180                first = first or ins.mnemonic
181        if n:
182            # a cold chunk or funclet has no map entry: it belongs to the nearest symbol before it
183            i = bisect.bisect_right(starts, b) - 1
184            sym, obj = base_sym[starts[i]] if i >= 0 else ("?", "?")
185            wide[(b, sym, obj)] = (n, first, guarded)
186    bad = []
187    for (b, sym, obj), (n, first, guarded) in sorted(wide.items()):
188        why = judge(sym, obj.split(":")[-1], "", guarded, False, False)
189        # an inline function defined in a header comes out of the map as `f i`; the wide-ISA files must have none
190        in_wide_obj = any(o in obj for o in WIDE_OBJECTS)
191        if why is None and in_wide_obj and not guarded and re.search(r"std@@|\?\$", sym) and not ("?A0x" in sym):
192            why = "template / std:: instantiation inside a wide-ISA object (COMDAT: the linker may share it)"
193        if why:
194            bad.append((sym, n, first, why + " [rva %x, %s]" % (b, obj)))
195    return report(path, nfun, {k[1]: v for k, v in wide.items()}, bad)
196
197
198def report(path, nfun, wide, bad):
199    print("check_isa_guard: %s: %s functions, %d hold wide-ISA instructions, %d not allowed"
200          % (path, nfun, len(wide), len(bad)))
201    for name, n, first, why in bad:
202        print("  VIOLATION %s (%d wide instructions, first %s): %s" % (name[:160], n, first, why))
203    return 1 if bad else 0
204
205
206def main():
207    ap = argparse.ArgumentParser()
208    ap.add_argument("binary")
209    ap.add_argument("--map", help="MSVC linker map (PE)")
210    a = ap.parse_args()
211    with open(a.binary, "rb") as f:
212        magic = f.read(4)
213    if magic[:2] == b"MZ":
214        if not a.map:
215            print("check_isa_guard: a PE binary needs --map (link with /MAP)")
216            return 77
217        return run_pe(a.binary, a.map)
218    if magic == b"\x7fELF" or magic == b"!<ar":
219        return run_elf(a.binary)
220    print("check_isa_guard: not a PE or ELF file")
221    return 77
222
223
224if __name__ == "__main__":
225    sys.exit(main())