Skip to contentSkip to conversation

add SPDX SBOM generation script

PATCH Superseded Luis 2 participants 20 messages Apr 10 – May 7

Subsystems (3)

v5 of 7 Superseded Latest is v7 →

lore
Share & tools
lore
author maintainer
#5 lore raw

PATCH v5 4/15 scripts/sbom: add command parsers

In reply to Luis

From: Luis Augenstein <[email protected]>

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

Assisted-by Cursor:claude-sonnet-4-5
Assisted-by OpenCode:GLM-4-7
---
 .../cmd_graph/savedcmd_parser/__init__.py     |   6 +
 .../command_parser_registry.py                | 474 ++++++++++++++++++
 .../savedcmd_parser/command_splitter.py       | 124 +++++
 .../savedcmd_parser/savedcmd_parser.py        |  68 +++
 .../cmd_graph/savedcmd_parser/tokenizer.py    |  94 ++++
 scripts/sbom/sbom/environment.py              | 192 +++++++
 6 files changed, 958 insertions(+)
 create mode 100644 scripts/sbom/sbom/cmd_graph/savedcmd_parser/__init__.py
 create mode 100644 scripts/sbom/sbom/cmd_graph/savedcmd_parser/command_parser_registry.py
 create mode 100644 scripts/sbom/sbom/cmd_graph/savedcmd_parser/command_splitter.py
 create mode 100644 scripts/sbom/sbom/cmd_graph/savedcmd_parser/savedcmd_parser.py
 create mode 100644 scripts/sbom/sbom/cmd_graph/savedcmd_parser/tokenizer.py
 create mode 100644 scripts/sbom/sbom/environment.py
scripts/sbom/sbom/cmd_graph/savedcmd_parser/__init__.py new file +6 -0
new file mode 100644
index 00000000000..d13876af4df
@@ -0,0 +1,6 @@
+# SPDX-License-Identifier: GPL-2.0-only OR MIT
+# Copyright (C) 2025 TNG Technology Consulting GmbH
+
+from sbom.cmd_graph.savedcmd_parser.savedcmd_parser import parse_inputs_from_commands
+
+__all__ = ["parse_inputs_from_commands"]
scripts/sbom/sbom/cmd_graph/savedcmd_parser/command_parser_registry.py new file +474 -0

474 lines not on this page · raw message

scripts/sbom/sbom/cmd_graph/savedcmd_parser/command_splitter.py new file +124 -0

124 lines not on this page · raw message

scripts/sbom/sbom/cmd_graph/savedcmd_parser/savedcmd_parser.py new file +68 -0

68 lines not on this page · raw message

scripts/sbom/sbom/cmd_graph/savedcmd_parser/tokenizer.py new file +94 -0

94 lines not on this page · raw message

scripts/sbom/sbom/environment.py new file +192 -0

192 lines not on this page · raw message

Signature · 1 line
2.43.0
author maintainer
#6 lore raw

PATCH v5 5/15 scripts/sbom: add cmd graph generation

In reply to Luis

From: Luis Augenstein <[email protected]>

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.

Assisted-by Cursor:claude-sonnet-4-5
Assisted-by OpenCode:GLM-4-7
---
 Makefile                                      |   6 +-
 scripts/sbom/sbom.py                          |  39 +++++
 scripts/sbom/sbom/cmd_graph/__init__.py       |   7 +
 scripts/sbom/sbom/cmd_graph/cmd_file.py       | 149 ++++++++++++++++++
 scripts/sbom/sbom/cmd_graph/cmd_graph.py      |  46 ++++++
 scripts/sbom/sbom/cmd_graph/cmd_graph_node.py | 111 +++++++++++++
 scripts/sbom/sbom/cmd_graph/deps_parser.py    |  52 ++++++
 scripts/sbom/sbom/config.py                   | 147 ++++++++++++++++-
 scripts/sbom/sbom/path_utils.py               |  11 ++
 9 files changed, 565 insertions(+), 3 deletions(-)
 create mode 100644 scripts/sbom/sbom/cmd_graph/__init__.py
 create mode 100644 scripts/sbom/sbom/cmd_graph/cmd_file.py
 create mode 100644 scripts/sbom/sbom/cmd_graph/cmd_graph.py
 create mode 100644 scripts/sbom/sbom/cmd_graph/cmd_graph_node.py
 create mode 100644 scripts/sbom/sbom/cmd_graph/deps_parser.py
 create mode 100644 scripts/sbom/sbom/path_utils.py
Makefile +5 -1
index 06d1ccd9b96..394ebd46e82 100644
@@ -2170,7 +2170,11 @@ sbom_targets += sbom-build.spdx.json sbom-output.spdx.json
 quiet_cmd_sbom = GEN     $(sbom_targets)
       cmd_sbom = printf "%s\n" "$(KBUILD_IMAGE)" >"$(tmp-target)"; \
                  $(if $(CONFIG_MODULES),sed 's/\.o$$/.ko/' $(objtree)/modules.order >> "$(tmp-target)";) \
-                 $(PYTHON3) $(srctree)/scripts/sbom/sbom.py;
+                 $(PYTHON3) $(srctree)/scripts/sbom/sbom.py \
+                     --src-tree $(abspath $(srctree)) \
+                     --obj-tree $(abspath $(objtree)) \
+                     --roots-file "$(tmp-target)" \
+                     --output-directory $(abspath $(objtree));
 PHONY += sbom
 sbom: $(notdir $(KBUILD_IMAGE)) include/generated/autoconf.h $(if $(CONFIG_MODULES),modules modules.order)
 	$(call cmd,sbom)
scripts/sbom/sbom.py +39 -0
index c7f23d6eb30..25d912a282d 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)
 
 
scripts/sbom/sbom/cmd_graph/__init__.py new file +7 -0
new file mode 100644
index 00000000000..9d661a5c3d9
@@ -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"]
scripts/sbom/sbom/cmd_graph/cmd_file.py new file +149 -0

