blob: f8ae41093b3f3e0bb6165f19f5eb876bf87aab88 [file] [log] [blame]
Patrick Williamsc124f4f2015-09-15 14:41:29 -05001#!/usr/bin/env python
Patrick Williamsc124f4f2015-09-15 14:41:29 -05002#
3# Copyright (C) 2003, 2004 Chris Larson
4# Copyright (C) 2003, 2004 Phil Blundell
5# Copyright (C) 2003 - 2005 Michael 'Mickey' Lauer
6# Copyright (C) 2005 Holger Hans Peter Freyther
7# Copyright (C) 2005 ROAD GmbH
8# Copyright (C) 2006 Richard Purdie
9#
Brad Bishopc342db32019-05-15 21:57:59 -040010# SPDX-License-Identifier: GPL-2.0-only
Patrick Williamsc124f4f2015-09-15 14:41:29 -050011#
Patrick Williamsc124f4f2015-09-15 14:41:29 -050012
Patrick Williamsc124f4f2015-09-15 14:41:29 -050013import logging
Patrick Williamsc0f7c042017-02-23 20:41:17 -060014import os
15import re
16import sys
17from functools import wraps
Patrick Williamsc124f4f2015-09-15 14:41:29 -050018import bb
19from bb import data
20import bb.parse
21
22logger = logging.getLogger("BitBake")
23parselog = logging.getLogger("BitBake.Parsing")
24
25class ConfigParameters(object):
26 def __init__(self, argv=sys.argv):
27 self.options, targets = self.parseCommandLine(argv)
28 self.environment = self.parseEnvironment()
29
30 self.options.pkgs_to_build = targets or []
31
Patrick Williamsc124f4f2015-09-15 14:41:29 -050032 for key, val in self.options.__dict__.items():
33 setattr(self, key, val)
34
35 def parseCommandLine(self, argv=sys.argv):
36 raise Exception("Caller must implement commandline option parsing")
37
38 def parseEnvironment(self):
39 return os.environ.copy()
40
41 def updateFromServer(self, server):
42 if not self.options.cmd:
43 defaulttask, error = server.runCommand(["getVariable", "BB_DEFAULT_TASK"])
44 if error:
45 raise Exception("Unable to get the value of BB_DEFAULT_TASK from the server: %s" % error)
46 self.options.cmd = defaulttask or "build"
47 _, error = server.runCommand(["setConfig", "cmd", self.options.cmd])
48 if error:
49 raise Exception("Unable to set configuration option 'cmd' on the server: %s" % error)
50
51 if not self.options.pkgs_to_build:
Patrick Williamsf1e5d692016-03-30 15:21:19 -050052 bbpkgs, error = server.runCommand(["getVariable", "BBTARGETS"])
Patrick Williamsc124f4f2015-09-15 14:41:29 -050053 if error:
Patrick Williamsf1e5d692016-03-30 15:21:19 -050054 raise Exception("Unable to get the value of BBTARGETS from the server: %s" % error)
Patrick Williamsc124f4f2015-09-15 14:41:29 -050055 if bbpkgs:
56 self.options.pkgs_to_build.extend(bbpkgs.split())
57
58 def updateToServer(self, server, environment):
59 options = {}
Brad Bishopd7bf8c12018-02-25 22:55:05 -050060 for o in ["abort", "force", "invalidate_stamp",
61 "verbose", "debug", "dry_run", "dump_signatures",
Patrick Williamsc124f4f2015-09-15 14:41:29 -050062 "debug_domains", "extra_assume_provided", "profile",
Brad Bishopd7bf8c12018-02-25 22:55:05 -050063 "prefile", "postfile", "server_timeout"]:
Patrick Williamsc124f4f2015-09-15 14:41:29 -050064 options[o] = getattr(self.options, o)
65
Brad Bishop6e60e8b2018-02-01 10:27:11 -050066 ret, error = server.runCommand(["updateConfig", options, environment, sys.argv])
Patrick Williamsc124f4f2015-09-15 14:41:29 -050067 if error:
Brad Bishopd7bf8c12018-02-25 22:55:05 -050068 raise Exception("Unable to update the server configuration with local parameters: %s" % error)
Patrick Williamsc124f4f2015-09-15 14:41:29 -050069
70 def parseActions(self):
71 # Parse any commandline into actions
72 action = {'action':None, 'msg':None}
73 if self.options.show_environment:
74 if 'world' in self.options.pkgs_to_build:
75 action['msg'] = "'world' is not a valid target for --environment."
76 elif 'universe' in self.options.pkgs_to_build:
77 action['msg'] = "'universe' is not a valid target for --environment."
78 elif len(self.options.pkgs_to_build) > 1:
79 action['msg'] = "Only one target can be used with the --environment option."
80 elif self.options.buildfile and len(self.options.pkgs_to_build) > 0:
81 action['msg'] = "No target should be used with the --environment and --buildfile options."
82 elif len(self.options.pkgs_to_build) > 0:
83 action['action'] = ["showEnvironmentTarget", self.options.pkgs_to_build]
84 else:
85 action['action'] = ["showEnvironment", self.options.buildfile]
86 elif self.options.buildfile is not None:
87 action['action'] = ["buildFile", self.options.buildfile, self.options.cmd]
88 elif self.options.revisions_changed:
89 action['action'] = ["compareRevisions"]
90 elif self.options.show_versions:
91 action['action'] = ["showVersions"]
92 elif self.options.parse_only:
93 action['action'] = ["parseFiles"]
94 elif self.options.dot_graph:
95 if self.options.pkgs_to_build:
96 action['action'] = ["generateDotGraph", self.options.pkgs_to_build, self.options.cmd]
97 else:
98 action['msg'] = "Please specify a package name for dependency graph generation."
99 else:
100 if self.options.pkgs_to_build:
101 action['action'] = ["buildTargets", self.options.pkgs_to_build, self.options.cmd]
102 else:
103 #action['msg'] = "Nothing to do. Use 'bitbake world' to build everything, or run 'bitbake --help' for usage information."
104 action = None
105 self.options.initialaction = action
106 return action
107
108class CookerConfiguration(object):
109 """
110 Manages build options and configurations for one run
111 """
112
113 def __init__(self):
114 self.debug_domains = []
115 self.extra_assume_provided = []
116 self.prefile = []
117 self.postfile = []
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500118 self.debug = 0
119 self.cmd = None
120 self.abort = True
121 self.force = False
122 self.profile = False
123 self.nosetscene = False
Patrick Williamsd8c66bc2016-06-20 12:57:21 -0500124 self.setsceneonly = False
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500125 self.invalidate_stamp = False
126 self.dump_signatures = []
127 self.dry_run = False
128 self.tracking = False
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500129 self.xmlrpcinterface = []
130 self.server_timeout = None
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500131 self.writeeventlog = False
Brad Bishop6e60e8b2018-02-01 10:27:11 -0500132 self.server_only = False
133 self.limited_deps = False
Brad Bishop316dfdd2018-06-25 12:45:53 -0400134 self.runall = []
135 self.runonly = []
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500136
137 self.env = {}
138
139 def setConfigParameters(self, parameters):
140 for key in self.__dict__.keys():
141 if key in parameters.options.__dict__:
142 setattr(self, key, parameters.options.__dict__[key])
143 self.env = parameters.environment.copy()
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500144
145 def setServerRegIdleCallback(self, srcb):
146 self.server_register_idlecallback = srcb
147
148 def __getstate__(self):
149 state = {}
150 for key in self.__dict__.keys():
151 if key == "server_register_idlecallback":
152 state[key] = None
153 else:
154 state[key] = getattr(self, key)
155 return state
156
157 def __setstate__(self,state):
158 for k in state:
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500159 setattr(self, k, state[k])
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500160
161
162def catch_parse_error(func):
163 """Exception handling bits for our parsing"""
164 @wraps(func)
165 def wrapped(fn, *args):
166 try:
167 return func(fn, *args)
168 except IOError as exc:
169 import traceback
170 parselog.critical(traceback.format_exc())
171 parselog.critical("Unable to parse %s: %s" % (fn, exc))
172 sys.exit(1)
Patrick Williamsd8c66bc2016-06-20 12:57:21 -0500173 except bb.data_smart.ExpansionError as exc:
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500174 import traceback
175
176 bbdir = os.path.dirname(__file__) + os.sep
177 exc_class, exc, tb = sys.exc_info()
178 for tb in iter(lambda: tb.tb_next, None):
179 # Skip frames in bitbake itself, we only want the metadata
180 fn, _, _, _ = traceback.extract_tb(tb, 1)[0]
181 if not fn.startswith(bbdir):
182 break
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600183 parselog.critical("Unable to parse %s" % fn, exc_info=(exc_class, exc, tb))
184 sys.exit(1)
Patrick Williamsd8c66bc2016-06-20 12:57:21 -0500185 except bb.parse.ParseError as exc:
186 parselog.critical(str(exc))
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500187 sys.exit(1)
188 return wrapped
189
190@catch_parse_error
191def parse_config_file(fn, data, include=True):
192 return bb.parse.handle(fn, data, include)
193
194@catch_parse_error
195def _inherit(bbclass, data):
196 bb.parse.BBHandler.inherit(bbclass, "configuration INHERITs", 0, data)
197 return data
198
199def findConfigFile(configfile, data):
200 search = []
Brad Bishop6e60e8b2018-02-01 10:27:11 -0500201 bbpath = data.getVar("BBPATH")
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500202 if bbpath:
203 for i in bbpath.split(":"):
204 search.append(os.path.join(i, "conf", configfile))
205 path = os.getcwd()
206 while path != "/":
207 search.append(os.path.join(path, "conf", configfile))
208 path, _ = os.path.split(path)
209
210 for i in search:
211 if os.path.exists(i):
212 return i
213
214 return None
215
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500216#
217# We search for a conf/bblayers.conf under an entry in BBPATH or in cwd working
218# up to /. If that fails, we search for a conf/bitbake.conf in BBPATH.
219#
220
221def findTopdir():
222 d = bb.data.init()
223 bbpath = None
224 if 'BBPATH' in os.environ:
225 bbpath = os.environ['BBPATH']
226 d.setVar('BBPATH', bbpath)
227
228 layerconf = findConfigFile("bblayers.conf", d)
229 if layerconf:
230 return os.path.dirname(os.path.dirname(layerconf))
231 if bbpath:
232 bitbakeconf = bb.utils.which(bbpath, "conf/bitbake.conf")
233 if bitbakeconf:
234 return os.path.dirname(os.path.dirname(bitbakeconf))
235 return None
236
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500237class CookerDataBuilder(object):
238
239 def __init__(self, cookercfg, worker = False):
240
241 self.prefiles = cookercfg.prefile
242 self.postfiles = cookercfg.postfile
243 self.tracking = cookercfg.tracking
244
245 bb.utils.set_context(bb.utils.clean_context())
246 bb.event.set_class_handlers(bb.event.clean_class_handlers())
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600247 self.basedata = bb.data.init()
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500248 if self.tracking:
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600249 self.basedata.enableTracking()
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500250
251 # Keep a datastore of the initial environment variables and their
252 # values from when BitBake was launched to enable child processes
253 # to use environment variables which have been cleaned from the
254 # BitBake processes env
255 self.savedenv = bb.data.init()
256 for k in cookercfg.env:
257 self.savedenv.setVar(k, cookercfg.env[k])
258
259 filtered_keys = bb.utils.approved_variables()
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600260 bb.data.inheritFromOS(self.basedata, self.savedenv, filtered_keys)
261 self.basedata.setVar("BB_ORIGENV", self.savedenv)
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500262
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500263 if worker:
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600264 self.basedata.setVar("BB_WORKERCONTEXT", "1")
265
266 self.data = self.basedata
267 self.mcdata = {}
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500268
269 def parseBaseConfiguration(self):
270 try:
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600271 bb.parse.init_parser(self.basedata)
272 self.data = self.parseConfigurationFiles(self.prefiles, self.postfiles)
273
274 if self.data.getVar("BB_WORKERCONTEXT", False) is None:
275 bb.fetch.fetcher_init(self.data)
276 bb.codeparser.parser_cache_init(self.data)
277
278 bb.event.fire(bb.event.ConfigParsed(), self.data)
279
280 reparse_cnt = 0
281 while self.data.getVar("BB_INVALIDCONF", False) is True:
282 if reparse_cnt > 20:
283 logger.error("Configuration has been re-parsed over 20 times, "
284 "breaking out of the loop...")
285 raise Exception("Too deep config re-parse loop. Check locations where "
286 "BB_INVALIDCONF is being set (ConfigParsed event handlers)")
287 self.data.setVar("BB_INVALIDCONF", False)
288 self.data = self.parseConfigurationFiles(self.prefiles, self.postfiles)
289 reparse_cnt += 1
290 bb.event.fire(bb.event.ConfigParsed(), self.data)
291
292 bb.parse.init_parser(self.data)
293 self.data_hash = self.data.get_hash()
294 self.mcdata[''] = self.data
295
Brad Bishop6e60e8b2018-02-01 10:27:11 -0500296 multiconfig = (self.data.getVar("BBMULTICONFIG") or "").split()
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600297 for config in multiconfig:
Brad Bishop37a0e4d2017-12-04 01:01:44 -0500298 mcdata = self.parseConfigurationFiles(self.prefiles, self.postfiles, config)
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600299 bb.event.fire(bb.event.ConfigParsed(), mcdata)
300 self.mcdata[config] = mcdata
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500301 if multiconfig:
302 bb.event.fire(bb.event.MultiConfigParsed(self.mcdata), self.data)
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600303
304 except (SyntaxError, bb.BBHandledException):
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500305 raise bb.BBHandledException
306 except bb.data_smart.ExpansionError as e:
307 logger.error(str(e))
308 raise bb.BBHandledException
309 except Exception:
310 logger.exception("Error parsing configuration files")
311 raise bb.BBHandledException
312
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500313 # Create a copy so we can reset at a later date when UIs disconnect
314 self.origdata = self.data
315 self.data = bb.data.createCopy(self.origdata)
316 self.mcdata[''] = self.data
317
318 def reset(self):
319 # We may not have run parseBaseConfiguration() yet
320 if not hasattr(self, 'origdata'):
321 return
322 self.data = bb.data.createCopy(self.origdata)
323 self.mcdata[''] = self.data
324
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500325 def _findLayerConf(self, data):
326 return findConfigFile("bblayers.conf", data)
327
Brad Bishop37a0e4d2017-12-04 01:01:44 -0500328 def parseConfigurationFiles(self, prefiles, postfiles, mc = "default"):
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600329 data = bb.data.createCopy(self.basedata)
Brad Bishop37a0e4d2017-12-04 01:01:44 -0500330 data.setVar("BB_CURRENT_MC", mc)
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500331
332 # Parse files for loading *before* bitbake.conf and any includes
333 for f in prefiles:
334 data = parse_config_file(f, data)
335
336 layerconf = self._findLayerConf(data)
337 if layerconf:
338 parselog.debug(2, "Found bblayers.conf (%s)", layerconf)
339 # By definition bblayers.conf is in conf/ of TOPDIR.
340 # We may have been called with cwd somewhere else so reset TOPDIR
341 data.setVar("TOPDIR", os.path.dirname(os.path.dirname(layerconf)))
342 data = parse_config_file(layerconf, data)
343
Brad Bishop6e60e8b2018-02-01 10:27:11 -0500344 layers = (data.getVar('BBLAYERS') or "").split()
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500345
346 data = bb.data.createCopy(data)
347 approved = bb.utils.approved_variables()
348 for layer in layers:
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600349 if not os.path.isdir(layer):
350 parselog.critical("Layer directory '%s' does not exist! "
351 "Please check BBLAYERS in %s" % (layer, layerconf))
352 sys.exit(1)
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500353 parselog.debug(2, "Adding layer %s", layer)
354 if 'HOME' in approved and '~' in layer:
355 layer = os.path.expanduser(layer)
Patrick Williamsd8c66bc2016-06-20 12:57:21 -0500356 if layer.endswith('/'):
357 layer = layer.rstrip('/')
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500358 data.setVar('LAYERDIR', layer)
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600359 data.setVar('LAYERDIR_RE', re.escape(layer))
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500360 data = parse_config_file(os.path.join(layer, "conf", "layer.conf"), data)
361 data.expandVarref('LAYERDIR')
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600362 data.expandVarref('LAYERDIR_RE')
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500363
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600364 data.delVar('LAYERDIR_RE')
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500365 data.delVar('LAYERDIR')
366
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500367 bbfiles_dynamic = (data.getVar('BBFILES_DYNAMIC') or "").split()
368 collections = (data.getVar('BBFILE_COLLECTIONS') or "").split()
369 invalid = []
370 for entry in bbfiles_dynamic:
371 parts = entry.split(":", 1)
372 if len(parts) != 2:
373 invalid.append(entry)
374 continue
375 l, f = parts
376 if l in collections:
377 data.appendVar("BBFILES", " " + f)
378 if invalid:
379 bb.fatal("BBFILES_DYNAMIC entries must be of the form <collection name>:<filename pattern>, not:\n %s" % "\n ".join(invalid))
380
381 layerseries = set((data.getVar("LAYERSERIES_CORENAMES") or "").split())
Brad Bishop19323692019-04-05 15:28:33 -0400382 collections_tmp = collections[:]
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500383 for c in collections:
Brad Bishop19323692019-04-05 15:28:33 -0400384 collections_tmp.remove(c)
385 if c in collections_tmp:
386 bb.fatal("Found duplicated BBFILE_COLLECTIONS '%s', check bblayers.conf or layer.conf to fix it." % c)
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500387 compat = set((data.getVar("LAYERSERIES_COMPAT_%s" % c) or "").split())
388 if compat and not (compat & layerseries):
389 bb.fatal("Layer %s is not compatible with the core layer which only supports these series: %s (layer is compatible with %s)"
390 % (c, " ".join(layerseries), " ".join(compat)))
Brad Bishop316dfdd2018-06-25 12:45:53 -0400391 elif not compat and not data.getVar("BB_WORKERCONTEXT"):
392 bb.warn("Layer %s should set LAYERSERIES_COMPAT_%s in its conf/layer.conf file to list the core layer names it is compatible with." % (c, c))
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500393
Brad Bishop6e60e8b2018-02-01 10:27:11 -0500394 if not data.getVar("BBPATH"):
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500395 msg = "The BBPATH variable is not set"
396 if not layerconf:
397 msg += (" and bitbake did not find a conf/bblayers.conf file in"
398 " the expected location.\nMaybe you accidentally"
399 " invoked bitbake from the wrong directory?")
400 raise SystemExit(msg)
401
402 data = parse_config_file(os.path.join("conf", "bitbake.conf"), data)
403
404 # Parse files for loading *after* bitbake.conf and any includes
405 for p in postfiles:
406 data = parse_config_file(p, data)
407
408 # Handle any INHERITs and inherit the base class
Brad Bishop6e60e8b2018-02-01 10:27:11 -0500409 bbclasses = ["base"] + (data.getVar('INHERIT') or "").split()
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500410 for bbclass in bbclasses:
411 data = _inherit(bbclass, data)
412
413 # Nomally we only register event handlers at the end of parsing .bb files
414 # We register any handlers we've found so far here...
415 for var in data.getVar('__BBHANDLERS', False) or []:
Patrick Williamsd8c66bc2016-06-20 12:57:21 -0500416 handlerfn = data.getVarFlag(var, "filename", False)
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600417 if not handlerfn:
418 parselog.critical("Undefined event handler function '%s'" % var)
419 sys.exit(1)
Patrick Williamsd8c66bc2016-06-20 12:57:21 -0500420 handlerln = int(data.getVarFlag(var, "lineno", False))
Brad Bishop6e60e8b2018-02-01 10:27:11 -0500421 bb.event.register(var, data.getVar(var, False), (data.getVarFlag(var, "eventmask") or "").split(), handlerfn, handlerln)
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500422
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500423 data.setVar('BBINCLUDED',bb.parse.get_file_depends(data))
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500424
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600425 return data
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500426