codeparser.py 15 KB

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