Skip to contentSkip to conversation

kbuild: record cmd-prereqs in .cmd files

PATCH In review Luis Augenstein 2 participants 10 messages Nov 19 – Nov 23

Subsystems (4)
lore
Share & tools
lore

Luis Augenstein

author maintainer
#0 lore raw

v6 cover kbuild: record cmd-prereqs in .cmd files

KernelSbom (scripts/sbom/sbom.py) reconstructs the kernel build graph from the .cmd files written by Kbuild. For most build outputs, KernelSbom must infer the build inputs from the shell command stored in savedcmd_*. This requires command-specific parsers, which add unnecessary complexity and are difficult to maintain.

Kbuild already knows these inputs as $(real-prereqs), the non-phony prerequisites of the Make rule. This series records them in .cmd files using a new metadata field:

make_prereqs_<target> := <prerequisites>

KernelSbom is updated to read the new field instead of parsing the shell command, and the obsolete command-specific parsers are removed.

The issue of manually parsing shell commands was originally mentioned in https://lore.kernel.org/r/[email protected].
This series is a proposal to address that.

Cmd writers and consumers
=========================

The new field should not affect existing behavior. Below is a summary of what I checked.

.cmd files are primarily written by cmd_and_savecmd and cmd_and_fixdep. Both writers add make_prereqs.

The following rules append information to existing .cmd files. None of these is affected by the new field:

- scripts/Makefile.lib: cmd_gen_objtooldep only appends new rule
target: $(wildcard ./tools/objtool/objtool)
- scripts/Makefile.build: gen_symversions only appends comments #SYMVER <name> <crc>
- scripts/Makefile.lib: cmd_save_c_flags only appends a variable saved_c_flags_<target> := <flags>
- rust/Makefile: cmd_gendwarfksyms only appends comments #SYMVER <name> <crc>
- kernel/Makefile: kheaders_data_dep appends a deps_* block deps_<target> := <headers>.

This series updates the following .cmd file consumers:

- scripts/sbom/sbom/cmd_graph/cmd_file.py: CmdFile.create() is rewritten to parse the fields by name, including the new make_prereqs field.
- scripts/make_fit.py: process_dtb() previously read and split the complete .cmd file to find the fdtoverlay command. It is changed to read only the first line, so it keeps working once the new field is introduced.

The remaining consumers are not affected:

- Kbuild Makefiles: -include reads .cmd files as Makefile fragments. The new field is an ordinary variable assignment not used in any dependency rule.
- scripts/Makefile.thinlto: the saved_c_flags_* lookup only reads saved_c_flags_<target> := <flags>.
- scripts/mod/modpost.c: extract_crcs_for_object() only reads comments #SYMVER <name> <crc>.
- scripts/mod/sumversion.c: parse_source_files() only reads source_<target> := <source> and deps_<target> := <dependencies>.
- scripts/clang-tools/gen_compile_commands.py: main() only reads the first line containing savedcmd_<target> := <command>.
- scripts/generate_builtin_ranges.awk and scripts/verify_builtin_ranges.awk: get_module_info() only reads the first line and searches the saved command for DKBUILD_MODFILE or RUST_MODFILE.

Alternative: extending the deps_* field
=======================================

An alternative to the new make_prereqs field is to merge $(real-prereqs) into the existing deps_* field for both cmd_and_savecmd and cmd_and_fixdep. This would avoid a new field and provide one dependency list. However, it would broaden the meaning of deps_* from dependencies discovered through generated .d files to include prerequisites already declared to Make. This increases the risk of undesired side effects.

The writers listed above would need to ensure that each .cmd file contains only one deps_* block. In particular, kheaders_data_dep would need to merge its header dependencies into the block written by cmd_and_savecmd instead of appending a second deps_* block. cmd_and_fixdep, or fixdep.c depending on the implementation, would likewise need to merge $(real-prereqs) with the generated dependencies.

Apart from KernelSbom, scripts/mod/sumversion.c is the only consumer that explicitly reads deps_*. It uses selected dependency files to calculate a module's srcversion. Extending deps_* could change this module metadata. Such an unrelated change should probably be avoided.

Kbuild Makefiles also consume deps_* by including .cmd files. This should not be an issue though, because $(real-prereqs) are already present on the original target rule, so repeating them through deps_* should not change rebuild behavior.

SBOM comparison
===============

I compared the SBOMs before and after the series for the same kernel builds on x86 and arm64 allmodconfig. They are ~99% the same. The following files are newly included in the SBOM because the manual parsers did not cover them.

- Linker scripts: *.lds.S sources and the generated *.lds scripts. The old tool never extracted -T arguments, so the whole linker-script chain was missing.

- The intermediate vmlinux link steps: vmlinux.o, .vmlinux.export.c/.o, the realmode pasyms.h. Previously vmlinux.a was hardcoded as an input of scripts/link-vmlinux.sh. Now the real chain vmlinux link -> vmlinux.o -> vmlinux.a is included.

- Per-module .mod object lists: the old tool expanded the .mod file contents in place and recorded the objects directly as link inputs, without explicitly including the .mod file in the SBOM.

- Generated headers: the drm/xe and msm register tables, the aic7xxx sequence tables, the x32 syscall header, and module.lds.h. The old tool found a header only where a .c file actually includes it via the dep file; the new tool records the full make view, including headers that are never included at all.

- Config and header archives: kernel/config_data.gz and kernel/kheaders_data.tar.xz. The old tool missed them because their generation commands had no matching parser.

- Devicetree overlay sources: the .dtso files are now recorded as inputs of the dtb/dtbo build steps. The old tool saw only the temporary files those steps produce, never the sources themselves.

The following files are removed:

