From patchwork Mon Nov 30 15:28:36 2026 Content-Type: text/plain; charset="utf-8" MIME-Version: 1.0 Content-Transfer-Encoding: 7bit X-Patchwork-Submitter: Richard Purdie X-Patchwork-Id: 106515 Received: from mail-wr1-f43.google.com (mail-wr1-f43.google.com [209.85.221.43]) by mx.groups.io with SMTP id smtpd.msgproc01-g2.34597.1796052537327310873 for ; Mon, 30 Nov 2026 07:28:57 -0800 Authentication-Results: mx.groups.io; dkim=pass header.i=@linuxfoundation.org header.s=google header.b=RZiduzwe; spf=pass (domain: linuxfoundation.org, ip: 209.85.221.43, mailfrom: richard.purdie@linuxfoundation.org) Received: by mail-wr1-f43.google.com with SMTP id ffacd0b85a97d-4a9be758734so6752152f8f.1 for ; Mon, 30 Nov 2026 07:28:57 -0800 (PST) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=linuxfoundation.org; s=google; t=1796052535; x=1796657335; darn=lists.openembedded.org; h=content-transfer-encoding:mime-version:references:in-reply-to :message-id:date:subject:to:from:from:to:cc:subject:date:message-id :reply-to:content-type; bh=XpoS954Pd7HwuE6OCU5NJ3QXDwwFmv//gUcBVCyuaa4=; b=RZiduzwe+LI6d2DsOGmEs+iYQe42mPbnsCUOgJcGPCfYxlEz/VpqcR9qoZNbhqLeQL x97o3PGF/JKOBj678xek2n56yitC2wPZjmaoDtMQzWGvSllPft0MqkMHOqNUT4IhgtS4 ZRN1K2ihCJdLXZXwnWPnyha7jClDJ9hVi99xw= X-Google-DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=1e100.net; s=20260707; t=1796052535; x=1796657335; h=content-transfer-encoding:mime-version:references:in-reply-to :message-id:date:subject:to:from:x-gm-gg:x-gm-message-state:from:to :cc:subject:date:message-id:reply-to:content-type; bh=XpoS954Pd7HwuE6OCU5NJ3QXDwwFmv//gUcBVCyuaa4=; b=Lj80VAfVLnAXfCfz/lYtEsY5hfvvpapuIBdOfa33ayammSFtlGqqUmPNSwX6hPTBo/ CY8I5VCUztHwDIiEVB1Q8Yyr8TJ5S7ZmaBWktfVEg93PS9dUU+fMKvrfAQo1ODkImDIL RO7HNBSawEsXCl1C07Wg7dX6DqC6dVcYC3UvmN/TugWunn0L53IBaQWZKyDAybvKyouz XCLfuz4nyvsVG5fhY3PGy3HWpr7GVC6qzo3+jU6GMD1kvlwi0IoJjiCE6xa2uPm+11gw bxZZ5sln00F5lgfTbcDF2b8NVnHVi84BzxpHRH9/eYVgeYN3zZs5cosdKljxrKUoJWPd 7iqg== X-Gm-Message-State: APuU4Z8BZWN5IVeD8QErtuSgiVF+DvqU5rmtXaGvhLjY29U4Wp822/P7 jQx/pb86Mo5qOHR/MkWsLRevJJsXC89I6MDHnT8ey23j1aKOxMK+pZBbnQGceV5mLzRaFjLCL6h QVdzHG+w= X-Gm-Gg: AZFdTZd2529q/Q6A13LWkUT+sAisP4r5F5X1ESm5upTle5qcax8v3OTCYsQzG5DpZSA o9UttWMuLj1tmGWQ05Tt01Elq3qOIzyojWL9AR7ltTNoDCpUspHP3moAvFHUyU6Bp6Z0Bv1de3w zcETyYCVTCw62ex81LqP8DvGDC4dp2QN0PFAhX55RiyVoqZbP5YBH5xvnWnOWlXfyGrRB9NAams 55I1YtUfD87ZdDD6p7nTPAzZISP4zC2hEv+CHJDZk0Fele0p7orKz0dWFpz0fQPHx1wMRTLmIEI H1djPKpBsTDDNtsGswximuYxddjKkFIWLfv0kIpTZw6HZsbUYeG8UBwrciWy7eJBl6gQMHtY/8C H26YNj19uPrpG8GGt5VCHGvjAAwtuqjIZpVNZKUQ2TYBkuL9I+yifb0hYhrWGwihVW+kjHKTL8E eqQWbp5c61vM/a/Kpg9Nx0Q8MHSwCw+McO8HnCl9P2gP13EkROHso0Baq/LX5UZIA3gNLpTPG6d smz0QLgpS6lEAqE2yFj5V7f+lzLqfMi7KjellFtlyF5acrg78cqzrmZtfS8HAwviwNZCofSiqeH fXjzes3E0ThRh41/48Dtfh6jrx5G/IneYOq1xG6otFZwQnOnkKA71LgSfg== X-Received: by 2002:a05:6000:2382:b0:4c6:5d10:b9f0 with SMTP id ffacd0b85a97d-4c8dd42313amr1109158f8f.14.1796052534696; Mon, 30 Nov 2026 07:28:54 -0800 (PST) Return-Path: Received: from max.int.rpsys.net ([2001:8b0:aba:5f3c:2444:81bb:2aff:8d84]) by smtp.gmail.com with ESMTPSA id ffacd0b85a97d-4ab6baa397asm66033172f8f.48.2026.11.30.07.28.53 for (version=TLS1_3 cipher=TLS_AES_256_GCM_SHA384 bits=256/256); Mon, 30 Nov 2026 07:28:53 -0800 (PST) From: Richard Purdie To: bitbake-devel@lists.openembedded.org Subject: [PATCH 06/17] cooker: Change layer.conf handling to new approach Date: Mon, 30 Nov 2026 15:28:36 +0000 Message-ID: <20261130152847.3472849-6-richard.purdie@linuxfoundation.org> X-Mailer: git-send-email 2.55.0 In-Reply-To: <20261130152847.3472849-1-richard.purdie@linuxfoundation.org> References: <20261130152847.3472849-1-richard.purdie@linuxfoundation.org> MIME-Version: 1.0 List-Id: X-Webhook-Received: from 45-33-107-173.ip.linodeusercontent.com [45.33.107.173] by lin-tor-korg-lkml-alma10-1 with HTTPS for ; Mon, 30 Nov 2026 15:29:01 -0000 X-Groupsio-URL: https://lists.openembedded.org/g/bitbake-devel/message/20495 This is a fairly radical set of changes to the way layer.conf is handled and how it works with layers. I tried to split this into more specific changes but bascially I couldn't make that work in any reasonable way. It is not intended to be backward compatible even if some bits of syntax are similar. There were several historical issues: - layers can contain multiple 'collections' - priorities could depend on the file, collection and layer which interacted in ways people couldn't easily picture - layer.conf became a dumping ground for random variables - the current internal layer/collection 'names' are suboptimal This patch therefore: - Drops the concept of 'collections' - Drops layer priorities - Drops file priorities - Requires LAYERNAME to be set - Auto constructs BBPATH based on layer dependencies - AUto constructs BBFILES based on layer dependencies - Auto constructs BBFILES_DYNAMIC based on a "dynamic-recipes" directory - Filter layer.conf variables - Adds support for layer specific variables in layervars.conf - Sets LAYERDIR_ variables (and includes bitbake) - No longer supports layers within layers (multiple layers in a repo is still fine) More details notes follow (with examples from OE): """ layer.conf has radically changed and is now parsed in isolation on top of bblayers.conf. This means any changes made to variables in that file don't pass to other files or the global state by default. ":append" would only add to the value from bblayers. Overrides will not work as they're not defined at this point. layer.conf is now expected to set a LAYERNAME. The layer names are going to change. Some examples: "core" -> "oe-core" "openembedded-layer" -> "meta-oe" "networking-layer" -> meta-oe-networking" "virtualization-layer" -> "meta-virtualization" The idea is to have a consistent base prefix for combined repos so that the repo can be identified from the name (e.g. in a list of dependencies), and drop unneeded "-layer" suffix, make "core" clearer from other "core" things. As such, we are expecting layers to move to new names. Note that any fragment references also then need to use the new layer names. The LAYERDEPENDS and LAYERRECOMMENDS variables remain as before. LAYER* variables which traditionally had a collection name suffix, e.g. "_core" now don't need to be suffixed with the layername, but can be. The concepts of layer priorities, bbfile prorities and collections are all removed. This means the variables BFILE_COLLECTIONS, BBFILE_PRIORITY and BBFILE_PATTERN no longer do anything but trigger warnings. BBPATH and BBFILES no longer should be set by layer.conf. They are both now set based upon the information from LAYERDEPENDS. If you depend on a layer, you have the ability to change it. BBFILES will now just include .bb and .bbappend files in any recipes* directories. BBFILES_DYNAMIC is also no longer needed. Instead, bitbake will look for a "dynamic-recipes" directory and apply any subdirectories directories there based on layername, adding any files contained to BBFILES internally dynamically. Bitbake will set LAYERDIR_ in the global namespace. In addition, it will also set BITBAKEDIR to point at itself (OE-Core needs that, hopefully nothing else does and it is really for internal use to build PATH correctly). BBLAYERS no longer controls much other that the layers to include. There are two variables which are exceptions, LAYERSERIES_CORENAMES and LAYER_PASSTHROUGH_VARS_PREFIXES. These two are only set by the first layer included that sets them. For the layerseries, this is by historical precedent, I did this for the latter for now to potentially cover some weird use cases people may have. I am tempted to remove that special casing and only allow one layer to set those variables. There are some variables which can pass from layer.conf into the global scope. There is a list of variable prefixes which are accepted in LAYER_PASSTHROUGH_VARS_PREFIXES. These should be lists which work well with +=. This list is deliberately restrictive, I've worked with the sample layers to remove as many of them that I can. Layers do need some way of setting variables for their own recipes. This is done with a new layervars.conf, which recipes in a given layer will always have included (in .bb files but not .bbappend). Note that layervars.conf is parsed on top of the base configuration, so much later in parsing than layer.conf. One pattern we've noticed is layers wanting to warn that the configuration they provide is not enabled and to provide that config, usually as a DISTRO_FEATURE. I've changed meta-virtiualization to use fragments to enable the different configs (which can enable DISTRO_FEATURES in turn). That means we can add a LAYER_FRAGEMENTS_RECOMMEND_ANY variable which is used to warn when fragments aren't selected and the user can override with LAYER_FRAGEMENTS_OPTED_OUT to hide the warnings if they really don't want to select any. Some things are better imeplemented with conf files and a "include_all" directive in core. I've changed security flags and reproducible builds to do that, we should be doing this anyway. Some layers have been setting INHERIT in layer.conf. This is no longer supported and should be done by configuration files/fragments instead. It can be done in layervars.conf but will only apply to recipes in that layer (and not bbapends). There is a BB_LAYER_FILTER_FUNC variable which takes the name of function which can make final changes to the datastore at the end of "layer" parsing before the main parse. If your layer is intended to be shared at all and used by others outside your own context, you *should not* be using this. It can only be set once, by the first layer.conf found that sets it. From an internals perspective, there is now a Layers object stored in the datastore as "layerdata". This is useful for some areas of the code to be able to work with layers, such as the fragment code. It is considered semi-internal API at this point. It does mean anyone iterating datastore values needs to be careful about non-text return values but we already have those. """ Signed-off-by: Richard Purdie --- .../bitbake-user-manual-metadata.rst | 2 +- .../bitbake-user-manual-ref-variables.rst | 56 +--- lib/bb/command.py | 9 - lib/bb/cooker.py | 214 +------------ lib/bb/cookerdata.py | 302 ++++++++++++++---- lib/bb/parse/ast.py | 26 +- 6 files changed, 273 insertions(+), 336 deletions(-) diff --git a/doc/bitbake-user-manual/bitbake-user-manual-metadata.rst b/doc/bitbake-user-manual/bitbake-user-manual-metadata.rst index 27711b2c849..3fe4489aebb 100644 --- a/doc/bitbake-user-manual/bitbake-user-manual-metadata.rst +++ b/doc/bitbake-user-manual/bitbake-user-manual-metadata.rst @@ -1021,7 +1021,7 @@ variable like this:: OE_FRAGMENTS = "core/domain/somefragment core/someotherfragment anotherlayer/anotherdomain/anotherfragment" Fragment names listed in this variable must be prefixed by the layer name -where a fragment file is located, defined by :term:`BBFILE_COLLECTIONS` in ``layer.conf``. +where a fragment file is located, defined by :term:`LAYERNAME` in ``layer.conf``. The implementation then expands this list into :ref:`require ` diff --git a/doc/bitbake-user-manual/bitbake-user-manual-ref-variables.rst b/doc/bitbake-user-manual/bitbake-user-manual-ref-variables.rst index e258e7afd64..7d3b97bc6ba 100644 --- a/doc/bitbake-user-manual/bitbake-user-manual-ref-variables.rst +++ b/doc/bitbake-user-manual/bitbake-user-manual-ref-variables.rst @@ -922,48 +922,6 @@ overview of their function and contents. You must set this variable in the external environment in order for it to work. - :term:`BBFILE_COLLECTIONS` - Lists the names of configured layers. These names are used to find - the other ``BBFILE_*`` variables. Typically, each layer appends its - name to this variable in its ``conf/layer.conf`` file. - - :term:`BBFILE_PATTERN` - Variable that expands to match files from - :term:`BBFILES` in a particular layer. This - variable is used in the ``conf/layer.conf`` file and must be suffixed - with the name of the specific layer (e.g. - ``BBFILE_PATTERN_emenlow``). - - :term:`BBFILE_PRIORITY` - Assigns the priority for recipe files in each layer. - - This variable is used in the ``conf/layer.conf`` file and must be - suffixed with a `_` followed by the name of the specific layer (e.g. - ``BBFILE_PRIORITY_emenlow``). Colon as separator is not supported. - - This variable is useful in situations where the same recipe appears - in more than one layer. Setting this variable allows you to - prioritize a layer against other layers that contain the same recipe - --- effectively letting you control the precedence for the multiple - layers. The precedence established through this variable stands - regardless of a recipe's version (:term:`PV` variable). - For example, a layer that has a recipe with a higher :term:`PV` value but - for which the :term:`BBFILE_PRIORITY` is set to have a lower precedence - still has a lower precedence. - - A larger value for the :term:`BBFILE_PRIORITY` variable results in a - higher precedence. For example, the value 6 has a higher precedence - than the value 5. If not specified, the :term:`BBFILE_PRIORITY` variable - is set based on layer dependencies (see the :term:`LAYERDEPENDS` variable - for more information). The default priority, if unspecified for a - layer with no dependencies, is the lowest defined priority + 1 (or 1 - if no priorities are defined). - - .. tip:: - - You can use the command bitbake-layers show-layers to list all - configured layers along with their priorities. - :term:`BBFILES` A space-separated list of recipe files BitBake uses to build software. @@ -1198,6 +1156,9 @@ overview of their function and contents. Allows you to use a configuration file to add to the list of command-line target recipes you want to build. + :term:`BITBAKEDIR` + BitBake sets this to location where bitbake is being run from. + :term:`BITBAKE_UI` Used to specify the UI module to use when running BitBake. Using this variable is equivalent to using the ``-u`` command-line option. @@ -1375,12 +1336,13 @@ overview of their function and contents. available outside of ``layer.conf`` and references are expanded immediately when parsing of the file completes. - :term:`LAYERDIR_RE` + :term:`LAYERDIR_` + + LAYERDIR_ is defined as the path each named layer is located. + + :term:`LAYERNAME` When used inside the ``layer.conf`` configuration file, this variable - provides the path of the current layer, escaped for use in a regular - expression (:term:`BBFILE_PATTERN`). This - variable is not available outside of ``layer.conf`` and references - are expanded immediately when parsing of the file completes. + provides the name assigned to the current layer. :term:`LAYERSERIES_COMPAT` Lists the versions of the OpenEmbedded-Core (OE-Core) for which diff --git a/lib/bb/command.py b/lib/bb/command.py index 9848b7a6732..b33e81d3e9a 100644 --- a/lib/bb/command.py +++ b/lib/bb/command.py @@ -300,15 +300,6 @@ class CommandsSync: command.cooker.parseConfiguration() parseConfiguration.needconfig = False - def getLayerPriorities(self, command, params): - command.cooker.parseConfiguration() - ret = [] - # regex objects cannot be marshalled by xmlrpc - for collection, pattern, regex, pri in command.cooker.bbfile_config_priorities: - ret.append((collection, pattern, regex.pattern, pri)) - return ret - getLayerPriorities.readonly = True - def revalidateCaches(self, command, params): """Called by UI clients when metadata may have changed""" command.cooker.revalidateCaches() diff --git a/lib/bb/cooker.py b/lib/bb/cooker.py index 7fca4ac2f74..31a78743406 100644 --- a/lib/bb/cooker.py +++ b/lib/bb/cooker.py @@ -454,10 +454,9 @@ You can also remove the BB_HASHSERVE_UPSTREAM setting, but this may result in si for mc in self.multiconfigs: self.recipecaches[mc] = bb.cache.CacheData(self.caches_array) - self.handleCollections(self.data.getVar("BBFILE_COLLECTIONS")) self.collections = {} for mc in self.multiconfigs: - self.collections[mc] = CookerCollectFiles(self.bbfile_config_priorities, mc) + self.collections[mc] = CookerCollectFiles(self.databuilder.layerdata, mc) self.collections[mc].collect_bbfiles(self.databuilder.mcdata[mc], self.databuilder.mcdata[mc]) self._parsecache_set(False) @@ -791,7 +790,7 @@ You can also remove the BB_HASHSERVE_UPSTREAM setting, but this may result in si depend_tree["rdepends-pkg"] = {} depend_tree["rrecs-pkg"] = {} depend_tree['providermap'] = {} - depend_tree["layer-priorities"] = self.bbfile_config_priorities + depend_tree["layer-priorities"] = None for mc in taskdata: for name, fn in list(taskdata[mc].get_providermap().items()): @@ -1181,129 +1180,6 @@ You can also remove the BB_HASHSERVE_UPSTREAM setting, but this may result in si else: shell.start( self ) - - def handleCollections(self, collections): - """Handle collections""" - errors = False - self.bbfile_config_priorities = [] - if collections: - collection_priorities = {} - collection_depends = {} - collection_list = collections.split() - min_prio = 0 - for c in collection_list: - bb.debug(1,'Processing %s in collection list' % (c)) - - # Get collection priority if defined explicitly - priority = self.data.getVar("BBFILE_PRIORITY_%s" % c) - if priority: - try: - prio = int(priority) - except ValueError: - parselog.error("invalid value for BBFILE_PRIORITY_%s: \"%s\"", c, priority) - errors = True - if min_prio == 0 or prio < min_prio: - min_prio = prio - collection_priorities[c] = prio - else: - collection_priorities[c] = None - - # Check dependencies and store information for priority calculation - deps = self.data.getVar("LAYERDEPENDS_%s" % c) - if deps: - try: - depDict = bb.utils.explode_dep_versions2(deps) - except bb.utils.VersionStringException as vse: - bb.fatal('Error parsing LAYERDEPENDS_%s: %s' % (c, str(vse))) - for dep, oplist in list(depDict.items()): - if dep in collection_list: - for opstr in oplist: - layerver = self.data.getVar("LAYERVERSION_%s" % dep) - (op, depver) = opstr.split() - if layerver: - try: - res = bb.utils.vercmp_string_op(layerver, depver, op) - except bb.utils.VersionStringException as vse: - bb.fatal('Error parsing LAYERDEPENDS_%s: %s' % (c, str(vse))) - if not res: - parselog.error("Layer '%s' depends on version %s of layer '%s', but version %s is currently enabled in your configuration. Check that you are using the correct matching versions/branches of these two layers.", c, opstr, dep, layerver) - errors = True - else: - parselog.error("Layer '%s' depends on version %s of layer '%s', which exists in your configuration but does not specify a version. Check that you are using the correct matching versions/branches of these two layers.", c, opstr, dep) - errors = True - else: - parselog.error("Layer '%s' depends on layer '%s', but this layer is not enabled in your configuration", c, dep) - errors = True - collection_depends[c] = list(depDict.keys()) - else: - collection_depends[c] = [] - - # Check recommends and store information for priority calculation - recs = self.data.getVar("LAYERRECOMMENDS_%s" % c) - if recs: - try: - recDict = bb.utils.explode_dep_versions2(recs) - except bb.utils.VersionStringException as vse: - bb.fatal('Error parsing LAYERRECOMMENDS_%s: %s' % (c, str(vse))) - for rec, oplist in list(recDict.items()): - if rec in collection_list: - if oplist: - opstr = oplist[0] - layerver = self.data.getVar("LAYERVERSION_%s" % rec) - if layerver: - (op, recver) = opstr.split() - try: - res = bb.utils.vercmp_string_op(layerver, recver, op) - except bb.utils.VersionStringException as vse: - bb.fatal('Error parsing LAYERRECOMMENDS_%s: %s' % (c, str(vse))) - if not res: - parselog.debug3("Layer '%s' recommends version %s of layer '%s', but version %s is currently enabled in your configuration. Check that you are using the correct matching versions/branches of these two layers.", c, opstr, rec, layerver) - continue - else: - parselog.debug3("Layer '%s' recommends version %s of layer '%s', which exists in your configuration but does not specify a version. Check that you are using the correct matching versions/branches of these two layers.", c, opstr, rec) - continue - parselog.debug3("Layer '%s' recommends layer '%s', so we are adding it", c, rec) - collection_depends[c].append(rec) - else: - parselog.debug3("Layer '%s' recommends layer '%s', but this layer is not enabled in your configuration", c, rec) - - # Recursively work out collection priorities based on dependencies - def calc_layer_priority(collection): - if not collection_priorities[collection]: - max_depprio = min_prio - for dep in collection_depends[collection]: - calc_layer_priority(dep) - depprio = collection_priorities[dep] - if depprio > max_depprio: - max_depprio = depprio - max_depprio += 1 - parselog.debug("Calculated priority of layer %s as %d", collection, max_depprio) - collection_priorities[collection] = max_depprio - - # Calculate all layer priorities using calc_layer_priority and store in bbfile_config_priorities - for c in collection_list: - calc_layer_priority(c) - regex = self.data.getVar("BBFILE_PATTERN_%s" % c) - if regex is None: - parselog.error("BBFILE_PATTERN_%s not defined" % c) - errors = True - continue - elif regex == "": - parselog.debug("BBFILE_PATTERN_%s is empty" % c) - cre = re.compile('^NULL$') - errors = False - else: - try: - cre = re.compile(regex) - except re.error: - parselog.error("BBFILE_PATTERN_%s \"%s\" is not a valid regular expression", c, regex) - errors = True - continue - self.bbfile_config_priorities.append((c, regex, cre, collection_priorities[c])) - if errors: - # We've already printed the actual error(s) - raise CollectionError("Errors during parsing layer configuration") - def buildSetVars(self): """ Setup any variables needed before starting a build @@ -1621,7 +1497,7 @@ You can also remove the BB_HASHSERVE_UPSTREAM setting, but this may result in si if flags and "func" in flags and "python" in flags: expand = False v = self.data.getVar(k, expand) - if not k.startswith("__") and not isinstance(v, bb.data_smart.DataSmart): + if not k.startswith("__") and not isinstance(v, bb.data_smart.DataSmart) and not isinstance(v, dict): dump[k] = { 'v' : str(v) , 'history' : self.data.varhistory.variable(k), @@ -1819,25 +1695,16 @@ class CookerExit(bb.event.Event): class CookerCollectFiles(object): - def __init__(self, priorities, mc=''): + def __init__(self, layerdata, mc=''): self.mc = mc self.bbappends = [] self.overlayed = None - # Priorities is a list of tuples, with the second element as the pattern. - # We need to sort the list with the longest pattern first, and so on to - # the shortest. This allows nested layers to be properly evaluated. - self.bbfile_config_priorities = sorted(priorities, key=lambda tup: tup[1], reverse=True) - - def calc_bbfile_priority(self, filename): - for layername, _, regex, pri in self.bbfile_config_priorities: - if regex.match(filename): - return pri, regex, layername - return 0, None, None + self.layerdata = layerdata def get_layername(self, filename): - for layername, _, regex, _ in self.bbfile_config_priorities: - if regex.match(filename): - return layername + for layer in self.layerdata: + if filename.startswith(self.layerdata[layer].path + "/"): + return layer return None def get_bbfiles(self): @@ -1857,7 +1724,8 @@ class CookerCollectFiles(object): for ignored in ('SCCS', 'CVS', '.svn'): if ignored in dirs: dirs.remove(ignored) - found += [os.path.join(dir, f) for f in files if (f.endswith(('.bb', '.bbappend')))] + dirs.sort() + found += [os.path.join(dir, f) for f in sorted(files) if (f.endswith(('.bb', '.bbappend')))] return found @@ -1992,68 +1860,6 @@ class CookerCollectFiles(object): filelist.append(filename) return tuple(filelist) - def collection_priorities(self, pkgfns, fns, d): - # Return the priorities of the entries in pkgfns - # Also check that all the regexes in self.bbfile_config_priorities are used - # (but to do that we need to ensure skipped recipes aren't counted, nor - # collections in BBFILE_PATTERN_IGNORE_EMPTY) - - priorities = {} - seen = set() - matched = set() - - matched_regex = set() - unmatched_regex = set() - for _, _, regex, _ in self.bbfile_config_priorities: - unmatched_regex.add(regex) - - # Calculate priorities for each file - for p in pkgfns: - realfn, cls, mc = bb.cache.virtualfn2realfn(p) - priorities[p], regex, _ = self.calc_bbfile_priority(realfn) - if regex in unmatched_regex: - matched_regex.add(regex) - unmatched_regex.remove(regex) - seen.add(realfn) - if regex: - matched.add(realfn) - - if unmatched_regex: - # Account for bbappend files - for b in self.bbappends: - (bbfile, append) = b - seen.add(append) - - # Account for skipped recipes - seen.update(fns) - - seen.difference_update(matched) - - def already_matched(fn): - for regex in matched_regex: - if regex.match(fn): - return True - return False - - for unmatch in unmatched_regex.copy(): - for fn in seen: - if unmatch.match(fn): - # If the bbappend or file was already matched by another regex, skip it - # e.g. for a layer within a layer, the outer regex could match, the inner - # regex may match nothing and we should warn about that - if already_matched(fn): - continue - unmatched_regex.remove(unmatch) - break - - for collection, pattern, regex, _ in self.bbfile_config_priorities: - if regex in unmatched_regex: - if d.getVar('BBFILE_PATTERN_IGNORE_EMPTY_%s' % collection) != '1': - collectlog.warning("No bb files in %s matched BBFILE_PATTERN_%s '%s'" % (self.mc if self.mc else 'default', - collection, pattern)) - - return priorities - class ParsingFailure(Exception): def __init__(self, realexception, recipe): self.realexception = realexception diff --git a/lib/bb/cookerdata.py b/lib/bb/cookerdata.py index 87310af7ce6..3bea91e2387 100644 --- a/lib/bb/cookerdata.py +++ b/lib/bb/cookerdata.py @@ -10,11 +10,13 @@ # SPDX-License-Identifier: GPL-2.0-only # +import dataclasses import logging import os import re import sys import hashlib +import graphlib from functools import wraps import bb.cache @@ -226,6 +228,22 @@ def findTopdir(): return os.path.abspath(os.getcwd()) +@dataclasses.dataclass(repr=False) +class Layer: + path: str + version: str + compat: set[str] = dataclasses.field(default_factory=set) + depends: dict[dict] = dataclasses.field(default_factory=dict) + recommends: dict[dict] = dataclasses.field(default_factory=dict) + fragment_recommends_any: set[str] = dataclasses.field(default_factory=set) + + # We need the cache to have a consistent value which sets won't allow so we need + # a custom sortable repr. + def __repr__(self): + return "Layer(path=%r, version=%r, compat=%r, depends=%r, recommends=%r, fragment_recommends_any=%r)" % ( + self.path, self.version, sorted(self.compat), self.depends, + self.recommends, sorted(self.fragment_recommends_any)) + class CookerDataBuilder(object): def __init__(self, cookercfg, worker = False): @@ -280,7 +298,7 @@ class CookerDataBuilder(object): def parseBaseConfiguration(self, worker=False): mcdata = {} try: - self.data = self.parseConfigurationFiles(self.prefiles, self.postfiles) + self.data, self.layerdata = self.parseConfigurationFiles(self.prefiles, self.postfiles) servercontext = self.data.getVar("BB_WORKERCONTEXT", False) is None and not worker bb.fetch.fetcher_init(self.data, servercontext) @@ -296,7 +314,7 @@ class CookerDataBuilder(object): raise Exception("Too deep config re-parse loop. Check locations where " "BB_INVALIDCONF is being set (ConfigParsed event handlers)") self.data.setVar("BB_INVALIDCONF", False) - self.data = self.parseConfigurationFiles(self.prefiles, self.postfiles) + self.data, self.layerdata = self.parseConfigurationFiles(self.prefiles, self.postfiles) reparse_cnt += 1 bb.event.fire(bb.event.ConfigParsed(), self.data) @@ -307,7 +325,7 @@ class CookerDataBuilder(object): for config in multiconfig: if config[0].isdigit(): bb.fatal("Multiconfig name '%s' is invalid as multiconfigs cannot start with a digit" % config) - parsed_mcdata = self.parseConfigurationFiles(self.prefiles, self.postfiles, config) + parsed_mcdata, _ = self.parseConfigurationFiles(self.prefiles, self.postfiles, config) bb.event.fire(bb.event.ConfigParsed(), parsed_mcdata) mcdata[config] = parsed_mcdata if multiconfig: @@ -369,6 +387,7 @@ class CookerDataBuilder(object): data = parse_config_file(f, data) layerconf = self._findLayerConf(data) + layerdata = {} if layerconf: parselog.debug2("Found bblayers.conf (%s)", layerconf) # By definition bblayers.conf is in conf/ of TOPDIR. @@ -402,77 +421,215 @@ class CookerDataBuilder(object): parselog.critical("Please check BBLAYERS in %s" % (layerconf)) raise bb.BBHandledException() + bitbakedir = os.path.realpath(os.path.dirname(__file__) + "/../../") + data.setVar("BITBAKEDIR", bitbakedir) + data.setVarFlag("BITBAKEDIR", "vardepvalue", "") + layerseries = None - compat_entries = {} + layer_safevars = tuple() + layer_filterfunc = None + errors = [] + datastores = {} for layer in layers: - parselog.debug2("Adding layer %s", layer) + parselog.debug2("Adding layer %s" % layer) if 'HOME' in approved and '~' in layer: layer = os.path.expanduser(layer) if layer.endswith('/'): layer = layer.rstrip('/') - data.setVar('LAYERDIR', layer) - data.setVar('LAYERDIR_RE', re.escape(layer)) - data = parse_config_file(os.path.join(layer, "conf", "layer.conf"), data) - data.expandVarref('LAYERDIR') - data.expandVarref('LAYERDIR_RE') - - # Sadly we can't have nice things. - # Some layers think they're going to be 'clever' and copy the values from - # another layer, e.g. using ${LAYERSERIES_COMPAT_core}. The whole point of - # this mechanism is to make it clear which releases a layer supports and - # show when a layer master branch is bitrotting and is unmaintained. - # We therefore avoid people doing this here. - collections = (data.getVar('BBFILE_COLLECTIONS') or "").split() - for c in collections: - compat_entry = data.getVar("LAYERSERIES_COMPAT_%s" % c) - if compat_entry: - compat_entries[c] = set(compat_entry.split()) - data.delVar("LAYERSERIES_COMPAT_%s" % c) - if not layerseries: - layerseries = set((data.getVar("LAYERSERIES_CORENAMES") or "").split()) - if layerseries: - data.delVar("LAYERSERIES_CORENAMES") - - data.delVar('LAYERDIR_RE') - data.delVar('LAYERDIR') - for c in compat_entries: - data.setVar("LAYERSERIES_COMPAT_%s" % c, " ".join(sorted(compat_entries[c]))) - - bbfiles_dynamic = (data.getVar('BBFILES_DYNAMIC') or "").split() - collections = (data.getVar('BBFILE_COLLECTIONS') or "").split() - invalid = [] - for entry in bbfiles_dynamic: - parts = entry.split(":", 1) - if len(parts) != 2: - invalid.append(entry) + layer = os.path.realpath(layer) + + ld = data.createCopy() + ld.setVar('LAYERDIR', layer) + #ld.setVar('LAYERDIR_RE', re.escape(layer)) + layerfile = os.path.join(layer, "conf", "layer.conf") + ld = parse_config_file(layerfile, ld) + bb.parse.mark_dependency(data, layerfile) + + layername = ld.getVar("LAYERNAME") + if not layername: + errors.append("Layer %s does not set LAYERNAME" % layer) + continue + if layername in layerdata: + errors.append("LAYERNAME %s is used by both %s and %s" % (layername, layer, layerdata[layername].path)) continue - l, f = parts - invert = l[0] == "!" - if invert: - l = l[1:] - if (l in collections and not invert) or (l not in collections and invert): - data.appendVar("BBFILES", " " + f) - if invalid: - bb.fatal("BBFILES_DYNAMIC entries must be of the form {!}:, not:\n %s" % "\n ".join(invalid)) - - collections_tmp = collections[:] - for c in collections: - collections_tmp.remove(c) - if c in collections_tmp: - bb.fatal("Found duplicated BBFILE_COLLECTIONS '%s', check bblayers.conf or layer.conf to fix it." % c) - - compat = set() - if c in compat_entries: - compat = compat_entries[c] - if compat and not layerseries: - bb.fatal("No core layer found to work with layer '%s'. Missing entry in bblayers.conf?" % c) - if compat and not (compat & layerseries): - bb.fatal("Layer %s is not compatible with the core layer which only supports these series: %s (layer is compatible with %s)" - % (c, " ".join(layerseries), " ".join(compat))) - elif not compat and not data.getVar("BB_WORKERCONTEXT"): - 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)) + nested = False + for pathcheck in layerdata: + otherpath = layerdata[pathcheck].path + if layer.startswith(otherpath + "/") or otherpath.startswith(layer + "/"): + errors.append("Layer path %s (layer %s) conflicts with path %s from layer %s. Layers can't nest." % (layer, layername, otherpath, pathcheck)) + nested = True + if nested: + continue + + def getVar(var, layername, ld): + value = ld.getVar(var) + if not value: + value = ld.getVar("%s_%s" % (var, layername)) + return value + + layerdata[layername] = Layer( + path=layer, + version=getVar("LAYERVERSION", layername, ld) or "1", + compat=set((getVar("LAYERSERIES_COMPAT", layername, ld) or "").split()), + depends=bb.utils.explode_dep_versions2(getVar("LAYERDEPENDS", layername, ld) or ""), + recommends=bb.utils.explode_dep_versions2(getVar("LAYERRECOMMENDS", layername, ld) or ""), + fragment_recommends_any=set((getVar("LAYER_FRAGMENT_RECOMMENDS_ANY", layername, ld) or "").split()), + ) + + if not layerdata[layername].compat: + errors.append("Layer %s should set LAYERSERIES_COMPAT in its conf/layer.conf file to list the core layer names it is compatible with." % (layername)) + + if not layerseries: + layerseries = set((ld.getVar("LAYERSERIES_CORENAMES") or "").split()) + if not layer_safevars: + layer_safevars = tuple((ld.getVar("LAYER_PASSTHROUGH_VARS_PREFIXES") or "").split()) + if not layer_filterfunc: + layer_filterfunc = ld.getVar("BB_LAYER_FILTER_FUNC") + datastores[layer] = ld + + for layername in layerdata: + data.setVar("LAYERDIR_%s" % layername, layerdata[layername].path) + data.setVarFlag("LAYERDIR_%s" % layername, "vardepvalue", "") + + def copy_layer_history(var, data, ld): + base = len(initial.varhistory.variable(var)) + for entry in ld.varhistory.variable(var)[base:]: + if "flag" not in entry: + data.varhistory.record(**entry) + + initial = data + data = data.createCopy() + for layer in sorted(datastores): + ld = datastores[layer] + for var in ld: + if var.startswith(("LAYERNAME", "LAYERDEPENDS", "LAYERRECOMMENDS", "LAYERVERSION", "LAYERSERIES_COMPAT", "LAYERSERIES_CORENAMES", "LAYERDIR", "LAYER_FRAGMENT_RECOMMENDS_ANY", "LAYER_PASSTHROUGH_VARS_PREFIXES")): + continue + if var.startswith(("BBFILE_COLLECTIONS", "BBFILE_PRIORITY", "BBFILE_PATTERN")): + bb.warn("Support for %s was removed and the variable is being ignored but is set by layer %s" % (var, layer)) + continue + if var in ["__depends"]: + continue + if var in ["BBPATH", "BBFILES", "BBFILES_DYNAMIC"]: + if ld.getVar(var) != data.getVar(var): + bb.warn("%s now set automatically, the variable is being ignored but is set by layer %s" % (var, layer)) + bb.warn(str(ld.getVar(var, expand=False))) + continue + append = None + if var in initial: + orig = initial.getVar(var, False) + new = ld.getVar(var, False) + if orig == new: + continue + if not new.startswith(orig): + errors.append("Layer %s is overwriting variable %s, it should only append to it" % (layer, var)) + continue + append = new.removeprefix(orig) + if var.startswith(layer_safevars): + pass + elif var.startswith(("BBLAYERS_LAYERINDEX_NAME", "BB_GLOBAL_PYMODULES")): + pass + else: + bb.warn("Variable %s is set by %s but it will be ignored" % (var, layer)) + continue + + copy_layer_history(var, data, ld) + if append: + data.appendVar(var, append) + elif var in data: + # Assume that if multiple layers set it, it should be space separated. + data.appendVar(var, " " + ld.getVar(var, False)) + else: + data.setVar(var, ld.getVar(var, False)) + if not layerseries: + errors.append("No layer sets LAYERSERIES_CORENAMES") data.setVar("LAYERSERIES_CORENAMES", " ".join(sorted(layerseries))) + data.setVar("LAYER_PASSTHROUGH_VARS_PREFIXES", " ".join(layer_safevars)) + + layers = set(layerdata) + for layer in layerdata: + if not (layerdata[layer].compat & layerseries): + errors.append("Layer %s is not compatible with the core layer which only supports these series: %s (layer is compatible with %s)" + % (layer, " ".join(layerseries), " ".join(layerdata[layer].compat))) + + # Check dependencies + if not set(layerdata[layer].depends).issubset(layers): + errors.append("Layer %s depends on %s but that layer isn't configured" % (layer, " ".join(set(layerdata[layer].depends) - layers))) + continue + + # Check dependency versions + for dep in layerdata[layer].depends: + for verop in layerdata[layer].depends[dep]: + (op, depver) = verop.split() + layerver = layerdata[dep].version + if not layerver: + errors.append("Layer '%s' depends on version %s of layer '%s', which exists in your configuration but does not specify a version. Check that you are using the correct matching versions/branches of these two layers." % (layer, verop, dep)) + continue + try: + res = bb.utils.vercmp_string_op(layerver, depver, op) + except bb.utils.VersionStringException as vse: + bb.fatal('Error parsing LAYERDEPENDS for layer %s: %s' % (layer, str(vse))) + if not res: + errors.append("Layer '%s' depends on version %s of layer '%s', but version %s is currently enabled in your configuration. Check that you are using the correct matching versions/branches of these two layers." % (layer, verop, dep, layerver)) + + # Check recommends versions + for dep in layerdata[layer].recommends: + for verop in layerdata[layer].recommends[dep]: + if dep not in layerdata: + continue + (op, depver) = verop.split() + layerver = layerdata[dep].version + if not layerver: + errors.append("Layer '%s' recommends version %s of layer '%s', which exists in your configuration but does not specify a version. Check that you are using the correct matching versions/branches of these two layers." % (layer, verop, dep)) + continue + try: + res = bb.utils.vercmp_string_op(layerver, depver, op) + except bb.utils.VersionStringException as vse: + bb.fatal('Error parsing LAYERRECOMMENDS for layer %s: %s' % (layer, str(vse))) + if not res: + errors.append("Layer '%s' recommends version %s of layer '%s', but version %s is currently enabled in your configuration. Check that you are using the correct matching versions/branches of these two layers." % (layer, verop, dep, layerver)) + + data.setVar("layerdata", layerdata) + + if errors: + for error in errors: + bb.error(error) + bb.fatal("Layer errors found, parsing stopped") + + # Using the layer dependencies, work out the order layers should be listed + # in BBPATH and searched for BBFILES + layerorder = graphlib.TopologicalSorter() + for layer in sorted(layerdata.keys()): + layerorder.add(layer) + for dep in layerdata[layer].depends: + layerorder.add(layer, dep) + + try: + ordering = list(layerorder.static_order()) + except graphlib.CycleError as exc: + bb.fatal("Circular dependencies found from LAYERDEPENDS, can't continue. (%s)" % str(exc)) + + # Construct BBPATH + data.setVar("BBPATH", ":".join(["${TOPDIR}"] + [layerdata[layer].path for layer in ordering[::-1]])) + + # Construct BBFILES + # - any recipes subdirs are added through a glob + # - any /dynamic-recipes// are added if the named layer is present + bbfiles = [] + for layer in ordering: + recipes = layerdata[layer].path + "/recipes*" + bbfiles.append(recipes) + dynamic_recipes = layerdata[layer].path + "/dynamic-recipes" + if os.path.isdir(dynamic_recipes): + for deplayer in os.listdir(dynamic_recipes): + if not os.path.isdir(dynamic_recipes + "/" + deplayer): + continue + if deplayer in layerdata: + bbfiles.append(dynamic_recipes + "/" + deplayer) + data.setVar("BBFILES", " ".join(bbfiles)) + + if layer_filterfunc: + bb.utils.better_eval("%s(d)" % layer_filterfunc, {"d": data}) if not data.getVar("BBPATH"): msg = "The BBPATH variable is not set" @@ -523,7 +680,7 @@ class CookerDataBuilder(object): data.setVar('BBINCLUDED',bb.parse.get_file_depends(data)) - return data + return data, layerdata @staticmethod def _parse_recipe(bb_data, bbfile, appends, mc, layername): @@ -538,6 +695,19 @@ class CookerDataBuilder(object): if appends: bb_data.setVar('__BBAPPEND', " ".join(appends)) + layerdir = bb_data.getVar("LAYERDIR_%s" % layername) + if layerdir: + conffile = layerdir + "/conf/layervars.conf" + bb.parse.mark_dependency(bb_data, conffile) + if os.path.exists(conffile): + bb.parse.handle(conffile, bb_data, True, baseconfig=True) + # Handle any added INHERITs + bbclasses = (bb_data.getVar('INHERIT') or "").split() + bb_data.setVar("__bbclasstype", "global") + for bbclass in bbclasses: + bb_data = _inherit(bbclass, bb_data) + bb_data.setVar("__bbclasstype", "recipe") + return bb.parse.handle(bbfile, bb_data) def parseRecipeVariants(self, bbfile, appends, virtonly=False, mc=None, layername=None): diff --git a/lib/bb/parse/ast.py b/lib/bb/parse/ast.py index d5d53a7c712..c26632b8b63 100644 --- a/lib/bb/parse/ast.py +++ b/lib/bb/parse/ast.py @@ -359,10 +359,11 @@ class AddFragmentsNode(AstNode): # No need to use mark_dependency since we would only match a fragment # from a specific layer and there can only be a single layer with a # given namespace. - def find_fragment(layers, layerid, full_fragment_name): - for layerpath in layers.split(): + def find_fragment(layerdata, layerid, full_fragment_name): + if layerid in layerdata: + layerpath = layerdata[layerid].path candidate_fragment_path = os.path.join(layerpath, full_fragment_name) - if os.path.exists(candidate_fragment_path) and bb.utils.get_file_layer(candidate_fragment_path, data) == layerid: + if os.path.exists(candidate_fragment_path): return candidate_fragment_path return None @@ -388,11 +389,17 @@ class AddFragmentsNode(AstNode): return True return False - fragments = data.getVar(self.fragments_variable) - layers = data.getVar('BBLAYERS') + fragments = (data.getVar(self.fragments_variable) or "").split() flagged_variables = data.getVar(self.flagged_variables_list_variable).split() builtin_fragments = {f[0]:f[1] for f in [f.split(':') for f in data.getVar(self.builtin_fragments_variable).split()] } + layerdata = data.getVar("layerdata", expand=False) + optedout = set((data.getVar("LAYER_FRAGMENTS_OPTED_OUT") or "").split()) + for layer in layerdata: + wanted = layerdata[layer].fragment_recommends_any - optedout + if wanted and not (wanted & set(fragments)): + bb.warn("Layer %s recommends one of the fragments %s to be enabled but none are" % (layer, str(wanted))) + if not fragments: return @@ -401,7 +408,7 @@ class AddFragmentsNode(AstNode): builtin_fragments_list = list( filter( lambda f: f.startswith(builtin_fragment_key + "/"), - fragments.split(), + fragments, ) ) if len(builtin_fragments_list) > 1: @@ -416,12 +423,12 @@ class AddFragmentsNode(AstNode): ) ) - for f in fragments.split(): + for f in fragments: if check_and_set_builtin_fragment(f, data, builtin_fragments): continue layerid, fragment_name = f.split('/', 1) full_fragment_name = data.expand("{}/{}.conf".format(self.fragments_path_prefix, fragment_name)) - fragment_path = find_fragment(layers, layerid, full_fragment_name) + fragment_path = find_fragment(layerdata, layerid, full_fragment_name) if fragment_path: bb.parse.ConfHandler.include(self.filename, fragment_path, self.lineno, data, "include fragment") for flagged_var in flagged_variables: @@ -429,7 +436,8 @@ class AddFragmentsNode(AstNode): data.setVarFlag(flagged_var, f, val) data.setVar(flagged_var, None) else: - bb.fatal("Could not find fragment {} in enabled layers:\n\t{}".format(f, "\n\t".join(layers.split()))) + paths = [layerdata[layer].path for layer in layerdata] + bb.fatal("Could not find fragment {} in enabled layers:\n\t{}".format(f, "\n\t".join(paths))) def handleInclude(statements, filename, lineno, m, force): statements.append(IncludeNode(filename, lineno, m.group(1), force))