data.py 15 KB

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