149 lines not on this page · raw message

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

46 lines not on this page · raw message

scripts/sbom/sbom/cmd_graph/cmd_graph_node.py new file +111 -0

111 lines not on this page · raw message

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

52 lines not on this page · raw message

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

180 lines not on this page · raw message

scripts/sbom/sbom/path_utils.py new file +11 -0
new file mode 100644
index 00000000000..d28d67b2539
@@ -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
Signature · 1 line
2.43.0
author maintainer
#7 lore raw

PATCH v5 6/15 scripts/sbom: add additional dependency sources for cmd graph

In reply to Luis

From: Luis Augenstein <[email protected]>

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

Assisted-by Cursor:claude-sonnet-4-5
Assisted-by OpenCode:GLM-4-7
---
 scripts/sbom/sbom/cmd_graph/cmd_graph_node.py | 33 +++++++-
 .../sbom/cmd_graph/hardcoded_dependencies.py  | 83 +++++++++++++++++++
 scripts/sbom/sbom/cmd_graph/incbin_parser.py  | 42 ++++++++++
 3 files changed, 157 insertions(+), 1 deletion(-)
 create mode 100644 scripts/sbom/sbom/cmd_graph/hardcoded_dependencies.py
 create mode 100644 scripts/sbom/sbom/cmd_graph/incbin_parser.py
scripts/sbom/sbom/cmd_graph/cmd_graph_node.py +32 -1
index 7a5279a1ba0..feacdbf7695 100644
@@ -2,15 +2,24 @@
 # Copyright (C) 2025 TNG Technology Consulting GmbH
 
 from dataclasses import dataclass, field
+from itertools import chain
 import logging
 import os
 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
 
 
+@dataclass
+class IncbinDependency:
+    node: "CmdGraphNode"
+    full_statement: str
+
+
 class CmdGraphNodeConfig(Protocol):
     obj_tree: PathStr
     src_tree: PathStr
@@ -28,11 +37,17 @@ class CmdGraphNode:
     """Parsed .cmd file describing how the file at absolute_path was built, or None if not available."""
 
     cmd_file_dependencies: list["CmdGraphNode"] = field(default_factory=list["CmdGraphNode"])
+    incbin_dependencies: list[IncbinDependency] = field(default_factory=list[IncbinDependency])
+    hardcoded_dependencies: list["CmdGraphNode"] = field(default_factory=list["CmdGraphNode"])
 
     @property
     def children(self) -> Iterator["CmdGraphNode"]:
         seen: set[PathStr] = set()
-        for node in self.cmd_file_dependencies:
+        for node in chain(
+            self.cmd_file_dependencies,
+            (dep.node for dep in self.incbin_dependencies),
+            self.hardcoded_dependencies,
+        ):
             if node.absolute_path not in seen:
                 seen.add(node.absolute_path)
                 yield node
@@ -95,6 +110,13 @@ class CmdGraphNode:
         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 = [
                 _build_child_node(cmd_file_dependency_path)
@@ -103,6 +125,15 @@ class CmdGraphNode:
                 )
             ]
 
+        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
 
 
scripts/sbom/sbom/cmd_graph/hardcoded_dependencies.py new file +83 -0

83 lines not on this page · raw message

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

42 lines not on this page · raw message

Signature · 1 line
2.43.0
author maintainer
#8 lore raw

PATCH v5 7/15 scripts/sbom: add SPDX classes

In reply to Luis

From: Luis Augenstein <[email protected]>

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.

Assisted-by Cursor:claude-sonnet-4-5
Assisted-by OpenCode:GLM-4-7
---
 scripts/sbom/sbom/spdx/__init__.py        |   7 +
 scripts/sbom/sbom/spdx/build.py           |  17 +++
 scripts/sbom/sbom/spdx/core.py            | 170 ++++++++++++++++++++++
 scripts/sbom/sbom/spdx/serialization.py   |  56 +++++++
 scripts/sbom/sbom/spdx/simplelicensing.py |  20 +++
 scripts/sbom/sbom/spdx/software.py        |  69 +++++++++
 scripts/sbom/sbom/spdx/spdxId.py          |  36 +++++
 7 files changed, 375 insertions(+)
 create mode 100644 scripts/sbom/sbom/spdx/__init__.py
 create mode 100644 scripts/sbom/sbom/spdx/build.py
 create mode 100644 scripts/sbom/sbom/spdx/core.py
 create mode 100644 scripts/sbom/sbom/spdx/serialization.py
 create mode 100644 scripts/sbom/sbom/spdx/simplelicensing.py
 create mode 100644 scripts/sbom/sbom/spdx/software.py
 create mode 100644 scripts/sbom/sbom/spdx/spdxId.py
scripts/sbom/sbom/spdx/__init__.py new file +7 -0
new file mode 100644
index 00000000000..4097b59f8f1
@@ -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"]
scripts/sbom/sbom/spdx/build.py new file +17 -0
new file mode 100644
index 00000000000..180a8f1e8bd
@@ -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])
scripts/sbom/sbom/spdx/core.py new file +170 -0

170 lines not on this page · raw message

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

56 lines not on this page · raw message

scripts/sbom/sbom/spdx/simplelicensing.py new file +20 -0
new file mode 100644
index 00000000000..750ddd24ad8
@@ -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
scripts/sbom/sbom/spdx/software.py new file +69 -0

69 lines not on this page · raw message

scripts/sbom/sbom/spdx/spdxId.py new file +36 -0
new file mode 100644
index 00000000000..589e85c5f70
@@ -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.43.0
author maintainer
#9 lore raw

PATCH v5 8/15 scripts/sbom: add JSON-LD serialization

In reply to Luis

From: Luis Augenstein <[email protected]>

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.

