Skip to contentSkip to conversation

Add SPDX SBOM generation tool

PATCH Superseded Luis Augenstein 4 participants 35 messages Jan 20 – Feb 3

Subsystems (2)

v2 of 7 Superseded Latest is v7 →

lore
Share & tools
lore
#0 lore raw

v2 cover Add SPDX SBOM generation tool

This patch series introduces a Python-based tool for generating SBOM documents in the SPDX 3.0.1 format for kernel builds.

A Software Bill of Materials (SBOM) describes the individual components of a software product. For the kernel, the goal is to describe the distributable build outputs (typically the kernel image and modules), the source files involved in producing these outputs, and the build process that connects the source and output files.

To achieve this, the SBOM tool generates three SPDX documents:

- sbom-output.spdx.json
Describes the final build outputs together with high-level build metadata.

- sbom-source.spdx.json
Describes all source files involved in the build, including licensing information and additional file metadata.

- sbom-build.spdx.json
Describes the entire build process, linking source files from the source SBOM to output files in the output SBOM.

The sbom tool is optional and runs only when CONFIG_SBOM is enabled. It is invoked after the build, once all output artifacts have been generated. Starting from the kernel image and modules as root nodes, the tool reconstructs the dependency graph up to the original source files. Build dependencies are primarily derived from the .cmd files generated by Kbuild, which record the full command used to build each output file.

Currently, the tool only supports x86 and arm64 architectures.

---
Changes in v2:
- regenerate sbom documents when build configuration changes
---
Luis Augenstein (14):
tools/sbom: integrate tool in make process tools/sbom: setup sbom logging
tools/sbom: add command parsers
tools/sbom: add cmd graph generation
tools/sbom: add additional dependency sources for cmd graph tools/sbom: add SPDX classes
tools/sbom: add JSON-LD serialization
tools/sbom: add shared SPDX elements
tools/sbom: collect file metadata
tools/sbom: add SPDX output graph
tools/sbom: add SPDX source graph
tools/sbom: add SPDX build graph
tools/sbom: add unit tests for command parsers tools/sbom: add unit tests for SPDX-License-Identifier parsing

 .gitignore                                    |   1 +
 MAINTAINERS                                   |   6 +
 Makefile                                      |  15 +-
 lib/Kconfig.debug                             |   9 +
 tools/Makefile                                |   3 +-
 tools/sbom/Makefile                           |  42 ++
 tools/sbom/README                             | 208 ++++++
 tools/sbom/sbom.py                            | 129 ++++
 tools/sbom/sbom/__init__.py                   |   0
 tools/sbom/sbom/cmd_graph/__init__.py         |   7 +
 tools/sbom/sbom/cmd_graph/cmd_file.py         | 149 ++++
 tools/sbom/sbom/cmd_graph/cmd_graph.py        |  46 ++
 tools/sbom/sbom/cmd_graph/cmd_graph_node.py   | 142 ++++
 tools/sbom/sbom/cmd_graph/deps_parser.py      |  52 ++
 .../sbom/cmd_graph/hardcoded_dependencies.py  |  83 +++
 tools/sbom/sbom/cmd_graph/incbin_parser.py    |  42 ++
 tools/sbom/sbom/cmd_graph/savedcmd_parser.py  | 664 ++++++++++++++++++
 tools/sbom/sbom/config.py                     | 335 +++++++++
 tools/sbom/sbom/environment.py                | 164 +++++
 tools/sbom/sbom/path_utils.py                 |  11 +
 tools/sbom/sbom/sbom_logging.py               |  88 +++
 tools/sbom/sbom/spdx/__init__.py              |   7 +
 tools/sbom/sbom/spdx/build.py                 |  17 +
 tools/sbom/sbom/spdx/core.py                  | 182 +++++
 tools/sbom/sbom/spdx/serialization.py         |  56 ++
 tools/sbom/sbom/spdx/simplelicensing.py       |  20 +
 tools/sbom/sbom/spdx/software.py              |  71 ++
 tools/sbom/sbom/spdx/spdxId.py                |  36 +
 tools/sbom/sbom/spdx_graph/__init__.py        |   7 +
 .../sbom/sbom/spdx_graph/build_spdx_graphs.py |  82 +++
 tools/sbom/sbom/spdx_graph/kernel_file.py     | 310 ++++++++
 .../sbom/spdx_graph/shared_spdx_elements.py   |  32 +
 .../sbom/sbom/spdx_graph/spdx_build_graph.py  | 317 +++++++++
 .../sbom/sbom/spdx_graph/spdx_graph_model.py  |  36 +
 .../sbom/sbom/spdx_graph/spdx_output_graph.py | 188 +++++
 .../sbom/sbom/spdx_graph/spdx_source_graph.py | 126 ++++
 tools/sbom/tests/__init__.py                  |   0
 tools/sbom/tests/cmd_graph/__init__.py        |   0
 .../tests/cmd_graph/test_savedcmd_parser.py   | 383 ++++++++++
 tools/sbom/tests/spdx_graph/__init__.py       |   0
 .../sbom/tests/spdx_graph/test_kernel_file.py |  32 +
 41 files changed, 4096 insertions(+), 2 deletions(-)
 create mode 100644 tools/sbom/Makefile
 create mode 100644 tools/sbom/README
 create mode 100644 tools/sbom/sbom.py
 create mode 100644 tools/sbom/sbom/__init__.py
 create mode 100644 tools/sbom/sbom/cmd_graph/__init__.py
 create mode 100644 tools/sbom/sbom/cmd_graph/cmd_file.py
 create mode 100644 tools/sbom/sbom/cmd_graph/cmd_graph.py
 create mode 100644 tools/sbom/sbom/cmd_graph/cmd_graph_node.py
 create mode 100644 tools/sbom/sbom/cmd_graph/deps_parser.py
 create mode 100644 tools/sbom/sbom/cmd_graph/hardcoded_dependencies.py
 create mode 100644 tools/sbom/sbom/cmd_graph/incbin_parser.py
 create mode 100644 tools/sbom/sbom/cmd_graph/savedcmd_parser.py
 create mode 100644 tools/sbom/sbom/config.py
 create mode 100644 tools/sbom/sbom/environment.py
 create mode 100644 tools/sbom/sbom/path_utils.py
 create mode 100644 tools/sbom/sbom/sbom_logging.py
 create mode 100644 tools/sbom/sbom/spdx/__init__.py
 create mode 100644 tools/sbom/sbom/spdx/build.py
 create mode 100644 tools/sbom/sbom/spdx/core.py
 create mode 100644 tools/sbom/sbom/spdx/serialization.py
 create mode 100644 tools/sbom/sbom/spdx/simplelicensing.py
 create mode 100644 tools/sbom/sbom/spdx/software.py
 create mode 100644 tools/sbom/sbom/spdx/spdxId.py
 create mode 100644 tools/sbom/sbom/spdx_graph/__init__.py
 create mode 100644 tools/sbom/sbom/spdx_graph/build_spdx_graphs.py
 create mode 100644 tools/sbom/sbom/spdx_graph/kernel_file.py
 create mode 100644 tools/sbom/sbom/spdx_graph/shared_spdx_elements.py
 create mode 100644 tools/sbom/sbom/spdx_graph/spdx_build_graph.py
 create mode 100644 tools/sbom/sbom/spdx_graph/spdx_graph_model.py
 create mode 100644 tools/sbom/sbom/spdx_graph/spdx_output_graph.py
 create mode 100644 tools/sbom/sbom/spdx_graph/spdx_source_graph.py
 create mode 100644 tools/sbom/tests/__init__.py
 create mode 100644 tools/sbom/tests/cmd_graph/__init__.py
 create mode 100644 tools/sbom/tests/cmd_graph/test_savedcmd_parser.py
 create mode 100644 tools/sbom/tests/spdx_graph/__init__.py
 create mode 100644 tools/sbom/tests/spdx_graph/test_kernel_file.py
Signature · 1 line
2.34.1
#1 lore raw

PATCH v2 1/14 tools/sbom: integrate tool in make process

Add CONFIG_SBOM option and integrate SBOM tool into the kernel build process.

---
 .gitignore          |   1 +
 MAINTAINERS         |   6 ++
 Makefile            |  15 +++-
 lib/Kconfig.debug   |   9 ++
 tools/Makefile      |   3 +-
 tools/sbom/Makefile |  35 ++++++++
 tools/sbom/README   | 208 ++++++++++++++++++++++++++++++++++++++++++++
 tools/sbom/sbom.py  |  16 ++++
 8 files changed, 291 insertions(+), 2 deletions(-)
 create mode 100644 tools/sbom/Makefile
 create mode 100644 tools/sbom/README
 create mode 100644 tools/sbom/sbom.py
.gitignore +1 -0
index 3a7241c941f5..f3372f15eb1b 100644
@@ -48,6 +48,7 @@
 *.s
 *.so
 *.so.dbg
+*.spdx.json
 *.su
 *.symtypes
 *.tab.[ch]
MAINTAINERS +6 -0
index f1b020588597..03d7d93d8e63 100644
@@ -23365,6 +23365,12 @@ R:	Marc Murphy <[email protected]>
 S:	Supported
 F:	arch/arm/boot/dts/ti/omap/am335x-sancloud*
 
+SBOM
+M:	Luis Augenstein <[email protected]>
+M:	Maximilian Huber <[email protected]>
+S:	Maintained
+F:	tools/sbom/
+
 SC1200 WDT DRIVER
 M:	Zwane Mwaikambo <[email protected]>
 S:	Maintained
Makefile +14 -1
index 9d38125263fb..a1c0cbd110e5 100644
@@ -1457,6 +1457,19 @@ prepare: tools/bpf/resolve_btfids
 endif
 endif
 
+ifdef CONFIG_SBOM
+all: tools/sbom
+tools/sbom: $(notdir $(KBUILD_IMAGE)) modules
+	$(Q)mkdir -p $(objtree)/tools
+	$(Q)$(MAKE) \
+		O=$(abspath $(objtree)) \
+		subdir=tools \
+		-C $(srctree)/tools/ \
+		sbom \
+		srctree=$(abspath $(srctree)) \
+		CONFIG_MODULES=$(CONFIG_MODULES)
+endif
+
 # The tools build system is not a part of Kbuild and tends to introduce
 # its own unique issues. If you need to integrate a new tool into Kbuild,
 # please consider locating that tool outside the tools/ tree and using the
@@ -1612,7 +1625,7 @@ CLEAN_FILES += vmlinux.symvers modules-only.symvers \
 	       modules.builtin.ranges vmlinux.o.map vmlinux.unstripped \
 	       compile_commands.json rust/test \
 	       rust-project.json .vmlinux.objs .vmlinux.export.c \
-               .builtin-dtbs-list .builtin-dtb.S
+	       .builtin-dtbs-list .builtin-dtb.S sbom-*.spdx.json
 
 # Directories & files removed with 'make mrproper'
 MRPROPER_FILES += include/config include/generated          \
lib/Kconfig.debug +9 -0
index ba36939fda79..9d03ef854f61 100644
@@ -563,6 +563,15 @@ config OBJTOOL_WERROR
 
 	  If unsure, say Y.
 
+config SBOM
+	bool "Generate Software Bill of Materials"
+	help
+	  If enabled, the kernel build will generate SPDX SBOM documents
+	  describing all source files, and build artifacts involved in the build.
+	  The SBOM documents are generated in SPDX 3.0.1 format and saved to the build output
+	  directory after the build completes.
+	  For more information, see tools/sbom/README
+
 config STACK_VALIDATION
 	bool "Compile-time stack metadata validation"
 	depends on HAVE_STACK_VALIDATION && UNWINDER_FRAME_POINTER
tools/Makefile +2 -1
index cb40961a740f..7b4b1c96dcd5 100644
@@ -27,6 +27,7 @@ help:
 	@echo '  nolibc                 - nolibc headers testing and installation'
 	@echo '  objtool                - an ELF object analysis tool'
 	@echo '  perf                   - Linux performance measurement and analysis tool'
+	@echo '  sbom                   - SBOM generation tool'
 	@echo '  selftests              - various kernel selftests'
 	@echo '  sched_ext              - sched_ext example schedulers'
 	@echo '  bootconfig             - boot config tool'
@@ -70,7 +71,7 @@ acpi: FORCE
 cpupower: FORCE
 	$(call descend,power/$@)
 
-counter dma firewire hv guest bootconfig spi usb virtio mm bpf iio gpio objtool leds wmi firmware debugging tracing: FORCE
+counter dma firewire hv guest bootconfig spi usb virtio mm bpf iio gpio objtool leds wmi firmware debugging tracing sbom: FORCE
 	$(call descend,$@)
 
 bpf/%: FORCE
tools/sbom/Makefile new file +35 -0
new file mode 100644
index 000000000000..8be7f2f3e631
@@ -0,0 +1,35 @@
+# SPDX-License-Identifier: GPL-2.0-only OR MIT
+# Copyright (C) 2025 TNG Technology Consulting GmbH
+
+SBOM_SOURCE_FILE := $(objtree)/sbom-source.spdx.json
+SBOM_BUILD_FILE := $(objtree)/sbom-build.spdx.json
+SBOM_OUTPUT_FILE := $(objtree)/sbom-output.spdx.json
+SBOM_ROOTS_FILE := $(objtree)/sbom-roots.txt
+
+
+ifeq ($(srctree),$(objtree))
+    SBOM_TARGETS := $(SBOM_BUILD_FILE) $(SBOM_OUTPUT_FILE)
+else
+    SBOM_TARGETS := $(SBOM_SOURCE_FILE) $(SBOM_BUILD_FILE) $(SBOM_OUTPUT_FILE)
+endif
+
+SBOM_DEPS := $(objtree)/$(KBUILD_IMAGE) $(objtree)/include/generated/autoconf.h
+ifdef CONFIG_MODULES
+    SBOM_DEPS += $(objtree)/modules.order
+endif
+
+sbom: $(SBOM_TARGETS)
+
+$(SBOM_TARGETS) &: $(SBOM_DEPS)
+	@echo "  GEN     $(notdir $(SBOM_TARGETS))"
+
+	@printf "%s\n" "$(KBUILD_IMAGE)" > $(SBOM_ROOTS_FILE)
+	@if [ "$(CONFIG_MODULES)" = "y" ]; then \
+		sed 's/\.o$$/.ko/' $(objtree)/modules.order >> $(SBOM_ROOTS_FILE); \
+	fi
+
+	@python3 sbom.py
+
+	@rm $(SBOM_ROOTS_FILE)
+
+.PHONY: sbom
tools/sbom/README new file +208 -0

208 lines not on this page · raw message

tools/sbom/sbom.py new file +16 -0
new file mode 100644
index 000000000000..9c2e4c7f17ce
@@ -0,0 +1,16 @@
+#!/usr/bin/env python3
+# SPDX-License-Identifier: GPL-2.0-only OR MIT
+# Copyright (C) 2025 TNG Technology Consulting GmbH
+
+"""
+Compute software bill of materials in SPDX format describing a kernel build.
+"""
+
+
+def main():
+    pass
+
+
+# Call main method
+if __name__ == "__main__":
+    main()
Signature · 1 line
2.34.1
#2 lore raw

