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. # SPDX-License-Identifier: GPL-2.0-only
  22. #
  23. # This program is free software; you can redistribute it and/or modify
  24. # it under the terms of the GNU General Public License version 2 as
  25. # published by the Free Software Foundation.
  26. #
  27. # This program is distributed in the hope that it will be useful,
  28. # but WITHOUT ANY WARRANTY; without even the implied warranty of
  29. # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  30. # GNU General Public License for more details.
  31. #
  32. # You should have received a copy of the GNU General Public License along
  33. # with this program; if not, write to the Free Software Foundation, Inc.,
  34. # 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
  35. #
  36. # Based on functions from the base bb module, Copyright 2003 Holger Schurig
  37. import sys, os, re
  38. import hashlib
  39. if sys.argv[0][-5:] == "pydoc":
  40. path = os.path.dirname(os.path.dirname(sys.argv[1]))
  41. else:
  42. path = os.path.dirname(os.path.dirname(sys.argv[0]))
  43. sys.path.insert(0, path)
  44. from itertools import groupby
  45. from bb import data_smart
  46. from bb import codeparser
  47. import bb
  48. logger = data_smart.logger
  49. _dict_type = data_smart.DataSmart
  50. def init():
  51. """Return a new object representing the Bitbake data"""
  52. return _dict_type()
  53. def init_db(parent = None):
  54. """Return a new object representing the Bitbake data,
  55. optionally based on an existing object"""
  56. if parent is not None:
  57. return parent.createCopy()
  58. else:
  59. return _dict_type()
  60. def createCopy(source):
  61. """Link the source set to the destination
  62. If one does not find the value in the destination set,
  63. search will go on to the source set to get the value.
  64. Value from source are copy-on-write. i.e. any try to
  65. modify one of them will end up putting the modified value
  66. in the destination set.
  67. """
  68. return source.createCopy()
  69. def initVar(var, d):
  70. """Non-destructive var init for data structure"""
  71. d.initVar(var)
  72. def keys(d):
  73. """Return a list of keys in d"""
  74. return d.keys()
  75. __expand_var_regexp__ = re.compile(r"\${[^{}]+}")
  76. __expand_python_regexp__ = re.compile(r"\${@.+?}")
  77. def expand(s, d, varname = None):
  78. """Variable expansion using the data store"""
  79. return d.expand(s, varname)
  80. def expandKeys(alterdata, readdata = None):
  81. if readdata == None:
  82. readdata = alterdata
  83. todolist = {}
  84. for key in alterdata:
  85. if not '${' in key:
  86. continue
  87. ekey = expand(key, readdata)
  88. if key == ekey:
  89. continue
  90. todolist[key] = ekey
  91. # These two for loops are split for performance to maximise the
  92. # usefulness of the expand cache
  93. for key in sorted(todolist):
  94. ekey = todolist[key]
  95. newval = alterdata.getVar(ekey, False)
  96. if newval is not None:
  97. val = alterdata.getVar(key, False)
  98. if val is not None:
  99. bb.warn("Variable key %s (%s) replaces original key %s (%s)." % (key, val, ekey, newval))
  100. alterdata.renameVar(key, ekey)
  101. def inheritFromOS(d, savedenv, permitted):
  102. """Inherit variables from the initial environment."""
  103. exportlist = bb.utils.preserved_envvars_exported()
  104. for s in savedenv.keys():
  105. if s in permitted:
  106. try:
  107. d.setVar(s, savedenv.getVar(s), op = 'from env')
  108. if s in exportlist:
  109. d.setVarFlag(s, "export", True, op = 'auto env export')
  110. except TypeError:
  111. pass
  112. def emit_var(var, o=sys.__stdout__, d = init(), all=False):
  113. """Emit a variable to be sourced by a shell."""
  114. func = d.getVarFlag(var, "func", False)
  115. if d.getVarFlag(var, 'python', False) and func:
  116. return False
  117. export = d.getVarFlag(var, "export", False)
  118. unexport = d.getVarFlag(var, "unexport", False)
  119. if not all and not export and not unexport and not func:
  120. return False
  121. try:
  122. if all:
  123. oval = d.getVar(var, False)
  124. val = d.getVar(var)
  125. except (KeyboardInterrupt, bb.build.FuncFailed):
  126. raise
  127. except Exception as exc:
  128. o.write('# expansion of %s threw %s: %s\n' % (var, exc.__class__.__name__, str(exc)))
  129. return False
  130. if all:
  131. d.varhistory.emit(var, oval, val, o, d)
  132. if (var.find("-") != -1 or var.find(".") != -1 or var.find('{') != -1 or var.find('}') != -1 or var.find('+') != -1) and not all:
  133. return False
  134. varExpanded = d.expand(var)
  135. if unexport:
  136. o.write('unset %s\n' % varExpanded)
  137. return False
  138. if val is None:
  139. return False
  140. val = str(val)
  141. if varExpanded.startswith("BASH_FUNC_"):
  142. varExpanded = varExpanded[10:-2]
  143. val = val[3:] # Strip off "() "
  144. o.write("%s() %s\n" % (varExpanded, val))
  145. o.write("export -f %s\n" % (varExpanded))
  146. return True
  147. if func:
  148. # NOTE: should probably check for unbalanced {} within the var
  149. val = val.rstrip('\n')
  150. o.write("%s() {\n%s\n}\n" % (varExpanded, val))
  151. return 1
  152. if export:
  153. o.write('export ')
  154. # if we're going to output this within doublequotes,
  155. # to a shell, we need to escape the quotes in the var
  156. alter = re.sub('"', '\\"', val)
  157. alter = re.sub('\n', ' \\\n', alter)
  158. alter = re.sub('\\$', '\\\\$', alter)
  159. o.write('%s="%s"\n' % (varExpanded, alter))
  160. return False
  161. def emit_env(o=sys.__stdout__, d = init(), all=False):
  162. """Emits all items in the data store in a format such that it can be sourced by a shell."""
  163. isfunc = lambda key: bool(d.getVarFlag(key, "func", False))
  164. keys = sorted((key for key in d.keys() if not key.startswith("__")), key=isfunc)
  165. grouped = groupby(keys, isfunc)
  166. for isfunc, keys in grouped:
  167. for key in sorted(keys):
  168. emit_var(key, o, d, all and not isfunc) and o.write('\n')
  169. def exported_keys(d):
  170. return (key for key in d.keys() if not key.startswith('__') and
  171. d.getVarFlag(key, 'export', False) and
  172. not d.getVarFlag(key, 'unexport', False))
  173. def exported_vars(d):
  174. k = list(exported_keys(d))
  175. for key in k:
  176. try:
  177. value = d.getVar(key)
  178. except Exception as err:
  179. bb.warn("%s: Unable to export ${%s}: %s" % (d.getVar("FILE"), key, err))
  180. continue
  181. if value is not None:
  182. yield key, str(value)
  183. def emit_func(func, o=sys.__stdout__, d = init()):
  184. """Emits all items in the data store in a format such that it can be sourced by a shell."""
  185. keys = (key for key in d.keys() if not key.startswith("__") and not d.getVarFlag(key, "func", False))
  186. for key in sorted(keys):
  187. emit_var(key, o, d, False)
  188. o.write('\n')
  189. emit_var(func, o, d, False) and o.write('\n')
  190. newdeps = bb.codeparser.ShellParser(func, logger).parse_shell(d.getVar(func))
  191. newdeps |= set((d.getVarFlag(func, "vardeps") or "").split())
  192. seen = set()
  193. while newdeps:
  194. deps = newdeps
  195. seen |= deps
  196. newdeps = set()
  197. for dep in deps:
  198. if d.getVarFlag(dep, "func", False) and not d.getVarFlag(dep, "python", False):
  199. emit_var(dep, o, d, False) and o.write('\n')
  200. newdeps |= bb.codeparser.ShellParser(dep, logger).parse_shell(d.getVar(dep))
  201. newdeps |= set((d.getVarFlag(dep, "vardeps") or "").split())
  202. newdeps -= seen
  203. _functionfmt = """
  204. def {function}(d):
  205. {body}"""
  206. def emit_func_python(func, o=sys.__stdout__, d = init()):
  207. """Emits all items in the data store in a format such that it can be sourced by a shell."""
  208. def write_func(func, o, call = False):
  209. body = d.getVar(func, False)
  210. if not body.startswith("def"):
  211. body = _functionfmt.format(function=func, body=body)
  212. o.write(body.strip() + "\n\n")
  213. if call:
  214. o.write(func + "(d)" + "\n\n")
  215. write_func(func, o, True)
  216. pp = bb.codeparser.PythonParser(func, logger)
  217. pp.parse_python(d.getVar(func, False))
  218. newdeps = pp.execs
  219. newdeps |= set((d.getVarFlag(func, "vardeps") or "").split())
  220. seen = set()
  221. while newdeps:
  222. deps = newdeps
  223. seen |= deps
  224. newdeps = set()
  225. for dep in deps:
  226. if d.getVarFlag(dep, "func", False) and d.getVarFlag(dep, "python", False):
  227. write_func(dep, o)
  228. pp = bb.codeparser.PythonParser(dep, logger)
  229. pp.parse_python(d.getVar(dep, False))
  230. newdeps |= pp.execs
  231. newdeps |= set((d.getVarFlag(dep, "vardeps") or "").split())
  232. newdeps -= seen
  233. def update_data(d):
  234. """Performs final steps upon the datastore, including application of overrides"""
  235. d.finalize(parent = True)
  236. def build_dependencies(key, keys, shelldeps, varflagsexcl, d):
  237. deps = set()
  238. try:
  239. if key[-1] == ']':
  240. vf = key[:-1].split('[')
  241. value, parser = d.getVarFlag(vf[0], vf[1], False, retparser=True)
  242. deps |= parser.references
  243. deps = deps | (keys & parser.execs)
  244. return deps, value
  245. varflags = d.getVarFlags(key, ["vardeps", "vardepvalue", "vardepsexclude", "exports", "postfuncs", "prefuncs", "lineno", "filename"]) or {}
  246. vardeps = varflags.get("vardeps")
  247. def handle_contains(value, contains, d):
  248. newvalue = ""
  249. for k in sorted(contains):
  250. l = (d.getVar(k) or "").split()
  251. for item in sorted(contains[k]):
  252. for word in item.split():
  253. if not word in l:
  254. newvalue += "\n%s{%s} = Unset" % (k, item)
  255. break
  256. else:
  257. newvalue += "\n%s{%s} = Set" % (k, item)
  258. if not newvalue:
  259. return value
  260. if not value:
  261. return newvalue
  262. return value + newvalue
  263. def handle_remove(value, deps, removes, d):
  264. for r in sorted(removes):
  265. r2 = d.expandWithRefs(r, None)
  266. value += "\n_remove of %s" % r
  267. deps |= r2.references
  268. deps = deps | (keys & r2.execs)
  269. return value
  270. if "vardepvalue" in varflags:
  271. value = varflags.get("vardepvalue")
  272. elif varflags.get("func"):
  273. if varflags.get("python"):
  274. value = d.getVarFlag(key, "_content", False)
  275. parser = bb.codeparser.PythonParser(key, logger)
  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.sha256(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