Assisted-by Cursor:claude-sonnet-4-5
Assisted-by OpenCode:GLM-4-7
---
 Makefile                                      |  3 +-
 scripts/sbom/sbom.py                          | 52 +++++++++++++++++
 scripts/sbom/sbom/config.py                   | 56 +++++++++++++++++++
 scripts/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 ++++++++++++
 6 files changed, 189 insertions(+), 1 deletion(-)
 create mode 100644 scripts/sbom/sbom/spdx_graph/__init__.py
 create mode 100644 scripts/sbom/sbom/spdx_graph/build_spdx_graphs.py
 create mode 100644 scripts/sbom/sbom/spdx_graph/spdx_graph_model.py
Makefile +2 -1
index 394ebd46e82..279e3abd34c 100644
@@ -2174,7 +2174,8 @@ quiet_cmd_sbom = GEN     $(sbom_targets)
                      --src-tree $(abspath $(srctree)) \
                      --obj-tree $(abspath $(objtree)) \
                      --roots-file "$(tmp-target)" \
-                     --output-directory $(abspath $(objtree));
+                     --output-directory $(abspath $(objtree)) \
+                     --generate-spdx;
 PHONY += sbom
 sbom: $(notdir $(KBUILD_IMAGE)) include/generated/autoconf.h $(if $(CONFIG_MODULES),modules modules.order)
 	$(call cmd,sbom)
scripts/sbom/sbom.py +52 -0

75 lines not on this page · raw message

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

116 lines not on this page · raw message

scripts/sbom/sbom/spdx_graph/__init__.py new file +7 -0
new file mode 100644
index 00000000000..3557b1d51bf
@@ -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"]
scripts/sbom/sbom/spdx_graph/build_spdx_graphs.py new file +36 -0
new file mode 100644
index 00000000000..bb3db4e423d
@@ -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 {}
scripts/sbom/sbom/spdx_graph/spdx_graph_model.py new file +36 -0
new file mode 100644
index 00000000000..682194d4362
@@ -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.43.0
author maintainer
#10 lore raw

PATCH v5 9/15 scripts/sbom: add shared SPDX elements

In reply to Luis

From: Luis Augenstein <[email protected]>

Implement shared SPDX elements used in all three documents.

Assisted-by Cursor:claude-sonnet-4-5
Assisted-by OpenCode:GLM-4-7
---
 scripts/sbom/sbom/config.py                   |  8 +++++
 .../sbom/sbom/spdx_graph/build_spdx_graphs.py |  5 ++-
 .../sbom/spdx_graph/shared_spdx_elements.py   | 32 +++++++++++++++++++
 3 files changed, 44 insertions(+), 1 deletion(-)
 create mode 100644 scripts/sbom/sbom/spdx_graph/shared_spdx_elements.py