PATCH v2 2/14 tools/sbom: setup sbom logging

In reply to Luis Augenstein

Add logging infrastructure for warnings and errors. Errors and warnings are accumulated and summarized in the end.

---
 tools/sbom/sbom.py              | 24 ++++++++-
 tools/sbom/sbom/__init__.py     |  0
 tools/sbom/sbom/config.py       | 47 ++++++++++++++++++
 tools/sbom/sbom/sbom_logging.py | 88 +++++++++++++++++++++++++++++++++
 4 files changed, 158 insertions(+), 1 deletion(-)
 create mode 100644 tools/sbom/sbom/__init__.py
 create mode 100644 tools/sbom/sbom/config.py
 create mode 100644 tools/sbom/sbom/sbom_logging.py
tools/sbom/sbom.py +23 -1
index 9c2e4c7f17ce..c7f23d6eb300 100644
@@ -6,9 +6,31 @@
 Compute software bill of materials in SPDX format describing a kernel build.
 """
 
+import logging
+import sys
+import sbom.sbom_logging as sbom_logging
+from sbom.config import get_config
+
 
 def main():
-    pass
+    # Read config
+    config = get_config()
+
+    # Configure logging
+    logging.basicConfig(
+        level=logging.DEBUG if config.debug else logging.INFO,
+        format="[%(levelname)s] %(message)s",
+    )
+
+    # Report collected warnings and errors in case of failure
+    warning_summary = sbom_logging.summarize_warnings()
+    error_summary = sbom_logging.summarize_errors()
+
+    if warning_summary:
+        logging.warning(warning_summary)
+    if error_summary:
+        logging.error(error_summary)
+        sys.exit(1)
 
 
 # Call main method
tools/sbom/sbom/__init__.py new file +0 -0
new file mode 100644
index 000000000000..e69de29bb2d1
tools/sbom/sbom/config.py new file +47 -0

47 lines not on this page · raw message

tools/sbom/sbom/sbom_logging.py new file +88 -0

88 lines not on this page · raw message

Signature · 1 line
2.34.1
#3 lore raw

PATCH v2 3/14 tools/sbom: add command parsers

In reply to Luis Augenstein

Implement savedcmd_parser module for extracting input files from kernel build commands.

---
 tools/sbom/sbom/cmd_graph/savedcmd_parser.py | 664 +++++++++++++++++++
 1 file changed, 664 insertions(+)
 create mode 100644 tools/sbom/sbom/cmd_graph/savedcmd_parser.py
tools/sbom/sbom/cmd_graph/savedcmd_parser.py new file +664 -0
new file mode 100644
index 000000000000..d72f781b4498
@@ -0,0 +1,664 @@
+# SPDX-License-Identifier: GPL-2.0-only OR MIT
+# Copyright (C) 2025 TNG Technology Consulting GmbH
+
+import re
+import shlex
+from dataclasses import dataclass
+from typing import Any, Callable, Union
+import sbom.sbom_logging as sbom_logging
+from sbom.path_utils import PathStr
+
+
+class CmdParsingError(Exception):
+    def __init__(self, message: str):
+        super().__init__(message)
+        self.message = message
+
+
+@dataclass
+class Option:
+    name: str
+    value: str | None = None
+
+
+@dataclass
+class Positional:
+    value: str
+
+
+_SUBCOMMAND_PATTERN = re.compile(r"\$\$\(([^()]*)\)")
+"""Pattern to match $$(...) blocks"""
+
+
+def _tokenize_single_command(command: str, flag_options: list[str] | None = None) -> list[Union[Option, Positional]]:
+    """
+    Parse a shell command into a list of Options and Positionals.
+    - Positional: the command and any positional arguments.
+    - Options: handles flags and options with values provided as space-separated, or equals-sign
+        (e.g., '--opt val', '--opt=val', '--flag').
+
+    Args:
+        command: Command line string.
+        flag_options: Options that are flags without values (e.g., '--verbose').
+
+    Returns:
+        List of `Option` and `Positional` objects in command order.
+    """
+
+    #  Wrap all $$(...) blocks in double quotes to prevent shlex from splitting them.
+    command_with_protected_subcommands = _SUBCOMMAND_PATTERN.sub(lambda m: f'"$$({m.group(1)})"', command)
+    tokens = shlex.split(command_with_protected_subcommands)
+
+    parsed: list[Option | Positional] = []
+    i = 0
+    while i < len(tokens):
+        token = tokens[i]
+
+        # Positional
+        if not token.startswith("-"):
+            parsed.append(Positional(token))
+            i += 1
+            continue
+
+        # Option without value (--flag)
+        if (token.startswith("-") and i + 1 < len(tokens) and tokens[i + 1].startswith("-")) or (
+            flag_options and token in flag_options
+        ):
+            parsed.append(Option(name=token))
+            i += 1
+            continue
+
+        # Option with equals sign (--opt=val)
+        if "=" in token:
+            name, value = token.split("=", 1)
+            parsed.append(Option(name=name, value=value))
+            i += 1
+            continue
+
+        # Option with space-separated value (--opt val)
+        if i + 1 < len(tokens) and not tokens[i + 1].startswith("-"):
+            parsed.append(Option(name=token, value=tokens[i + 1]))
+            i += 2
+            continue
+
+        raise CmdParsingError(f"Unrecognized token: {token} in command {command}")
+
+    return parsed
+
+
+def _tokenize_single_command_positionals_only(command: str) -> list[str]:
+    command_parts = _tokenize_single_command(command)
+    positionals = [p.value for p in command_parts if isinstance(p, Positional)]
+    if len(positionals) != len(command_parts):
+        raise CmdParsingError(
+            f"Invalid command format: expected positional arguments only but got options in command {command}."
+        )
+    return positionals
+
+
+def _parse_dd_command(command: str) -> list[PathStr]:
+    match = re.match(r"dd.*?if=(\S+)", command)
+    if match:
+        return [match.group(1)]
+    return []
+
+
+def _parse_cat_command(command: str) -> list[PathStr]:
+    positionals = _tokenize_single_command_positionals_only(command)
+    # expect positionals to be ["cat", input1, input2, ...]
+    return [p for p in positionals[1:]]
+
+
+def _parse_compound_command(command: str) -> list[PathStr]:
+    compound_command_parsers: list[tuple[re.Pattern[str], Callable[[str], list[PathStr]]]] = [
+        (re.compile(r"dd\b"), _parse_dd_command),
+        (re.compile(r"cat.*?\|"), lambda c: _parse_cat_command(c.split("|")[0])),
+        (re.compile(r"cat\b[^|>]*$"), _parse_cat_command),
+        (re.compile(r"echo\b"), _parse_noop),
+        (re.compile(r"\S+="), _parse_noop),
+        (re.compile(r"printf\b"), _parse_noop),
+        (re.compile(r"sed\b"), _parse_sed_command),
+        (
+            re.compile(r"(.*/)scripts/bin2c\s*<"),
+            lambda c: [input] if (input := c.split("<")[1].strip()) != "/dev/null" else [],
+        ),
+        (re.compile(r"^:$"), _parse_noop),
+    ]
+
+    match = re.match(r"\s*[\(\{](.*)[\)\}]\s*>", command, re.DOTALL)
+    if match is None:
+        raise CmdParsingError("No inner commands found for compound command")
+    input_files: list[PathStr] = []
+    inner_commands = _split_commands(match.group(1))
+    for inner_command in inner_commands:
+        if isinstance(inner_command, IfBlock):
+            sbom_logging.error(
+                "Skip parsing inner command {inner_command} of compound command because IfBlock is not supported",
+                inner_command=inner_command,
+            )
+            continue
+
+        parser = next((parser for pattern, parser in compound_command_parsers if pattern.match(inner_command)), None)
+        if parser is None:
+            sbom_logging.error(
+                "Skip parsing inner command {inner_command} of compound command because no matching parser was found",
+                inner_command=inner_command,
+            )
+            continue
+        try:
+            input_files += parser(inner_command)
+        except CmdParsingError as e:
+            sbom_logging.error(
+                "Skip parsing inner command {inner_command} of compound command because of command parsing error: {error_message}",
+                inner_command=inner_command,
+                error_message=e.message,
+            )
+    return input_files
+
+
+def _parse_objcopy_command(command: str) -> list[PathStr]:
+    command_parts = _tokenize_single_command(command, flag_options=["-S", "-w"])
+    positionals = [part.value for part in command_parts if isinstance(part, Positional)]
+    # expect positionals to be ['objcopy', input_file] or ['objcopy', input_file, output_file]
+    if not (len(positionals) == 2 or len(positionals) == 3):
+        raise CmdParsingError(
+            f"Invalid objcopy command format: expected 2 or 3 positional arguments, got {len(positionals)} ({positionals})"
+        )
+    return [positionals[1]]
+
+
+def _parse_link_vmlinux_command(command: str) -> list[PathStr]:
+    """
+    For simplicity we do not parse the `scripts/link-vmlinux.sh` script.
+    Instead the `vmlinux.a` dependency is just hardcoded for now.
+    """
+    return ["vmlinux.a"]
+
+
+def _parse_noop(command: str) -> list[PathStr]:
+    """
+    No-op parser for commands with no input files (e.g., 'rm', 'true').
+    Returns an empty list.
+    """
+    return []
+
+
+def _parse_ar_command(command: str) -> list[PathStr]:
+    positionals = _tokenize_single_command_positionals_only(command)
+    # expect positionals to be ['ar', flags, output, input1, input2, ...]
+    flags = positionals[1]
+    if "r" not in flags:
+        # 'r' option indicates that new files are added to the archive.
+        # If this option is missing we won't find any relevant input files.
+        return []
+    return positionals[3:]
+
+
+def _parse_ar_piped_xargs_command(command: str) -> list[PathStr]:
+    printf_command, _ = command.split("|", 1)
+    positionals = _tokenize_single_command_positionals_only(printf_command.strip())
+    # expect positionals to be ['printf', '{prefix_path}%s ', input1, input2, ...]
+    prefix_path = positionals[1].rstrip("%s ")
+    return [f"{prefix_path}{filename}" for filename in positionals[2:]]
+
+
+def _parse_gcc_or_clang_command(command: str) -> list[PathStr]:
+    parts = shlex.split(command)
+    # compile mode: expect last positional argument ending in `.c` or `.S` to be the input file
+    for part in reversed(parts):
+        if not part.startswith("-") and any(part.endswith(suffix) for suffix in [".c", ".S"]):
+            return [part]
+
+    # linking mode: expect all .o files to be the inputs
+    return [p for p in parts if p.endswith(".o")]
+
+
+def _parse_rustc_command(command: str) -> list[PathStr]:
+    parts = shlex.split(command)
+    # expect last positional argument ending in `.rs` to be the input file
+    for part in reversed(parts):
+        if not part.startswith("-") and part.endswith(".rs"):
+            return [part]
+    raise CmdParsingError("Could not find .rs input source file")
+
+
+def _parse_rustdoc_command(command: str) -> list[PathStr]:
+    parts = shlex.split(command)
+    # expect last positional argument ending in `.rs` to be the input file
+    for part in reversed(parts):
+        if not part.startswith("-") and part.endswith(".rs"):
+            return [part]
+    raise CmdParsingError("Could not find .rs input source file")
+
+
+def _parse_syscallhdr_command(command: str) -> list[PathStr]:
+    command_parts = _tokenize_single_command(command.strip(), flag_options=["--emit-nr"])
+    positionals = [p.value for p in command_parts if isinstance(p, Positional)]
+    # expect positionals to be ["sh", path/to/syscallhdr.sh, input, output]
+    return [positionals[2]]
+
+
+def _parse_syscalltbl_command(command: str) -> list[PathStr]:
+    command_parts = _tokenize_single_command(command.strip())
+    positionals = [p.value for p in command_parts if isinstance(p, Positional)]
+    # expect positionals to be ["sh", path/to/syscalltbl.sh, input, output]
+    return [positionals[2]]
+
+
+def _parse_mkcapflags_command(command: str) -> list[PathStr]:
+    positionals = _tokenize_single_command_positionals_only(command)
+    # expect positionals to be ["sh", path/to/mkcapflags.sh, output, input1, input2]
+    return [positionals[3], positionals[4]]
+
+
+def _parse_orc_hash_command(command: str) -> list[PathStr]:
+    positionals = _tokenize_single_command_positionals_only(command)
+    # expect positionals to be ["sh", path/to/orc_hash.sh, '<', input, '>', output]
+    return [positionals[3]]
+
+
+def _parse_xen_hypercalls_command(command: str) -> list[PathStr]:
+    positionals = _tokenize_single_command_positionals_only(command)
+    # expect positionals to be ["sh", path/to/xen-hypercalls.sh, output, input1, input2, ...]
+    return positionals[3:]
+
+
+def _parse_gen_initramfs_command(command: str) -> list[PathStr]:
+    command_parts = _tokenize_single_command(command)
+    positionals = [p.value for p in command_parts if isinstance(p, Positional)]
+    # expect positionals to be ["sh", path/to/gen_initramfs.sh, input1, input2, ...]
+    return positionals[2:]
+
+
+def _parse_vdso2c_command(command: str) -> list[PathStr]:
+    positionals = _tokenize_single_command_positionals_only(command)
+    # expect positionals to be ['vdso2c', raw_input, stripped_input, output]
+    return [positionals[1], positionals[2]]
+
+
+def _parse_ld_command(command: str) -> list[PathStr]:
+    command_parts = _tokenize_single_command(
+        command=command.strip(),
+        flag_options=[
+            "-shared",
+            "--no-undefined",
+            "--eh-frame-hdr",
+            "-Bsymbolic",
+            "-r",
+            "--no-ld-generated-unwind-info",
+            "--no-dynamic-linker",
+            "-pie",
+            "--no-dynamic-linker--whole-archive",
+            "--whole-archive",
+            "--no-whole-archive",
+            "--start-group",
+            "--end-group",
+        ],
+    )
+    positionals = [p.value for p in command_parts if isinstance(p, Positional)]
+    # expect positionals to be ["ld", input1, input2, ...]
+    return positionals[1:]
+
+
+def _parse_sed_command(command: str) -> list[PathStr]:
+    command_parts = shlex.split(command)
+    # expect command parts to be ["sed", *, input]
+    input = command_parts[-1]
+    if input == "/dev/null":
+        return []
+    return [input]
+
+
+def _parse_awk(command: str) -> list[PathStr]:
+    command_parts = _tokenize_single_command(command)
+    positionals = [p.value for p in command_parts if isinstance(p, Positional)]
+    # expect positionals to be ["awk", input1, input2, ...]
+    return positionals[1:]
+
+
+def _parse_nm_piped_command(command: str) -> list[PathStr]:
+    nm_command, _ = command.split("|", 1)
+    command_parts = _tokenize_single_command(
+        command=nm_command.strip(),
+        flag_options=["p", "--defined-only"],
+    )
+    positionals = [p.value for p in command_parts if isinstance(p, Positional)]
+    # expect positionals to be ["nm", input1, input2, ...]
+    return [p for p in positionals[1:]]
+
+
+def _parse_pnm_to_logo_command(command: str) -> list[PathStr]:
+    command_parts = shlex.split(command)
+    # expect command parts to be ["pnmtologo", <options>, input]
+    return [command_parts[-1]]
+
+
+def _parse_relacheck(command: str) -> list[PathStr]:
+    positionals = _tokenize_single_command_positionals_only(command)
+    # expect positionals to be ["relachek", input, log_reference]
+    return [positionals[1]]
+
+
+def _parse_perl_command(command: str) -> list[PathStr]:
+    positionals = _tokenize_single_command_positionals_only(command.strip())
+    # expect positionals to be ["perl", input]
+    return [positionals[1]]
+
+
+def _parse_strip_command(command: str) -> list[PathStr]:
+    command_parts = _tokenize_single_command(command, flag_options=["--strip-debug"])
+    positionals = [p.value for p in command_parts if isinstance(p, Positional)]
+    # expect positionals to be ["strip", input1, input2, ...]
+    return positionals[1:]
+
+
+def _parse_mkpiggy_command(command: str) -> list[PathStr]:
+    mkpiggy_command, _ = command.split(">", 1)
+    positionals = _tokenize_single_command_positionals_only(mkpiggy_command)
+    # expect positionals to be ["mkpiggy", input]
+    return [positionals[1]]
+
+
+def _parse_relocs_command(command: str) -> list[PathStr]:
+    if ">" not in command:
+        # Only consider relocs commands that redirect output to a file.
+        # If there's no redirection, we assume it produces no output file and therefore has no input we care about.
+        return []
+    relocs_command, _ = command.split(">", 1)
+    command_parts = shlex.split(relocs_command)
+    # expect command_parts to be ["relocs", options, input]
+    return [command_parts[-1]]
+
+
+def _parse_mk_elfconfig_command(command: str) -> list[PathStr]:
+    positionals = _tokenize_single_command_positionals_only(command)
+    # expect positionals to be ["mk_elfconfig", "<", input, ">", output]
+    return [positionals[2]]
+
+
+def _parse_flex_command(command: str) -> list[PathStr]:
+    parts = shlex.split(command)
+    # expect last positional argument ending in `.l` to be the input file
+    for part in reversed(parts):
+        if not part.startswith("-") and part.endswith(".l"):
+            return [part]
+    raise CmdParsingError("Could not find .l input source file in command")
+
+
+def _parse_bison_command(command: str) -> list[PathStr]:
+    parts = shlex.split(command)
+    # expect last positional argument ending in `.y` to be the input file
+    for part in reversed(parts):
+        if not part.startswith("-") and part.endswith(".y"):
+            return [part]
+    raise CmdParsingError("Could not find input .y input source file in command")
+
+
+def _parse_tools_build_command(command: str) -> list[PathStr]:
+    positionals = _tokenize_single_command_positionals_only(command)
+    # expect positionals to be ["tools/build", "input1", "input2", "input3", "output"]
+    return positionals[1:-1]
+
+
+def _parse_extract_cert_command(command: str) -> list[PathStr]:
+    command_parts = shlex.split(command)
+    # expect command parts to be [path/to/extract-cert, input, output]
+    input = command_parts[1]
+    if not input:
+        return []
+    return [input]
+
+
+def _parse_dtc_command(command: str) -> list[PathStr]:
+    wno_flags = [command_part for command_part in shlex.split(command) if command_part.startswith("-Wno-")]
+    command_parts = _tokenize_single_command(command, flag_options=wno_flags)
+    positionals = [p.value for p in command_parts if isinstance(p, Positional)]
+    # expect positionals to be [path/to/dtc, input]
+    return [positionals[1]]
+
+
+def _parse_bindgen_command(command: str) -> list[PathStr]:
+    command_parts = shlex.split(command)
+    header_file_input_paths = [part for part in command_parts if part.endswith(".h")]
+    return header_file_input_paths
+
+
+def _parse_gen_header(command: str) -> list[PathStr]:
+    command_parts = shlex.split(command)
+    # expect command parts to be ["python3", path/to/gen_headers.py, ..., "--xml", input]
+    i = next(i for i, token in enumerate(command_parts) if token == "--xml")
+    return [command_parts[i + 1]]
+
+
+# Command parser registry
+SINGLE_COMMAND_PARSERS: list[tuple[re.Pattern[str], Callable[[str], list[PathStr]]]] = [
+    # Compound commands
+    (re.compile(r"\(.*?\)\s*>", re.DOTALL), _parse_compound_command),
+    (re.compile(r"\{.*?\}\s*>", re.DOTALL), _parse_compound_command),
+    # Standard Unix utilities and system tools
+    (re.compile(r"^rm\b"), _parse_noop),
+    (re.compile(r"^mkdir\b"), _parse_noop),
+    (re.compile(r"^touch\b"), _parse_noop),
+    (re.compile(r"^cat\b.*?[\|>]"), lambda c: _parse_cat_command(c.split("|")[0].split(">")[0])),
+    (re.compile(r"^echo[^|]*$"), _parse_noop),
+    (re.compile(r"^sed.*?>"), lambda c: _parse_sed_command(c.split(">")[0])),
+    (re.compile(r"^sed\b"), _parse_noop),
+    (re.compile(r"^awk.*?<.*?>"), lambda c: [c.split("<")[1].split(">")[0]]),
+    (re.compile(r"^awk.*?>"), lambda c: _parse_awk(c.split(">")[0])),
+    (re.compile(r"^(/bin/)?true\b"), _parse_noop),
+    (re.compile(r"^(/bin/)?false\b"), _parse_noop),
+    (re.compile(r"^openssl\s+req.*?-new.*?-keyout"), _parse_noop),
+    # Compilers and code generators
+    # (C/LLVM toolchain, Rust, Flex/Bison, Bindgen, Perl, etc.)
+    (re.compile(r"^([^\s]+-)?(gcc|clang)\b"), _parse_gcc_or_clang_command),
+    (re.compile(r"^([^\s]+-)?ld(\.bfd)?\b"), _parse_ld_command),
+    (re.compile(r"^printf\b.*\| xargs ([^\s]+-)?ar\b"), _parse_ar_piped_xargs_command),
+    (re.compile(r"^([^\s]+-)?ar\b"), _parse_ar_command),
+    (re.compile(r"^([^\s]+-)?nm\b.*?\|"), _parse_nm_piped_command),
+    (re.compile(r"^([^\s]+-)?objcopy\b"), _parse_objcopy_command),
+    (re.compile(r"^([^\s]+-)?strip\b"), _parse_strip_command),
+    (re.compile(r".*?rustc\b"), _parse_rustc_command),
+    (re.compile(r".*?rustdoc\b"), _parse_rustdoc_command),
+    (re.compile(r"^flex\b"), _parse_flex_command),
+    (re.compile(r"^bison\b"), _parse_bison_command),
+    (re.compile(r"^bindgen\b"), _parse_bindgen_command),
+    (re.compile(r"^perl\b"), _parse_perl_command),
+    # Kernel-specific build scripts and tools
+    (re.compile(r"^(.*/)?link-vmlinux\.sh\b"), _parse_link_vmlinux_command),
+    (re.compile(r"sh (.*/)?syscallhdr\.sh\b"), _parse_syscallhdr_command),
+    (re.compile(r"sh (.*/)?syscalltbl\.sh\b"), _parse_syscalltbl_command),
+    (re.compile(r"sh (.*/)?mkcapflags\.sh\b"), _parse_mkcapflags_command),
+    (re.compile(r"sh (.*/)?orc_hash\.sh\b"), _parse_orc_hash_command),
+    (re.compile(r"sh (.*/)?xen-hypercalls\.sh\b"), _parse_xen_hypercalls_command),
+    (re.compile(r"sh (.*/)?gen_initramfs\.sh\b"), _parse_gen_initramfs_command),
+    (re.compile(r"sh (.*/)?checkundef\.sh\b"), _parse_noop),
+    (re.compile(r"(.*/)?vdso2c\b"), _parse_vdso2c_command),
+    (re.compile(r"^(.*/)?mkpiggy.*?>"), _parse_mkpiggy_command),
+    (re.compile(r"^(.*/)?relocs\b"), _parse_relocs_command),
+    (re.compile(r"^(.*/)?mk_elfconfig.*?<.*?>"), _parse_mk_elfconfig_command),
+    (re.compile(r"^(.*/)?tools/build\b"), _parse_tools_build_command),
+    (re.compile(r"^(.*/)?certs/extract-cert"), _parse_extract_cert_command),
+    (re.compile(r"^(.*/)?scripts/dtc/dtc\b"), _parse_dtc_command),
+    (re.compile(r"^(.*/)?pnmtologo\b"), _parse_pnm_to_logo_command),
+    (re.compile(r"^(.*/)?kernel/pi/relacheck"), _parse_relacheck),
+    (re.compile(r"^drivers/gpu/drm/radeon/mkregtable"), lambda c: [c.split(" ")[1]]),
+    (re.compile(r"(.*/)?genheaders\b"), _parse_noop),
+    (re.compile(r"^(.*/)?mkcpustr\s+>"), _parse_noop),
+    (re.compile(r"^(.*/)polgen\b"), _parse_noop),
+    (re.compile(r"make -f .*/arch/x86/Makefile\.postlink"), _parse_noop),
+    (re.compile(r"^(.*/)?raid6/mktables\s+>"), _parse_noop),
+    (re.compile(r"^(.*/)?objtool\b"), _parse_noop),
+    (re.compile(r"^(.*/)?module/gen_test_kallsyms.sh"), _parse_noop),
+    (re.compile(r"^(.*/)?gen_header.py"), _parse_gen_header),
+    (re.compile(r"^(.*/)?scripts/rustdoc_test_gen"), _parse_noop),
+]
+
+
+# If Block pattern to match a simple, single-level if-then-fi block. Nested If blocks are not supported.
+IF_BLOCK_PATTERN = re.compile(
+    r"""
+    ^if(.*?);\s*         # Match 'if <condition>;' (non-greedy)
+    then(.*?);\s*        # Match 'then <body>;' (non-greedy)
+    fi\b                 # Match 'fi'
+    """,
+    re.VERBOSE,
+)
+
+
+@dataclass
+class IfBlock:
+    condition: str
+    then_statement: str
+
+
+def _unwrap_outer_parentheses(s: str) -> str:
+    s = s.strip()
+    if not (s.startswith("(") and s.endswith(")")):
+        return s
+
+    count = 0
+    for i, char in enumerate(s):
+        if char == "(":
+            count += 1
+        elif char == ")":
+            count -= 1
+            # If count is 0 before the end, outer parentheses don't match
+            if count == 0 and i != len(s) - 1:
+                return s
+
+    # outer parentheses do match, unwrap once
+    return _unwrap_outer_parentheses(s[1:-1])
+
+
+def _find_first_top_level_command_separator(
+    commands: str, separators: list[str] = [";", "&&"]
+) -> tuple[int | None, int | None]:
+    in_single_quote = False
+    in_double_quote = False
+    in_curly_braces = 0
+    in_braces = 0
+    for i, char in enumerate(commands):
+        if char == "'" and not in_double_quote:
+            # Toggle single quote state (unless inside double quotes)
+            in_single_quote = not in_single_quote
+        elif char == '"' and not in_single_quote:
+            # Toggle double quote state (unless inside single quotes)
+            in_double_quote = not in_double_quote
+
+        if in_single_quote or in_double_quote:
+            continue
+
+        # Toggle braces state
+        if char == "{":
+            in_curly_braces += 1
+        if char == "}":
+            in_curly_braces -= 1
+
+        if char == "(":
+            in_braces += 1
+        if char == ")":
+            in_braces -= 1
+
+        if in_curly_braces > 0 or in_braces > 0:
+            continue
+
+        # return found separator position and separator length
+        for separator in separators:
+            if commands[i : i + len(separator)] == separator:
+                return i, len(separator)
+
+    return None, None
+
+
+def _split_commands(commands: str) -> list[str | IfBlock]:
+    """
+    Splits a string of command-line commands into individual parts.
+
+    This function handles:
+    - Top-level command separators (e.g., `;` and `&&`) to split multiple commands.
+    - Conditional if-blocks, returning them as `IfBlock` instances.
+    - Preserves the order of commands and trims whitespace.
+
+    Args:
+        commands (str): The raw command string.
+
+    Returns:
+        list[str | IfBlock]: A list of single commands or `IfBlock` objects.
+    """
+    single_commands: list[str | IfBlock] = []
+    remaining_commands = _unwrap_outer_parentheses(commands)
+    while len(remaining_commands) > 0:
+        remaining_commands = remaining_commands.strip()
+
+        # if block
+        matched_if = IF_BLOCK_PATTERN.match(remaining_commands)
+        if matched_if:
+            condition, then_statement = matched_if.groups()
+            single_commands.append(IfBlock(condition.strip(), then_statement.strip()))
+            full_matched = matched_if.group(0)
+            remaining_commands = remaining_commands.removeprefix(full_matched).lstrip("; \n")
+            continue
+
+        # command until next separator
+        separator_position, separator_length = _find_first_top_level_command_separator(remaining_commands)
+        if separator_position is not None and separator_length is not None:
+            single_commands.append(remaining_commands[:separator_position].strip())
+            remaining_commands = remaining_commands[separator_position + separator_length :].strip()
+            continue
+
+        # single last command
+        single_commands.append(remaining_commands)
+        break
+
+    return single_commands
+
+
+def parse_inputs_from_commands(commands: str, fail_on_unknown_build_command: bool) -> list[PathStr]:
+    """
+    Extract input files referenced in a set of command-line commands.
+
+    Args:
+        commands (str): Command line expression to parse.
+        fail_on_unknown_build_command (bool): Whether to fail if an unknown build command is encountered. If False, errors are logged as warnings.
+
+    Returns:
+        list[PathStr]: List of input file paths required by the commands.
+    """
+
+    def log_error_or_warning(message: str, /, **kwargs: Any) -> None:
+        if fail_on_unknown_build_command:
+            sbom_logging.error(message, **kwargs)
+        else:
+            sbom_logging.warning(message, **kwargs)
+
+    input_files: list[PathStr] = []
+    for single_command in _split_commands(commands):
+        if isinstance(single_command, IfBlock):
+            inputs = parse_inputs_from_commands(single_command.then_statement, fail_on_unknown_build_command)
+            if inputs:
+                log_error_or_warning(
+                    "Skipped parsing command {then_statement} because input files in IfBlock 'then' statement are not supported",
+                    then_statement=single_command.then_statement,
+                )
+            continue
+
+        matched_parser = next(
+            (parser for pattern, parser in SINGLE_COMMAND_PARSERS if pattern.match(single_command)), None
+        )
+        if matched_parser is None:
+            log_error_or_warning(
+                "Skipped parsing command {single_command} because no matching parser was found",
+                single_command=single_command,
+            )
+            continue
+        try:
+            inputs = matched_parser(single_command)
+            input_files.extend(inputs)
+        except CmdParsingError as e:
+            log_error_or_warning(
+                "Skipped parsing command {single_command} because of command parsing error: {error_message}",
+                single_command=single_command,
+                error_message=e.message,
+            )
+
+    return [input.strip().rstrip("/") for input in input_files]
Signature · 1 line
2.34.1
#4 lore raw

PATCH v2 4/14 tools/sbom: add cmd graph generation

In reply to Luis Augenstein

Implement command graph generation by parsing .cmd files to build a dependency graph.
Add CmdGraph, CmdGraphNode, and .cmd file parsing. Supports generating a flat list of used source files via the --generate-used-files cli argument.

---
 tools/sbom/Makefile                         |   6 +-
 tools/sbom/sbom.py                          |  39 +++++
 tools/sbom/sbom/cmd_graph/__init__.py       |   7 +
 tools/sbom/sbom/cmd_graph/cmd_file.py       | 149 ++++++++++++++++++++
 tools/sbom/sbom/cmd_graph/cmd_graph.py      |  46 ++++++
 tools/sbom/sbom/cmd_graph/cmd_graph_node.py | 120 ++++++++++++++++
 tools/sbom/sbom/cmd_graph/deps_parser.py    |  52 +++++++
 tools/sbom/sbom/config.py                   | 147 ++++++++++++++++++-
 8 files changed, 563 insertions(+), 3 deletions(-)
 create mode 100644 tools/sbom/sbom/cmd_graph/__init__.py
 create mode 100644 tools/sbom/sbom/cmd_graph/cmd_file.py
 create mode 100644 tools/sbom/sbom/cmd_graph/cmd_graph.py
 create mode 100644 tools/sbom/sbom/cmd_graph/cmd_graph_node.py
 create mode 100644 tools/sbom/sbom/cmd_graph/deps_parser.py
tools/sbom/Makefile +5 -1
index 8be7f2f3e631..b4ef72b30960 100644
@@ -28,7 +28,11 @@ $(SBOM_TARGETS) &: $(SBOM_DEPS)
 		sed 's/\.o$$/.ko/' $(objtree)/modules.order >> $(SBOM_ROOTS_FILE); \
 	fi
 
-	@python3 sbom.py
+	@python3 sbom.py \
+      --src-tree $(srctree) \
+      --obj-tree $(objtree) \
+      --roots-file $(SBOM_ROOTS_FILE) \
+      --output-directory $(objtree)
 
 	@rm $(SBOM_ROOTS_FILE)
 
tools/sbom/sbom.py +39 -0
index c7f23d6eb300..25d912a282de 100644
@@ -7,9 +7,13 @@ Compute software bill of materials in SPDX format describing a kernel build.
 """
 
 import logging
