okami.mom/strata
git clone https://git.nkp.pet/okami.mom/strata
f2eedfe9f
main
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 9compiler 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 11COMDAT / 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 18Linux : check_isa_guard.py libstrata_kernels_cpu.a (needs objdump and nm from binutils) 19Windows: 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 ): 57return 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.""" 62if guarded : 63return None 64if name .startswith ("?" ):# MSVC decorated: ?name@scope@... 65base = re .match (r"\?+(?:\$)?([^@$?]+)" ,name ).group (1 )if re .match (r"\?+(?:\$)?([^@$?]+)" ,name )else name 66else :# demangled ELF names carry the argument list 67base = re .sub (r"\(.*$" ,"" ,name ) 68base = re .sub (r"<.*$" ,"" ,base ).split ("::" )[- 1 ] 69anon = ("(anonymous namespace)" in name )or ("?A0x" in name ) 70if weak : 71return "weak / COMDAT symbol: the linker may pick this wide copy for every caller (ODR)" 72if 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 ): 73return "wide-ISA code outside the wide-ISA translation units (object %s)" % obj 74if anon or base in WIDE_PUBLIC : 75return None 76return "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 82holds ggml-cpu, which a Linux source build compiles for the build machine (-march=native) on purpose.""" 83for tool in ("objdump" ,"nm" ): 84if shutil .which (tool )is None : 85"check_isa_guard: %s not found" % tool ) 86return 77 87nm = subprocess .run (["nm" ,"-C" ,"--defined-only" ,path ],capture_output = True ,text = True ,check = True ).stdout 88weak ,obj = set (),None 89for line in nm .splitlines (): 90m = re .match (r"^(\S+\.o):$" ,line ) 91if m : 92obj = m .group (1 ) 93continue 94m = re .match (r"^[0-9a-f]+ ([A-Za-z]) (.*)$" ,line ) 95if m and m .group (2 )and m .group (1 )in "WVwu" : 96weak .add ((obj ,m .group (2 ))) 97dis = subprocess .run (["objdump" ,"-d" ,"-C" ,"-w" ,"--no-addresses" ,path ],capture_output = True ,text = True , 98check = True ).stdout 99obj ,cur ,wide ,funcs ,inits = None ,None , {},0 , {} 100for line in dis .splitlines (): 101m = re .match (r"^(\S+\.o):\s+file format" ,line ) 102if m : 103obj = m .group (1 ) 104continue 105m = re .match (r"^(?:[0-9a-f]+ )?<(.*)>:$" ,line .strip ()) 106if m : 107cur = m .group (1 ) 108funcs += 1 109continue 110if cur is None or "\t" not in line : 111continue 112parts = line .split ("\t" ) 113if len (parts )< 3 : 114continue 115raw = parts [1 ].split () 116text = parts [2 ].strip ().split (None ,1 ) 117if not raw or not text : 118continue 119ops = text [1 ]if len (text )> 1 else "" 120if is_wide (int (raw [0 ],16 ),text [0 ],ops ): 121e = wide .setdefault ((obj ,cur ), [0 ,text [0 ]]) 122e [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 125if 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" ))): 126e = inits .setdefault ((obj ,cur ), [0 ,text [0 ]]) 127e [0 ]+= 1 128bad = [] 129for (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 131root = re .sub (r"( \[clone [^\]]*\])+$" ,"" ,name ) 132is_weak = (obj ,name )in weak or (obj ,root )in weak 133why = judge (root ,obj ,"" ,False ,is_weak ,True ) 134if why : 135bad .append ((name ,n ,first ,why + (" [%s]" % obj if obj else "" ))) 136for (o ,name ), (n ,first )in sorted (inits .items ()): 137bad .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 )) 139return report (path ,funcs , {k [1 ]:v for k ,v in wide .items ()},bad ) 140 141 142# ---------------------------------------------------------------- PE 143def run_pe (path ,mapf ): 144try : 145import pefile 146from capstone import Cs ,CS_ARCH_X86 ,CS_MODE_64 147except ImportError : 148"check_isa_guard: pip install capstone pefile to check a PE binary" ) 149return 77 150base_sym ,isa_rva = {},None 151pe = pefile .PE (path ) 152image_base = pe .OPTIONAL_HEADER .ImageBase 153for line in open (mapf ,errors = "replace" ): 154m = re .match (r"\s*0001:[0-9a-f]+\s+(\S+)\s+([0-9a-f]{16})\s+(?:f i|f)?\s*(\S+)\s*$" ,line ) 155if m : 156rva = int (m .group (2 ),16 )- image_base 157base_sym [rva ]= (m .group (1 ),m .group (3 )) 158for line in open (mapf ,errors = "replace" ): 159m = re .match (r"\s*0003:[0-9a-f]+\s+__isa_available\s+([0-9a-f]{16})" ,line ) 160if m : 161isa_rva = int (m .group (1 ),16 )- image_base 162starts = sorted (base_sym ) 163text = [s for s in pe .sections if s .Name .startswith (b".text" )][0 ] 164funcs = sorted ((e .struct .BeginAddress ,e .struct .EndAddress )for e in pe .DIRECTORY_ENTRY_EXCEPTION ) 165md = Cs (CS_ARCH_X86 ,CS_MODE_64 ) 166wide ,nfun = {},0 167for b ,e in funcs : 168if not (text .VirtualAddress <= b < text .VirtualAddress + text .Misc_VirtualSize ): 169continue 170nfun += 1 171n ,first ,guarded = 0 ,None ,False 172for ins in md .disasm (pe .get_data (b ,e - b ),b ): 173if isa_rva is not None and "[rip" in ins .op_str : 174m = re .search (r"\[rip ([+-]) 0x([0-9a-f]+)\]" ,ins .op_str ) 175if m :# the function reads __isa_available: MSVC's own run-time guard for its vectorizer 176disp = int (m .group (2 ),16 )* (1 if m .group (1 )== "+" else - 1 ) 177guarded = guarded or ins .address + ins .size + disp == isa_rva 178if is_wide (ins .bytes [0 ],ins .mnemonic ,ins .op_str ): 179n += 1 180first = first or ins .mnemonic 181if n : 182# a cold chunk or funclet has no map entry: it belongs to the nearest symbol before it 183i = bisect .bisect_right (starts ,b )- 1 184sym ,obj = base_sym [starts [i ]]if i >= 0 else ("?" ,"?" ) 185wide [(b ,sym ,obj )]= (n ,first ,guarded ) 186bad = [] 187for (b ,sym ,obj ), (n ,first ,guarded )in sorted (wide .items ()): 188why = 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 190in_wide_obj = any (o in obj for o in WIDE_OBJECTS ) 191if why is None and in_wide_obj and not guarded and re .search (r"std@@|\?\$" ,sym )and not ("?A0x" in sym ): 192why = "template / std:: instantiation inside a wide-ISA object (COMDAT: the linker may share it)" 193if why : 194bad .append ((sym ,n ,first ,why + " [rva %x, %s]" % (b ,obj ))) 195return report (path ,nfun , {k [1 ]:v for k ,v in wide .items ()},bad ) 196 197 198def report (path ,nfun ,wide ,bad ): 199"check_isa_guard: %s: %s functions, %d hold wide-ISA instructions, %d not allowed" 200% (path ,nfun ,len (wide ),len (bad ))) 201for name ,n ,first ,why in bad : 202" VIOLATION %s (%d wide instructions, first %s): %s" % (name [:160 ],n ,first ,why )) 203return 1 if bad else 0 204 205 206def main (): 207ap = argparse .ArgumentParser () 208ap .add_argument ("binary" ) 209ap .add_argument ("--map" ,help = "MSVC linker map (PE)" ) 210a = ap .parse_args () 211with open (a .binary ,"rb" )as f : 212magic = f .read (4 ) 213if magic [:2 ]== b"MZ" : 214if not a .map : 215"check_isa_guard: a PE binary needs --map (link with /MAP)" ) 216return 77 217return run_pe (a .binary ,a .map ) 218if magic == b"\x7fELF" or magic == b"!<ar" : 219return run_elf (a .binary ) 220"check_isa_guard: not a PE or ELF file" ) 221return 77 222 223 224if __name__ == "__main__" : 225sys .exit (main ())