Skip to contentSkip to conversation

Add SPDX SBOM generation tool

PATCH Superseded Luis Augenstein 2 participants 19 messages Jan 19 – Jan 20

Subsystems (2)

v1 of 7 Superseded Latest is v7 →

lore
Share & tools
lore
#0 lore raw

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.

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                                      |   8 +-
 lib/Kconfig.debug                             |   9 +
 tools/Makefile                                |   3 +-
 tools/sbom/Makefile                           |  39 +
 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, 4086 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 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            |   8 +-
 lib/Kconfig.debug   |   9 ++
 tools/Makefile      |   3 +-
 tools/sbom/Makefile |  32 +++++++
 tools/sbom/README   | 208 ++++++++++++++++++++++++++++++++++++++++++++
 tools/sbom/sbom.py  |  16 ++++
 8 files changed, 281 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 3a7241c94..f3372f15e 100644
@@ -48,6 +48,7 @@
 *.s
 *.so
 *.so.dbg
+*.spdx.json
 *.su
 *.symtypes
 *.tab.[ch]
MAINTAINERS +6 -0
index f1b020588..03d7d93d8 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 +7 -1
index 9d3812526..22bfe5cea 100644
@@ -1457,6 +1457,12 @@ prepare: tools/bpf/resolve_btfids
 endif
 endif
 
+ifdef CONFIG_SBOM
+all: tools/sbom
+tools/sbom: $(notdir $(KBUILD_IMAGE)) modules
+	$(Q)$(MAKE) O=$(abspath $(objtree)) subdir=tools -C $(srctree)/tools/ sbom
+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 +1618,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 ba36939fd..9d03ef854 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 cb40961a7..7b4b1c96d 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 +32 -0
new file mode 100644
index 000000000..5b80b455c
@@ -0,0 +1,32 @@
+# SPDX-License-Identifier: GPL-2.0-only OR MIT
+# Copyright (C) 2025 TNG Technology Consulting GmbH
+
+srctree := $(abspath ../../..)
+
+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_SOURCE_FILE) $(SBOM_BUILD_FILE) $(SBOM_OUTPUT_FILE)
+else
+    SBOM_TARGETS := $(SBOM_BUILD_FILE) $(SBOM_OUTPUT_FILE)
+endif
+
+sbom: $(SBOM_TARGETS)
+
+$(SBOM_TARGETS) &:
+	@echo "  GEN     $(notdir $(SBOM_TARGETS))"
+
+	@printf "%s\n" "$(KBUILD_IMAGE)" > $(SBOM_ROOTS_FILE)
+	@if [ -f $(objtree)/modules.order ]; 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 000000000..9c2e4c7f1
@@ -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 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 9c2e4c7f1..c7f23d6eb 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 000000000..e69de29bb
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 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 000000000..d72f781b4
@@ -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 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 5b80b455c..052858556 100644
@@ -25,7 +25,11 @@ $(SBOM_TARGETS) &:
 		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 c7f23d6eb..25d912a28 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 000000000..9d661a5c3
@@ -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 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 fdaed0f0c..feacdbf76 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 000000000..b3fb2f0ba
@@ -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 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 000000000..4097b59f8
@@ -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 000000000..180a8f1e8
@@ -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 000000000..750ddd24a
@@ -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 000000000..589e85c5f
@@ -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 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 052858556..1d1388851 100644
@@ -29,7 +29,8 @@ $(SBOM_TARGETS) &:
       --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 000000000..d28d67b25
@@ -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 000000000..3557b1d51
@@ -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 000000000..bb3db4e42
@@ -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 000000000..682194d43
@@ -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 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 0985457c3..9278e2be7 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 bb3db4e42..9c47258a3 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 000000000..0c83428f4
@@ -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 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 9c47258a3..0f95f99d5 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 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 1d1388851..9ed6067e9 100644
@@ -30,7 +30,9 @@ $(SBOM_TARGETS) &:
       --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 0f95f99d5..2af0fbe6c 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 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 2af0fbe6c..a61257a90 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 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 a61257a90..eecc52156 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 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 000000000..e69de29bb