+import os
 import sys
+import time
 import sbom.sbom_logging as sbom_logging
 from sbom.config import get_config
+from sbom.path_utils import is_relative_to
+from sbom.cmd_graph import CmdGraph
 
 
 def main():
@@ -22,6 +26,36 @@ def main():
         format="[%(levelname)s] %(message)s",
     )
 
+    # Build cmd graph
+    logging.debug("Start building cmd graph")
+    start_time = time.time()
+    cmd_graph = CmdGraph.create(config.root_paths, config)
+    logging.debug(f"Built cmd graph in {time.time() - start_time} seconds")
+
+    # Save used files document
+    if config.generate_used_files:
+        if config.src_tree == config.obj_tree:
+            logging.info(
+                f"Extracting all files from the cmd graph to {(config.used_files_file_name,)} "
+                "instead of only source files because source files cannot be "
+                "reliably classified when the source and object trees are identical.",
+            )
+            used_files = [os.path.relpath(node.absolute_path, config.src_tree) for node in cmd_graph]
+            logging.debug(f"Found {len(used_files)} files in cmd graph.")
+        else:
+            used_files = [
+                os.path.relpath(node.absolute_path, config.src_tree)
+                for node in cmd_graph
+                if is_relative_to(node.absolute_path, config.src_tree)
+                and not is_relative_to(node.absolute_path, config.obj_tree)
+            ]
+            logging.debug(f"Found {len(used_files)} source files in cmd graph")
+        if not sbom_logging.has_errors() or config.write_output_on_error:
+            used_files_path = os.path.join(config.output_directory, config.used_files_file_name)
+            with open(used_files_path, "w", encoding="utf-8") as f:
+                f.write("\n".join(str(file_path) for file_path in used_files))
+            logging.debug(f"Successfully saved {used_files_path}")
+
     # Report collected warnings and errors in case of failure
     warning_summary = sbom_logging.summarize_warnings()
     error_summary = sbom_logging.summarize_errors()
