blob: fab47c75f54b737a4ce94983ad13f22cdb43a726 [file] [log] [blame]
Patrick Williamsc124f4f2015-09-15 14:41:29 -05001#!/usr/bin/env python
2# ex:ts=4:sw=4:sts=4:et
3# -*- tab-width: 4; c-basic-offset: 4; indent-tabs-mode: nil -*-
4#
5# Copyright (C) 2003, 2004 Chris Larson
6# Copyright (C) 2003, 2004 Phil Blundell
7# Copyright (C) 2003 - 2005 Michael 'Mickey' Lauer
8# Copyright (C) 2005 Holger Hans Peter Freyther
9# Copyright (C) 2005 ROAD GmbH
10# Copyright (C) 2006 Richard Purdie
11#
12# This program is free software; you can redistribute it and/or modify
13# it under the terms of the GNU General Public License version 2 as
14# published by the Free Software Foundation.
15#
16# This program is distributed in the hope that it will be useful,
17# but WITHOUT ANY WARRANTY; without even the implied warranty of
18# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
19# GNU General Public License for more details.
20#
21# You should have received a copy of the GNU General Public License along
22# with this program; if not, write to the Free Software Foundation, Inc.,
23# 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
24
Patrick Williamsc124f4f2015-09-15 14:41:29 -050025import logging
Patrick Williamsc0f7c042017-02-23 20:41:17 -060026import os
27import re
28import sys
29from functools import wraps
Patrick Williamsc124f4f2015-09-15 14:41:29 -050030import bb
31from bb import data
32import bb.parse
33
34logger = logging.getLogger("BitBake")
35parselog = logging.getLogger("BitBake.Parsing")
36
37class ConfigParameters(object):
38 def __init__(self, argv=sys.argv):
39 self.options, targets = self.parseCommandLine(argv)
40 self.environment = self.parseEnvironment()
41
42 self.options.pkgs_to_build = targets or []
43
Patrick Williamsc124f4f2015-09-15 14:41:29 -050044 for key, val in self.options.__dict__.items():
45 setattr(self, key, val)
46
47 def parseCommandLine(self, argv=sys.argv):
48 raise Exception("Caller must implement commandline option parsing")
49
50 def parseEnvironment(self):
51 return os.environ.copy()
52
53 def updateFromServer(self, server):
54 if not self.options.cmd:
55 defaulttask, error = server.runCommand(["getVariable", "BB_DEFAULT_TASK"])
56 if error:
57 raise Exception("Unable to get the value of BB_DEFAULT_TASK from the server: %s" % error)
58 self.options.cmd = defaulttask or "build"
59 _, error = server.runCommand(["setConfig", "cmd", self.options.cmd])
60 if error:
61 raise Exception("Unable to set configuration option 'cmd' on the server: %s" % error)
62
63 if not self.options.pkgs_to_build:
Patrick Williamsf1e5d692016-03-30 15:21:19 -050064 bbpkgs, error = server.runCommand(["getVariable", "BBTARGETS"])
Patrick Williamsc124f4f2015-09-15 14:41:29 -050065 if error:
Patrick Williamsf1e5d692016-03-30 15:21:19 -050066 raise Exception("Unable to get the value of BBTARGETS from the server: %s" % error)
Patrick Williamsc124f4f2015-09-15 14:41:29 -050067 if bbpkgs:
68 self.options.pkgs_to_build.extend(bbpkgs.split())
69
70 def updateToServer(self, server, environment):
71 options = {}
Brad Bishopd7bf8c12018-02-25 22:55:05 -050072 for o in ["abort", "force", "invalidate_stamp",
73 "verbose", "debug", "dry_run", "dump_signatures",
Patrick Williamsc124f4f2015-09-15 14:41:29 -050074 "debug_domains", "extra_assume_provided", "profile",
Brad Bishopd7bf8c12018-02-25 22:55:05 -050075 "prefile", "postfile", "server_timeout"]:
Patrick Williamsc124f4f2015-09-15 14:41:29 -050076 options[o] = getattr(self.options, o)
77
Brad Bishop6e60e8b2018-02-01 10:27:11 -050078 ret, error = server.runCommand(["updateConfig", options, environment, sys.argv])
Patrick Williamsc124f4f2015-09-15 14:41:29 -050079 if error:
Brad Bishopd7bf8c12018-02-25 22:55:05 -050080 raise Exception("Unable to update the server configuration with local parameters: %s" % error)
Patrick Williamsc124f4f2015-09-15 14:41:29 -050081
82 def parseActions(self):
83 # Parse any commandline into actions
84 action = {'action':None, 'msg':None}
85 if self.options.show_environment:
86 if 'world' in self.options.pkgs_to_build:
87 action['msg'] = "'world' is not a valid target for --environment."
88 elif 'universe' in self.options.pkgs_to_build:
89 action['msg'] = "'universe' is not a valid target for --environment."
90 elif len(self.options.pkgs_to_build) > 1:
91 action['msg'] = "Only one target can be used with the --environment option."
92 elif self.options.buildfile and len(self.options.pkgs_to_build) > 0:
93 action['msg'] = "No target should be used with the --environment and --buildfile options."
94 elif len(self.options.pkgs_to_build) > 0:
95 action['action'] = ["showEnvironmentTarget", self.options.pkgs_to_build]
96 else:
97 action['action'] = ["showEnvironment", self.options.buildfile]
98 elif self.options.buildfile is not None:
99 action['action'] = ["buildFile", self.options.buildfile, self.options.cmd]
100 elif self.options.revisions_changed:
101 action['action'] = ["compareRevisions"]
102 elif self.options.show_versions:
103 action['action'] = ["showVersions"]
104 elif self.options.parse_only:
105 action['action'] = ["parseFiles"]
106 elif self.options.dot_graph:
107 if self.options.pkgs_to_build:
108 action['action'] = ["generateDotGraph", self.options.pkgs_to_build, self.options.cmd]
109 else:
110 action['msg'] = "Please specify a package name for dependency graph generation."
111 else:
112 if self.options.pkgs_to_build:
113 action['action'] = ["buildTargets", self.options.pkgs_to_build, self.options.cmd]
114 else:
115 #action['msg'] = "Nothing to do. Use 'bitbake world' to build everything, or run 'bitbake --help' for usage information."
116 action = None
117 self.options.initialaction = action
118 return action
119
120class CookerConfiguration(object):
121 """
122 Manages build options and configurations for one run
123 """
124
125 def __init__(self):
126 self.debug_domains = []
127 self.extra_assume_provided = []
128 self.prefile = []
129 self.postfile = []
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500130 self.debug = 0
131 self.cmd = None
132 self.abort = True
133 self.force = False
134 self.profile = False
135 self.nosetscene = False
Patrick Williamsd8c66bc2016-06-20 12:57:21 -0500136 self.setsceneonly = False
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500137 self.invalidate_stamp = False
138 self.dump_signatures = []
139 self.dry_run = False
140 self.tracking = False
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500141 self.xmlrpcinterface = []
142 self.server_timeout = None
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500143 self.writeeventlog = False
Brad Bishop6e60e8b2018-02-01 10:27:11 -0500144 self.server_only = False
145 self.limited_deps = False
146 self.runall = None
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500147
148 self.env = {}
149
150 def setConfigParameters(self, parameters):
151 for key in self.__dict__.keys():
152 if key in parameters.options.__dict__:
153 setattr(self, key, parameters.options.__dict__[key])
154 self.env = parameters.environment.copy()
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500155
156 def setServerRegIdleCallback(self, srcb):
157 self.server_register_idlecallback = srcb
158
159 def __getstate__(self):
160 state = {}
161 for key in self.__dict__.keys():
162 if key == "server_register_idlecallback":
163 state[key] = None
164 else:
165 state[key] = getattr(self, key)
166 return state
167
168 def __setstate__(self,state):
169 for k in state:
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500170 setattr(self, k, state[k])
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500171
172
173def catch_parse_error(func):
174 """Exception handling bits for our parsing"""
175 @wraps(func)
176 def wrapped(fn, *args):
177 try:
178 return func(fn, *args)
179 except IOError as exc:
180 import traceback
181 parselog.critical(traceback.format_exc())
182 parselog.critical("Unable to parse %s: %s" % (fn, exc))
183 sys.exit(1)
Patrick Williamsd8c66bc2016-06-20 12:57:21 -0500184 except bb.data_smart.ExpansionError as exc:
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500185 import traceback
186
187 bbdir = os.path.dirname(__file__) + os.sep
188 exc_class, exc, tb = sys.exc_info()
189 for tb in iter(lambda: tb.tb_next, None):
190 # Skip frames in bitbake itself, we only want the metadata
191 fn, _, _, _ = traceback.extract_tb(tb, 1)[0]
192 if not fn.startswith(bbdir):
193 break
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600194 parselog.critical("Unable to parse %s" % fn, exc_info=(exc_class, exc, tb))
195 sys.exit(1)
Patrick Williamsd8c66bc2016-06-20 12:57:21 -0500196 except bb.parse.ParseError as exc:
197 parselog.critical(str(exc))
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500198 sys.exit(1)
199 return wrapped
200
201@catch_parse_error
202def parse_config_file(fn, data, include=True):
203 return bb.parse.handle(fn, data, include)
204
205@catch_parse_error
206def _inherit(bbclass, data):
207 bb.parse.BBHandler.inherit(bbclass, "configuration INHERITs", 0, data)
208 return data
209
210def findConfigFile(configfile, data):
211 search = []
Brad Bishop6e60e8b2018-02-01 10:27:11 -0500212 bbpath = data.getVar("BBPATH")
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500213 if bbpath:
214 for i in bbpath.split(":"):
215 search.append(os.path.join(i, "conf", configfile))
216 path = os.getcwd()
217 while path != "/":
218 search.append(os.path.join(path, "conf", configfile))
219 path, _ = os.path.split(path)
220
221 for i in search:
222 if os.path.exists(i):
223 return i
224
225 return None
226
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500227#
228# We search for a conf/bblayers.conf under an entry in BBPATH or in cwd working
229# up to /. If that fails, we search for a conf/bitbake.conf in BBPATH.
230#
231
232def findTopdir():
233 d = bb.data.init()
234 bbpath = None
235 if 'BBPATH' in os.environ:
236 bbpath = os.environ['BBPATH']
237 d.setVar('BBPATH', bbpath)
238
239 layerconf = findConfigFile("bblayers.conf", d)
240 if layerconf:
241 return os.path.dirname(os.path.dirname(layerconf))
242 if bbpath:
243 bitbakeconf = bb.utils.which(bbpath, "conf/bitbake.conf")
244 if bitbakeconf:
245 return os.path.dirname(os.path.dirname(bitbakeconf))
246 return None
247
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500248class CookerDataBuilder(object):
249
250 def __init__(self, cookercfg, worker = False):
251
252 self.prefiles = cookercfg.prefile
253 self.postfiles = cookercfg.postfile
254 self.tracking = cookercfg.tracking
255
256 bb.utils.set_context(bb.utils.clean_context())
257 bb.event.set_class_handlers(bb.event.clean_class_handlers())
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600258 self.basedata = bb.data.init()
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500259 if self.tracking:
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600260 self.basedata.enableTracking()
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500261
262 # Keep a datastore of the initial environment variables and their
263 # values from when BitBake was launched to enable child processes
264 # to use environment variables which have been cleaned from the
265 # BitBake processes env
266 self.savedenv = bb.data.init()
267 for k in cookercfg.env:
268 self.savedenv.setVar(k, cookercfg.env[k])
269
270 filtered_keys = bb.utils.approved_variables()
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600271 bb.data.inheritFromOS(self.basedata, self.savedenv, filtered_keys)
272 self.basedata.setVar("BB_ORIGENV", self.savedenv)
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500273
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500274 if worker:
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600275 self.basedata.setVar("BB_WORKERCONTEXT", "1")
276
277 self.data = self.basedata
278 self.mcdata = {}
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500279
280 def parseBaseConfiguration(self):
281 try:
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600282 bb.parse.init_parser(self.basedata)
283 self.data = self.parseConfigurationFiles(self.prefiles, self.postfiles)
284
285 if self.data.getVar("BB_WORKERCONTEXT", False) is None:
286 bb.fetch.fetcher_init(self.data)
287 bb.codeparser.parser_cache_init(self.data)
288
289 bb.event.fire(bb.event.ConfigParsed(), self.data)
290
291 reparse_cnt = 0
292 while self.data.getVar("BB_INVALIDCONF", False) is True:
293 if reparse_cnt > 20:
294 logger.error("Configuration has been re-parsed over 20 times, "
295 "breaking out of the loop...")
296 raise Exception("Too deep config re-parse loop. Check locations where "
297 "BB_INVALIDCONF is being set (ConfigParsed event handlers)")
298 self.data.setVar("BB_INVALIDCONF", False)
299 self.data = self.parseConfigurationFiles(self.prefiles, self.postfiles)
300 reparse_cnt += 1
301 bb.event.fire(bb.event.ConfigParsed(), self.data)
302
303 bb.parse.init_parser(self.data)
304 self.data_hash = self.data.get_hash()
305 self.mcdata[''] = self.data
306
Brad Bishop6e60e8b2018-02-01 10:27:11 -0500307 multiconfig = (self.data.getVar("BBMULTICONFIG") or "").split()
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600308 for config in multiconfig:
Brad Bishop37a0e4d2017-12-04 01:01:44 -0500309 mcdata = self.parseConfigurationFiles(self.prefiles, self.postfiles, config)
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600310 bb.event.fire(bb.event.ConfigParsed(), mcdata)
311 self.mcdata[config] = mcdata
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500312 if multiconfig:
313 bb.event.fire(bb.event.MultiConfigParsed(self.mcdata), self.data)
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600314
315 except (SyntaxError, bb.BBHandledException):
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500316 raise bb.BBHandledException
317 except bb.data_smart.ExpansionError as e:
318 logger.error(str(e))
319 raise bb.BBHandledException
320 except Exception:
321 logger.exception("Error parsing configuration files")
322 raise bb.BBHandledException
323
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500324 # Create a copy so we can reset at a later date when UIs disconnect
325 self.origdata = self.data
326 self.data = bb.data.createCopy(self.origdata)
327 self.mcdata[''] = self.data
328
329 def reset(self):
330 # We may not have run parseBaseConfiguration() yet
331 if not hasattr(self, 'origdata'):
332 return
333 self.data = bb.data.createCopy(self.origdata)
334 self.mcdata[''] = self.data
335
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500336 def _findLayerConf(self, data):
337 return findConfigFile("bblayers.conf", data)
338
Brad Bishop37a0e4d2017-12-04 01:01:44 -0500339 def parseConfigurationFiles(self, prefiles, postfiles, mc = "default"):
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600340 data = bb.data.createCopy(self.basedata)
Brad Bishop37a0e4d2017-12-04 01:01:44 -0500341 data.setVar("BB_CURRENT_MC", mc)
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500342
343 # Parse files for loading *before* bitbake.conf and any includes
344 for f in prefiles:
345 data = parse_config_file(f, data)
346
347 layerconf = self._findLayerConf(data)
348 if layerconf:
349 parselog.debug(2, "Found bblayers.conf (%s)", layerconf)
350 # By definition bblayers.conf is in conf/ of TOPDIR.
351 # We may have been called with cwd somewhere else so reset TOPDIR
352 data.setVar("TOPDIR", os.path.dirname(os.path.dirname(layerconf)))
353 data = parse_config_file(layerconf, data)
354
Brad Bishop6e60e8b2018-02-01 10:27:11 -0500355 layers = (data.getVar('BBLAYERS') or "").split()
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500356
357 data = bb.data.createCopy(data)
358 approved = bb.utils.approved_variables()
359 for layer in layers:
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600360 if not os.path.isdir(layer):
361 parselog.critical("Layer directory '%s' does not exist! "
362 "Please check BBLAYERS in %s" % (layer, layerconf))
363 sys.exit(1)
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500364 parselog.debug(2, "Adding layer %s", layer)
365 if 'HOME' in approved and '~' in layer:
366 layer = os.path.expanduser(layer)
Patrick Williamsd8c66bc2016-06-20 12:57:21 -0500367 if layer.endswith('/'):
368 layer = layer.rstrip('/')
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500369 data.setVar('LAYERDIR', layer)
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600370 data.setVar('LAYERDIR_RE', re.escape(layer))
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500371 data = parse_config_file(os.path.join(layer, "conf", "layer.conf"), data)
372 data.expandVarref('LAYERDIR')
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600373 data.expandVarref('LAYERDIR_RE')
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500374
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600375 data.delVar('LAYERDIR_RE')
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500376 data.delVar('LAYERDIR')
377
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500378 bbfiles_dynamic = (data.getVar('BBFILES_DYNAMIC') or "").split()
379 collections = (data.getVar('BBFILE_COLLECTIONS') or "").split()
380 invalid = []
381 for entry in bbfiles_dynamic:
382 parts = entry.split(":", 1)
383 if len(parts) != 2:
384 invalid.append(entry)
385 continue
386 l, f = parts
387 if l in collections:
388 data.appendVar("BBFILES", " " + f)
389 if invalid:
390 bb.fatal("BBFILES_DYNAMIC entries must be of the form <collection name>:<filename pattern>, not:\n %s" % "\n ".join(invalid))
391
392 layerseries = set((data.getVar("LAYERSERIES_CORENAMES") or "").split())
393 for c in collections:
394 compat = set((data.getVar("LAYERSERIES_COMPAT_%s" % c) or "").split())
395 if compat and not (compat & layerseries):
396 bb.fatal("Layer %s is not compatible with the core layer which only supports these series: %s (layer is compatible with %s)"
397 % (c, " ".join(layerseries), " ".join(compat)))
398
Brad Bishop6e60e8b2018-02-01 10:27:11 -0500399 if not data.getVar("BBPATH"):
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500400 msg = "The BBPATH variable is not set"
401 if not layerconf:
402 msg += (" and bitbake did not find a conf/bblayers.conf file in"
403 " the expected location.\nMaybe you accidentally"
404 " invoked bitbake from the wrong directory?")
405 raise SystemExit(msg)
406
407 data = parse_config_file(os.path.join("conf", "bitbake.conf"), data)
408
409 # Parse files for loading *after* bitbake.conf and any includes
410 for p in postfiles:
411 data = parse_config_file(p, data)
412
413 # Handle any INHERITs and inherit the base class
Brad Bishop6e60e8b2018-02-01 10:27:11 -0500414 bbclasses = ["base"] + (data.getVar('INHERIT') or "").split()
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500415 for bbclass in bbclasses:
416 data = _inherit(bbclass, data)
417
418 # Nomally we only register event handlers at the end of parsing .bb files
419 # We register any handlers we've found so far here...
420 for var in data.getVar('__BBHANDLERS', False) or []:
Patrick Williamsd8c66bc2016-06-20 12:57:21 -0500421 handlerfn = data.getVarFlag(var, "filename", False)
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600422 if not handlerfn:
423 parselog.critical("Undefined event handler function '%s'" % var)
424 sys.exit(1)
Patrick Williamsd8c66bc2016-06-20 12:57:21 -0500425 handlerln = int(data.getVarFlag(var, "lineno", False))
Brad Bishop6e60e8b2018-02-01 10:27:11 -0500426 bb.event.register(var, data.getVar(var, False), (data.getVarFlag(var, "eventmask") or "").split(), handlerfn, handlerln)
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500427
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500428 data.setVar('BBINCLUDED',bb.parse.get_file_depends(data))
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500429
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600430 return data
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500431