tools/sbom/tests/cmd_graph/__init__.py new file +0 -0
new file mode 100644
index 000000000..e69de29bb
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

PATCH 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 000000000..e69de29bb
tools/sbom/tests/spdx_graph/test_kernel_file.py new file +32 -0
new file mode 100644
index 000000000..bc44e7a97
@@ -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
#15 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 5 lines

Currently, the tool only supports x86 and arm64 architectures.

This is great work, thank you so much for doing this!

Note, I just tested the series, on 6.19-rc6, and with CONFIG_SBOM enabled, I get this following "message" at the end of the build when it generates the sbom:

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

Is that intentional?

thanks,

greg k-h

#16 lore raw
Quoted 40 lines · Greg KH
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 5 lines

Currently, the tool only supports x86 and arm64 architectures.

This is great work, thank you so much for doing this!

Quoted 7 lines

Note, I just tested the series, on 6.19-rc6, and with CONFIG_SBOM enabled, I get this following "message" at the end of the build when it generates the sbom:

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

Is that intentional?

Ah, it's on the second run that I see this:

End of the first run that builds the sbom files:
...
OBJCOPY arch/x86/boot/vmlinux.bin
AS arch/x86/boot/header.o
LD arch/x86/boot/setup.elf
OBJCOPY arch/x86/boot/setup.bin
BUILD arch/x86/boot/bzImage
Kernel: arch/x86/boot/bzImage is ready (#526)
DESCEND sbom
GEN sbom-build.spdx.json sbom-output.spdx.json
[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.

Then I build again and get the following:

DESCEND objtool
CALL scripts/checksyscalls.sh
INSTALL libsubcmd_headers
Kernel: arch/x86/boot/bzImage is ready (#526)
DESCEND sbom
make[3]: Nothing to be done for 'sbom'.

That make message shouldn't probably show up, right?

Also, I don't know if this is even possible, or you care about it, but if you have ANY sbom file present, it is not regenerated:

	$ rm sbom-build.spdx.json sbom-output.spdx.json
	$ touch sbom-build.spdx.json sbom-output.spdx.json
	$ make
	  DESCEND objtool
	  CALL    scripts/checksyscalls.sh
	  INSTALL libsubcmd_headers
	Kernel: arch/x86/boot/bzImage is ready  (#526)
	  DESCEND sbom
	make[3]: Nothing to be done for 'sbom'.

So, if I change the build config, which will change the sbom output, will the sbom be regenerated? Should it depend on the config .h files to know this?

thanks,

greg k-h

#17 lore raw
Quoted 6 lines

Also, I don't know if this is even possible, or you care about it, but if you have ANY sbom file present, it is not regenerated:
[...]
So, if I change the build config, which will change the sbom output, will the sbom be regenerated?
Should it depend on the config .h files to know this?

Thanks for pointing this out.
Yes, we can add the following to the Makefile dependencies to ensure the SBOM is regenerated when the build changes:
- $(objtree)/$(KBUILD_IMAGE)
- $(objtree)/include/generated/autoconf.h
- $(objtree)/modules.order (if CONFIG_MODULES is set)

This should cover most changes.
When you mentioned "config .h files," did you have any other specific files in mind that should be included as dependencies?

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
#18 lore raw
Quoted 14 lines · Luis Augenstein
Quoted 6 lines

Also, I don't know if this is even possible, or you care about it, but if you have ANY sbom file present, it is not regenerated:
[...]
So, if I change the build config, which will change the sbom output, will the sbom be regenerated?
Should it depend on the config .h files to know this?

Thanks for pointing this out.
Yes, we can add the following to the Makefile dependencies to ensure the SBOM is regenerated when the build changes:
- $(objtree)/$(KBUILD_IMAGE)
- $(objtree)/include/generated/autoconf.h
- $(objtree)/modules.order (if CONFIG_MODULES is set)

Quoted 3 lines

This should cover most changes.
When you mentioned "config .h files," did you have any other specific files in mind that should be included as dependencies?

I was referring to the autoconf.h file, thanks for figuring that out, I couldn't remember what the exact name was. So that should be sufficient here.

thanks,

greg k-h