@@ -30,6 +64,11 @@ def main():
         logging.warning(warning_summary)
     if error_summary:
         logging.error(error_summary)
+        if not config.write_output_on_error:
+            logging.info(
+                "Use --write-output-on-error to generate output documents even when errors occur. "
+                "Note that in this case the generated SPDX documents may be incomplete."
+            )
         sys.exit(1)
 
 
tools/sbom/sbom/cmd_graph/__init__.py new file +7 -0
new file mode 100644
index 000000000000..9d661a5c3d93
@@ -0,0 +1,7 @@
+# SPDX-License-Identifier: GPL-2.0-only OR MIT
+# Copyright (C) 2025 TNG Technology Consulting GmbH
+
+from .cmd_graph import CmdGraph
+from .cmd_graph_node import CmdGraphNode, CmdGraphNodeConfig
+
+__all__ = ["CmdGraph", "CmdGraphNode", "CmdGraphNodeConfig"]
tools/sbom/sbom/cmd_graph/cmd_file.py new file +149 -0

149 lines not on this page · raw message

tools/sbom/sbom/cmd_graph/cmd_graph.py new file +46 -0

46 lines not on this page · raw message

tools/sbom/sbom/cmd_graph/cmd_graph_node.py new file +120 -0

120 lines not on this page · raw message

tools/sbom/sbom/cmd_graph/deps_parser.py new file +52 -0

52 lines not on this page · raw message

tools/sbom/sbom/config.py +145 -2

180 lines not on this page · raw message

Signature · 1 line
2.34.1
#5 lore raw

PATCH v2 5/14 tools/sbom: add additional dependency sources for cmd graph

In reply to Luis Augenstein

Add hardcoded dependencies and .incbin directive parsing to discover dependencies not tracked by .cmd files.

---
 tools/sbom/sbom/cmd_graph/cmd_graph_node.py   | 24 +++++-
 .../sbom/cmd_graph/hardcoded_dependencies.py  | 83 +++++++++++++++++++
 tools/sbom/sbom/cmd_graph/incbin_parser.py    | 42 ++++++++++
 tools/sbom/sbom/environment.py                | 14 ++++
 4 files changed, 162 insertions(+), 1 deletion(-)
 create mode 100644 tools/sbom/sbom/cmd_graph/hardcoded_dependencies.py
 create mode 100644 tools/sbom/sbom/cmd_graph/incbin_parser.py
 create mode 100644 tools/sbom/sbom/environment.py
tools/sbom/sbom/cmd_graph/cmd_graph_node.py +23 -1
index fdaed0f0ccba..feacdbf76955 100644
@@ -9,6 +9,8 @@ from typing import Iterator, Protocol
 
 from sbom import sbom_logging
 from sbom.cmd_graph.cmd_file import CmdFile
+from sbom.cmd_graph.hardcoded_dependencies import get_hardcoded_dependencies
+from sbom.cmd_graph.incbin_parser import parse_incbin_statements
 from sbom.path_utils import PathStr, is_relative_to
 
 
@@ -104,14 +106,34 @@ class CmdGraphNode:
             )
             return node
 
+        # Search for dependencies to add to the graph as child nodes. Child paths are always relative to the output tree.
+        def _build_child_node(child_path: PathStr) -> "CmdGraphNode":
+            return CmdGraphNode.create(child_path, config, cache, depth + 1)
+
+        node.hardcoded_dependencies = [
+            _build_child_node(hardcoded_dependency_path)
+            for hardcoded_dependency_path in get_hardcoded_dependencies(
+                target_path_absolute, config.obj_tree, config.src_tree
+            )
+        ]
+
         if cmd_file is not None:
             node.cmd_file_dependencies = [
-                CmdGraphNode.create(cmd_file_dependency_path, config, cache, depth + 1)
+                _build_child_node(cmd_file_dependency_path)
                 for cmd_file_dependency_path in cmd_file.get_dependencies(
                     target_path, config.obj_tree, config.fail_on_unknown_build_command
                 )
             ]
 
+        if node.absolute_path.endswith(".S"):
+            node.incbin_dependencies = [
+                IncbinDependency(
+                    node=_build_child_node(incbin_statement.path),
+                    full_statement=incbin_statement.full_statement,
+                )
+                for incbin_statement in parse_incbin_statements(node.absolute_path)
+            ]
+
         return node
 
 
tools/sbom/sbom/cmd_graph/hardcoded_dependencies.py new file +83 -0

83 lines not on this page · raw message

tools/sbom/sbom/cmd_graph/incbin_parser.py new file +42 -0

42 lines not on this page · raw message

tools/sbom/sbom/environment.py new file +14 -0
new file mode 100644
index 000000000000..b3fb2f0ba61d
@@ -0,0 +1,14 @@
+# SPDX-License-Identifier: GPL-2.0-only OR MIT
+# Copyright (C) 2025 TNG Technology Consulting GmbH
+
+import os
+
+
+class Environment:
+    """
+    Read-only accessor for kernel build environment variables.
+    """
+
+    @classmethod
+    def SRCARCH(cls) -> str | None:
+        return os.getenv("SRCARCH")
Signature · 1 line
2.34.1
#6 lore raw

PATCH v2 6/14 tools/sbom: add SPDX classes

In reply to Luis Augenstein

Implement Python dataclasses to model the SPDX classes required within an SPDX document. The class and property names are consistent with the SPDX 3.0.1 specification.

---
 tools/sbom/sbom/spdx/__init__.py        |   7 +
 tools/sbom/sbom/spdx/build.py           |  17 +++
 tools/sbom/sbom/spdx/core.py            | 182 ++++++++++++++++++++++++
 tools/sbom/sbom/spdx/serialization.py   |  56 ++++++++
 tools/sbom/sbom/spdx/simplelicensing.py |  20 +++
 tools/sbom/sbom/spdx/software.py        |  71 +++++++++
 tools/sbom/sbom/spdx/spdxId.py          |  36 +++++
 7 files changed, 389 insertions(+)
 create mode 100644 tools/sbom/sbom/spdx/__init__.py
 create mode 100644 tools/sbom/sbom/spdx/build.py
 create mode 100644 tools/sbom/sbom/spdx/core.py
 create mode 100644 tools/sbom/sbom/spdx/serialization.py
 create mode 100644 tools/sbom/sbom/spdx/simplelicensing.py
 create mode 100644 tools/sbom/sbom/spdx/software.py
 create mode 100644 tools/sbom/sbom/spdx/spdxId.py
tools/sbom/sbom/spdx/__init__.py new file +7 -0
new file mode 100644
index 000000000000..4097b59f8f17
@@ -0,0 +1,7 @@
+# SPDX-License-Identifier: GPL-2.0-only OR MIT
+# Copyright (C) 2025 TNG Technology Consulting GmbH
+
+from .spdxId import SpdxId, SpdxIdGenerator
+from .serialization import JsonLdSpdxDocument
+
+__all__ = ["JsonLdSpdxDocument", "SpdxId", "SpdxIdGenerator"]
tools/sbom/sbom/spdx/build.py new file +17 -0
new file mode 100644
index 000000000000..180a8f1e8bd3
@@ -0,0 +1,17 @@
+# SPDX-License-Identifier: GPL-2.0-only OR MIT
+# Copyright (C) 2025 TNG Technology Consulting GmbH
+
+from dataclasses import dataclass, field
+from sbom.spdx.core import DictionaryEntry, Element, Hash
+
+
+@dataclass(kw_only=True)
+class Build(Element):
+    """https://spdx.github.io/spdx-spec/v3.0.1/model/Build/Classes/Build/"""
+
+    type: str = field(init=False, default="build_Build")
+    build_buildType: str
+    build_buildId: str
+    build_environment: list[DictionaryEntry] = field(default_factory=list[DictionaryEntry])
+    build_configSourceUri: list[str] = field(default_factory=list[str])
+    build_configSourceDigest: list[Hash] = field(default_factory=list[Hash])
tools/sbom/sbom/spdx/core.py new file +182 -0

182 lines not on this page · raw message

tools/sbom/sbom/spdx/serialization.py new file +56 -0

56 lines not on this page · raw message

tools/sbom/sbom/spdx/simplelicensing.py new file +20 -0
new file mode 100644
index 000000000000..750ddd24ad89
@@ -0,0 +1,20 @@
+# SPDX-License-Identifier: GPL-2.0-only OR MIT
+# Copyright (C) 2025 TNG Technology Consulting GmbH
+
+from dataclasses import dataclass, field
+from sbom.spdx.core import Element
+
+
+@dataclass(kw_only=True)
+class AnyLicenseInfo(Element):
+    """https://spdx.github.io/spdx-spec/v3.0.1/model/SimpleLicensing/Classes/AnyLicenseInfo/"""
+
+    type: str = field(init=False, default="simplelicensing_AnyLicenseInfo")
+
+
+@dataclass(kw_only=True)
+class LicenseExpression(AnyLicenseInfo):
+    """https://spdx.github.io/spdx-spec/v3.0.1/model/SimpleLicensing/Classes/LicenseExpression/"""
+
+    type: str = field(init=False, default="simplelicensing_LicenseExpression")
+    simplelicensing_licenseExpression: str
tools/sbom/sbom/spdx/software.py new file +71 -0

71 lines not on this page · raw message

tools/sbom/sbom/spdx/spdxId.py new file +36 -0
new file mode 100644
index 000000000000..589e85c5f706
@@ -0,0 +1,36 @@
+# SPDX-License-Identifier: GPL-2.0-only OR MIT
+# Copyright (C) 2025 TNG Technology Consulting GmbH
+
+from itertools import count
+from typing import Iterator
+
+SpdxId = str
+
+
+class SpdxIdGenerator:
+    _namespace: str
+    _prefix: str | None = None
+    _counter: Iterator[int]
+
+    def __init__(self, namespace: str, prefix: str | None = None) -> None:
+        """
+        Initialize the SPDX ID generator with a namespace.
+
+        Args:
+            namespace: The full namespace to use for generated IDs.
+            prefix: Optional. If provided, generated IDs will use this prefix instead of the full namespace.
+        """
+        self._namespace = namespace
+        self._prefix = prefix
+        self._counter = count(0)
+
+    def generate(self) -> SpdxId:
+        return f"{f'{self._prefix}:' if self._prefix else self._namespace}{next(self._counter)}"
+
+    @property
+    def prefix(self) -> str | None:
+        return self._prefix
+
+    @property
+    def namespace(self) -> str:
+        return self._namespace
Signature · 1 line
2.34.1
#7 lore raw

PATCH v2 7/14 tools/sbom: add JSON-LD serialization

In reply to Luis Augenstein

Add infrastructure to serialize an SPDX graph as a JSON-LD document. NamespaceMaps in the SPDX document are converted to custom prefixes in the @context field of the JSON-LD output.

