data.py 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452
  1. # ex:ts=4:sw=4:sts=4:et
  2. # -*- tab-width: 4; c-basic-offset: 4; indent-tabs-mode: nil -*-
  3. """
  4. BitBake 'Data' implementations
  5. Functions for interacting with the data structure used by the
  6. BitBake build tools.
  7. The expandKeys and update_data are the most expensive
  8. operations. At night the cookie monster came by and
  9. suggested 'give me cookies on setting the variables and
  10. things will work out'. Taking this suggestion into account
  11. applying the skills from the not yet passed 'Entwurf und
  12. Analyse von Algorithmen' lecture and the cookie
  13. monster seems to be right. We will track setVar more carefully
  14. to have faster update_data and expandKeys operations.
  15. This is a trade-off between speed and memory again but
  16. the speed is more critical here.
  17. """
  18. # Copyright (C) 2003, 2004 Chris Larson
  19. # Copyright (C) 2005 Holger Hans Peter Freyther
  20. #
  21. # This program is free software; you can redistribute it and/or modify
  22. # it under the terms of the GNU General Public License version 2 as
  23. # published by the Free Software Foundation.
  24. #
  25. # This program is distributed in the hope that it will be useful,
  26. # but WITHOUT ANY WARRANTY; without even the implied warranty of
  27. # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  28. # GNU General Public License for more details.
  29. #
  30. # You should have received a copy of the GNU General Public License along
  31. # with this program; if not, write to the Free Software Foundation, Inc.,
  32. # 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
  33. #
  34. # Based on functions from the base bb module, Copyright 2003 Holger Schurig
  35. import sys, os, re
  36. import hashlib
  37. if sys.argv[0][-5:] == "pydoc":
  38. path = os.path.dirname(os.path.dirname(sys.argv[1]))
  39. else:
  40. path = os.path.dirname(os.path.dirname(sys.argv[0]))
  41. sys.path.insert(0, path)
  42. from itertools import groupby
  43. from bb import data_smart
  44. from bb import codeparser
  45. import bb
  46. logger = data_smart.logger
  47. _dict_type = data_smart.DataSmart
  48. def init():
  49. """Return a new object representing the Bitbake data"""
  50. return _dict_type()
  51. def init_db(parent = None):
  52. """Return a new object representing the Bitbake data,
  53. optionally based on an existing object"""
  54. if parent is not None:
  55. return parent.createCopy()
  56. else:
  57. return _dict_type()
  58. def createCopy(source):
  59. """Link the source set to the destination
  60. If one does not find the value in the destination set,
  61. search will go on to the source set to get the value.
  62. Value from source are copy-on-write. i.e. any try to
  63. modify one of them will end up putting the modified value
  64. in the destination set.
  65. """
  66. return source.createCopy()
  67. def initVar(var, d):
  68. """Non-destructive var init for data structure"""
  69. d.initVar(var)
  70. def keys(d):
  71. """Return a list of keys in d"""
  72. return d.keys()
  73. __expand_var_regexp__ = re.compile(r"\${[^{}]+}")
  74. __expand_python_regexp__ = re.compile(r"\${@.+?}")
  75. def expand(s, d, varname = None):
  76. """Variable expansion using the data store"""
  77. return d.expand(s, varname)
  78. def expandKeys(alterdata, readdata = None):
  79. if readdata == None:
  80. readdata = alterdata
  81. todolist = {}
  82. for key in alterdata:
  83. if not '${' in key:
  84. continue
  85. ekey = expand(key, readdata)
  86. if key == ekey:
  87. continue
  88. todolist[key] = ekey
  89. # These two for loops are split for performance to maximise the
  90. # usefulness of the expand cache
  91. for key in sorted(todolist):
  92. ekey = todolist[key]
  93. newval = alterdata.getVar(ekey, False)
  94. if newval is not None:
  95. val = alterdata.getVar(key, False)
  96. if val is not None:
  97. bb.warn("Variable key %s (%s) replaces original key %s (%s)." % (key, val, ekey, newval))
  98. alterdata.renameVar(key, ekey)
  99. def inheritFromOS(d, savedenv, permitted):
  100. """Inherit variables from the initial environment."""
  101. exportlist = bb.utils.preserved_envvars_exported()
  102. for s in savedenv.keys():
  103. if s in permitted:
  104. try:
  105. d.setVar(s, savedenv.getVar(s), op = 'from env')
  106. if s in exportlist:
  107. d.setVarFlag(s, "export", True, op = 'auto env export')
  108. except TypeError:
  109. pass
  110. def emit_var(var, o=sys.__stdout__, d = init(), all=False):
  111. """Emit a variable to be sourced by a shell."""
  112. func = d.getVarFlag(var, "func", False)
  113. if d.getVarFlag(var, 'python', False) and func:
  114. return False
  115. export = d.getVarFlag(var, "export", False)
  116. unexport = d.getVarFlag(var, "unexport", False)
  117. if not all and not export and not unexport and not func:
  118. return False
  119. try:
  120. if all:
  121. oval = d.getVar(var, False)
  122. val = d.getVar(var)
  123. except (KeyboardInterrupt, bb.build.FuncFailed):
  124. raise
  125. except Exception as exc:
  126. o.write('# expansion of %s threw %s: %s\n' % (var, exc.__class__.__name__, str(exc)))
  127. return False
  128. if all:
  129. d.varhistory.emit(var, oval, val, o, d)
  130. if (var.find("-") != -1 or var.find(".") != -1 or var.find('{') != -1 or var.find('}') != -1 or var.find('+') != -1) and not all:
  131. return False
  132. varExpanded = d.expand(var)
  133. if unexport:
  134. o.write('unset %s\n' % varExpanded)
  135. return False
  136. if val is None:
  137. return False
  138. val = str(val)
  139. if varExpanded.startswith("BASH_FUNC_"):
  140. varExpanded = varExpanded[10:-2]
  141. val = val[3:] # Strip off "() "
  142. o.write("%s() %s\n" % (varExpanded, val))
  143. o.write("export -f %s\n" % (varExpanded))
  144. return True
  145. if func:
  146. # NOTE: should probably check for unbalanced {} within the var
  147. val = val.rstrip('\n')
  148. o.write("%s() {\n%s\n}\n" % (varExpanded, val))
  149. return 1
  150. if export:
  151. o.write('export ')
  152. # if we're going to output this within doublequotes,
  153. # to a shell, we need to escape the quotes in the var
  154. alter = re.sub('"', '\\"', val)
  155. alter = re.sub('\n', ' \\\n', alter)
  156. alter = re.sub('\\$', '\\\\$', alter)
  157. o.write('%s="%s"\n' % (varExpanded, alter))
  158. return False
  159. def emit_env(o=sys.__stdout__, d = init(), all=False):
  160. """Emits all items in the data store in a format such that it can be sourced by a shell."""
  161. isfunc = lambda key: bool(d.getVarFlag(key, "func", False))
  162. keys = sorted((key for key in d.keys() if not key.startswith("__")), key=isfunc)
  163. grouped = groupby(keys, isfunc)
  164. for isfunc, keys in grouped:
  165. for key in sorted(keys):
  166. emit_var(key, o, d, all and not isfunc) and o.write('\n')
  167. def exported_keys(d):
  168. return (key for key in d.keys() if not key.startswith('__') and
  169. d.getVarFlag(key, 'export', False) and
  170. not d.getVarFlag(key, 'unexport', False))
  171. def exported_vars(d):
  172. k = list(exported_keys(d))
  173. for key in k:
  174. try:
  175. value = d.getVar(key)
  176. except Exception as err:
  177. bb.warn("%s: Unable to export ${%s}: %s" % (d.getVar("FILE"), key, err))
  178. continue
  179. if value is not None:
  180. yield key, str(value)
  181. def emit_func(func, o=sys.__stdout__, d = init()):
  182. """Emits all items in the data store in a format such that it can be sourced by a shell."""
  183. keys = (key for key in d.keys() if not key.startswith("__") and not d.getVarFlag(key, "func", False))
  184. for key in sorted(keys):
  185. emit_var(key, o, d, False)
  186. o.write('\n')
  187. emit_var(func, o, d, False) and o.write('\n')
  188. newdeps = bb.codeparser.ShellParser(func, logger).parse_shell(d.getVar(func))
  189. newdeps |= set((d.getVarFlag(func, "vardeps") or "").split())
  190. seen = set()
  191. while newdeps:
  192. deps = newdeps
  193. seen |= deps
  194. newdeps = set()
  195. for dep in deps:
  196. if d.getVarFlag(dep, "func", False) and not d.getVarFlag(dep, "python", False):
  197. emit_var(dep, o, d, False) and o.write('\n')
  198. newdeps |= bb.codeparser.ShellParser(dep, logger).parse_shell(d.getVar(dep))
  199. newdeps |= set((d.getVarFlag(dep, "vardeps") or "").split())
  200. newdeps -= seen
  201. _functionfmt = """
  202. def {function}(d):
  203. {body}"""
  204. def emit_func_python(func, o=sys.__stdout__, d = init()):
  205. """Emits all items in the data store in a format such that it can be sourced by a shell."""
  206. def write_func(func, o, call = False):
  207. body = d.getVar(func, False)
  208. if not body.startswith("def"):
  209. body = _functionfmt.format(function=func, body=body)
  210. o.write(body.strip() + "\n\n")
  211. if call:
  212. o.write(func + "(d)" + "\n\n")
  213. write_func(func, o, True)
  214. pp = bb.codeparser.PythonParser(func, logger)
  215. pp.parse_python(d.getVar(func, False))
  216. newdeps = pp.execs
  217. newdeps |= set((d.getVarFlag(func, "vardeps") or "").split())
  218. seen = set()
  219. while newdeps:
  220. deps = newdeps
  221. seen |= deps
  222. newdeps = set()
  223. for dep in deps:
  224. if d.getVarFlag(dep, "func", False) and d.getVarFlag(dep, "python", False):
  225. write_func(dep, o)
  226. pp = bb.codeparser.PythonParser(dep, logger)
  227. pp.parse_python(d.getVar(dep, False))
  228. newdeps |= pp.execs
  229. newdeps |= set((d.getVarFlag(dep, "vardeps") or "").split())
  230. newdeps -= seen
  231. def update_data(d):
  232. """Performs final steps upon the datastore, including application of overrides"""
  233. d.finalize(parent = True)
  234. def build_dependencies(key, keys, shelldeps, varflagsexcl, d):
  235. deps = set()
  236. try:
  237. if key[-1] == ']':
  238. vf = key[:-1].split('[')
  239. value, parser = d.getVarFlag(vf[0], vf[1], False, retparser=True)
  240. deps |= parser.references
  241. deps = deps | (keys & parser.execs)
  242. return deps, value
  243. varflags = d.getVarFlags(key, ["vardeps", "vardepvalue", "vardepsexclude", "exports", "postfuncs", "prefuncs", "lineno", "filename"]) or {}
  244. vardeps = varflags.get("vardeps")
  245. def handle_contains(value, contains, d):
  246. newvalue = ""
  247. for k in sorted(contains):
  248. l = (d.getVar(k) or "").split()
  249. for item in sorted(contains[k]):
  250. for word in item.split():
  251. if not word in l:
  252. newvalue += "\n%s{%s} = Unset" % (k, item)
  253. break
  254. else:
  255. newvalue += "\n%s{%s} = Set" % (k, item)
  256. if not newvalue:
  257. return value
  258. if not value:
  259. return newvalue
  260. return value + newvalue
  261. def handle_remove(value, deps, removes, d):
  262. for r in sorted(removes):
  263. r2 = d.expandWithRefs(r, None)
  264. value += "\n_remove of %s" % r
  265. deps |= r2.references
  266. deps = deps | (keys & r2.execs)
  267. return value
  268. if "vardepvalue" in varflags:
  269. value = varflags.get("vardepvalue")
  270. elif varflags.get("func"):
  271. if varflags.get("python"):
  272. value = d.getVarFlag(key, "_content", False)
  273. parser = bb.codeparser.PythonParser(key, logger)
  274. if value and "\t" in value:
  275. logger.warning("Variable %s contains tabs, please remove these (%s)" % (key, d.getVar("FILE")))
  276. parser.parse_python(value, filename=varflags.get("filename"), lineno=varflags.get("lineno"))
  277. deps = deps | parser.references
  278. deps = deps | (keys & parser.execs)
  279. value = handle_contains(value, parser.contains, d)
  280. else:
  281. value, parsedvar = d.getVarFlag(key, "_content", False, retparser=True)
  282. parser = bb.codeparser.ShellParser(key, logger)
  283. parser.parse_shell(parsedvar.value)
  284. deps = deps | shelldeps
  285. deps = deps | parsedvar.references
  286. deps = deps | (keys & parser.execs) | (keys & parsedvar.execs)
  287. value = handle_contains(value, parsedvar.contains, d)
  288. if hasattr(parsedvar, "removes"):
  289. value = handle_remove(value, deps, parsedvar.removes, d)
  290. if vardeps is None:
  291. parser.log.flush()
  292. if "prefuncs" in varflags:
  293. deps = deps | set(varflags["prefuncs"].split())
  294. if "postfuncs" in varflags:
  295. deps = deps | set(varflags["postfuncs"].split())
  296. if "exports" in varflags:
  297. deps = deps | set(varflags["exports"].split())
  298. else:
  299. value, parser = d.getVarFlag(key, "_content", False, retparser=True)
  300. deps |= parser.references
  301. deps = deps | (keys & parser.execs)
  302. value = handle_contains(value, parser.contains, d)
  303. if hasattr(parser, "removes"):
  304. value = handle_remove(value, deps, parser.removes, d)
  305. if "vardepvalueexclude" in varflags:
  306. exclude = varflags.get("vardepvalueexclude")
  307. for excl in exclude.split('|'):
  308. if excl:
  309. value = value.replace(excl, '')
  310. # Add varflags, assuming an exclusion list is set
  311. if varflagsexcl:
  312. varfdeps = []
  313. for f in varflags:
  314. if f not in varflagsexcl:
  315. varfdeps.append('%s[%s]' % (key, f))
  316. if varfdeps:
  317. deps |= set(varfdeps)
  318. deps |= set((vardeps or "").split())
  319. deps -= set(varflags.get("vardepsexclude", "").split())
  320. except bb.parse.SkipRecipe:
  321. raise
  322. except Exception as e:
  323. bb.warn("Exception during build_dependencies for %s" % key)
  324. raise
  325. return deps, value
  326. #bb.note("Variable %s references %s and calls %s" % (key, str(deps), str(execs)))
  327. #d.setVarFlag(key, "vardeps", deps)
  328. def generate_dependencies(d):
  329. keys = set(key for key in d if not key.startswith("__"))
  330. shelldeps = set(key for key in d.getVar("__exportlist", False) if d.getVarFlag(key, "export", False) and not d.getVarFlag(key, "unexport", False))
  331. varflagsexcl = d.getVar('BB_SIGNATURE_EXCLUDE_FLAGS')
  332. deps = {}
  333. values = {}
  334. tasklist = d.getVar('__BBTASKS', False) or []
  335. for task in tasklist:
  336. deps[task], values[task] = build_dependencies(task, keys, shelldeps, varflagsexcl, d)
  337. newdeps = deps[task]
  338. seen = set()
  339. while newdeps:
  340. nextdeps = newdeps
  341. seen |= nextdeps
  342. newdeps = set()
  343. for dep in nextdeps:
  344. if dep not in deps:
  345. deps[dep], values[dep] = build_dependencies(dep, keys, shelldeps, varflagsexcl, d)
  346. newdeps |= deps[dep]
  347. newdeps -= seen
  348. #print "For %s: %s" % (task, str(deps[task]))
  349. return tasklist, deps, values
  350. def generate_dependency_hash(tasklist, gendeps, lookupcache, whitelist, fn):
  351. taskdeps = {}
  352. basehash = {}
  353. for task in tasklist:
  354. data = lookupcache[task]
  355. if data is None:
  356. bb.error("Task %s from %s seems to be empty?!" % (task, fn))
  357. data = ''
  358. gendeps[task] -= whitelist
  359. newdeps = gendeps[task]
  360. seen = set()
  361. while newdeps:
  362. nextdeps = newdeps
  363. seen |= nextdeps
  364. newdeps = set()
  365. for dep in nextdeps:
  366. if dep in whitelist:
  367. continue
  368. gendeps[dep] -= whitelist
  369. newdeps |= gendeps[dep]
  370. newdeps -= seen
  371. alldeps = sorted(seen)
  372. for dep in alldeps:
  373. data = data + dep
  374. var = lookupcache[dep]
  375. if var is not None:
  376. data = data + str(var)
  377. k = fn + "." + task
  378. basehash[k] = hashlib.md5(data.encode("utf-8")).hexdigest()
  379. taskdeps[task] = alldeps
  380. return taskdeps, basehash
  381. def inherits_class(klass, d):
  382. val = d.getVar('__inherit_cache', False) or []
  383. needle = os.path.join('classes', '%s.bbclass' % klass)
  384. for v in val:
  385. if v.endswith(needle):
  386. return True
  387. return False