blob: e408a35e15e262dd225a377508441b1cf5dcbc2c [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
44 self.options.tracking = False
45 if hasattr(self.options, "show_environment") and self.options.show_environment:
46 self.options.tracking = True
47
48 for key, val in self.options.__dict__.items():
49 setattr(self, key, val)
50
51 def parseCommandLine(self, argv=sys.argv):
52 raise Exception("Caller must implement commandline option parsing")
53
54 def parseEnvironment(self):
55 return os.environ.copy()
56
57 def updateFromServer(self, server):
58 if not self.options.cmd:
59 defaulttask, error = server.runCommand(["getVariable", "BB_DEFAULT_TASK"])
60 if error:
61 raise Exception("Unable to get the value of BB_DEFAULT_TASK from the server: %s" % error)
62 self.options.cmd = defaulttask or "build"
63 _, error = server.runCommand(["setConfig", "cmd", self.options.cmd])
64 if error:
65 raise Exception("Unable to set configuration option 'cmd' on the server: %s" % error)
66
67 if not self.options.pkgs_to_build:
Patrick Williamsf1e5d692016-03-30 15:21:19 -050068 bbpkgs, error = server.runCommand(["getVariable", "BBTARGETS"])
Patrick Williamsc124f4f2015-09-15 14:41:29 -050069 if error:
Patrick Williamsf1e5d692016-03-30 15:21:19 -050070 raise Exception("Unable to get the value of BBTARGETS from the server: %s" % error)
Patrick Williamsc124f4f2015-09-15 14:41:29 -050071 if bbpkgs:
72 self.options.pkgs_to_build.extend(bbpkgs.split())
73
74 def updateToServer(self, server, environment):
75 options = {}
76 for o in ["abort", "tryaltconfigs", "force", "invalidate_stamp",
77 "verbose", "debug", "dry_run", "dump_signatures",
78 "debug_domains", "extra_assume_provided", "profile",
79 "prefile", "postfile"]:
80 options[o] = getattr(self.options, o)
81
Brad Bishop6e60e8b2018-02-01 10:27:11 -050082 ret, error = server.runCommand(["updateConfig", options, environment, sys.argv])
Patrick Williamsc124f4f2015-09-15 14:41:29 -050083 if error:
84 raise Exception("Unable to update the server configuration with local parameters: %s" % error)
85
86 def parseActions(self):
87 # Parse any commandline into actions
88 action = {'action':None, 'msg':None}
89 if self.options.show_environment:
90 if 'world' in self.options.pkgs_to_build:
91 action['msg'] = "'world' is not a valid target for --environment."
92 elif 'universe' in self.options.pkgs_to_build:
93 action['msg'] = "'universe' is not a valid target for --environment."
94 elif len(self.options.pkgs_to_build) > 1:
95 action['msg'] = "Only one target can be used with the --environment option."
96 elif self.options.buildfile and len(self.options.pkgs_to_build) > 0:
97 action['msg'] = "No target should be used with the --environment and --buildfile options."
98 elif len(self.options.pkgs_to_build) > 0:
99 action['action'] = ["showEnvironmentTarget", self.options.pkgs_to_build]
100 else:
101 action['action'] = ["showEnvironment", self.options.buildfile]
102 elif self.options.buildfile is not None:
103 action['action'] = ["buildFile", self.options.buildfile, self.options.cmd]
104 elif self.options.revisions_changed:
105 action['action'] = ["compareRevisions"]
106 elif self.options.show_versions:
107 action['action'] = ["showVersions"]
108 elif self.options.parse_only:
109 action['action'] = ["parseFiles"]
110 elif self.options.dot_graph:
111 if self.options.pkgs_to_build:
112 action['action'] = ["generateDotGraph", self.options.pkgs_to_build, self.options.cmd]
113 else:
114 action['msg'] = "Please specify a package name for dependency graph generation."
115 else:
116 if self.options.pkgs_to_build:
117 action['action'] = ["buildTargets", self.options.pkgs_to_build, self.options.cmd]
118 else:
119 #action['msg'] = "Nothing to do. Use 'bitbake world' to build everything, or run 'bitbake --help' for usage information."
120 action = None
121 self.options.initialaction = action
122 return action
123
124class CookerConfiguration(object):
125 """
126 Manages build options and configurations for one run
127 """
128
129 def __init__(self):
130 self.debug_domains = []
131 self.extra_assume_provided = []
132 self.prefile = []
133 self.postfile = []
Patrick Williamsf1e5d692016-03-30 15:21:19 -0500134 self.prefile_server = []
135 self.postfile_server = []
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500136 self.debug = 0
137 self.cmd = None
138 self.abort = True
139 self.force = False
140 self.profile = False
141 self.nosetscene = False
Patrick Williamsd8c66bc2016-06-20 12:57:21 -0500142 self.setsceneonly = False
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500143 self.invalidate_stamp = False
144 self.dump_signatures = []
145 self.dry_run = False
146 self.tracking = False
147 self.interface = []
148 self.writeeventlog = False
Brad Bishop6e60e8b2018-02-01 10:27:11 -0500149 self.server_only = False
150 self.limited_deps = False
151 self.runall = None
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500152
153 self.env = {}
154
155 def setConfigParameters(self, parameters):
156 for key in self.__dict__.keys():
157 if key in parameters.options.__dict__:
158 setattr(self, key, parameters.options.__dict__[key])
159 self.env = parameters.environment.copy()
160 self.tracking = parameters.tracking
161
162 def setServerRegIdleCallback(self, srcb):
163 self.server_register_idlecallback = srcb
164
165 def __getstate__(self):
166 state = {}
167 for key in self.__dict__.keys():
168 if key == "server_register_idlecallback":
169 state[key] = None
170 else:
171 state[key] = getattr(self, key)
172 return state
173
174 def __setstate__(self,state):
175 for k in state:
176 setattr(self, k, state[k])
177
178
179def catch_parse_error(func):
180 """Exception handling bits for our parsing"""
181 @wraps(func)
182 def wrapped(fn, *args):
183 try:
184 return func(fn, *args)
185 except IOError as exc:
186 import traceback
187 parselog.critical(traceback.format_exc())
188 parselog.critical("Unable to parse %s: %s" % (fn, exc))
189 sys.exit(1)
Patrick Williamsd8c66bc2016-06-20 12:57:21 -0500190 except bb.data_smart.ExpansionError as exc:
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500191 import traceback
192
193 bbdir = os.path.dirname(__file__) + os.sep
194 exc_class, exc, tb = sys.exc_info()
195 for tb in iter(lambda: tb.tb_next, None):
196 # Skip frames in bitbake itself, we only want the metadata
197 fn, _, _, _ = traceback.extract_tb(tb, 1)[0]
198 if not fn.startswith(bbdir):
199 break
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600200 parselog.critical("Unable to parse %s" % fn, exc_info=(exc_class, exc, tb))
201 sys.exit(1)
Patrick Williamsd8c66bc2016-06-20 12:57:21 -0500202 except bb.parse.ParseError as exc:
203 parselog.critical(str(exc))
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500204 sys.exit(1)
205 return wrapped
206
207@catch_parse_error
208def parse_config_file(fn, data, include=True):
209 return bb.parse.handle(fn, data, include)
210
211@catch_parse_error
212def _inherit(bbclass, data):
213 bb.parse.BBHandler.inherit(bbclass, "configuration INHERITs", 0, data)
214 return data
215
216def findConfigFile(configfile, data):
217 search = []
Brad Bishop6e60e8b2018-02-01 10:27:11 -0500218 bbpath = data.getVar("BBPATH")
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500219 if bbpath:
220 for i in bbpath.split(":"):
221 search.append(os.path.join(i, "conf", configfile))
222 path = os.getcwd()
223 while path != "/":
224 search.append(os.path.join(path, "conf", configfile))
225 path, _ = os.path.split(path)
226
227 for i in search:
228 if os.path.exists(i):
229 return i
230
231 return None
232
233class CookerDataBuilder(object):
234
235 def __init__(self, cookercfg, worker = False):
236
237 self.prefiles = cookercfg.prefile
238 self.postfiles = cookercfg.postfile
239 self.tracking = cookercfg.tracking
240
241 bb.utils.set_context(bb.utils.clean_context())
242 bb.event.set_class_handlers(bb.event.clean_class_handlers())
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600243 self.basedata = bb.data.init()
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500244 if self.tracking:
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600245 self.basedata.enableTracking()
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500246
247 # Keep a datastore of the initial environment variables and their
248 # values from when BitBake was launched to enable child processes
249 # to use environment variables which have been cleaned from the
250 # BitBake processes env
251 self.savedenv = bb.data.init()
252 for k in cookercfg.env:
253 self.savedenv.setVar(k, cookercfg.env[k])
254
255 filtered_keys = bb.utils.approved_variables()
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600256 bb.data.inheritFromOS(self.basedata, self.savedenv, filtered_keys)
257 self.basedata.setVar("BB_ORIGENV", self.savedenv)
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500258
259 if worker:
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600260 self.basedata.setVar("BB_WORKERCONTEXT", "1")
261
262 self.data = self.basedata
263 self.mcdata = {}
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500264
265 def parseBaseConfiguration(self):
266 try:
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600267 bb.parse.init_parser(self.basedata)
268 self.data = self.parseConfigurationFiles(self.prefiles, self.postfiles)
269
270 if self.data.getVar("BB_WORKERCONTEXT", False) is None:
271 bb.fetch.fetcher_init(self.data)
272 bb.codeparser.parser_cache_init(self.data)
273
274 bb.event.fire(bb.event.ConfigParsed(), self.data)
275
276 reparse_cnt = 0
277 while self.data.getVar("BB_INVALIDCONF", False) is True:
278 if reparse_cnt > 20:
279 logger.error("Configuration has been re-parsed over 20 times, "
280 "breaking out of the loop...")
281 raise Exception("Too deep config re-parse loop. Check locations where "
282 "BB_INVALIDCONF is being set (ConfigParsed event handlers)")
283 self.data.setVar("BB_INVALIDCONF", False)
284 self.data = self.parseConfigurationFiles(self.prefiles, self.postfiles)
285 reparse_cnt += 1
286 bb.event.fire(bb.event.ConfigParsed(), self.data)
287
288 bb.parse.init_parser(self.data)
289 self.data_hash = self.data.get_hash()
290 self.mcdata[''] = self.data
291
Brad Bishop6e60e8b2018-02-01 10:27:11 -0500292 multiconfig = (self.data.getVar("BBMULTICONFIG") or "").split()
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600293 for config in multiconfig:
Brad Bishop37a0e4d2017-12-04 01:01:44 -0500294 mcdata = self.parseConfigurationFiles(self.prefiles, self.postfiles, config)
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600295 bb.event.fire(bb.event.ConfigParsed(), mcdata)
296 self.mcdata[config] = mcdata
297
298 except (SyntaxError, bb.BBHandledException):
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500299 raise bb.BBHandledException
300 except bb.data_smart.ExpansionError as e:
301 logger.error(str(e))
302 raise bb.BBHandledException
303 except Exception:
304 logger.exception("Error parsing configuration files")
305 raise bb.BBHandledException
306
307 def _findLayerConf(self, data):
308 return findConfigFile("bblayers.conf", data)
309
Brad Bishop37a0e4d2017-12-04 01:01:44 -0500310 def parseConfigurationFiles(self, prefiles, postfiles, mc = "default"):
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600311 data = bb.data.createCopy(self.basedata)
Brad Bishop37a0e4d2017-12-04 01:01:44 -0500312 data.setVar("BB_CURRENT_MC", mc)
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500313
314 # Parse files for loading *before* bitbake.conf and any includes
315 for f in prefiles:
316 data = parse_config_file(f, data)
317
318 layerconf = self._findLayerConf(data)
319 if layerconf:
320 parselog.debug(2, "Found bblayers.conf (%s)", layerconf)
321 # By definition bblayers.conf is in conf/ of TOPDIR.
322 # We may have been called with cwd somewhere else so reset TOPDIR
323 data.setVar("TOPDIR", os.path.dirname(os.path.dirname(layerconf)))
324 data = parse_config_file(layerconf, data)
325
Brad Bishop6e60e8b2018-02-01 10:27:11 -0500326 layers = (data.getVar('BBLAYERS') or "").split()
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500327
328 data = bb.data.createCopy(data)
329 approved = bb.utils.approved_variables()
330 for layer in layers:
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600331 if not os.path.isdir(layer):
332 parselog.critical("Layer directory '%s' does not exist! "
333 "Please check BBLAYERS in %s" % (layer, layerconf))
334 sys.exit(1)
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500335 parselog.debug(2, "Adding layer %s", layer)
336 if 'HOME' in approved and '~' in layer:
337 layer = os.path.expanduser(layer)
Patrick Williamsd8c66bc2016-06-20 12:57:21 -0500338 if layer.endswith('/'):
339 layer = layer.rstrip('/')
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500340 data.setVar('LAYERDIR', layer)
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600341 data.setVar('LAYERDIR_RE', re.escape(layer))
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500342 data = parse_config_file(os.path.join(layer, "conf", "layer.conf"), data)
343 data.expandVarref('LAYERDIR')
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600344 data.expandVarref('LAYERDIR_RE')
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500345
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600346 data.delVar('LAYERDIR_RE')
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500347 data.delVar('LAYERDIR')
348
Brad Bishop6e60e8b2018-02-01 10:27:11 -0500349 if not data.getVar("BBPATH"):
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500350 msg = "The BBPATH variable is not set"
351 if not layerconf:
352 msg += (" and bitbake did not find a conf/bblayers.conf file in"
353 " the expected location.\nMaybe you accidentally"
354 " invoked bitbake from the wrong directory?")
355 raise SystemExit(msg)
356
357 data = parse_config_file(os.path.join("conf", "bitbake.conf"), data)
358
359 # Parse files for loading *after* bitbake.conf and any includes
360 for p in postfiles:
361 data = parse_config_file(p, data)
362
363 # Handle any INHERITs and inherit the base class
Brad Bishop6e60e8b2018-02-01 10:27:11 -0500364 bbclasses = ["base"] + (data.getVar('INHERIT') or "").split()
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500365 for bbclass in bbclasses:
366 data = _inherit(bbclass, data)
367
368 # Nomally we only register event handlers at the end of parsing .bb files
369 # We register any handlers we've found so far here...
370 for var in data.getVar('__BBHANDLERS', False) or []:
Patrick Williamsd8c66bc2016-06-20 12:57:21 -0500371 handlerfn = data.getVarFlag(var, "filename", False)
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600372 if not handlerfn:
373 parselog.critical("Undefined event handler function '%s'" % var)
374 sys.exit(1)
Patrick Williamsd8c66bc2016-06-20 12:57:21 -0500375 handlerln = int(data.getVarFlag(var, "lineno", False))
Brad Bishop6e60e8b2018-02-01 10:27:11 -0500376 bb.event.register(var, data.getVar(var, False), (data.getVarFlag(var, "eventmask") or "").split(), handlerfn, handlerln)
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500377
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500378 data.setVar('BBINCLUDED',bb.parse.get_file_depends(data))
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500379
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600380 return data
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500381