Skip to contentSkip to conversation

objtool/klp: sympos/module/alternative/etc fixes

PATCH Applied Josh Poimboeuf 6 participants 36 messages Aug 3 – Aug 14

Subsystems (5)

v1 of 3 Applied Latest is v3 →

lore
Share & tools
lore

Josh Poimboeuf

author maintainer
#0 lore raw

cover objtool/klp: sympos/module/alternative/etc fixes

This consolidates fixes for the klp-build issues reported by Joe over the last several weeks, plus some more things I found while testing/reviewing.

Fun stuff like symbol resolution, module dependencies, alternatives.

MODULE MAINTAINERS: see patches 7 and 8, you can probably ignore the rest.

Joe Lawrence (2):
objtool/klp: Normalize Module.symvers paths to module names objtool/klp: Allow new references to module exports

Josh Poimboeuf (12):
objtool/klp: Fix module name normalization for paths with dots objtool/klp: Fix false module dependencies caused by dead relocs objtool/klp: Skip hidden directories when finding objects objtool/klp: Add .klp.symid for sympos disambiguation objtool/klp: Fix symbol resolution for duplicate data symbols
module: Add module_kallsyms_on_each_core_symbol() objtool/klp,livepatch: Resolve module symbols against core kallsyms objtool/klp: Fix size of empty special section entries objtool/klp: Ignore replacement offset of empty x86 alternatives objtool/klp: Explicitly disallow patching or referencing init
code/data
objtool/klp: Fix cross-module klp relocation section naming objtool/klp: Don't match local symbols against exports

 include/asm-generic/vmlinux.lds.h       |  10 +-
 include/linux/module.h                  |  11 +
 kernel/livepatch/core.c                 |   2 +-
 kernel/module/kallsyms.c                |  46 +++
 scripts/Makefile.vmlinux_o              |   3 +
 scripts/livepatch/klp-build             |  17 +-
 scripts/mod/modpost.c                   |   1 +
 tools/objtool/Build                     |   4 +-
 tools/objtool/arch/x86/special.c        |  27 ++
 tools/objtool/builtin-check.c           |   7 +
 tools/objtool/check.c                   |   7 +
 tools/objtool/elf.c                     |  13 +
 tools/objtool/include/objtool/builtin.h |   1 +
 tools/objtool/include/objtool/klp.h     |  32 +-
 tools/objtool/include/objtool/special.h |   7 +
 tools/objtool/klp-diff.c                | 192 ++++++-----
 tools/objtool/klp-post-link.c           |  53 +--
 tools/objtool/klp-symid.c               | 117 +++++++
 tools/objtool/klp-sympos.c              | 441 ++++++++++++++++++++++++
 19 files changed, 877 insertions(+), 114 deletions(-)
 create mode 100644 tools/objtool/klp-symid.c
 create mode 100644 tools/objtool/klp-sympos.c
Signature · 1 line
2.54.0
author maintainer
#1 lore raw

PATCH 1/14 objtool/klp: Fix module name normalization for paths with dots

When .modinfo has no "name=" tag, __find_modname() falls back to converting the object's build-tree path to a runtime module name by stripping directory components, converting '-' to '_' and truncating the file extension.

It does all that in a single pass over the entire path, so the first dot anywhere in the path ends the name. For an object built in a directory whose name contains a dot, e.g. "drivers/foo-1.0/bar.o", the result is a bogus module name.

Strip the directory components up front so only the basename is scanned for the extension separator.

Fixes dd590d4d57eb ("objtool/klp: Introduce klp diff subcommand for diffing object files")
---
 tools/objtool/klp-diff.c | 10 ++++++----
 1 file changed, 6 insertions(+), 4 deletions(-)
