data.py 15 KB

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