data.py 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443
  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. # Write a comment indicating where the shell function came from (line number and filename) to make it easier
  134. # for the user to diagnose task failures. This comment is also used by build.py to determine the metadata
  135. # location of shell functions.
  136. o.write("# line: {0}, file: {1}\n".format(
  137. d.getVarFlag(var, "lineno", False),
  138. d.getVarFlag(var, "filename", False)))
  139. # NOTE: should probably check for unbalanced {} within the var
  140. val = val.rstrip('\n')
  141. o.write("%s() {\n%s\n}\n" % (varExpanded, val))
  142. return 1
  143. if export:
  144. o.write('export ')
  145. # if we're going to output this within doublequotes,
  146. # to a shell, we need to escape the quotes in the var
  147. alter = re.sub('"', '\\"', val)
  148. alter = re.sub('\n', ' \\\n', alter)
  149. alter = re.sub('\\$', '\\\\$', alter)
  150. o.write('%s="%s"\n' % (varExpanded, alter))
  151. return False
  152. def emit_env(o=sys.__stdout__, d = init(), all=False):
  153. """Emits all items in the data store in a format such that it can be sourced by a shell."""
  154. isfunc = lambda key: bool(d.getVarFlag(key, "func", False))
  155. keys = sorted((key for key in d.keys() if not key.startswith("__")), key=isfunc)
  156. grouped = groupby(keys, isfunc)
  157. for isfunc, keys in grouped:
  158. for key in sorted(keys):
  159. emit_var(key, o, d, all and not isfunc) and o.write('\n')
  160. def exported_keys(d):
  161. return (key for key in d.keys() if not key.startswith('__') and
  162. d.getVarFlag(key, 'export', False) and
  163. not d.getVarFlag(key, 'unexport', False))
  164. def exported_vars(d):
  165. k = list(exported_keys(d))
  166. for key in k:
  167. try:
  168. value = d.getVar(key)
  169. except Exception as err:
  170. bb.warn("%s: Unable to export ${%s}: %s" % (d.getVar("FILE"), key, err))
  171. continue
  172. if value is not None:
  173. yield key, str(value)
  174. def emit_func(func, o=sys.__stdout__, d = init()):
  175. """Emits all items in the data store in a format such that it can be sourced by a shell."""
  176. keys = (key for key in d.keys() if not key.startswith("__") and not d.getVarFlag(key, "func", False))
  177. for key in sorted(keys):
  178. emit_var(key, o, d, False)
  179. o.write('\n')
  180. emit_var(func, o, d, False) and o.write('\n')
  181. newdeps = bb.codeparser.ShellParser(func, logger).parse_shell(d.getVar(func))
  182. newdeps |= set((d.getVarFlag(func, "vardeps") or "").split())
  183. seen = set()
  184. while newdeps:
  185. deps = newdeps
  186. seen |= deps
  187. newdeps = set()
  188. for dep in deps:
  189. if d.getVarFlag(dep, "func", False) and not d.getVarFlag(dep, "python", False):
  190. emit_var(dep, o, d, False) and o.write('\n')
  191. newdeps |= bb.codeparser.ShellParser(dep, logger).parse_shell(d.getVar(dep))
  192. newdeps |= set((d.getVarFlag(dep, "vardeps") or "").split())
  193. newdeps -= seen
  194. _functionfmt = """
  195. def {function}(d):
  196. {body}"""
  197. def emit_func_python(func, o=sys.__stdout__, d = init()):
  198. """Emits all items in the data store in a format such that it can be sourced by a shell."""
  199. def write_func(func, o, call = False):
  200. body = d.getVar(func, False)
  201. if not body.startswith("def"):
  202. body = _functionfmt.format(function=func, body=body)
  203. o.write(body.strip() + "\n\n")
  204. if call:
  205. o.write(func + "(d)" + "\n\n")
  206. write_func(func, o, True)
  207. pp = bb.codeparser.PythonParser(func, logger)
  208. pp.parse_python(d.getVar(func, False))
  209. newdeps = pp.execs
  210. newdeps |= set((d.getVarFlag(func, "vardeps") or "").split())
  211. seen = set()
  212. while newdeps:
  213. deps = newdeps
  214. seen |= deps
  215. newdeps = set()
  216. for dep in deps:
  217. if d.getVarFlag(dep, "func", False) and d.getVarFlag(dep, "python", False):
  218. write_func(dep, o)
  219. pp = bb.codeparser.PythonParser(dep, logger)
  220. pp.parse_python(d.getVar(dep, False))
  221. newdeps |= pp.execs
  222. newdeps |= set((d.getVarFlag(dep, "vardeps") or "").split())
  223. newdeps -= seen
  224. def update_data(d):
  225. """Performs final steps upon the datastore, including application of overrides"""
  226. d.finalize(parent = True)
  227. def build_dependencies(key, keys, shelldeps, varflagsexcl, d):
  228. deps = set()
  229. try:
  230. if key[-1] == ']':
  231. vf = key[:-1].split('[')
  232. value, parser = d.getVarFlag(vf[0], vf[1], False, retparser=True)
  233. deps |= parser.references
  234. deps = deps | (keys & parser.execs)
  235. return deps, value
  236. varflags = d.getVarFlags(key, ["vardeps", "vardepvalue", "vardepsexclude", "exports", "postfuncs", "prefuncs", "lineno", "filename"]) or {}
  237. vardeps = varflags.get("vardeps")
  238. def handle_contains(value, contains, d):
  239. newvalue = ""
  240. for k in sorted(contains):
  241. l = (d.getVar(k) or "").split()
  242. for item in sorted(contains[k]):
  243. for word in item.split():
  244. if not word in l:
  245. newvalue += "\n%s{%s} = Unset" % (k, item)
  246. break
  247. else:
  248. newvalue += "\n%s{%s} = Set" % (k, item)
  249. if not newvalue:
  250. return value
  251. if not value:
  252. return newvalue
  253. return value + newvalue
  254. def handle_remove(value, deps, removes, d):
  255. for r in sorted(removes):
  256. r2 = d.expandWithRefs(r, None)
  257. value += "\n_remove of %s" % r
  258. deps |= r2.references
  259. deps = deps | (keys & r2.execs)
  260. return value
  261. if "vardepvalue" in varflags:
  262. value = varflags.get("vardepvalue")
  263. elif varflags.get("func"):
  264. if varflags.get("python"):
  265. value = d.getVarFlag(key, "_content", False)
  266. parser = bb.codeparser.PythonParser(key, logger)
  267. parser.parse_python(value, filename=varflags.get("filename"), lineno=varflags.get("lineno"))
  268. deps = deps | parser.references
  269. deps = deps | (keys & parser.execs)
  270. value = handle_contains(value, parser.contains, d)
  271. else:
  272. value, parsedvar = d.getVarFlag(key, "_content", False, retparser=True)
  273. parser = bb.codeparser.ShellParser(key, logger)
  274. parser.parse_shell(parsedvar.value)
  275. deps = deps | shelldeps
  276. deps = deps | parsedvar.references
  277. deps = deps | (keys & parser.execs) | (keys & parsedvar.execs)
  278. value = handle_contains(value, parsedvar.contains, d)
  279. if hasattr(parsedvar, "removes"):
  280. value = handle_remove(value, deps, parsedvar.removes, d)
  281. if vardeps is None:
  282. parser.log.flush()
  283. if "prefuncs" in varflags:
  284. deps = deps | set(varflags["prefuncs"].split())
  285. if "postfuncs" in varflags:
  286. deps = deps | set(varflags["postfuncs"].split())
  287. if "exports" in varflags:
  288. deps = deps | set(varflags["exports"].split())
  289. else:
  290. value, parser = d.getVarFlag(key, "_content", False, retparser=True)
  291. deps |= parser.references
  292. deps = deps | (keys & parser.execs)
  293. value = handle_contains(value, parser.contains, d)
  294. if hasattr(parser, "removes"):
  295. value = handle_remove(value, deps, parser.removes, d)
  296. if "vardepvalueexclude" in varflags:
  297. exclude = varflags.get("vardepvalueexclude")
  298. for excl in exclude.split('|'):
  299. if excl:
  300. value = value.replace(excl, '')
  301. # Add varflags, assuming an exclusion list is set
  302. if varflagsexcl:
  303. varfdeps = []
  304. for f in varflags:
  305. if f not in varflagsexcl:
  306. varfdeps.append('%s[%s]' % (key, f))
  307. if varfdeps:
  308. deps |= set(varfdeps)
  309. deps |= set((vardeps or "").split())
  310. deps -= set(varflags.get("vardepsexclude", "").split())
  311. except bb.parse.SkipRecipe:
  312. raise
  313. except Exception as e:
  314. bb.warn("Exception during build_dependencies for %s" % key)
  315. raise
  316. return deps, value
  317. #bb.note("Variable %s references %s and calls %s" % (key, str(deps), str(execs)))
  318. #d.setVarFlag(key, "vardeps", deps)
  319. def generate_dependencies(d, whitelist):
  320. keys = set(key for key in d if not key.startswith("__"))
  321. shelldeps = set(key for key in d.getVar("__exportlist", False) if d.getVarFlag(key, "export", False) and not d.getVarFlag(key, "unexport", False))
  322. varflagsexcl = d.getVar('BB_SIGNATURE_EXCLUDE_FLAGS')
  323. deps = {}
  324. values = {}
  325. tasklist = d.getVar('__BBTASKS', False) or []
  326. for task in tasklist:
  327. deps[task], values[task] = build_dependencies(task, keys, shelldeps, varflagsexcl, d)
  328. newdeps = deps[task]
  329. seen = set()
  330. while newdeps:
  331. nextdeps = newdeps - whitelist
  332. seen |= nextdeps
  333. newdeps = set()
  334. for dep in nextdeps:
  335. if dep not in deps:
  336. deps[dep], values[dep] = build_dependencies(dep, keys, shelldeps, varflagsexcl, d)
  337. newdeps |= deps[dep]
  338. newdeps -= seen
  339. #print "For %s: %s" % (task, str(deps[task]))
  340. return tasklist, deps, values
  341. def generate_dependency_hash(tasklist, gendeps, lookupcache, whitelist, fn):
  342. taskdeps = {}
  343. basehash = {}
  344. for task in tasklist:
  345. data = lookupcache[task]
  346. if data is None:
  347. bb.error("Task %s from %s seems to be empty?!" % (task, fn))
  348. data = ''
  349. gendeps[task] -= whitelist
  350. newdeps = gendeps[task]
  351. seen = set()
  352. while newdeps:
  353. nextdeps = newdeps
  354. seen |= nextdeps
  355. newdeps = set()
  356. for dep in nextdeps:
  357. if dep in whitelist:
  358. continue
  359. gendeps[dep] -= whitelist
  360. newdeps |= gendeps[dep]
  361. newdeps -= seen
  362. alldeps = sorted(seen)
  363. for dep in alldeps:
  364. data = data + dep
  365. var = lookupcache[dep]
  366. if var is not None:
  367. data = data + str(var)
  368. k = fn + ":" + task
  369. basehash[k] = hashlib.sha256(data.encode("utf-8")).hexdigest()
  370. taskdeps[task] = alldeps
  371. return taskdeps, basehash
  372. def inherits_class(klass, d):
  373. val = d.getVar('__inherit_cache', False) or []
  374. needle = os.path.join('classes', '%s.bbclass' % klass)
  375. for v in val:
  376. if v.endswith(needle):
  377. return True
  378. return False