The SBOM tool uses NamespaceMaps solely to shorten SPDX IDs, avoiding repetition of full namespace URIs by using short prefixes.

---
 tools/sbom/Makefile                           |  3 +-
 tools/sbom/sbom.py                            | 52 +++++++++++++++++
 tools/sbom/sbom/config.py                     | 56 +++++++++++++++++++
 tools/sbom/sbom/path_utils.py                 | 11 ++++
 tools/sbom/sbom/spdx_graph/__init__.py        |  7 +++
 .../sbom/sbom/spdx_graph/build_spdx_graphs.py | 36 ++++++++++++
 .../sbom/sbom/spdx_graph/spdx_graph_model.py  | 36 ++++++++++++
 7 files changed, 200 insertions(+), 1 deletion(-)
 create mode 100644 tools/sbom/sbom/path_utils.py
 create mode 100644 tools/sbom/sbom/spdx_graph/__init__.py
 create mode 100644 tools/sbom/sbom/spdx_graph/build_spdx_graphs.py
 create mode 100644 tools/sbom/sbom/spdx_graph/spdx_graph_model.py
tools/sbom/Makefile +2 -1
index b4ef72b30960..f907f427bf8d 100644
@@ -32,7 +32,8 @@ $(SBOM_TARGETS) &: $(SBOM_DEPS)
       --src-tree $(srctree) \
       --obj-tree $(objtree) \
       --roots-file $(SBOM_ROOTS_FILE) \
-      --output-directory $(objtree)
+      --output-directory $(objtree) \
+      --generate-spdx
 
 	@rm $(SBOM_ROOTS_FILE)
 
tools/sbom/sbom.py +52 -0

75 lines not on this page · raw message

tools/sbom/sbom/config.py +56 -0

116 lines not on this page · raw message

tools/sbom/sbom/path_utils.py new file +11 -0
new file mode 100644
index 000000000000..d28d67b25398
@@ -0,0 +1,11 @@
+# SPDX-License-Identifier: GPL-2.0-only OR MIT
+# Copyright (C) 2025 TNG Technology Consulting GmbH
+
+import os
+
+PathStr = str
+"""Filesystem path represented as a plain string for better performance than pathlib.Path."""
+
+
+def is_relative_to(path: PathStr, base: PathStr) -> bool:
+    return os.path.commonpath([path, base]) == base
tools/sbom/sbom/spdx_graph/__init__.py new file +7 -0
new file mode 100644
index 000000000000..3557b1d51bf9
@@ -0,0 +1,7 @@
+# SPDX-License-Identifier: GPL-2.0-only OR MIT
+# Copyright (C) 2025 TNG Technology Consulting GmbH
+
+from .build_spdx_graphs import build_spdx_graphs
+from .spdx_graph_model import SpdxIdGeneratorCollection
+
+__all__ = ["build_spdx_graphs", "SpdxIdGeneratorCollection"]
tools/sbom/sbom/spdx_graph/build_spdx_graphs.py new file +36 -0
new file mode 100644
index 000000000000..bb3db4e423da
@@ -0,0 +1,36 @@
+# SPDX-License-Identifier: GPL-2.0-only OR MIT
+# Copyright (C) 2025 TNG Technology Consulting GmbH
+
+
+from typing import Protocol
+
+from sbom.config import KernelSpdxDocumentKind
+from sbom.cmd_graph import CmdGraph
+from sbom.path_utils import PathStr
+from sbom.spdx_graph.spdx_graph_model import SpdxGraph, SpdxIdGeneratorCollection
+
+
+class SpdxGraphConfig(Protocol):
+    obj_tree: PathStr
+    src_tree: PathStr
+
+
+def build_spdx_graphs(
+    cmd_graph: CmdGraph,
+    spdx_id_generators: SpdxIdGeneratorCollection,
+    config: SpdxGraphConfig,
+) -> dict[KernelSpdxDocumentKind, SpdxGraph]:
+    """
+    Builds SPDX graphs (output, source, and build) based on a cmd dependency graph.
+    If the source and object trees are identical, no dedicated source graph can be created.
+    In that case the source files are added to the build graph instead.
+
+    Args:
+        cmd_graph: The dependency graph of a kernel build.
+        spdx_id_generators: Collection of SPDX ID generators.
+        config: Configuration options.
+
+    Returns:
+        Dictionary of SPDX graphs
+    """
+    return {}
tools/sbom/sbom/spdx_graph/spdx_graph_model.py new file +36 -0
new file mode 100644
index 000000000000..682194d4362a
@@ -0,0 +1,36 @@
+# SPDX-License-Identifier: GPL-2.0-only OR MIT
+# Copyright (C) 2025 TNG Technology Consulting GmbH
+
+from dataclasses import dataclass
+from sbom.spdx.core import CreationInfo, SoftwareAgent, SpdxDocument, SpdxObject
+from sbom.spdx.software import Sbom
+from sbom.spdx.spdxId import SpdxIdGenerator
+
+
+@dataclass
+class SpdxGraph:
+    """Represents the complete graph of a single SPDX document."""
+
+    spdx_document: SpdxDocument
+    agent: SoftwareAgent
+    creation_info: CreationInfo
+    sbom: Sbom
+
+    def to_list(self) -> list[SpdxObject]:
+        return [
+            self.spdx_document,
+            self.agent,
+            self.creation_info,
+            self.sbom,
+            *self.sbom.element,
+        ]
+
+
+@dataclass
+class SpdxIdGeneratorCollection:
+    """Holds SPDX ID generators for different document types to ensure globally unique SPDX IDs."""
+
+    base: SpdxIdGenerator
+    source: SpdxIdGenerator
+    build: SpdxIdGenerator
+    output: SpdxIdGenerator
Signature · 1 line
2.34.1
#8 lore raw

PATCH v2 8/14 tools/sbom: add shared SPDX elements

In reply to Luis Augenstein

Implement shared SPDX elements used in all three documents.

---
 tools/sbom/sbom/config.py                     | 25 +++++++++++++++
 .../sbom/sbom/spdx_graph/build_spdx_graphs.py |  5 ++-
 .../sbom/spdx_graph/shared_spdx_elements.py   | 32 +++++++++++++++++++
 3 files changed, 61 insertions(+), 1 deletion(-)
 create mode 100644 tools/sbom/sbom/spdx_graph/shared_spdx_elements.py
tools/sbom/sbom/config.py +25 -0
index 0985457c3cae..9278e2be7cb2 100644
@@ -3,6 +3,7 @@
 
 import argparse
 from dataclasses import dataclass
+from datetime import datetime
 from enum import Enum
 import os
 from typing import Any
@@ -52,6 +53,9 @@ class KernelSbomConfig:
     write_output_on_error: bool
     """Whether to write output documents even if errors occur."""
 
+    created: datetime
+    """Datetime to use for the SPDX created property of the CreationInfo element."""
+
     spdxId_prefix: str
     """Prefix to use for all SPDX element IDs."""
 
@@ -150,6 +154,16 @@ def _parse_cli_arguments() -> dict[str, Any]:
 
     # SPDX specific options
     spdx_group = parser.add_argument_group("SPDX options", "Options for customizing SPDX document generation")
+    spdx_group.add_argument(
+        "--created",
+        default=None,
+        help=(
+            "The SPDX created property to use for the CreationInfo element in "
+            "ISO format (YYYY-MM-DD [HH:MM:SS]).\n"
+            "If not provided the last modification time of the first root output "
+            "is used. (default: None)"
+        ),
+    )
     spdx_group.add_argument(
         "--spdxId-prefix",
         default="urn:spdx.dev:",
@@ -195,6 +209,16 @@ def get_config() -> KernelSbomConfig:
     fail_on_unknown_build_command = not args["do_not_fail_on_unknown_build_command"]
     write_output_on_error = args["write_output_on_error"]
 
+    if args["created"] is None:
+        created = datetime.fromtimestamp(os.path.getmtime(os.path.join(obj_tree, root_paths[0])))
+    else:
+        try:
+            created = datetime.fromisoformat(args["created"])
+        except ValueError:
+            raise argparse.ArgumentTypeError(
+                f"Invalid date format for argument '--created': '{args['created']}'. "
+                "Expected ISO format (YYYY-MM-DD [HH:MM:SS])."
+            )
     spdxId_prefix = args["spdxId_prefix"]
     prettify_json = args["prettify_json"]
 
@@ -218,6 +242,7 @@ def get_config() -> KernelSbomConfig:
         debug=debug,
         fail_on_unknown_build_command=fail_on_unknown_build_command,
         write_output_on_error=write_output_on_error,
+        created=created,
         spdxId_prefix=spdxId_prefix,
         prettify_json=prettify_json,
     )
tools/sbom/sbom/spdx_graph/build_spdx_graphs.py +4 -1
index bb3db4e423da..9c47258a31c6 100644
@@ -1,18 +1,20 @@
 # SPDX-License-Identifier: GPL-2.0-only OR MIT
 # Copyright (C) 2025 TNG Technology Consulting GmbH
 
-
+from datetime import datetime
 from typing import Protocol
 
 from sbom.config import KernelSpdxDocumentKind
 from sbom.cmd_graph import CmdGraph
 from sbom.path_utils import PathStr
 from sbom.spdx_graph.spdx_graph_model import SpdxGraph, SpdxIdGeneratorCollection
+from sbom.spdx_graph.shared_spdx_elements import SharedSpdxElements
 
 
 class SpdxGraphConfig(Protocol):
     obj_tree: PathStr
     src_tree: PathStr
