codeparser.py 17 KB

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