data.py 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448
  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. # 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 = False):
  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, False)
  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 sorted(todolist):
  129. ekey = todolist[key]
  130. newval = alterdata.getVar(ekey, False)
  131. if newval is not None:
  132. val = alterdata.getVar(key, False)
  133. if val 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, savedenv.getVar(s, 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. func = d.getVarFlag(var, "func", False)
  150. if d.getVarFlag(var, 'python', False) and func:
  151. return False
  152. export = d.getVarFlag(var, "export", False)
  153. unexport = d.getVarFlag(var, "unexport", False)
  154. if not all and not export and not unexport and not func:
  155. return False
  156. try:
  157. if all:
  158. oval = d.getVar(var, False)
  159. val = d.getVar(var, True)
  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 False
  165. if all:
  166. d.varhistory.emit(var, oval, val, o, d)
  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 False
  169. varExpanded = d.expand(var)
  170. if unexport:
  171. o.write('unset %s\n' % varExpanded)
  172. return False
  173. if val is None:
  174. return False
  175. val = str(val)
  176. if varExpanded.startswith("BASH_FUNC_"):
  177. varExpanded = varExpanded[10:-2]
  178. val = val[3:] # Strip off "() "
  179. o.write("%s() %s\n" % (varExpanded, val))
  180. o.write("export -f %s\n" % (varExpanded))
  181. return True
  182. if func:
  183. # NOTE: should probably check for unbalanced {} within the var
  184. val = val.rstrip('\n')
  185. o.write("%s() {\n%s\n}\n" % (varExpanded, val))
  186. return 1
  187. if export:
  188. o.write('export ')
  189. # if we're going to output this within doublequotes,
  190. # to a shell, we need to escape the quotes in the var
  191. alter = re.sub('"', '\\"', val)
  192. alter = re.sub('\n', ' \\\n', alter)
  193. alter = re.sub('\\$', '\\\\$', alter)
  194. o.write('%s="%s"\n' % (varExpanded, alter))
  195. return False
  196. def emit_env(o=sys.__stdout__, d = init(), all=False):
  197. """Emits all items in the data store in a format such that it can be sourced by a shell."""
  198. isfunc = lambda key: bool(d.getVarFlag(key, "func", False))
  199. keys = sorted((key for key in d.keys() if not key.startswith("__")), key=isfunc)
  200. grouped = groupby(keys, isfunc)
  201. for isfunc, keys in grouped:
  202. for key in keys:
  203. emit_var(key, o, d, all and not isfunc) and o.write('\n')
  204. def exported_keys(d):
  205. return (key for key in d.keys() if not key.startswith('__') and
  206. d.getVarFlag(key, 'export', False) and
  207. not d.getVarFlag(key, 'unexport', False))
  208. def exported_vars(d):
  209. for key in exported_keys(d):
  210. try:
  211. value = d.getVar(key, True)
  212. except Exception:
  213. pass
  214. if value is not None:
  215. yield key, str(value)
  216. def emit_func(func, o=sys.__stdout__, d = init()):
  217. """Emits all items in the data store in a format such that it can be sourced by a shell."""
  218. keys = (key for key in d.keys() if not key.startswith("__") and not d.getVarFlag(key, "func", False))
  219. for key in keys:
  220. emit_var(key, o, d, False)
  221. o.write('\n')
  222. emit_var(func, o, d, False) and o.write('\n')
  223. newdeps = bb.codeparser.ShellParser(func, logger).parse_shell(d.getVar(func, True))
  224. newdeps |= set((d.getVarFlag(func, "vardeps", True) or "").split())
  225. seen = set()
  226. while newdeps:
  227. deps = newdeps
  228. seen |= deps
  229. newdeps = set()
  230. for dep in deps:
  231. if d.getVarFlag(dep, "func", False) and not d.getVarFlag(dep, "python", False):
  232. emit_var(dep, o, d, False) and o.write('\n')
  233. newdeps |= bb.codeparser.ShellParser(dep, logger).parse_shell(d.getVar(dep, True))
  234. newdeps |= set((d.getVarFlag(dep, "vardeps", True) or "").split())
  235. newdeps -= seen
  236. _functionfmt = """
  237. def {function}(d):
  238. {body}"""
  239. def emit_func_python(func, o=sys.__stdout__, d = init()):
  240. """Emits all items in the data store in a format such that it can be sourced by a shell."""
  241. def write_func(func, o, call = False):
  242. body = d.getVar(func, False)
  243. if not body.startswith("def"):
  244. body = _functionfmt.format(function=func, body=body)
  245. o.write(body.strip() + "\n\n")
  246. if call:
  247. o.write(func + "(d)" + "\n\n")
  248. write_func(func, o, True)
  249. pp = bb.codeparser.PythonParser(func, logger)
  250. pp.parse_python(d.getVar(func, False))
  251. newdeps = pp.execs
  252. newdeps |= set((d.getVarFlag(func, "vardeps", True) or "").split())
  253. seen = set()
  254. while newdeps:
  255. deps = newdeps
  256. seen |= deps
  257. newdeps = set()
  258. for dep in deps:
  259. if d.getVarFlag(dep, "func", False) and d.getVarFlag(dep, "python", False):
  260. write_func(dep, o)
  261. pp = bb.codeparser.PythonParser(dep, logger)
  262. pp.parse_python(d.getVar(dep, False))
  263. newdeps |= pp.execs
  264. newdeps |= set((d.getVarFlag(dep, "vardeps", True) or "").split())
  265. newdeps -= seen
  266. def update_data(d):
  267. """Performs final steps upon the datastore, including application of overrides"""
  268. d.finalize(parent = True)
  269. def build_dependencies(key, keys, shelldeps, varflagsexcl, d):
  270. deps = set()
  271. try:
  272. if key[-1] == ']':
  273. vf = key[:-1].split('[')
  274. value = d.getVarFlag(vf[0], vf[1], False)
  275. parser = d.expandWithRefs(value, key)
  276. deps |= parser.references
  277. deps = deps | (keys & parser.execs)
  278. return deps, value
  279. varflags = d.getVarFlags(key, ["vardeps", "vardepvalue", "vardepsexclude", "vardepvalueexclude", "postfuncs", "prefuncs", "lineno", "filename"]) or {}
  280. vardeps = varflags.get("vardeps")
  281. value = d.getVar(key, False)
  282. def handle_contains(value, contains, d):
  283. newvalue = ""
  284. for k in sorted(contains):
  285. l = (d.getVar(k, True) or "").split()
  286. for word in sorted(contains[k]):
  287. if word in l:
  288. newvalue += "\n%s{%s} = Set" % (k, word)
  289. else:
  290. newvalue += "\n%s{%s} = Unset" % (k, word)
  291. if not newvalue:
  292. return value
  293. if not value:
  294. return newvalue
  295. return value + newvalue
  296. if "vardepvalue" in varflags:
  297. value = varflags.get("vardepvalue")
  298. elif varflags.get("func"):
  299. if varflags.get("python"):
  300. parser = bb.codeparser.PythonParser(key, logger)
  301. if value and "\t" in value:
  302. logger.warning("Variable %s contains tabs, please remove these (%s)" % (key, d.getVar("FILE", True)))
  303. parser.parse_python(value, filename=varflags.get("filename"), lineno=varflags.get("lineno"))
  304. deps = deps | parser.references
  305. deps = deps | (keys & parser.execs)
  306. value = handle_contains(value, parser.contains, d)
  307. else:
  308. parsedvar = d.expandWithRefs(value, key)
  309. parser = bb.codeparser.ShellParser(key, logger)
  310. parser.parse_shell(parsedvar.value)
  311. deps = deps | shelldeps
  312. deps = deps | parsedvar.references
  313. deps = deps | (keys & parser.execs) | (keys & parsedvar.execs)
  314. value = handle_contains(value, parsedvar.contains, d)
  315. if vardeps is None:
  316. parser.log.flush()
  317. if "prefuncs" in varflags:
  318. deps = deps | set(varflags["prefuncs"].split())
  319. if "postfuncs" in varflags:
  320. deps = deps | set(varflags["postfuncs"].split())
  321. else:
  322. parser = d.expandWithRefs(value, key)
  323. deps |= parser.references
  324. deps = deps | (keys & parser.execs)
  325. value = handle_contains(value, parser.contains, d)
  326. if "vardepvalueexclude" in varflags:
  327. exclude = varflags.get("vardepvalueexclude")
  328. for excl in exclude.split('|'):
  329. if excl:
  330. value = value.replace(excl, '')
  331. # Add varflags, assuming an exclusion list is set
  332. if varflagsexcl:
  333. varfdeps = []
  334. for f in varflags:
  335. if f not in varflagsexcl:
  336. varfdeps.append('%s[%s]' % (key, f))
  337. if varfdeps:
  338. deps |= set(varfdeps)
  339. deps |= set((vardeps or "").split())
  340. deps -= set(varflags.get("vardepsexclude", "").split())
  341. except Exception as e:
  342. bb.warn("Exception during build_dependencies for %s" % key)
  343. raise
  344. return deps, value
  345. #bb.note("Variable %s references %s and calls %s" % (key, str(deps), str(execs)))
  346. #d.setVarFlag(key, "vardeps", deps)
  347. def generate_dependencies(d):
  348. keys = set(key for key in d if not key.startswith("__"))
  349. shelldeps = set(key for key in d.getVar("__exportlist", False) if d.getVarFlag(key, "export", False) and not d.getVarFlag(key, "unexport", False))
  350. varflagsexcl = d.getVar('BB_SIGNATURE_EXCLUDE_FLAGS', True)
  351. deps = {}
  352. values = {}
  353. tasklist = d.getVar('__BBTASKS', False) or []
  354. for task in tasklist:
  355. deps[task], values[task] = build_dependencies(task, keys, shelldeps, varflagsexcl, d)
  356. newdeps = deps[task]
  357. seen = set()
  358. while newdeps:
  359. nextdeps = newdeps
  360. seen |= nextdeps
  361. newdeps = set()
  362. for dep in nextdeps:
  363. if dep not in deps:
  364. deps[dep], values[dep] = build_dependencies(dep, keys, shelldeps, varflagsexcl, d)
  365. newdeps |= deps[dep]
  366. newdeps -= seen
  367. #print "For %s: %s" % (task, str(deps[task]))
  368. return tasklist, deps, values
  369. def inherits_class(klass, d):
  370. val = d.getVar('__inherit_cache', False) or []
  371. needle = os.path.join('classes', '%s.bbclass' % klass)
  372. for v in val:
  373. if v.endswith(needle):
  374. return True
  375. return False