- dtc preprocessing scratch files: .dts.tmp, .d.pre.tmp, .d.dtc.tmp. The old tool recorded these temporary build by-products as inputs; the new tool records the real .dtso source instead. This is a cleanup, not a loss.

- Host tooling: the rust toolchain .md docs, the gen_smb1/2_mapping perl generators, and the dtc host tool's libfdt headers. Deliberately excluded. The SBOM should track what ends up in the image or modules, not the tooling that produces it.

Changes in v6:
- strip leading ./ prefixes from deps_* paths in cmd-prereqs.

Changes in v5:
- exclude .awk files from the SBOM
- add an explicit include list for genuine kernel inputs that are covered by the general exclusion rules, for example genuine kernel input files under scripts/ and tools/ directories.
- remove Assisted-by: LLM trailers from the commit messages

Changes in v4:
- fix a bug where excluding src tree dependencies only worked when the object tree was a direct child of the source tree
- fix a bug where non-normalized paths containing '..' segments bypassed the exclude list.

Changes in v3:
- split the changes into individual patches
- include the sbom changes directly in this series instead of deferring it
- add the SBOM comparison section to the cover letter
- Assisted-by trailer follows Documentation/process/coding-assistants.rst

Changes in v2:
- filter depfile entries from make_prereqs in fixdep.c to ensure make_prereqs is consistent between clean and incremental builds. Filtering $(deps_$@) from previous builds is still required to not include deps that got removed in the current depfile.
---

Luis Augenstein (7):
scripts/make_fit: limit .cmd file parsing to the savedcmd_ line
kbuild: refactor fixdep to collect dependencies before printing scripts/sbom: skip make_prereqs lines when parsing .cmd files
kbuild: record cmd-prereqs in .cmd files scripts/sbom: parse make_prereqs from .cmd files scripts/sbom: use make_prereqs to determine build inputs scripts/sbom: remove the command-specific parsers

 Documentation/tools/sbom/sbom.rst             |  23 +-
 scripts/Kbuild.include                        |  10 +-
 scripts/basic/fixdep.c                        | 163 +++++-
 scripts/make_fit.py                           |   2 +-
 scripts/sbom/sbom/cmd_graph/cmd_file.py       | 149 ++---
 scripts/sbom/sbom/cmd_graph/cmd_graph.py      |   6 +-
 scripts/sbom/sbom/cmd_graph/cmd_graph_node.py |  57 +-
 .../sbom/sbom/cmd_graph/dependency_filter.py  | 109 ++++
 .../sbom/cmd_graph/hardcoded_dependencies.py  |   1 -
 .../cmd_graph/savedcmd_parser/__init__.py     |   6 -
 .../command_parser_registry.py                | 516 ------------------
 .../savedcmd_parser/command_splitter.py       | 128 -----
 .../savedcmd_parser/savedcmd_parser.py        |  67 ---
 .../cmd_graph/savedcmd_parser/tokenizer.py    |  92 ----
 scripts/sbom/sbom/config.py                   |  14 -
 scripts/sbom/sbom/spdx_graph/kernel_file.py   |  63 ++-
 .../tests/cmd_graph/test_savedcmd_parser.py   | 468 ----------------
 17 files changed, 376 insertions(+), 1498 deletions(-)
 create mode 100644 scripts/sbom/sbom/cmd_graph/dependency_filter.py
 delete mode 100644 scripts/sbom/sbom/cmd_graph/savedcmd_parser/__init__.py
 delete mode 100644 scripts/sbom/sbom/cmd_graph/savedcmd_parser/command_parser_registry.py
 delete mode 100644 scripts/sbom/sbom/cmd_graph/savedcmd_parser/command_splitter.py
 delete mode 100644 scripts/sbom/sbom/cmd_graph/savedcmd_parser/savedcmd_parser.py
 delete mode 100644 scripts/sbom/sbom/cmd_graph/savedcmd_parser/tokenizer.py
 delete mode 100644 scripts/sbom/tests/cmd_graph/test_savedcmd_parser.py
Signature · 1 line
2.43.0
author maintainer
#1 lore raw

PATCH v6 1/7 scripts/make_fit: limit .cmd file parsing to the savedcmd_ line

The command is always stored in the first line of the .cmd file. Read only the first line, so remaining lines cannot get misparsed once .cmd files record additional fields.

---
 scripts/make_fit.py | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)
scripts/make_fit.py +1 -1
index 9bd35aa7211..38ef9a95dd3 100755
@@ -288,7 +288,7 @@ def process_dtb(fname, args):
         path, basename = os.path.split(fname)
         cmd_fname = os.path.join(path, f'.{basename}.cmd')
         with open(cmd_fname, 'r', encoding='ascii') as inf:
-            cmd = inf.read()
+            cmd = inf.readline()
 
         if 'scripts/dtc/fdtoverlay' in cmd:
             # This depends on the structure of the composite DTB command
Signature · 1 line
2.43.0
author maintainer
#2 lore raw

PATCH v6 2/7 kbuild: refactor fixdep to collect dependencies before printing

In reply to Luis Augenstein

fixdep currently writes the .cmd file content while parsing the .dep file. Separate the parsing from the printing: parse_dep_file() now collects the source file and all dependencies in a list, and print_dep_file() emits the assignments afterwards. No functional change intended.

---
 scripts/basic/fixdep.c | 109 ++++++++++++++++++++++++++++++++++-------
 1 file changed, 92 insertions(+), 17 deletions(-)
scripts/basic/fixdep.c +92 -17
index 54063d98044..f514ef606ec 100644
@@ -114,6 +114,17 @@ struct item {
 	char		name[];
 };
 
