add SPDX SBOM generation script
Subsystems (3)
Luis Augenstein
maintainerv4 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.
---
Changes in v4:
- move sbom script from tools/ to scripts/ and simplify Makefile
- use $(Q), $(PYTHON3) in scripts/sbom/Makefile
- replace README with Documentation/tools/sbom/sbom.rst
- add Assisted-by tags to document usage of AI tools
---
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 | 11 +- scripts/sbom/Makefile | 40 ++ 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 ++ .../sbom/sbom/cmd_graph/savedcmd_parser.py | 664 ++++++++++++++++++ scripts/sbom/sbom/config.py | 335 +++++++++ scripts/sbom/sbom/environment.py | 168 +++++ 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 | 182 +++++ scripts/sbom/sbom/spdx/serialization.py | 56 ++ scripts/sbom/sbom/spdx/simplelicensing.py | 20 + scripts/sbom/sbom/spdx/software.py | 71 ++ 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 | 188 +++++ .../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 | 383 ++++++++++ scripts/sbom/tests/spdx_graph/__init__.py | 0 .../sbom/tests/spdx_graph/test_kernel_file.py | 32 + 40 files changed, 4081 insertions(+), 2 deletions(-) create mode 100644 Documentation/tools/sbom/sbom.rst create mode 100644 scripts/sbom/Makefile 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.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.34.1
Luis Augenstein
maintainerPATCH v4 1/15 scripts/sbom: add documentation
--- 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
@@ -12,6 +12,7 @@ more additions are needed here: rtla/index rv/index + sbom/sbom .. only:: subproject and html
Documentation/tools/sbom/sbom.rst new file +206 -0
206 lines not on this page · raw message
Signature · 1 line
2.34.1
Luis Augenstein
maintainerPATCH v4 2/15 scripts/sbom: integrate script in make process
In reply to Luis Augensteinintegrate SBOM script into the kernel build process.
--- .gitignore | 1 + MAINTAINERS | 6 ++++++ Makefile | 11 +++++++++-- scripts/sbom/Makefile | 33 +++++++++++++++++++++++++++++++++ scripts/sbom/sbom.py | 16 ++++++++++++++++ 5 files changed, 65 insertions(+), 2 deletions(-) create mode 100644 scripts/sbom/Makefile create mode 100644 scripts/sbom/sbom.py
.gitignore +1 -0
@@ -48,6 +48,7 @@ *.s *.so *.so.dbg +*.spdx.json *.su *.symtypes *.tab.[ch]
MAINTAINERS +6 -0
@@ -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: scripts/sbom/ + SC1200 WDT DRIVER M: Zwane Mwaikambo <[email protected]> S: Maintained
Makefile +9 -2
@@ -772,7 +772,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
@@ -1612,7 +1612,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 \
@@ -1728,6 +1728,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'
@@ -2108,6 +2109,12 @@ nsdeps: export KBUILD_NSDEPS=1 nsdeps: modules $(Q)$(CONFIG_SHELL) $(srctree)/scripts/nsdeps +# Script to generate .spdx.json SBOM documents describing the build +# --------------------------------------------------------------------------- +PHONY += sbom +sbom: all + $(Q)$(MAKE) $(build)=scripts/sbom + # Clang Tooling # ---------------------------------------------------------------------------
scripts/sbom/Makefile new file +33 -0
@@ -0,0 +1,33 @@ +# SPDX-License-Identifier: GPL-2.0-only OR MIT +# Copyright (C) 2025 TNG Technology Consulting GmbH + +SBOM_SOURCE_FILE := $(objtree)/sbom-source.spdx.json +SBOM_BUILD_FILE := $(objtree)/sbom-build.spdx.json +SBOM_OUTPUT_FILE := $(objtree)/sbom-output.spdx.json +SBOM_ROOTS_FILE := $(objtree)/sbom-roots.txt + + +ifeq ($(srctree),$(objtree)) + SBOM_TARGETS := $(SBOM_BUILD_FILE) $(SBOM_OUTPUT_FILE) +else + SBOM_TARGETS := $(SBOM_SOURCE_FILE) $(SBOM_BUILD_FILE) $(SBOM_OUTPUT_FILE) +endif + +SBOM_DEPS := $(objtree)/$(KBUILD_IMAGE) $(objtree)/include/generated/autoconf.h +ifdef CONFIG_MODULES + SBOM_DEPS += $(objtree)/modules.order +endif + +$(SBOM_TARGETS) &: $(SBOM_DEPS) + $(Q)echo " GEN $(notdir $(SBOM_TARGETS))" + + $(Q)printf "%s\n" "$(KBUILD_IMAGE)" > $(SBOM_ROOTS_FILE) + $(Q)if [ "$(CONFIG_MODULES)" = "y" ]; then \ + sed 's/\.o$$/.ko/' $(objtree)/modules.order >> $(SBOM_ROOTS_FILE); \ + fi + + $(Q)$(PYTHON3) $(srctree)/scripts/sbom/sbom.py + + $(Q)rm $(SBOM_ROOTS_FILE) + +$(obj)/: $(SBOM_TARGETS)
scripts/sbom/sbom.py new file +16 -0
@@ -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
Nathan Chancellor
maintainerRe: [PATCH 02/15] scripts/sbom: integrate script in make process
Hi Luis,
Quoted 7 lines · Luis Augenstein
integrate SBOM script into the kernel build process.
Assisted-by Claude Sonnet 4.5Assisted-by GLM-4.7Co-developed-by Maximilian Huber <[email protected]>Signed-off-by Maximilian Huber <[email protected]>Signed-off-by Luis Augenstein <[email protected]>
...
Quoted 14 lines
Makefile +1
-1@@ -772,7 +772,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
Makefile CLEAN_FILES += vmlinux.symvers modules-only.symvers \ · line 1615
Quoted 5 lines
Makefile +1
-1@@ -1612,7 +1612,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
Does sbom-roots.txt need to be cleaned up as well?
A note for Greg: this will conflict with commit a76e30c2479c ("kbuild:
Delete .builtin-dtbs.S when running make clean").
Quoted 33 lines
Makefile +7
-0# Directories & files removed with 'make mrproper' MRPROPER_FILES += include/config include/generated \@@ -1728,6 +1728,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'@@ -2108,6 +2109,12 @@ nsdeps: export KBUILD_NSDEPS=1 nsdeps: modules $(Q)$(CONFIG_SHELL) $(srctree)/scripts/nsdeps +# Script to generate .spdx.json SBOM documents describing the build +# --------------------------------------------------------------------------- +PHONY += sbom +sbom: all + $(Q)$(MAKE) $(build)=scripts/sbom + # Clang Tooling # ---------------------------------------------------------------------------scripts/sbom/Makefile new file +4
-0@@ -0,0 +1,33 @@ +# SPDX-License-Identifier: GPL-2.0-only OR MIT +# Copyright (C) 2025 TNG Technology Consulting GmbH + +SBOM_SOURCE_FILE := $(objtree)/sbom-source.spdx.json
scripts/sbom/Makefile line 14
Quoted 10 lines
scripts/sbom/Makefile new file +10
-0+SBOM_BUILD_FILE := $(objtree)/sbom-build.spdx.json +SBOM_OUTPUT_FILE := $(objtree)/sbom-output.spdx.json +SBOM_ROOTS_FILE := $(objtree)/sbom-roots.txt + + +ifeq ($(srctree),$(objtree)) + SBOM_TARGETS := $(SBOM_BUILD_FILE) $(SBOM_OUTPUT_FILE) +else + SBOM_TARGETS := $(SBOM_SOURCE_FILE) $(SBOM_BUILD_FILE) $(SBOM_OUTPUT_FILE) +endif
This might be easier to read if it were
ifeq ($(srctree),$(objtree))SBOM_TARGETS := $(SBOM_SOURCE_FILE)
endifSBOM_TARGETS += $(SBOM_BUILD_FILE) $(SBOM_OUTPUT_FILE)
scripts/sbom/Makefile line 19
Quoted 4 lines
scripts/sbom/Makefile new file +4
-0+SBOM_DEPS := $(objtree)/$(KBUILD_IMAGE) $(objtree)/include/generated/autoconf.h +ifdef CONFIG_MODULES + SBOM_DEPS += $(objtree)/modules.order +endif
Is $(objtree)/ necessary on these? You might be able to turn this into
SBOM_DEPS := $(KBUILD_IMAGE) include/generated/autoconf.h $(if $(CONFIG_MODULES),modules.order)
scripts/sbom/Makefile line 21
Quoted 1 line
scripts/sbom/Makefile new file +1
-0+$(SBOM_TARGETS) &: $(SBOM_DEPS)
&: is a feature from make 4.3 but the kernel supports make 4.0 and newer, so you should probably make this
# Use # $(SBOM_TARGETS) &: $(SBOM_DEPS) # when make 4.3 is the minimum. $(SBOM_BUILD_FILE): $(SBOM_DEPS) $(obj)/: $(SBOM_BUILD_FILE)
scripts/sbom/Makefile line 31
Quoted 9 lines
scripts/sbom/Makefile new file +8
-0+ $(Q)echo " GEN $(notdir $(SBOM_TARGETS))" + $(Q)if [ "$(CONFIG_MODULES)" = "y" ]; then \ + sed 's/\.o$$/.ko/' $(objtree)/modules.order >> $(SBOM_ROOTS_FILE); \ + fi + + $(Q)$(PYTHON3) $(srctree)/scripts/sbom/sbom.py + + $(Q)rm $(SBOM_ROOTS_FILE)
I think this would look better if it used the standard quiet_cmd_ and cmd_ syntax:
quiet_cmd_sbom = GEN $(notdir $(SBOM_TARGETS))
cmd_sbom = printf "%s\n" "$(KBUILD_IMAGE)" >$(SBOM_ROOTS_FILE); \
$(if $(CONFIG_MODULES),sed 's/\.o$$/.ko/' $(objtree)/modules.order >> $(SBOM_ROOTS_FILE);) \
$(PYTHON3) $(srctree)/scripts/sbom/sbom.py \
--src-tree $(abspath $(srctree)) \
--obj-tree $(abspath $(objtree)) \
--roots-file $(SBOM_ROOTS_FILE) \
--output-directory $(abspath $(objtree)) \
--generate-spdx \
--package-license "GPL-2.0 WITH Linux-syscall-note" \
--package-version "$(KERNELVERSION)"; \
rm $(SBOM_ROOTS_FILE)$(SBOM_BUILD_FILE): $(SBOM_DEPS)
$(call cmd,sbom)
Quoted 1 line
+$(obj)/: $(SBOM_TARGETS)
It seems like this could use the standard always-y Kbuild syntax but I am not sure. Honestly, looking at the bigger picture, it feels like most of this Makefile could be moved into the main Makefile under the sbom target? scripts/sbom is not actually used as an output directory and the generated files do not really need to be listed as targets since their names are hardcoded in scripts/sbom/sbom/config.py?
# Script to generate .spdx.json SBOM documents describing the build # ---------------------------------------------------------------------------
ifdef building_out_of_srctreesbom_targets := sbom-source.spdx.json
endifsbom_targets += sbom-build.spdx.json sbom-output.spdx.json sbom_roots_file := $(objtree)/sbom-roots.txt
quiet_cmd_sbom = GEN $(notdir $(sbom_targets))
cmd_sbom = printf "%s\n" "$(KBUILD_IMAGE)" >$(sbom_roots_file); \
$(if $(CONFIG_MODULES),sed 's/\.o$$/.ko/' $(objtree)/modules.order >> $(sbom_roots_file);) \
$(PYTHON3) $(srctree)/scripts/sbom/sbom.py \
--src-tree $(abspath $(srctree)) \
--obj-tree $(abspath $(objtree)) \
--roots-file $(sbom_roots_file) \
--output-directory $(abspath $(objtree)) \
--generate-spdx \
--package-license "GPL-2.0 WITH Linux-syscall-note" \
--package-version "$(KERNELVERSION)"; \
rm $(sbom_roots_file)
PHONY += sbom
sbom: $(notdir $(KBUILD_IMAGE)) include/generated/autoconf.h $(if $(CONFIG_MODULES),modules modules.order)
$(call cmd,sbom)appears to do the right thing for me?
FWIW, I get errors like
$ make -kj"$(nproc)" ARCH=arm64 CROSS_COMPILE=aarch64-linux- O=build mrproper defconfig sbom
...
GEN sbom-source.spdx.json sbom-build.spdx.json sbom-output.spdx.json
[ERROR] File "/src/scripts/sbom/sbom/cmd_graph/savedcmd_parser.py", line 630, in log_error_or_warning
Skipped parsing command ccache aarch64-linux-gcc ... -o init/main.o /src/init/main.c because no matching parser was found
[ERROR] File "/src/scripts/sbom/sbom/cmd_graph/savedcmd_parser.py", line 630, in log_error_or_warning
Skipped parsing command ccache aarch64-linux-gcc ... -o arch/arm64/kernel/asm-offsets.s /src/arch/arm64/kernel/asm-offsets.c because no matching parser was found
[ERROR] File "/src/scripts/sbom/sbom/cmd_graph/savedcmd_parser.py", line 630, in log_error_or_warning
Skipped parsing command ccache aarch64-linux-gcc ... -o kernel/bounds.s /src/kernel/bounds.c because no matching parser was found
... (Found 10435 more instances of this error)when testing the whole series without any modifications, am I doing something wrong?
Cheers,
Nathan
Luis Augenstein
maintainerRe: [PATCH 02/15] scripts/sbom: integrate script in make process
Hi Nathan,
thanks a lot for your recommendations.
Quoted 1 line
Does sbom-roots.txt need to be cleaned up as well?
This file is only required to pass the roots into the python script. We could also use a tmp file. Then we don't need to worry about clean up. Together with your other suggested changes something like this should work:
# Script to generate .spdx.json SBOM documents describing the build #
---------------------------------------------------------------------------
ifdef building_out_of_srctreesbom_targets := sbom-source.spdx.json
endifsbom_targets += sbom-build.spdx.json sbom-output.spdx.jsonquiet_cmd_sbom = GEN $(notdir $(sbom_targets))
cmd_sbom = roots_file=$$(mktemp); \
printf "%s\n" "$(KBUILD_IMAGE)" >"$$roots_file"; \
$(if $(CONFIG_MODULES),sed 's/\.o$$/.ko/'
$(objtree)/modules.order >> "$$roots_file";) \
$(PYTHON3) $(srctree)/scripts/sbom/sbom.py \
--src-tree $(abspath $(srctree)) \
--obj-tree $(abspath $(objtree)) \
--roots-file "$$roots_file" \
--output-directory $(abspath $(objtree)) \
--generate-spdx \
--package-license "GPL-2.0 WITH Linux-syscall-note" \
--package-version "$(KERNELVERSION)" \
--write-output-on-error;
rm -f "$$roots_file"
PHONY += sbom
sbom: $(notdir $(KBUILD_IMAGE)) include/generated/autoconf.h $(if
$(CONFIG_MODULES),modules modules.order)
$(call cmd,sbom)Note, I will also add the --write-output-on-error flag by default such that the .spdx.json documents are generated as much as possible even if some build commands are unknown to the parser.
Quoted 3 lines
FWIW, I get errors like
$ make -kj"$(nproc)" ARCH=arm64 CROSS_COMPILE=aarch64-linux- O=build
mrproper defconfig sbom
Quoted 2 lines
...
GEN sbom-source.spdx.json sbom-build.spdx.json
sbom-output.spdx.json
Quoted 1 line
[ERROR] File "/src/scripts/sbom/sbom/cmd_graph/savedcmd_parser.py",
line 630, in log_error_or_warning
Quoted 1 line
Skipped parsing command ccache aarch64-linux-gcc ... -o
init/main.o
/src/init/main.c because no matching parser was found
Quoted 1 line
[ERROR] File "/src/scripts/sbom/sbom/cmd_graph/savedcmd_parser.py",
line 630, in log_error_or_warning
Quoted 1 line
Skipped parsing command ccache aarch64-linux-gcc ... -o
arch/arm64/kernel/asm-offsets.s /src/arch/arm64/kernel/asm-offsets.c because no matching parser was found
Quoted 1 line
[ERROR] File "/src/scripts/sbom/sbom/cmd_graph/savedcmd_parser.py",
line 630, in log_error_or_warning
Quoted 1 line
Skipped parsing command ccache aarch64-linux-gcc ... -o
kernel/bounds.s /src/kernel/bounds.c because no matching parser was found
Quoted 4 lines
... (Found 10435 more instances of this error)
when testing the whole series without any modifications, am I doing something wrong?
I was not aware of ccache. If you rebuild without using ccache the gcc commands should be parsed correctly.
The parser expects gcc commands to be of the form
"^([^\s]+-)?(gcc|clang)\b" When using tools like ccache this breaks. I will update the parser to look for "^(ccache\s+)?([^\s]+-)?(gcc|clang)\b"
instead.
Feedback like this is very helpful—thanks! Do you know of any other commonly used tools that modify build commands in a similar way and should be considered?
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
Re: [PATCH 02/15] scripts/sbom: integrate script in make process
Quoted 76 lines · Luis Augenstein
Hi Nathan,
thanks a lot for your recommendations.
Quoted 1 line
Does sbom-roots.txt need to be cleaned up as well?
This file is only required to pass the roots into the python script. We could also use a tmp file. Then we don't need to worry about clean up. Together with your other suggested changes something like this should work:
# Script to generate .spdx.json SBOM documents describing the build #
---------------------------------------------------------------------------ifdef
building_out_of_srctreesbom_targets:= sbom-source.spdx.json
endifsbom_targets+= sbom-build.spdx.json sbom-output.spdx.jsonquiet_cmd_sbom= GEN $(notdir $(sbom_targets))cmd_sbom = roots_file=$$(mktemp); \ printf "%s\n" "$(KBUILD_IMAGE)" >"$$roots_file"; \ $(if $(CONFIG_MODULES),sed 's/\.o$$/.ko/' $(objtree)/modules.order >> "$$roots_file";) \ $(PYTHON3) $(srctree)/scripts/sbom/sbom.py \ --src-tree $(abspath $(srctree)) \ --obj-tree $(abspath $(objtree)) \ --roots-file "$$roots_file" \ --output-directory $(abspath $(objtree)) \ --generate-spdx \ --package-license "GPL-2.0 WITH Linux-syscall-note" \ --package-version "$(KERNELVERSION)" \ --write-output-on-error; rm -f "$$roots_file" PHONY += sbom sbom: $(notdir $(KBUILD_IMAGE)) include/generated/autoconf.h $(if $(CONFIG_MODULES),modules modules.order) $(call cmd,sbom)Note, I will also add the --write-output-on-error flag by default such that the .spdx.json documents are generated as much as possible even if some build commands are unknown to the parser.
Quoted 3 lines
FWIW, I get errors like
$ make -kj"$(nproc)" ARCH=arm64 CROSS_COMPILE=aarch64-linux- O=buildmrproper defconfig sbom
Quoted 2 lines
...
GEN sbom-source.spdx.json sbom-build.spdx.jsonsbom-output.spdx.json
Quoted 1 line
[ERROR] File "/src/scripts/sbom/sbom/cmd_graph/savedcmd_parser.py",
line 630, in
log_error_or_warningQuoted 1 line
Skipped parsing command ccache aarch64-linux-gcc ... -o
init/main.o/src/init/main.c because no matching parser was found
Quoted 1 line
[ERROR] File "/src/scripts/sbom/sbom/cmd_graph/savedcmd_parser.py",
line 630, in
log_error_or_warningQuoted 1 line
Skipped parsing command ccache aarch64-linux-gcc ... -o
arch/arm64/kernel/asm-offsets.s/src/arch/arm64/kernel/asm-offsets.c because no matching parser was foundQuoted 1 line
[ERROR] File "/src/scripts/sbom/sbom/cmd_graph/savedcmd_parser.py",
line 630, in
log_error_or_warningQuoted 1 line
Skipped parsing command ccache aarch64-linux-gcc ... -o
kernel/bounds.s/src/kernel/bounds.c because no matching parser was foundQuoted 4 lines
... (Found 10435 more instances of this error)
when testing the whole series without any modifications, am I doing something wrong?
I was not aware of ccache. If you rebuild without using ccache the gcc commands should be parsed correctly.
The parser expects gcc commands to be of the form
"^([^\s]+-)?(gcc|clang)\b" When using tools like ccache this breaks. I will update the parser to look for "^(ccache\s+)?([^\s]+-)?(gcc|clang)\b"
Quoted 5 lines
instead.
Feedback like this is very helpful—thanks! Do you know of any other commonly used tools that modify build commands in a similar way and should be considered?
Ick, this might get messy as you can modify the compiler with the CC= option to be anything. There are other build tools out there that do much the same as ccache does (which I should have caught this as I use ccache on my build systems), like distcc and friends, so this might just want to look at the result of "CC" instead?
thanks,
greg k-h
Nathan Chancellor
maintainerRe: [PATCH 02/15] scripts/sbom: integrate script in make process
Quoted 16 lines · Greg KH
Quoted 15 lines · Luis Augenstein
Hi Nathan,
thanks a lot for your recommendations.
Quoted 1 line
Does sbom-roots.txt need to be cleaned up as well?
This file is only required to pass the roots into the python script. We could also use a tmp file. Then we don't need to worry about clean up. Together with your other suggested changes something like this should work:
# Script to generate .spdx.json SBOM documents describing the build #
---------------------------------------------------------------------------
Quoted 6 lines
Quoted 6 lines
ifdef
building_out_of_srctreesbom_targets:= sbom-source.spdx.json
endifsbom_targets+= sbom-build.spdx.json sbom-output.spdx.jsonquiet_cmd_sbom= GEN $(notdir $(sbom_targets))cmd_sbom = roots_file=$$(mktemp); \
I think I would rather have a named file in objtree instead of one in /tmp, as we want all output to remain in the build folder.
Quoted 5 lines
Quoted 5 lines
printf "%s\n" "$(KBUILD_IMAGE)" >"$$roots_file"; \ $(if $(CONFIG_MODULES),sed 's/\.o$$/.ko/' $(objtree)/modules.order >> "$$roots_file";) \ $(PYTHON3) $(srctree)/scripts/sbom/sbom.py \ --src-tree $(abspath $(srctree)) \
Quoted 8 lines
Quoted 8 lines
--obj-tree $(abspath $(objtree)) \ --roots-file "$$roots_file" \ --output-directory $(abspath $(objtree)) \ --generate-spdx \ --package-license "GPL-2.0 WITH Linux-syscall-note" \ --package-version "$(KERNELVERSION)" \ --write-output-on-error; rm -f "$$roots_file"
The cmd macro uses 'set -e', so consider moving this up and making it
trap "rm -rf $$roots_file" EXIT; \
like try-run in scripts/Makefile.compiler does to ensure it is always cleaned up.
Quoted 8 lines
Quoted 8 lines
PHONY += sbom
sbom: $(notdir $(KBUILD_IMAGE))include/generated/autoconf.h$(if $(CONFIG_MODULES),modules modules.order)$(call cmd,sbom)Note, I will also add the --write-output-on-error flag by default such that the .spdx.json documents are generated as much as possible even if some build commands are unknown to the parser.
Seems reasonable to me.
Quoted 39 lines
Quoted 33 lines
Quoted 3 lines
FWIW, I get errors like
$ make -kj"$(nproc)" ARCH=arm64 CROSS_COMPILE=aarch64-linux- O=buildmrproper defconfig sbom
Quoted 2 lines
...
GEN sbom-source.spdx.json sbom-build.spdx.jsonsbom-output.spdx.json
Quoted 1 line
[ERROR] File "/src/scripts/sbom/sbom/cmd_graph/savedcmd_parser.py",
line 630, in
log_error_or_warningQuoted 1 line
Skipped parsing command ccache aarch64-linux-gcc ... -o
init/main.o/src/init/main.c because no matching parser was found
Quoted 1 line
[ERROR] File "/src/scripts/sbom/sbom/cmd_graph/savedcmd_parser.py",
line 630, in
log_error_or_warningQuoted 1 line
Skipped parsing command ccache aarch64-linux-gcc ... -o
arch/arm64/kernel/asm-offsets.s/src/arch/arm64/kernel/asm-offsets.c because no matching parser was foundQuoted 1 line
[ERROR] File "/src/scripts/sbom/sbom/cmd_graph/savedcmd_parser.py",
line 630, in
log_error_or_warningQuoted 1 line
Skipped parsing command ccache aarch64-linux-gcc ... -o
kernel/bounds.s/src/kernel/bounds.c because no matching parser was foundQuoted 4 lines
... (Found 10435 more instances of this error)
when testing the whole series without any modifications, am I doing something wrong?
I was not aware of ccache. If you rebuild without using ccache the gcc commands should be parsed correctly.
The parser expects gcc commands to be of the form
"^([^\s]+-)?(gcc|clang)\b" When using tools like ccache this breaks. I will update the parser to look for "^(ccache\s+)?([^\s]+-)?(gcc|clang)\b"Quoted 5 lines
instead.
Feedback like this is very helpful—thanks! Do you know of any other commonly used tools that modify build commands in a similar way and should be considered?
Quoted 5 lines
Ick, this might get messy as you can modify the compiler with the CC= option to be anything. There are other build tools out there that do much the same as ccache does (which I should have caught this as I use ccache on my build systems), like distcc and friends, so this might just want to look at the result of "CC" instead?
Yeah, it would be much more robust to just look at $(CC) directly if it is set (i.e., running within Kbuild) vs. having a separate parser like this. If you want to keep a fallback for standalone usage for development and such, that's fine, but we should use the information we have available to be as accurate as possible.
Cheers,
Nathan
Nicolas Schier
maintainerRe: [PATCH 02/15] scripts/sbom: integrate script in make process
Quoted 24 lines · Nathan Chancellor
Quoted 16 lines · Greg KH
Quoted 15 lines · Luis Augenstein
Hi Nathan,
thanks a lot for your recommendations.
Quoted 1 line
Does sbom-roots.txt need to be cleaned up as well?
This file is only required to pass the roots into the python script. We could also use a tmp file. Then we don't need to worry about clean up. Together with your other suggested changes something like this should work:
# Script to generate .spdx.json SBOM documents describing the build #
---------------------------------------------------------------------------Quoted 6 lines
Quoted 6 lines
ifdef
building_out_of_srctreesbom_targets:= sbom-source.spdx.json
endifsbom_targets+= sbom-build.spdx.json sbom-output.spdx.jsonquiet_cmd_sbom= GEN $(notdir $(sbom_targets))cmd_sbom = roots_file=$$(mktemp); \
Quoted 2 lines
I think I would rather have a named file in objtree instead of one in /tmp, as we want all output to remain in the build folder.
+1
The common way in kbuild is using '$(tmp-target)'.
Quoted 15 lines
Quoted 14 lines
Quoted 14 lines
printf "%s\n" "$(KBUILD_IMAGE)" >"$$roots_file"; \ $(if $(CONFIG_MODULES),sed 's/\.o$$/.ko/' $(objtree)/modules.order >> "$$roots_file";) \ $(PYTHON3) $(srctree)/scripts/sbom/sbom.py \ --src-tree $(abspath $(srctree)) \ --obj-tree $(abspath $(objtree)) \ --roots-file "$$roots_file" \ --output-directory $(abspath $(objtree)) \ --generate-spdx \ --package-license "GPL-2.0 WITH Linux-syscall-note" \ --package-version "$(KERNELVERSION)" \ --write-output-on-error; rm -f "$$roots_file"
Quoted 6 lines
The cmd macro uses 'set -e', so consider moving this up and making it
trap "rm -rf $$roots_file" EXIT; \like try-run in
scripts/Makefile.compilerdoes to ensure it is always cleaned up.
hm, well. Yes, this should do as expected, but please be aware that this also kills the $(delete-on-interrupt) which is part of $(cmd) and removes $@ in case of error or interruption by installing a trap -- which will be overwritten. See also below.
I think it might become a bit cleaner if the roots file is a separate target and the 'sbom' target simply depends on it. But we can defer that.
Quoted 11 lines
Quoted 9 lines
Quoted 9 lines
PHONY += sbom
sbom: $(notdir $(KBUILD_IMAGE))include/generated/autoconf.h$(if $(CONFIG_MODULES),modules modules.order)$(call cmd,sbom)Note, I will also add the --write-output-on-error flag by default such that the .spdx.json documents are generated as much as possible even if some build commands are unknown to the parser.
Seems reasonable to me.
If sbom.py is unable to parse the build commands, does it exit with a non-zero exit code, correct? As 'cmd_sbom' is run within a 'set -e' shell environment, the $(delete-on-interrupt) will delete $@, thus there should be _no_ output on error, regardless of --write-output-on-error. So, it might make sense to kill $(delete-on-interrupt) by intention; but that doesn't feel good to me, as the intention of 'cmd' will be intransparently.
Kind regards,
Nicolas
Luis Augenstein
maintainerRe: [PATCH 02/15] scripts/sbom: integrate script in make process
Hi everyone,
Quoted 2 lines
If
sbom.pyis unable to parse the build commands, does it exit with a non-zero exit code, correct?
yes correct. The current behavior is to always parse as much as possible, collect all problems, print an error summary in the end and exit with a non-zero exit code.
Quoted 11 lines
Quoted 6 lines
The cmd macro uses 'set -e', so consider moving this up and making it
trap "rm -rf $$roots_file" EXIT; \like try-run in
scripts/Makefile.compilerdoes to ensure it is always cleaned up.hm, well. Yes, this should do as expected, but please be aware that this also kills the $(delete-on-interrupt) which is part of $(cmd) and removes $@ in case of error or interruption by installing a trap -- which will be overwritten. See also below.
I think $(delete-on-interrupt) only operates on non-phony targets. Since our target is $@=sbom instead of the generated .spdx.json files $(delete-on-interrupt) currently has no effect and wouldn't really be "killed by intention" by introducing a trap within cmd_sbom.
Quoted 1 line
there should be _no_ output on error, regardless of
--write-output-on-error.
If this is a general convention we should follow, then we maybe want to return a zero exit code in sbom.py in case of errors when --write-output-on-error is set, effectively treating errors as warnings? Alternatively, we could keep not using --write-output-on-error by default. Or we don't follow the convention and write the output *.spdx.json files in case of errors.
I am not sure what's the most appropriate behavior here. However, we know that people will very likely encounter cases with commands unknown to the parser. It's not very useful to simply deny generating the entire documents, because in many cases the sbom will still be quite usable although less complete. For example, if the parsing error occurs close to the leaf nodes it cuts off only a small part of the dependency graph which still retains most of the information.
Tim Bird apparently already encountered this problem which lead him to manually add the --write-output-on-error flag.
https://birdcloud.org/bc/Linux_Kernel_Missing_SPDX_ID_lines_from_build_SBOMs
Quoted 6 lines
The cmd macro uses 'set -e', so consider moving this up and making it
trap "rm -rf $$roots_file" EXIT; \like try-run in
scripts/Makefile.compilerdoes to ensure it is always cleaned up.
and
Quoted 1 line
The common way in kbuild is using '$(tmp-target)'.
This would be the new version then:
# Script to generate .spdx.json SBOM documents describing the build #
---------------------------------------------------------------------------
ifdef building_out_of_srctreesbom_targets := sbom-source.spdx.json
endifsbom_targets += sbom-build.spdx.json sbom-output.spdx.jsonquiet_cmd_sbom = GEN $(notdir $(sbom_targets))
cmd_sbom = roots_file="$(tmp-target)"; \
trap "rm -rf $$roots_file" EXIT; \
printf "%s\n" "$(KBUILD_IMAGE)" >"$$roots_file"; \
$(if $(CONFIG_MODULES),sed 's/\.o$$/.ko/'
$(objtree)/modules.order >> "$$roots_file";) \
$(PYTHON3) $(srctree)/scripts/sbom/sbom.py \
--src-tree $(abspath $(srctree)) \
--obj-tree $(abspath $(objtree)) \
--roots-file "$$roots_file" \
--output-directory $(abspath $(objtree)) \
--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)thanks,
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
Nicolas Schier
maintainerRe: [PATCH 02/15] scripts/sbom: integrate script in make process
Quoted 21 lines · Luis Augenstein
Hi everyone,
Quoted 2 lines
If
sbom.pyis unable to parse the build commands, does it exit with a non-zero exit code, correct?yes correct. The current behavior is to always parse as much as possible, collect all problems, print an error summary in the end and exit with a non-zero exit code.
Quoted 11 lines
Quoted 6 lines
The cmd macro uses 'set -e', so consider moving this up and making it
trap "rm -rf $$roots_file" EXIT; \like try-run in
scripts/Makefile.compilerdoes to ensure it is always cleaned up.hm, well. Yes, this should do as expected, but please be aware that this also kills the $(delete-on-interrupt) which is part of $(cmd) and removes $@ in case of error or interruption by installing a trap -- which will be overwritten. See also below.
Quoted 4 lines
I think $(delete-on-interrupt) only operates on non-phony targets. Since our target is $@=sbom instead of the generated .spdx.json files $(delete-on-interrupt) currently has no effect and wouldn't really be "killed by intention" by introducing a trap within
cmd_sbom.
ah yes, correct.
Quoted 9 lines
Quoted 1 line
there should be _no_ output on error, regardless of
--write-output-on-error.
If this is a general convention we should follow, then we maybe want to return a zero exit code in
sbom.pyin case of errors when --write-output-on-error is set, effectively treating errors as warnings? Alternatively, we could keep not using --write-output-on-error by default. Or we don't follow the convention and write the output *.spdx.json files in case of errors.
I don't have a strong opnion on that. But I think it is important to keep make exiting with a non-zero exit code if a target fails. As you described above, that is the way it is with your current patch set version; thus I am happy with that behaviour.
Quoted 7 lines
I am not sure what's the most appropriate behavior here. However, we know that people will very likely encounter cases with commands unknown to the parser. It's not very useful to simply deny generating the entire documents, because in many cases the sbom will still be quite usable although less complete. For example, if the parsing error occurs close to the leaf nodes it cuts off only a small part of the dependency graph which still retains most of the information.
Ack.
Quoted 20 lines
Tim Bird apparently already encountered this problem which lead him to manually add the --write-output-on-error flag.
https://birdcloud.org/bc/Linux_Kernel_Missing_SPDX_ID_lines_from_build_SBOMsQuoted 6 lines
The cmd macro uses 'set -e', so consider moving this up and making it
trap "rm -rf $$roots_file" EXIT; \like try-run in
scripts/Makefile.compilerdoes to ensure it is always cleaned up.and
Quoted 1 line
The common way in kbuild is using '$(tmp-target)'.
This would be the new version then:
# Script to generate .spdx.json SBOM documents describing the build #
---------------------------------------------------------------------------
Quoted 5 lines
ifdef
building_out_of_srctreesbom_targets:= sbom-source.spdx.json
endifsbom_targets+= sbom-build.spdx.json sbom-output.spdx.jsonquiet_cmd_sbom= GEN $(notdir $(sbom_targets))
If all filenames in $(sbom_targets) are w/o path components, the $(notdir) is obsolete.
Quoted 2 lines
cmd_sbom = roots_file="$(tmp-target)"; \ trap "rm -rf $$roots_file" EXIT; \
I don't see a good reason in the trap here, now that the roots file is a kernel build temp file (ignored by git, removed by make clean). Thus I'd rather recommend to remove the 'trap' line as well as the roots_file variable but use $(tmp-target) instead in all three places.
Thanks!
Kind regards
Nicolas
Luis Augenstein
maintainerRe: [PATCH 02/15] scripts/sbom: integrate script in make process
In reply to Nathan ChancellorQuoted 6 lines
Quoted 5 lines
Ick, this might get messy as you can modify the compiler with the CC= option to be anything. There are other build tools out there that do much the same as ccache does (which I should have caught this as I use ccache on my build systems), like distcc and friends, so this might just want to look at the result of "CC" instead?
Quoted 8 lines
Yeah, it would be much more robust to just look at $(CC) directly if it is set (i.e., running within
Kbuild) vs. having a separate parser like this. If you want to keep a fallback for standalone usage for development and such, that's fine, but we should use the information we have available to be as accurate as possible.Cheers,
Nathan
Ok, sounds good. I will work on that. Thanks.
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
Luis Augenstein
maintainerPATCH v4 3/15 scripts/sbom: setup sbom logging
In reply to Luis AugensteinAdd logging infrastructure for warnings and errors. Errors and warnings are accumulated and summarized in the end.
--- 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
@@ -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
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.34.1
Luis Augenstein
maintainerPATCH v4 4/15 scripts/sbom: add command parsers
In reply to Luis AugensteinImplement savedcmd_parser module for extracting input files from kernel build commands.
--- .../sbom/sbom/cmd_graph/savedcmd_parser.py | 664 ++++++++++++++++++ 1 file changed, 664 insertions(+) create mode 100644 scripts/sbom/sbom/cmd_graph/savedcmd_parser.py
scripts/sbom/sbom/cmd_graph/savedcmd_parser.py new file +664 -0
@@ -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
Luis Augenstein
maintainerPATCH v4 5/15 scripts/sbom: add cmd graph generation
In reply to Luis AugensteinImplement 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.
--- scripts/sbom/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 | 142 +++++++++++++++++ scripts/sbom/sbom/cmd_graph/deps_parser.py | 52 ++++++ scripts/sbom/sbom/config.py | 147 ++++++++++++++++- 8 files changed, 585 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
scripts/sbom/Makefile +5 -1
@@ -26,7 +26,11 @@ $(SBOM_TARGETS) &: $(SBOM_DEPS) sed 's/\.o$$/.ko/' $(objtree)/modules.order >> $(SBOM_ROOTS_FILE); \ fi - $(Q)$(PYTHON3) $(srctree)/scripts/sbom/sbom.py + $(Q)$(PYTHON3) $(srctree)/scripts/sbom/sbom.py \ + --src-tree $(abspath $(srctree)) \ + --obj-tree $(abspath $(objtree)) \ + --roots-file $(SBOM_ROOTS_FILE) \ + --output-directory $(abspath $(objtree)) $(Q)rm $(SBOM_ROOTS_FILE)
scripts/sbom/sbom.py +39 -0
@@ -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
@@ -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 +142 -0
142 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
Signature · 1 line
2.34.1
Luis Augenstein
maintainerPATCH v4 6/15 scripts/sbom: add additional dependency sources for cmd graph
In reply to Luis AugensteinAdd hardcoded dependencies and .incbin directive parsing to discover dependencies not tracked by .cmd files.
--- .../sbom/cmd_graph/hardcoded_dependencies.py | 83 +++++++++++++++++++ scripts/sbom/sbom/cmd_graph/incbin_parser.py | 42 ++++++++++ scripts/sbom/sbom/environment.py | 14 ++++ 3 files changed, 139 insertions(+) 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/environment.py
scripts/sbom/sbom/cmd_graph/hardcoded_dependencies.py new file +83 -0
@@ -0,0 +1,83 @@ +# SPDX-License-Identifier: GPL-2.0-only OR MIT +# Copyright (C) 2025 TNG Technology Consulting GmbH + +import os +from typing import Callable +import sbom.sbom_logging as sbom_logging +from sbom.path_utils import PathStr, is_relative_to +from sbom.environment import Environment + +HARDCODED_DEPENDENCIES: dict[str, list[str]] = { + # defined in linux/Kbuild + "include/generated/rq-offsets.h": ["kernel/sched/rq-offsets.s"], + "kernel/sched/rq-offsets.s": ["include/generated/asm-offsets.h"], + "include/generated/bounds.h": ["kernel/bounds.s"], + "include/generated/asm-offsets.h": ["arch/{arch}/kernel/asm-offsets.s"], +} + + +def get_hardcoded_dependencies(path: PathStr, obj_tree: PathStr, src_tree: PathStr) -> list[PathStr]: + """ + Some files in the kernel build process are not tracked by the .cmd dependency mechanism. + Parsing these dependencies programmatically is too complex for the scope of this project. + Therefore, this function provides manually defined dependencies to be added to the build graph. + + Args: + path: absolute path to a file within the src tree or object tree. + obj_tree: absolute Path to the base directory of the object tree. + src_tree: absolute Path to the `linux` source directory. + + Returns: + list[PathStr]: A list of dependency file paths (relative to the object tree) required to build the file at the given path. + """ + if is_relative_to(path, obj_tree): + path = os.path.relpath(path, obj_tree) + elif is_relative_to(path, src_tree): + path = os.path.relpath(path, src_tree) + + if path not in HARDCODED_DEPENDENCIES: + return [] + + template_variables: dict[str, Callable[[], str | None]] = { + "arch": lambda: _get_arch(path), + } + + dependencies: list[PathStr] = [] + for dependency_template in HARDCODED_DEPENDENCIES[path]: + dependency = _evaluate_template(dependency_template, template_variables) + if dependency is None: + continue + if os.path.exists(os.path.join(obj_tree, dependency)): + dependencies.append(dependency) + elif os.path.exists(os.path.join(src_tree, dependency)): + dependencies.append(os.path.relpath(dependency, obj_tree)) + else: + sbom_logging.error( + "Skip hardcoded dependency '{dependency}' for '{path}' because the dependency lies neither in the src tree nor the object tree.", + dependency=dependency, + path=path, + ) + + return dependencies + + +def _evaluate_template(template: str, variables: dict[str, Callable[[], str | None]]) -> str | None: + for key, value_function in variables.items(): + template_key = "{" + key + "}" + if template_key in template: + value = value_function() + if value is None: + return None + template = template.replace(template_key, value) + return template + + +def _get_arch(path: PathStr): + srcarch = Environment.SRCARCH() + if srcarch is None: + sbom_logging.error( + "Skipped architecture specific hardcoded dependency for '{path}' because the SRCARCH environment variable was not set.", + path=path, + ) + return None + return srcarch
scripts/sbom/sbom/cmd_graph/incbin_parser.py new file +42 -0
42 lines not on this page · raw message
scripts/sbom/sbom/environment.py new file +14 -0
@@ -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
Luis Augenstein
maintainerPATCH v4 7/15 scripts/sbom: add SPDX classes
In reply to Luis AugensteinImplement 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.
--- scripts/sbom/sbom/spdx/__init__.py | 7 + scripts/sbom/sbom/spdx/build.py | 17 ++ scripts/sbom/sbom/spdx/core.py | 182 ++++++++++++++++++++++ scripts/sbom/sbom/spdx/serialization.py | 56 +++++++ scripts/sbom/sbom/spdx/simplelicensing.py | 20 +++ scripts/sbom/sbom/spdx/software.py | 71 +++++++++ scripts/sbom/sbom/spdx/spdxId.py | 36 +++++ 7 files changed, 389 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
@@ -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
@@ -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 +182 -0
182 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
@@ -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 +71 -0
71 lines not on this page · raw message
scripts/sbom/sbom/spdx/spdxId.py new file +36 -0
@@ -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
Luis Augenstein
maintainerPATCH v4 8/15 scripts/sbom: add JSON-LD serialization
In reply to Luis AugensteinAdd 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.
--- scripts/sbom/Makefile | 3 +- scripts/sbom/sbom.py | 52 +++++++++++++++++ scripts/sbom/sbom/config.py | 56 +++++++++++++++++++ scripts/sbom/sbom/path_utils.py | 11 ++++ 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 ++++++++++++ 7 files changed, 200 insertions(+), 1 deletion(-) create mode 100644 scripts/sbom/sbom/path_utils.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/spdx_graph_model.py
scripts/sbom/Makefile +2 -1
@@ -30,7 +30,8 @@ $(SBOM_TARGETS) &: $(SBOM_DEPS) --src-tree $(abspath $(srctree)) \ --obj-tree $(abspath $(objtree)) \ --roots-file $(SBOM_ROOTS_FILE) \ - --output-directory $(abspath $(objtree)) + --output-directory $(abspath $(objtree)) \ + --generate-spdx $(Q)rm $(SBOM_ROOTS_FILE)
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/path_utils.py new file +11 -0
@@ -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
scripts/sbom/sbom/spdx_graph/__init__.py new file +7 -0
@@ -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
@@ -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
@@ -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
Luis Augenstein
maintainerPATCH v4 9/15 scripts/sbom: add shared SPDX elements
In reply to Luis AugensteinImplement shared SPDX elements used in all three documents.
--- scripts/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 scripts/sbom/sbom/spdx_graph/shared_spdx_elements.py
scripts/sbom/sbom/config.py +25 -0
@@ -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, )
scripts/sbom/sbom/spdx_graph/build_spdx_graphs.py +4 -1
@@ -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
@@ -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
Luis Augenstein
maintainerPATCH v4 10/15 scripts/sbom: collect file metadata
In reply to Luis AugensteinImplement 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 + 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
@@ -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.34.1
Luis Augenstein
maintainerPATCH v4 11/15 scripts/sbom: add SPDX output graph
In reply to Luis AugensteinImplement the SPDX output graph which contains the distributable build outputs and high level metadata about the build.
--- scripts/sbom/Makefile | 4 +- scripts/sbom/sbom/config.py | 64 ++++++ scripts/sbom/sbom/environment.py | 154 ++++++++++++++ .../sbom/sbom/spdx_graph/build_spdx_graphs.py | 18 +- .../sbom/sbom/spdx_graph/spdx_output_graph.py | 188 ++++++++++++++++++ 5 files changed, 426 insertions(+), 2 deletions(-) create mode 100644 scripts/sbom/sbom/spdx_graph/spdx_output_graph.py
scripts/sbom/Makefile +3 -1
@@ -31,7 +31,9 @@ $(SBOM_TARGETS) &: $(SBOM_DEPS) --obj-tree $(abspath $(objtree)) \ --roots-file $(SBOM_ROOTS_FILE) \ --output-directory $(abspath $(objtree)) \ - --generate-spdx + --generate-spdx \ + --package-license "GPL-2.0 WITH Linux-syscall-note" \ + --package-version "$(KERNELVERSION)" $(Q)rm $(SBOM_ROOTS_FILE)
scripts/sbom/sbom/config.py +64 -0
88 lines not on this page · raw message
scripts/sbom/sbom/environment.py +154 -0
166 lines not on this page · raw message
scripts/sbom/sbom/spdx_graph/build_spdx_graphs.py +17 -1
@@ -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 +188 -0
188 lines not on this page · raw message
Signature · 1 line
2.34.1
Luis Augenstein
maintainerPATCH v4 12/15 scripts/sbom: add SPDX source graph
In reply to Luis AugensteinImplement 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 scripts/sbom/sbom/spdx_graph/spdx_source_graph.py
scripts/sbom/sbom/spdx_graph/build_spdx_graphs.py +8 -0
@@ -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.34.1
Luis Augenstein
maintainerPATCH v4 13/15 scripts/sbom: add SPDX build graph
In reply to Luis AugensteinImplement 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 scripts/sbom/sbom/spdx_graph/spdx_build_graph.py
scripts/sbom/sbom/spdx_graph/build_spdx_graphs.py +17 -0
@@ -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.34.1
Luis Augenstein
maintainerPATCH v4 14/15 scripts/sbom: add unit tests for command parsers
In reply to Luis AugensteinAdd unit tests to verify that command parsers correctly extract input files from build commands.
--- scripts/sbom/tests/__init__.py | 0 scripts/sbom/tests/cmd_graph/__init__.py | 0 .../tests/cmd_graph/test_savedcmd_parser.py | 383 ++++++++++++++++++ 3 files changed, 383 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
scripts/sbom/tests/cmd_graph/__init__.py new file +0 -0
scripts/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
Luis Augenstein
maintainerPATCH v4 15/15 scripts/sbom: add unit tests for SPDX-License-Identifier parsing
In reply to Luis AugensteinVerify that SPDX-License-Identifier headers at the top of source files are parsed correctly.
--- 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
scripts/sbom/tests/spdx_graph/test_kernel_file.py new file +32 -0
@@ -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
Quoted 38 lines · Luis Augenstein
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 sbomtarget. This target depends onalland 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.cmdfiles generated byKbuild, 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.
Quoted 5 lines
Assisted-by Claude Sonnet 4.5Assisted-by GLM-4.7Co-developed-by Maximilian Huber <[email protected]>Signed-off-by Maximilian Huber <[email protected]>Signed-off-by Luis Augenstein <[email protected]>
What tree should this go through, the kbuild one?
thanks,
greg k-h
Quoted 58 lines · Luis Augenstein
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 sbomtarget. This target depends onalland 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.cmdfiles generated byKbuild, 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 Claude Sonnet 4.5Assisted-by GLM-4.7Co-developed-by Maximilian Huber <[email protected]>Signed-off-by Maximilian Huber <[email protected]>Signed-off-by Luis Augenstein <[email protected]>---
Changes in v4:
- move sbom script fromtools/toscripts/and simplifyMakefile
- use $(Q), $(PYTHON3) inscripts/sbom/Makefile
- replace README withDocumentation/tools/sbom/sbom.rst
- add Assisted-by tags to document usage of AI tools
---
Luis Augenstein (15):
scripts/sbom: add documentation
scripts/sbom: integrate script in make processscripts/sbom: setup sbom logging
scripts/sbom: add command parsers
scripts/sbom: add cmd graph generation
scripts/sbom: add additional dependency sources for cmd graphscripts/sbom: add SPDX classes
Quoted 8 lines
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 parsersscripts/sbom: add unit tests for SPDX-License-Identifier parsing
Nathan and Nicolas, any objection from me taking this through my char/misc tree, or is there something remaining to be done here that would require another respin, or do you want to take it through the kbuild tree?
thanks,
greg k-h
Nathan Chancellor
maintainerQuoted 4 lines · Greg KH
Nathan and Nicolas, any objection from me taking this through my char/misc tree, or is there something remaining to be done here that would require another respin, or do you want to take it through the kbuild tree?
I don't have any objection to you taking this through char/misc but I do have some comments on the kbuild integration that will likely require a respin. I will try to get those out today.
Cheers,
Nathan