1# 2# Copyright (C) 2003, 2004 Chris Larson 3# Copyright (C) 2003, 2004 Phil Blundell 4# Copyright (C) 2003 - 2005 Michael 'Mickey' Lauer 5# Copyright (C) 2005 Holger Hans Peter Freyther 6# Copyright (C) 2005 ROAD GmbH 7# Copyright (C) 2006 Richard Purdie 8# 9# SPDX-License-Identifier: GPL-2.0-only 10# 11 12import logging 13import os 14import re 15import sys 16import hashlib 17from functools import wraps 18import 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=None): 27 self.options, targets = self.parseCommandLine(argv or sys.argv) 28 self.environment = self.parseEnvironment() 29 30 self.options.pkgs_to_build = targets or [] 31 32 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: 52 bbpkgs, error = server.runCommand(["getVariable", "BBTARGETS"]) 53 if error: 54 raise Exception("Unable to get the value of BBTARGETS from the server: %s" % error) 55 if bbpkgs: 56 self.options.pkgs_to_build.extend(bbpkgs.split()) 57 58 def updateToServer(self, server, environment): 59 options = {} 60 for o in ["halt", "force", "invalidate_stamp", 61 "dry_run", "dump_signatures", 62 "extra_assume_provided", "profile", 63 "prefile", "postfile", "server_timeout", 64 "nosetscene", "setsceneonly", "skipsetscene", 65 "runall", "runonly", "writeeventlog"]: 66 options[o] = getattr(self.options, o) 67 68 options['build_verbose_shell'] = self.options.verbose 69 options['build_verbose_stdout'] = self.options.verbose 70 options['default_loglevel'] = bb.msg.loggerDefaultLogLevel 71 options['debug_domains'] = bb.msg.loggerDefaultDomains 72 73 ret, error = server.runCommand(["updateConfig", options, environment, sys.argv]) 74 if error: 75 raise Exception("Unable to update the server configuration with local parameters: %s" % error) 76 77 def parseActions(self): 78 # Parse any commandline into actions 79 action = {'action':None, 'msg':None} 80 if self.options.show_environment: 81 if 'world' in self.options.pkgs_to_build: 82 action['msg'] = "'world' is not a valid target for --environment." 83 elif 'universe' in self.options.pkgs_to_build: 84 action['msg'] = "'universe' is not a valid target for --environment." 85 elif len(self.options.pkgs_to_build) > 1: 86 action['msg'] = "Only one target can be used with the --environment option." 87 elif self.options.buildfile and len(self.options.pkgs_to_build) > 0: 88 action['msg'] = "No target should be used with the --environment and --buildfile options." 89 elif self.options.pkgs_to_build: 90 action['action'] = ["showEnvironmentTarget", self.options.pkgs_to_build] 91 else: 92 action['action'] = ["showEnvironment", self.options.buildfile] 93 elif self.options.buildfile is not None: 94 action['action'] = ["buildFile", self.options.buildfile, self.options.cmd] 95 elif self.options.revisions_changed: 96 action['action'] = ["compareRevisions"] 97 elif self.options.show_versions: 98 action['action'] = ["showVersions"] 99 elif self.options.parse_only: 100 action['action'] = ["parseFiles"] 101 elif self.options.dot_graph: 102 if self.options.pkgs_to_build: 103 action['action'] = ["generateDotGraph", self.options.pkgs_to_build, self.options.cmd] 104 else: 105 action['msg'] = "Please specify a package name for dependency graph generation." 106 else: 107 if self.options.pkgs_to_build: 108 action['action'] = ["buildTargets", self.options.pkgs_to_build, self.options.cmd] 109 else: 110 #action['msg'] = "Nothing to do. Use 'bitbake world' to build everything, or run 'bitbake --help' for usage information." 111 action = None 112 self.options.initialaction = action 113 return action 114 115class CookerConfiguration(object): 116 """ 117 Manages build options and configurations for one run 118 """ 119 120 def __init__(self): 121 self.debug_domains = bb.msg.loggerDefaultDomains 122 self.default_loglevel = bb.msg.loggerDefaultLogLevel 123 self.extra_assume_provided = [] 124 self.prefile = [] 125 self.postfile = [] 126 self.cmd = None 127 self.halt = True 128 self.force = False 129 self.profile = False 130 self.nosetscene = False 131 self.setsceneonly = False 132 self.skipsetscene = False 133 self.invalidate_stamp = False 134 self.dump_signatures = [] 135 self.build_verbose_shell = False 136 self.build_verbose_stdout = False 137 self.dry_run = False 138 self.tracking = False 139 self.writeeventlog = False 140 self.limited_deps = False 141 self.runall = [] 142 self.runonly = [] 143 144 self.env = {} 145 146 def __getstate__(self): 147 state = {} 148 for key in self.__dict__.keys(): 149 state[key] = getattr(self, key) 150 return state 151 152 def __setstate__(self,state): 153 for k in state: 154 setattr(self, k, state[k]) 155 156 157def catch_parse_error(func): 158 """Exception handling bits for our parsing""" 159 @wraps(func) 160 def wrapped(fn, *args): 161 try: 162 return func(fn, *args) 163 except Exception as exc: 164 import traceback 165 166 bbdir = os.path.dirname(__file__) + os.sep 167 exc_class, exc, tb = sys.exc_info() 168 for tb in iter(lambda: tb.tb_next, None): 169 # Skip frames in bitbake itself, we only want the metadata 170 fn, _, _, _ = traceback.extract_tb(tb, 1)[0] 171 if not fn.startswith(bbdir): 172 break 173 parselog.critical("Unable to parse %s" % fn, exc_info=(exc_class, exc, tb)) 174 raise bb.BBHandledException() 175 return wrapped 176 177@catch_parse_error 178def parse_config_file(fn, data, include=True): 179 return bb.parse.handle(fn, data, include) 180 181@catch_parse_error 182def _inherit(bbclass, data): 183 bb.parse.BBHandler.inherit(bbclass, "configuration INHERITs", 0, data) 184 return data 185 186def findConfigFile(configfile, data): 187 search = [] 188 bbpath = data.getVar("BBPATH") 189 if bbpath: 190 for i in bbpath.split(":"): 191 search.append(os.path.join(i, "conf", configfile)) 192 path = os.getcwd() 193 while path != "/": 194 search.append(os.path.join(path, "conf", configfile)) 195 path, _ = os.path.split(path) 196 197 for i in search: 198 if os.path.exists(i): 199 return i 200 201 return None 202 203# 204# We search for a conf/bblayers.conf under an entry in BBPATH or in cwd working 205# up to /. If that fails, bitbake would fall back to cwd. 206# 207 208def findTopdir(): 209 d = bb.data.init() 210 bbpath = None 211 if 'BBPATH' in os.environ: 212 bbpath = os.environ['BBPATH'] 213 d.setVar('BBPATH', bbpath) 214 215 layerconf = findConfigFile("bblayers.conf", d) 216 if layerconf: 217 return os.path.dirname(os.path.dirname(layerconf)) 218 219 return os.path.abspath(os.getcwd()) 220 221class CookerDataBuilder(object): 222 223 def __init__(self, cookercfg, worker = False): 224 225 self.prefiles = cookercfg.prefile 226 self.postfiles = cookercfg.postfile 227 self.tracking = cookercfg.tracking 228 229 bb.utils.set_context(bb.utils.clean_context()) 230 bb.event.set_class_handlers(bb.event.clean_class_handlers()) 231 self.basedata = bb.data.init() 232 if self.tracking: 233 self.basedata.enableTracking() 234 235 # Keep a datastore of the initial environment variables and their 236 # values from when BitBake was launched to enable child processes 237 # to use environment variables which have been cleaned from the 238 # BitBake processes env 239 self.savedenv = bb.data.init() 240 for k in cookercfg.env: 241 self.savedenv.setVar(k, cookercfg.env[k]) 242 if k in bb.data_smart.bitbake_renamed_vars: 243 bb.error('Variable %s from the shell environment has been renamed to %s' % (k, bb.data_smart.bitbake_renamed_vars[k])) 244 bb.fatal("Exiting to allow enviroment variables to be corrected") 245 246 filtered_keys = bb.utils.approved_variables() 247 bb.data.inheritFromOS(self.basedata, self.savedenv, filtered_keys) 248 self.basedata.setVar("BB_ORIGENV", self.savedenv) 249 250 if worker: 251 self.basedata.setVar("BB_WORKERCONTEXT", "1") 252 253 self.data = self.basedata 254 self.mcdata = {} 255 256 def parseBaseConfiguration(self, worker=False): 257 data_hash = hashlib.sha256() 258 try: 259 self.data = self.parseConfigurationFiles(self.prefiles, self.postfiles) 260 261 if self.data.getVar("BB_WORKERCONTEXT", False) is None and not worker: 262 bb.fetch.fetcher_init(self.data) 263 bb.parse.init_parser(self.data) 264 bb.codeparser.parser_cache_init(self.data) 265 266 bb.event.fire(bb.event.ConfigParsed(), self.data) 267 268 reparse_cnt = 0 269 while self.data.getVar("BB_INVALIDCONF", False) is True: 270 if reparse_cnt > 20: 271 logger.error("Configuration has been re-parsed over 20 times, " 272 "breaking out of the loop...") 273 raise Exception("Too deep config re-parse loop. Check locations where " 274 "BB_INVALIDCONF is being set (ConfigParsed event handlers)") 275 self.data.setVar("BB_INVALIDCONF", False) 276 self.data = self.parseConfigurationFiles(self.prefiles, self.postfiles) 277 reparse_cnt += 1 278 bb.event.fire(bb.event.ConfigParsed(), self.data) 279 280 bb.parse.init_parser(self.data) 281 data_hash.update(self.data.get_hash().encode('utf-8')) 282 self.mcdata[''] = self.data 283 284 multiconfig = (self.data.getVar("BBMULTICONFIG") or "").split() 285 for config in multiconfig: 286 if config[0].isdigit(): 287 bb.fatal("Multiconfig name '%s' is invalid as multiconfigs cannot start with a digit" % config) 288 mcdata = self.parseConfigurationFiles(self.prefiles, self.postfiles, config) 289 bb.event.fire(bb.event.ConfigParsed(), mcdata) 290 self.mcdata[config] = mcdata 291 data_hash.update(mcdata.get_hash().encode('utf-8')) 292 if multiconfig: 293 bb.event.fire(bb.event.MultiConfigParsed(self.mcdata), self.data) 294 295 self.data_hash = data_hash.hexdigest() 296 except bb.data_smart.ExpansionError as e: 297 logger.error(str(e)) 298 raise bb.BBHandledException() 299 300 301 # Handle obsolete variable names 302 d = self.data 303 renamedvars = d.getVarFlags('BB_RENAMED_VARIABLES') or {} 304 renamedvars.update(bb.data_smart.bitbake_renamed_vars) 305 issues = False 306 for v in renamedvars: 307 if d.getVar(v) != None or d.hasOverrides(v): 308 issues = True 309 loginfo = {} 310 history = d.varhistory.get_variable_refs(v) 311 for h in history: 312 for line in history[h]: 313 loginfo = {'file' : h, 'line' : line} 314 bb.data.data_smart._print_rename_error(v, loginfo, renamedvars) 315 if not history: 316 bb.data.data_smart._print_rename_error(v, loginfo, renamedvars) 317 if issues: 318 raise bb.BBHandledException() 319 320 # Create a copy so we can reset at a later date when UIs disconnect 321 self.origdata = self.data 322 self.data = bb.data.createCopy(self.origdata) 323 self.mcdata[''] = self.data 324 325 def reset(self): 326 # We may not have run parseBaseConfiguration() yet 327 if not hasattr(self, 'origdata'): 328 return 329 self.data = bb.data.createCopy(self.origdata) 330 self.mcdata[''] = self.data 331 332 def _findLayerConf(self, data): 333 return findConfigFile("bblayers.conf", data) 334 335 def parseConfigurationFiles(self, prefiles, postfiles, mc = "default"): 336 data = bb.data.createCopy(self.basedata) 337 data.setVar("BB_CURRENT_MC", mc) 338 339 # Parse files for loading *before* bitbake.conf and any includes 340 for f in prefiles: 341 data = parse_config_file(f, data) 342 343 layerconf = self._findLayerConf(data) 344 if layerconf: 345 parselog.debug(2, "Found bblayers.conf (%s)", layerconf) 346 # By definition bblayers.conf is in conf/ of TOPDIR. 347 # We may have been called with cwd somewhere else so reset TOPDIR 348 data.setVar("TOPDIR", os.path.dirname(os.path.dirname(layerconf))) 349 data = parse_config_file(layerconf, data) 350 351 layers = (data.getVar('BBLAYERS') or "").split() 352 broken_layers = [] 353 354 if not layers: 355 bb.fatal("The bblayers.conf file doesn't contain any BBLAYERS definition") 356 357 data = bb.data.createCopy(data) 358 approved = bb.utils.approved_variables() 359 360 # Check whether present layer directories exist 361 for layer in layers: 362 if not os.path.isdir(layer): 363 broken_layers.append(layer) 364 365 if broken_layers: 366 parselog.critical("The following layer directories do not exist:") 367 for layer in broken_layers: 368 parselog.critical(" %s", layer) 369 parselog.critical("Please check BBLAYERS in %s" % (layerconf)) 370 raise bb.BBHandledException() 371 372 for layer in layers: 373 parselog.debug(2, "Adding layer %s", layer) 374 if 'HOME' in approved and '~' in layer: 375 layer = os.path.expanduser(layer) 376 if layer.endswith('/'): 377 layer = layer.rstrip('/') 378 data.setVar('LAYERDIR', layer) 379 data.setVar('LAYERDIR_RE', re.escape(layer)) 380 data = parse_config_file(os.path.join(layer, "conf", "layer.conf"), data) 381 data.expandVarref('LAYERDIR') 382 data.expandVarref('LAYERDIR_RE') 383 384 data.delVar('LAYERDIR_RE') 385 data.delVar('LAYERDIR') 386 387 bbfiles_dynamic = (data.getVar('BBFILES_DYNAMIC') or "").split() 388 collections = (data.getVar('BBFILE_COLLECTIONS') or "").split() 389 invalid = [] 390 for entry in bbfiles_dynamic: 391 parts = entry.split(":", 1) 392 if len(parts) != 2: 393 invalid.append(entry) 394 continue 395 l, f = parts 396 invert = l[0] == "!" 397 if invert: 398 l = l[1:] 399 if (l in collections and not invert) or (l not in collections and invert): 400 data.appendVar("BBFILES", " " + f) 401 if invalid: 402 bb.fatal("BBFILES_DYNAMIC entries must be of the form {!}<collection name>:<filename pattern>, not:\n %s" % "\n ".join(invalid)) 403 404 layerseries = set((data.getVar("LAYERSERIES_CORENAMES") or "").split()) 405 collections_tmp = collections[:] 406 for c in collections: 407 collections_tmp.remove(c) 408 if c in collections_tmp: 409 bb.fatal("Found duplicated BBFILE_COLLECTIONS '%s', check bblayers.conf or layer.conf to fix it." % c) 410 compat = set((data.getVar("LAYERSERIES_COMPAT_%s" % c) or "").split()) 411 if compat and not layerseries: 412 bb.fatal("No core layer found to work with layer '%s'. Missing entry in bblayers.conf?" % c) 413 if compat and not (compat & layerseries): 414 bb.fatal("Layer %s is not compatible with the core layer which only supports these series: %s (layer is compatible with %s)" 415 % (c, " ".join(layerseries), " ".join(compat))) 416 elif not compat and not data.getVar("BB_WORKERCONTEXT"): 417 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)) 418 419 if not data.getVar("BBPATH"): 420 msg = "The BBPATH variable is not set" 421 if not layerconf: 422 msg += (" and bitbake did not find a conf/bblayers.conf file in" 423 " the expected location.\nMaybe you accidentally" 424 " invoked bitbake from the wrong directory?") 425 bb.fatal(msg) 426 427 if not data.getVar("TOPDIR"): 428 data.setVar("TOPDIR", os.path.abspath(os.getcwd())) 429 430 data = parse_config_file(os.path.join("conf", "bitbake.conf"), data) 431 432 # Parse files for loading *after* bitbake.conf and any includes 433 for p in postfiles: 434 data = parse_config_file(p, data) 435 436 # Handle any INHERITs and inherit the base class 437 bbclasses = ["base"] + (data.getVar('INHERIT') or "").split() 438 for bbclass in bbclasses: 439 data = _inherit(bbclass, data) 440 441 # Normally we only register event handlers at the end of parsing .bb files 442 # We register any handlers we've found so far here... 443 for var in data.getVar('__BBHANDLERS', False) or []: 444 handlerfn = data.getVarFlag(var, "filename", False) 445 if not handlerfn: 446 parselog.critical("Undefined event handler function '%s'" % var) 447 raise bb.BBHandledException() 448 handlerln = int(data.getVarFlag(var, "lineno", False)) 449 bb.event.register(var, data.getVar(var, False), (data.getVarFlag(var, "eventmask") or "").split(), handlerfn, handlerln, data) 450 451 data.setVar('BBINCLUDED',bb.parse.get_file_depends(data)) 452 453 return data 454 455