+struct dep_item {
+	struct dep_item	*next;
+	char		name[];
+};
+
+struct dep_info {
+	char			*source;
+	struct dep_item		*deps;
+	struct dep_item		*last_dep;
+};
+
 #define HASHSZ 256
 static struct item *config_hashtab[HASHSZ], *file_hashtab[HASHSZ];
 
@@ -163,16 +174,42 @@ static bool in_hashtable(const char *name, int len, struct item *hashtab[])
 	return false;
 }
 
+/*
+ * Append a dependency or include/config/<SYM> path to the info linked list.
+ */
+static void dep_info_add(struct dep_info *info, const char *name, int len)
+{
+	struct dep_item *dep = xmalloc(sizeof(*dep) + len + 1);
+
+	memcpy(dep->name, name, len);
+	dep->name[len] = '\0';
+	dep->next = NULL;
+
+	if (info->last_dep)
+		info->last_dep->next = dep;
+	else
+		info->deps = dep;
+	info->last_dep = dep;
+}
+
 /*
  * Record the use of a CONFIG_* word.
  */
-static void use_config(const char *m, int slen)
+static void use_config(const char *m, int slen, struct dep_info *info)
 {
 	if (in_hashtable(m, slen, config_hashtab))
 		return;
 
-	/* Print out a dependency path from a symbol name. */
-	printf("    $(wildcard include/config/%.*s) \\\n", slen, m);
+	/* Build a dependency path from a symbol name. */
+	static const char config_path[] = "include/config/";
+	char *path;
+	int path_len = sizeof(config_path) - 1 + slen;
+
+	path = xmalloc(path_len);
+	memcpy(path, config_path, sizeof(config_path) - 1);
+	memcpy(path + sizeof(config_path) - 1, m, slen);
+	dep_info_add(info, path, path_len);
+	free(path);
 }
 
 /* test if s ends in sub */
@@ -186,7 +223,12 @@ static int str_ends_with(const char *s, int slen, const char *sub)
 	return !memcmp(s + slen - sublen, sub, sublen);
 }
 
-static void parse_config_file(const char *p)
+/*
+ * Scan dependency p for CONFIG_ words, map each to an
+ * include/config/ path and append to the dep_info list if not
+ * already included.
+ */
+static void parse_config_file(const char *p, struct dep_info *info)
 {
 	const char *q, *r;
 	const char *start = p;
@@ -205,7 +247,7 @@ static void parse_config_file(const char *p)
 		else
 			r = q;
 		if (r > p)
-			use_config(p, r - p);
+			use_config(p, r - p, info);
 		p = q;
 	}
 }
@@ -253,13 +295,9 @@ static int is_no_parse_file(const char *s, int len)
 	       str_ends_with(s, len, ".so");
 }
 
-/*
- * Important: The below generated source_foo.o and deps_foo.o variable
- * assignments are parsed not only by make, but also by the rather simple
- * parser in scripts/mod/sumversion.c.
- */
-static void parse_dep_file(char *p, const char *target)
+static struct dep_info parse_dep_file(char *p)
 {
+	struct dep_info info = {};
 	bool saw_any_target = false;
 	bool is_target = true;
 	bool is_source = false;
@@ -375,13 +413,12 @@ static void parse_dep_file(char *p, const char *target)
 			 */
 			if (!saw_any_target) {
 				saw_any_target = true;
-				printf("source_%s := %s\n\n", target, p);
-				printf("deps_%s := \\\n", target);
+				info.source = xstrdup(p);
 				need_parse = true;
 			}
 		} else if (!is_ignored_file(p, q - p) &&
 			   !in_hashtable(p, q - p, file_hashtab)) {
-			printf("  %s \\\n", p);
+			dep_info_add(&info, p, q - p);
 			need_parse = true;
 		}
 
@@ -389,7 +426,7 @@ static void parse_dep_file(char *p, const char *target)
 			void *buf;
 
 			buf = read_file(p);
-			parse_config_file(buf);
+			parse_config_file(buf, &info);
 			free(buf);
 		}
 
@@ -403,6 +440,40 @@ static void parse_dep_file(char *p, const char *target)
 		exit(1);
 	}
 
+	return info;
+}
+
+static void free_dep_info(struct dep_info *info)
+{
+	struct dep_item *dep, *next;
+
+	for (dep = info->deps; dep; dep = next) {
+		next = dep->next;
+		free(dep);
+	}
+	free(info->source);
+}
+
+/*
+ * Important: The below generated source_foo.o and deps_foo.o variable
+ * assignments are parsed not only by make, but also by the rather simple
+ * parser in scripts/mod/sumversion.c.
+ */
+static void print_dep_file(const char *target, const struct dep_info *info)
+{
+	static const char config_path[] = "include/config/";
+	const struct dep_item *dep;
+
+	printf("source_%s := %s\n\n", target, info->source);
+	printf("deps_%s := \\\n", target);
+
+	for (dep = info->deps; dep; dep = dep->next) {
+		if (!strncmp(dep->name, config_path, sizeof(config_path) - 1))
+			printf("    $(wildcard %s) \\\n", dep->name);
+		else
+			printf("  %s \\\n", dep->name);
+	}
+
 	printf("\n%s: $(deps_%s)\n\n", target, target);
 	printf("$(deps_%s):\n", target);
 }
