data.py 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393
  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 expandData 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 treade-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. if sys.argv[0][-5:] == "pydoc":
  37. path = os.path.dirname(os.path.dirname(sys.argv[1]))
  38. else:
  39. path = os.path.dirname(os.path.dirname(sys.argv[0]))
  40. sys.path.insert(0, path)
  41. from itertools import groupby
  42. from bb import data_smart
  43. from bb import codeparser
  44. import bb
  45. logger = data_smart.logger
  46. _dict_type = data_smart.DataSmart
  47. def init():
  48. """Return a new object representing the Bitbake data"""
  49. return _dict_type()
  50. def init_db(parent = None):
  51. """Return a new object representing the Bitbake data,
  52. optionally based on an existing object"""
  53. if parent is not None:
  54. return parent.createCopy()
  55. else:
  56. return _dict_type()
  57. def createCopy(source):
  58. """Link the source set to the destination
  59. If one does not find the value in the destination set,
  60. search will go on to the source set to get the value.
  61. Value from source are copy-on-write. i.e. any try to
  62. modify one of them will end up putting the modified value
  63. in the destination set.
  64. """
  65. return source.createCopy()
  66. def initVar(var, d):
  67. """Non-destructive var init for data structure"""
  68. d.initVar(var)
  69. def setVar(var, value, d):
  70. """Set a variable to a given value"""
  71. d.setVar(var, value)
  72. def getVar(var, d, exp = 0):
  73. """Gets the value of a variable"""
  74. return d.getVar(var, exp)
  75. def renameVar(key, newkey, d):
  76. """Renames a variable from key to newkey"""
  77. d.renameVar(key, newkey)
  78. def delVar(var, d):
  79. """Removes a variable from the data set"""
  80. d.delVar(var)
  81. def appendVar(var, value, d):
  82. """Append additional value to a variable"""
  83. d.appendVar(var, value)
  84. def setVarFlag(var, flag, flagvalue, d):
  85. """Set a flag for a given variable to a given value"""
  86. d.setVarFlag(var, flag, flagvalue)
  87. def getVarFlag(var, flag, d):
  88. """Gets given flag from given var"""
  89. return d.getVarFlag(var, flag)
  90. def delVarFlag(var, flag, d):
  91. """Removes a given flag from the variable's flags"""
  92. d.delVarFlag(var, flag)
  93. def setVarFlags(var, flags, d):
  94. """Set the flags for a given variable
  95. Note:
  96. setVarFlags will not clear previous
  97. flags. Think of this method as
  98. addVarFlags
  99. """
  100. d.setVarFlags(var, flags)
  101. def getVarFlags(var, d):
  102. """Gets a variable's flags"""
  103. return d.getVarFlags(var)
  104. def delVarFlags(var, d):
  105. """Removes a variable's flags"""
  106. d.delVarFlags(var)
  107. def keys(d):
  108. """Return a list of keys in d"""
  109. return d.keys()
  110. __expand_var_regexp__ = re.compile(r"\${[^{}]+}")
  111. __expand_python_regexp__ = re.compile(r"\${@.+?}")
  112. def expand(s, d, varname = None):
  113. """Variable expansion using the data store"""
  114. return d.expand(s, varname)
  115. def expandKeys(alterdata, readdata = None):
  116. if readdata == None:
  117. readdata = alterdata
  118. todolist = {}
  119. for key in alterdata:
  120. if not '${' in key:
  121. continue
  122. ekey = expand(key, readdata)
  123. if key == ekey:
  124. continue
  125. todolist[key] = ekey
  126. # These two for loops are split for performance to maximise the
  127. # usefulness of the expand cache
  128. for key in todolist:
  129. ekey = todolist[key]
  130. newval = alterdata.getVar(ekey, 0)
  131. if newval:
  132. val = alterdata.getVar(key, 0)
  133. if val is not None and newval is not None:
  134. bb.warn("Variable key %s (%s) replaces original key %s (%s)." % (key, val, ekey, newval))
  135. alterdata.renameVar(key, ekey)
  136. def inheritFromOS(d, savedenv, permitted):
  137. """Inherit variables from the initial environment."""
  138. exportlist = bb.utils.preserved_envvars_exported()
  139. for s in savedenv.keys():
  140. if s in permitted:
  141. try:
  142. d.setVar(s, getVar(s, savedenv, True), op = 'from env')
  143. if s in exportlist:
  144. d.setVarFlag(s, "export", True, op = 'auto env export')
  145. except TypeError:
  146. pass
  147. def emit_var(var, o=sys.__stdout__, d = init(), all=False):
  148. """Emit a variable to be sourced by a shell."""
  149. if getVarFlag(var, "python", d):
  150. return 0
  151. export = getVarFlag(var, "export", d)
  152. unexport = getVarFlag(var, "unexport", d)
  153. func = getVarFlag(var, "func", d)
  154. if not all and not export and not unexport and not func:
  155. return 0
  156. try:
  157. if all:
  158. oval = getVar(var, d, 0)
  159. val = getVar(var, d, 1)
  160. except (KeyboardInterrupt, bb.build.FuncFailed):
  161. raise
  162. except Exception as exc:
  163. o.write('# expansion of %s threw %s: %s\n' % (var, exc.__class__.__name__, str(exc)))
  164. return 0
  165. if all:
  166. d.varhistory.emit(var, oval, val, o)
  167. if (var.find("-") != -1 or var.find(".") != -1 or var.find('{') != -1 or var.find('}') != -1 or var.find('+') != -1) and not all:
  168. return 0
  169. varExpanded = expand(var, d)
  170. if unexport:
  171. o.write('unset %s\n' % varExpanded)
  172. return 0
  173. if val is None:
  174. return 0
  175. val = str(val)
  176. if func:
  177. # NOTE: should probably check for unbalanced {} within the var
  178. o.write("%s() {\n%s\n}\n" % (varExpanded, val))
  179. return 1
  180. if export:
  181. o.write('export ')
  182. # if we're going to output this within doublequotes,
  183. # to a shell, we need to escape the quotes in the var
  184. alter = re.sub('"', '\\"', val)
  185. alter = re.sub('\n', ' \\\n', alter)
  186. o.write('%s="%s"\n' % (varExpanded, alter))
  187. return 0
  188. def emit_env(o=sys.__stdout__, d = init(), all=False):
  189. """Emits all items in the data store in a format such that it can be sourced by a shell."""
  190. isfunc = lambda key: bool(d.getVarFlag(key, "func"))
  191. keys = sorted((key for key in d.keys() if not key.startswith("__")), key=isfunc)
  192. grouped = groupby(keys, isfunc)
  193. for isfunc, keys in grouped:
  194. for key in keys:
  195. emit_var(key, o, d, all and not isfunc) and o.write('\n')
  196. def exported_keys(d):
  197. return (key for key in d.keys() if not key.startswith('__') and
  198. d.getVarFlag(key, 'export') and
  199. not d.getVarFlag(key, 'unexport'))
  200. def exported_vars(d):
  201. for key in exported_keys(d):
  202. try:
  203. value = d.getVar(key, True)
  204. except Exception:
  205. pass
  206. if value is not None:
  207. yield key, str(value)
  208. def emit_func(func, o=sys.__stdout__, d = init()):
  209. """Emits all items in the data store in a format such that it can be sourced by a shell."""
  210. keys = (key for key in d.keys() if not key.startswith("__") and not d.getVarFlag(key, "func"))
  211. for key in keys:
  212. emit_var(key, o, d, False) and o.write('\n')
  213. emit_var(func, o, d, False) and o.write('\n')
  214. newdeps = bb.codeparser.ShellParser(func, logger).parse_shell(d.getVar(func, True))
  215. newdeps |= set((d.getVarFlag(func, "vardeps", True) or "").split())
  216. seen = set()
  217. while newdeps:
  218. deps = newdeps
  219. seen |= deps
  220. newdeps = set()
  221. for dep in deps:
  222. if d.getVarFlag(dep, "func"):
  223. emit_var(dep, o, d, False) and o.write('\n')
  224. newdeps |= bb.codeparser.ShellParser(dep, logger).parse_shell(d.getVar(dep, True))
  225. newdeps |= set((d.getVarFlag(dep, "vardeps", True) or "").split())
  226. newdeps -= seen
  227. def update_data(d):
  228. """Performs final steps upon the datastore, including application of overrides"""
  229. d.finalize(parent = True)
  230. def build_dependencies(key, keys, shelldeps, varflagsexcl, d):
  231. deps = set()
  232. try:
  233. if key[-1] == ']':
  234. vf = key[:-1].split('[')
  235. value = d.getVarFlag(vf[0], vf[1], False)
  236. parser = d.expandWithRefs(value, key)
  237. deps |= parser.references
  238. deps = deps | (keys & parser.execs)
  239. return deps, value
  240. varflags = d.getVarFlags(key, ["vardeps", "vardepvalue", "vardepsexclude"]) or {}
  241. vardeps = varflags.get("vardeps")
  242. value = d.getVar(key, False)
  243. def handle_contains(value, contains, d):
  244. newvalue = ""
  245. for k in sorted(contains):
  246. l = (d.getVar(k, True) or "").split()
  247. for word in sorted(contains[k]):
  248. if word in l:
  249. newvalue += "\n%s{%s} = Set" % (k, word)
  250. else:
  251. newvalue += "\n%s{%s} = Unset" % (k, word)
  252. if not newvalue:
  253. return value
  254. if not value:
  255. return newvalue
  256. return value + newvalue
  257. if "vardepvalue" in varflags:
  258. value = varflags.get("vardepvalue")
  259. elif varflags.get("func"):
  260. if varflags.get("python"):
  261. parsedvar = d.expandWithRefs(value, key)
  262. parser = bb.codeparser.PythonParser(key, logger)
  263. if parsedvar.value and "\t" in parsedvar.value:
  264. logger.warn("Variable %s contains tabs, please remove these (%s)" % (key, d.getVar("FILE", True)))
  265. parser.parse_python(parsedvar.value)
  266. deps = deps | parser.references
  267. value = handle_contains(value, parser.contains, d)
  268. else:
  269. parsedvar = d.expandWithRefs(value, key)
  270. parser = bb.codeparser.ShellParser(key, logger)
  271. parser.parse_shell(parsedvar.value)
  272. deps = deps | shelldeps
  273. if vardeps is None:
  274. parser.log.flush()
  275. deps = deps | parsedvar.references
  276. deps = deps | (keys & parser.execs) | (keys & parsedvar.execs)
  277. value = handle_contains(value, parsedvar.contains, d)
  278. else:
  279. parser = d.expandWithRefs(value, key)
  280. deps |= parser.references
  281. deps = deps | (keys & parser.execs)
  282. value = handle_contains(value, parser.contains, d)
  283. # Add varflags, assuming an exclusion list is set
  284. if varflagsexcl:
  285. varfdeps = []
  286. for f in varflags:
  287. if f not in varflagsexcl:
  288. varfdeps.append('%s[%s]' % (key, f))
  289. if varfdeps:
  290. deps |= set(varfdeps)
  291. deps |= set((vardeps or "").split())
  292. deps -= set(varflags.get("vardepsexclude", "").split())
  293. except Exception as e:
  294. raise bb.data_smart.ExpansionError(key, None, e)
  295. return deps, value
  296. #bb.note("Variable %s references %s and calls %s" % (key, str(deps), str(execs)))
  297. #d.setVarFlag(key, "vardeps", deps)
  298. def generate_dependencies(d):
  299. keys = set(key for key in d if not key.startswith("__"))
  300. shelldeps = set(key for key in d.getVar("__exportlist", False) if d.getVarFlag(key, "export") and not d.getVarFlag(key, "unexport"))
  301. varflagsexcl = d.getVar('BB_SIGNATURE_EXCLUDE_FLAGS', True)
  302. deps = {}
  303. values = {}
  304. tasklist = d.getVar('__BBTASKS') or []
  305. for task in tasklist:
  306. deps[task], values[task] = build_dependencies(task, keys, shelldeps, varflagsexcl, d)
  307. newdeps = deps[task]
  308. seen = set()
  309. while newdeps:
  310. nextdeps = newdeps
  311. seen |= nextdeps
  312. newdeps = set()
  313. for dep in nextdeps:
  314. if dep not in deps:
  315. deps[dep], values[dep] = build_dependencies(dep, keys, shelldeps, varflagsexcl, d)
  316. newdeps |= deps[dep]
  317. newdeps -= seen
  318. #print "For %s: %s" % (task, str(deps[task]))
  319. return tasklist, deps, values
  320. def inherits_class(klass, d):
  321. val = getVar('__inherit_cache', d) or []
  322. needle = os.path.join('classes', '%s.bbclass' % klass)
  323. for v in val:
  324. if v.endswith(needle):
  325. return True
  326. return False