scripts/sbom/sbom/config.py +8 -0
index 0985457c3ca..fa049f757cb 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."""
 
@@ -195,6 +199,9 @@ 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"]
 
+    created = datetime.fromtimestamp(
+        max([os.path.getmtime(os.path.join(obj_tree, root_path)) for root_path in root_paths])
+    )
     spdxId_prefix = args["spdxId_prefix"]
     prettify_json = args["prettify_json"]
 
@@ -218,6 +225,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,
     )
scripts/sbom/sbom/spdx_graph/build_spdx_graphs.py +4 -1
index bb3db4e423d..9c47258a31c 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 {}
scripts/sbom/sbom/spdx_graph/shared_spdx_elements.py new file +32 -0
new file mode 100644
index 00000000000..0c83428f4c7
@@ -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.43.0
author maintainer
#11 lore raw

PATCH v5 10/15 scripts/sbom: collect file metadata

In reply to Luis

From: Luis Augenstein <[email protected]>

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.

Assisted-by Cursor:claude-sonnet-4-5
Assisted-by OpenCode:GLM-4-7
---
 .../sbom/sbom/spdx_graph/build_spdx_graphs.py |   2 +
 scripts/sbom/sbom/spdx_graph/kernel_file.py   | 310 ++++++++++++++++++
 2 files changed, 312 insertions(+)
 create mode 100644 scripts/sbom/sbom/spdx_graph/kernel_file.py
scripts/sbom/sbom/spdx_graph/build_spdx_graphs.py +2 -0
index 9c47258a31c..0f95f99d560 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 {}
scripts/sbom/sbom/spdx_graph/kernel_file.py new file +310 -0

310 lines not on this page · raw message

Signature · 1 line
2.43.0
author maintainer
#12 lore raw

PATCH v5 11/15 scripts/sbom: add SPDX output graph

In reply to Luis

From: Luis Augenstein <[email protected]>

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

Assisted-by Cursor:claude-sonnet-4-5
Assisted-by OpenCode:GLM-4-7
---
 Makefile                                      |   5 +-
 scripts/sbom/sbom/config.py                   |  64 ++++++
 .../sbom/sbom/spdx_graph/build_spdx_graphs.py |  18 +-
 .../sbom/sbom/spdx_graph/spdx_output_graph.py | 187 ++++++++++++++++++
 4 files changed, 272 insertions(+), 2 deletions(-)
 create mode 100644 scripts/sbom/sbom/spdx_graph/spdx_output_graph.py
Makefile +4 -1
index 279e3abd34c..286effedafb 100644
@@ -2175,7 +2175,10 @@ quiet_cmd_sbom = GEN     $(sbom_targets)
                      --obj-tree $(abspath $(objtree)) \
                      --roots-file "$(tmp-target)" \
                      --output-directory $(abspath $(objtree)) \
-                     --generate-spdx;
+                     --generate-spdx \
+                     --package-license "GPL-2.0 WITH Linux-syscall-note" \
+                     --package-version "$(KERNELVERSION)" \
+                     --write-output-on-error;
 PHONY += sbom
 sbom: $(notdir $(KBUILD_IMAGE)) include/generated/autoconf.h $(if $(CONFIG_MODULES),modules modules.order)
 	$(call cmd,sbom)
scripts/sbom/sbom/config.py +64 -0

88 lines not on this page · raw message

scripts/sbom/sbom/spdx_graph/build_spdx_graphs.py +17 -1
index 0f95f99d560..2af0fbe6cdb 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
scripts/sbom/sbom/spdx_graph/spdx_output_graph.py new file +187 -0

187 lines not on this page · raw message

Signature · 1 line
2.43.0
author maintainer
#13 lore raw

PATCH v5 12/15 scripts/sbom: add SPDX source graph

In reply to Luis

From: Luis Augenstein <[email protected]>

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

Assisted-by Cursor:claude-sonnet-4-5
Assisted-by OpenCode:GLM-4-7
---
 .../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 scripts/sbom/sbom/spdx_graph/spdx_source_graph.py
scripts/sbom/sbom/spdx_graph/build_spdx_graphs.py +8 -0
index 2af0fbe6cdb..a61257a905f 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
scripts/sbom/sbom/spdx_graph/spdx_source_graph.py new file +126 -0

126 lines not on this page · raw message

Signature · 1 line
2.43.0
author maintainer
#14 lore raw

PATCH v5 13/15 scripts/sbom: add SPDX build graph

In reply to Luis

From: Luis Augenstein <[email protected]>

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

Assisted-by Cursor:claude-sonnet-4-5
Assisted-by OpenCode:GLM-4-7
---
 .../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 scripts/sbom/sbom/spdx_graph/spdx_build_graph.py
scripts/sbom/sbom/spdx_graph/build_spdx_graphs.py +17 -0
index a61257a905f..eecc5215644 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
scripts/sbom/sbom/spdx_graph/spdx_build_graph.py new file +317 -0

317 lines not on this page · raw message

Signature · 1 line
2.43.0
author maintainer
#15 lore raw

PATCH v5 14/15 scripts/sbom: add unit tests for command parsers

In reply to Luis

From: Luis Augenstein <[email protected]>

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

Assisted-by Cursor:claude-sonnet-4-5
Assisted-by OpenCode:GLM-4-7
---
 scripts/sbom/tests/__init__.py                |   0
 scripts/sbom/tests/cmd_graph/__init__.py      |   0
 .../tests/cmd_graph/test_savedcmd_parser.py   | 412 ++++++++++++++++++
 3 files changed, 412 insertions(+)
 create mode 100644 scripts/sbom/tests/__init__.py
 create mode 100644 scripts/sbom/tests/cmd_graph/__init__.py
 create mode 100644 scripts/sbom/tests/cmd_graph/test_savedcmd_parser.py
scripts/sbom/tests/__init__.py new file +0 -0
new file mode 100644
index 00000000000..e69de29bb2d
scripts/sbom/tests/cmd_graph/__init__.py new file +0 -0
new file mode 100644
index 00000000000..e69de29bb2d
scripts/sbom/tests/cmd_graph/test_savedcmd_parser.py new file +412 -0

412 lines not on this page · raw message

Signature · 1 line
2.43.0
author maintainer
#16 lore raw

PATCH v5 15/15 scripts/sbom: add unit tests for SPDX-License-Identifier parsing

In reply to Luis

From: Luis Augenstein <[email protected]>

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

Assisted-by Cursor:claude-sonnet-4-5
Assisted-by OpenCode:GLM-4-7
---
 scripts/sbom/tests/spdx_graph/__init__.py     |  0
 .../sbom/tests/spdx_graph/test_kernel_file.py | 32 +++++++++++++++++++
 2 files changed, 32 insertions(+)
 create mode 100644 scripts/sbom/tests/spdx_graph/__init__.py
 create mode 100644 scripts/sbom/tests/spdx_graph/test_kernel_file.py
scripts/sbom/tests/spdx_graph/__init__.py new file +0 -0
new file mode 100644
index 00000000000..e69de29bb2d
scripts/sbom/tests/spdx_graph/test_kernel_file.py new file +32 -0
new file mode 100644
index 00000000000..bc44e7a97d2
@@ -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.43.0

Luis

author maintainer
#0 lore raw

v5 cover add SPDX SBOM generation script

This patch series introduces a Python-based script 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 script 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 script is optional. It can be invoked via the make sbom target. This target depends on all and triggers a standard kernel build. Once all output artifacts have been generated, starting from the kernel image and modules as root nodes, the script 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 script only supports x86 and arm64 architectures.

This series was developed with assistance from AI tools, namely Cursor with Claude Sonnet 4.5 and OpenCode with GLM-4.7. The AI was used for documentation, exploring the repository, and iterating on design questions and implementation details such as regex patterns.

Assisted-by Cursor:claude-sonnet-4-5
Assisted-by OpenCode:GLM-4-7

---
Changes in v5:
- simplify make integration. No dedicated Makefile. Only top level.
- support dynamic command parser templates based on environment variable overwrites:
CC, LD, AR, NM, OBJCOPY, STRIP.
- add --write-output-on-error cli argument when invoked from the Makefile which
allows to generate spdx documents despite errors.
This was for example a problem in https://birdcloud.org/bc/Linux_Kernel_Missing_SPDX_ID_lines_from_build_SBOMs
The script still exits with a non-zero exit code.
- split savedcmd_parser.py file into multiple files for better readability.
- add command parser for gen-hyprel command.
- remove the created cli argument for CreationInfo object which does not need to be a configurable. Instead, the latest modified timestamp of the provided root artifacts is used.
- remove the originatedBy property from Package elements which was set to the agent who created the SBOM. This was a wrong usage of the property.
- remove some spdx properties that were not used in the current version, namely SoftwareArtifact.additionalPurpose, Package.downloadLocation, Artifact.builtTime, and Agent.externalIdentifier
---
Luis Augenstein (15):
scripts/sbom: add documentation
scripts/sbom: integrate script in make process
scripts/sbom: setup sbom logging
scripts/sbom: add command parsers
scripts/sbom: add cmd graph generation
scripts/sbom: add additional dependency sources for cmd graph
scripts/sbom: add SPDX classes
scripts/sbom: add JSON-LD serialization
scripts/sbom: add shared SPDX elements
scripts/sbom: collect file metadata
scripts/sbom: add SPDX output graph
scripts/sbom: add SPDX source graph
scripts/sbom: add SPDX build graph
scripts/sbom: add unit tests for command parsers
scripts/sbom: add unit tests for SPDX-License-Identifier parsing

 .gitignore                                    |   1 +
 Documentation/tools/index.rst                 |   1 +
 Documentation/tools/sbom/sbom.rst             | 206 ++++++++
 MAINTAINERS                                   |   6 +
 Makefile                                      |  28 +-
 scripts/sbom/sbom.py                          | 129 +++++
 scripts/sbom/sbom/__init__.py                 |   0
 scripts/sbom/sbom/cmd_graph/__init__.py       |   7 +
 scripts/sbom/sbom/cmd_graph/cmd_file.py       | 149 ++++++
 scripts/sbom/sbom/cmd_graph/cmd_graph.py      |  46 ++
 scripts/sbom/sbom/cmd_graph/cmd_graph_node.py | 142 ++++++
 scripts/sbom/sbom/cmd_graph/deps_parser.py    |  52 ++
 .../sbom/cmd_graph/hardcoded_dependencies.py  |  83 +++
 scripts/sbom/sbom/cmd_graph/incbin_parser.py  |  42 ++
 .../cmd_graph/savedcmd_parser/__init__.py     |   6 +
 .../command_parser_registry.py                | 474 ++++++++++++++++++
 .../savedcmd_parser/command_splitter.py       | 124 +++++
 .../savedcmd_parser/savedcmd_parser.py        |  68 +++
 .../cmd_graph/savedcmd_parser/tokenizer.py    |  94 ++++
 scripts/sbom/sbom/config.py                   | 318 ++++++++++++
 scripts/sbom/sbom/environment.py              | 192 +++++++
 scripts/sbom/sbom/path_utils.py               |  11 +
 scripts/sbom/sbom/sbom_logging.py             |  88 ++++
 scripts/sbom/sbom/spdx/__init__.py            |   7 +
 scripts/sbom/sbom/spdx/build.py               |  17 +
 scripts/sbom/sbom/spdx/core.py                | 170 +++++++
 scripts/sbom/sbom/spdx/serialization.py       |  56 +++
 scripts/sbom/sbom/spdx/simplelicensing.py     |  20 +
 scripts/sbom/sbom/spdx/software.py            |  69 +++
 scripts/sbom/sbom/spdx/spdxId.py              |  36 ++
 scripts/sbom/sbom/spdx_graph/__init__.py      |   7 +
 .../sbom/sbom/spdx_graph/build_spdx_graphs.py |  82 +++
 scripts/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 | 187 +++++++
 .../sbom/sbom/spdx_graph/spdx_source_graph.py | 126 +++++
 scripts/sbom/tests/__init__.py                |   0
 scripts/sbom/tests/cmd_graph/__init__.py      |   0
 .../tests/cmd_graph/test_savedcmd_parser.py   | 412 +++++++++++++++
 scripts/sbom/tests/spdx_graph/__init__.py     |   0
 .../sbom/tests/spdx_graph/test_kernel_file.py |  32 ++
 43 files changed, 4181 insertions(+), 2 deletions(-)
 create mode 100644 Documentation/tools/sbom/sbom.rst
 create mode 100644 scripts/sbom/sbom.py
 create mode 100644 scripts/sbom/sbom/__init__.py
 create mode 100644 scripts/sbom/sbom/cmd_graph/__init__.py
 create mode 100644 scripts/sbom/sbom/cmd_graph/cmd_file.py
 create mode 100644 scripts/sbom/sbom/cmd_graph/cmd_graph.py
 create mode 100644 scripts/sbom/sbom/cmd_graph/cmd_graph_node.py
 create mode 100644 scripts/sbom/sbom/cmd_graph/deps_parser.py
 create mode 100644 scripts/sbom/sbom/cmd_graph/hardcoded_dependencies.py
 create mode 100644 scripts/sbom/sbom/cmd_graph/incbin_parser.py
 create mode 100644 scripts/sbom/sbom/cmd_graph/savedcmd_parser/__init__.py
 create mode 100644 scripts/sbom/sbom/cmd_graph/savedcmd_parser/command_parser_registry.py
 create mode 100644 scripts/sbom/sbom/cmd_graph/savedcmd_parser/command_splitter.py
 create mode 100644 scripts/sbom/sbom/cmd_graph/savedcmd_parser/savedcmd_parser.py
 create mode 100644 scripts/sbom/sbom/cmd_graph/savedcmd_parser/tokenizer.py
 create mode 100644 scripts/sbom/sbom/config.py
 create mode 100644 scripts/sbom/sbom/environment.py
 create mode 100644 scripts/sbom/sbom/path_utils.py
 create mode 100644 scripts/sbom/sbom/sbom_logging.py
 create mode 100644 scripts/sbom/sbom/spdx/__init__.py
 create mode 100644 scripts/sbom/sbom/spdx/build.py
 create mode 100644 scripts/sbom/sbom/spdx/core.py
 create mode 100644 scripts/sbom/sbom/spdx/serialization.py
 create mode 100644 scripts/sbom/sbom/spdx/simplelicensing.py
 create mode 100644 scripts/sbom/sbom/spdx/software.py
 create mode 100644 scripts/sbom/sbom/spdx/spdxId.py
 create mode 100644 scripts/sbom/sbom/spdx_graph/__init__.py
 create mode 100644 scripts/sbom/sbom/spdx_graph/build_spdx_graphs.py
 create mode 100644 scripts/sbom/sbom/spdx_graph/kernel_file.py
 create mode 100644 scripts/sbom/sbom/spdx_graph/shared_spdx_elements.py
 create mode 100644 scripts/sbom/sbom/spdx_graph/spdx_build_graph.py
 create mode 100644 scripts/sbom/sbom/spdx_graph/spdx_graph_model.py
 create mode 100644 scripts/sbom/sbom/spdx_graph/spdx_output_graph.py
 create mode 100644 scripts/sbom/sbom/spdx_graph/spdx_source_graph.py
 create mode 100644 scripts/sbom/tests/__init__.py
 create mode 100644 scripts/sbom/tests/cmd_graph/__init__.py
 create mode 100644 scripts/sbom/tests/cmd_graph/test_savedcmd_parser.py
 create mode 100644 scripts/sbom/tests/spdx_graph/__init__.py
 create mode 100644 scripts/sbom/tests/spdx_graph/test_kernel_file.py
Signature · 1 line
2.43.0
author maintainer
#1 lore raw

PATCH v5 1/15 scripts/sbom: add documentation

From: Luis Augenstein <[email protected]>

Assisted-by Cursor:claude-sonnet-4-5
Assisted-by OpenCode:GLM-4-7
---
 Documentation/tools/index.rst     |   1 +
 Documentation/tools/sbom/sbom.rst | 206 ++++++++++++++++++++++++++++++
 2 files changed, 207 insertions(+)
 create mode 100644 Documentation/tools/sbom/sbom.rst
Documentation/tools/index.rst +1 -0
index 5f2f63bcb28..1adf4a6f909 100644
@@ -13,3 +13,4 @@ more additions are needed here:
    rtla/index
    rv/index
    python
+   sbom/sbom
Documentation/tools/sbom/sbom.rst new file +206 -0

206 lines not on this page · raw message

Signature · 1 line
2.43.0
author maintainer
#2 lore raw

PATCH v5 2/15 scripts/sbom: integrate script in make process

In reply to Luis

From: Luis Augenstein <[email protected]>

integrate SBOM script into the kernel build process.

Assisted-by Cursor:claude-sonnet-4-5
Assisted-by OpenCode:GLM-4-7
---
 .gitignore           |  1 +
 MAINTAINERS          |  6 ++++++
 Makefile             | 20 ++++++++++++++++++--
 scripts/sbom/sbom.py | 16 ++++++++++++++++
 4 files changed, 41 insertions(+), 2 deletions(-)
 create mode 100644 scripts/sbom/sbom.py
.gitignore +1 -0
index 3a7241c941f..f3372f15eb1 100644
@@ -48,6 +48,7 @@
 *.s
 *.so
 *.so.dbg
+*.spdx.json
 *.su
 *.symtypes
 *.tab.[ch]
MAINTAINERS +6 -0
index c3fe46d7c4b..419a1f70a3a 100644
@@ -23657,6 +23657,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:	scripts/sbom/
+
 SC1200 WDT DRIVER
 M:	Zwane Mwaikambo <[email protected]>
 S:	Maintained
Makefile +18 -2
index 4f54c568563..06d1ccd9b96 100644
@@ -777,7 +777,7 @@ endif
 # in addition to whatever we do anyway.
 # Just "make" or "make all" shall build modules as well
 
-ifneq ($(filter all modules nsdeps compile_commands.json clang-%,$(MAKECMDGOALS)),)
+ifneq ($(filter all modules nsdeps compile_commands.json clang-% sbom,$(MAKECMDGOALS)),)
   KBUILD_MODULES := y
 endif
 
@@ -1654,7 +1654,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-dtbs.S
+	       .builtin-dtbs-list .builtin-dtbs.S sbom-*.spdx.json
 
 # Directories & files removed with 'make mrproper'
 MRPROPER_FILES += include/config include/generated          \
@@ -1773,6 +1773,7 @@ help:
 	@echo  ''
 	@echo  'Tools:'
 	@echo  '  nsdeps          - Generate missing symbol namespace dependencies'
+	@echo  '  sbom            - Generate Software Bill of Materials'
 	@echo  ''
 	@echo  'Kernel selftest:'
 	@echo  '  kselftest         - Build and run kernel selftest'
@@ -2159,6 +2160,21 @@ nsdeps: export KBUILD_NSDEPS=1
 nsdeps: modules
 	$(Q)$(CONFIG_SHELL) $(srctree)/scripts/nsdeps
 
+# Script to generate .spdx.json SBOM documents describing the build
+# ---------------------------------------------------------------------------
+
+ifdef building_out_of_srctree
+sbom_targets := sbom-source.spdx.json
+endif
+sbom_targets += sbom-build.spdx.json sbom-output.spdx.json
+quiet_cmd_sbom = GEN     $(sbom_targets)
+      cmd_sbom = printf "%s\n" "$(KBUILD_IMAGE)" >"$(tmp-target)"; \
+                 $(if $(CONFIG_MODULES),sed 's/\.o$$/.ko/' $(objtree)/modules.order >> "$(tmp-target)";) \
+                 $(PYTHON3) $(srctree)/scripts/sbom/sbom.py;
+PHONY += sbom
+sbom: $(notdir $(KBUILD_IMAGE)) include/generated/autoconf.h $(if $(CONFIG_MODULES),modules modules.order)
+	$(call cmd,sbom)
+
 # Clang Tooling
 # ---------------------------------------------------------------------------
 
scripts/sbom/sbom.py new file +16 -0
new file mode 100644
index 00000000000..9c2e4c7f17c
@@ -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.43.0
author maintainer
#4 lore raw

PATCH v5 3/15 scripts/sbom: setup sbom logging

In reply to Luis

From: Luis Augenstein <[email protected]>

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

Assisted-by Cursor:claude-sonnet-4-5
Assisted-by OpenCode:GLM-4-7
---
 scripts/sbom/sbom.py              | 24 ++++++++-
 scripts/sbom/sbom/__init__.py     |  0
 scripts/sbom/sbom/config.py       | 47 +++++++++++++++++
 scripts/sbom/sbom/sbom_logging.py | 88 +++++++++++++++++++++++++++++++
 4 files changed, 158 insertions(+), 1 deletion(-)
 create mode 100644 scripts/sbom/sbom/__init__.py
 create mode 100644 scripts/sbom/sbom/config.py
 create mode 100644 scripts/sbom/sbom/sbom_logging.py
scripts/sbom/sbom.py +23 -1
index 9c2e4c7f17c..c7f23d6eb30 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
scripts/sbom/sbom/__init__.py new file +0 -0
new file mode 100644
index 00000000000..e69de29bb2d
scripts/sbom/sbom/config.py new file +47 -0

47 lines not on this page · raw message

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

88 lines not on this page · raw message

Signature · 1 line
2.43.0
#17 lore raw
In reply to Luis
Quoted 2 lines · Luis

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

I see the following error when building ARCH=arm64 virtconfig sbom:

  | $ make -skj"$(nproc)" ARCH=arm64 CROSS_COMPILE=aarch64-linux- CROSS_COMPILE_COMPAT=arm-linux-gnueabi- mrproper virtconfig sbom
  | [ERROR] File "/src/scripts/sbom/sbom/cmd_graph/savedcmd_parser/savedcmd_parser.py", line 33, in log_error_or_warning
  | Skipped parsing command arch/arm64/kernel/vdso32/../../../arm/vdso/vdsomunge arch/arm64/kernel/vdso32/vdso.so.raw arch/arm64/kernel/vdso32/vdso32.so.dbg because no matching parser was found
  | ...
  | make[3]: *** [/src/Makefile:2184: sbom] Error 1
  | ...

I would highly recommend running some randconfig builds with ARCH=arm64 and ARCH=x86_64 if you have not already done so to ensure you have caught all corner cases. This one was understandably missed because GCC builds require a separate 32-bit cross compiler (specified with CROSS_COMPILE_COMPAT) to build this code. Testing with LLVM=1 would help with that since the build system handles cross compile automatically in that case.

Quoted 7 lines

[...]
modules as root nodes, the script 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 script only supports x86 and arm64 architectures.

This does not appear to be codified anywhere? I can run the sbom target when targeting ARCH=arm for example, resulting in:

  | [ERROR] File "/src/scripts/sbom/sbom/cmd_graph/savedcmd_parser/savedcmd_parser.py", line 33, in log_error_or_warning
  | Skipped parsing command sh /src/arch/arm/tools/syscallnr.sh /src/arch/arm/tools/syscall.tbl arch/arm/include/generated/asm/unistd-nr.h because no matching parser was found
  | [ERROR] File "/src/scripts/sbom/sbom/cmd_graph/savedcmd_parser/savedcmd_parser.py", line 33, in log_error_or_warning
  | Skipped parsing command ./arch/arm/vdso/vdsomunge arch/arm/vdso/vdso.so.raw arch/arm/vdso/vdso.so.dbg because no matching parser was found
  | [WARNING] Could not infer primary purpose for /src/arch/arm/tools/mach-types
  | [WARNING] Could not infer primary purpose for /build/arch/arm/boot/compressed/piggy_data

Otherwise, from a Kbuild perspective, this seems fine. I will provide my Ack on patch 2, which is the only place it should matter. I think Greg can take this when he thinks it is in good enough shape.

Sashiko points out a number of things as well:

https://sashiko.dev/#/patchset/[email protected]

Signature · 2 lines
Cheers,
Nathan
author maintainer
#18 lore raw
In reply to Nathan Chancellor
Quoted 13 lines · Nathan Chancellor
Quoted 2 lines · Luis

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

I see the following error when building ARCH=arm64 virtconfig sbom:

   | $ make -skj"$(nproc)" ARCH=arm64 CROSS_COMPILE=aarch64-linux- CROSS_COMPILE_COMPAT=arm-linux-gnueabi- mrproper virtconfig sbom
   | [ERROR] File "/src/scripts/sbom/sbom/cmd_graph/savedcmd_parser/savedcmd_parser.py", line 33, in log_error_or_warning
   | Skipped parsing command arch/arm64/kernel/vdso32/../../../arm/vdso/vdsomunge arch/arm64/kernel/vdso32/vdso.so.raw arch/arm64/kernel/vdso32/vdso32.so.dbg because no matching parser was found
   | ...
   | make[3]: *** [/src/Makefile:2184: sbom] Error 1
   | ...
Quoted 7 lines

I would highly recommend running some randconfig builds with ARCH=arm64 and ARCH=x86_64 if you have not already done so to ensure you have caught all corner cases. This one was understandably missed because GCC builds require a separate 32-bit cross compiler (specified with CROSS_COMPILE_COMPAT) to build this code. Testing with LLVM=1 would help with that since the build system handles cross compile automatically in that case.

So far, I have mainly tested with tinyconfig, defconfig, allmodconfig, and the configs from https://github.com/gregkh/gregkh-linux/tree/master/stable/configs.
Additionally, I have now tested some randconfig builds. Still, there will most likely be edge cases that we will only discover over time. However, while the tool is designed to exit with a non-zero status code when unknown commands are encountered, it still produces a valid SBOM based on the information it was able to collect. So, despite missing command parser errors like these, the tool remains usable. There is also the --do-not-fail-on-unknown-build-command option to log missing command parser errors as warnings and exit with a zero status code. I have disabled this by default, though, to make people more likely to report any missing command parser issues they encounter.

Quoted 10 lines
Quoted 6 lines

modules as root nodes, the script 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 script only supports x86 and arm64 architectures.

This does not appear to be codified anywhere? I can run the sbom target when targeting ARCH=arm for example, resulting in:

Quoted 6 lines
   | [ERROR] File "/src/scripts/sbom/sbom/cmd_graph/savedcmd_parser/savedcmd_parser.py", line 33, in log_error_or_warning
   | Skipped parsing command sh /src/arch/arm/tools/syscallnr.sh /src/arch/arm/tools/syscall.tbl arch/arm/include/generated/asm/unistd-nr.h because no matching parser was found
   | [ERROR] File "/src/scripts/sbom/sbom/cmd_graph/savedcmd_parser/savedcmd_parser.py", line 33, in log_error_or_warning
   | Skipped parsing command ./arch/arm/vdso/vdsomunge arch/arm/vdso/vdso.so.raw arch/arm/vdso/vdso.so.dbg because no matching parser was found
   | [WARNING] Could not infer primary purpose for /src/arch/arm/tools/mach-types
   | [WARNING] Could not infer primary purpose for /build/arch/arm/boot/compressed/piggy_data

Yes, this is not codified in the sense that the tool does not restrict execution to specific architectures.
Should it?
As stated above, the tool is designed to collect as much of the dependency graph as possible. For other architectures, it behaves the same way, i.e., a valid SBOM is produced, but the missing parser errors indicate that the SBOM is not complete. I think this behavior is more useful than denying execution for other architectures entirely, but we could change that if you think otherwise.

Quoted 3 lines

Sashiko points out a number of things as well:

   https://sashiko.dev/#/patchset/[email protected]

Cool, thanks. I didn't know this exists.
I worked through the comments and will provide according changes in v6 of the patch series soon.

Best,
Luis

Signature · 5 lines
Luis Augenstein * [email protected] * +4915225275761
TNG Technology Consulting GmbH, Beta-Str. 13, 85774 Unterföhring
Geschäftsführer: Henrik Klagges, Dr. Robert Dahlke, Thomas Endres
Aufsichtsratsvorsitzender: Moritz Prinz
Sitz: Unterföhring * Amtsgericht München * HRB 135082
#19 lore raw
Quoted 22 lines · Luis Augenstein
Quoted 13 lines · Nathan Chancellor
Quoted 2 lines · Luis

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

I see the following error when building ARCH=arm64 virtconfig sbom:

   | $ make -skj"$(nproc)" ARCH=arm64 CROSS_COMPILE=aarch64-linux- CROSS_COMPILE_COMPAT=arm-linux-gnueabi- mrproper virtconfig sbom
   | [ERROR] File "/src/scripts/sbom/sbom/cmd_graph/savedcmd_parser/savedcmd_parser.py", line 33, in log_error_or_warning
   | Skipped parsing command arch/arm64/kernel/vdso32/../../../arm/vdso/vdsomunge arch/arm64/kernel/vdso32/vdso.so.raw arch/arm64/kernel/vdso32/vdso32.so.dbg because no matching parser was found
   | ...
   | make[3]: *** [/src/Makefile:2184: sbom] Error 1
   | ...
Quoted 7 lines

I would highly recommend running some randconfig builds with ARCH=arm64 and ARCH=x86_64 if you have not already done so to ensure you have caught all corner cases. This one was understandably missed because GCC builds require a separate 32-bit cross compiler (specified with CROSS_COMPILE_COMPAT) to build this code. Testing with LLVM=1 would help with that since the build system handles cross compile automatically in that case.

Quoted 13 lines

So far, I have mainly tested with tinyconfig, defconfig, allmodconfig, and the configs from
https://github.com/gregkh/gregkh-linux/tree/master/stable/configs.
Additionally, I have now tested some randconfig builds. Still, there will most likely be edge cases that we will only discover over time. However, while the tool is designed to exit with a non-zero status code when unknown commands are encountered, it still produces a valid SBOM based on the information it was able to collect. So, despite missing command parser errors like these, the tool remains usable.
There is also the --do-not-fail-on-unknown-build-command option to log missing command parser errors as warnings and exit with a zero status code. I have disabled this by default, though, to make people more likely to report any missing command parser issues they encounter.

Sure. Just be prepared for the bug reports regardless :)

Quoted 17 lines
Quoted 10 lines
Quoted 6 lines

modules as root nodes, the script 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 script only supports x86 and arm64 architectures.

This does not appear to be codified anywhere? I can run the sbom target when targeting ARCH=arm for example, resulting in:

Quoted 6 lines
   | [ERROR] File "/src/scripts/sbom/sbom/cmd_graph/savedcmd_parser/savedcmd_parser.py", line 33, in log_error_or_warning
   | Skipped parsing command sh /src/arch/arm/tools/syscallnr.sh /src/arch/arm/tools/syscall.tbl arch/arm/include/generated/asm/unistd-nr.h because no matching parser was found
   | [ERROR] File "/src/scripts/sbom/sbom/cmd_graph/savedcmd_parser/savedcmd_parser.py", line 33, in log_error_or_warning
   | Skipped parsing command ./arch/arm/vdso/vdsomunge arch/arm/vdso/vdso.so.raw arch/arm/vdso/vdso.so.dbg because no matching parser was found
   | [WARNING] Could not infer primary purpose for /src/arch/arm/tools/mach-types
   | [WARNING] Could not infer primary purpose for /build/arch/arm/boot/compressed/piggy_data
Quoted 9 lines

Yes, this is not codified in the sense that the tool does not restrict execution to specific architectures.
Should it?
As stated above, the tool is designed to collect as much of the dependency graph as possible. For other architectures, it behaves the same way, i.e., a valid SBOM is produced, but the missing parser errors indicate that the SBOM is not complete. I think this behavior is more useful than denying execution for other architectures entirely, but we could change that if you think otherwise.

I don't really care one way or another. I merely pointed it out since there seems to be some low hanging fruit there but it may be worth waiting to see who would use this with those various architectures before working on supporting those commands.

Signature · 2 lines
Cheers,
Nathan