@@ -410,6 +481,7 @@ static void parse_dep_file(char *p, const char *target)
 int main(int argc, char *argv[])
 {
 	const char *depfile, *target, *cmdline;
+	struct dep_info info;
 	void *buf;
 
 	if (argc != 4)
@@ -419,10 +491,13 @@ int main(int argc, char *argv[])
 	target = argv[2];
 	cmdline = argv[3];
 
+	buf = read_file(depfile);
+	info = parse_dep_file(buf);
+
 	printf("savedcmd_%s := %s\n\n", target, cmdline);
+	print_dep_file(target, &info);
 
-	buf = read_file(depfile);
-	parse_dep_file(buf, target);
+	free_dep_info(&info);
 	free(buf);
 
 	fflush(stdout);
Signature · 1 line
2.43.0
author maintainer
#3 lore raw

PATCH v6 3/7 scripts/sbom: skip make_prereqs lines when parsing .cmd files

In reply to Luis Augenstein

kbuild will record the prerequisites of a target in a new make_prereqs_<target> field in .cmd files. Skip such lines so the parser keeps working once the field is introduced.

---
 scripts/sbom/sbom/cmd_graph/cmd_file.py | 4 ++++
 1 file changed, 4 insertions(+)
scripts/sbom/sbom/cmd_graph/cmd_file.py +4 -0
index dcd63e284a3..08819b4d117 100644
@@ -50,6 +50,10 @@ class CmdFile:
         with open(cmd_file_path, "rt", encoding="utf-8") as f:
             lines = [line.strip() for line in f.readlines() if line.strip() != "" and not line.startswith("#")]
 
+        # make_prereqs_* is recorded for future use. Ignore it for now to
+        # preserve the existing parser behavior.
+        lines = [line for line in lines if not line.startswith("make_prereqs_")]
+
         # savedcmd
         match = SAVEDCMD_PATTERN.match(lines[0] if lines else "")
         if match is None:
Signature · 1 line
2.43.0
author maintainer
#4 lore raw

PATCH v6 4/7 kbuild: record cmd-prereqs in .cmd files

In reply to Luis Augenstein

Record $(cmd-prereqs), i.e. $(real-prereqs) with the deps_* dependencies filtered out, in a new .cmd file metadata field:

make_prereqs_<target> := <prerequisites>

On an incremental build, deps_<target> holds the dependencies recorded from the depfile of the previous build. Those are filtered out from $(real-prereqs), even if they no longer appear in the current depfile. fixdep additionally filters the dependencies collected from the current depfile, so that they are not recorded in both deps_<target> and make_prereqs_<target>. This keeps the field consistent between clean and incremental builds.

---
 scripts/Kbuild.include | 10 ++++++--
 scripts/basic/fixdep.c | 54 +++++++++++++++++++++++++++++++++++++-----
 2 files changed, 56 insertions(+), 8 deletions(-)
scripts/Kbuild.include +8 -2
index 8c311b997e2..94a0711b669 100644
@@ -181,6 +181,9 @@ endif
 # (needed for the shell)
 make-cmd = $(call escsq,$(subst $(pound),$$(pound),$(subst $$,$$$$,$(cmd_$(1)))))
 
+# prerequisites to record in .cmd files, excluding those covered in deps_*
+cmd-prereqs = $(call escsq,$(filter-out $(patsubst ./%,%,$(deps_$@)), $(real-prereqs)))
+
 # Find any prerequisites that are newer than target or that do not exist.
 # PHONY targets skipped in both cases.
 # If there is no prerequisite other than phony targets, $(newer-prereqs) becomes
@@ -198,14 +201,17 @@ if_changed = $(if $(if-changed-cond),$(cmd_and_savecmd),@:)
 
 cmd_and_savecmd =                                                            \
 	$(cmd);                                                              \
-	printf '%s\n' 'savedcmd_$@ := $(make-cmd)' > $(dot-target).cmd
+	printf '%s\n'                                                        \
+		'savedcmd_$@ := $(make-cmd)' ''                              \
+		'make_prereqs_$@ := $(cmd-prereqs)' > $(dot-target).cmd
 
 # Execute the command and also postprocess generated .d dependencies file.
 if_changed_dep = $(if $(if-changed-cond),$(cmd_and_fixdep),@:)
 
 cmd_and_fixdep =                                                             \
 	$(cmd);                                                              \
-	$(objtree)/scripts/basic/fixdep $(depfile) $@ '$(make-cmd)' > $(dot-target).cmd;\
+	$(objtree)/scripts/basic/fixdep $(depfile) $@ '$(make-cmd)'          \
+		'$(cmd-prereqs)' > $(dot-target).cmd;                        \
 	rm -f $(depfile)
 
 # Usage: $(call if_changed_rule,foo)
scripts/basic/fixdep.c +48 -6

93 lines not on this page · raw message

Signature · 1 line
2.43.0
#5 lore raw
Thank you for your contribution! Sashiko AI review found 1 potential issue to consider: - [Low] kbuild: fixdep: strip leading ./ from dep->name in print_make_prereqs() --

Thank you for your contribution! Sashiko AI review found 1 potential issue to consider:
- [Low] kbuild: fixdep: strip leading ./ from dep->name in print_make_prereqs()
--

commit 893f80d84c71797a734bc7704bb47fc515aee146
Author: Luis Augenstein <[email protected]>

kbuild: record cmd-prereqs in .cmd files

This commit records prerequisites not covered by deps_<target> as make_prereqs_<target> in .cmd files and teaches fixdep to filter out dependencies from the current depfile.

Quoted 11 lines
scripts/Kbuild.include +3 -0
index 8c311b997e246..94a0711b66934 100644
@@ -181,6 +181,9 @@ endif
 # (needed for the shell)
 make-cmd = $(call escsq,$(subst $(pound),$$(pound),$(subst $$,$$$$,$(cmd_$(1)))))
 
+# prerequisites to record in .cmd files, excluding those covered in deps_*
+cmd-prereqs = $(call escsq,$(filter-out $(patsubst ./%,%,$(deps_$@)), $(real-prereqs)))
+

[ ... ]

Quoted 4 lines
scripts/basic/fixdep.c +0 -0
index f514ef606ec63..005c1c3df494a 100644

[ ... ]

Quoted 8 lines
scripts/basic/fixdep.c +4 -0
@@ -478,23 +480,63 @@ static void print_dep_file(const char *target, const struct dep_info *info)
 	printf("$(deps_%s):\n", target);
 }
 
