codeparser.py 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459
  1. #
  2. # SPDX-License-Identifier: GPL-2.0-only
  3. #
  4. """
  5. BitBake code parser
  6. Parses actual code (i.e. python and shell) for functions and in-line
  7. expressions. Used mainly to determine dependencies on other functions
  8. and variables within the BitBake metadata. Also provides a cache for
  9. this information in order to speed up processing.
  10. (Not to be confused with the code that parses the metadata itself,
  11. see lib/bb/parse/ for that).
  12. NOTE: if you change how the parsers gather information you will almost
  13. certainly need to increment CodeParserCache.CACHE_VERSION below so that
  14. any existing codeparser cache gets invalidated. Additionally you'll need
  15. to increment __cache_version__ in cache.py in order to ensure that old
  16. recipe caches don't trigger "Taskhash mismatch" errors.
  17. """
  18. import ast
  19. import sys
  20. import codegen
  21. import logging
  22. import bb.pysh as pysh
  23. import bb.utils, bb.data
  24. import hashlib
  25. from itertools import chain
  26. from bb.pysh import pyshyacc, pyshlex
  27. from bb.cache import MultiProcessCache
  28. logger = logging.getLogger('BitBake.CodeParser')
  29. def bbhash(s):
  30. return hashlib.sha256(s.encode("utf-8")).hexdigest()
  31. def check_indent(codestr):
  32. """If the code is indented, add a top level piece of code to 'remove' the indentation"""
  33. i = 0
  34. while codestr[i] in ["\n", "\t", " "]:
  35. i = i + 1
  36. if i == 0:
  37. return codestr
  38. if codestr[i-1] == "\t" or codestr[i-1] == " ":
  39. if codestr[0] == "\n":
  40. # Since we're adding a line, we need to remove one line of any empty padding
  41. # to ensure line numbers are correct
  42. codestr = codestr[1:]
  43. return "if 1:\n" + codestr
  44. return codestr
  45. # A custom getstate/setstate using tuples is actually worth 15% cachesize by
  46. # avoiding duplication of the attribute names!
  47. class SetCache(object):
  48. def __init__(self):
  49. self.setcache = {}
  50. def internSet(self, items):
  51. new = []
  52. for i in items:
  53. new.append(sys.intern(i))
  54. s = frozenset(new)
  55. h = hash(s)
  56. if h in self.setcache:
  57. return self.setcache[h]
  58. self.setcache[h] = s
  59. return s
  60. codecache = SetCache()
  61. class pythonCacheLine(object):
  62. def __init__(self, refs, execs, contains):
  63. self.refs = codecache.internSet(refs)
  64. self.execs = codecache.internSet(execs)
  65. self.contains = {}
  66. for c in contains:
  67. self.contains[c] = codecache.internSet(contains[c])
  68. def __getstate__(self):
  69. return (self.refs, self.execs, self.contains)
  70. def __setstate__(self, state):
  71. (refs, execs, contains) = state
  72. self.__init__(refs, execs, contains)
  73. def __hash__(self):
  74. l = (hash(self.refs), hash(self.execs))
  75. for c in sorted(self.contains.keys()):
  76. l = l + (c, hash(self.contains[c]))
  77. return hash(l)
  78. def __repr__(self):
  79. return " ".join([str(self.refs), str(self.execs), str(self.contains)])
  80. class shellCacheLine(object):
  81. def __init__(self, execs):
  82. self.execs = codecache.internSet(execs)
  83. def __getstate__(self):
  84. return (self.execs)
  85. def __setstate__(self, state):
  86. (execs) = state
  87. self.__init__(execs)
  88. def __hash__(self):
  89. return hash(self.execs)
  90. def __repr__(self):
  91. return str(self.execs)
  92. class CodeParserCache(MultiProcessCache):
  93. cache_file_name = "bb_codeparser.dat"
  94. # NOTE: you must increment this if you change how the parsers gather information,
  95. # so that an existing cache gets invalidated. Additionally you'll need
  96. # to increment __cache_version__ in cache.py in order to ensure that old
  97. # recipe caches don't trigger "Taskhash mismatch" errors.
  98. CACHE_VERSION = 11
  99. def __init__(self):
  100. MultiProcessCache.__init__(self)
  101. self.pythoncache = self.cachedata[0]
  102. self.shellcache = self.cachedata[1]
  103. self.pythoncacheextras = self.cachedata_extras[0]
  104. self.shellcacheextras = self.cachedata_extras[1]
  105. # To avoid duplication in the codeparser cache, keep
  106. # a lookup of hashes of objects we already have
  107. self.pythoncachelines = {}
  108. self.shellcachelines = {}
  109. def newPythonCacheLine(self, refs, execs, contains):
  110. cacheline = pythonCacheLine(refs, execs, contains)
  111. h = hash(cacheline)
  112. if h in self.pythoncachelines:
  113. return self.pythoncachelines[h]
  114. self.pythoncachelines[h] = cacheline
  115. return cacheline
  116. def newShellCacheLine(self, execs):
  117. cacheline = shellCacheLine(execs)
  118. h = hash(cacheline)
  119. if h in self.shellcachelines:
  120. return self.shellcachelines[h]
  121. self.shellcachelines[h] = cacheline
  122. return cacheline
  123. def init_cache(self, d):
  124. # Check if we already have the caches
  125. if self.pythoncache:
  126. return
  127. MultiProcessCache.init_cache(self, d)
  128. # cachedata gets re-assigned in the parent
  129. self.pythoncache = self.cachedata[0]
  130. self.shellcache = self.cachedata[1]
  131. def create_cachedata(self):
  132. data = [{}, {}]
  133. return data
  134. codeparsercache = CodeParserCache()
  135. def parser_cache_init(d):
  136. codeparsercache.init_cache(d)
  137. def parser_cache_save():
  138. codeparsercache.save_extras()
  139. def parser_cache_savemerge():
  140. codeparsercache.save_merge()
  141. Logger = logging.getLoggerClass()
  142. class BufferedLogger(Logger):
  143. def __init__(self, name, level=0, target=None):
  144. Logger.__init__(self, name)
  145. self.setLevel(level)
  146. self.buffer = []
  147. self.target = target
  148. def handle(self, record):
  149. self.buffer.append(record)
  150. def flush(self):
  151. for record in self.buffer:
  152. if self.target.isEnabledFor(record.levelno):
  153. self.target.handle(record)
  154. self.buffer = []
  155. class PythonParser():
  156. getvars = (".getVar", ".appendVar", ".prependVar", "oe.utils.conditional")
  157. getvarflags = (".getVarFlag", ".appendVarFlag", ".prependVarFlag")
  158. containsfuncs = ("bb.utils.contains", "base_contains")
  159. containsanyfuncs = ("bb.utils.contains_any", "bb.utils.filter")
  160. execfuncs = ("bb.build.exec_func", "bb.build.exec_task")
  161. def warn(self, func, arg):
  162. """Warn about calls of bitbake APIs which pass a non-literal
  163. argument for the variable name, as we're not able to track such
  164. a reference.
  165. """
  166. try:
  167. funcstr = codegen.to_source(func)
  168. argstr = codegen.to_source(arg)
  169. except TypeError:
  170. self.log.debug(2, 'Failed to convert function and argument to source form')
  171. else:
  172. self.log.debug(1, self.unhandled_message % (funcstr, argstr))
  173. def visit_Call(self, node):
  174. name = self.called_node_name(node.func)
  175. if name and (name.endswith(self.getvars) or name.endswith(self.getvarflags) or name in self.containsfuncs or name in self.containsanyfuncs):
  176. if isinstance(node.args[0], ast.Str):
  177. varname = node.args[0].s
  178. if name in self.containsfuncs and isinstance(node.args[1], ast.Str):
  179. if varname not in self.contains:
  180. self.contains[varname] = set()
  181. self.contains[varname].add(node.args[1].s)
  182. elif name in self.containsanyfuncs and isinstance(node.args[1], ast.Str):
  183. if varname not in self.contains:
  184. self.contains[varname] = set()
  185. self.contains[varname].update(node.args[1].s.split())
  186. elif name.endswith(self.getvarflags):
  187. if isinstance(node.args[1], ast.Str):
  188. self.references.add('%s[%s]' % (varname, node.args[1].s))
  189. else:
  190. self.warn(node.func, node.args[1])
  191. else:
  192. self.references.add(varname)
  193. else:
  194. self.warn(node.func, node.args[0])
  195. elif name and name.endswith(".expand"):
  196. if isinstance(node.args[0], ast.Str):
  197. value = node.args[0].s
  198. d = bb.data.init()
  199. parser = d.expandWithRefs(value, self.name)
  200. self.references |= parser.references
  201. self.execs |= parser.execs
  202. for varname in parser.contains:
  203. if varname not in self.contains:
  204. self.contains[varname] = set()
  205. self.contains[varname] |= parser.contains[varname]
  206. elif name in self.execfuncs:
  207. if isinstance(node.args[0], ast.Str):
  208. self.var_execs.add(node.args[0].s)
  209. else:
  210. self.warn(node.func, node.args[0])
  211. elif name and isinstance(node.func, (ast.Name, ast.Attribute)):
  212. self.execs.add(name)
  213. def called_node_name(self, node):
  214. """Given a called node, return its original string form"""
  215. components = []
  216. while node:
  217. if isinstance(node, ast.Attribute):
  218. components.append(node.attr)
  219. node = node.value
  220. elif isinstance(node, ast.Name):
  221. components.append(node.id)
  222. return '.'.join(reversed(components))
  223. else:
  224. break
  225. def __init__(self, name, log):
  226. self.name = name
  227. self.var_execs = set()
  228. self.contains = {}
  229. self.execs = set()
  230. self.references = set()
  231. self.log = BufferedLogger('BitBake.Data.PythonParser', logging.DEBUG, log)
  232. self.unhandled_message = "in call of %s, argument '%s' is not a string literal"
  233. self.unhandled_message = "while parsing %s, %s" % (name, self.unhandled_message)
  234. def parse_python(self, node, lineno=0, filename="<string>"):
  235. if not node or not node.strip():
  236. return
  237. h = bbhash(str(node))
  238. if h in codeparsercache.pythoncache:
  239. self.references = set(codeparsercache.pythoncache[h].refs)
  240. self.execs = set(codeparsercache.pythoncache[h].execs)
  241. self.contains = {}
  242. for i in codeparsercache.pythoncache[h].contains:
  243. self.contains[i] = set(codeparsercache.pythoncache[h].contains[i])
  244. return
  245. if h in codeparsercache.pythoncacheextras:
  246. self.references = set(codeparsercache.pythoncacheextras[h].refs)
  247. self.execs = set(codeparsercache.pythoncacheextras[h].execs)
  248. self.contains = {}
  249. for i in codeparsercache.pythoncacheextras[h].contains:
  250. self.contains[i] = set(codeparsercache.pythoncacheextras[h].contains[i])
  251. return
  252. # We can't add to the linenumbers for compile, we can pad to the correct number of blank lines though
  253. node = "\n" * int(lineno) + node
  254. code = compile(check_indent(str(node)), filename, "exec",
  255. ast.PyCF_ONLY_AST)
  256. for n in ast.walk(code):
  257. if n.__class__.__name__ == "Call":
  258. self.visit_Call(n)
  259. self.execs.update(self.var_execs)
  260. codeparsercache.pythoncacheextras[h] = codeparsercache.newPythonCacheLine(self.references, self.execs, self.contains)
  261. class ShellParser():
  262. def __init__(self, name, log):
  263. self.funcdefs = set()
  264. self.allexecs = set()
  265. self.execs = set()
  266. self.log = BufferedLogger('BitBake.Data.%s' % name, logging.DEBUG, log)
  267. self.unhandled_template = "unable to handle non-literal command '%s'"
  268. self.unhandled_template = "while parsing %s, %s" % (name, self.unhandled_template)
  269. def parse_shell(self, value):
  270. """Parse the supplied shell code in a string, returning the external
  271. commands it executes.
  272. """
  273. h = bbhash(str(value))
  274. if h in codeparsercache.shellcache:
  275. self.execs = set(codeparsercache.shellcache[h].execs)
  276. return self.execs
  277. if h in codeparsercache.shellcacheextras:
  278. self.execs = set(codeparsercache.shellcacheextras[h].execs)
  279. return self.execs
  280. self._parse_shell(value)
  281. self.execs = set(cmd for cmd in self.allexecs if cmd not in self.funcdefs)
  282. codeparsercache.shellcacheextras[h] = codeparsercache.newShellCacheLine(self.execs)
  283. return self.execs
  284. def _parse_shell(self, value):
  285. try:
  286. tokens, _ = pyshyacc.parse(value, eof=True, debug=False)
  287. except Exception:
  288. bb.error('Error during parse shell code, the last 5 lines are:\n%s' % '\n'.join(value.split('\n')[-5:]))
  289. raise
  290. self.process_tokens(tokens)
  291. def process_tokens(self, tokens):
  292. """Process a supplied portion of the syntax tree as returned by
  293. pyshyacc.parse.
  294. """
  295. def function_definition(value):
  296. self.funcdefs.add(value.name)
  297. return [value.body], None
  298. def case_clause(value):
  299. # Element 0 of each item in the case is the list of patterns, and
  300. # Element 1 of each item in the case is the list of commands to be
  301. # executed when that pattern matches.
  302. words = chain(*[item[0] for item in value.items])
  303. cmds = chain(*[item[1] for item in value.items])
  304. return cmds, words
  305. def if_clause(value):
  306. main = chain(value.cond, value.if_cmds)
  307. rest = value.else_cmds
  308. if isinstance(rest, tuple) and rest[0] == "elif":
  309. return chain(main, if_clause(rest[1]))
  310. else:
  311. return chain(main, rest)
  312. def simple_command(value):
  313. return None, chain(value.words, (assign[1] for assign in value.assigns))
  314. token_handlers = {
  315. "and_or": lambda x: ((x.left, x.right), None),
  316. "async": lambda x: ([x], None),
  317. "brace_group": lambda x: (x.cmds, None),
  318. "for_clause": lambda x: (x.cmds, x.items),
  319. "function_definition": function_definition,
  320. "if_clause": lambda x: (if_clause(x), None),
  321. "pipeline": lambda x: (x.commands, None),
  322. "redirect_list": lambda x: ([x.cmd], None),
  323. "subshell": lambda x: (x.cmds, None),
  324. "while_clause": lambda x: (chain(x.condition, x.cmds), None),
  325. "until_clause": lambda x: (chain(x.condition, x.cmds), None),
  326. "simple_command": simple_command,
  327. "case_clause": case_clause,
  328. }
  329. def process_token_list(tokens):
  330. for token in tokens:
  331. if isinstance(token, list):
  332. process_token_list(token)
  333. continue
  334. name, value = token
  335. try:
  336. more_tokens, words = token_handlers[name](value)
  337. except KeyError:
  338. raise NotImplementedError("Unsupported token type " + name)
  339. if more_tokens:
  340. self.process_tokens(more_tokens)
  341. if words:
  342. self.process_words(words)
  343. process_token_list(tokens)
  344. def process_words(self, words):
  345. """Process a set of 'words' in pyshyacc parlance, which includes
  346. extraction of executed commands from $() blocks, as well as grabbing
  347. the command name argument.
  348. """
  349. words = list(words)
  350. for word in list(words):
  351. wtree = pyshlex.make_wordtree(word[1])
  352. for part in wtree:
  353. if not isinstance(part, list):
  354. continue
  355. if part[0] in ('`', '$('):
  356. command = pyshlex.wordtree_as_string(part[1:-1])
  357. self._parse_shell(command)
  358. if word[0] in ("cmd_name", "cmd_word"):
  359. if word in words:
  360. words.remove(word)
  361. usetoken = False
  362. for word in words:
  363. if word[0] in ("cmd_name", "cmd_word") or \
  364. (usetoken and word[0] == "TOKEN"):
  365. if "=" in word[1]:
  366. usetoken = True
  367. continue
  368. cmd = word[1]
  369. if cmd.startswith("$"):
  370. self.log.debug(1, self.unhandled_template % cmd)
  371. elif cmd == "eval":
  372. command = " ".join(word for _, word in words[1:])
  373. self._parse_shell(command)
  374. else:
  375. self.allexecs.add(cmd)
  376. break