okami.mom/strata
git clone https://git.nkp.pet/okami.mom/strata
6a74320ca
main
1#!/usr/bin/env python3 2"""gen_stubs.py LINK_LOG OUT.cpp CLANG_ARGS... : stubs for the kernel-library entry points the Metal engine leaves undefined. 3 4LINK_LOG is the output of a failed link of `strata` (ld64 prints each undefined symbol demangled). The declarations 5come from the engine's own headers through clang's AST dump (-ast-dump-filter), so every stub has the header's exact 6types; it is defined in the declaring namespace (free functions) or out of line (members, trailing return type), and 7calls strata::metal_engine::missing("name") (metal/src/engine/missing.cpp). Entry points that have a Metal 8implementation are defined in metal/src/engine/*.cpp and are therefore not undefined: they never get a stub. 9""" 10import os ,re ,subprocess ,sys ,tempfile 11 12log ,out = sys .argv [1 ],sys .argv [2 ] 13clang_args = sys .argv [3 :] 14root = None 15for a in clang_args : 16if a .startswith ("-I" )and a .endswith ("/include" )and os .path .isdir (os .path .join (a [2 :],"strata" )): 17root = a [2 :] 18assert root ,"need -I<repo>/include among the clang args" 19 20# ---- the undefined symbols (demangled), from ld64's report 21undef = [] 22for m in re .finditer (r'^\s+"(.+)", referenced from:' ,open (log ,errors = "replace" ).read (),re .M ): 23undef .append (m .group (1 )) 24undef = sorted (set (undef )) 25 26def split_top (s ): 27out ,d ,cur = [],0 ,"" 28for ch in s : 29if ch in "(<[" :d += 1 30if ch in ")>]" :d -= 1 31if ch == "," and d == 0 : 32out .append (cur .strip ());cur = "" 33else : 34cur += ch 35if cur .strip ():out .append (cur .strip ()) 36return out 37 38def parse_demangled (s ): 39"""'ns::f(int, float*) const' -> ('ns::f', nparams)""" 40s = re .sub (r"\s+const$" ,"" ,s ) 41d ,i = 0 ,len (s )- 1 42while i >= 0 : 43if s [i ]== ")" :d += 1 44elif s [i ]== "(" : 45d -= 1 46if d == 0 :break 47i -= 1 48name ,params = s [:i ],s [i + 1 :- 1 ] 49p = split_top (params ) 50if p == ["void" ]:p = [] 51return name ,len (p ) 52 53wanted = {} 54skipped = [] 55for u in undef : 56if "(" not in u or u .startswith ("_" )or "::" not in u : 57skipped .append (u );continue 58n ,k = parse_demangled (u ) 59wanted .setdefault (n ,set ()).add (k ) 60 61# ---- declarations from the headers 62hdrs = [] 63for d in ["kernels" ,"kernels/cpu" ,"prefill" ,"core" ,"platform" ,"ngram" ,"spec" ]: 64p = os .path .join (root ,"strata" ,d ) 65if os .path .isdir (p ): 66hdrs += sorted ("strata/%s/%s" % (d ,f )for f in os .listdir (p )if f .endswith (".hpp" )) 67def compiles (h ): 68f = tempfile .NamedTemporaryFile ("w" ,suffix = ".cpp" ,delete = False ) 69f .write ('#include "%s"\n' % h );f .close () 70r = subprocess .run (["clang++" ,"-fsyntax-only" ]+ clang_args + [f .name ],capture_output = True ,text = True ) 71os .unlink (f .name ) 72return r .returncode == 0 73bad = [h for h in hdrs if not compiles (h )] 74hdrs = [h for h in hdrs if h not in bad ] 75for h in bad :"HEADER-SKIPPED" ,h ) 76tu = tempfile .NamedTemporaryFile ("w" ,suffix = ".cpp" ,delete = False ) 77for h in hdrs :tu .write ('#include "%s"\n' % h ) 78tu .close () 79decls = {}# qualname -> list of (kind, type_str, params[(name,type)], is_const, is_static, file) 80cmd = ["clang++" ,"-fsyntax-only" ,"-Xclang" ,"-ast-dump" ,"-Xclang" ,"-ast-dump-filter=strata" ,"-fno-color-diagnostics" ]+ clang_args + [tu .name ] 81r = subprocess .run (cmd ,capture_output = True ,text = True ) 82if r .returncode != 0 :sys .stderr .write (r .stderr [- 4000 :]) 83# the AST dump is a tree ("|-", "`-", "| " prefixes, two characters per level): walk it, keeping the enclosing 84# namespaces and records, and collect every function declaration that has no body 85FN = ("FunctionDecl" ,"CXXMethodDecl" ,"CXXConstructorDecl" ,"CXXDestructorDecl" ) 86stack = []# (depth, kind, name) 87cur = None # the function being read: [qual, kind, type, params, depth, has_body, rest] 88def flush (): 89global cur 90if cur and not cur [5 ]and cur [0 ]in wanted : 91q ,kind ,ty ,params ,d ,hb ,rest = cur 92decls .setdefault (q , []).append ((kind ,ty ,params ,bool (re .search (r"\)\s*const\s*(noexcept)?\s*$" ,ty ))," static" in rest ,"" )) 93cur = None 94for line in r .stdout .splitlines (): 95if line .startswith ("Dumping " ):flush ();stack = [];continue 96m = re .match (r"^([| `-]*)(\w+) " ,line ) 97if not m :continue 98depth = len (m .group (1 ))// 2 99kind = m .group (2 ) 100if cur and depth <= cur [4 ]:flush () 101while stack and stack [- 1 ][0 ]>= depth :stack .pop () 102if cur : 103if kind == "CompoundStmt" and depth == cur [4 ]+ 1 :cur [5 ]= True 104if kind == "ParmVarDecl" and depth == cur [4 ]+ 1 : 105pm = re .search (r"(?:col|line):[\d:]+(?: used| referenced)?(?: (\w+))? '([^']*)'(?::'[^']*')?" ,line ) 106if pm :cur [3 ].append ((pm .group (1 )or "" ,pm .group (2 ))) 107continue 108if kind == "NamespaceDecl" : 109nm = re .search (r"> (?:prev 0x\w+ )?(?:line|col):[\d:]+ (\w+)" ,line ) 110stack .append ((depth ,kind ,nm .group (1 )if nm else "(anonymous)" )) 111elif kind in ("CXXRecordDecl" ,"ClassTemplateDecl" ): 112nm = re .search (r"(?:class|struct|union) (\w+)" ,line ) 113if " implicit " in line or not nm :stack .append ((depth ,kind ,"(implicit)" )) 114else :stack .append ((depth ,kind ,nm .group (1 ))) 115elif kind in FN and " implicit " not in line : 116fm = re .findall (r"(~?\w+) '([^']*)'(?::'[^']*')?" ,line ) 117if not fm :continue 118name ,ty = fm [- 1 ] 119rest = line [line .rfind ("'" )+ 1 :] 120names = [s [2 ]for s in stack ] 121if any (n .startswith ("(" )for n in names )or any (s [1 ]== "ClassTemplateDecl" for s in stack ):continue 122cur = [("::" .join (names + [name ])),kind ,ty , [],depth ,False ,rest ] 123elif kind in ("FunctionTemplateDecl" ,): 124stack .append ((depth ,kind ,"(template)" )) 125flush () 126 127def nx (ty ): 128return " noexcept" if re .search (r"\)\s*(const\s*)?noexcept\s*$" ,ty )else "" 129 130def ret_stmt (r ): 131if r == "void" :return "" 132if r .endswith ("&" ):# a reference: to a zero-initialised object of its own 133return " static std::remove_cv_t<std::remove_reference_t<%s>> s{}; return s;" % r 134return " return {};" 135 136def ret_of (ty ): 137d ,i = 0 ,len (ty )- 1 138# the function type is "R (P...)" [ const]; find the '(' that opens the parameter list 139s = re .sub (r"\)\s*(const)?\s*(noexcept)?\s*$" ,")" ,ty ) 140i = len (s )- 1 ;d = 0 141while i >= 0 : 142if s [i ]== ")" :d += 1 143elif s [i ]== "(" : 144d -= 1 145if d == 0 :break 146i -= 1 147return s [:i ].strip () 148 149lines = ['// metal/src/engine/stubs.cpp - GENERATED by metal/tools/gen_stubs.py: do not edit.' , 150'// The kernel-library entry points with no Metal implementation yet: each stops the engine with its name' , 151'// (metal/src/engine/missing.cpp). Regenerate after porting one.' ,'' ] 152lines += ['#include "%s"' % h for h in hdrs ] 153lines += ['#include <type_traits>' ,'' ,'namespace strata::metal_engine { void missing(const char* name); }' ,'' ] 154done ,unmatched = 0 , [] 155for qn in sorted (wanted ): 156ds = decls .get (qn , []) 157ds = [d for d in ds if len (d [2 ])in wanted [qn ]] 158if not ds : 159unmatched .append (qn );continue 160seen = set () 161for kind ,ty ,params ,is_const ,is_static ,loc in ds : 162key = (ty ,kind ) 163if key in seen :continue 164seen .add (key ) 165ps = ", " .join ("%s p%d" % (t ,k )if "(*)" not in t else t .replace ("(*)" ,"(*p%d)" % k )for k , (n ,t )in enumerate (params )) 166if kind == "FunctionDecl" : 167ns ,fn = qn .rsplit ("::" ,1 ) 168r = ret_of (ty ) 169body = 'strata::metal_engine::missing("%s");' % qn 170body += ret_stmt (r ) 171lines .append ("namespace %s { %s %s(%s)%s { %s } }" % (ns ,r ,fn ,ps ,nx (ty ),body )) 172elif kind == "CXXMethodDecl" : 173r = ret_of (ty ) 174body = 'strata::metal_engine::missing("%s");' % qn 175body += ret_stmt (r ) 176lines .append ("auto %s(%s)%s%s -> %s { %s }" % (qn ,ps ," const" if is_const else "" ,nx (ty ),r ,body )) 177elif kind in ("CXXConstructorDecl" ,"CXXDestructorDecl" ): 178lines .append ('%s(%s) { strata::metal_engine::missing("%s"); }' % (qn ,ps ,qn )) 179done += 1 180open (out ,"w" ).write ("\n" .join (lines )+ "\n" ) 181"undefined %d, stubs %d, unmatched %d, skipped %d" % (len (undef ),done ,len (unmatched ),len (skipped ))) 182for u in unmatched :"UNMATCHED" ,u ) 183for u in skipped :"SKIPPED" ,u ) 184os .unlink (tu .name )