+/*
+ * Print make_prereqs_<target> from prereqs, excluding the deps listed
+ * in info.
+ */

scripts/basic/fixdep.c static void print_dep_file(const char *target, const struct dep_info *info) · line 496

Quoted 10 lines
scripts/basic/fixdep.c +10 -0
+static void print_make_prereqs(const char *target, const char *prereqs,
+			       const struct dep_info *info)
+{
+	struct item *seen_prereqs_hashtab[HASHSZ] = {};
+	const struct dep_item *dep;
+	const char *p = prereqs;
+
+	for (dep = info->deps; dep; dep = dep->next)
+		in_hashtable(dep->name, strlen(dep->name),
+			     seen_prereqs_hashtab);

[Severity: Low]
Should print_make_prereqs() strip a leading "./" from dep->name before inserting it into seen_prereqs_hashtab?

Make strips leading "./" from prerequisites in $(real-prereqs), whereas compiler depfiles record paths under -I./include (and similar flags using $(objtree) or $(srctree) when set to ".") with a leading "./". On a clean build, those dep->name entries will not match the tokens in prereqs and will be recorded in both make_prereqs_<target> and deps_<target>, while an incremental build filters them out via $(patsubst ./%,%,$(deps_$@)) in cmd-prereqs.

Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=4
author maintainer
#6 lore raw
Quoted 11 lines · On 11/20/26 21:45, [email protected] wrote:

[Severity: Low]
Should print_make_prereqs() strip a leading "./" from dep->name before inserting it into seen_prereqs_hashtab?

Make strips leading "./" from prerequisites in $(real-prereqs), whereas compiler depfiles record paths under -I./include (and similar flags using $(objtree) or $(srctree) when set to ".") with a leading "./". On a clean build, those dep->name entries will not match the tokens in prereqs and will be recorded in both make_prereqs_<target> and deps_<target>, while an incremental build filters them out via $(patsubst ./%,%,$(deps_$@)) in cmd-prereqs.

This is not an issue.

Depfiles consumed by fixdep do not contain a "./"-prefix. The only observed "./"-prefixed deps are in kernel/.kheaders_data.tar.xz.cmd. That file is generated by cmd_and_savecmd, with its depfile appended afterward by a custom rule. It does not use fixdep. So this does not justify changing fixdep.

cmd-prereqs only strips leading "./" so that incremental builds filter the appended deps_ out of make_prereqs_. Without it, cmd_and_savecmd would duplicate those paths and break the build as described in my v5 response.

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

PATCH v6 5/7 scripts/sbom: parse make_prereqs from .cmd files

In reply to Luis Augenstein

Add support for parsing the make_prereqs_<target> field recorded by kbuild in .cmd files.

Refactor CmdFile.create() to collect the required fields by name instead of deriving the file structure from the number of lines and the position.

The source_ entry is no longer parsed, because it is always also included in make_prereqs_<target> and therefore redundant for KernelSbom.

---
 scripts/sbom/sbom/cmd_graph/cmd_file.py | 103 +++++++++---------------
 1 file changed, 36 insertions(+), 67 deletions(-)
scripts/sbom/sbom/cmd_graph/cmd_file.py +36 -67
index 08819b4d117..cc576c7c6be 100644
@@ -10,97 +10,66 @@ import sbom.sbom_logging as sbom_logging
 from sbom.path_utils import PathStr
 
 SAVEDCMD_PATTERN = re.compile(r"^(saved)?cmd_.*?:=\s*(?P<full_command>.+)$")
-SOURCE_PATTERN = re.compile(r"^source.*?:=\s*(?P<source_file>.+)$")
+MAKE_PREREQS_PATTERN = re.compile(r"^make_prereqs_.*?:=\s*(?P<prereqs>.+)$")
+DEPS_ASSIGNMENT_PATTERN = re.compile(r"^deps_.*?:=")
 
 
 @dataclass
 class CmdFile:
     cmd_file_path: PathStr
     savedcmd: str
-    source: PathStr | None = None
+    make_prereqs: list[str] = field(default_factory=list)
     deps: list[str] = field(default_factory=list)
-    make_rules: list[str] = field(default_factory=list)
 
     @classmethod
     def create(cls, cmd_file_path: PathStr) -> "CmdFile | None":
-        """
-        Parses a .cmd file.
-        .cmd files are assumed to have one of the following structures:
-        1. Full Cmd File
-            (saved)?cmd_<output> := <command>
-            source_<output> := <main_input>
-            deps_<output> := \
-            <dependencies>
-            <output> := $(deps_<output>)
-            $(deps_<output>):
-
-        2. Command Only Cmd File
-            (saved)?cmd_<output> := <command>
-
-        3. Single Dependency Cmd File
-            (saved)?cmd_<output> := <command>
-            <output> : <dependency>
+        r"""
+        Parse the following fields from a `.cmd` file:
+
+        * `(saved)?cmd_<target> := <shell command>` (required) —
+          the shell command Kbuild ran to produce the build target.
+        * `make_prereqs_<target> := <prerequisites>` (required but can be empty) —
+          the non-phony make prerequisites.
+        * `deps_<target> := \` (optional) —
+          additional dependencies not covered by make prerequisites, e.g., headers.
 
         Args:
-            cmd_file_path (Path): absolute Path to a .cmd file
+            cmd_file_path (Path): absolute Path to a `.cmd` file.
 
         Returns:
-            cmd_file (CmdFile): Parsed cmd file.
+            cmd_file (CmdFile): Parsed `.cmd` file or `None` if no `savedcmd` line was found.
         """
         with open(cmd_file_path, "rt", encoding="utf-8") as f:
             lines = [line.strip() for line in f.readlines() if line.strip() != "" and not line.startswith("#")]
 
-        # make_prereqs_* is recorded for future use. Ignore it for now to
-        # preserve the existing parser behavior.
-        lines = [line for line in lines if not line.startswith("make_prereqs_")]
+        savedcmd: str | None = None
+        make_prereqs: list[str] = []
+        deps: list[str] = []
+
+        for i, line in enumerate(lines):
+            match = SAVEDCMD_PATTERN.match(line)
+            if match is not None:
+                savedcmd = match.group("full_command")
+                continue
+
+            match = MAKE_PREREQS_PATTERN.match(line)
+            if match is not None:
+                make_prereqs = match.group("prereqs").split()
+                continue
 
-        # savedcmd
-        match = SAVEDCMD_PATTERN.match(lines[0] if lines else "")
-        if match is None:
+            if DEPS_ASSIGNMENT_PATTERN.match(line):
+                j = i + 1
+                while j < len(lines) and lines[j].endswith("\\"):
+                    deps.append(lines[j].removesuffix("\\").strip())
+                    j += 1
+
+        if savedcmd is None:
             sbom_logging.error(
                 "Skip parsing '{cmd_file_path}' because no 'savedcmd_' command was found.", cmd_file_path=cmd_file_path
             )
             return None
-        savedcmd = match.group("full_command")
-
-        # Command Only Cmd File
-        if len(lines) == 1:
-            return CmdFile(cmd_file_path, savedcmd)
-
-        # Single Dependency Cmd File
-        if len(lines) == 2:
-            parts = lines[1].split(":", 1)
-            if len(parts) != 2:
-                sbom_logging.error(
-                    "Skip parsing '{cmd_file_path}'. Expected dependency line '<output>: <dependency>' but got {second_line}", cmd_file_path=cmd_file_path, second_line=lines[1]
-                )
-                return None
-            dep = parts[1].strip()
-            return CmdFile(cmd_file_path, savedcmd, deps=[dep])
-
-        # Full Cmd File
-        # source
-        line1 = SOURCE_PATTERN.match(lines[1])
-        if line1 is None:
-            sbom_logging.error(
-                "Skip parsing '{cmd_file_path}' because no 'source_' entry was found.", cmd_file_path=cmd_file_path
-            )
-            return CmdFile(cmd_file_path, savedcmd)
-        source = line1.group("source_file")
-
-        # deps
-        deps: list[str] = []
-        i = 3  # lines[2] includes the variable assignment but no actual dependency, so we need to start at lines[3].
-        while i < len(lines):
-            if not lines[i].endswith("\\"):
-                break
-            deps.append(lines[i][:-1].strip())
-            i += 1
-
-        # make_rules
-        make_rules = lines[i:]
 
-        return CmdFile(cmd_file_path, savedcmd, source, deps, make_rules)
+        return CmdFile(cmd_file_path, savedcmd, make_prereqs, deps)
 
     def get_dependencies(
         self: "CmdFile", target_path: PathStr, obj_tree: PathStr, fail_on_unknown_build_command: bool
Signature · 1 line
2.43.0
author maintainer
#8 lore raw

PATCH v6 6/7 scripts/sbom: use make_prereqs to determine build inputs

In reply to Luis Augenstein

Build the list of file dependencies of a target from the make_prereqs_<target> field and the deps_<target> entries of the .cmd file instead of parsing the shell command stored in savedcmd_.

The prerequisites include more than KernelSbom wants to track: files should be tracked if they end up in the kernel image or loadable modules, but not each and every host tool or helper script used to build them. Add a manually maintained exclude list for such dependencies. It is still manual, but much easier to maintain than the command-specific parsers that were needed to extract the relevant inputs from each individual build command.

---
 scripts/sbom/sbom/cmd_graph/cmd_file.py       |  47 +-------
 scripts/sbom/sbom/cmd_graph/cmd_graph.py      |   6 +-
 scripts/sbom/sbom/cmd_graph/cmd_graph_node.py |  56 ++++-----
 .../sbom/sbom/cmd_graph/dependency_filter.py  | 109 ++++++++++++++++++
 scripts/sbom/sbom/spdx_graph/kernel_file.py   |  63 ++++++----
 5 files changed, 187 insertions(+), 94 deletions(-)
 create mode 100644 scripts/sbom/sbom/cmd_graph/dependency_filter.py
scripts/sbom/sbom/cmd_graph/cmd_file.py +4 -43
index cc576c7c6be..58ca6aa5946 100644
@@ -5,7 +5,6 @@ import os
 import re
 from dataclasses import dataclass, field
 from sbom.cmd_graph.deps_parser import parse_cmd_file_deps
-from sbom.cmd_graph.savedcmd_parser import parse_inputs_from_commands
 import sbom.sbom_logging as sbom_logging
 from sbom.path_utils import PathStr
 
@@ -71,65 +70,27 @@ class CmdFile:
 
         return CmdFile(cmd_file_path, savedcmd, make_prereqs, deps)
 
-    def get_dependencies(
-        self: "CmdFile", target_path: PathStr, obj_tree: PathStr, fail_on_unknown_build_command: bool
-    ) -> list[PathStr]:
+    def get_dependencies(self: "CmdFile", obj_tree: PathStr) -> list[PathStr]:
         """
         Parses all dependencies required to build a target file from its cmd file.
 
         Args:
-            target_path: path to the target file relative to `obj_tree`.
             obj_tree: absolute path to the object tree.
             fail_on_unknown_build_command: Whether to fail if an unknown build command is encountered.
 
         Returns:
             list[PathStr]: dependency file paths relative to `obj_tree`.
         """
-        input_files: list[PathStr] = [
-            str(p) for p in parse_inputs_from_commands(self.savedcmd, fail_on_unknown_build_command)
-        ]
+        input_files: list[PathStr] = list(self.make_prereqs)
+
         if self.deps:
             input_files += [str(p) for p in parse_cmd_file_deps(self.deps)]
-        input_files = _expand_resolve_files(input_files, obj_tree)
 
         cmd_file_dependencies: list[PathStr] = []
         for input_file in input_files:
-            # input files are either absolute or relative to the object tree
+            # input files are either absolute or already relative to the object tree
             if os.path.isabs(input_file):
                 input_file = os.path.relpath(input_file, obj_tree)
-            if input_file == target_path:
-                # Skip target file to prevent cycles. This is necessary because some multi stage commands first create an output and then pass it as input to the next command, e.g., objcopy.
-                continue
             cmd_file_dependencies.append(input_file)
         unique_cmd_file_dependencies = list(dict.fromkeys(cmd_file_dependencies))
         return unique_cmd_file_dependencies
-
-
-def _expand_resolve_files(input_files: list[PathStr], obj_tree: PathStr) -> list[PathStr]:
-    """
-    Expands resolve files which may reference additional files via '@' notation.
-
-    Args:
-        input_files (list[PathStr]): List of file paths relative to the object tree, where paths starting with '@' refer to files
-                                     containing further file paths, each on a separate line.
-        obj_tree: Absolute path to the root of the object tree.
-
-    Returns:
-        list[PathStr]: Flattened list of all input file paths, with any nested '@' file references resolved recursively.
-    """
-    expanded_input_files: list[PathStr] = []
-    for input_file in input_files:
-        if not input_file.startswith("@"):
-            expanded_input_files.append(input_file)
-            continue
-        resolve_file_path = os.path.join(obj_tree, input_file.removeprefix("@"))
-        if not os.path.exists(resolve_file_path):
-            sbom_logging.error(
-                "Skip resolving '{resolve_file_path}' because the response file does not exist.",
-                resolve_file_path=resolve_file_path,
-            )
-            continue
-        with open(resolve_file_path, "rt", encoding="utf-8") as f:
-            resolve_file_content = [line_stripped for line in f.readlines() if (line_stripped := line.strip())]
-        expanded_input_files += _expand_resolve_files(resolve_file_content, obj_tree)
-    return expanded_input_files
scripts/sbom/sbom/cmd_graph/cmd_graph.py +5 -1
index 2f57965237f..f511167de00 100644
@@ -3,6 +3,7 @@
 
 from collections import deque
 from dataclasses import dataclass, field
+import os
 from typing import Iterator
 
 from sbom.cmd_graph.cmd_graph_node import CmdGraphNode, CmdGraphNodeConfig
@@ -29,7 +30,10 @@ class CmdGraph:
             CmdGraph: A graph of all build dependencies for the given root files.
         """
         node_cache: dict[PathStr, CmdGraphNode] = {}
-        root_nodes = [CmdGraphNode.create(root_path, config, node_cache) for root_path in root_paths]
+        root_nodes = [
+            CmdGraphNode.create(os.path.realpath(os.path.join(config.obj_tree, root_path)), config, node_cache)
+            for root_path in root_paths
+        ]
         return CmdGraph(root_nodes)
 
     def __iter__(self) -> Iterator[CmdGraphNode]:
scripts/sbom/sbom/cmd_graph/cmd_graph_node.py +30 -26

105 lines not on this page · raw message

scripts/sbom/sbom/cmd_graph/dependency_filter.py new file +109 -0

109 lines not on this page · raw message

scripts/sbom/sbom/spdx_graph/kernel_file.py +39 -24

91 lines not on this page · raw message

Signature · 1 line
2.43.0
author maintainer
#9 lore raw

PATCH v6 7/7 scripts/sbom: remove the command-specific parsers

In reply to Luis Augenstein

With the build inputs taken from make_prereqs_ and deps_, the command-specific parsers are no longer needed. Remove them, and with them the --do-not-fail-on-unknown-build-command option, which only existed to tolerate build commands that the parsers did not support.

---
 Documentation/tools/sbom/sbom.rst             |  23 +-
 scripts/sbom/sbom/cmd_graph/cmd_file.py       |   1 -
 scripts/sbom/sbom/cmd_graph/cmd_graph_node.py |   1 -
 .../sbom/cmd_graph/hardcoded_dependencies.py  |   1 -
 .../cmd_graph/savedcmd_parser/__init__.py     |   6 -
 .../command_parser_registry.py                | 516 ------------------
 .../savedcmd_parser/command_splitter.py       | 128 -----
 .../savedcmd_parser/savedcmd_parser.py        |  67 ---
 .../cmd_graph/savedcmd_parser/tokenizer.py    |  92 ----
 scripts/sbom/sbom/config.py                   |  14 -
 .../tests/cmd_graph/test_savedcmd_parser.py   | 468 ----------------
 11 files changed, 3 insertions(+), 1314 deletions(-)
 delete mode 100644 scripts/sbom/sbom/cmd_graph/savedcmd_parser/__init__.py
 delete mode 100644 scripts/sbom/sbom/cmd_graph/savedcmd_parser/command_parser_registry.py
 delete mode 100644 scripts/sbom/sbom/cmd_graph/savedcmd_parser/command_splitter.py
 delete mode 100644 scripts/sbom/sbom/cmd_graph/savedcmd_parser/savedcmd_parser.py
 delete mode 100644 scripts/sbom/sbom/cmd_graph/savedcmd_parser/tokenizer.py
 delete mode 100644 scripts/sbom/tests/cmd_graph/test_savedcmd_parser.py
Documentation/tools/sbom/sbom.rst +3 -20
index 029b08b6ad8..1ab32c57fa6 100644
@@ -121,9 +121,9 @@ from multiple sources:
 
 * **.cmd files**: The primary source is the ``.cmd`` file of the
   generated artifact, e.g., ``arch/x86/boot/.bzImage.cmd``. These files
-  contain the exact command used to build the artifact and often include
-  an explicit list of input dependencies. By parsing the ``.cmd``
-  file, the full list of dependencies can be obtained.
+  record the shell command used to build the artifact, the make
+  prerequisites (``make_prereqs_*``), and, for compiler-generated targets,
+  additional dependencies (``deps_*``) like header files.
 
 * **.incbin statements**: The second source are include binary
   ``.incbin`` statements in ``.S`` assembly files.
@@ -187,20 +187,3 @@ In this scenario, KernelSbom does not produce a dedicated
 ``sbom-source.spdx.json`` document. Instead, both source files and build
 artifacts are included together in ``sbom-build.spdx.json``, and
 ``sbom.used-files.txt`` lists all files referenced in the build document.
-
-Unknown Build Commands
-~~~~~~~~~~~~~~~~~~~~~~
-
-Because the kernel supports a wide range of configurations and versions,
-KernelSbom may encounter build commands in ``.cmd`` files that it does
-not yet support. By default, KernelSbom will fail if an unknown build
-command is encountered.
-
-If you still wish to generate SPDX documents despite unsupported
-commands, you can use the ``--do-not-fail-on-unknown-build-command``
-option. KernelSbom will continue and produce the documents, although
-the resulting SBOM will be incomplete.
-
-This option should only be used when the missing portion of the
-dependency graph is small and an incomplete SBOM is acceptable for
-your use case.
scripts/sbom/sbom/cmd_graph/cmd_file.py +0 -1
index 58ca6aa5946..648404efec3 100644
@@ -76,7 +76,6 @@ class CmdFile:
 
         Args:
             obj_tree: absolute path to the object tree.
-            fail_on_unknown_build_command: Whether to fail if an unknown build command is encountered.
 
         Returns:
             list[PathStr]: dependency file paths relative to `obj_tree`.
scripts/sbom/sbom/cmd_graph/cmd_graph_node.py +0 -1
index c608cb1ca82..dea257b2251 100644
@@ -24,7 +24,6 @@ class IncbinDependency:
 class CmdGraphNodeConfig(Protocol):
     obj_tree: PathStr
     src_tree: PathStr
-    fail_on_unknown_build_command: bool
 
 
 @dataclass
scripts/sbom/sbom/cmd_graph/hardcoded_dependencies.py +0 -1
index 2eb04d30f4e..f911fc6f23a 100644
@@ -10,7 +10,6 @@ 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"],
 }
scripts/sbom/sbom/cmd_graph/savedcmd_parser/__init__.py deleted +0 -6
deleted file mode 100644
index d13876af4df..00000000000
@@ -1,6 +0,0 @@
-# SPDX-License-Identifier: GPL-2.0-only OR MIT
-# Copyright (C) 2025 TNG Technology Consulting GmbH
-
-from sbom.cmd_graph.savedcmd_parser.savedcmd_parser import parse_inputs_from_commands
-
-__all__ = ["parse_inputs_from_commands"]
scripts/sbom/sbom/cmd_graph/savedcmd_parser/command_parser_registry.py deleted +0 -516

516 lines not on this page · raw message

scripts/sbom/sbom/cmd_graph/savedcmd_parser/command_splitter.py deleted +0 -128

128 lines not on this page · raw message

scripts/sbom/sbom/cmd_graph/savedcmd_parser/savedcmd_parser.py deleted +0 -67

67 lines not on this page · raw message

scripts/sbom/sbom/cmd_graph/savedcmd_parser/tokenizer.py deleted +0 -92

92 lines not on this page · raw message

scripts/sbom/sbom/config.py +0 -14
index 6811f782943..08474c2bfc3 100644
@@ -47,9 +47,6 @@ class KernelSbomConfig:
     debug: bool
     """Whether to enable debug logging."""
 
-    fail_on_unknown_build_command: bool
-    """Whether to fail if an unknown build command is encountered in a .cmd file."""
-
     write_output_on_error: bool
     """Whether to write output documents even if errors occur."""
 
@@ -141,15 +138,6 @@ def _parse_cli_arguments(parser: argparse.ArgumentParser) -> dict[str, Any]:
     )
 
     # Error handling settings
-    parser.add_argument(
-        "--do-not-fail-on-unknown-build-command",
-        action="store_true",
-        default=False,
-        help=(
-            "Whether to fail if an unknown build command is encountered in a .cmd file.\n"
-            "If set to True, errors are logged as warnings instead. (default: False)"
-        ),
-    )
     parser.add_argument(
         "--write-output-on-error",
         action="store_true",
@@ -245,7 +233,6 @@ def get_config() -> KernelSbomConfig:
     output_directory = os.path.realpath(args["output_directory"])
     debug = args["debug"]
 
-    fail_on_unknown_build_command = not args["do_not_fail_on_unknown_build_command"]
     write_output_on_error = args["write_output_on_error"]
 
     created = datetime.fromtimestamp(
@@ -283,7 +270,6 @@ def get_config() -> KernelSbomConfig:
         used_files_file_name=used_files_file_name,
         output_directory=output_directory,
         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,
scripts/sbom/tests/cmd_graph/test_savedcmd_parser.py deleted +0 -468

468 lines not on this page · raw message

Signature · 1 line
2.43.0