+    created: datetime
 
 
 def build_spdx_graphs(
@@ -33,4 +35,5 @@ def build_spdx_graphs(
     Returns:
         Dictionary of SPDX graphs
     """
+    shared_elements = SharedSpdxElements.create(spdx_id_generators.base, config.created)
     return {}
tools/sbom/sbom/spdx_graph/shared_spdx_elements.py new file +32 -0
new file mode 100644
index 000000000000..0c83428f4c70
@@ -0,0 +1,32 @@
+# SPDX-License-Identifier: GPL-2.0-only OR MIT
+# Copyright (C) 2025 TNG Technology Consulting GmbH
+
+from dataclasses import dataclass
+from datetime import datetime
+from sbom.spdx.core import CreationInfo, SoftwareAgent
+from sbom.spdx.spdxId import SpdxIdGenerator
+
+
+@dataclass(frozen=True)
+class SharedSpdxElements:
+    agent: SoftwareAgent
+    creation_info: CreationInfo
+
+    @classmethod
+    def create(cls, spdx_id_generator: SpdxIdGenerator, created: datetime) -> "SharedSpdxElements":
+        """
+        Creates shared SPDX elements used across multiple documents.
+
+        Args:
+            spdx_id_generator: Generator for creating SPDX IDs.
+            created: SPDX 'created' property used for the creation info.
+
+        Returns:
+            SharedSpdxElements with agent and creation info.
+        """
+        agent = SoftwareAgent(
+            spdxId=spdx_id_generator.generate(),
+            name="KernelSbom",
+        )
+        creation_info = CreationInfo(createdBy=[agent], created=created.strftime("%Y-%m-%dT%H:%M:%SZ"))
+        return SharedSpdxElements(agent=agent, creation_info=creation_info)
Signature · 1 line
2.34.1
#9 lore raw

PATCH v2 9/14 tools/sbom: collect file metadata

In reply to Luis Augenstein

Implement the kernel_file module that collects file metadata, including license identifier for source files, SHA-256 hash, Git blob object ID, an estimation of the file type, and whether files belong to the source, build, or output SBOM.

---
 .../sbom/sbom/spdx_graph/build_spdx_graphs.py |   2 +
 tools/sbom/sbom/spdx_graph/kernel_file.py     | 310 ++++++++++++++++++
 2 files changed, 312 insertions(+)
 create mode 100644 tools/sbom/sbom/spdx_graph/kernel_file.py
tools/sbom/sbom/spdx_graph/build_spdx_graphs.py +2 -0
index 9c47258a31c6..0f95f99d560a 100644
@@ -7,6 +7,7 @@ from typing import Protocol
 from sbom.config import KernelSpdxDocumentKind
 from sbom.cmd_graph import CmdGraph
 from sbom.path_utils import PathStr
+from sbom.spdx_graph.kernel_file import KernelFileCollection
 from sbom.spdx_graph.spdx_graph_model import SpdxGraph, SpdxIdGeneratorCollection
 from sbom.spdx_graph.shared_spdx_elements import SharedSpdxElements
 
@@ -36,4 +37,5 @@ def build_spdx_graphs(
         Dictionary of SPDX graphs
     """
     shared_elements = SharedSpdxElements.create(spdx_id_generators.base, config.created)
+    kernel_files = KernelFileCollection.create(cmd_graph, config.obj_tree, config.src_tree, spdx_id_generators)
     return {}
tools/sbom/sbom/spdx_graph/kernel_file.py new file +310 -0

310 lines not on this page · raw message

Signature · 1 line
2.34.1
#10 lore raw

PATCH v2 10/14 tools/sbom: add SPDX output graph

In reply to Luis Augenstein

Implement the SPDX output graph which contains the distributable build outputs and high level metadata about the build.

---
 tools/sbom/Makefile                           |   4 +-
 tools/sbom/sbom/config.py                     |  64 ++++++
 tools/sbom/sbom/environment.py                | 150 ++++++++++++++
 .../sbom/sbom/spdx_graph/build_spdx_graphs.py |  18 +-
 .../sbom/sbom/spdx_graph/spdx_output_graph.py | 188 ++++++++++++++++++
 5 files changed, 422 insertions(+), 2 deletions(-)
 create mode 100644 tools/sbom/sbom/spdx_graph/spdx_output_graph.py
tools/sbom/Makefile +3 -1
index f907f427bf8d..6af0f0f6e2eb 100644
@@ -33,7 +33,9 @@ $(SBOM_TARGETS) &: $(SBOM_DEPS)
       --obj-tree $(objtree) \
       --roots-file $(SBOM_ROOTS_FILE) \
       --output-directory $(objtree) \
-      --generate-spdx
+      --generate-spdx \
+      --package-license "GPL-2.0 WITH Linux-syscall-note" \
+      --package-version "$(KERNELVERSION)"
 
 	@rm $(SBOM_ROOTS_FILE)
 
tools/sbom/sbom/config.py +64 -0

88 lines not on this page · raw message

tools/sbom/sbom/environment.py +150 -0

162 lines not on this page · raw message

tools/sbom/sbom/spdx_graph/build_spdx_graphs.py +17 -1
index 0f95f99d560a..2af0fbe6cdbe 100644
@@ -10,12 +10,18 @@ from sbom.path_utils import PathStr
 from sbom.spdx_graph.kernel_file import KernelFileCollection
 from sbom.spdx_graph.spdx_graph_model import SpdxGraph, SpdxIdGeneratorCollection
 from sbom.spdx_graph.shared_spdx_elements import SharedSpdxElements
+from sbom.spdx_graph.spdx_output_graph import SpdxOutputGraph
 
 
 class SpdxGraphConfig(Protocol):
     obj_tree: PathStr
     src_tree: PathStr
     created: datetime
+    build_type: str
+    build_id: str | None
+    package_license: str
+    package_version: str | None
+    package_copyright_text: str | None
 
 
 def build_spdx_graphs(
@@ -38,4 +44,14 @@ def build_spdx_graphs(
     """
     shared_elements = SharedSpdxElements.create(spdx_id_generators.base, config.created)
     kernel_files = KernelFileCollection.create(cmd_graph, config.obj_tree, config.src_tree, spdx_id_generators)
-    return {}
+    output_graph = SpdxOutputGraph.create(
+        root_files=list(kernel_files.output.values()),
+        shared_elements=shared_elements,
+        spdx_id_generators=spdx_id_generators,
+        config=config,
+    )
+    spdx_graphs: dict[KernelSpdxDocumentKind, SpdxGraph] = {
+        KernelSpdxDocumentKind.OUTPUT: output_graph,
+    }
+
+    return spdx_graphs
tools/sbom/sbom/spdx_graph/spdx_output_graph.py new file +188 -0

188 lines not on this page · raw message

Signature · 1 line
2.34.1
#11 lore raw

PATCH v2 11/14 tools/sbom: add SPDX source graph

In reply to Luis Augenstein

Implement the SPDX source graph which contains all source files involved during the build, along with the licensing information for each file.

---
 .../sbom/sbom/spdx_graph/build_spdx_graphs.py |   8 ++
 .../sbom/sbom/spdx_graph/spdx_source_graph.py | 126 ++++++++++++++++++
 2 files changed, 134 insertions(+)
 create mode 100644 tools/sbom/sbom/spdx_graph/spdx_source_graph.py
tools/sbom/sbom/spdx_graph/build_spdx_graphs.py +8 -0
index 2af0fbe6cdbe..a61257a905f3 100644
@@ -10,6 +10,7 @@ from sbom.path_utils import PathStr
 from sbom.spdx_graph.kernel_file import KernelFileCollection
 from sbom.spdx_graph.spdx_graph_model import SpdxGraph, SpdxIdGeneratorCollection
 from sbom.spdx_graph.shared_spdx_elements import SharedSpdxElements
+from sbom.spdx_graph.spdx_source_graph import SpdxSourceGraph
 from sbom.spdx_graph.spdx_output_graph import SpdxOutputGraph
 
 
@@ -54,4 +55,11 @@ def build_spdx_graphs(
         KernelSpdxDocumentKind.OUTPUT: output_graph,
     }
 
+    if len(kernel_files.source) > 0:
+        spdx_graphs[KernelSpdxDocumentKind.SOURCE] = SpdxSourceGraph.create(
+            source_files=list(kernel_files.source.values()),
+            shared_elements=shared_elements,
+            spdx_id_generators=spdx_id_generators,
+        )
+
     return spdx_graphs
tools/sbom/sbom/spdx_graph/spdx_source_graph.py new file +126 -0

126 lines not on this page · raw message

Signature · 1 line
2.34.1
#12 lore raw

PATCH v2 12/14 tools/sbom: add SPDX build graph

In reply to Luis Augenstein

Implement the SPDX build graph to describe the relationships between source files in the source SBOM and output files in the output SBOM.

---
 .../sbom/sbom/spdx_graph/build_spdx_graphs.py |  17 +
 .../sbom/sbom/spdx_graph/spdx_build_graph.py  | 317 ++++++++++++++++++
 2 files changed, 334 insertions(+)
 create mode 100644 tools/sbom/sbom/spdx_graph/spdx_build_graph.py
tools/sbom/sbom/spdx_graph/build_spdx_graphs.py +17 -0
index a61257a905f3..eecc52156449 100644
@@ -4,6 +4,7 @@
 from datetime import datetime
 from typing import Protocol
 
+import logging
 from sbom.config import KernelSpdxDocumentKind
 from sbom.cmd_graph import CmdGraph
 from sbom.path_utils import PathStr
@@ -11,6 +12,7 @@ from sbom.spdx_graph.kernel_file import KernelFileCollection
 from sbom.spdx_graph.spdx_graph_model import SpdxGraph, SpdxIdGeneratorCollection
 from sbom.spdx_graph.shared_spdx_elements import SharedSpdxElements
 from sbom.spdx_graph.spdx_source_graph import SpdxSourceGraph
+from sbom.spdx_graph.spdx_build_graph import SpdxBuildGraph
 from sbom.spdx_graph.spdx_output_graph import SpdxOutputGraph
 
 
@@ -61,5 +63,20 @@ def build_spdx_graphs(
             shared_elements=shared_elements,
             spdx_id_generators=spdx_id_generators,
         )
+    else:
+        logging.info(
+            "Skipped creating a dedicated source SBOM because source files cannot be "
+            "reliably classified when the source and object trees are identical. "
+            "Added source files to the build SBOM instead."
+        )
+
+    build_graph = SpdxBuildGraph.create(
+        cmd_graph,
+        kernel_files,
+        shared_elements,
+        output_graph.high_level_build_element,
+        spdx_id_generators,
+    )
+    spdx_graphs[KernelSpdxDocumentKind.BUILD] = build_graph
 
     return spdx_graphs
tools/sbom/sbom/spdx_graph/spdx_build_graph.py new file +317 -0

317 lines not on this page · raw message

Signature · 1 line
2.34.1
#13 lore raw

PATCH v2 13/14 tools/sbom: add unit tests for command parsers

In reply to Luis Augenstein

Add unit tests to verify that command parsers correctly extract input files from build commands.

---
 tools/sbom/tests/__init__.py                  |   0
 tools/sbom/tests/cmd_graph/__init__.py        |   0
 .../tests/cmd_graph/test_savedcmd_parser.py   | 383 ++++++++++++++++++
 3 files changed, 383 insertions(+)
 create mode 100644 tools/sbom/tests/__init__.py
 create mode 100644 tools/sbom/tests/cmd_graph/__init__.py
 create mode 100644 tools/sbom/tests/cmd_graph/test_savedcmd_parser.py
tools/sbom/tests/__init__.py new file +0 -0
new file mode 100644
index 000000000000..e69de29bb2d1
tools/sbom/tests/cmd_graph/__init__.py new file +0 -0
new file mode 100644
index 000000000000..e69de29bb2d1
tools/sbom/tests/cmd_graph/test_savedcmd_parser.py new file +383 -0

383 lines not on this page · raw message

Signature · 1 line
2.34.1
#14 lore raw

Re: [PATCH v2 13/14] tools/sbom: add unit tests for command parsers

tools/sbom/tests/cmd_graph/test_savedcmd_parser.py line 197

Quoted 5 lines · Luis Augenstein
tools/sbom/tests/cmd_graph/test_savedcmd_parser.py new file +4 -0
+    # rustc command tests
+    def test_rustc(self):
+        cmd = """OBJTREE=/workspace/linux/kernel_build rustc -Zbinary_dep_depinfo=y -Astable_features -Dnon_ascii_idents -Dunsafe_op_in_unsafe_fn -Wmissing_docs -Wrust_2018_idioms -Wclippy::all -Wclippy::as_ptr_cast_mut -Wclippy::as_underscore -Wclippy::cast_lossless -Wclippy::ignored_unit_patterns -Wclippy::mut_mut -Wclippy::needless_bitwise_bool -Aclippy::needless_lifetimes -Wclippy::no_mangle_with_rust_abi -Wclippy::ptr_as_ptr -Wclippy::ptr_cast_constness -Wclippy::ref_as_ptr -Wclippy::undocumented_unsafe_blocks -Wclippy::unnecessary_safety_comment -Wclippy::unnecessary_safety_doc -Wrustdoc::missing_crate_level_docs -Wrustdoc::unescaped_backticks -Cpanic=abort -Cembed-bitcode=n -Clto=n -Cforce-unwind-tables=n -Ccodegen-units=1 -Csymbol-mangling-version=v0 -Crelocation-model=static -Zfunction-sections=n -Wclippy::float_arithmetic --target=./scripts/target.json -Ctarget-feature=-sse,-sse2,-sse3,-ssse3,-sse4.1,-sse4.2,-avx,-avx2 -Zcf-protection=branch -Zno-jump-tables -Ctarget-cpu=x86-64 -Ztune-cpu=generic -Cno-redzone=y -Ccode-model=kernel -Zfunction-return=thunk-extern -Zpatchable-function-entry=16,16 -Copt-level=2 -Cdebug-assertions=n -Coverflow-checks=y -Dwarnings @./include/generated/rustc_cfg --edition=2021 --cfg no_fp_fmt_parse --emit=dep-info=rust/.core.o.d --emit=obj=rust/core.o --emit=metadata=rust/libcore.rmeta --crate-type rlib -L./rust --crate-name core /usr/lib/rust-1.84/lib/rustlib/src/rust/library/core/src/lib.rs --sysroot=/dev/null ;llvm-objcopy --redefine-sym __addsf3=__rust__addsf3 --redefine-sym __eqsf2=__rust__eqsf2 --redefine-sym __extendsfdf2=__rust__extendsfdf2 --redefine-sym __gesf2=__rust__gesf2 --redefine-sym __lesf2=__rust__lesf2 --redefine-sym __ltsf2=__rust__ltsf2 --redefine-sym __mulsf3=__rust__mulsf3 --redefine-sym __nesf2=__rust__nesf2 --redefine-sym __truncdfsf2=__rust__truncdfsf2 --redefine-sym __unordsf2=__rust__unordsf2 --redefine-sym __adddf3=__rust__adddf3 --redefine-sym __eqdf2=__rust__eqdf2 --redefine-sym __ledf2=__rust__ledf2 --redefine-sym __ltdf2=__rust__ltdf2 --redefine-sym __muldf3=__rust__muldf3 --redefine-sym __unorddf2=__rust__unorddf2 --redefine-sym __muloti4=__rust__muloti4 --redefine-sym __multi3=__rust__multi3 --redefine-sym __udivmodti4=__rust__udivmodti4 --redefine-sym __udivti3=__rust__udivti3 --redefine-sym __umodti3=__rust__umodti3 rust/core.o"""
+        expected = "/usr/lib/rust-1.84/lib/rustlib/src/rust/library/core/src/lib.rs rust/core.o"

Hmm... Is this supposed to have two files in expected?

I mean, core.o is really the output of the rule, even if it gets modified in-place in the middle.

Cheers,
Miguel

#15 lore raw

Re: [PATCH v2 13/14] tools/sbom: add unit tests for command parsers

Quoted 4 lines

Hmm... Is this supposed to have two files in expected?

I mean, core.o is really the output of the rule, even if it gets modified in-place in the middle.

Hi Miguel,

thank you for the review.

I believe the test is correct under the current design. The test case consists of two commands:

1. A rustc invocation, with lib.rs as the input and rust/core.o as the output.
2. An llvm-objcopy invocation, where rust/core.o is used as both the input and the output.

The parse_inputs_from_commands function is designed to return all inputs it encounters across all provided commands. The motivation behind this is to allow isolated parser functions that operate independently of which other commands occur before or after.
Take for example the commands
objcopy [...] vmlinux.unstripped vmlinux and
objcopy [...] rust/core.o. Both should be handled by the same objcopy parser logic, which should return vmlinux.unstripped and rust/core.o as inputs, respectively.

That said, you are absolutely right that the final graph node for rust/core.o should only depend on lib.rs, and not on itself, as that would introduce a cyclical dependency. The current implementation accounts for this case in cmd_file.py:121, where such self-dependencies are explicitly filtered out:

Quoted 2 lines

if input_file == target_path:
# Skip target file to prevent cycles. This is necessary because

some multi stage commands first create an output and then pass it as input to the next command, e.g., objcopy.

Quoted 1 line

continue

An alternative approach would be to have each parser function suppress returning inputs when the input and output files are identical, but I think that would be more complex in the end.

Best,
Luis

Signature · 5 lines
Luis Augenstein * [email protected] * +49-152-25275761
TNG Technology Consulting GmbH, Beta-Str. 13, 85774 Unterföhring
Geschäftsführer: Henrik Klagges, Dr. Robert Dahlke, Thomas Endres
Aufsichtsratsvorsitzender: Christoph Stock
Sitz: Unterföhring * Amtsgericht München * HRB 135082
#16 lore raw

PATCH v2 14/14 tools/sbom: add unit tests for SPDX-License-Identifier parsing

In reply to Luis Augenstein

Verify that SPDX-License-Identifier headers at the top of source files are parsed correctly.

---
 tools/sbom/tests/spdx_graph/__init__.py       |  0
 .../sbom/tests/spdx_graph/test_kernel_file.py | 32 +++++++++++++++++++
 2 files changed, 32 insertions(+)
 create mode 100644 tools/sbom/tests/spdx_graph/__init__.py
 create mode 100644 tools/sbom/tests/spdx_graph/test_kernel_file.py
tools/sbom/tests/spdx_graph/__init__.py new file +0 -0
new file mode 100644
index 000000000000..e69de29bb2d1
tools/sbom/tests/spdx_graph/test_kernel_file.py new file +32 -0
new file mode 100644
index 000000000000..bc44e7a97d2a
@@ -0,0 +1,32 @@
+# SPDX-License-Identifier: GPL-2.0-only OR MIT
+# Copyright (C) 2025 TNG Technology Consulting GmbH
+
+import unittest
+from pathlib import Path
+import tempfile
+from sbom.spdx_graph.kernel_file import _parse_spdx_license_identifier  # type: ignore
+
+
+class TestKernelFile(unittest.TestCase):
+    def setUp(self):
+        self.tmpdir = tempfile.TemporaryDirectory()
+        self.src_tree = Path(self.tmpdir.name)
+
+    def tearDown(self):
+        self.tmpdir.cleanup()
+
+    def test_parse_spdx_license_identifier(self):
+        # REUSE-IgnoreStart
+        test_cases: list[tuple[str, str | None]] = [
+            ("/* SPDX-License-Identifier: MIT*/", "MIT"),
+            ("// SPDX-License-Identifier: GPL-2.0-only", "GPL-2.0-only"),
+            ("/* SPDX-License-Identifier: GPL-2.0-or-later OR MIT */", "GPL-2.0-or-later OR MIT"),
+            ("/* SPDX-License-Identifier: Apache-2.0 */\n extra text", "Apache-2.0"),
+            ("int main() { return 0; }", None),
+        ]
+        # REUSE-IgnoreEnd
+
+        for i, (file_content, expected_identifier) in enumerate(test_cases):
+            file_path = self.src_tree / f"file_{i}.c"
+            file_path.write_text(file_content)
+            self.assertEqual(_parse_spdx_license_identifier(str(file_path)), expected_identifier)
Signature · 1 line
2.34.1
#17 lore raw
In reply to Luis Augenstein
Quoted 31 lines · Luis Augenstein

This patch series introduces a Python-based tool for generating SBOM documents in the SPDX 3.0.1 format for kernel builds.

A Software Bill of Materials (SBOM) describes the individual components of a software product. For the kernel, the goal is to describe the distributable build outputs (typically the kernel image and modules), the source files involved in producing these outputs, and the build process that connects the source and output files.

To achieve this, the SBOM tool generates three SPDX documents:

- sbom-output.spdx.json
Describes the final build outputs together with high-level build metadata.

- sbom-source.spdx.json
Describes all source files involved in the build, including licensing information and additional file metadata.

- sbom-build.spdx.json
Describes the entire build process, linking source files from the source SBOM to output files in the output SBOM.

The sbom tool is optional and runs only when CONFIG_SBOM is enabled. It is invoked after the build, once all output artifacts have been generated. Starting from the kernel image and modules as root nodes, the tool reconstructs the dependency graph up to the original source files. Build dependencies are primarily derived from the .cmd files generated by Kbuild, which record the full command used to build each output file.

Quoted 8 lines

Currently, the tool only supports x86 and arm64 architectures.

---
Changes in v2:
- regenerate sbom documents when build configuration changes

I'm still getting:

make[3]: Nothing to be done for 'sbom'.

When rebuilding the kernel and nothing needs to be done for the sbom. That message should not be there, right?

thanks,

greg k-h

#18 lore raw
Quoted 6 lines

I'm still getting:

make[3]: Nothing to be done for 'sbom'.

When rebuilding the kernel and nothing needs to be done for the sbom. That message should not be there, right?

Ah, you mean the message should always be suppressed. Sorry, I thought your concern was just that this message appeared when the SBOM should have been regenerated.
With the changes in v2, the SBOM should now regenerate correctly whenever the build configuration changes.
I will include the additional suppression of the make message in the next version.

Best,
Luis

Signature · 5 lines
Luis Augenstein * [email protected] * +49-152-25275761
TNG Technology Consulting GmbH, Beta-Str. 13, 85774 Unterföhring
Geschäftsführer: Henrik Klagges, Dr. Robert Dahlke, Thomas Endres
Aufsichtsratsvorsitzender: Christoph Stock
Sitz: Unterföhring * Amtsgericht München * HRB 135082
#19 lore raw
In reply to Luis Augenstein
Quoted 10 lines · Luis Augenstein

The sbom tool is optional and runs only when CONFIG_SBOM is enabled. It is invoked after the build, once all output artifacts have been generated. Starting from the kernel image and modules as root nodes, the tool reconstructs the dependency graph up to the original source files. Build dependencies are primarily derived from the .cmd files generated by Kbuild, which record the full command used to build each output file.

Currently, the tool only supports x86 and arm64 architectures.

I am out of the loop, and I don't know the requirements here, but what kind of approaches were considered for this?

Parsing the .cmds seems a bit ad-hoc / after-the-fact approach, and from a very cursory look at the patches, it seems to require a fair amount of hardcoding, e.g. it seems we may need to list every generator tool in SINGLE_COMMAND_PARSERS?

Now, if this is meant to be best-effort and cover the most important parts, it may be fine -- again, I don't know the requirements here. But if it is meant to accurately match everything, then it will require keeping those lists in sync with Kbuild, right?

Hmm... I feel like changing the build system itself (whether at the Kbuild level or even a customized Make itself if needed) to record this information would be conceptually simpler / more elegant, even if changing Kbuild itself can sometimes be quite a challenge.

In addition, why does this need to be a CONFIG_ option? Should this be a separate tool or at most a target that supports whatever config happens to be, rather than part of the config itself?

Thanks!

Cheers,
Miguel

#20 lore raw
Quoted 11 lines · Miguel Ojeda
Quoted 9 lines · Luis Augenstein

The sbom tool is optional and runs only when CONFIG_SBOM is enabled. It is invoked after the build, once all output artifacts have been generated. Starting from the kernel image and modules as root nodes, the tool reconstructs the dependency graph up to the original source files. Build dependencies are primarily derived from the .cmd files generated by Kbuild, which record the full command used to build each output file.

Quoted 4 lines
Quoted 1 line

Currently, the tool only supports x86 and arm64 architectures.

I am out of the loop, and I don't know the requirements here, but what kind of approaches were considered for this?

Lots of different attempts, usually using bpf and other run-time tracing tools. But it was determined that we already have this info in our build dependancy files, so parsing them was picked.

Quoted 4 lines

Parsing the .cmds seems a bit ad-hoc / after-the-fact approach, and from a very cursory look at the patches, it seems to require a fair amount of hardcoding, e.g. it seems we may need to list every generator tool in SINGLE_COMMAND_PARSERS?

If you know of a better way, that would be great!

Quoted 4 lines

Now, if this is meant to be best-effort and cover the most important parts, it may be fine -- again, I don't know the requirements here. But if it is meant to accurately match everything, then it will require keeping those lists in sync with Kbuild, right?

It should match everything, and yes, it will require keeping things in sync.

Quoted 4 lines

Hmm... I feel like changing the build system itself (whether at the Kbuild level or even a customized Make itself if needed) to record this information would be conceptually simpler / more elegant, even if changing Kbuild itself can sometimes be quite a challenge.

Changing kbuild would be great too, if you know of a way we can get that info out of it.

Quoted 3 lines

In addition, why does this need to be a CONFIG_ option? Should this be a separate tool or at most a target that supports whatever config happens to be, rather than part of the config itself?

It should be part of the kernel build process, and generated as part of it as it will want to go into some packages directly. Having to run the build "again" is probably not a good idea (i.e. do you want to modify all the distro rpm scripts?)

thanks,

greg k-h

#21 lore raw
Quoted 6 lines · Greg KH

Lots of different attempts, usually using bpf and other run-time tracing tools. But it was determined that we already have this info in our build dependancy files, so parsing them was picked.

If you know of a better way, that would be great!

Yes, if I understand correctly, then this should be done on the build system side (i.e. I don't see how BPF/tracing could achieve this, so maybe I am missing something), but what I meant is that there are several ways to do this in the build system side.

One is this kind of post-processing after the build, which is easier in that it avoids touching Kbuild and can be written in something like Python, which always helps. The downside (my worry) is that it introduces yet another layer to Kbuild.

My first instinct would have been to try to see if the build system itself could already give us what is built while it gets built (i.e. just like it outputs the cmd files). So I wondered if that was considered.

Quoted 2 lines

Changing kbuild would be great too, if you know of a way we can get that info out of it.

It depends on what is needed, but Kbuild of course knows about input and output files and dependencies, so I was thinking of outputting that information in an easier format instead of having to parse command lines from the cmd files.

Quoted 4 lines

It should be part of the kernel build process, and generated as part of it as it will want to go into some packages directly. Having to run the build "again" is probably not a good idea (i.e. do you want to modify all the distro rpm scripts?)

Even with CONFIG_SBOM, they will need to modify at least their kernel configuration, and perhaps more if they want to save the SBOM files differently, e.g. in another package etc. So I am not sure if it is a big difference for any distro than adding a word to their make line.

Now, I understand it may be easier to tell users to "just turn one more config", and perhaps it looks more "integrated" to them, but I mainly asked because, to me, the SBOM is orthogonal to the kernel configuration.

In other words, I would have expected to be able to get an SBOM for any build, without having to modify the kernel configuration at all. After all, the kernel image should not change at all whether there is an SBOM or not. We also do not do that for some other big "globally orthogonal" things that involve generating extra files, like documentation.

I hope that helps somehow...

Cheers,
Miguel

#22 lore raw
Quoted 3 lines · Miguel Ojeda

After all, the kernel image should not change at all whether there is an SBOM or not.

Well, I guess the SBOM could be saved into the kernel itself (and perhaps retrieved in different ways, e.g. at runtime), in which case, then an option definitely makes sense.

Cheers,
Miguel

#23 lore raw
Quoted 9 lines · Miguel Ojeda
Quoted 3 lines · Miguel Ojeda

After all, the kernel image should not change at all whether there is an SBOM or not.

Well, I guess the SBOM could be saved into the kernel itself (and perhaps retrieved in different ways, e.g. at runtime), in which case, then an option definitely makes sense.

Ick, let's not dump the HUGE sbom json file inside the binary kernel image itself, unless you want to do something like /proc/sbom.gz?

That would be funny, but a big waste of memory :)

greg k-h

#24 lore raw
In reply to Miguel Ojeda
Quoted 6 lines · Miguel Ojeda
Quoted 5 lines · Greg KH

Lots of different attempts, usually using bpf and other run-time tracing tools. But it was determined that we already have this info in our build dependancy files, so parsing them was picked.

Quoted 6 lines
Quoted 1 line

If you know of a better way, that would be great!

Yes, if I understand correctly, then this should be done on the build system side (i.e. I don't see how BPF/tracing could achieve this, so maybe I am missing something), but what I meant is that there are several ways to do this in the build system side.

for a horrible hack of an example of how you can do this using bpf/tracing, see this "fun" thing that I use every so often:
https://github.com/gregkh/gregkh-linux/blob/master/scripts/trace_kernel_build.sh
it uses bpftrace to inject a script and then do a build and then post-process the output. Not something you should ever do on a "real" build system :)

Quoted 4 lines

One is this kind of post-processing after the build, which is easier in that it avoids touching Kbuild and can be written in something like Python, which always helps. The downside (my worry) is that it introduces yet another layer to Kbuild.

That's what is happening here, it's post-processing the build files to detetct the dependancy graph it already knows about.

Quoted 4 lines

My first instinct would have been to try to see if the build system itself could already give us what is built while it gets built (i.e. just like it outputs the cmd files). So I wondered if that was considered.

cmake can do this, that's what Zephyr uses, but we don't use cmake for kernel builds. I know the gnu toolchain developers have talked about adding this to make/gcc/whatever in the past, and I thought Red Hat was funding them to do that, but it seems to have never gone anywhere and it's been years since I last heard from them.

Quoted 7 lines
Quoted 2 lines

Changing kbuild would be great too, if you know of a way we can get that info out of it.

It depends on what is needed, but Kbuild of course knows about input and output files and dependencies, so I was thinking of outputting that information in an easier format instead of having to parse command lines from the cmd files.

"all" we need is the list of files that are used to make the resulting kernel image and modules. Given that the kernel build is self-contained, and does not pull in anything from outside of its tree (well, with the exception of some rust things I think), we should be ok.

And kbuild already encodes this information in the cmd files, for the most part (there are corner cases and exceptions which the developers here have gone through great lengths to track down and document in the scripts.) So 99% of the info is there already, which is why the cmd files are used for parsing, no need to re-create that info in yet-another-format, right?

Quoted 10 lines
Quoted 4 lines

It should be part of the kernel build process, and generated as part of it as it will want to go into some packages directly. Having to run the build "again" is probably not a good idea (i.e. do you want to modify all the distro rpm scripts?)

Even with CONFIG_SBOM, they will need to modify at least their kernel configuration, and perhaps more if they want to save the SBOM files differently, e.g. in another package etc. So I am not sure if it is a big difference for any distro than adding a word to their make line.

Let's stick with a config option for now please. If the distros who will need/want this decide to do it in a different way, they can send patches :)

For now, this should be sufficient.

Quoted 4 lines

Now, I understand it may be easier to tell users to "just turn one more config", and perhaps it looks more "integrated" to them, but I mainly asked because, to me, the SBOM is orthogonal to the kernel configuration.

It's a build-time output, just like debugging symbols are, and documentation. Ok, documentation is a separate build target, and "to the side" of the source build, but you get the idea :)

Quoted 6 lines

In other words, I would have expected to be able to get an SBOM for any build, without having to modify the kernel configuration at all. After all, the kernel image should not change at all whether there is an SBOM or not. We also do not do that for some other big "globally orthogonal" things that involve generating extra files, like documentation.

The SBOM is directly tied to the kernel configuration in that it needs to know the config in order to determine exactly what files were used to generate the resulting binaries. That's what the SBOM is documenting, not "all of the files in the tarball", but just "these are the files that are required to build the binaries". Which is a tiny subset of the overall files in the tree, and is really, all that the target system cares about.

thanks,

greg k-h

#25 lore raw
Quoted 7 lines · Greg KH

for a horrible hack of an example of how you can do this using bpf/tracing, see this "fun" thing that I use every so often:
https://github.com/gregkh/gregkh-linux/blob/master/scripts/trace_kernel_build.sh
it uses bpftrace to inject a script and then do a build and then post-process the output. Not something you should ever do on a "real" build system :)

Oof... So you really meant tracing the builder. :)

Quoted 2 lines

That's what is happening here, it's post-processing the build files to detetct the dependancy graph it already knows about.

Yeah, I am aware -- I mentioned both sides to explain the upsides and my worry about hardcoding all this stuff out of band.

Quoted 5 lines

cmake can do this, that's what Zephyr uses, but we don't use cmake for kernel builds. I know the gnu toolchain developers have talked about adding this to make/gcc/whatever in the past, and I thought Red Hat was funding them to do that, but it seems to have never gone anywhere and it's been years since I last heard from them.

Well, Make can ""do"" things like that, in the sense that we can program it, which is essentially what Kbuild does -- it "hacks" the usual Make graph to do extra stuff on top.

i.e. Kbuild and friends are the ones writing the .cmd files and running custom filtering and so on, not Make, and just like we abuse Make to do that, in principle we could encode and output more information (if that would help).

To be clear, I am not sure exactly what information it is needed -- when I was Cc'd for the Rust bit, I noticed it was parsing the command line to try to guess more deps (?), which seemed odd and I wondered whether we could provide that (even if it requires additions) so that we don't need to parse those.

Quoted 4 lines

And kbuild already encodes this information in the cmd files, for the most part (there are corner cases and exceptions which the developers here have gone through great lengths to track down and document in the scripts.)

By "corner cases and exceptions", I assume you mean the hardcoded ones (not the command line parsing), which I hadn't noticed yet.

Those aren't really documented from what I can see? It is just the list of cases, which we will also have to maintain.

I also see the .incbin now, which is even more hardcoding, but I see Makefiles explicitly adding the dependency on their side, which is closer to what I am saying: that it would be better to add the dependencies (or whatever information is needed) in the build system side.

In other words, we could make those generate a .cmd file or similar, rather than hardcode it on the script.

I guess my question to Luis et al. is: for things like .incbin and the hardcoded dependencies, is there a reason to avoid declaring any missing dependencies or to generate the .cmd files to begin with?

The patches say, for instance:

Some files in the kernel build process are not tracked by the .cmd
dependency mechanism.
Parsing these dependencies programmatically is too complex for the
scope of this project.
Therefore, this function provides manually defined dependencies to
be added to the build graph.

And my point is precisely that we should not be parsing Makefiles, but neither command lines, if at all possible. Instead, if there are missing dependencies, we should fix them; and if there are missing .cmds (i.e. dependency information not saved) you need, we could add those, and so on.

Quoted 3 lines

So 99% of the info is there already, which is why the cmd files are used for parsing, no need to re-create that info in yet-another-format, right?

Yeah, the extra information may be just in deps_ in the .cmd, or it could be an extra variable there or whatever is needed, i.e. no need for a new format.

i.e. what I was trying to avoid was the out-of-band hardcoding as much as possible.

Quoted 3 lines

Let's stick with a config option for now please. If the distros who will need/want this decide to do it in a different way, they can send patches :)

In case it wasn't clear: for the config bit, it wouldn't be a big change -- it would just require removing ~10 lines unless I am missing something.

But if this was already discussed with users or you think it will be easier etc., then fine, I won't press. :)

Quoted 3 lines

It's a build-time output, just like debugging symbols are, and documentation. Ok, documentation is a separate build target, and "to the side" of the source build, but you get the idea :)

Just in case: debugging symbols are different -- they change the actual build (e.g. flags), and even the actual image (unless requested to be separate). So those make sense as a config option.

(We also have other targets that work like docs, i.e. it is not just docs. But fine... :)

Quoted 7 lines

The SBOM is directly tied to the kernel configuration in that it needs to know the config in order to determine exactly what files were used to generate the resulting binaries. That's what the SBOM is documenting, not "all of the files in the tarball", but just "these are the files that are required to build the binaries". Which is a tiny subset of the overall files in the tree, and is really, all that the target system cares about.

To clarify, I didn't suggest we document the files in the tarball, nor that the kernel config doesn't influence the SBOM contents.

What I am saying is that whether an SBOM is generated or not is orthogonal to the kernel configuration, and as a user I would have expected to be able to obtain one in my build without having to change any configuration.

I hope that helps.

Cheers,
Miguel

#26 lore raw
Quoted 10 lines
Quoted 3 lines

Let's stick with a config option for now please. If the distros who will need/want this decide to do it in a different way, they can send patches :)

In case it wasn't clear: for the config bit, it wouldn't be a big change -- it would just require removing ~10 lines unless I am missing something.

But if this was already discussed with users or you think it will be easier etc., then fine, I won't press. :)

Thanks for this suggestion.
I explored this approach in v3 where I removed the CONFIG_SBOM option and instead introduced the make sbom target to invoke the sbom tool. This way the default all target is not changed at all. The sbom target depends on all such that make sbom can be used to build the kernel if not present and generate the SBOM afterwards. The environment variables picked up by the SBOM remain the same as in v2. I like that this solves the need to find a good place for a CONFIG_SBOM option since the previous location in lib/Kconfig.debug was not optimal. Let me know what you think.

Quoted 9 lines

To be clear, I am not sure exactly what information it is needed -- when I was Cc'd for the Rust bit, I noticed it was parsing the command line to try to guess more deps (?), which seemed odd and I wondered whether we could provide that (even if it requires additions) so that we don't need to parse those.
[...]
In other words, we could make those generate a .cmd file or similar, rather than hardcode it on the script.

Quoted 3 lines

I guess my question to Luis et al. is: for things like .incbin and the hardcoded dependencies, is there a reason to avoid declaring any missing dependencies or to generate the .cmd files to begin with?

I agree that it would likely be a cleaner solution if the .cmd files directly contained all dependencies. Ideally, the SBOM tool would only need to consume dependency information from the existing .cmd files, without parsing build commands or collecting additional dependencies that are not tracked by the .cmd mechanism.

However, as mentioned previously, adapting the .cmd file generation was considered out of scope for this project. Early on, we decided to focus on an isolated tool that works with the information currently available to keep the scope manageable. Improving dependency coverage at the Kbuild level would certainly be a worthwhile follow-up, but it was not something we could realistically address within this effort.

Best,
Luis

Signature · 5 lines
Luis Augenstein * [email protected] * +49-152-25275761
TNG Technology Consulting GmbH, Beta-Str. 13, 85774 Unterföhring
Geschäftsführer: Henrik Klagges, Dr. Robert Dahlke, Thomas Endres
Aufsichtsratsvorsitzender: Christoph Stock
Sitz: Unterföhring * Amtsgericht München * HRB 135082
#27 lore raw

Hi Luis, Greg, and Miguel,

Sorry for not having any input up until this point, as I felt this was not going to be ready for 6.20/7.0 and I wanted to focus on getting things ready for that release (on top of other work). Some high level comments based on what has been discussed so far to follow, it was going to be hard to reply inline to everything. I will try to take a closer look at v3 in the next couple of weeks but I might not get to it until after the merge window closes.

I agree with Miguel that if there is any information that we can add to the .cmd files or another file generated by Kbuild to avoid hard coding things while preprocessing, it should be pursued, as we should be making the build system work for us. We have already some prior art with post processing Kbuild files like scripts/clang-tools/gen_compile_commands.py so I am not too worried about that. At the same time, I do like how self contained the implementation currently is, as it is just there available for people to use if they want it but it impacts nothing if it is not being used. It also makes it an easier maintenance burden in the immediate term, as I would like this to be shown as useful to various entities before it starts to entangle itself into the build system.

I think getting rid of CONFIG_SBOM in favor of just an sbom make target is a good direction. If we really wanted some sort of configuration option, I think it should only mean "generate an SBOM by default" and nothing more but I worry about this getting turned on via compile testing and causing issues. At that point, it feels like whatever entity wants this information can just add 'make sbom' to their build system since they may have to control the outputs beyond the simple "all" make target.

I wonder if it would be better for this to live within scripts/ instead of tools/, as that should allow it to be integrated into the build process a little bit more naturally, such as using $(Q) instead of @, $(PYTHON3) instead of the bare python3, being able to access CONFIG_MODULES directly, and cleaning up the actual implementation of the sbom target in Makefile.

Cheers,
Nathan

#28 lore raw

Hi Nathan,

Quoted 6 lines

I wonder if it would be better for this to live within scripts/ instead of tools/, as that should allow it to be integrated into the build process a little bit more naturally, such as using $(Q) instead of @, $(PYTHON3) instead of the bare python3, being able to access CONFIG_MODULES directly, and cleaning up the actual implementation of the sbom target in Makefile.

Thanks, I wasn’t aware that targets under scripts/ have access to more Make variables by default. During development, we didn’t have strong reasons for choosing either tools/ or scripts/. I’m happy to move it to scripts/ if that is the preferred location.

Regarding $(Q) and $(PYTHON3), I noticed that these variables are actually available within the tools/ directory as well, so we could switch to using them even if we stay under tools/.

CONFIG_MODULES and src_tree, on the other hand, need to be passed explicitly when staying in tools/, whereas they would be available by default under scripts/ in which case we could simply invoke the script via:

```Makefile
PHONY += sbom
sbom: all
	$(Q)$(MAKE) $(build)=scripts/sbom
```

So yes, I think it makes sense to move it to scripts then.

Best,
Luis

Signature · 5 lines
Luis Augenstein * [email protected] * +49-152-25275761
TNG Technology Consulting GmbH, Beta-Str. 13, 85774 Unterföhring
Geschäftsführer: Henrik Klagges, Dr. Robert Dahlke, Thomas Endres
Aufsichtsratsvorsitzender: Christoph Stock
Sitz: Unterföhring * Amtsgericht München * HRB 135082
#29 lore raw

Hi Luis,

Quoted 9 lines · Luis Augenstein
Quoted 6 lines

I wonder if it would be better for this to live within scripts/ instead of tools/, as that should allow it to be integrated into the build process a little bit more naturally, such as using $(Q) instead of @, $(PYTHON3) instead of the bare python3, being able to access CONFIG_MODULES directly, and cleaning up the actual implementation of the sbom target in Makefile.

Thanks, I wasn’t aware that targets under scripts/ have access to more Make variables by default. During development, we didn’t have strong

I think this is a byproduct of being fully within Kbuild at that point, rather than in the tools/ build system.

Quoted 2 lines

reasons for choosing either tools/ or scripts/. I’m happy to move it to scripts/ if that is the preferred location.

Yes please. If this tool is designed to run within and parse Kbuild, it should live fully within Kbuild, as the "tools build system" comment in Makefile added by Masahiro in commit 6e6ef2da3a28 ("Makefile: add comment to discourage tools/* addition for kernel builds") notes (even though this is not a C program so the hostprogs comment is irrelevant here). scripts/sbom seems entirely reasonable to me.

Quoted 3 lines

Regarding $(Q) and $(PYTHON3), I noticed that these variables are actually available within the tools/ directory as well, so we could switch to using them even if we stay under tools/.

Ah, good to know. I do not delve into the tools build system all too much.

Quoted 10 lines

CONFIG_MODULES and src_tree, on the other hand, need to be passed explicitly when staying in tools/, whereas they would be available by default under scripts/ in which case we could simply invoke the script via:

```Makefile
PHONY += sbom
sbom: all
	$(Q)$(MAKE) $(build)=scripts/sbom
```

So yes, I think it makes sense to move it to scripts then.

Yeah, that looks much cleaner to me. I suspect scripts/sbom/Makefile could be cleaned up a little bit as a result of that move as well.

Also, two other comments I forgot to bring up:

1. With the movement out of tools/, I think the README should become a proper Documentation file so that its contents is more discoverable. That should probably be separate from the change that adds the initial SBOM scaffolding in Kbuild to help with review.

2. This depends on having a clean initial build tree (either empty directory or 'clean' as a make target) due to needing to parse the .cmd files, which could be stale if someone builds a kernel, changes their config, and rebuilds, right? This should be documented since I do not think it is possible to do something like what Masahiro did in commit 3d32285fa995 ("kbuild: wire up the build rule of compile_commands.json to Makefile") because of the drawback that it misses too many things.

Cheers,
Nathan

#30 lore raw

Hi Nathan,

Quoted 8 lines

2. This depends on having a clean initial build tree (either empty directory or 'clean' as a make target) due to needing to parse the .cmd files, which could be stale if someone builds a kernel, changes their config, and rebuilds, right? This should be documented since I do not think it is possible to do something like what Masahiro did in commit 3d32285fa995 ("kbuild: wire up the build rule of compile_commands.json to Makefile") because of the drawback that it misses too many things.

There might be edge cases, but in general stale .cmd files should not be an issue.

The script does not scan the build tree for .cmd files. It starts from a set of root build artifacts (kernel image and .ko modules listed in modules.order). From these roots, it parses the corresponding .cmd files to discover the immediate dependencies, and then recursively processes the .cmd files of those dependencies, effectively walking the entire dependency graph up to the individual source files.

Stale .cmd files should not be referenced as dependencies by the root artifacts and therefore not be part of the resulting dependency graph.

Best,
Luis

Signature · 5 lines
Luis Augenstein * [email protected] * +49-152-25275761
TNG Technology Consulting GmbH, Beta-Str. 13, 85774 Unterföhring
Geschäftsführer: Henrik Klagges, Dr. Robert Dahlke, Thomas Endres
Aufsichtsratsvorsitzender: Christoph Stock
Sitz: Unterföhring * Amtsgericht München * HRB 135082
#31 lore raw
Quoted 21 lines · Luis Augenstein

Hi Nathan,

Quoted 8 lines

2. This depends on having a clean initial build tree (either empty directory or 'clean' as a make target) due to needing to parse the .cmd files, which could be stale if someone builds a kernel, changes their config, and rebuilds, right? This should be documented since I do not think it is possible to do something like what Masahiro did in commit 3d32285fa995 ("kbuild: wire up the build rule of compile_commands.json to Makefile") because of the drawback that it misses too many things.

There might be edge cases, but in general stale .cmd files should not be an issue.

The script does not scan the build tree for .cmd files. It starts from a set of root build artifacts (kernel image and .ko modules listed in modules.order). From these roots, it parses the corresponding .cmd files to discover the immediate dependencies, and then recursively processes the .cmd files of those dependencies, effectively walking the entire dependency graph up to the individual source files.

Quoted 2 lines

Stale .cmd files should not be referenced as dependencies by the root artifacts and therefore not be part of the resulting dependency graph.

Ah okay, thanks for the explanation! I have not had a chance to review the actual Python implementation yet. It sounds very similar to the approach taken by Masahiro for compile_commands.json but by looking at the .cmd files recursively from the root artifacts.

Cheers,
Nathan

#32 lore raw
In reply to Miguel Ojeda
Quoted 3 lines

it seems to require a fair amount of hardcoding, e.g. it seems we may need to list every generator tool in SINGLE_COMMAND_PARSERS?

Yes. Optimally, the cmd files would contain the full list of input files, such that parsing the commands would no longer be necessary. However, that was considered out of scope for this project.

Quoted 2 lines

But if it is meant to accurately match everything, then it will require keeping those lists in sync with Kbuild, right?

Yes. The goal should be to keep the parser functions complete, that is, to add new ones as soon as unsupported commands are discovered. It is quite likely that the current list of parser functions is not complete. When unsupported commands are encountered, KernelSbom is still able to generate the SBOM as much as possible, as explained in the last section of the README.

Quoted 13 lines

Unknown Build Commands
----------------------

Because the kernel supports a wide range of configurations and versions, KernelSbom may encounter build commands in .cmd files that it does not yet support. By default, KernelSbom will fail if an unknown build command is encountered.

If you still wish to generate SPDX documents despite unsupported commands, you can use the --do-not-fail-on-unknown-build-command option. KernelSbom will continue and produce the documents, although the resulting SBOM will be incomplete.

Quoted 8 lines

This option should only be used when the missing portion of the dependency graph is small and an incomplete SBOM is acceptable for your use case.

In addition, why does this need to be a CONFIG_ option? Should this be a separate tool or at most a target that supports whatever config happens to be, rather than part of the config itself?

The main reason to run the SBOM tool within the main make process is to gain direct access to the make/environment variables used during the build. The KERNEL_BUILD_VARIABLES_ALLOWLIST defines which environment variables should be included in the SBOM if they are available. When the tool is run outside of the main build, this information is no longer accessible.
We are looking for a better place for the CONFIG_SBOM option though, as lib/Kconfig.debug may not be the most appropriate place?

Best,
Luis

Signature · 5 lines
Luis Augenstein * [email protected] * +49-152-25275761
TNG Technology Consulting GmbH, Beta-Str. 13, 85774 Unterföhring
Geschäftsführer: Henrik Klagges, Dr. Robert Dahlke, Thomas Endres
Aufsichtsratsvorsitzender: Christoph Stock
Sitz: Unterföhring * Amtsgericht München * HRB 135082
#33 lore raw
Quoted 7 lines · Luis Augenstein

The main reason to run the SBOM tool within the main make process is to gain direct access to the make/environment variables used during the build. The KERNEL_BUILD_VARIABLES_ALLOWLIST defines which environment variables should be included in the SBOM if they are available. When the tool is run outside of the main build, this information is no longer accessible.

I was not suggesting to take it out of make completely if the environment is needed, but rather have the user call the target (which could still depend on the kernel build like you have it now).

For instance, for generating the rust-analyzer configuration, we want to have the environment too, so we have a Make target that users call when they need it, rather than making it a configuration of the kernel.

Now, I can understand there may be other reasons (please see my reply to Greg).

Thanks!

Cheers,
Miguel

#34 lore raw
Quoted 3 lines

I was not suggesting to take it out of make completely if the environment is needed, but rather have the user call the target (which could still depend on the kernel build like you have it now).

Thanks for clarifying.
I will try that.

Best,
Luis

Signature · 5 lines
Luis Augenstein * [email protected] * +49-152-25275761
TNG Technology Consulting GmbH, Beta-Str. 13, 85774 Unterföhring
Geschäftsführer: Henrik Klagges, Dr. Robert Dahlke, Thomas Endres
Aufsichtsratsvorsitzender: Christoph Stock
Sitz: Unterföhring * Amtsgericht München * HRB 135082