tools/objtool/klp-diff.c +6 -4
index f8787d7d1454..aeb99d572300 100644
@@ -1140,7 +1140,7 @@ static struct export *find_export(struct symbol *sym)
 static const char *__find_modname(struct elfs *e)
 {
 	struct section *sec;
-	char *name;
+	char *name, *slash;
 
 	sec = find_section_by_name(e->orig, ".modinfo");
 	if (!sec) {
@@ -1158,10 +1158,12 @@ static const char *__find_modname(struct elfs *e)
 		return NULL;
 	}
 
+	slash = strrchr(name, '/');
+	if (slash)
+		name = slash + 1;
+
 	for (char *c = name; *c; c++) {
-		if (*c == '/')
-			name = c + 1;
-		else if (*c == '-')
+		if (*c == '-')
 			*c = '_';
 		else if (*c == '.') {
 			*c = '\0';
Signature · 1 line
2.54.0
author maintainer
#3 lore raw

PATCH 2/14 objtool/klp: Normalize Module.symvers paths to module names

In reply to Josh Poimboeuf

From: Joe Lawrence <[email protected]>

Module.symvers contains build-tree object paths as module identifiers (e.g., "arch/x86/kvm/kvm") rather than runtime module names ("kvm"). Objtool's clone_reloc_klp() uses this field directly for exported symbols, while unexported symbols correctly go through __find_modname().

This means that exported symbol relocations may land in a .klp.rela section named with the build path rather than the module name. That is a crash waiting to happen: the kernel's livepatch loader silently skips this relocation because it doesn't match the expected klp_object name. The unresolved relocation sits in the newly activated code, crashing when executed.

Normalize export->mod at Module.symvers read time using the same logic as __find_modname() (refactored into a shared normalize_modname() helper).

Fixes dd590d4d57eb ("objtool/klp: Introduce klp diff subcommand for diffing object files")
---
 tools/objtool/klp-diff.c | 49 ++++++++++++++++++++++++++++------------
 1 file changed, 34 insertions(+), 15 deletions(-)
tools/objtool/klp-diff.c +34 -15
index aeb99d572300..15d37d955af0 100644
@@ -83,6 +83,35 @@ static char *escape_str(const char *orig)
 	return new;
 }
 
+/*
+ * Convert a build-tree object path to a runtime module name: strip
+ * directory components, replace '-' with '_', and remove file
+ * extensions.  Examples:
+ *
+ *   "arch/x86/kvm/kvm" -> "kvm"
+ *   "arch/x86/kvm/kvm-intel" -> "kvm_intel".
+ *
+ * Used by read_exports() to normalize Module.symvers entries and by
+ * __find_modname() as a fallback when .modinfo lacks a "name=" tag.
+ */
+static char *normalize_modname(char *name)
+{
+	char *slash = strrchr(name, '/');
+
+	if (slash)
+		name = slash + 1;
+
+	for (char *c = name; *c; c++) {
+		if (*c == '-')
+			*c = '_';
+		else if (*c == '.') {
+			*c = '\0';
+			break;
+		}
+	}
+	return name;
+}
+
 static int read_exports(void)
 {
 	const char *symvers = "Module.symvers";
@@ -150,6 +179,9 @@ static int read_exports(void)
 			return -1;
 		}
 
+		if (strcmp(export->mod, "vmlinux"))
+			export->mod = normalize_modname(export->mod);
+
 		export->sym = strdup(sym);
 		if (!export->sym) {
 			ERROR_GLIBC("strdup");
@@ -1140,7 +1172,7 @@ static struct export *find_export(struct symbol *sym)
 static const char *__find_modname(struct elfs *e)
 {
 	struct section *sec;
-	char *name, *slash;
+	char *name;
 
 	sec = find_section_by_name(e->orig, ".modinfo");
 	if (!sec) {
@@ -1158,20 +1190,7 @@ static const char *__find_modname(struct elfs *e)
 		return NULL;
 	}
 
-	slash = strrchr(name, '/');
-	if (slash)
-		name = slash + 1;
-
-	for (char *c = name; *c; c++) {
-		if (*c == '-')
-			*c = '_';
-		else if (*c == '.') {
-			*c = '\0';
-			break;
-		}
-	}
-
-	return name;
+	return normalize_modname(name);
 }
 
 /* Get the object's module name as defined by the kernel (and klp_object) */
Signature · 1 line
2.54.0
author maintainer
#7 lore raw

PATCH 3/14 objtool/klp: Fix false module dependencies caused by dead relocs

In reply to Josh Poimboeuf

When creating a klp reloc, klp-diff keeps the original relocation but converts the referenced symbol to an UNDEF/WEAK placeholder tombstone symbol, which gets fully disabled later by klp post-link. The tombstone symbol is only needed to avoid confusing objtool when it does the final run on the patch module.

However, for references to exported symbols, modpost sees the reference to the tombstone symbol as a real reference to an exported symbol, resulting in a false module dependency getting created.

Further, for a reference to a tombstone symbol which is exported into a module namespace, e.g. via EXPORT_SYMBOL_FOR_KVM_INTERNAL(), modpost can't satisfy the dependency, resulting in a warning like the following:

module ... uses symbol kvm_flush_remote_tlbs from namespace module:kvm-amd,kvm-intel, but does not import it.

Rename the placeholder tombstone symbols to ".klp.tombstone.<name>" so modpost no longer recognizes them.

Fixes dd590d4d57eb ("objtool/klp: Introduce klp diff subcommand for diffing object files")
---
 tools/objtool/elf.c                 | 13 +++++++++++++
 tools/objtool/include/objtool/klp.h |  2 ++
 tools/objtool/klp-diff.c            | 16 ++++++++++++----
 3 files changed, 27 insertions(+), 4 deletions(-)
tools/objtool/elf.c +13 -0
index 33c95a74a51b..a791f4ea6ec1 100644
@@ -23,6 +23,7 @@
 #include <linux/log2.h>
 #include <objtool/builtin.h>
 #include <objtool/elf.h>
+#include <objtool/klp.h>
 #include <objtool/warn.h>
 
 static ssize_t demangled_name_len(const char *name);
@@ -626,6 +627,18 @@ static int read_symbols(struct elf *elf)
 			return -1;
 		}
 
+		/*
+		 * "klp diff" renames the placeholder symbols of KLP relocs to
+		 * hide them from modpost.  Hide the prefix from the rest of
+		 * objtool so its many name-based heuristics (noreturns,
+		 * uaccess safe list, ...) still see the original symbol name.
+		 *
+		 * st_name is left alone, so the renamed symbol is preserved in
+		 * the output file.
+		 */
+		if (strstarts(sym->name, KLP_TOMBSTONE_PREFIX))
+			sym->name += strlen(KLP_TOMBSTONE_PREFIX);
+
 		if ((sym->sym.st_shndx > SHN_UNDEF &&
 		     sym->sym.st_shndx < SHN_LORESERVE) ||
 		    (shndx_data && sym->sym.st_shndx == SHN_XINDEX)) {
tools/objtool/include/objtool/klp.h +2 -0
index 6f60cf05db86..aab6db42052d 100644
@@ -23,6 +23,8 @@
 #define KLP_RELOCS_SEC	"__klp_relocs"
 #define KLP_STRINGS_SEC	".rodata.klp.str1.1"
 
+#define KLP_TOMBSTONE_PREFIX	".klp.tombstone."
+
 struct klp_reloc {
 	void *offset;
 	void *sym;
tools/objtool/klp-diff.c +12 -4
index 15d37d955af0..75ba0e060a34 100644
@@ -1362,6 +1362,7 @@ static int clone_reloc_klp(struct elfs *e, struct reloc *patched_reloc,
 	s64 addend = reloc_addend(patched_reloc);
 	const char *sym_modname, *sym_orig_name;
 	static struct section *klp_relocs;
+	char tombstone_name[SYM_NAME_LEN];
 	struct symbol *sym, *klp_sym;
 	unsigned long klp_reloc_off;
 	char sym_name[SYM_NAME_LEN];
@@ -1376,15 +1377,22 @@ static int clone_reloc_klp(struct elfs *e, struct reloc *patched_reloc,
 	/*
 	 * Keep the original reloc intact for now to avoid breaking objtool run
 	 * which relies on proper relocations for many of its features.  This
-	 * will be disabled later by "objtool klp post-link".
+	 * reloc now targets a functionally dead tombstone symbol and will be
+	 * disabled later by "objtool klp post-link".
 	 *
-	 * Convert it to UNDEF (and WEAK to avoid modpost warnings).
+	 * Convert the symbol to UNDEF/WEAK and rename to
+	 * .klp.tombstone.sym_name to prevent modpost from printing warnings or
+	 * creating false module dependencies.  The prefix is hidden from the
+	 * objtool run itself by read_symbols().
 	 */
 
 	sym = patched_sym->clone;
 	if (!sym) {
-		/* STB_WEAK: avoid modpost undefined symbol warnings */
-		sym = elf_create_symbol(e->out, patched_sym->name, NULL,
+		if (snprintf_check(tombstone_name, SYM_NAME_LEN,
+				   KLP_TOMBSTONE_PREFIX "%s", patched_sym->name))
+			return -1;
+
+		sym = elf_create_symbol(e->out, tombstone_name, NULL,
 					STB_WEAK, patched_sym->type, 0, 0);
 		if (!sym)
 			return -1;
Signature · 1 line
2.54.0
author maintainer
#13 lore raw

PATCH 4/14 objtool/klp: Skip hidden directories when finding objects

In reply to Josh Poimboeuf

klp-build's find_objects() scans the whole tree for vmlinux.o and .ko files, pruning only klp-tmp/ and .git/. Development tools can leave other dot-directories in the tree. Kernel objects never live under hidden directories, so prune them all.

---
 scripts/livepatch/klp-build | 5 +++--
 1 file changed, 3 insertions(+), 2 deletions(-)
scripts/livepatch/klp-build +3 -2
index c4a7acf8edc3..a8c103ce7763 100755
@@ -575,8 +575,9 @@ find_objects() {
 	local opts=("$@")
 
 	# Find root-level vmlinux.o and non-root-level .ko files,
-	# excluding klp-tmp/ and .git/
-	find "$PWD" \( -path "$TMP_DIR" -o -path "$PWD/.git" -o -regex "$PWD/[^/][^/]*\.ko" \) -prune -o \
+	# excluding klp-tmp/ and hidden directories.
+	find "$PWD" -mindepth 1 \
+		    \( -path "$TMP_DIR" -o -name ".*" -o -regex "$PWD/[^/][^/]*\.ko" \) -prune -o \
 		    -type f "${opts[@]}"				\
 		    \( -name "*.ko" -o -path "$PWD/vmlinux.o" \)	\
 		    -printf '%P\n'
Signature · 1 line
2.54.0
author maintainer
#15 lore raw

PATCH 5/14 objtool/klp: Add .klp.symid for sympos disambiguation

In reply to Josh Poimboeuf

Livepatch identifies a duplicate-named symbol by its position (sympos) among same-named kallsyms entries, which for vmlinux are counted in ascending address order in the final linked kernel. That order can't be reliably derived from vmlinux.o: the final link reorders sub-sections (.text.unlikely*, .data..*, etc).

Bridge the gap with a new .klp.symid section which can be used to correlate symbols between vmlinux.o and vmlinux so that klp-diff can reliably determine the sympos.

The table can't survive --gc-sections: keeping it alive would keep every duplicate-named symbol's section alive, so the reference kernel would stop matching the one which ships. klp-build rejects CONFIG_LD_DEAD_CODE_DATA_ELIMINATION instead. Nothing is lost today:
x86_64 is the only HAVE_KLP_BUILD arch and doesn't select HAVE_LD_DEAD_CODE_DATA_ELIMINATION, arm64 and s390 have never selected it either, and on powerpc, it's still EXPERIMENTAL and disabled by every distro kernel.

This is the build-time half of reliable vmlinux sympos computation; "objtool klp diff" will consume the table in a subsequent commit.

---
 include/asm-generic/vmlinux.lds.h       |  10 +-
 scripts/Makefile.vmlinux_o              |   3 +
 scripts/livepatch/klp-build             |   5 +
 scripts/mod/modpost.c                   |   1 +
 tools/objtool/Build                     |   1 +
 tools/objtool/builtin-check.c           |   7 ++
 tools/objtool/check.c                   |   7 ++
 tools/objtool/include/objtool/builtin.h |   1 +
 tools/objtool/include/objtool/klp.h     |  15 +++
 tools/objtool/klp-symid.c               | 117 ++++++++++++++++++++++++
 10 files changed, 166 insertions(+), 1 deletion(-)
 create mode 100644 tools/objtool/klp-symid.c
include/asm-generic/vmlinux.lds.h +9 -1
index 5659f4b5a125..ee9c5d354a85 100644
@@ -839,12 +839,20 @@
 		.stab.index 0 : { *(.stab.index) }			\
 		.stab.indexstr 0 : { *(.stab.indexstr) }
 
+#ifdef CONFIG_KLP_BUILD
+#define KLP_SYMID							\
+		.klp.symid 0 : { *(.klp.symid) }
+#else
+#define KLP_SYMID
+#endif
+
 /* Required sections not related to debugging. */
 #define ELF_DETAILS							\
 		.comment 0 : { *(.comment) }				\
 		.symtab 0 : { *(.symtab) }				\
 		.strtab 0 : { *(.strtab) }				\
-		.shstrtab 0 : { *(.shstrtab) }
+		.shstrtab 0 : { *(.shstrtab) }				\
+		KLP_SYMID
 
 #define MODINFO								\
 		.modinfo : { *(.modinfo) . = ALIGN(8); }
scripts/Makefile.vmlinux_o +3 -0
index 527352c222ff..24a3a4fd271c 100644
@@ -47,6 +47,9 @@ endif
 vmlinux-objtool-args-$(CONFIG_NOINSTR_VALIDATION)	+= --noinstr \
 							   $(if $(or $(CONFIG_MITIGATION_UNRET_ENTRY),$(CONFIG_MITIGATION_SRSO)), --unret)
 
+# Only used for builds initiated by klp-build
+vmlinux-objtool-args-$(if $(KLP_SYMIDS),y)		+= --klp-symids
+
 objtool-args = $(vmlinux-objtool-args-y) --link
 
 # Link of vmlinux.o used for section mismatch analysis
scripts/livepatch/klp-build +5 -0
index a8c103ce7763..f94e324ff53c 100755
@@ -271,6 +271,9 @@ validate_config() {
 	[[ -v CONFIG_GCC_PLUGIN_RANDSTRUCT ]] &&	\
 		die "kernel option 'CONFIG_GCC_PLUGIN_RANDSTRUCT' not supported"
 
+	[[ -v CONFIG_LD_DEAD_CODE_DATA_ELIMINATION ]] &&		\
+		die "kernel option 'CONFIG_LD_DEAD_CODE_DATA_ELIMINATION' not supported"
+
 	[[ -v CONFIG_AS_IS_LLVM ]] &&				\
 		[[ "$CONFIG_AS_VERSION" -lt 200000 ]] &&	\
 		die "Clang assembler version < 20 not supported"
@@ -555,6 +558,8 @@ build_kernel() {
 	#
 	cmd+=("KBUILD_MODPOST_WARN=1")
 
+	cmd+=("KLP_SYMIDS=1")
+
 	if [[ -v VERBOSE ]]; then
 		cmd+=("V=1")
 	else
scripts/mod/modpost.c +1 -0
index a7b72a81d248..027944fe35b4 100644
@@ -767,6 +767,7 @@ static const char *const section_white_list[] =
 	".llvm.call-graph-profile",	/* call graph */
 	"__llvm_covfun",
 	"__llvm_covmap",
+	".klp.symid",			/* objtool --klp-symids */
 	NULL
 };
 
tools/objtool/Build +1 -0
index 93a37b0dfd31..506f89bed808 100644
@@ -6,6 +6,7 @@ objtool-y += check.o
 objtool-y += special.o
 objtool-y += builtin-check.o
 objtool-y += elf.o
+objtool-y += klp-symid.o
 objtool-y += objtool.o
 
 objtool-$(BUILD_DISAS) += disas.o
tools/objtool/builtin-check.c +7 -0
index 118c3de2f293..75b11dc85010 100644
@@ -76,6 +76,7 @@ static const struct option check_options[] = {
 	OPT_STRING_OPTARG('d',	 "disas", &opts.disas, "function-pattern", "disassemble functions", "*"),
 	OPT_CALLBACK_OPTARG('h', "hacks", NULL, NULL, "jump_label,noinstr,skylake", "patch toolchain bugs/limitations", parse_hacks),
 	OPT_BOOLEAN('i',	 "ibt", &opts.ibt, "validate and annotate IBT"),
+	OPT_BOOLEAN(0,		 "klp-symids", &opts.klp_symids, "generate .klp.symids for duplicate symbol disambiguation"),
 	OPT_BOOLEAN('m',	 "mcount", &opts.mcount, "annotate mcount/fentry calls for ftrace"),
 	OPT_BOOLEAN(0,		 "noabs", &opts.noabs, "reject absolute references in allocatable sections"),
 	OPT_BOOLEAN('n',	 "noinstr", &opts.noinstr, "validate noinstr rules"),
@@ -174,10 +175,16 @@ static bool opts_valid(void)
 		return false;
 	}
 
+	if (opts.klp_symids && !opts.link) {
+		ERROR("--klp-symids requires --link");
+		return false;
+	}
+
 	if (opts.disas			||
 	    opts.hack_jump_label	||
 	    opts.hack_noinstr		||
 	    opts.ibt			||
+	    opts.klp_symids		||
 	    opts.mcount			||
 	    opts.noabs			||
 	    opts.noinstr		||
tools/objtool/check.c +7 -0
index 10b18cf9c360..4e6366663be1 100644
@@ -15,6 +15,7 @@
 #include <objtool/arch.h>
 #include <objtool/disas.h>
 #include <objtool/check.h>
+#include <objtool/klp.h>
 #include <objtool/special.h>
 #include <objtool/trace.h>
 #include <objtool/warn.h>
@@ -4922,6 +4923,12 @@ int check(struct objtool_file *file)
 			goto out;
 	}
 
+	if (opts.klp_symids) {
+		ret = klp_create_symid_sections(file);
+		if (ret)
+			goto out;
+	}
+
 	if (opts.noabs)
 		warnings += check_abs_references(file);
 
tools/objtool/include/objtool/builtin.h +1 -0
index e844e9c82b7b..349690bb1c50 100644
@@ -16,6 +16,7 @@ struct opts {
 	bool hack_noinstr;
 	bool hack_skylake;
 	bool ibt;
+	bool klp_symids;
 	bool mcount;
 	bool noabs;
 	bool noinstr;
tools/objtool/include/objtool/klp.h +15 -0
index aab6db42052d..4d3c3bd462aa 100644
@@ -31,6 +31,21 @@ struct klp_reloc {
 	u32 type;
 };
 
+/*
+ * .klp.symid is used to correlate symbols between vmlinux.o and vmlinux, for
+ * calculating sympos to disambiguate duplicately-named symbols.
+ */
+#define KLP_SYMID_SEC	".klp.symid"
+
+struct klp_symid {
+	u64 id;
+	u64 addr;
+};
+
+struct objtool_file;
+
+int klp_create_symid_sections(struct objtool_file *file);
+
 int cmd_klp_checksum(int argc, const char **argv);
 int cmd_klp_diff(int argc, const char **argv);
 int cmd_klp_post_link(int argc, const char **argv);
tools/objtool/klp-symid.c new file +117 -0

117 lines not on this page · raw message

Signature · 1 line
2.54.0
author maintainer
#23 lore raw

PATCH 6/14 objtool/klp: Fix symbol resolution for duplicate data symbols

In reply to Josh Poimboeuf

find_sympos() calculates a sympos used by livepatch to disambiguate duplicately-named symbols. For function symbols, there's a hack which counts .text.unlikely symbols before other .text symbols, matching the linker script's section ordering.

Not only is the hack fragile, data symbols can have the same problem. So for example, adding a reference to pwq_cache in ep_unregister_pollwait() can trigger a corrupt sympos and a relocation to the wrong pwq_cache symbol in the livepatch module, resulting in a crash or undefined behavior.

Remove the existing hack in favor of a fully deterministic solution, using the new .klp.symid table to derive the symbol-to-id mapping from the original vmlinux.o and the id-to-address mapping from the corresponding vmlinux, which can then be used to determine the exact sympos associated with the original vmlinux.

Modules don't need any special treatment: the .ko has the same section/symbol ordering as the original whole-archive symbol table.

Fixes dd590d4d57eb ("objtool/klp: Introduce klp diff subcommand for diffing object files")
---
 scripts/livepatch/klp-build         |   4 +
 tools/objtool/Build                 |   3 +-
 tools/objtool/include/objtool/klp.h |   5 +
 tools/objtool/klp-diff.c            |  66 +----
 tools/objtool/klp-sympos.c          | 411 ++++++++++++++++++++++++++++
 5 files changed, 427 insertions(+), 62 deletions(-)
 create mode 100644 tools/objtool/klp-sympos.c
scripts/livepatch/klp-build +4 -0
index f94e324ff53c..b52a8489d9f6 100755
@@ -611,6 +611,8 @@ copy_orig_objects() {
 	done
 	xtrace_restore
 
+	cp -f "$PWD/vmlinux" "$ORIG_DIR" || die "missing vmlinux"
+
 	mv -f "$TMP_DIR/build.log" "$ORIG_DIR"
 	touch "$TIMESTAMP"
 	touch "$ORIG_DIR/.complete"
@@ -681,6 +683,8 @@ generate_checksums() {
 		"$OBJTOOL" klp checksum "$dest"
 	done
 
+	[[ -f "$src_dir/vmlinux" ]] && cp -f "$src_dir/vmlinux" "$dest_dir"
+
 	touch "$dest_dir/.complete"
 }
 
tools/objtool/Build +2 -1
index 506f89bed808..59f948628098 100644
@@ -13,7 +13,8 @@ objtool-$(BUILD_DISAS) += disas.o
 objtool-$(BUILD_DISAS) += trace.o
 
 objtool-$(BUILD_ORC) += orc_gen.o orc_dump.o
-objtool-$(BUILD_KLP) += builtin-klp.o klp-checksum.o klp-diff.o klp-post-link.o
+objtool-$(BUILD_KLP) += builtin-klp.o klp-checksum.o klp-diff.o \
+			klp-post-link.o klp-sympos.o
 
 objtool-y += libstring.o
 objtool-y += libctype.o
tools/objtool/include/objtool/klp.h +5 -0
index 4d3c3bd462aa..0118c2c170c3 100644
@@ -43,9 +43,14 @@ struct klp_symid {
 };
 
 struct objtool_file;
+struct elf;
+struct symbol;
 
 int klp_create_symid_sections(struct objtool_file *file);
 
+int klp_sympos_init(struct elf *orig);
+unsigned long klp_find_sympos(struct elf *elf, struct symbol *sym);
+
 int cmd_klp_checksum(int argc, const char **argv);
 int cmd_klp_diff(int argc, const char **argv);
 int cmd_klp_post_link(int argc, const char **argv);
tools/objtool/klp-diff.c +5 -61

90 lines not on this page · raw message

tools/objtool/klp-sympos.c new file +411 -0

411 lines not on this page · raw message

Signature · 1 line
2.54.0
author maintainer
#25 lore raw

PATCH 7/14 module: Add module_kallsyms_on_each_core_symbol()

In reply to Josh Poimboeuf

module_kallsyms_on_each_symbol() iterates mod->kallsyms, which points at the full init symbol table until do_init_module() swaps it out. The set of symbols it reports thus differs based on whether init memory has been freed yet.

Add module_kallsyms_on_each_core_symbol() for callers which need a symbol's position to be the same before and after that swap. core_kallsyms is fully populated by add_kallsyms() before the module leaves MODULE_STATE_UNFORMED, so it's readable on both paths.

---
 include/linux/module.h   | 11 ++++++++++
 kernel/module/kallsyms.c | 46 ++++++++++++++++++++++++++++++++++++++++
 2 files changed, 57 insertions(+)
include/linux/module.h +11 -0
index 7566815fabbe..4ea4522a5fc5 100644
@@ -947,6 +947,9 @@ static inline bool module_sig_ok(struct module *module)
 int module_kallsyms_on_each_symbol(const char *modname,
 				   int (*fn)(void *, const char *, unsigned long),
 				   void *data);
+int module_kallsyms_on_each_core_symbol(const char *modname,
+					int (*fn)(void *, const char *, unsigned long),
+					void *data);
 
 /* For kallsyms to ask for address resolution.  namebuf should be at
  * least KSYM_NAME_LEN long: a pointer to namebuf is returned if
@@ -984,6 +987,14 @@ static inline int module_kallsyms_on_each_symbol(const char *modname,
 	return -EOPNOTSUPP;
 }
 
+static inline int
+module_kallsyms_on_each_core_symbol(const char *modname,
+				    int (*fn)(void *, const char *, unsigned long),
+				    void *data)
+{
+	return -EOPNOTSUPP;
+}
+
 /* For kallsyms to ask for address resolution.  NULL means not found. */
 static inline int module_address_lookup(unsigned long addr,
 						unsigned long *symbolsize,
kernel/module/kallsyms.c +46 -0

49 lines not on this page · raw message

Signature · 1 line
2.54.0
author maintainer
#27 lore raw

PATCH 8/14 objtool/klp,livepatch: Resolve module symbols against core kallsyms

In reply to Josh Poimboeuf

For patching a module, klp_find_sympos() counts every symbol table entry whose name matches. However, the module loader only includes symbols matched by is_core_symbol().

The runtime count is inconsistent as well. It's done by module_kallsyms_on_each_symbol(), which iterates the full init symbol table until do_init_module() swaps in the cut-down core table, so the same symbol can have different positions depending on whether init memory has been freed yet.

Define a module's sympos as its position in the core symbol table, which is what sympos already means for a live module and what users see in /proc/kallsyms. Enforce that on both ends: count with module_kallsyms_on_each_core_symbol() at runtime, and mirror the is_core_symbol() filter in objtool with a new mod_sym_in_kallsyms() helper.

The init-layout half of the filter is only correct if .exit sections are core sections, which requires CONFIG_MODULE_UNLOAD, otherwise .exit code is laid out as part of init memory and freed after module init. Enforce CONFIG_MODULE_UNLOAD to ensure that behavior is deterministic.

Symbols which exist only in init sections are no longer resolvable, but they never were once the module went live, and init memory is freed after module init anyway.

Fixes dd590d4d57eb ("objtool/klp: Introduce klp diff subcommand for diffing object files")
Fixes b2b018ef4867 ("livepatch: add old_sympos as disambiguator field to klp_func")
---
 kernel/livepatch/core.c     |  2 +-
 scripts/livepatch/klp-build |  3 +++
 tools/objtool/klp-sympos.c  | 22 +++++++++++++++++++++-
 3 files changed, 25 insertions(+), 2 deletions(-)
kernel/livepatch/core.c +1 -1
index 28d15ba58a26..a05cd2c38caa 100644
@@ -168,7 +168,7 @@ static int klp_find_object_symbol(const char *objname, const char *name,
 	};
 
 	if (objname)
-		module_kallsyms_on_each_symbol(objname, klp_find_callback, &args);
+		module_kallsyms_on_each_core_symbol(objname, klp_find_callback, &args);
 	else
 		kallsyms_on_each_match_symbol(klp_match_callback, name, &args);
 
scripts/livepatch/klp-build +3 -0
index b52a8489d9f6..9b375e018d76 100755
@@ -265,6 +265,9 @@ validate_config() {
 	[[ -v CONFIG_KLP_BUILD ]] ||			\
 		die "CONFIG_KLP_BUILD not enabled"
 
+	[[ -v CONFIG_MODULE_UNLOAD ]] ||		\
+		die "kernel option 'CONFIG_MODULE_UNLOAD' required"
+
 	[[ -v CONFIG_GCC_PLUGIN_LATENT_ENTROPY ]] &&	\
 		die "kernel option 'CONFIG_GCC_PLUGIN_LATENT_ENTROPY' not supported"
 
tools/objtool/klp-sympos.c +21 -1
index bbfae516d339..34bb8d1971bd 100644
@@ -367,6 +367,17 @@ static unsigned long find_vmlinux_sympos(struct symbol *sym)
 	return sympos;
 }
 
+static bool mod_sym_in_kallsyms(struct symbol *sym)
+{
+	if (is_undef_sym(sym))
+		return false;
+
+	if (!(sym->sec->sh.sh_flags & SHF_ALLOC))
+		return false;
+
+	return !strstarts(sym->sec->name, ".init");
+}
+
 /*
  * "sympos" is used by livepatch to disambiguate duplicate symbol names.
  */
@@ -387,12 +398,21 @@ unsigned long klp_find_sympos(struct elf *elf, struct symbol *sym)
 	if (vmlinux.elf)
 		return find_vmlinux_sympos(sym);
 
+	if (!mod_sym_in_kallsyms(sym)) {
+		ERROR("symbol %s is not visible to module kallsyms, can't compute sympos",
+		      sym->name);
+		return ULONG_MAX;
+	}
+
 	/*
 	 * modules: the final .ko preserves symbol table order, so a
 	 * symtab-order count here matches the runtime count done by
-	 * module_kallsyms_on_each_symbol().
+	 * module_kallsyms_on_each_core_symbol().
 	 */
 	for_each_sym(elf, s) {
+		if (!mod_sym_in_kallsyms(s))
+			continue;
+
 		if (!strcmp(s->name, sym->name)) {
 			nr_matches++;
 			if (s == sym)
Signature · 1 line
2.54.0
author maintainer
#30 lore raw

PATCH 9/14 objtool/klp: Fix size of empty special section entries

In reply to Josh Poimboeuf

create_fake_symbols() sizes each ANNOTATE_DATA_SPECIAL entry from the offset of the next annotation, falling back to the end of the section for the last entry. But the last entry is detected by a zero size, which also happens for an *empty* entry: ALTERNATIVE(oldinstr, "", ft) still annotates its zero-length replacement, at the same offset as the next entry's annotation.

So every empty replacement gets a fake symbol spanning the entire rest of .altinstr_replacement. That's harmless today only because find_symbol_containing() picks the smaller of two overlapping symbols.

Track whether a next annotation was found rather than inferring it from the size. A zero-length fake symbol is fine: find_symbol_containing() skips those, so the properly sized symbol at the same offset still wins.

Fixes dd590d4d57eb ("objtool/klp: Introduce klp diff subcommand for diffing object files")
---
 tools/objtool/klp-diff.c | 4 +++-
 1 file changed, 3 insertions(+), 1 deletion(-)
tools/objtool/klp-diff.c +3 -1
index c5284d275207..257e7f924928 100644
@@ -1628,6 +1628,7 @@ static int create_fake_symbols(struct elf *elf)
 	for_each_reloc(sec->rsec, reloc) {
 		unsigned long offset, size;
 		struct reloc *next_reloc;
+		bool last = true;
 
 		if (annotype(elf, sec, reloc) != ANNOTYPE_DATA_SPECIAL)
 			continue;
@@ -1642,10 +1643,11 @@ static int create_fake_symbols(struct elf *elf)
 				continue;
 
 			size = reloc_addend(next_reloc) - offset;
+			last = false;
 			break;
 		}
 
-		if (!size)
+		if (last)
 			size = sec_size(reloc->sym->sec) - offset;
 
 		if (create_fake_symbol(elf, reloc->sym->sec, offset, size))
Signature · 1 line
2.54.0
author maintainer
#31 lore raw

PATCH 10/14 objtool/klp: Ignore replacement offset of empty x86 alternatives

In reply to Josh Poimboeuf

An x86 alternative with an empty replacement, e.g. the second entry of

ALTERNATIVE_2("orig", "repl", ft1, "", ft2)

has a replacementlen of zero. Its replacement offset still gets a relocation, but the label it points at is the end of the previous replacement, which is also the beginning of the *next* alternative's replacement. The value is meaningless; get_alt_entry() already ignores it for that reason.

klp diff doesn't ignore it. When such an alternative belongs to a changed function, cloning its relocations drags in the unrelated neighboring replacement, along with everything that replacement references. On an x86 clang/lto build an empty alternative in meminfo_proc_show() pulled in the replacement of an alternative in proc_kcore_init(), silently emitting a klp relocation against init text which has long since been freed by the time the patch is applied.

Add arch_alt_ignore_new_reloc() and skip such relocations when cloning. This has to be arch specific: on arm64 a zero-length replacement instead identifies an alternative callback, whose replacement offset points at the callback function and must be preserved.

Fixes dd590d4d57eb ("objtool/klp: Introduce klp diff subcommand for diffing object files")
---
 tools/objtool/arch/x86/special.c        | 27 +++++++++++++++++++++++++
 tools/objtool/include/objtool/special.h |  7 +++++++
 tools/objtool/klp-diff.c                |  6 +++++-
 3 files changed, 39 insertions(+), 1 deletion(-)
tools/objtool/arch/x86/special.c +27 -0
index e817a3fff449..1e84c81bfcd8 100644
@@ -1,6 +1,7 @@
 // SPDX-License-Identifier: GPL-2.0-or-later
 #include <string.h>
 
+#include <arch/special.h>
 #include <objtool/special.h>
 #include <objtool/builtin.h>
 #include <objtool/warn.h>
@@ -9,6 +10,32 @@
 /* cpu feature name array generated from cpufeatures.h */
 #include "cpu-feature-names.c"
 
+/*
+ * An alternative with an empty replacement, e.g. the second entry of
+ *
+ *   ALTERNATIVE_2("orig", "repl", ft1, "", ft2)
+ *
+ * still gets a relocation for its replacement offset.  But the label it points
+ * at is the end of the previous entry's replacement, which is also the
+ * beginning of the *next* entry's replacement.  The value is meaningless: it's
+ * only ever used with a length of zero.
+ */
+bool arch_alt_ignore_new_reloc(struct section *sec, unsigned long offset)
+{
+	unsigned long entry_off;
+
+	if (strcmp(sec->name, ".altinstructions"))
+		return false;
+
+	entry_off = offset - (offset % ALT_ENTRY_SIZE);
+
+	if (offset - entry_off != ALT_NEW_OFFSET)
+		return false;
+
+	return !*(unsigned char *)(sec->data->d_buf + entry_off +
+				   ALT_NEW_LEN_OFFSET);
+}
+
 void arch_handle_alternative(struct special_alt *alt)
 {
 	static struct special_alt *group, *prev;
tools/objtool/include/objtool/special.h +7 -0
index 121c3761899c..620dbf6cb0e5 100644
@@ -32,6 +32,13 @@ int special_get_alts(struct elf *elf, struct list_head *alts);
 
 void arch_handle_alternative(struct special_alt *alt);
 
+/*
+ * Should the reloc at @offset -- the "new" (replacement) field of a special
+ * section group entry -- be ignored?  The meaning of a zero-length replacement
+ * is arch specific, so the arch decides.
+ */
+bool arch_alt_ignore_new_reloc(struct section *sec, unsigned long offset);
+
 bool arch_support_alt_relocation(struct special_alt *special_alt,
 				 struct instruction *insn,
 				 struct reloc *reloc);
tools/objtool/klp-diff.c +5 -1
index 257e7f924928..cf6fc88bc979 100644
@@ -12,7 +12,7 @@
 #include <objtool/arch.h>
 #include <objtool/klp.h>
 #include <objtool/util.h>
-#include <arch/special.h>
+#include <objtool/special.h>
 
 #include <linux/align.h>
 #include <linux/objtool_types.h>
@@ -1538,6 +1538,10 @@ static int clone_sym_relocs(struct elfs *e, struct symbol *patched_sym)
 		    !strcmp(patched_reloc->sym->sec->name, ".altinstr_aux"))
 			continue;
 
+		if (arch_alt_ignore_new_reloc(patched_sym->sec,
+					      reloc_offset(patched_reloc)))
+			continue;
+
 		ret = convert_reloc_sym(e->patched, patched_reloc);
 		if (ret < 0) {
 			ERROR_FUNC(patched_rsec->base, reloc_offset(patched_reloc),
Signature · 1 line
2.54.0
author maintainer
#32 lore raw

PATCH 11/14 objtool/klp: Explicitly disallow patching or referencing init code/data

In reply to Josh Poimboeuf

Explicitly disallow the patching and referencing of init code/data. Otherwise it could potentially introduce some odd edge cases depending on whether the target object's init section has been freed yet (note that the init code still exists in the target module when doing late module patching).

Such edge cases include sympos calculation and the patching and/or referencing of non-existent (init-freed) code/data. Not to mention the inherent differences in behavior that occur when the init code is only patched *some* of the time depending on module loading order or kernel config.

---
 tools/objtool/klp-sympos.c | 10 ++++++++++
 1 file changed, 10 insertions(+)
tools/objtool/klp-sympos.c +10 -0
index 34bb8d1971bd..822ac53cfa47 100644
@@ -378,6 +378,11 @@ static bool mod_sym_in_kallsyms(struct symbol *sym)
 	return !strstarts(sym->sec->name, ".init");
 }
 
+static bool is_init_sym(struct symbol *sym)
+{
+	return strstarts(sym->sec->name, ".init");
+}
+
 /*
  * "sympos" is used by livepatch to disambiguate duplicate symbol names.
  */
@@ -387,6 +392,11 @@ unsigned long klp_find_sympos(struct elf *elf, struct symbol *sym)
 	bool has_dup = false;
 	struct symbol *s;
 
+	if (is_init_sym(sym)) {
+		ERROR("%s: can't patch or reference init code/data", sym->name);
+		return ULONG_MAX;
+	}
+
 	if (sym->bind != STB_LOCAL)
 		return 0;
 
Signature · 1 line
2.54.0
author maintainer
#33 lore raw

PATCH 12/14 objtool/klp: Fix cross-module klp relocation section naming

In reply to Josh Poimboeuf

A klp relocation section is .klp.rela.<objname>.<secname>, where objname is the object being patched.

klp-build wrongly derives objname from where the referenced symbol lives, not where it's referenced. For a cross-module reference like patched can_isotp code calling can.ko's can_rx_unregister(), that gives .klp.rela.can..text rather than .klp.rela.can_isotp..text. Unless the patch happens to patch can.ko as well, the relocation never gets applied and the call goes off into the weeds.

Name the intermediate section __klp_relocs.<objname> so post-link can read the patched object's name from there.

Fixes dd590d4d57eb ("objtool/klp: Introduce klp diff subcommand for diffing object files")
---
 tools/objtool/include/objtool/klp.h | 10 ++++--
 tools/objtool/klp-diff.c            | 17 +++++++--
 tools/objtool/klp-post-link.c       | 53 +++++++++++++++++------------
 3 files changed, 52 insertions(+), 28 deletions(-)
tools/objtool/include/objtool/klp.h +7 -3
index 0118c2c170c3..646d8e1f12ef 100644
@@ -14,11 +14,15 @@
 #define KLP_FUNCS_SEC	".init.klp_funcs"
 
 /*
- * __klp_relocs is an intermediate section which are created by klp diff and
- * converted into KLP symbols/relas by "objtool klp post-link".  This is needed
- * to work around the linker, which doesn't preserve SHN_LIVEPATCH or
+ * __klp_relocs.<objname> are intermediate sections which are created by klp
+ * diff and converted into KLP symbols/relas by "objtool klp post-link".  This
+ * is needed to work around the linker, which doesn't preserve SHN_LIVEPATCH or
  * SHF_RELA_LIVEPATCH, nor does it support having two RELA sections for a
  * single PROGBITS section.
+ *
+ * "objname" is the name of the object being patched ("vmlinux" or a module
+ * name).  post-link uses it to name the resulting
+ * .klp.rela.objname.section_name sections.
  */
 #define KLP_RELOCS_SEC	"__klp_relocs"
 #define KLP_STRINGS_SEC	".rodata.klp.str1.1"
tools/objtool/klp-diff.c +14 -3
index cf6fc88bc979..e00dbe053a6e 100644
@@ -1381,8 +1381,8 @@ static int clone_reloc_klp(struct elfs *e, struct reloc *patched_reloc,
 	}
 
 	/*
-	 * Create the __klp_relocs entry.  This will be converted to an actual
-	 * KLP rela by "objtool klp post-link".
+	 * Create the __klp_relocs.<objname> entry.  This will be converted to
+	 * an actual KLP rela by "objtool klp post-link".
 	 *
 	 * This intermediate step is necessary to prevent corruption by the
 	 * linker, which doesn't know how to properly handle two rela sections
@@ -1390,7 +1390,18 @@ static int clone_reloc_klp(struct elfs *e, struct reloc *patched_reloc,
 	 */
 
 	if (!klp_relocs) {
-		klp_relocs = elf_create_section(e->out, KLP_RELOCS_SEC, 0,
+		const char *objname = find_modname(e);
+		char sec_name[SEC_NAME_LEN];
+
+		if (!objname)
+			return -1;
+
+		/* section format: __klp_relocs.objname */
+		if (snprintf_check(sec_name, SEC_NAME_LEN,
+				   KLP_RELOCS_SEC ".%s", objname))
+			return -1;
+
+		klp_relocs = elf_create_section(e->out, sec_name, 0,
 						0, SHT_PROGBITS, 8, SHF_ALLOC);
 		if (!klp_relocs)
 			return -1;
tools/objtool/klp-post-link.c +31 -22

98 lines not on this page · raw message

Signature · 1 line
2.54.0
author maintainer
#34 lore raw

PATCH 13/14 objtool/klp: Don't match local symbols against exports

In reply to Josh Poimboeuf

While cloning a reloc, klp diff calls find_export() to determine whether the referenced symbol is exported. That decides whether the reference needs a klp reloc, which object the klp symbol belongs to, and whether the symbol's data needs to be copied into the patch module.

But find_export() matches purely on symbol name, so a static function or variable which happens to share its name with an export is mistaken for a reference to that export:

- klp_reloc_needed() creates a klp reloc pointing at the exporting module's symbol rather than the local one. For a vmlinux export it skips the klp reloc altogether, leaving a normal reloc which the module loader resolves to the vmlinux symbol.

- clone_reloc() treats the symbol as external and clones it without its data, leaving a dangling reference.

- validate_special_section_klp_reloc() attributes a static branch or call key to the wrong module, and for a vmlinux export skips the unsupported-key check entirely.

Exports are always global, so ignore local symbols in find_export().

Fixes dd590d4d57eb ("objtool/klp: Introduce klp diff subcommand for diffing object files")
---
 tools/objtool/klp-diff.c | 3 +++
 1 file changed, 3 insertions(+)
tools/objtool/klp-diff.c +3 -0
index e00dbe053a6e..e0dc22cef2c3 100644
@@ -1102,6 +1102,9 @@ static struct export *find_export(struct symbol *sym)
 {
 	struct export *export;
 
+	if (is_local_sym(sym))
+		return NULL;
+
 	hash_for_each_possible(exports, export, hash, str_hash(sym->name)) {
 		if (!strcmp(export->sym, sym->name))
 			return export;
Signature · 1 line
2.54.0
author maintainer
#35 lore raw

PATCH 14/14 objtool/klp: Allow new references to module exports

In reply to Josh Poimboeuf

From: Joe Lawrence <[email protected]>

klp_reloc_needed() returns true for module exports to support late-module patching. However, clone_reloc_klp() unconditionally rejects symbols without a twin (i.e., new references added by the patch), even when the symbol is a known export from Module.symvers.

Relax the check: allow new references to exported symbols by only erroring on !twin when there is no export. The export metadata from Module.symvers provides sufficient context to emit the klp-relocation without a twin.

For a module export that isn't sufficient on its own though, as the resulting klp relocation will only be resolved at patch-enable time if the exporting module is loaded.

If the original (unpatched) module already depends on the exporting module, the dependency is safe: the module loader ensures the dependency is satisfied before the patched module can be loaded, so the klp relocation target will exist.

However, if the patch introduces a reference to a module that the original doesn't depend on, there is no such guarantee. The exporting module could be absent or could be unloaded at any time, leading to a relocation failure or use-after-free.

So also add a build-time check: when a new symbol reference (no twin) targets a module export, verify that the original module already has at least one UNDEF symbol resolving to that same exporting module. If not, error out with a diagnostic message.

---
 tools/objtool/klp-diff.c | 35 +++++++++++++++++++++++++++++++++--
 1 file changed, 33 insertions(+), 2 deletions(-)
tools/objtool/klp-diff.c +33 -2
index e0dc22cef2c3..abda2e5c17f7 100644
@@ -1295,6 +1295,28 @@ static int convert_reloc_sym(struct elf *elf, struct reloc *reloc)
 	return convert_reloc_secsym_to_sym(elf, reloc);
 }
 
+/*
+ * Check if the original module already has a dependency on dep_mod, i.e. it
+ * already references at least one export from that module.
+ */
+static bool has_module_dep(struct elfs *e, const char *dep_mod)
+{
+	struct symbol *sym;
+
+	for_each_sym(e->orig, sym) {
+		struct export *exp;
+
+		if (!is_undef_sym(sym) || is_weak_sym(sym))
+			continue;
+
+		exp = find_export(sym);
+		if (exp && !strcmp(exp->mod, dep_mod))
+			return true;
+	}
+
+	return false;
+}
+
 /*
  * Convert a regular relocation to a klp relocation (sort of).
  */
@@ -1314,8 +1336,17 @@ static int clone_reloc_klp(struct elfs *e, struct reloc *patched_reloc,
 	unsigned long sympos;
 
 	if (!patched_sym->twin) {
-		ERROR("unexpected klp reloc for new symbol %s", patched_sym->name);
-		return -1;
+		if (!export) {
+			ERROR("unexpected klp reloc for new symbol %s", patched_sym->name);
+			return -1;
+		}
+
+		if (strcmp(export->mod, "vmlinux") &&
+		    !has_module_dep(e, export->mod)) {
+			ERROR("%s: new reference to %s (exported by %s) would create an undeclared module dependency",
+			      patched_sym->name, export->sym, export->mod);
+			return -1;
+		}
 	}
 
 	/*
Signature · 1 line
2.54.0
#4 lore raw

Re: [PATCH 02/14] objtool/klp: Normalize Module.symvers paths to module names

In reply to Josh Poimboeuf
Thank you for your contribution! Sashiko AI review found 1 potential issue(s) to consider: - [Medium] normalize_modname() returns an interior pointer, causing the original heap allocation base…

Thank you for your contribution! Sashiko AI review found 1 potential issue(s) to consider:
- [Medium] normalize_modname() returns an interior pointer, causing the original heap allocation base pointer to be lost in read_exports() and __find_modname(). --

--- Patch [2]: [PATCH 02/14] objtool/klp: Normalize Module.symvers paths to module names --- commit 8f5aadae3b846aa3bb569cfc55ef783d4449690f
Author: Joe Lawrence <[email protected]>

objtool/klp: Normalize Module.symvers paths to module names

This commit normalizes Module.symvers object paths to runtime module names for exported symbols to prevent a crash during livepatch loading. It extracts the module name processing into a shared normalize_modname() helper.

Quoted 5 lines
tools/objtool/klp-diff.c +0 -0
index aeb99d572300c..15d37d955af0e 100644
@@ -83,6 +83,35 @@ static char *escape_str(const char *orig)

[ ... ]

Quoted 20 lines
tools/objtool/klp-diff.c +18 -0
+static char *normalize_modname(char *name)
+{
+	char *slash = strrchr(name, '/');
+
+	if (slash)
+		name = slash + 1;
+
+	for (char *c = name; *c; c++) {
+		if (*c == '-')
+			*c = '_';
+		else if (*c == '.') {
+			*c = '\0';
+			break;
+		}
+	}
+	return name;
+}
+
 static int read_exports(void)
 {

[ ... ]

tools/objtool/klp-diff.c static int read_exports(void) · line 184

Quoted 7 lines
tools/objtool/klp-diff.c +3 -0
@@ -150,6 +179,9 @@ static int read_exports(void)
 			return -1;
 		}
 
+		if (strcmp(export->mod, "vmlinux"))
+			export->mod = normalize_modname(export->mod);
+

[Severity: Medium]
Does this assignment leak the original pointer returned by strdup()?

Looking at read_exports(), export->mod is allocated via strdup() right before this check:

        export->mod = strdup(mod);
        if (!export->mod) {
                ERROR_GLIBC("strdup");
                return -1;
        }

        if (strcmp(export->mod, "vmlinux"))
                export->mod = normalize_modname(export->mod);

When processing module paths with a slash, normalize_modname() returns an interior pointer (slash + 1).

If this offset pointer overwrites export->mod, the original base address from strdup() is permanently lost.

While objtool often relies on process termination for cleanup, if these strings are ever freed later, passing an interior pointer to free() will cause an invalid free crash.

Could this be avoided by shifting the string contents in-place with memmove() instead?

Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=2
#16 lore raw

Re: [PATCH 05/14] objtool/klp: Add .klp.symid for sympos disambiguation

In reply to Josh Poimboeuf
Thank you for your contribution! Sashiko AI review found 1 potential issue(s) to consider: - [Low] Relocations in .klp.symid pointing to discarded sections (.exitcall.exit, .exit.text, etc.) will…

Thank you for your contribution! Sashiko AI review found 1 potential issue(s) to consider:
- [Low] Relocations in .klp.symid pointing to discarded sections (.exitcall.exit, .exit.text, etc.) will cause a link-time error when building vmlinux. --

--- Patch [5]: [PATCH 05/14] objtool/klp: Add .klp.symid for sympos disambiguation --- commit 09454266fcd41f3c022cac215ab86d1269c37d52
Author: Josh Poimboeuf <[email protected]>

objtool/klp: Add .klp.symid for sympos disambiguation

This commit introduces a new .klp.symid section to vmlinux.o to help livepatch reliably determine the sympos of duplicate-named symbols. It emits an array of identifiers and relocations that survives the final link, allowing klp-diff to correlate symbols between vmlinux.o and vmlinux.

Quoted 5 lines
tools/objtool/klp-symid.c new file +0 -0
new file mode 100644
index 0000000000000..cf188cdfa6079

[ ... ]

Quoted 7 lines
tools/objtool/klp-symid.c new file +7 -0
+static const char * const discarded_secs[] = {
+	".discard",
+	".modinfo",
+	"__tracepoint_check",
+};
+
+static bool discarded_sec(struct section *sec)

tools/objtool/klp-symid.c line 47

Quoted 10 lines
tools/objtool/klp-symid.c new file +10 -0
+{
+	if (!(sec->sh.sh_flags & SHF_ALLOC))
+		return true;
+
+	for (int i = 0; i < ARRAY_SIZE(discarded_secs); i++)
+		if (strstarts(sec->name, discarded_secs[i]))
+			return true;
+
+	return false;
+}

[Severity: Low]
Should the discarded_secs array also include .exitcall.exit and .exit. sections?

Because these exit sections have the SHF_ALLOC flag set, the first check in discarded_sec() will not catch them. If they are also omitted from the discarded_secs array, klp_create_symid_sections() will mistakenly generate relocations pointing to them.

Since the linker script unconditionally discards .exitcall.exit via the DISCARDS macro, generating relocations against it causes a deterministic link-time error ("relocation refers to a discarded section") when building vmlinux.

Could this happen in practice? Common driver exit handlers (e.g., module_cleanup used by drivers like cx18 and ivtv) often result in duplicate static symbols like __exitcall_module_cleanup in the .exitcall.exit section when the modules are built-in.

[ ... ]

Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=5
#28 lore raw

Re: [PATCH 08/14] objtool/klp,livepatch: Resolve module symbols against core kallsyms

In reply to Josh Poimboeuf
Thank you for your contribution! Sashiko AI review found 1 potential issue(s) to consider: - [Medium] objtool's mod_sym_in_kallsyms() diverges from the kernel's is_core_symbol() logic on PowerPC 64…

Thank you for your contribution! Sashiko AI review found 1 potential issue(s) to consider:
- [Medium] objtool's mod_sym_in_kallsyms() diverges from the kernel's is_core_symbol() logic on PowerPC 64, leading to incorrect sympos calculation for livepatches. --

--- Patch [8]: [PATCH 08/14] objtool/klp,livepatch: Resolve module symbols against core kallsyms --- commit 5384e2809ccb86e9339029bde934f86f745e7b61
Author: Josh Poimboeuf <[email protected]>

objtool/klp,livepatch: Resolve module symbols against core kallsyms

This commit updates livepatch to use a module's position in the core symbol table as its sympos. It enforces this by using module_kallsyms_on_each_core_symbol() at runtime and mirroring the is_core_symbol() filter in objtool.

Quoted 7 lines
tools/objtool/klp-sympos.c +0 -0
index bbfae516d3395..34bb8d1971bd2 100644
@@ -367,6 +367,17 @@ static unsigned long find_vmlinux_sympos(struct symbol *sym)
 	return sympos;
 }

tools/objtool/klp-sympos.c static unsigned long find_vmlinux_sympos(struct symbol *sym) · line 378

Quoted 10 lines
tools/objtool/klp-sympos.c +9 -0
 
+static bool mod_sym_in_kallsyms(struct symbol *sym)
+{
+	if (is_undef_sym(sym))
+		return false;
+
+	if (!(sym->sec->sh.sh_flags & SHF_ALLOC))
+		return false;
+
+	return !strstarts(sym->sec->name, ".init");

[Severity: Medium]
Will this hardcoded filter improperly exclude .init symbols on PowerPC 64?

On PowerPC 64, module_init_section() unconditionally returns false, meaning the kernel treats .init sections as core memory. This hardcoded string matching appears to diverge from the kernel's is_core_symbol() logic on that architecture, potentially leading to incorrect sympos calculations for livepatches if an object contains duplicate symbols where at least one resides in an .init section.

Quoted 1 line
tools/objtool/klp-sympos.c +1 -0
+}
Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=8
author maintainer
#5 lore raw

Re: [PATCH 02/14] objtool/klp: Normalize Module.symvers paths to module names

In reply to [email protected]
Quoted 21 lines · On Mon, Aug 03, 2026 at 03:37:11AM +0000, [email protected] wrote:

[Severity: Medium]
Does this assignment leak the original pointer returned by strdup()?

Looking at read_exports(), export->mod is allocated via strdup() right before this check:

        export->mod = strdup(mod);
        if (!export->mod) {
                ERROR_GLIBC("strdup");
                return -1;
        }

        if (strcmp(export->mod, "vmlinux"))
                export->mod = normalize_modname(export->mod);

When processing module paths with a slash, normalize_modname() returns an interior pointer (slash + 1).

If this offset pointer overwrites export->mod, the original base address from strdup() is permanently lost.

Quoted 6 lines

While objtool often relies on process termination for cleanup, if these strings are ever freed later, passing an interior pointer to free() will cause an invalid free crash.

Could this be avoided by shifting the string contents in-place with memmove() instead?

Perhaps, but these are small memory leaks and klp diff frees all its memory when it exits so I'm not sure we care.

Signature · 1 line
Josh
author maintainer
#17 lore raw

Re: [PATCH 05/14] objtool/klp: Add .klp.symid for sympos disambiguation

In reply to [email protected]
Quoted 53 lines · On Mon, Aug 03, 2026 at 03:41:15AM +0000, [email protected] wrote:

Thank you for your contribution! Sashiko AI review found 1 potential issue(s) to consider:
- [Low] Relocations in .klp.symid pointing to discarded sections (.exitcall.exit, .exit.text, etc.) will cause a link-time error when building vmlinux. --

--- Patch [5]: [PATCH 05/14] objtool/klp: Add .klp.symid for sympos disambiguation --- commit 09454266fcd41f3c022cac215ab86d1269c37d52
Author: Josh Poimboeuf <[email protected]>

objtool/klp: Add .klp.symid for sympos disambiguation

This commit introduces a new .klp.symid section to vmlinux.o to help livepatch reliably determine the sympos of duplicate-named symbols. It emits an array of identifiers and relocations that survives the final link, allowing klp-diff to correlate symbols between vmlinux.o and vmlinux.

Quoted 5 lines
tools/objtool/klp-symid.c new file +0 -0
new file mode 100644
index 0000000000000..cf188cdfa6079

[ ... ]

Quoted 7 lines
tools/objtool/klp-symid.c new file +7 -0
+static const char * const discarded_secs[] = {
+	".discard",
+	".modinfo",
+	"__tracepoint_check",
+};
+
+static bool discarded_sec(struct section *sec)

tools/objtool/klp-symid.c line 47

Quoted 10 lines
tools/objtool/klp-symid.c new file +10 -0
+{
+	if (!(sec->sh.sh_flags & SHF_ALLOC))
+		return true;
+
+	for (int i = 0; i < ARRAY_SIZE(discarded_secs); i++)
+		if (strstarts(sec->name, discarded_secs[i]))
+			return true;
+
+	return false;
+}

[Severity: Low]
Should the discarded_secs array also include .exitcall.exit and .exit. sections?

Because these exit sections have the SHF_ALLOC flag set, the first check in discarded_sec() will not catch them. If they are also omitted from the discarded_secs array, klp_create_symid_sections() will mistakenly generate relocations pointing to them.

Since the linker script unconditionally discards .exitcall.exit via the DISCARDS macro, generating relocations against it causes a deterministic link-time error ("relocation refers to a discarded section") when building vmlinux.

Quoted 4 lines

Could this happen in practice? Common driver exit handlers (e.g., module_cleanup used by drivers like cx18 and ivtv) often result in duplicate static symbols like __exitcall_module_cleanup in the .exitcall.exit section when the modules are built-in.

I'm not convinced this can happen in practice. Why would somebody be trying to patch or reference a module exit symbol anyway?

Signature · 1 line
Josh
merge bot Applied
#24 lore raw

[tip: objtool/core] objtool/klp: Fix symbol resolution for duplicate data symbols

In reply to Josh Poimboeuf
The following commit has been merged into the objtool/core branch of tip:

The following commit has been merged into the objtool/core branch of tip:

Commit-ID:     15fa203ef91e8a303c322eaaa8ca01a6ddaf94dc
Gitweb:        https://git.kernel.org/tip/15fa203ef91e8a303c322eaaa8ca01a6ddaf94dc
Author:        Josh Poimboeuf <[email protected]>
AuthorDate:    Sun, 02 Aug 2026 20:24:28 -07:00
Committer:     Ingo Molnar <[email protected]>
CommitterDate: Mon, 03 Aug 2026 07:12:39 +02:00

objtool/klp: Fix symbol resolution for duplicate data symbols

find_sympos() calculates a sympos used by livepatch to disambiguate duplicately-named symbols. For function symbols, there's a hack which counts .text.unlikely symbols before other .text symbols, matching the linker script's section ordering.

Not only is the hack fragile, data symbols can have the same problem. So for example, adding a reference to pwq_cache in ep_unregister_pollwait() can trigger a corrupt sympos and a relocation to the wrong pwq_cache symbol in the livepatch module, resulting in a crash or undefined behavior.

Remove the existing hack in favor of a fully deterministic solution, using the new .klp.symid table to derive the symbol-to-id mapping from the original vmlinux.o and the id-to-address mapping from the corresponding vmlinux, which can then be used to determine the exact sympos associated with the original vmlinux.

Modules don't need any special treatment: the .ko has the same section/symbol ordering as the original whole-archive symbol table.

---
 scripts/livepatch/klp-build         |   4 +-
 tools/objtool/Build                 |   3 +-
 tools/objtool/include/objtool/klp.h |   5 +-
 tools/objtool/klp-diff.c            |  66 +----
 tools/objtool/klp-sympos.c          | 411 +++++++++++++++++++++++++++-
 5 files changed, 427 insertions(+), 62 deletions(-)
 create mode 100644 tools/objtool/klp-sympos.c
scripts/livepatch/klp-build +4 -0
index f94e324..b52a848 100755
@@ -611,6 +611,8 @@ copy_orig_objects() {
 	done
 	xtrace_restore
 
+	cp -f "$PWD/vmlinux" "$ORIG_DIR" || die "missing vmlinux"
+
 	mv -f "$TMP_DIR/build.log" "$ORIG_DIR"
 	touch "$TIMESTAMP"
 	touch "$ORIG_DIR/.complete"
@@ -681,6 +683,8 @@ generate_checksums() {
 		"$OBJTOOL" klp checksum "$dest"
 	done
 
+	[[ -f "$src_dir/vmlinux" ]] && cp -f "$src_dir/vmlinux" "$dest_dir"
+
 	touch "$dest_dir/.complete"
 }
 
tools/objtool/Build +2 -1
index 506f89b..59f9486 100644
@@ -13,7 +13,8 @@ objtool-$(BUILD_DISAS) += disas.o
 objtool-$(BUILD_DISAS) += trace.o
 
 objtool-$(BUILD_ORC) += orc_gen.o orc_dump.o
-objtool-$(BUILD_KLP) += builtin-klp.o klp-checksum.o klp-diff.o klp-post-link.o
+objtool-$(BUILD_KLP) += builtin-klp.o klp-checksum.o klp-diff.o \
+			klp-post-link.o klp-sympos.o
 
 objtool-y += libstring.o
 objtool-y += libctype.o
tools/objtool/include/objtool/klp.h +5 -0
index 4d3c3bd..0118c2c 100644
@@ -43,9 +43,14 @@ struct klp_symid {
 };
 
 struct objtool_file;
+struct elf;
+struct symbol;
 
 int klp_create_symid_sections(struct objtool_file *file);
 
+int klp_sympos_init(struct elf *orig);
+unsigned long klp_find_sympos(struct elf *elf, struct symbol *sym);
+
 int cmd_klp_checksum(int argc, const char **argv);
 int cmd_klp_diff(int argc, const char **argv);
 int cmd_klp_post_link(int argc, const char **argv);
tools/objtool/klp-diff.c +5 -61

90 lines not on this page · raw message

tools/objtool/klp-sympos.c new file +411 -0

411 lines not on this page · raw message

merge bot Applied
#21 lore raw

[tip: objtool/core] objtool/klp: Add .klp.symid for sympos disambiguation

In reply to Josh Poimboeuf
The following commit has been merged into the objtool/core branch of tip:

The following commit has been merged into the objtool/core branch of tip:

Commit-ID:     029223d301620bc4e1086696047b0d5d6eba5edd
Gitweb:        https://git.kernel.org/tip/029223d301620bc4e1086696047b0d5d6eba5edd
Author:        Josh Poimboeuf <[email protected]>
AuthorDate:    Sun, 02 Aug 2026 20:24:27 -07:00
Committer:     Ingo Molnar <[email protected]>
CommitterDate: Mon, 03 Aug 2026 07:12:39 +02:00

objtool/klp: Add .klp.symid for sympos disambiguation

Livepatch identifies a duplicate-named symbol by its position (sympos) among same-named kallsyms entries, which for vmlinux are counted in ascending address order in the final linked kernel. That order can't be reliably derived from vmlinux.o: the final link reorders sub-sections (.text.unlikely*, .data..*, etc).

Bridge the gap with a new .klp.symid section which can be used to correlate symbols between vmlinux.o and vmlinux so that klp-diff can reliably determine the sympos.

The table can't survive --gc-sections: keeping it alive would keep every duplicate-named symbol's section alive, so the reference kernel would stop matching the one which ships. klp-build rejects CONFIG_LD_DEAD_CODE_DATA_ELIMINATION instead. Nothing is lost today:
x86_64 is the only HAVE_KLP_BUILD arch and doesn't select HAVE_LD_DEAD_CODE_DATA_ELIMINATION, arm64 and s390 have never selected it either, and on powerpc, it's still EXPERIMENTAL and disabled by every distro kernel.

This is the build-time half of reliable vmlinux sympos computation; "objtool klp diff" will consume the table in a subsequent commit.

---
 include/asm-generic/vmlinux.lds.h       |  10 +-
 scripts/Makefile.vmlinux_o              |   3 +-
 scripts/livepatch/klp-build             |   5 +-
 scripts/mod/modpost.c                   |   1 +-
 tools/objtool/Build                     |   1 +-
 tools/objtool/builtin-check.c           |   7 +-
 tools/objtool/check.c                   |   7 +-
 tools/objtool/include/objtool/builtin.h |   1 +-
 tools/objtool/include/objtool/klp.h     |  15 +++-
 tools/objtool/klp-symid.c               | 117 +++++++++++++++++++++++-
 10 files changed, 166 insertions(+), 1 deletion(-)
 create mode 100644 tools/objtool/klp-symid.c
include/asm-generic/vmlinux.lds.h +9 -1
index 5659f4b..ee9c5d3 100644
@@ -839,12 +839,20 @@
 		.stab.index 0 : { *(.stab.index) }			\
 		.stab.indexstr 0 : { *(.stab.indexstr) }
 
+#ifdef CONFIG_KLP_BUILD
+#define KLP_SYMID							\
+		.klp.symid 0 : { *(.klp.symid) }
+#else
+#define KLP_SYMID
+#endif
+
 /* Required sections not related to debugging. */
 #define ELF_DETAILS							\
 		.comment 0 : { *(.comment) }				\
 		.symtab 0 : { *(.symtab) }				\
 		.strtab 0 : { *(.strtab) }				\
-		.shstrtab 0 : { *(.shstrtab) }
+		.shstrtab 0 : { *(.shstrtab) }				\
+		KLP_SYMID
 
 #define MODINFO								\
 		.modinfo : { *(.modinfo) . = ALIGN(8); }
scripts/Makefile.vmlinux_o +3 -0
index 527352c..24a3a4f 100644
@@ -47,6 +47,9 @@ endif
 vmlinux-objtool-args-$(CONFIG_NOINSTR_VALIDATION)	+= --noinstr \
 							   $(if $(or $(CONFIG_MITIGATION_UNRET_ENTRY),$(CONFIG_MITIGATION_SRSO)), --unret)
 
+# Only used for builds initiated by klp-build
+vmlinux-objtool-args-$(if $(KLP_SYMIDS),y)		+= --klp-symids
+
 objtool-args = $(vmlinux-objtool-args-y) --link
 
 # Link of vmlinux.o used for section mismatch analysis
scripts/livepatch/klp-build +5 -0
index a8c103c..f94e324 100755
@@ -271,6 +271,9 @@ validate_config() {
 	[[ -v CONFIG_GCC_PLUGIN_RANDSTRUCT ]] &&	\
 		die "kernel option 'CONFIG_GCC_PLUGIN_RANDSTRUCT' not supported"
 
+	[[ -v CONFIG_LD_DEAD_CODE_DATA_ELIMINATION ]] &&		\
+		die "kernel option 'CONFIG_LD_DEAD_CODE_DATA_ELIMINATION' not supported"
+
 	[[ -v CONFIG_AS_IS_LLVM ]] &&				\
 		[[ "$CONFIG_AS_VERSION" -lt 200000 ]] &&	\
 		die "Clang assembler version < 20 not supported"
@@ -555,6 +558,8 @@ build_kernel() {
 	#
 	cmd+=("KBUILD_MODPOST_WARN=1")
 
+	cmd+=("KLP_SYMIDS=1")
+
 	if [[ -v VERBOSE ]]; then
 		cmd+=("V=1")
 	else
scripts/mod/modpost.c +1 -0
index a7b72a8..027944f 100644
@@ -767,6 +767,7 @@ static const char *const section_white_list[] =
 	".llvm.call-graph-profile",	/* call graph */
 	"__llvm_covfun",
 	"__llvm_covmap",
+	".klp.symid",			/* objtool --klp-symids */
 	NULL
 };
 
tools/objtool/Build +1 -0
index 93a37b0..506f89b 100644
@@ -6,6 +6,7 @@ objtool-y += check.o
 objtool-y += special.o
 objtool-y += builtin-check.o
 objtool-y += elf.o
+objtool-y += klp-symid.o
 objtool-y += objtool.o
 
 objtool-$(BUILD_DISAS) += disas.o
tools/objtool/builtin-check.c +7 -0
index 118c3de..75b11dc 100644
@@ -76,6 +76,7 @@ static const struct option check_options[] = {
 	OPT_STRING_OPTARG('d',	 "disas", &opts.disas, "function-pattern", "disassemble functions", "*"),
 	OPT_CALLBACK_OPTARG('h', "hacks", NULL, NULL, "jump_label,noinstr,skylake", "patch toolchain bugs/limitations", parse_hacks),
 	OPT_BOOLEAN('i',	 "ibt", &opts.ibt, "validate and annotate IBT"),
+	OPT_BOOLEAN(0,		 "klp-symids", &opts.klp_symids, "generate .klp.symids for duplicate symbol disambiguation"),
 	OPT_BOOLEAN('m',	 "mcount", &opts.mcount, "annotate mcount/fentry calls for ftrace"),
 	OPT_BOOLEAN(0,		 "noabs", &opts.noabs, "reject absolute references in allocatable sections"),
 	OPT_BOOLEAN('n',	 "noinstr", &opts.noinstr, "validate noinstr rules"),
@@ -174,10 +175,16 @@ static bool opts_valid(void)
 		return false;
 	}
 
+	if (opts.klp_symids && !opts.link) {
+		ERROR("--klp-symids requires --link");
+		return false;
+	}
+
 	if (opts.disas			||
 	    opts.hack_jump_label	||
 	    opts.hack_noinstr		||
 	    opts.ibt			||
+	    opts.klp_symids		||
 	    opts.mcount			||
 	    opts.noabs			||
 	    opts.noinstr		||
tools/objtool/check.c +7 -0
index f03dd59..a98d758 100644
@@ -15,6 +15,7 @@
 #include <objtool/arch.h>
 #include <objtool/disas.h>
 #include <objtool/check.h>
+#include <objtool/klp.h>
 #include <objtool/special.h>
 #include <objtool/trace.h>
 #include <objtool/warn.h>
@@ -4923,6 +4924,12 @@ int check(struct objtool_file *file)
 			goto out;
 	}
 
+	if (opts.klp_symids) {
+		ret = klp_create_symid_sections(file);
+		if (ret)
+			goto out;
+	}
+
 	if (opts.noabs)
 		warnings += check_abs_references(file);
 
tools/objtool/include/objtool/builtin.h +1 -0
index e844e9c..349690b 100644
@@ -16,6 +16,7 @@ struct opts {
 	bool hack_noinstr;
 	bool hack_skylake;
 	bool ibt;
+	bool klp_symids;
 	bool mcount;
 	bool noabs;
 	bool noinstr;
tools/objtool/include/objtool/klp.h +15 -0
index aab6db4..4d3c3bd 100644
@@ -31,6 +31,21 @@ struct klp_reloc {
 	u32 type;
 };
 
+/*
+ * .klp.symid is used to correlate symbols between vmlinux.o and vmlinux, for
+ * calculating sympos to disambiguate duplicately-named symbols.
+ */
+#define KLP_SYMID_SEC	".klp.symid"
+
+struct klp_symid {
+	u64 id;
+	u64 addr;
+};
+
+struct objtool_file;
+
+int klp_create_symid_sections(struct objtool_file *file);
+
 int cmd_klp_checksum(int argc, const char **argv);
 int cmd_klp_diff(int argc, const char **argv);
 int cmd_klp_post_link(int argc, const char **argv);
tools/objtool/klp-symid.c new file +117 -0

117 lines not on this page · raw message

merge bot Applied
#14 lore raw

[tip: objtool/core] objtool/klp: Skip hidden directories when finding objects

In reply to Josh Poimboeuf
The following commit has been merged into the objtool/core branch of tip:

The following commit has been merged into the objtool/core branch of tip:

Commit-ID:     f5f762fc93d0b81d30b815a2f96320909ad10eb3
Gitweb:        https://git.kernel.org/tip/f5f762fc93d0b81d30b815a2f96320909ad10eb3
Author:        Josh Poimboeuf <[email protected]>
AuthorDate:    Sun, 02 Aug 2026 20:24:26 -07:00
Committer:     Ingo Molnar <[email protected]>
CommitterDate: Mon, 03 Aug 2026 07:12:39 +02:00

objtool/klp: Skip hidden directories when finding objects

klp-build's find_objects() scans the whole tree for vmlinux.o and .ko files, pruning only klp-tmp/ and .git/. Development tools can leave other dot-directories in the tree. Kernel objects never live under hidden directories, so prune them all.

---
 scripts/livepatch/klp-build | 5 +++--
 1 file changed, 3 insertions(+), 2 deletions(-)
scripts/livepatch/klp-build +3 -2
index c4a7acf..a8c103c 100755
@@ -575,8 +575,9 @@ find_objects() {
 	local opts=("$@")
 
 	# Find root-level vmlinux.o and non-root-level .ko files,
-	# excluding klp-tmp/ and .git/
-	find "$PWD" \( -path "$TMP_DIR" -o -path "$PWD/.git" -o -regex "$PWD/[^/][^/]*\.ko" \) -prune -o \
+	# excluding klp-tmp/ and hidden directories.
+	find "$PWD" -mindepth 1 \
+		    \( -path "$TMP_DIR" -o -name ".*" -o -regex "$PWD/[^/][^/]*\.ko" \) -prune -o \
 		    -type f "${opts[@]}"				\
 		    \( -name "*.ko" -o -path "$PWD/vmlinux.o" \)	\
 		    -printf '%P\n'
merge bot Applied
#8 lore raw

[tip: objtool/core] objtool/klp: Fix false module dependencies caused by dead relocs

In reply to Josh Poimboeuf
The following commit has been merged into the objtool/core branch of tip:

The following commit has been merged into the objtool/core branch of tip:

Commit-ID:     5ca8c91d1ea6534842e7e0065d15104d802506cd
Gitweb:        https://git.kernel.org/tip/5ca8c91d1ea6534842e7e0065d15104d802506cd
Author:        Josh Poimboeuf <[email protected]>
AuthorDate:    Sun, 02 Aug 2026 20:24:25 -07:00
Committer:     Ingo Molnar <[email protected]>
CommitterDate: Mon, 03 Aug 2026 07:12:38 +02:00

objtool/klp: Fix false module dependencies caused by dead relocs

When creating a klp reloc, klp-diff keeps the original relocation but converts the referenced symbol to an UNDEF/WEAK placeholder tombstone symbol, which gets fully disabled later by klp post-link. The tombstone symbol is only needed to avoid confusing objtool when it does the final run on the patch module.

However, for references to exported symbols, modpost sees the reference to the tombstone symbol as a real reference to an exported symbol, resulting in a false module dependency getting created.

Further, for a reference to a tombstone symbol which is exported into a module namespace, e.g. via EXPORT_SYMBOL_FOR_KVM_INTERNAL(), modpost can't satisfy the dependency, resulting in a warning like the following:

module ... uses symbol kvm_flush_remote_tlbs from namespace module:kvm-amd,kvm-intel, but does not import it.

Rename the placeholder tombstone symbols to ".klp.tombstone.<name>" so modpost no longer recognizes them.

---
 tools/objtool/elf.c                 | 13 +++++++++++++
 tools/objtool/include/objtool/klp.h |  2 ++
 tools/objtool/klp-diff.c            | 16 ++++++++++++----
 3 files changed, 27 insertions(+), 4 deletions(-)
tools/objtool/elf.c +13 -0
index 33c95a7..a791f4e 100644
@@ -23,6 +23,7 @@
 #include <linux/log2.h>
 #include <objtool/builtin.h>
 #include <objtool/elf.h>
+#include <objtool/klp.h>
 #include <objtool/warn.h>
 
 static ssize_t demangled_name_len(const char *name);
@@ -626,6 +627,18 @@ static int read_symbols(struct elf *elf)
 			return -1;
 		}
 
+		/*
+		 * "klp diff" renames the placeholder symbols of KLP relocs to
+		 * hide them from modpost.  Hide the prefix from the rest of
+		 * objtool so its many name-based heuristics (noreturns,
+		 * uaccess safe list, ...) still see the original symbol name.
+		 *
+		 * st_name is left alone, so the renamed symbol is preserved in
+		 * the output file.
+		 */
+		if (strstarts(sym->name, KLP_TOMBSTONE_PREFIX))
+			sym->name += strlen(KLP_TOMBSTONE_PREFIX);
+
 		if ((sym->sym.st_shndx > SHN_UNDEF &&
 		     sym->sym.st_shndx < SHN_LORESERVE) ||
 		    (shndx_data && sym->sym.st_shndx == SHN_XINDEX)) {
tools/objtool/include/objtool/klp.h +2 -0
index 6f60cf0..aab6db4 100644
@@ -23,6 +23,8 @@
 #define KLP_RELOCS_SEC	"__klp_relocs"
 #define KLP_STRINGS_SEC	".rodata.klp.str1.1"
 
+#define KLP_TOMBSTONE_PREFIX	".klp.tombstone."
+
 struct klp_reloc {
 	void *offset;
 	void *sym;
tools/objtool/klp-diff.c +12 -4
index 15d37d9..75ba0e0 100644
@@ -1362,6 +1362,7 @@ static int clone_reloc_klp(struct elfs *e, struct reloc *patched_reloc,
 	s64 addend = reloc_addend(patched_reloc);
 	const char *sym_modname, *sym_orig_name;
 	static struct section *klp_relocs;
+	char tombstone_name[SYM_NAME_LEN];
 	struct symbol *sym, *klp_sym;
 	unsigned long klp_reloc_off;
 	char sym_name[SYM_NAME_LEN];
@@ -1376,15 +1377,22 @@ static int clone_reloc_klp(struct elfs *e, struct reloc *patched_reloc,
 	/*
 	 * Keep the original reloc intact for now to avoid breaking objtool run
 	 * which relies on proper relocations for many of its features.  This
-	 * will be disabled later by "objtool klp post-link".
+	 * reloc now targets a functionally dead tombstone symbol and will be
+	 * disabled later by "objtool klp post-link".
 	 *
-	 * Convert it to UNDEF (and WEAK to avoid modpost warnings).
+	 * Convert the symbol to UNDEF/WEAK and rename to
+	 * .klp.tombstone.sym_name to prevent modpost from printing warnings or
+	 * creating false module dependencies.  The prefix is hidden from the
+	 * objtool run itself by read_symbols().
 	 */
 
 	sym = patched_sym->clone;
 	if (!sym) {
-		/* STB_WEAK: avoid modpost undefined symbol warnings */
-		sym = elf_create_symbol(e->out, patched_sym->name, NULL,
+		if (snprintf_check(tombstone_name, SYM_NAME_LEN,
+				   KLP_TOMBSTONE_PREFIX "%s", patched_sym->name))
+			return -1;
+
+		sym = elf_create_symbol(e->out, tombstone_name, NULL,
 					STB_WEAK, patched_sym->type, 0, 0);
 		if (!sym)
 			return -1;
merge bot Applied
#6 lore raw

[tip: objtool/core] objtool/klp: Normalize Module.symvers paths to module names

In reply to Josh Poimboeuf
The following commit has been merged into the objtool/core branch of tip:

The following commit has been merged into the objtool/core branch of tip:

Commit-ID:     8668bf91e0508abeb8e98b4edd89032be02228a1
Gitweb:        https://git.kernel.org/tip/8668bf91e0508abeb8e98b4edd89032be02228a1
Author:        Joe Lawrence <[email protected]>
AuthorDate:    Sun, 02 Aug 2026 20:24:24 -07:00
Committer:     Ingo Molnar <[email protected]>
CommitterDate: Mon, 03 Aug 2026 07:12:38 +02:00

objtool/klp: Normalize Module.symvers paths to module names

Module.symvers contains build-tree object paths as module identifiers (e.g., "arch/x86/kvm/kvm") rather than runtime module names ("kvm"). Objtool's clone_reloc_klp() uses this field directly for exported symbols, while unexported symbols correctly go through __find_modname().

This means that exported symbol relocations may land in a .klp.rela section named with the build path rather than the module name. That is a crash waiting to happen: the kernel's livepatch loader silently skips this relocation because it doesn't match the expected klp_object name. The unresolved relocation sits in the newly activated code, crashing when executed.

Normalize export->mod at Module.symvers read time using the same logic as __find_modname() (refactored into a shared normalize_modname() helper).

---
 tools/objtool/klp-diff.c | 49 +++++++++++++++++++++++++++------------
 1 file changed, 34 insertions(+), 15 deletions(-)
tools/objtool/klp-diff.c +34 -15
index aeb99d5..15d37d9 100644
@@ -83,6 +83,35 @@ static char *escape_str(const char *orig)
 	return new;
 }
 
+/*
+ * Convert a build-tree object path to a runtime module name: strip
+ * directory components, replace '-' with '_', and remove file
+ * extensions.  Examples:
+ *
+ *   "arch/x86/kvm/kvm" -> "kvm"
+ *   "arch/x86/kvm/kvm-intel" -> "kvm_intel".
+ *
+ * Used by read_exports() to normalize Module.symvers entries and by
+ * __find_modname() as a fallback when .modinfo lacks a "name=" tag.
+ */
+static char *normalize_modname(char *name)
+{
+	char *slash = strrchr(name, '/');
+
+	if (slash)
+		name = slash + 1;
+
+	for (char *c = name; *c; c++) {
+		if (*c == '-')
+			*c = '_';
+		else if (*c == '.') {
+			*c = '\0';
+			break;
+		}
+	}
+	return name;
+}
+
 static int read_exports(void)
 {
 	const char *symvers = "Module.symvers";
@@ -150,6 +179,9 @@ static int read_exports(void)
 			return -1;
 		}
 
+		if (strcmp(export->mod, "vmlinux"))
+			export->mod = normalize_modname(export->mod);
+
 		export->sym = strdup(sym);
 		if (!export->sym) {
 			ERROR_GLIBC("strdup");
@@ -1140,7 +1172,7 @@ static struct export *find_export(struct symbol *sym)
 static const char *__find_modname(struct elfs *e)
 {
 	struct section *sec;
-	char *name, *slash;
+	char *name;
 
 	sec = find_section_by_name(e->orig, ".modinfo");
 	if (!sec) {
@@ -1158,20 +1190,7 @@ static const char *__find_modname(struct elfs *e)
 		return NULL;
 	}
 
-	slash = strrchr(name, '/');
-	if (slash)
-		name = slash + 1;
-
-	for (char *c = name; *c; c++) {
-		if (*c == '-')
-			*c = '_';
-		else if (*c == '.') {
-			*c = '\0';
-			break;
-		}
-	}
-
-	return name;
+	return normalize_modname(name);
 }
 
 /* Get the object's module name as defined by the kernel (and klp_object) */
merge bot Applied
#2 lore raw

[tip: objtool/core] objtool/klp: Fix module name normalization for paths with dots

In reply to Josh Poimboeuf
The following commit has been merged into the objtool/core branch of tip:

The following commit has been merged into the objtool/core branch of tip:

Commit-ID:     165affd6f095323d953b0ed5823ec4d0db3b7d0d
Gitweb:        https://git.kernel.org/tip/165affd6f095323d953b0ed5823ec4d0db3b7d0d
Author:        Josh Poimboeuf <[email protected]>
AuthorDate:    Sun, 02 Aug 2026 20:24:23 -07:00
Committer:     Ingo Molnar <[email protected]>
CommitterDate: Mon, 03 Aug 2026 07:12:38 +02:00

objtool/klp: Fix module name normalization for paths with dots

When .modinfo has no "name=" tag, __find_modname() falls back to converting the object's build-tree path to a runtime module name by stripping directory components, converting '-' to '_' and truncating the file extension.

It does all that in a single pass over the entire path, so the first dot anywhere in the path ends the name. For an object built in a directory whose name contains a dot, e.g. "drivers/foo-1.0/bar.o", the result is a bogus module name.

Strip the directory components up front so only the basename is scanned for the extension separator.

---
 tools/objtool/klp-diff.c | 10 ++++++----
 1 file changed, 6 insertions(+), 4 deletions(-)
tools/objtool/klp-diff.c +6 -4
index f8787d7..aeb99d5 100644
@@ -1140,7 +1140,7 @@ static struct export *find_export(struct symbol *sym)
 static const char *__find_modname(struct elfs *e)
 {
 	struct section *sec;
-	char *name;
+	char *name, *slash;
 
 	sec = find_section_by_name(e->orig, ".modinfo");
 	if (!sec) {
@@ -1158,10 +1158,12 @@ static const char *__find_modname(struct elfs *e)
 		return NULL;
 	}
 
+	slash = strrchr(name, '/');
+	if (slash)
+		name = slash + 1;
+
 	for (char *c = name; *c; c++) {
-		if (*c == '/')
-			name = c + 1;
-		else if (*c == '-')
+		if (*c == '-')
 			*c = '_';
 		else if (*c == '.') {
 			*c = '\0';
#22 lore raw

Re: [tip: objtool/core] objtool/klp: Add .klp.symid for sympos disambiguation

In reply to tip-bot2 for Josh Poimboeuf
Thank you for your contribution! Sashiko AI review found 1 potential issue(s) to consider: - [Low] The `.exitcall.exit` section is discarded during the final vmlinux link, but…

Thank you for your contribution! Sashiko AI review found 1 potential issue(s) to consider:
- [Low] The .exitcall.exit section is discarded during the final vmlinux link, but klp_create_symid_sections incorrectly generates .klp.symid relocations to duplicate static symbols within it. --

--- Patch [1]: [tip: objtool/core] objtool/klp: Add .klp.symid for sympos disambiguation --- commit 95a71e72a77916e00e9b21eb4e2fc9a9e4c3258d

Author: Josh Poimboeuf <[email protected]>
Date:   Mon Aug 3 05:49:39 2026 +0000

objtool/klp: Add .klp.symid for sympos disambiguation

Livepatch identifies a duplicate-named symbol by its position (sympos) among same-named kallsyms entries, which for vmlinux are counted in ascending address order in the final linked kernel. This commit adds a new .klp.symid section to bridge the gap and correlate symbols between vmlinux.o and vmlinux.

Quoted 5 lines
tools/objtool/klp-symid.c new file +0 -0
new file mode 100644
index 0000000000000..cf188cdfa6079

[ ... ]

tools/objtool/klp-symid.c line 35

Quoted 5 lines
tools/objtool/klp-symid.c new file +5 -0
+static const char * const discarded_secs[] = {
+	".discard",
+	".modinfo",
+	"__tracepoint_check",
+};

[Severity: Low]
Does this list need to include ".exitcall.exit"?

When built-in components use module_exit() with identical function names (like sm4_exit in multiple x86 crypto modules), duplicate static variables are created in the .exitcall.exit section.

Because this section is missing from discarded_secs[], symid_needed() generates R_ABS64 relocations in .klp.symid to these symbols.

Since .exitcall.exit is unconditionally discarded by the linker during the final vmlinux link, this can cause a fatal linker error: ".klp.symid refers to discarded section .exitcall.exit".

Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/178573617913.1210945.4137827646322421739.tip-bot2@tip-bot2?part=1
author maintainer NAK
#26 lore raw

Re: [PATCH 07/14] module: Add module_kallsyms_on_each_core_symbol()

In reply to Josh Poimboeuf
Quoted 11 lines · Josh Poimboeuf

module_kallsyms_on_each_symbol() iterates mod->kallsyms, which points at the full init symbol table until do_init_module() swaps it out. The set of symbols it reports thus differs based on whether init memory has been freed yet.

Add module_kallsyms_on_each_core_symbol() for callers which need a symbol's position to be the same before and after that swap. core_kallsyms is fully populated by add_kallsyms() before the module leaves MODULE_STATE_UNFORMED, so it's readable on both paths.

NAK

The Sashiko comment made me realize this is not worth adding kernel code for. A duplicate symbol name between init and non-init module code is somewhere between exceedingly rare and non-existent. I'll submit another patch separately which will make it a build error for now.

Signature · 1 line
Josh
author maintainer NAK
#29 lore raw

Re: [PATCH 08/14] objtool/klp,livepatch: Resolve module symbols against core kallsyms

In reply to Josh Poimboeuf
Quoted 22 lines · Josh Poimboeuf

For patching a module, klp_find_sympos() counts every symbol table entry whose name matches. However, the module loader only includes symbols matched by is_core_symbol().

The runtime count is inconsistent as well. It's done by module_kallsyms_on_each_symbol(), which iterates the full init symbol table until do_init_module() swaps in the cut-down core table, so the same symbol can have different positions depending on whether init memory has been freed yet.

Define a module's sympos as its position in the core symbol table, which is what sympos already means for a live module and what users see in /proc/kallsyms. Enforce that on both ends: count with module_kallsyms_on_each_core_symbol() at runtime, and mirror the is_core_symbol() filter in objtool with a new mod_sym_in_kallsyms() helper.

The init-layout half of the filter is only correct if .exit sections are core sections, which requires CONFIG_MODULE_UNLOAD, otherwise .exit code is laid out as part of init memory and freed after module init. Enforce CONFIG_MODULE_UNLOAD to ensure that behavior is deterministic.

Quoted 7 lines

Symbols which exist only in init sections are no longer resolvable, but they never were once the module went live, and init memory is freed after module init anyway.

Fixes dd590d4d57eb ("objtool/klp: Introduce klp diff subcommand for diffing object files")
Fixes b2b018ef4867 ("livepatch: add old_sympos as disambiguator field to klp_func")

NAK - as mentioned for the previous patch, this is a theoretical edge case which I will fix in a different way.

Signature · 1 line
Josh
#18 lore raw

Re: [PATCH 05/14] objtool/klp: Add .klp.symid for sympos disambiguation

In reply to Josh Poimboeuf
Quoted 54 lines · Josh Poimboeuf
Quoted 53 lines · On Mon, Aug 03, 2026 at 03:41:15AM +0000, [email protected] wrote:

Thank you for your contribution! Sashiko AI review found 1 potential issue(s) to consider:
- [Low] Relocations in .klp.symid pointing to discarded sections (.exitcall.exit, .exit.text, etc.) will cause a link-time error when building vmlinux. --

--- Patch [5]: [PATCH 05/14] objtool/klp: Add .klp.symid for sympos disambiguation --- commit 09454266fcd41f3c022cac215ab86d1269c37d52
Author: Josh Poimboeuf <[email protected]>

objtool/klp: Add .klp.symid for sympos disambiguation

This commit introduces a new .klp.symid section to vmlinux.o to help livepatch reliably determine the sympos of duplicate-named symbols. It emits an array of identifiers and relocations that survives the final link, allowing klp-diff to correlate symbols between vmlinux.o and vmlinux.

Quoted 5 lines
tools/objtool/klp-symid.c new file +0 -0
new file mode 100644
index 0000000000000..cf188cdfa6079

[ ... ]

Quoted 7 lines
tools/objtool/klp-symid.c new file +7 -0
+static const char * const discarded_secs[] = {
+	".discard",
+	".modinfo",
+	"__tracepoint_check",
+};
+
+static bool discarded_sec(struct section *sec)

tools/objtool/klp-symid.c

Quoted 10 lines
tools/objtool/klp-symid.c new file +10 -0
+{
+	if (!(sec->sh.sh_flags & SHF_ALLOC))
+		return true;
+
+	for (int i = 0; i < ARRAY_SIZE(discarded_secs); i++)
+		if (strstarts(sec->name, discarded_secs[i]))
+			return true;
+
+	return false;
+}

[Severity: Low]
Should the discarded_secs array also include .exitcall.exit and .exit. sections?

Because these exit sections have the SHF_ALLOC flag set, the first check in discarded_sec() will not catch them. If they are also omitted from the discarded_secs array, klp_create_symid_sections() will mistakenly generate relocations pointing to them.

Since the linker script unconditionally discards .exitcall.exit via the DISCARDS macro, generating relocations against it causes a deterministic link-time error ("relocation refers to a discarded section") when building vmlinux.

Quoted 7 lines
Quoted 4 lines

Could this happen in practice? Common driver exit handlers (e.g., module_cleanup used by drivers like cx18 and ivtv) often result in duplicate static symbols like __exitcall_module_cleanup in the .exitcall.exit section when the modules are built-in.

I'm not convinced this can happen in practice. Why would somebody be trying to patch or reference a module exit symbol anyway?

I see this on my arm64 host with your arm64 support patches applied:

make KLP_SYMIDS=1 -j$(nproc) vmlinux
DESCEND objtool
DESCEND bpf/resolve_btfids
INSTALL libsubcmd_headers

  UPD     include/generated/utsversion.h
  CC      init/version-timestamp.o
  KSYMS   .tmp_vmlinux0.kallsyms.S
  AS      .tmp_vmlinux0.kallsyms.o
  LD      .tmp_vmlinux1

__exitcall_aes_mod_exit' referenced in section .klp.symid' of vmlinux.o: defined in discarded section .exitcall.exit' of vmlinux.o __exitcall_aes_mod_exit' referenced in section .klp.symid' of vmlinux.o: defined in discarded section .exitcall.exit' of vmlinux.o __exitcall_dax_exit' referenced in section .klp.symid' of vmlinux.o: defined in discarded section .exitcall.exit' of vmlinux.o __exitcall_dax_exit' referenced in section .klp.symid' of vmlinux.o: defined in discarded section .exitcall.exit' of vmlinux.o __exitcall_usb_serial_module_exit' referenced in section .klp.symid' of vmlinux.o: defined in discarded section .exitcall.exit' of vmlinux.o __exitcall_usb_serial_module_exit' referenced in section .klp.symid' of vmlinux.o: defined in discarded section .exitcall.exit' of vmlinux.o __exitcall_hid_exit' referenced in section .klp.symid' of vmlinux.o: defined in discarded section .exitcall.exit' of vmlinux.o __exitcall_hid_exit' referenced in section .klp.symid' of vmlinux.o: defined in discarded section .exitcall.exit' of vmlinux.o make[2]: *** [scripts/Makefile.vmlinux:72: vmlinux.unstripped] Error 1
make[1]: *** [/data/users/pjy/linux_worktrees/meta_klp_build/Makefile:1341: vmlinux] Error 2
make: *** [Makefile:248: __sub-make] Error 2

Applying the patch below fixes it:

-- >8 --

From 93c99313870d7375ab07e494c2d0d971758578eb Mon Sep 17 00:00:00 2001
From: Puranjay Mohan <[email protected]>
Date: Fri, 7 Aug 2026 11:16:29 -0700
Subject: [PATCH] objtool/klp: Fix vmlinux .klp.symid link error for
.exitcall.exit symbols

Building a kernel via klp-build fails to link:

__exitcall_aes_mod_exit' referenced in section .klp.symid' of vmlinux.o: defined in discarded section .exitcall.exit' of vmlinux.o __exitcall_dax_exit' referenced in section .klp.symid' of vmlinux.o: defined in discarded section .exitcall.exit' of vmlinux.o __exitcall_hid_exit' referenced in section .klp.symid' of vmlinux.o: defined in discarded section .exitcall.exit' of vmlinux.o __exitcall_usb_serial_module_exit' referenced in section .klp.symid' of vmlinux.o: defined in discarded section .exitcall.exit' of vmlinux.o

module_exit() on a built-in emits a static __exitcall_$fn pointer into .exitcall.exit, which vmlinux.lds.h discards unconditionally via EXIT_CALL. When two built-in translation units define a module_exit() function of the same name, the resulting local symbols collide, symid_needed() sees a duplicate and emits a .klp.symid entry for each, referencing symbols the linker then throws away.

Same-named module_exit() functions are not rare:

  dax_exit                drivers/dax/device.c, drivers/dax/fsdev.c
  hid_exit                drivers/hid/hid-core.c, drivers/hid/usbhid/hid-core.c
  aes_mod_exit            arch/arm64/crypto/aes-ce-ccm-glue.c, lib/crypto/aes.c
  usb_serial_module_exit  module_usb_serial_driver() expands to this fixed

name in each of its ~49 users

The last one makes the collision structural rather than accidental: any kernel with two built-in USB serial drivers has it. This is not arch specific either; it only requires the objects to be built in rather than modular, which is why a monolithic config trips it while a typical distro config does not.

Add .exitcall.exit to the discarded section list so its symbols don't get symids.

This is the same failure mode as "objtool/klp: Fix vmlinux .klp.symid link error for .no_trim_symbol symbols", for another unconditionally discarded allocated section.

Fixes 029223d30162 ("objtool/klp: Add .klp.symid for sympos disambiguation")
---
 tools/objtool/klp-symid.c | 1 +
 1 file changed, 1 insertion(+)
tools/objtool/klp-symid.c +1 -0
index 1934c2a1afc4d..1bdb8e4516e8f 100644
@@ -30,6 +30,7 @@
 
 static const char * const discarded_secs[] = {
        ".discard",
+       ".exitcall.exit",
        ".modinfo",
        ".no_trim_symbol",
        "__tracepoint_check",

--
2.53.0-Meta

-- 8< --

Thanks,
Puranjay

#9 lore raw

Re: [PATCH 03/14] objtool/klp: Fix false module dependencies caused by dead relocs

In reply to Josh Poimboeuf

+Dylan

Quoted 25 lines · Josh Poimboeuf

When creating a klp reloc, klp-diff keeps the original relocation but converts the referenced symbol to an UNDEF/WEAK placeholder tombstone symbol, which gets fully disabled later by klp post-link. The tombstone symbol is only needed to avoid confusing objtool when it does the final run on the patch module.

However, for references to exported symbols, modpost sees the reference to the tombstone symbol as a real reference to an exported symbol, resulting in a false module dependency getting created.

Further, for a reference to a tombstone symbol which is exported into a module namespace, e.g. via EXPORT_SYMBOL_FOR_KVM_INTERNAL(), modpost can't satisfy the dependency, resulting in a warning like the following:

module ... uses symbol kvm_flush_remote_tlbs from namespace module:kvm-amd,kvm-intel, but does not import it.

Rename the placeholder tombstone symbols to ".klp.tombstone.<name>" so modpost no longer recognizes them.

Fixes dd590d4d57eb ("objtool/klp: Introduce klp diff subcommand for diffing object files")
Quoted 5 lines
---
 tools/objtool/elf.c                 | 13 +++++++++++++
 tools/objtool/include/objtool/klp.h |  2 ++
 tools/objtool/klp-diff.c            | 16 ++++++++++++----
 3 files changed, 27 insertions(+), 4 deletions(-)

Naive question(s) incoming...

How does livepatching deal with the kernel's restrictions around module-specific namespaces/exports? AIUI, klp builds a livepatch module, and then loading the resulting livepatch.ko (or whatever its called) performs the actual patching of the kernel. If a patched function in livepatch.ko references an module-specific exported symbol, how does it actually resolve that symbol?

AFAICT, livepatch.ko would need to explicitly import the module namespace, but then it would run afoul of setup_modinfo()'s checks that a module isn't explicitly importing a module namespace.

E.g. if (not-so-hypothetically) one were to try to livepatch nested_vmx_enter_non_root_mode(), how would livepatch.ko get at things like kvm_service_local_tlb_flush_requests() and kvm_spurious_fault() without also creating copies of those functions? Wouldn't the kernel need something like the below to exempt livepatch modules from the restriction?

--
From: Sean Christopherson <[email protected]>
Date: Mon, 10 Aug 2026 14:27:50 -0700
Subject: [PATCH] module: Allow livepatch modules to import module-specific
namespaces

Allow livepatch modules to explicitly import module-specific namespaces, i.e. to use symbols that were exported for select module(s), as disallowing use of module-specific exports cripples the ability to livepatch the target modules.

KVM x86 heavily uses module-specific exports to restrict KVM-internal exports to KVM's own sub-modules, e.g. kvm-{amd,intel}.ko on x86, and to restrict a variety of "dangerous" kernel exports that exists purely to support KVM. See commits 20c489205836 ("KVM: Export KVM-internal symbols for sub-modules only") and 6276c67f2bc4 ("x86: Restrict KVM-induced symbol exports to KVM modules where obvious/possible").

Preventing livepatch modules from using those exports makes it infeasible to livepatch huge swaths of KVM, even if the to-be-livepatched function itself is generally compatible with livepatching, to the point where KVM is effectively un-livepatchable as the most interesting/critical flows in KVM vendor code rely on functionality provided by the kernel and/or kvm.ko.

Exempting livepatch modules isn't exactly ideal, as it allows circumventing the "no explicit module-specific imports" rule by using MODULE_INFO() to tag an arbitrary module as a livepatch module. However, that's only viable on kernels built with CONFIG_LIVEPATCH=y, and loading such a module also taints the kernel.

Fixes 520b1a147d91 ("module: Add module specific symbol namespace support")
Cc Peter Zijlstra <[email protected]>
Cc Josh Poimboeuf <[email protected]>
Cc Jiri Kosina <[email protected]>
Cc Miroslav Benes <[email protected]>
Cc Petr Mladek <[email protected]>
Cc Joe Lawrence <[email protected]>
---
 kernel/module/main.c | 5 +++--
 1 file changed, 3 insertions(+), 2 deletions(-)
kernel/module/main.c +3 -2
index 46dd8d25a605..67181c768af0 100644
@@ -1823,9 +1823,10 @@ static int setup_modinfo(struct module *mod, struct load_info *info)
 	for_each_modinfo_entry(imported_namespace, info, "import_ns") {
 		/*
 		 * 'module:' prefixed namespaces are implicit, disallow
-		 * explicit imports.
+		 * explicit imports, except for livepatching.
 		 */
-		if (strstarts(imported_namespace, "module:")) {
+		if (!is_livepatch_module(mod) &&
+		    strstarts(imported_namespace, "module:")) {
 			pr_err("%s: module tries to import module namespace: %s\n",
 			       mod->name, imported_namespace);
 			return -EPERM;

base-commit: d58772d8520c7ef247c4b95c9bd76d3a25da9ff5

author maintainer
#19 lore raw

Re: [PATCH 05/14] objtool/klp: Add .klp.symid for sympos disambiguation

In reply to Puranjay Mohan
Quoted 41 lines · Puranjay Mohan

Applying the patch below fixes it:

-- >8 --

From 93c99313870d7375ab07e494c2d0d971758578eb Mon Sep 17 00:00:00 2001
From: Puranjay Mohan <[email protected]>
Date: Fri, 7 Aug 2026 11:16:29 -0700
Subject: [PATCH] objtool/klp: Fix vmlinux .klp.symid link error for
.exitcall.exit symbols

Building a kernel via klp-build fails to link:

__exitcall_aes_mod_exit' referenced in section .klp.symid' of vmlinux.o: defined in discarded section .exitcall.exit' of vmlinux.o __exitcall_dax_exit' referenced in section .klp.symid' of vmlinux.o: defined in discarded section .exitcall.exit' of vmlinux.o __exitcall_hid_exit' referenced in section .klp.symid' of vmlinux.o: defined in discarded section .exitcall.exit' of vmlinux.o __exitcall_usb_serial_module_exit' referenced in section .klp.symid' of vmlinux.o: defined in discarded section .exitcall.exit' of vmlinux.o

module_exit() on a built-in emits a static __exitcall_$fn pointer into .exitcall.exit, which vmlinux.lds.h discards unconditionally via EXIT_CALL. When two built-in translation units define a module_exit() function of the same name, the resulting local symbols collide, symid_needed() sees a duplicate and emits a .klp.symid entry for each, referencing symbols the linker then throws away.

Same-named module_exit() functions are not rare:

  dax_exit                drivers/dax/device.c, drivers/dax/fsdev.c
  hid_exit                drivers/hid/hid-core.c, drivers/hid/usbhid/hid-core.c
  aes_mod_exit            arch/arm64/crypto/aes-ce-ccm-glue.c, lib/crypto/aes.c
  usb_serial_module_exit  module_usb_serial_driver() expands to this fixed

name in each of its ~49 users

The last one makes the collision structural rather than accidental: any kernel with two built-in USB serial drivers has it. This is not arch specific either; it only requires the objects to be built in rather than modular, which is why a monolithic config trips it while a typical distro config does not.

Add .exitcall.exit to the discarded section list so its symbols don't get symids.

Quoted 6 lines

This is the same failure mode as "objtool/klp: Fix vmlinux .klp.symid link error for .no_trim_symbol symbols", for another unconditionally discarded allocated section.

Fixes 029223d30162 ("objtool/klp: Add .klp.symid for sympos disambiguation")

Indeed, I'll add it to the queue, thanks!

Signature · 1 line
Josh
author maintainer
#10 lore raw

Re: [PATCH 03/14] objtool/klp: Fix false module dependencies caused by dead relocs

In reply to Sean Christopherson
Quoted 46 lines · Sean Christopherson

+Dylan

Quoted 25 lines · Josh Poimboeuf

When creating a klp reloc, klp-diff keeps the original relocation but converts the referenced symbol to an UNDEF/WEAK placeholder tombstone symbol, which gets fully disabled later by klp post-link. The tombstone symbol is only needed to avoid confusing objtool when it does the final run on the patch module.

However, for references to exported symbols, modpost sees the reference to the tombstone symbol as a real reference to an exported symbol, resulting in a false module dependency getting created.

Further, for a reference to a tombstone symbol which is exported into a module namespace, e.g. via EXPORT_SYMBOL_FOR_KVM_INTERNAL(), modpost can't satisfy the dependency, resulting in a warning like the following:

module ... uses symbol kvm_flush_remote_tlbs from namespace module:kvm-amd,kvm-intel, but does not import it.

Rename the placeholder tombstone symbols to ".klp.tombstone.<name>" so modpost no longer recognizes them.

Fixes dd590d4d57eb ("objtool/klp: Introduce klp diff subcommand for diffing object files")
Quoted 5 lines
---
 tools/objtool/elf.c                 | 13 +++++++++++++
 tools/objtool/include/objtool/klp.h |  2 ++
 tools/objtool/klp-diff.c            | 16 ++++++++++++----
 3 files changed, 27 insertions(+), 4 deletions(-)

Naive question(s) incoming...

How does livepatching deal with the kernel's restrictions around module-specific namespaces/exports? AIUI, klp builds a livepatch module, and then loading the resulting livepatch.ko (or whatever its called) performs the actual patching of the kernel. If a patched function in livepatch.ko references an module-specific exported symbol, how does it actually resolve that symbol?

AFAICT, livepatch.ko would need to explicitly import the module namespace, but then it would run afoul of setup_modinfo()'s checks that a module isn't explicitly importing a module namespace.

Quoted 5 lines

E.g. if (not-so-hypothetically) one were to try to livepatch nested_vmx_enter_non_root_mode(), how would livepatch.ko get at things like kvm_service_local_tlb_flush_requests() and kvm_spurious_fault() without also creating copies of those functions? Wouldn't the kernel need something like the below to exempt livepatch modules from the restriction?

Indeed, though we approached it from the tooling side, see this (not yet merged) patched:

https://lore.kernel.org/fe5a00818e06ec613344d41d5944de054fcd8832.1786138493.git.jpoimboe@kernel.org

Signature · 1 line
Josh
#11 lore raw

Re: [PATCH 03/14] objtool/klp: Fix false module dependencies caused by dead relocs

Quoted 53 lines · Josh Poimboeuf
Quoted 46 lines · Sean Christopherson

+Dylan

Quoted 25 lines · Josh Poimboeuf

When creating a klp reloc, klp-diff keeps the original relocation but converts the referenced symbol to an UNDEF/WEAK placeholder tombstone symbol, which gets fully disabled later by klp post-link. The tombstone symbol is only needed to avoid confusing objtool when it does the final run on the patch module.

However, for references to exported symbols, modpost sees the reference to the tombstone symbol as a real reference to an exported symbol, resulting in a false module dependency getting created.

Further, for a reference to a tombstone symbol which is exported into a module namespace, e.g. via EXPORT_SYMBOL_FOR_KVM_INTERNAL(), modpost can't satisfy the dependency, resulting in a warning like the following:

module ... uses symbol kvm_flush_remote_tlbs from namespace module:kvm-amd,kvm-intel, but does not import it.

Rename the placeholder tombstone symbols to ".klp.tombstone.<name>" so modpost no longer recognizes them.

Fixes dd590d4d57eb ("objtool/klp: Introduce klp diff subcommand for diffing object files")
Quoted 5 lines
---
 tools/objtool/elf.c                 | 13 +++++++++++++
 tools/objtool/include/objtool/klp.h |  2 ++
 tools/objtool/klp-diff.c            | 16 ++++++++++++----
 3 files changed, 27 insertions(+), 4 deletions(-)

Naive question(s) incoming...

How does livepatching deal with the kernel's restrictions around module-specific namespaces/exports? AIUI, klp builds a livepatch module, and then loading the resulting livepatch.ko (or whatever its called) performs the actual patching of the kernel. If a patched function in livepatch.ko references an module-specific exported symbol, how does it actually resolve that symbol?

AFAICT, livepatch.ko would need to explicitly import the module namespace, but then it would run afoul of setup_modinfo()'s checks that a module isn't explicitly importing a module namespace.

Quoted 5 lines

E.g. if (not-so-hypothetically) one were to try to livepatch nested_vmx_enter_non_root_mode(), how would livepatch.ko get at things like kvm_service_local_tlb_flush_requests() and kvm_spurious_fault() without also creating copies of those functions? Wouldn't the kernel need something like the below to exempt livepatch modules from the restriction?

Quoted 4 lines

Indeed, though we approached it from the tooling side, see this (not yet merged) patched:

https://lore.kernel.org/fe5a00818e06ec613344d41d5944de054fcd8832.1786138493.git.jpoimboe@kernel.org

Thanks much! After educating myself (a very little bit) on KLP relocs, I think I even understood all of that!

merge bot Applied
#20 lore raw

[tip: objtool/core] objtool/klp: Fix vmlinux .klp.symid link error for .exitcall.exit symbols

In reply to Puranjay Mohan
The following commit has been merged into the objtool/core branch of tip:

The following commit has been merged into the objtool/core branch of tip:

Commit-ID:     6656cf1e975aa152c082012b820efffaebd49979
Gitweb:        https://git.kernel.org/tip/6656cf1e975aa152c082012b820efffaebd49979
Author:        Puranjay Mohan <[email protected]>
AuthorDate:    Fri, 07 Aug 2026 11:16:29 -07:00
Committer:     Josh Poimboeuf <[email protected]>
CommitterDate: Wed, 12 Aug 2026 13:33:32 -07:00

objtool/klp: Fix vmlinux .klp.symid link error for .exitcall.exit symbols

Building a kernel via klp-build fails to link:

__exitcall_aes_mod_exit' referenced in section .klp.symid' of vmlinux.o: defined in discarded section .exitcall.exit' of vmlinux.o __exitcall_dax_exit' referenced in section .klp.symid' of vmlinux.o: defined in discarded section .exitcall.exit' of vmlinux.o __exitcall_hid_exit' referenced in section .klp.symid' of vmlinux.o: defined in discarded section .exitcall.exit' of vmlinux.o __exitcall_usb_serial_module_exit' referenced in section .klp.symid' of vmlinux.o: defined in discarded section .exitcall.exit' of vmlinux.o

module_exit() on a built-in emits a static __exitcall_$fn pointer into .exitcall.exit, which vmlinux.lds.h discards unconditionally via EXIT_CALL. When two built-in translation units define a module_exit() function of the same name, the resulting local symbols collide, symid_needed() sees a duplicate and emits a .klp.symid entry for each, referencing symbols the linker then throws away.

Same-named module_exit() functions are not rare:

  dax_exit                drivers/dax/device.c, drivers/dax/fsdev.c
  hid_exit                drivers/hid/hid-core.c, drivers/hid/usbhid/hid-core.c
  aes_mod_exit            arch/arm64/crypto/aes-ce-ccm-glue.c, lib/crypto/aes.c
  usb_serial_module_exit  module_usb_serial_driver() expands to this fixed

name in each of its ~49 users

The last one makes the collision structural rather than accidental: any kernel with two built-in USB serial drivers has it. This is not arch specific either; it only requires the objects to be built in rather than modular, which is why a monolithic config trips it while a typical distro config does not.

Add .exitcall.exit to the discarded section list so its symbols don't get symids.

This is the same failure mode as "objtool/klp: Fix vmlinux .klp.symid link error for .no_trim_symbol symbols", for another unconditionally discarded allocated section.

Fixes 029223d30162 ("objtool/klp: Add .klp.symid for sympos disambiguation")
---
 tools/objtool/klp-symid.c | 1 +
 1 file changed, 1 insertion(+)
tools/objtool/klp-symid.c +1 -0
index 21d8708..b19f76d 100644
@@ -30,6 +30,7 @@
 
 static const char * const discarded_secs[] = {
 	".discard",
+	".exitcall.exit",
 	".modinfo",
 	".no_trim_symbol",
 	"__tracepoint_check",
#12 lore raw

Re: [PATCH 03/14] objtool/klp: Fix false module dependencies caused by dead relocs

In reply to Josh Poimboeuf

Hi Josh,

Quoted 8 lines · Josh Poimboeuf
Quoted 5 lines · Sean Christopherson

E.g. if (not-so-hypothetically) one were to try to livepatch nested_vmx_enter_non_root_mode(), how would livepatch.ko get at things like kvm_service_local_tlb_flush_requests() and kvm_spurious_fault() without also creating copies of those functions? Wouldn't the kernel need something like the below to exempt livepatch modules from the restriction?

Quoted 4 lines

Indeed, though we approached it from the tooling side, see this (not yet merged) patched:

https://lore.kernel.org/fe5a00818e06ec613344d41d5944de054fcd8832.1786138493.git.jpoimboe@kernel.org

In the case where KVM is built as a module, a livepatch to nested_vmx_enter_non_root_mode() doesn't seem to work because livepatch doesn't allow KLP relocs for vmlinux symbols when they're in a patch function originating in a module. I was able to recreate this failure with a simple module/livepatch combo:

https://github.com/dylanbhatch/linux/tree/mod-ns-lp

Is there a way to work around this issue in the .patch source itself, or some other way to allow these relocs?

I'll also send a reply to your V3 patch with some more details on my findings.

Thanks,
Dylan