Files
pruefwerk/docker/pruefwerk_yocto_recipes.py
T
sharang ba499d14e4
CI / Check (push) Skipped
CI / Detect Changes (push) Successful in 3s
CI / Deploy Dashboard (push) Successful in 7m17s
CI / Deploy Docs (push) Successful in 1m13s
CI / Deploy Agent (push) Successful in 10m7s
CI / Deploy MCP (push) Successful in 3m21s
feat(yocto): recipes an image recipe installs are marked as in the image (declared) (#557)
2026-10-09 17:58:38 +00:00

583 lines
23 KiB
Python

"""Read the recipes of a Yocto/OpenEmbedded layer tree as JSON, without a build.
Prüfwerk runs this with `python3 -I pruefwerk_yocto_recipes.py <tree>` and turns
the output into SBOM components and VEX statements (see
compliance-agent/src/pipeline/yocto_inventory.rs). The recipes are parsed with
oelint-parser (BSD-2-Clause), which reads BitBake syntax and never executes the
recipes' Python or shell code.
Each recipe is parsed with its own bbappends. Layer overrides between layers,
PACKAGECONFIG, the distro and machine configuration are not resolved: this is
an inventory of the recipes in the tree, not the image's SBOM.
What the image recipes, local.conf.sample and the distro configurations
declare an image installs (IMAGE_INSTALL, CORE_IMAGE_EXTRA_INSTALL,
IMAGE_FEATURES) is read as written, with the package groups' RDEPENDS and
RRECOMMENDS, so that the agent can mark the recipes an image names. Every
override's assignment counts; nothing is resolved the way BitBake would.
Output: {"recipes", "images", "packagegroups", "configs": [...],
"errors": [{"file", "error"}]}, each sorted by file.
"""
import glob
import json
import os
import re
import sys
import regex
from oelint_parser import cls_stash
from oelint_parser.cls_item import FlagAssignment, Item, Variable
from oelint_parser.cls_stash import Stash
from oelint_parser.parser import INLINE_BLOCK
# Directories never walked: version control, and the build output a tree may
# carry next to its layers.
SKIPPED_DIRS = {".git", ".hg", ".svn", "build", "tmp", "sstate-cache", "downloads"}
# How much of a patch is read for its CVE: tags; the header comes first.
PATCH_HEADER_BYTES = 64 * 1024
# The variables saying what an image installs, and its features.
INSTALL_VARIABLES = ("IMAGE_INSTALL", "CORE_IMAGE_EXTRA_INSTALL")
FEATURE_VARIABLES = ("IMAGE_FEATURES", "EXTRA_IMAGE_FEATURES")
# The operations an override suffix can name (`:append`, old `_append`).
OPERATIONS = ("append", "prepend", "remove")
VERSION_CONSTRAINT = re.compile(r"\([^()]*\)")
CVE_ID = re.compile(r"CVE-\d{4}-\d{4,}")
CVE_TAG = re.compile(r"^CVE:\s*(.*)$", re.MULTILINE)
def inside(path: str, tree: str) -> bool:
"""Whether `path`, symlinks resolved, lies within `tree`."""
real = os.path.realpath(path)
return real == tree or real.startswith(tree + os.sep)
def confine(tree: str) -> None:
"""Keep the parser inside `tree`. A recipe is the customer's input: an
`include /proc/1/environ` or `${@oe.utils.read_file(...)}` must not bring
another file's content into a value Prüfwerk stores. Includes outside the
tree are treated as missing, and read_file is never evaluated."""
find = Stash.FindLocalOrLayer
def find_inside(self: Stash, name: str, localdir: str) -> str:
found = find(self, name, localdir)
return found if found and inside(found, tree) else ""
Stash.FindLocalOrLayer = find_inside
# A pattern that never matches: ExpandTerm then leaves the call as text.
setattr(cls_stash, "__oe_utils_read_file_regex__", regex.compile(r"(?!)"))
def is_config(root: str, name: str) -> bool:
"""Whether `name` in directory `root` is a configuration that can declare
what images install: a local.conf.sample or a distro configuration."""
if name == "local.conf.sample":
return True
return name.endswith(".conf") and os.path.basename(root) == "distro" and (
os.path.basename(os.path.dirname(root)) == "conf"
)
def walk(tree: str) -> tuple[list[str], list[str], list[str], list[str]]:
"""The layer roots (directories with conf/layer.conf), recipes, appends
and the configurations that can declare what images install."""
layers: list[str] = []
recipes: list[str] = []
appends: list[str] = []
configs: list[str] = []
for root, dirs, files in os.walk(tree):
dirs[:] = sorted(d for d in dirs if d not in SKIPPED_DIRS)
if os.path.basename(root) == "conf" and "layer.conf" in files:
layers.append(os.path.dirname(root))
for name in files:
path = os.path.join(root, name)
if not inside(path, tree):
continue
if name.endswith(".bb"):
recipes.append(path)
elif name.endswith(".bbappend"):
appends.append(path)
elif is_config(root, name):
configs.append(path)
return sorted(layers), sorted(recipes), sorted(appends), sorted(configs)
def appends_for(recipe: str, appends: list[str]) -> list[str]:
"""The bbappends that apply to `recipe` (`%` matches any version suffix)."""
stem = os.path.basename(recipe)[: -len(".bb")]
matching = []
for append in appends:
pattern = re.escape(os.path.basename(append)[: -len(".bbappend")])
pattern = pattern.replace(re.escape("%"), ".*")
if re.fullmatch(pattern, stem):
matching.append(append)
return matching
def file_stem(path: str) -> str:
"""The recipe name part of a .bb or .bbappend file name: before the
version (`busybox_1.35.0.bb`), without an append's `%` wildcard."""
name = os.path.basename(path)
for suffix in (".bbappend", ".bb"):
if name.endswith(suffix):
name = name[: -len(suffix)]
break
return name.split("_", 1)[0].replace("%", "")
def is_image_name(path: str) -> bool:
"""Whether the file is named like an image recipe (`*-image*.bb`)."""
return "-image" in file_stem(path)
def is_build_host_recipe(name: str) -> bool:
"""Whether the recipe only builds a tool for the build host or SDK."""
return name.endswith(("-native", "-cross", "-crosssdk")) or name.startswith("nativesdk-")
def assignments(stash: Stash, recipe: str, name: str) -> list:
"""Every assignment of `name` in the recipe, its includes and appends."""
return sorted(
stash.GetItemsFor(
filename=recipe,
classifier=Variable.CLASSIFIER,
attribute=Variable.ATTR_VAR,
attributeValue=name,
),
key=lambda i: i.Line,
)
def raw(stash: Stash, item: Variable) -> str:
"""An assignment's value with its inline Python (`${@...}`) put back as
written: the parser swaps it for a placeholder, and it is never run."""
if INLINE_BLOCK in item.VarValueStripped:
return stash._ReverseInlineBlock(item)
return item.VarValueStripped
def value(stash: Stash, recipe: str, name: str) -> str | None:
"""The expanded value of `name` as BitBake would combine its assignments:
`=`, `?=`, `+=`, `.=` in order, then `:append`, `:prepend` and `:remove`.
Overrides (`:class-target`, a machine) are not resolved: every override's
append counts, so a value may list more than one configuration uses."""
items = assignments(stash, recipe, name)
if not items:
return None
current: str | None = None
for item in items:
if item.SubItems:
continue
text = raw(stash, item)
op = item.VarOp.strip()
if op in ("=", ":="):
current = text
elif op in ("?=", "??="):
current = text if current is None else current
elif op == "+=":
current = f"{current or ''} {text}"
elif op == "=+":
current = f"{text} {current or ''}"
elif op == ".=":
current = f"{current or ''}{text}"
elif op == "=.":
current = f"{text}{current or ''}"
for item in items:
if "append" in item.SubItems:
current = f"{current or ''}{raw(stash, item)}"
elif "prepend" in item.SubItems:
current = f"{raw(stash, item)}{current or ''}"
for item in items:
if "remove" in item.SubItems and current is not None:
for word in item.VarValueStripped.split():
current = " ".join(w for w in current.split() if w != word)
if current is None:
return None
return stash.ExpandTerm(recipe, current).strip()
def words(stash: Stash, recipe: str, name: str) -> list[str]:
"""The value of `name` split into words."""
return Item.safe_linesplit(value(stash, recipe, name) or "")
def flags(stash: Stash, recipe: str, name: str) -> dict[str, str]:
"""The expanded flags of `name` (`CVE_STATUS[CVE-...]`), the last one winning."""
items = stash.GetItemsFor(
filename=recipe,
classifier=FlagAssignment.CLASSIFIER,
attribute=FlagAssignment.ATTR_NAME,
attributeValue=name,
)
found: dict[str, str] = {}
for item in sorted(items, key=lambda i: i.Line):
found[item.Flag] = stash.ExpandTerm(recipe, item.ValueStripped).strip()
return found
def assignment_parts(
item: Variable, name: str, scoped: bool
) -> tuple[list[str], str | None, list[str]] | None:
"""What an assignment to `name` is: the words before its operation (a
package such as `${PN}-utils`, or an override such as `qemux86`), the
operation (`append`, `prepend`, `remove` or None) and the overrides after
it. None for an assignment of another variable.
oelint-parser splits `IMAGE_INSTALL_append` (the syntax before Kirkstone)
into the variable and `append` only in a file without any `:` override;
otherwise it keeps the whole name, which is split here. Another variable
with a longer name (`IMAGE_FEATURES_REPLACES_…`) is not an assignment of
`name`: in the old syntax only an operation may follow the name directly,
or, for a per-package variable (RDEPENDS), the package."""
if item.VarName == name:
subs = list(item.SubItems)
elif item.VarName.startswith(name + "_"):
subs = item.VarName[len(name) + 1 :].split("_") + list(item.SubItems)
if not scoped and subs[0] not in OPERATIONS:
return None
else:
return None
operation = next((s for s in subs if s in OPERATIONS), None)
if operation is None:
return subs, None, []
at = subs.index(operation)
return subs[:at], operation, subs[at + 1 :]
def without_inline_python(text: str) -> str:
"""`text` without its inline Python (`${@bb.utils.contains(...)}`): what
it would add depends on the configuration, which is not resolved."""
kept = []
at = 0
while (start := text.find("${@", at)) != -1:
kept.append(text[at:start])
depth = 0
end = start + 1
while end < len(text):
if text[end] == "{":
depth += 1
elif text[end] == "}":
depth -= 1
if depth == 0:
break
end += 1
at = end + 1
kept.append(text[at:])
return " ".join(kept)
def fold(stash: Stash, path: str, items: list[Variable], name: str, scoped: bool) -> list[str]:
"""The words `items` (assignments of `name`) give together: `=`, `?=`,
`+=` in order, then every `:append`/`:prepend` and every override's
assignment added, then `:remove` taken away. With `scoped`, the first word
before the operation is the package and the rest are overrides."""
base: list[str] | None = None
added: list[str] = []
removed: set[str] = set()
for item in sorted(items, key=lambda i: i.Line):
parts = assignment_parts(item, name, scoped)
if parts is None:
continue
before, operation, after = parts
overrides = before[1:] if scoped else before
text = without_inline_python(stash.ExpandTerm(path, raw(stash, item)))
# A version constraint (`foo (>= 1.2)`) is not a package.
found = Item.safe_linesplit(VERSION_CONSTRAINT.sub(" ", text))
if operation == "remove" and not overrides and not after:
removed.update(found)
elif operation is not None or overrides:
# An override (a machine, a distro) is not resolved: it counts.
if operation != "remove":
added.extend(found)
else:
op = item.VarOp.strip()
if op in ("=", ":="):
base = found
elif op in ("?=", "??="):
base = found if base is None else base
else:
base = (base or []) + found
words_found = [w for w in (base or []) + added if w not in removed]
return list(dict.fromkeys(words_found))
def variables(stash: Stash, path: str) -> list[Variable]:
"""Every variable assignment in `path`, its includes and appends."""
return stash.GetItemsFor(filename=path, classifier=Variable.CLASSIFIER)
def declared(stash: Stash, path: str, names: tuple[str, ...]) -> list[str]:
"""The words the variables `names` declare in `path`, in order, once."""
items = variables(stash, path)
found = [w for name in names for w in fold(stash, path, items, name, scoped=False)]
return list(dict.fromkeys(found))
def per_package(stash: Stash, path: str, names: tuple[str, ...]) -> dict[str, list[str]]:
"""The words the per-package variables `names` (RDEPENDS:${PN}-x) give
each package of `path`, keyed by the package name as expanded."""
items = variables(stash, path)
keyed: dict[str, list[Variable]] = {}
for name in names:
for item in items:
parts = assignment_parts(item, name, scoped=True)
if parts is None or not parts[0]:
continue
package = stash.ExpandTerm(path, parts[0][0]).strip()
keyed.setdefault(package, [])
if item not in keyed[package]:
keyed[package].append(item)
found: dict[str, list[str]] = {}
for package, group in sorted(keyed.items()):
words_found = [w for name in names for w in fold(stash, path, group, name, scoped=True)]
if words_found:
found[package] = list(dict.fromkeys(words_found))
return found
def image_declarations(stash: Stash, path: str) -> dict[str, list[str]]:
"""What `path` declares an image installs, and its features."""
return {
"install": declared(stash, path, INSTALL_VARIABLES),
"features": declared(stash, path, FEATURE_VARIABLES),
}
def status_entry(cve: str, value: str) -> dict[str, str]:
"""A CVE_STATUS value `reason: detail` as its parts."""
reason, _, detail = value.partition(":")
return {"cve": cve, "status": reason.strip(), "detail": detail.strip()}
def cve_statuses(stash: Stash, recipe: str) -> list[dict]:
"""CVE_STATUS flags, CVE_STATUS_GROUPS and the older CVE_CHECK_IGNORE."""
statuses = {cve: status_entry(cve, v) for cve, v in flags(stash, recipe, "CVE_STATUS").items()}
for group in words(stash, recipe, "CVE_STATUS_GROUPS"):
status = flags(stash, recipe, group).get("status")
if status is None:
continue
for cve in words(stash, recipe, group):
statuses.setdefault(cve, status_entry(cve, status))
for cve in words(stash, recipe, "CVE_CHECK_IGNORE"):
statuses.setdefault(cve, {"cve": cve, "status": "ignored", "detail": "CVE_CHECK_IGNORE"})
return [statuses[cve] for cve in sorted(statuses) if CVE_ID.fullmatch(cve)]
def find_local_file(name: str, origins: list[str], tree: str) -> str | None:
"""Where a `file://` entry lives: next to the recipe or one of its appends,
directly or in one subdirectory (`files/`, `${BPN}/`, `${BP}/`)."""
for origin in origins:
base = os.path.dirname(origin)
candidates = [os.path.join(base, name)]
candidates += sorted(glob.glob(os.path.join(glob.escape(base), "*", glob.escape(name))))
for candidate in candidates:
if os.path.isfile(candidate) and inside(candidate, tree):
return candidate
return None
def patch_cves(path: str | None, name: str) -> list[str]:
"""The CVEs a patch fixes: its `CVE:` tags and the ids in its file name,
as OpenEmbedded's cve-check reads them."""
cves = set(CVE_ID.findall(os.path.basename(name)))
if path is not None:
with open(path, "rb") as patch:
header = patch.read(PATCH_HEADER_BYTES).decode("utf-8", errors="replace")
for tag in CVE_TAG.findall(header):
cves.update(CVE_ID.findall(tag))
return sorted(cves)
def sources(origins: list[str], tree: str, src_uri: list[str]) -> tuple[str | None, list[dict]]:
"""The first upstream URL of SRC_URI and the patches it applies."""
upstream = None
patches = []
for entry in src_uri:
url, *options = entry.split(";")
if not url.startswith("file://"):
upstream = upstream or entry
continue
if "apply=no" in options:
continue
name = url[len("file://"):]
if not name.endswith((".patch", ".diff")) and "apply=yes" not in options:
continue
path = find_local_file(name, origins, tree)
patches.append({
"file": os.path.relpath(path, tree) if path else name,
"cves": patch_cves(path, name),
})
return upstream, patches
def parsed(paths: list[str], layers: list[str], negative: bool = False) -> Stash:
"""A stash of `paths` (a recipe and its appends, or a configuration).
oelint-parser emulates `bb.utils.contains` by taking its true branch, or
with `negative` its false one; it never runs the Python."""
stash = Stash(quiet=True, layer_paths=layers, negative_inline=negative)
for path in paths:
stash.AddFile(path)
stash.Finalize()
return stash
def static_words(found: list[str]) -> list[str]:
"""The words that are names as written, not a variable left unexpanded."""
return [w for w in found if "${" not in w and "@" not in w]
def common(positive, negative):
"""What two readings agree on: the words of a list in both (in the first
one's order), a dictionary key by key, any other value as first read."""
if isinstance(positive, list):
kept = set(negative) if isinstance(negative, list) else set()
return [w for w in positive if w in kept]
if isinstance(positive, dict):
other = negative if isinstance(negative, dict) else {}
return {key: common(value, other.get(key)) for key, value in positive.items()}
return positive
def unconditional(paths: list[str], layers: list[str], read) -> dict:
"""`read(stash)` of `paths` with what both branches of every inline
condition give: an install only when `DISTRO_FEATURES` contains `x11`
is not declared for the image as such."""
return common(read(parsed(paths, layers)), read(parsed(paths, layers, negative=True)))
def read_image(stash: Stash, recipe: str, appends: list[str], tree: str) -> dict:
"""An image recipe (or a bbappend of one not in the tree): its name and
what it declares it installs."""
return {
"file": os.path.relpath(recipe, tree),
"appends": [os.path.relpath(a, tree) for a in appends],
"pn": file_stem(recipe),
**image_declarations(stash, recipe),
}
def read_packagegroup(stash: Stash, recipe: str, tree: str) -> dict:
"""A package group: the packages it makes and what each one pulls in
(RDEPENDS, and RRECOMMENDS, which are installed unless excluded)."""
pn = stash.GuessRecipeName(recipe)
return {
"file": os.path.relpath(recipe, tree),
"pn": pn,
"packages": static_words(declared(stash, recipe, ("PACKAGES",))) or [pn],
"rdepends": per_package(stash, recipe, ("RDEPENDS", "RRECOMMENDS")),
}
def read_recipe(
recipe: str, appends: list[str], layers: list[str], tree: str
) -> tuple[str, dict] | None:
"""One recipe as JSON with its kind: `recipe` for a component of the
product, `image` or `packagegroup`; None for a build-host tool."""
paths = [recipe, *appends]
stash = parsed(paths, layers)
if stash.IsPackageGroup(recipe):
return "packagegroup", unconditional(
paths, layers, lambda s: read_packagegroup(s, recipe, tree)
)
if stash.IsImage(recipe) or is_image_name(recipe):
image = unconditional(paths, layers, lambda s: read_image(s, recipe, appends, tree))
# Named like an image (`*-image*.bb`) without inheriting an image
# class: an image only if it declares what to install
# (`xcb-util-image` is a library).
if stash.IsImage(recipe) or image["install"] or image["features"]:
return "image", image
pn = stash.GuessRecipeName(recipe)
if is_build_host_recipe(pn):
return None
pv = value(stash, recipe, "PV") or stash.GuessRecipeVersion(recipe)
origins = [recipe, *appends]
upstream, patches = sources(origins, tree, words(stash, recipe, "SRC_URI"))
return "recipe", {
"file": os.path.relpath(recipe, tree),
"appends": [os.path.relpath(a, tree) for a in appends],
"pn": pn,
"bpn": stash.GuessBaseRecipeName(recipe),
"packages": static_words(declared(stash, recipe, ("PACKAGES",))),
"pv": pv,
"srcrev": value(stash, recipe, "SRCREV") or None,
"src_uri": upstream,
"license": value(stash, recipe, "LICENSE") or None,
"cve_product": words(stash, recipe, "CVE_PRODUCT"),
"cve_version": value(stash, recipe, "CVE_VERSION") or None,
"cve_status": cve_statuses(stash, recipe),
"patches": patches,
}
def orphan_image_appends(recipe_files: list[str], appends: list[str]) -> list[str]:
"""The bbappends of images whose recipe is not in the tree
(`core-image-minimal.bbappend` extending Poky's image)."""
return [
append
for append in appends
if is_image_name(append)
and not any(append in appends_for(recipe, [append]) for recipe in recipe_files)
]
def declaring_image(append: str, layers: list[str], tree: str) -> tuple[str, dict] | None:
"""The bbappend of an image not in the tree, if it declares anything."""
image = unconditional([append], layers, lambda s: read_image(s, append, [], tree))
return ("image", image) if image["install"] or image["features"] else None
def read_config(config: str, layers: list[str], tree: str) -> tuple[str, dict] | None:
"""What a local.conf.sample or distro configuration declares every image
installs; None when it declares nothing."""
declarations = unconditional([config], layers, lambda s: image_declarations(s, config))
if not declarations["install"] and not declarations["features"]:
return None
return "config", {"file": os.path.relpath(config, tree), **declarations}
def main(tree: str) -> int:
tree = os.path.realpath(tree)
confine(tree)
layers, recipe_files, appends, configs = walk(tree)
layers = layers or [tree]
read: dict[str, list[dict]] = {"recipe": [], "image": [], "packagegroup": [], "config": []}
errors = []
def attempt(path: str, reader) -> None:
try:
result = reader()
except Exception as error: # noqa: BLE001 - one unreadable file must not stop the rest
errors.append({"file": os.path.relpath(path, tree), "error": type(error).__name__})
return
if result is not None:
read[result[0]].append(result[1])
for recipe in recipe_files:
attempt(recipe, lambda: read_recipe(recipe, appends_for(recipe, appends), layers, tree))
for append in orphan_image_appends(recipe_files, appends):
attempt(append, lambda: declaring_image(append, layers, tree))
for config in configs:
attempt(config, lambda: read_config(config, layers, tree))
output = {
"recipes": read["recipe"],
"images": sorted(read["image"], key=lambda i: i["file"]),
"packagegroups": read["packagegroup"],
"configs": read["config"],
"errors": errors,
}
json.dump(output, sys.stdout, sort_keys=True)
return 0
if __name__ == "__main__":
if len(sys.argv) != 2:
sys.stderr.write("usage: pruefwerk_yocto_recipes.py <layer tree>\n")
sys.exit(2)
sys.exit(main(sys.argv[1]))