Skip to contentSkip to conversation

Unit test framework for klp-build toolchain

PATCH Applied Song Liu 4 participants 180 messages Sep 16 – Sep 21 Page 1 of 2

Subsystems (2)
lore
Share & tools
lore

Song Liu

author maintainer
#0 lore raw

v5 cover Unit test framework for klp-build toolchain

This is the unit test part of a test framework for the klp-build toolchain. The other part of the test framework will be some integration tests, similar to an earlier propose [1].

This is joint work by Puranjay Mohan, Joe Lawrence, and myself (Song Liu). Note that, while only two patches here are under Joe's authorship, his contribution to this set is much bigger than the number represents. A lot of these tests are based on Joe's earlier work in this area [2].

As the Assisted-by tags show, a lot of the work here is done with assists of AI. We actually designed the framework to so that we expect AI to write these tests in the future. AI also contributed in the design of the test framework. However, we (human) carefully reviewed the test framework. Also, this cover letter is 100% written by a human being (Song Liu).

Here are some key design choices we made for this unit tests framework:

1. We do not need different unit test here for different kernel CONFIG_* options. Instead, the tests cover different CONFIG_* options by passing different arguments to the compiler and objtool.

2. The test is NOT designed to be backward compatible. Similar to objtool itself, the unit tests are delivered with the kernel tree. The user of these tests should test the objtool with the unit tests in the same branch. Once this test framework lands, future changes and fixes to the objtool klp command should land with unit tests that cover the changes.

3. It is possible to run these tests on a different architecture with proper cross compilers. However, for automated CI, we are planning to focus on native tests. Please refer to "Future work" section below for more information about the CI.

4. AI will help write tests. We found AI is very cable to write good tests. tools/objtool/Documentation/klp-write-tests.txt is added for AI to read, so that AI can write tests for this test framework.

Future work
1. The integration test simiar to [1]. Unlike the unit tests, the integration tests will need separate runs to cover different kernel CONFIG_* combinations.

2. CI. The plan is to build a lore => patchwork => GitHub CI framework. This is the model used by subsystems such as netdev, bpf, and risc-v. We also have some ideas on "who will pay for the CI" issue, but I would rather not promise anything yet.

3. More tests.

Thanks,
Song

[1] https://lore.kernel.org/live-patching/[email protected]/
[2] https://github.com/joe-lawrence/klp-build-unit-tests

Changes v4 => v5:
1. Yet more fixes based on Sashiko reviews.

v4: https://lore.kernel.org/live-patching/[email protected]/

Changes v3 => v4:
1. Fix yet more issues reported by Sashiko.

v3: https://lore.kernel.org/live-patching/[email protected]/

Changes v2 => v3:
1. Fix more issues reported by Sashiko.

v2: https://lore.kernel.org/live-patching/[email protected]/

Changes v1 => v2:
1. Fix issues reported by Sashiko.

v1: https://lore.kernel.org/live-patching/[email protected]/

Joe Lawrence (2):
objtool: Keep failing test workdirs by default
objtool: Forward toolchain variables to the klp test runner

Puranjay Mohan (16):
objtool: Add test harness for the klp subcommands objtool/klp: Add test for rejecting changed data objtool/klp: Add test for newly introduced data objtool/klp: Add test for newly introduced functions objtool/klp: Add test for static local correlation objtool/klp: Add test for cold function halves objtool/klp: Add test for special section extraction objtool/klp: Add test for selective special section extraction objtool/klp: Add test for jump table key relocations objtool/klp: Add test for rejecting module-owned static branch keys objtool/klp: Add test for rejecting module-owned static call keys objtool/klp: Add test for symids in discarded sections objtool/klp: Add test for rejecting references to init code/data objtool/klp: Add test for correlation across ThinLTO name mangling objtool/klp: Add test for objects without .modinfo objtool/klp: Add test for unchecksummed input

Song Liu (40):
objtool/klp: Check the klp test environment once, before any test objtool/klp: Group the klp tests by architecture objtool/klp: Classify klp test outcomes
objtool/klp: Build klp test fixtures through the harness objtool/klp: Grow the klp test harness vocabulary objtool/klp: Give each run one working directory, one per test inside
it
objtool/klp: Run the klp tests under set -u
objtool/klp: Document the klp test harness
objtool/klp: Add klp diff and post-link regression tests objtool/klp: Add test for klp reloc section naming in module objects objtool/klp: Add test for vmlinux relocs in a patched module objtool/klp: Add test for Module.symvers path normalization objtool/klp: Add test for the contents of the klp_funcs list objtool/klp: Add test for EXPORT_SYMBOL_FOR_MODULES references objtool/klp: Add test for new references to exported symbols objtool/klp: Add test for empty x86 alternative replacements objtool/klp: Add test for recorded checksum values objtool/klp: Add test for position-independent checksums objtool/klp: Add test for sympos in module objects objtool/klp: Add test for sympos resolved against a linked vmlinux objtool/klp: Add test for static locals which must not be correlated objtool/klp: Add test for __bug_table, __ex_table and __mcount_loc
extraction
objtool/klp: Add test for kCFI prefix symbols and traps objtool/klp: Add test for symbols whose linkage the patch changes objtool/klp: Test rejection of a file-local static branch key objtool/klp: Test a hand-built livepatch module's static call keys objtool/klp: Test text annotations on alternative replacements objtool/klp: Add test for data object checksums objtool/klp: Add test for symbols with no checksum entry of their own objtool/klp: Add test for a static branch introduced by the patch objtool/klp: Add test for tracepoint and pr_debug static branch keys objtool/klp: Add test for a static call introduced by the patch objtool/klp: Add test for instruction operand checksums objtool/klp: Add test for alternative replacement code in checksums objtool/klp: Add test for the alignment of cloned data sections objtool/klp: Add test for a patch which strips a data annotation objtool/klp: Add test for absolute and __ADDRESSABLE symbols objtool/klp: Add test for UBSAN metadata in an unchanged function objtool/klp: Add test for Clang switch jump tables objtool/klp: Add test for ThinLTO symbols sharing a demangled name

 .../objtool/Documentation/klp-test-design.txt | 286 ++++++
 .../objtool/Documentation/klp-write-tests.txt | 266 +++++
 tools/objtool/Makefile                        |  15 +-
 .../generic/fixtures/abs_and_addressable.c    |  44 +
 tools/objtool/tests/generic/fixtures/basic.c  |  20 +
 .../tests/generic/fixtures/changed_data.c     |  16 +
 .../tests/generic/fixtures/checksum_data.c    | 116 +++
 .../tests/generic/fixtures/checksum_insn.c    |  78 ++
 .../generic/fixtures/checksum_position.c      |  42 +
 .../tests/generic/fixtures/checksum_skip.c    |  47 +
 .../tests/generic/fixtures/cold_function.c    |  21 +
 .../tests/generic/fixtures/cross_module.c     |  25 +
 .../tests/generic/fixtures/data_alignment.c   |  29 +
 .../tests/generic/fixtures/function_removal.c |  25 +
 .../tests/generic/fixtures/init_reference.c   |  17 +
 .../tests/generic/fixtures/jump_label.c       |  76 ++
 .../tests/generic/fixtures/klp_funcs.c        |  31 +
 .../tests/generic/fixtures/local_to_global.c  |  34 +
 .../objtool/tests/generic/fixtures/new_data.c |  23 +
 .../tests/generic/fixtures/new_export_ref.c   |  35 +
 .../tests/generic/fixtures/new_function.c     |  21 +
 .../tests/generic/fixtures/no_modinfo.c       |  11 +
 .../tests/generic/fixtures/special_section.c  |  24 +
 .../generic/fixtures/special_section_shared.c |  31 +
 .../tests/generic/fixtures/static_call.c      |  59 ++
 .../tests/generic/fixtures/static_local.c     |  17 +
 .../fixtures/static_local_uncorrelated.c      |  41 +
 .../tests/generic/fixtures/switch_rodata.c    |  31 +
 .../tests/generic/fixtures/symid_discarded.c  |  25 +
 .../tests/generic/fixtures/sympos_dup.c       |  32 +
 .../tests/generic/fixtures/sympos_vmlinux.c   |  40 +
 .../generic/fixtures/thinlto_ambiguity.c      |  57 ++
 .../tests/generic/fixtures/thinlto_local.c    |  39 +
 .../tests/generic/fixtures/ubsan_noise.c      |  49 +
 .../tests/generic/test-abs-and-addressable.sh |  50 +
 tools/objtool/tests/generic/test-basic.sh     |  17 +
 .../tests/generic/test-changed-data.sh        |  18 +
 .../tests/generic/test-checksum-data.sh       |  61 ++
 .../tests/generic/test-checksum-debug.sh      |  49 +
 .../tests/generic/test-checksum-insn.sh       |  49 +
 .../tests/generic/test-checksum-position.sh   |  50 +
 .../tests/generic/test-checksum-skip.sh       |  81 ++
 .../tests/generic/test-checksum-value.sh      |  37 +
 .../tests/generic/test-cold-function.sh       |  39 +
 .../tests/generic/test-data-alignment.sh      |  40 +
 .../generic/test-export-symbol-for-modules.sh |  39 +
 .../tests/generic/test-function-removal.sh    |  34 +
 .../tests/generic/test-init-reference.sh      |  29 +
 .../generic/test-jump-label-exempt-keys.sh    |  51 +
 .../tests/generic/test-jump-label-key.sh      |  44 +
 .../generic/test-jump-label-module-key.sh     |  22 +
 .../test-jump-label-module-static-key.sh      |  45 +
 .../tests/generic/test-jump-label-new-key.sh  |  51 +
 .../tests/generic/test-klp-funcs-content.sh   |  45 +
 .../generic/test-local-to-global-flip.sh      |  63 ++
 .../tests/generic/test-local-vs-export.sh     |  32 +
 .../tests/generic/test-missing-checksum.sh    |  18 +
 .../tests/generic/test-missing-modinfo.sh     |  16 +
 .../tests/generic/test-modname-normalize.sh   |  26 +
 .../tests/generic/test-module-object.sh       |  31 +
 .../generic/test-module-vmlinux-reloc.sh      |  40 +
 tools/objtool/tests/generic/test-new-data.sh  |  27 +
 .../tests/generic/test-new-export-ref.sh      |  46 +
 .../tests/generic/test-new-function.sh        |  16 +
 tools/objtool/tests/generic/test-post-link.sh |  42 +
 .../generic/test-special-section-shared.sh    |  26 +
 .../tests/generic/test-special-section.sh     |  20 +
 .../test-static-call-annotate-stripped.sh     |  42 +
 .../generic/test-static-call-module-key.sh    |  36 +
 .../tests/generic/test-static-call-new.sh     |  45 +
 .../generic/test-static-local-uncorrelated.sh |  41 +
 .../tests/generic/test-static-local.sh        |  24 +
 .../tests/generic/test-switch-rodata.sh       |  53 +
 .../tests/generic/test-symid-discarded.sh     |  44 +
 .../tests/generic/test-sympos-vmlinux.sh      |  57 ++
 tools/objtool/tests/generic/test-sympos.sh    |  51 +
 .../tests/generic/test-symvers-parse-error.sh |  23 +
 .../tests/generic/test-thinlto-ambiguity.sh   |  77 ++
 .../tests/generic/test-thinlto-local.sh       |  48 +
 .../objtool/tests/generic/test-ubsan-noise.sh |  48 +
 tools/objtool/tests/lib.sh                    | 911 ++++++++++++++++++
 tools/objtool/tests/run-tests.sh              | 239 +++++
 .../objtool/tests/x86/fixtures/alt_annotate.c |  57 ++
 .../objtool/tests/x86/fixtures/checksum_alt.c |  66 ++
 .../tests/x86/fixtures/empty_alternative.c    |  77 ++
 tools/objtool/tests/x86/fixtures/kcfi.c       |  39 +
 .../tests/x86/fixtures/special_sections.c     |  77 ++
 .../tests/x86/fixtures/static_call_no_key.c   |  32 +
 .../objtool/tests/x86/test-alt-annotation.sh  |  38 +
 tools/objtool/tests/x86/test-checksum-alt.sh  |  45 +
 .../tests/x86/test-empty-alternative.sh       |  31 +
 tools/objtool/tests/x86/test-kcfi.sh          |  39 +
 .../tests/x86/test-manual-klp-static-call.sh  |  40 +
 .../tests/x86/test-special-sections.sh        |  42 +
 94 files changed, 5298 insertions(+), 1 deletion(-)
 create mode 100644 tools/objtool/Documentation/klp-test-design.txt
 create mode 100644 tools/objtool/Documentation/klp-write-tests.txt
 create mode 100644 tools/objtool/tests/generic/fixtures/abs_and_addressable.c
 create mode 100644 tools/objtool/tests/generic/fixtures/basic.c
 create mode 100644 tools/objtool/tests/generic/fixtures/changed_data.c
 create mode 100644 tools/objtool/tests/generic/fixtures/checksum_data.c
 create mode 100644 tools/objtool/tests/generic/fixtures/checksum_insn.c
 create mode 100644 tools/objtool/tests/generic/fixtures/checksum_position.c
 create mode 100644 tools/objtool/tests/generic/fixtures/checksum_skip.c
 create mode 100644 tools/objtool/tests/generic/fixtures/cold_function.c
 create mode 100644 tools/objtool/tests/generic/fixtures/cross_module.c
 create mode 100644 tools/objtool/tests/generic/fixtures/data_alignment.c
 create mode 100644 tools/objtool/tests/generic/fixtures/function_removal.c
 create mode 100644 tools/objtool/tests/generic/fixtures/init_reference.c
 create mode 100644 tools/objtool/tests/generic/fixtures/jump_label.c
 create mode 100644 tools/objtool/tests/generic/fixtures/klp_funcs.c
 create mode 100644 tools/objtool/tests/generic/fixtures/local_to_global.c
 create mode 100644 tools/objtool/tests/generic/fixtures/new_data.c
 create mode 100644 tools/objtool/tests/generic/fixtures/new_export_ref.c
 create mode 100644 tools/objtool/tests/generic/fixtures/new_function.c
 create mode 100644 tools/objtool/tests/generic/fixtures/no_modinfo.c
 create mode 100644 tools/objtool/tests/generic/fixtures/special_section.c
 create mode 100644 tools/objtool/tests/generic/fixtures/special_section_shared.c
 create mode 100644 tools/objtool/tests/generic/fixtures/static_call.c
 create mode 100644 tools/objtool/tests/generic/fixtures/static_local.c
 create mode 100644 tools/objtool/tests/generic/fixtures/static_local_uncorrelated.c
 create mode 100644 tools/objtool/tests/generic/fixtures/switch_rodata.c
 create mode 100644 tools/objtool/tests/generic/fixtures/symid_discarded.c
 create mode 100644 tools/objtool/tests/generic/fixtures/sympos_dup.c
 create mode 100644 tools/objtool/tests/generic/fixtures/sympos_vmlinux.c
 create mode 100644 tools/objtool/tests/generic/fixtures/thinlto_ambiguity.c
 create mode 100644 tools/objtool/tests/generic/fixtures/thinlto_local.c
 create mode 100644 tools/objtool/tests/generic/fixtures/ubsan_noise.c
 create mode 100755 tools/objtool/tests/generic/test-abs-and-addressable.sh
 create mode 100755 tools/objtool/tests/generic/test-basic.sh
 create mode 100755 tools/objtool/tests/generic/test-changed-data.sh
 create mode 100755 tools/objtool/tests/generic/test-checksum-data.sh
 create mode 100755 tools/objtool/tests/generic/test-checksum-debug.sh
 create mode 100755 tools/objtool/tests/generic/test-checksum-insn.sh
 create mode 100755 tools/objtool/tests/generic/test-checksum-position.sh
 create mode 100755 tools/objtool/tests/generic/test-checksum-skip.sh
 create mode 100755 tools/objtool/tests/generic/test-checksum-value.sh
 create mode 100755 tools/objtool/tests/generic/test-cold-function.sh
 create mode 100755 tools/objtool/tests/generic/test-data-alignment.sh
 create mode 100755 tools/objtool/tests/generic/test-export-symbol-for-modules.sh
 create mode 100755 tools/objtool/tests/generic/test-function-removal.sh
 create mode 100755 tools/objtool/tests/generic/test-init-reference.sh
 create mode 100755 tools/objtool/tests/generic/test-jump-label-exempt-keys.sh
 create mode 100755 tools/objtool/tests/generic/test-jump-label-key.sh
 create mode 100755 tools/objtool/tests/generic/test-jump-label-module-key.sh
 create mode 100755 tools/objtool/tests/generic/test-jump-label-module-static-key.sh
 create mode 100755 tools/objtool/tests/generic/test-jump-label-new-key.sh
 create mode 100755 tools/objtool/tests/generic/test-klp-funcs-content.sh
 create mode 100755 tools/objtool/tests/generic/test-local-to-global-flip.sh
 create mode 100755 tools/objtool/tests/generic/test-local-vs-export.sh
 create mode 100755 tools/objtool/tests/generic/test-missing-checksum.sh
 create mode 100755 tools/objtool/tests/generic/test-missing-modinfo.sh
 create mode 100755 tools/objtool/tests/generic/test-modname-normalize.sh
 create mode 100755 tools/objtool/tests/generic/test-module-object.sh
 create mode 100755 tools/objtool/tests/generic/test-module-vmlinux-reloc.sh
 create mode 100755 tools/objtool/tests/generic/test-new-data.sh
 create mode 100755 tools/objtool/tests/generic/test-new-export-ref.sh
 create mode 100755 tools/objtool/tests/generic/test-new-function.sh
 create mode 100755 tools/objtool/tests/generic/test-post-link.sh
 create mode 100755 tools/objtool/tests/generic/test-special-section-shared.sh
 create mode 100755 tools/objtool/tests/generic/test-special-section.sh
 create mode 100755 tools/objtool/tests/generic/test-static-call-annotate-stripped.sh
 create mode 100755 tools/objtool/tests/generic/test-static-call-module-key.sh
 create mode 100755 tools/objtool/tests/generic/test-static-call-new.sh
 create mode 100755 tools/objtool/tests/generic/test-static-local-uncorrelated.sh
 create mode 100755 tools/objtool/tests/generic/test-static-local.sh
 create mode 100755 tools/objtool/tests/generic/test-switch-rodata.sh
 create mode 100755 tools/objtool/tests/generic/test-symid-discarded.sh
 create mode 100755 tools/objtool/tests/generic/test-sympos-vmlinux.sh
 create mode 100755 tools/objtool/tests/generic/test-sympos.sh
 create mode 100755 tools/objtool/tests/generic/test-symvers-parse-error.sh
 create mode 100755 tools/objtool/tests/generic/test-thinlto-ambiguity.sh
 create mode 100755 tools/objtool/tests/generic/test-thinlto-local.sh
 create mode 100755 tools/objtool/tests/generic/test-ubsan-noise.sh
 create mode 100644 tools/objtool/tests/lib.sh
 create mode 100755 tools/objtool/tests/run-tests.sh
 create mode 100644 tools/objtool/tests/x86/fixtures/alt_annotate.c
 create mode 100644 tools/objtool/tests/x86/fixtures/checksum_alt.c
 create mode 100644 tools/objtool/tests/x86/fixtures/empty_alternative.c
 create mode 100644 tools/objtool/tests/x86/fixtures/kcfi.c
 create mode 100644 tools/objtool/tests/x86/fixtures/special_sections.c
 create mode 100644 tools/objtool/tests/x86/fixtures/static_call_no_key.c
 create mode 100755 tools/objtool/tests/x86/test-alt-annotation.sh
 create mode 100755 tools/objtool/tests/x86/test-checksum-alt.sh
 create mode 100755 tools/objtool/tests/x86/test-empty-alternative.sh
 create mode 100755 tools/objtool/tests/x86/test-kcfi.sh
 create mode 100755 tools/objtool/tests/x86/test-manual-klp-static-call.sh
 create mode 100755 tools/objtool/tests/x86/test-special-sections.sh

--
2.53.0-Meta

author maintainer
#1 lore raw

PATCH v5 1/58 objtool: Add test harness for the klp subcommands

From: Puranjay Mohan <[email protected]>

"objtool klp checksum" and "objtool klp diff" work on object files alone, with no kernel, vmlinux or configuration involved, so they can be tested directly. That is worth doing: most klp generation bugs so far have been in symbol correlation, special section extraction and relocation conversion, and several of them failed silently, producing a livepatch which built cleanly but was missing data.

A test compiles a fixture twice, as the original and (with -DPATCHED) the patched object, runs both through klp checksum, diffs them and asserts on the result. Fixtures are compiled at test time rather than committed as
binaries: codegen varies between compilers and architectures, and that variation is where a good number of these bugs come from.

Assertions check properties rather than compare against recorded output. Golden files would need re-recording for every compiler change and would report churn instead of regressions.

klp diff resolves symbols against Module.symvers, so the harness writes one. Whether a symbol is listed there decides between an ordinary relocation and a klp relocation, which makes it the main knob tests use.

Run with:

make -C tools/objtool tests

Tests skip when objtool was built without klp support or when a fixture does not build for the target architecture. A missing objtool binary fails instead of skipping, since that means a broken invocation rather than an environment which cannot run the test.

Assisted-by Claude:claude-opus-5
---
 tools/objtool/Makefile               |   5 +-
 tools/objtool/tests/fixtures/basic.c |  20 +++
 tools/objtool/tests/lib.sh           | 179 +++++++++++++++++++++++++++
 tools/objtool/tests/run-tests.sh     |  20 +++
 tools/objtool/tests/test-basic.sh    |  17 +++
 5 files changed, 240 insertions(+), 1 deletion(-)
 create mode 100644 tools/objtool/tests/fixtures/basic.c
 create mode 100644 tools/objtool/tests/lib.sh
 create mode 100755 tools/objtool/tests/run-tests.sh
 create mode 100755 tools/objtool/tests/test-basic.sh
tools/objtool/Makefile +4 -1
index a4484fd22a96..f4ec9f813a20 100644
@@ -151,6 +151,9 @@ clean: $(LIBSUBCMD)-clean
 mrproper: clean
 	$(call QUIET_CLEAN, objtool) $(RM) $(OBJTOOL)
 
+tests: $(OBJTOOL)
+	$(Q)OBJTOOL=$(abspath $(OBJTOOL)) $(srctree)/tools/objtool/tests/run-tests.sh
+
 FORCE:
 
-.PHONY: clean mrproper FORCE
+.PHONY: clean mrproper tests FORCE
tools/objtool/tests/fixtures/basic.c new file +20 -0
new file mode 100644
index 000000000000..811529e7bfb1
@@ -0,0 +1,20 @@
+// SPDX-License-Identifier: GPL-2.0
+/* One changed function and one unchanged function. */
+
+/* klp diff takes the object's module name from .modinfo */
+static const char __modinfo[]
+	__attribute__((section(".modinfo"), used, aligned(1))) = "\0name=vmlinux";
+
+int untouched(int x)
+{
+	return x * 3;
+}
+
+int changed(int x)
+{
+#ifdef PATCHED
+	return x + 2;
+#else
+	return x + 1;
+#endif
+}
tools/objtool/tests/lib.sh new file +179 -0

179 lines not on this page · raw message

tools/objtool/tests/run-tests.sh new file +20 -0
new file mode 100755
index 000000000000..ab1dea58811e
@@ -0,0 +1,20 @@
+#!/bin/bash
+# SPDX-License-Identifier: GPL-2.0
+#
+# Run the objtool klp tests.  Each test-*.sh prints one TAP result line.
+
+set -u
+
+cd "$(dirname "$0")" || exit 1
+
+tests=( test-*.sh )
+[ "${tests[0]}" = "test-*.sh" ] && { echo "1..0 # SKIP no tests found"; exit 0; }
+
+echo "1..${#tests[@]}"
+
+rc=0
+for t in "${tests[@]}"; do
+	./"$t" || rc=1
+done
+
+exit $rc
tools/objtool/tests/test-basic.sh new file +17 -0
new file mode 100755
index 000000000000..6b769962399a
@@ -0,0 +1,17 @@
+#!/bin/bash
+# SPDX-License-Identifier: GPL-2.0
+#
+# Only functions whose code changed get cloned into the patch.
+
+. "$(dirname "$0")/lib.sh"
+
+setup
+build_pair basic.c
+run_diff
+
+assert_patched     changed
+assert_not_patched untouched
+assert_section     ".init.klp_funcs"
+assert_section     ".init.klp_objects"
+
+pass "changed function cloned, unchanged function left alone"
Signature · 1 line
2.53.0-Meta
merge bot Applied
#2 lore raw

[tip: objtool/core] objtool: Add test harness for the klp subcommands

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:     8aab0eb12944c076bcbb263fbd865ab0fdb6408e
Gitweb:        https://git.kernel.org/tip/8aab0eb12944c076bcbb263fbd865ab0fdb6408e
Author:        Puranjay Mohan <[email protected]>
AuthorDate:    Wed, 16 Sep 2026 11:42:54 -07:00
Committer:     Josh Poimboeuf <[email protected]>
CommitterDate: Wed, 16 Sep 2026 17:13:26 -07:00

objtool: Add test harness for the klp subcommands

"objtool klp checksum" and "objtool klp diff" work on object files alone, with no kernel, vmlinux or configuration involved, so they can be tested directly. That is worth doing: most klp generation bugs so far have been in symbol correlation, special section extraction and relocation conversion, and several of them failed silently, producing a livepatch which built cleanly but was missing data.

A test compiles a fixture twice, as the original and (with -DPATCHED) the patched object, runs both through klp checksum, diffs them and asserts on the result. Fixtures are compiled at test time rather than committed as
binaries: codegen varies between compilers and architectures, and that variation is where a good number of these bugs come from.

Assertions check properties rather than compare against recorded output. Golden files would need re-recording for every compiler change and would report churn instead of regressions.

klp diff resolves symbols against Module.symvers, so the harness writes one. Whether a symbol is listed there decides between an ordinary relocation and a klp relocation, which makes it the main knob tests use.

Run with:

make -C tools/objtool tests

Tests skip when objtool was built without klp support or when a fixture does not build for the target architecture. A missing objtool binary fails instead of skipping, since that means a broken invocation rather than an environment which cannot run the test.

---
 tools/objtool/Makefile               |   5 +-
 tools/objtool/tests/fixtures/basic.c |  20 +++-
 tools/objtool/tests/lib.sh           | 179 ++++++++++++++++++++++++++-
 tools/objtool/tests/run-tests.sh     |  20 +++-
 tools/objtool/tests/test-basic.sh    |  17 ++-
 5 files changed, 240 insertions(+), 1 deletion(-)
 create mode 100644 tools/objtool/tests/fixtures/basic.c
 create mode 100644 tools/objtool/tests/lib.sh
 create mode 100755 tools/objtool/tests/run-tests.sh
 create mode 100755 tools/objtool/tests/test-basic.sh
tools/objtool/Makefile +4 -1
index a4484fd..f4ec9f8 100644
@@ -151,6 +151,9 @@ clean: $(LIBSUBCMD)-clean
 mrproper: clean
 	$(call QUIET_CLEAN, objtool) $(RM) $(OBJTOOL)
 
+tests: $(OBJTOOL)
+	$(Q)OBJTOOL=$(abspath $(OBJTOOL)) $(srctree)/tools/objtool/tests/run-tests.sh
+
 FORCE:
 
-.PHONY: clean mrproper FORCE
+.PHONY: clean mrproper tests FORCE
tools/objtool/tests/fixtures/basic.c new file +20 -0
new file mode 100644
index 0000000..811529e
@@ -0,0 +1,20 @@
+// SPDX-License-Identifier: GPL-2.0
+/* One changed function and one unchanged function. */
+
+/* klp diff takes the object's module name from .modinfo */
+static const char __modinfo[]
+	__attribute__((section(".modinfo"), used, aligned(1))) = "\0name=vmlinux";
+
+int untouched(int x)
+{
+	return x * 3;
+}
+
+int changed(int x)
+{
+#ifdef PATCHED
+	return x + 2;
+#else
+	return x + 1;
+#endif
+}
tools/objtool/tests/lib.sh new file +179 -0

179 lines not on this page · raw message

tools/objtool/tests/run-tests.sh new file +20 -0
new file mode 100755
index 0000000..ab1dea5
@@ -0,0 +1,20 @@
+#!/bin/bash
+# SPDX-License-Identifier: GPL-2.0
+#
+# Run the objtool klp tests.  Each test-*.sh prints one TAP result line.
+
+set -u
+
+cd "$(dirname "$0")" || exit 1
+
+tests=( test-*.sh )
+[ "${tests[0]}" = "test-*.sh" ] && { echo "1..0 # SKIP no tests found"; exit 0; }
+
+echo "1..${#tests[@]}"
+
+rc=0
+for t in "${tests[@]}"; do
+	./"$t" || rc=1
+done
+
+exit $rc
tools/objtool/tests/test-basic.sh new file +17 -0
new file mode 100755
index 0000000..6b76996
@@ -0,0 +1,17 @@
+#!/bin/bash
+# SPDX-License-Identifier: GPL-2.0
+#
+# Only functions whose code changed get cloned into the patch.
+
+. "$(dirname "$0")/lib.sh"
+
+setup
+build_pair basic.c
+run_diff
+
+assert_patched     changed
+assert_not_patched untouched
+assert_section     ".init.klp_funcs"
+assert_section     ".init.klp_objects"
+
+pass "changed function cloned, unchanged function left alone"
merge bot Applied
#3 lore raw

[tip: objtool/core] objtool: Add test harness for the klp subcommands

In reply to Song Liu
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:     cff27d90769da941f6897a9d9152670af7b71f95
Gitweb:        https://git.kernel.org/tip/cff27d90769da941f6897a9d9152670af7b71f95
Author:        Puranjay Mohan <[email protected]>
AuthorDate:    Wed, 16 Sep 2026 11:42:54 -07:00
Committer:     Ingo Molnar <[email protected]>
CommitterDate: Mon, 21 Sep 2026 10:50:49 +02:00

objtool: Add test harness for the klp subcommands

"objtool klp checksum" and "objtool klp diff" work on object files alone, with no kernel, vmlinux or configuration involved, so they can be tested directly. That is worth doing: most klp generation bugs so far have been in symbol correlation, special section extraction and relocation conversion, and several of them failed silently, producing a livepatch which built cleanly but was missing data.

A test compiles a fixture twice, as the original and (with -DPATCHED) the patched object, runs both through klp checksum, diffs them and asserts on the result. Fixtures are compiled at test time rather than committed as
binaries: codegen varies between compilers and architectures, and that variation is where a good number of these bugs come from.

Assertions check properties rather than compare against recorded output. Golden files would need re-recording for every compiler change and would report churn instead of regressions.

klp diff resolves symbols against Module.symvers, so the harness writes one. Whether a symbol is listed there decides between an ordinary relocation and a klp relocation, which makes it the main knob tests use.

Run with:

make -C tools/objtool tests

Tests skip when objtool was built without klp support or when a fixture does not build for the target architecture. A missing objtool binary fails instead of skipping, since that means a broken invocation rather than an environment which cannot run the test.

---
 tools/objtool/Makefile               |   5 +-
 tools/objtool/tests/fixtures/basic.c |  20 +++-
 tools/objtool/tests/lib.sh           | 179 ++++++++++++++++++++++++++-
 tools/objtool/tests/run-tests.sh     |  20 +++-
 tools/objtool/tests/test-basic.sh    |  17 ++-
 5 files changed, 240 insertions(+), 1 deletion(-)
 create mode 100644 tools/objtool/tests/fixtures/basic.c
 create mode 100644 tools/objtool/tests/lib.sh
 create mode 100755 tools/objtool/tests/run-tests.sh
 create mode 100755 tools/objtool/tests/test-basic.sh
tools/objtool/Makefile +4 -1
index 4cc2e75..0f34abb 100644
@@ -153,6 +153,9 @@ clean: $(LIBSUBCMD)-clean
 mrproper: clean
 	$(call QUIET_CLEAN, objtool) $(RM) $(OBJTOOL)
 
+tests: $(OBJTOOL)
+	$(Q)OBJTOOL=$(abspath $(OBJTOOL)) $(srctree)/tools/objtool/tests/run-tests.sh
+
 FORCE:
 
-.PHONY: clean mrproper FORCE
+.PHONY: clean mrproper tests FORCE
tools/objtool/tests/fixtures/basic.c new file +20 -0
new file mode 100644
index 0000000..811529e
@@ -0,0 +1,20 @@
+// SPDX-License-Identifier: GPL-2.0
+/* One changed function and one unchanged function. */
+
+/* klp diff takes the object's module name from .modinfo */
+static const char __modinfo[]
+	__attribute__((section(".modinfo"), used, aligned(1))) = "\0name=vmlinux";
+
+int untouched(int x)
+{
+	return x * 3;
+}
+
+int changed(int x)
+{
+#ifdef PATCHED
+	return x + 2;
+#else
+	return x + 1;
+#endif
+}
tools/objtool/tests/lib.sh new file +179 -0

179 lines not on this page · raw message

tools/objtool/tests/run-tests.sh new file +20 -0
new file mode 100755
index 0000000..ab1dea5
@@ -0,0 +1,20 @@
+#!/bin/bash
+# SPDX-License-Identifier: GPL-2.0
+#
+# Run the objtool klp tests.  Each test-*.sh prints one TAP result line.
+
+set -u
+
+cd "$(dirname "$0")" || exit 1
+
+tests=( test-*.sh )
+[ "${tests[0]}" = "test-*.sh" ] && { echo "1..0 # SKIP no tests found"; exit 0; }
+
+echo "1..${#tests[@]}"
+
+rc=0
+for t in "${tests[@]}"; do
+	./"$t" || rc=1
+done
+
+exit $rc
tools/objtool/tests/test-basic.sh new file +17 -0
new file mode 100755
index 0000000..6b76996
@@ -0,0 +1,17 @@
+#!/bin/bash
+# SPDX-License-Identifier: GPL-2.0
+#
+# Only functions whose code changed get cloned into the patch.
+
+. "$(dirname "$0")/lib.sh"
+
+setup
+build_pair basic.c
+run_diff
+
+assert_patched     changed
+assert_not_patched untouched
+assert_section     ".init.klp_funcs"
+assert_section     ".init.klp_objects"
+
+pass "changed function cloned, unchanged function left alone"
author maintainer
#4 lore raw

PATCH v5 2/58 objtool/klp: Check the klp test environment once, before any test

In reply to Song Liu

Every test checked for itself that objtool exists, was built with klp support, and that $CC runs. Three problems with that: it is the same work done 40 times, a missing objtool reads as a per-test skip rather than as a suite which cannot run, and a run in which everything skipped still exits 0.

Do it once, before any test, in klp_preflight() in lib.sh, and export the answers where the tests can read them. If the suite cannot run the whole run fails and says why; a test which gets as far as running can assume its environment.

Nothing is written down, so nothing can go stale. Sourcing lib.sh runs the checks, which means a test run by hand establishes its own answers rather than inheriting those of some earlier run with a different CC, and a test is never handed an empty value for where objtool is or which architecture it is on: either the exports are set or the run has already failed.

preflight answers only whether the suite can run at all -- not what the compiler is capable of. A test needing a particular compiler feature probes for it and skips; that costs one compile and keeps the reason next to the test that has to justify it.

Assisted-by Claude:claude-opus-5
---
 tools/objtool/Makefile           |   3 +-
 tools/objtool/tests/lib.sh       | 124 +++++++++++++++++++++++++------
 tools/objtool/tests/run-tests.sh |   7 ++
 3 files changed, 112 insertions(+), 22 deletions(-)
tools/objtool/Makefile +2 -1
index f4ec9f813a20..2c200d05c276 100644
@@ -152,7 +152,8 @@ mrproper: clean
 	$(call QUIET_CLEAN, objtool) $(RM) $(OBJTOOL)
 
 tests: $(OBJTOOL)
-	$(Q)OBJTOOL=$(abspath $(OBJTOOL)) $(srctree)/tools/objtool/tests/run-tests.sh
+	$(Q)OBJTOOL=$(abspath $(OBJTOOL)) ARCH=$(ARCH) CROSS_COMPILE=$(CROSS_COMPILE) \
+		$(srctree)/tools/objtool/tests/run-tests.sh
 
 FORCE:
 
tools/objtool/tests/lib.sh +103 -21

143 lines not on this page · raw message

tools/objtool/tests/run-tests.sh +7 -0
index ab1dea58811e..f6a3e1b7677e 100755
@@ -2,6 +2,9 @@
 # SPDX-License-Identifier: GPL-2.0
 #
 # Run the objtool klp tests.  Each test-*.sh prints one TAP result line.
+#
+# The harness checks the environment once up front and fails the run if the
+# suite cannot execute, rather than letting every test skip and exit 0.
 
 set -u
 
@@ -10,6 +13,10 @@ cd "$(dirname "$0")" || exit 1
 tests=( test-*.sh )
 [ "${tests[0]}" = "test-*.sh" ] && { echo "1..0 # SKIP no tests found"; exit 0; }
 
+# Sourcing the harness runs its preflight, and exports what it found so the
+# tests inherit it rather than working it out again.
+. ./lib.sh
+
 echo "1..${#tests[@]}"
 
 rc=0
Signature · 1 line
2.53.0-Meta
merge bot Applied
#5 lore raw

[tip: objtool/core] objtool/klp: Check the klp test environment once, before any test

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:     c03a4cf88206163f9a78abdd798ffdba9671ae5d
Gitweb:        https://git.kernel.org/tip/c03a4cf88206163f9a78abdd798ffdba9671ae5d
Author:        Song Liu <[email protected]>
AuthorDate:    Wed, 16 Sep 2026 11:42:55 -07:00
Committer:     Josh Poimboeuf <[email protected]>
CommitterDate: Wed, 16 Sep 2026 17:13:26 -07:00

objtool/klp: Check the klp test environment once, before any test

Every test checked for itself that objtool exists, was built with klp support, and that $CC runs. Three problems with that: it is the same work done 40 times, a missing objtool reads as a per-test skip rather than as a suite which cannot run, and a run in which everything skipped still exits 0.

Do it once, before any test, in klp_preflight() in lib.sh, and export the answers where the tests can read them. If the suite cannot run the whole run fails and says why; a test which gets as far as running can assume its environment.

Nothing is written down, so nothing can go stale. Sourcing lib.sh runs the checks, which means a test run by hand establishes its own answers rather than inheriting those of some earlier run with a different CC, and a test is never handed an empty value for where objtool is or which architecture it is on: either the exports are set or the run has already failed.

preflight answers only whether the suite can run at all -- not what the compiler is capable of. A test needing a particular compiler feature probes for it and skips; that costs one compile and keeps the reason next to the test that has to justify it.

---
 tools/objtool/Makefile           |   3 +-
 tools/objtool/tests/lib.sh       | 124 ++++++++++++++++++++++++------
 tools/objtool/tests/run-tests.sh |   7 ++-
 3 files changed, 112 insertions(+), 22 deletions(-)
tools/objtool/Makefile +2 -1
index f4ec9f8..2c200d0 100644
@@ -152,7 +152,8 @@ mrproper: clean
 	$(call QUIET_CLEAN, objtool) $(RM) $(OBJTOOL)
 
 tests: $(OBJTOOL)
-	$(Q)OBJTOOL=$(abspath $(OBJTOOL)) $(srctree)/tools/objtool/tests/run-tests.sh
+	$(Q)OBJTOOL=$(abspath $(OBJTOOL)) ARCH=$(ARCH) CROSS_COMPILE=$(CROSS_COMPILE) \
+		$(srctree)/tools/objtool/tests/run-tests.sh
 
 FORCE:
 
tools/objtool/tests/lib.sh +103 -21

143 lines not on this page · raw message

tools/objtool/tests/run-tests.sh +7 -0
index ab1dea5..f6a3e1b 100755
@@ -2,6 +2,9 @@
 # SPDX-License-Identifier: GPL-2.0
 #
 # Run the objtool klp tests.  Each test-*.sh prints one TAP result line.
+#
+# The harness checks the environment once up front and fails the run if the
+# suite cannot execute, rather than letting every test skip and exit 0.
 
 set -u
 
@@ -10,6 +13,10 @@ cd "$(dirname "$0")" || exit 1
 tests=( test-*.sh )
 [ "${tests[0]}" = "test-*.sh" ] && { echo "1..0 # SKIP no tests found"; exit 0; }
 
+# Sourcing the harness runs its preflight, and exports what it found so the
+# tests inherit it rather than working it out again.
+. ./lib.sh
+
 echo "1..${#tests[@]}"
 
 rc=0
merge bot Applied
#6 lore raw

[tip: objtool/core] objtool/klp: Check the klp test environment once, before any test

In reply to Song Liu
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:     c009fabc865200029173eb40db62f407225043d4
Gitweb:        https://git.kernel.org/tip/c009fabc865200029173eb40db62f407225043d4
Author:        Song Liu <[email protected]>
AuthorDate:    Wed, 16 Sep 2026 11:42:55 -07:00
Committer:     Ingo Molnar <[email protected]>
CommitterDate: Mon, 21 Sep 2026 10:54:35 +02:00

objtool/klp: Check the klp test environment once, before any test

Every test checked for itself that objtool exists, was built with klp support, and that $CC runs. Three problems with that: it is the same work done 40 times, a missing objtool reads as a per-test skip rather than as a suite which cannot run, and a run in which everything skipped still exits 0.

Do it once, before any test, in klp_preflight() in lib.sh, and export the answers where the tests can read them. If the suite cannot run the whole run fails and says why; a test which gets as far as running can assume its environment.

Nothing is written down, so nothing can go stale. Sourcing lib.sh runs the checks, which means a test run by hand establishes its own answers rather than inheriting those of some earlier run with a different CC, and a test is never handed an empty value for where objtool is or which architecture it is on: either the exports are set or the run has already failed.

preflight answers only whether the suite can run at all -- not what the compiler is capable of. A test needing a particular compiler feature probes for it and skips; that costs one compile and keeps the reason next to the test that has to justify it.

---
 tools/objtool/Makefile           |   3 +-
 tools/objtool/tests/lib.sh       | 124 ++++++++++++++++++++++++------
 tools/objtool/tests/run-tests.sh |   7 ++-
 3 files changed, 112 insertions(+), 22 deletions(-)
tools/objtool/Makefile +2 -1
index 0f34abb..e9a4cc8 100644
@@ -154,7 +154,8 @@ mrproper: clean
 	$(call QUIET_CLEAN, objtool) $(RM) $(OBJTOOL)
 
 tests: $(OBJTOOL)
-	$(Q)OBJTOOL=$(abspath $(OBJTOOL)) $(srctree)/tools/objtool/tests/run-tests.sh
+	$(Q)OBJTOOL=$(abspath $(OBJTOOL)) ARCH=$(ARCH) CROSS_COMPILE=$(CROSS_COMPILE) \
+		$(srctree)/tools/objtool/tests/run-tests.sh
 
 FORCE:
 
tools/objtool/tests/lib.sh +103 -21

143 lines not on this page · raw message

tools/objtool/tests/run-tests.sh +7 -0
index ab1dea5..f6a3e1b 100755
@@ -2,6 +2,9 @@
 # SPDX-License-Identifier: GPL-2.0
 #
 # Run the objtool klp tests.  Each test-*.sh prints one TAP result line.
+#
+# The harness checks the environment once up front and fails the run if the
+# suite cannot execute, rather than letting every test skip and exit 0.
 
 set -u
 
@@ -10,6 +13,10 @@ cd "$(dirname "$0")" || exit 1
 tests=( test-*.sh )
 [ "${tests[0]}" = "test-*.sh" ] && { echo "1..0 # SKIP no tests found"; exit 0; }
 
+# Sourcing the harness runs its preflight, and exports what it found so the
+# tests inherit it rather than working it out again.
+. ./lib.sh
+
 echo "1..${#tests[@]}"
 
 rc=0
author maintainer
#7 lore raw

PATCH v5 3/58 objtool/klp: Group the klp tests by architecture

In reply to Song Liu

Which architecture a test is for is expressed by where it lives: tests are in generic/ or in a directory named for their architecture, each carrying its own fixtures, and the runner executes generic/ plus the one that matches. A test which cannot apply here is then not run at all, rather than running in order to announce that it did not.

Layout does this better than a declaration would. There is no x86_only(), and no lookup letting a fixtures/<arch>/ file shadow a generic one of the same name -- an arch-specific test simply carries its own fixtures.

Compilers cannot work the same way: CI varies CC over the same tree, so a compiler requirement stays a declaration in the test.

What a run leaves out is reported once:

  # not run: 5 tests in x86/ (this run is arm64)

Silence would have been cheaper and wrong. A run covering less than the tree holds must not look like a run that covered all of it.

Assisted-by Claude:claude-opus-5
---
 .../tests/{ => generic}/fixtures/basic.c      |  0
 .../objtool/tests/{ => generic}/test-basic.sh |  2 +-
 tools/objtool/tests/lib.sh                    | 27 ++++++++++++--
 tools/objtool/tests/run-tests.sh              | 36 ++++++++++++++++---
 4 files changed, 56 insertions(+), 9 deletions(-)
 rename tools/objtool/tests/{ => generic}/fixtures/basic.c (100%)
 rename tools/objtool/tests/{ => generic}/test-basic.sh (91%)
tools/objtool/tests/generic/fixtures/basic.c renamed from tools/objtool/tests/fixtures/basic.c +0 -0
similarity index 100%
rename from tools/objtool/tests/fixtures/basic.c
rename to tools/objtool/tests/generic/fixtures/basic.c
tools/objtool/tests/generic/test-basic.sh renamed from tools/objtool/tests/test-basic.sh +1 -1
similarity index 91%
rename from tools/objtool/tests/test-basic.sh
rename to tools/objtool/tests/generic/test-basic.sh
index 6b769962399a..562edfbc8646 100755
@@ -3,7 +3,7 @@
 #
 # Only functions whose code changed get cloned into the patch.
 
-. "$(dirname "$0")/lib.sh"
+. "$(dirname "$0")/../lib.sh"
 
 setup
 build_pair basic.c
tools/objtool/tests/lib.sh +24 -3
index 46bdb985765e..fdea9b790c4d 100644
@@ -9,7 +9,10 @@
 # of regressions.
 
 TESTS_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
-FIXTURES_DIR="$TESTS_DIR/fixtures"
+
+# Tests live in generic/ or in an architecture directory beside it, and each
+# carries its own fixtures.
+FIXTURES_DIR="$(cd "$(dirname "$0")/fixtures" 2>/dev/null && pwd)"
 
 # The kernel's convention: CROSS_COMPILE is the one knob, with per-tool
 # overrides for what it does not cover.  objtool itself is always a host binary
@@ -36,7 +39,7 @@ OBJTOOL="${OBJTOOL:-$TESTS_DIR/../objtool}"
 #
 klp_preflight()
 {
-	local tmp tool cc_version host cc_arch
+	local tmp tool cc_version arch host cc_arch
 
 	bail() { echo "Bail out! $*" >&2; exit 1; }
 
@@ -96,8 +99,26 @@ klp_preflight()
 	esac
 	rm -rf "$tmp"
 
+	# Normalize to the kernel's SRCARCH.
+	case "${ARCH:-$(uname -m)}" in
+	x86_64|i?86)	arch=x86 ;;
+	aarch64*)	arch=arm64 ;;
+	*)		arch="${ARCH:-$(uname -m)}" ;;
+	esac
+
+	case "$(uname -m)" in
+	x86_64|i?86)	host=x86 ;;
+	aarch64*)	host=arm64 ;;
+	*)		host="$(uname -m)" ;;
+	esac
+
+	[ -z "$cc_arch" ] || [ "$cc_arch" = "$arch" ] ||
+		bail "ARCH says $arch but '$CC' builds $cc_arch objects;" \
+		     "the $arch tests would run against the wrong architecture"
+
+	KLP_TEST_ARCH="$arch"
 	KLP_TEST_PREFLIGHT=done
-	export OBJTOOL CC KLP_TEST_PREFLIGHT
+	export OBJTOOL CC KLP_TEST_ARCH KLP_TEST_PREFLIGHT
 
 	cc_version="$($CC --version 2>/dev/null | head -1)"
 	cat <<EOF
tools/objtool/tests/run-tests.sh +31 -5
index f6a3e1b7677e..48728a98d995 100755
@@ -3,6 +3,11 @@
 #
 # Run the objtool klp tests.  Each test-*.sh prints one TAP result line.
 #
+# Tests live in generic/ and in a directory per architecture.  A run executes
+# generic/ plus the one matching this architecture, so a test which cannot
+# apply here is not run rather than reporting a skip; what was left out is
+# reported once, as a comment, so differing coverage is still visible.
+#
 # The harness checks the environment once up front and fails the run if the
 # suite cannot execute, rather than letting every test skip and exit 0.
 
@@ -10,13 +15,34 @@ set -u
 
 cd "$(dirname "$0")" || exit 1
 
-tests=( test-*.sh )
-[ "${tests[0]}" = "test-*.sh" ] && { echo "1..0 # SKIP no tests found"; exit 0; }
-
-# Sourcing the harness runs its preflight, and exports what it found so the
-# tests inherit it rather than working it out again.
+# Sourcing the harness runs its preflight, which decides which architecture
+# this run is for -- so the test list cannot be built before it has, and the
+# tests inherit the answers rather than working them out again.
 . ./lib.sh
 
+dirs=( generic )
+[ -d "$KLP_TEST_ARCH" ] && dirs+=( "$KLP_TEST_ARCH" )
+
+tests=()
+for d in "${dirs[@]}"; do
+	for t in "$d"/test-*.sh; do
+		[ -f "$t" ] && tests+=( "$t" )
+	done
+done
+[ "${#tests[@]}" -gt 0 ] || { echo "1..0 # SKIP no tests found"; exit 0; }
+
+# Tests for another architecture are absent from this run entirely.  Say how
+# many, so a run which covers less than the tree holds does not look like one
+# that covers all of it.
+for d in */; do
+	d="${d%/}"
+	case "$d" in generic|"$KLP_TEST_ARCH") continue ;; esac
+	n=$(ls "$d"/test-*.sh 2>/dev/null | wc -l)
+	[ "$n" -gt 0 ] || continue
+	echo "# not run: $n test$( [ "$n" = 1 ] || echo s ) in $d/" \
+	     "(this run is $KLP_TEST_ARCH)"
+done
+
 echo "1..${#tests[@]}"
 
 rc=0
Signature · 1 line
2.53.0-Meta
merge bot Applied
#8 lore raw

[tip: objtool/core] objtool/klp: Group the klp tests by architecture

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:     141ed8d0c414a5298a2da4e06bacbec46f14614e
Gitweb:        https://git.kernel.org/tip/141ed8d0c414a5298a2da4e06bacbec46f14614e
Author:        Song Liu <[email protected]>
AuthorDate:    Wed, 16 Sep 2026 11:42:56 -07:00
Committer:     Josh Poimboeuf <[email protected]>
CommitterDate: Wed, 16 Sep 2026 17:13:26 -07:00

objtool/klp: Group the klp tests by architecture

Which architecture a test is for is expressed by where it lives: tests are in generic/ or in a directory named for their architecture, each carrying its own fixtures, and the runner executes generic/ plus the one that matches. A test which cannot apply here is then not run at all, rather than running in order to announce that it did not.

Layout does this better than a declaration would. There is no x86_only(), and no lookup letting a fixtures/<arch>/ file shadow a generic one of the same name -- an arch-specific test simply carries its own fixtures.

Compilers cannot work the same way: CI varies CC over the same tree, so a compiler requirement stays a declaration in the test.

What a run leaves out is reported once:

  # not run: 5 tests in x86/ (this run is arm64)

Silence would have been cheaper and wrong. A run covering less than the tree holds must not look like a run that covered all of it.

---
 tools/objtool/tests/fixtures/basic.c         | 20 +-----------
 tools/objtool/tests/generic/fixtures/basic.c | 20 +++++++++++-
 tools/objtool/tests/generic/test-basic.sh    | 17 +++++++++-
 tools/objtool/tests/lib.sh                   | 27 ++++++++++++--
 tools/objtool/tests/run-tests.sh             | 36 ++++++++++++++++---
 tools/objtool/tests/test-basic.sh            | 17 +---------
 6 files changed, 92 insertions(+), 45 deletions(-)
 delete mode 100644 tools/objtool/tests/fixtures/basic.c
 create mode 100644 tools/objtool/tests/generic/fixtures/basic.c
 create mode 100755 tools/objtool/tests/generic/test-basic.sh
 delete mode 100755 tools/objtool/tests/test-basic.sh
tools/objtool/tests/fixtures/basic.c deleted +0 -20
deleted file mode 100644
index 811529e..0000000
@@ -1,20 +0,0 @@
-// SPDX-License-Identifier: GPL-2.0
-/* One changed function and one unchanged function. */
-
-/* klp diff takes the object's module name from .modinfo */
-static const char __modinfo[]
-	__attribute__((section(".modinfo"), used, aligned(1))) = "\0name=vmlinux";
-
-int untouched(int x)
-{
-	return x * 3;
-}
-
-int changed(int x)
-{
-#ifdef PATCHED
-	return x + 2;
-#else
-	return x + 1;
-#endif
-}
tools/objtool/tests/generic/fixtures/basic.c new file +20 -0
new file mode 100644
index 0000000..811529e
@@ -0,0 +1,20 @@
+// SPDX-License-Identifier: GPL-2.0
+/* One changed function and one unchanged function. */
+
+/* klp diff takes the object's module name from .modinfo */
+static const char __modinfo[]
+	__attribute__((section(".modinfo"), used, aligned(1))) = "\0name=vmlinux";
+
+int untouched(int x)
+{
+	return x * 3;
+}
+
+int changed(int x)
+{
+#ifdef PATCHED
+	return x + 2;
+#else
+	return x + 1;
+#endif
+}
tools/objtool/tests/generic/test-basic.sh new file +17 -0
new file mode 100755
index 0000000..562edfb
@@ -0,0 +1,17 @@
+#!/bin/bash
+# SPDX-License-Identifier: GPL-2.0
+#
+# Only functions whose code changed get cloned into the patch.
+
+. "$(dirname "$0")/../lib.sh"
+
+setup
+build_pair basic.c
+run_diff
+
+assert_patched     changed
+assert_not_patched untouched
+assert_section     ".init.klp_funcs"
+assert_section     ".init.klp_objects"
+
+pass "changed function cloned, unchanged function left alone"
tools/objtool/tests/lib.sh +24 -3
index 46bdb98..fdea9b7 100644
@@ -9,7 +9,10 @@
 # of regressions.
 
 TESTS_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
-FIXTURES_DIR="$TESTS_DIR/fixtures"
+
+# Tests live in generic/ or in an architecture directory beside it, and each
+# carries its own fixtures.
+FIXTURES_DIR="$(cd "$(dirname "$0")/fixtures" 2>/dev/null && pwd)"
 
 # The kernel's convention: CROSS_COMPILE is the one knob, with per-tool
 # overrides for what it does not cover.  objtool itself is always a host binary
@@ -36,7 +39,7 @@ OBJTOOL="${OBJTOOL:-$TESTS_DIR/../objtool}"
 #
 klp_preflight()
 {
-	local tmp tool cc_version host cc_arch
+	local tmp tool cc_version arch host cc_arch
 
 	bail() { echo "Bail out! $*" >&2; exit 1; }
 
@@ -96,8 +99,26 @@ klp_preflight()
 	esac
 	rm -rf "$tmp"
 
+	# Normalize to the kernel's SRCARCH.
+	case "${ARCH:-$(uname -m)}" in
+	x86_64|i?86)	arch=x86 ;;
+	aarch64*)	arch=arm64 ;;
+	*)		arch="${ARCH:-$(uname -m)}" ;;
+	esac
+
+	case "$(uname -m)" in
+	x86_64|i?86)	host=x86 ;;
+	aarch64*)	host=arm64 ;;
+	*)		host="$(uname -m)" ;;
+	esac
+
+	[ -z "$cc_arch" ] || [ "$cc_arch" = "$arch" ] ||
+		bail "ARCH says $arch but '$CC' builds $cc_arch objects;" \
+		     "the $arch tests would run against the wrong architecture"
+
+	KLP_TEST_ARCH="$arch"
 	KLP_TEST_PREFLIGHT=done
-	export OBJTOOL CC KLP_TEST_PREFLIGHT
+	export OBJTOOL CC KLP_TEST_ARCH KLP_TEST_PREFLIGHT
 
 	cc_version="$($CC --version 2>/dev/null | head -1)"
 	cat <<EOF
tools/objtool/tests/run-tests.sh +31 -5
index f6a3e1b..48728a9 100755
@@ -3,6 +3,11 @@
 #
 # Run the objtool klp tests.  Each test-*.sh prints one TAP result line.
 #
+# Tests live in generic/ and in a directory per architecture.  A run executes
+# generic/ plus the one matching this architecture, so a test which cannot
+# apply here is not run rather than reporting a skip; what was left out is
+# reported once, as a comment, so differing coverage is still visible.
+#
 # The harness checks the environment once up front and fails the run if the
 # suite cannot execute, rather than letting every test skip and exit 0.
 
@@ -10,13 +15,34 @@ set -u
 
 cd "$(dirname "$0")" || exit 1
 
-tests=( test-*.sh )
-[ "${tests[0]}" = "test-*.sh" ] && { echo "1..0 # SKIP no tests found"; exit 0; }
-
-# Sourcing the harness runs its preflight, and exports what it found so the
-# tests inherit it rather than working it out again.
+# Sourcing the harness runs its preflight, which decides which architecture
+# this run is for -- so the test list cannot be built before it has, and the
+# tests inherit the answers rather than working them out again.
 . ./lib.sh
 
+dirs=( generic )
+[ -d "$KLP_TEST_ARCH" ] && dirs+=( "$KLP_TEST_ARCH" )
+
+tests=()
+for d in "${dirs[@]}"; do
+	for t in "$d"/test-*.sh; do
+		[ -f "$t" ] && tests+=( "$t" )
+	done
+done
+[ "${#tests[@]}" -gt 0 ] || { echo "1..0 # SKIP no tests found"; exit 0; }
+
+# Tests for another architecture are absent from this run entirely.  Say how
+# many, so a run which covers less than the tree holds does not look like one
+# that covers all of it.
+for d in */; do
+	d="${d%/}"
+	case "$d" in generic|"$KLP_TEST_ARCH") continue ;; esac
+	n=$(ls "$d"/test-*.sh 2>/dev/null | wc -l)
+	[ "$n" -gt 0 ] || continue
+	echo "# not run: $n test$( [ "$n" = 1 ] || echo s ) in $d/" \
+	     "(this run is $KLP_TEST_ARCH)"
+done
+
 echo "1..${#tests[@]}"
 
 rc=0
tools/objtool/tests/test-basic.sh deleted +0 -17
deleted file mode 100755
index 6b76996..0000000
@@ -1,17 +0,0 @@
-#!/bin/bash
-# SPDX-License-Identifier: GPL-2.0
-#
-# Only functions whose code changed get cloned into the patch.
-
-. "$(dirname "$0")/lib.sh"
-
-setup
-build_pair basic.c
-run_diff
-
-assert_patched     changed
-assert_not_patched untouched
-assert_section     ".init.klp_funcs"
-assert_section     ".init.klp_objects"
-
-pass "changed function cloned, unchanged function left alone"
merge bot Applied
#9 lore raw

[tip: objtool/core] objtool/klp: Group the klp tests by architecture

In reply to Song Liu
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:     d76312b8a1f69be71ec38d04d69fbcdd0520ff89
Gitweb:        https://git.kernel.org/tip/d76312b8a1f69be71ec38d04d69fbcdd0520ff89
Author:        Song Liu <[email protected]>
AuthorDate:    Wed, 16 Sep 2026 11:42:56 -07:00
Committer:     Ingo Molnar <[email protected]>
CommitterDate: Mon, 21 Sep 2026 10:54:41 +02:00

objtool/klp: Group the klp tests by architecture

Which architecture a test is for is expressed by where it lives: tests are in generic/ or in a directory named for their architecture, each carrying its own fixtures, and the runner executes generic/ plus the one that matches. A test which cannot apply here is then not run at all, rather than running in order to announce that it did not.

Layout does this better than a declaration would. There is no x86_only(), and no lookup letting a fixtures/<arch>/ file shadow a generic one of the same name -- an arch-specific test simply carries its own fixtures.

Compilers cannot work the same way: CI varies CC over the same tree, so a compiler requirement stays a declaration in the test.

What a run leaves out is reported once:

  # not run: 5 tests in x86/ (this run is arm64)

Silence would have been cheaper and wrong. A run covering less than the tree holds must not look like a run that covered all of it.

---
 tools/objtool/tests/fixtures/basic.c         | 20 +-----------
 tools/objtool/tests/generic/fixtures/basic.c | 20 +++++++++++-
 tools/objtool/tests/generic/test-basic.sh    | 17 +++++++++-
 tools/objtool/tests/lib.sh                   | 27 ++++++++++++--
 tools/objtool/tests/run-tests.sh             | 36 ++++++++++++++++---
 tools/objtool/tests/test-basic.sh            | 17 +---------
 6 files changed, 92 insertions(+), 45 deletions(-)
 delete mode 100644 tools/objtool/tests/fixtures/basic.c
 create mode 100644 tools/objtool/tests/generic/fixtures/basic.c
 create mode 100755 tools/objtool/tests/generic/test-basic.sh
 delete mode 100755 tools/objtool/tests/test-basic.sh
tools/objtool/tests/fixtures/basic.c deleted +0 -20
deleted file mode 100644
index 811529e..0000000
@@ -1,20 +0,0 @@
-// SPDX-License-Identifier: GPL-2.0
-/* One changed function and one unchanged function. */
-
-/* klp diff takes the object's module name from .modinfo */
-static const char __modinfo[]
-	__attribute__((section(".modinfo"), used, aligned(1))) = "\0name=vmlinux";
-
-int untouched(int x)
-{
-	return x * 3;
-}
-
-int changed(int x)
-{
-#ifdef PATCHED
-	return x + 2;
-#else
-	return x + 1;
-#endif
-}
tools/objtool/tests/generic/fixtures/basic.c new file +20 -0
new file mode 100644
index 0000000..811529e
@@ -0,0 +1,20 @@
+// SPDX-License-Identifier: GPL-2.0
+/* One changed function and one unchanged function. */
+
+/* klp diff takes the object's module name from .modinfo */
+static const char __modinfo[]
+	__attribute__((section(".modinfo"), used, aligned(1))) = "\0name=vmlinux";
+
+int untouched(int x)
+{
+	return x * 3;
+}
+
+int changed(int x)
+{
+#ifdef PATCHED
+	return x + 2;
+#else
+	return x + 1;
+#endif
+}
tools/objtool/tests/generic/test-basic.sh new file +17 -0
new file mode 100755
index 0000000..562edfb
@@ -0,0 +1,17 @@
+#!/bin/bash
+# SPDX-License-Identifier: GPL-2.0
+#
+# Only functions whose code changed get cloned into the patch.
+
+. "$(dirname "$0")/../lib.sh"
+
+setup
+build_pair basic.c
+run_diff
+
+assert_patched     changed
+assert_not_patched untouched
+assert_section     ".init.klp_funcs"
+assert_section     ".init.klp_objects"
+
+pass "changed function cloned, unchanged function left alone"
tools/objtool/tests/lib.sh +24 -3
index 46bdb98..fdea9b7 100644
@@ -9,7 +9,10 @@
 # of regressions.
 
 TESTS_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
-FIXTURES_DIR="$TESTS_DIR/fixtures"
+
+# Tests live in generic/ or in an architecture directory beside it, and each
+# carries its own fixtures.
+FIXTURES_DIR="$(cd "$(dirname "$0")/fixtures" 2>/dev/null && pwd)"
 
 # The kernel's convention: CROSS_COMPILE is the one knob, with per-tool
 # overrides for what it does not cover.  objtool itself is always a host binary
@@ -36,7 +39,7 @@ OBJTOOL="${OBJTOOL:-$TESTS_DIR/../objtool}"
 #
 klp_preflight()
 {
-	local tmp tool cc_version host cc_arch
+	local tmp tool cc_version arch host cc_arch
 
 	bail() { echo "Bail out! $*" >&2; exit 1; }
 
@@ -96,8 +99,26 @@ klp_preflight()
 	esac
 	rm -rf "$tmp"
 
+	# Normalize to the kernel's SRCARCH.
+	case "${ARCH:-$(uname -m)}" in
+	x86_64|i?86)	arch=x86 ;;
+	aarch64*)	arch=arm64 ;;
+	*)		arch="${ARCH:-$(uname -m)}" ;;
+	esac
+
+	case "$(uname -m)" in
+	x86_64|i?86)	host=x86 ;;
+	aarch64*)	host=arm64 ;;
+	*)		host="$(uname -m)" ;;
+	esac
+
+	[ -z "$cc_arch" ] || [ "$cc_arch" = "$arch" ] ||
+		bail "ARCH says $arch but '$CC' builds $cc_arch objects;" \
+		     "the $arch tests would run against the wrong architecture"
+
+	KLP_TEST_ARCH="$arch"
 	KLP_TEST_PREFLIGHT=done
-	export OBJTOOL CC KLP_TEST_PREFLIGHT
+	export OBJTOOL CC KLP_TEST_ARCH KLP_TEST_PREFLIGHT
 
 	cc_version="$($CC --version 2>/dev/null | head -1)"
 	cat <<EOF
tools/objtool/tests/run-tests.sh +31 -5
index f6a3e1b..48728a9 100755
@@ -3,6 +3,11 @@
 #
 # Run the objtool klp tests.  Each test-*.sh prints one TAP result line.
 #
+# Tests live in generic/ and in a directory per architecture.  A run executes
+# generic/ plus the one matching this architecture, so a test which cannot
+# apply here is not run rather than reporting a skip; what was left out is
+# reported once, as a comment, so differing coverage is still visible.
+#
 # The harness checks the environment once up front and fails the run if the
 # suite cannot execute, rather than letting every test skip and exit 0.
 
@@ -10,13 +15,34 @@ set -u
 
 cd "$(dirname "$0")" || exit 1
 
-tests=( test-*.sh )
-[ "${tests[0]}" = "test-*.sh" ] && { echo "1..0 # SKIP no tests found"; exit 0; }
-
-# Sourcing the harness runs its preflight, and exports what it found so the
-# tests inherit it rather than working it out again.
+# Sourcing the harness runs its preflight, which decides which architecture
+# this run is for -- so the test list cannot be built before it has, and the
+# tests inherit the answers rather than working them out again.
 . ./lib.sh
 
+dirs=( generic )
+[ -d "$KLP_TEST_ARCH" ] && dirs+=( "$KLP_TEST_ARCH" )
+
+tests=()
+for d in "${dirs[@]}"; do
+	for t in "$d"/test-*.sh; do
+		[ -f "$t" ] && tests+=( "$t" )
+	done
+done
+[ "${#tests[@]}" -gt 0 ] || { echo "1..0 # SKIP no tests found"; exit 0; }
+
+# Tests for another architecture are absent from this run entirely.  Say how
+# many, so a run which covers less than the tree holds does not look like one
+# that covers all of it.
+for d in */; do
+	d="${d%/}"
+	case "$d" in generic|"$KLP_TEST_ARCH") continue ;; esac
+	n=$(ls "$d"/test-*.sh 2>/dev/null | wc -l)
+	[ "$n" -gt 0 ] || continue
+	echo "# not run: $n test$( [ "$n" = 1 ] || echo s ) in $d/" \
+	     "(this run is $KLP_TEST_ARCH)"
+done
+
 echo "1..${#tests[@]}"
 
 rc=0
tools/objtool/tests/test-basic.sh deleted +0 -17
deleted file mode 100755
index 6b76996..0000000
@@ -1,17 +0,0 @@
-#!/bin/bash
-# SPDX-License-Identifier: GPL-2.0
-#
-# Only functions whose code changed get cloned into the patch.
-
-. "$(dirname "$0")/lib.sh"
-
-setup
-build_pair basic.c
-run_diff
-
-assert_patched     changed
-assert_not_patched untouched
-assert_section     ".init.klp_funcs"
-assert_section     ".init.klp_objects"
-
-pass "changed function cloned, unchanged function left alone"
author maintainer
#10 lore raw

PATCH v5 4/58 objtool/klp: Classify klp test outcomes

In reply to Song Liu

A test could pass, fail, or skip, and the runner reported only the exit status of the last one to fail. Skips are the interesting case: they are how a suite quietly stops testing anything.

Three kinds, and the runner counts them separately:

declared the test said in advance it does not apply here, e.g. gcc_only
on a clang run. Expected indefinitely.
probe the construct did not turn up in the built object this time.
Weaker: one which becomes permanent is a fixture that stopped testing anything.
undeclared counted as a failure. A test which gives up for a reason it
never declared is a hole, not an outcome.

xfail and xpass come with them, so a known failure is reported rather than commented out and forgotten, and one which starts passing says so instead of going quietly green.

The result line is what gets classified, not the whole of a test's output:
objtool warns on stderr and the runner captures it, and a stray line ahead of the result would otherwise leave the exit status to decide -- counting an expected failure, which exits 0, as a pass.

Every test owes the plan exactly one result line, so a substituted verdict replaces the test's own rather than being printed beside it, and a test which dies before reporting gets a result of its own instead of being inferred from its exit status.

Also: a TAP version line, LC_ALL=C so the order tests run in and the behaviour of grep's character ranges inside them do not depend on the invoking shell's locale, and fail() on stdout with every other verdict.

Assisted-by Claude:claude-opus-5
---
 tools/objtool/tests/lib.sh       |  67 ++++++++++++--
 tools/objtool/tests/run-tests.sh | 148 ++++++++++++++++++++++++++-----
 2 files changed, 186 insertions(+), 29 deletions(-)
tools/objtool/tests/lib.sh +59 -8
index fdea9b790c4d..1531caab4627 100644
@@ -139,8 +139,38 @@ test_name="$(basename "$0" .sh)"
 workdir=
 
 pass() { echo "ok - $test_name${1:+: $1}"; exit 0; }
-fail() { echo "not ok - $test_name: $1" >&2; exit 1; }
-skip() { echo "ok - $test_name # SKIP $1"; exit 0; }
+fail() { echo "not ok - $test_name: $1"; exit 1; }
+
+# Two kinds of skip, and the runner tells them apart.
+#
+#   declared_skip  the test said in advance it does not apply here, e.g.
+#                  gcc_only on a clang run.  Expected indefinitely.
+#   probe_skip     the construct did not turn up in the built object this
+#                  time.  Weaker: it may appear on another compiler version,
+#                  and one which becomes permanent is a fixture that quietly
+#                  stopped testing anything.
+#
+# A bare skip() is neither, and the runner counts it as a failure: a test which
+# gives up for a reason it never declared is a hole, not an outcome.
+declared_skip() { echo "ok - $test_name # SKIP (declared) $*"; exit 0; }
+probe_skip()    { echo "ok - $test_name # SKIP (probe) $*"; exit 0; }
+skip()          { echo "ok - $test_name # SKIP $*"; exit 0; }
+
+# TAP directives.  A test which is known to fail reports it rather than being
+# commented out and forgotten, and one which starts passing again says so
+# instead of quietly going green: the expectation has to be removed by hand,
+# which is the point.
+xfail()
+{
+	echo "not ok - $test_name${1:+: $1} # TODO known failure"
+	exit 0
+}
+
+xpass()
+{
+	echo "ok - $test_name${1:+: $1} # TODO expected failure, but passed"
+	exit 1
+}
 
 cleanup() { [ -n "$workdir" ] && rm -rf "$workdir"; }
 
@@ -170,6 +200,23 @@ export_syms()
 	done
 }
 
+# gcc_only / clang_only <reason>
+gcc_only()
+{
+	case "$($CC --version 2>/dev/null | head -1)" in
+	*[Gg][Cc][Cc]*)	return 0 ;;
+	esac
+	declared_skip "gcc only${1:+: $1}"
+}
+
+clang_only()
+{
+	case "$($CC --version 2>/dev/null | head -1)" in
+	*clang*)	return 0 ;;
+	esac
+	declared_skip "clang only${1:+: $1}"
+}
+
 # build_pair <fixture.c> [cflags...]
 build_pair()
 {
@@ -178,9 +225,9 @@ build_pair()
 	[ -f "$fixture" ] || fail "missing fixture $fixture"
 
 	$CC $FIXTURE_CFLAGS "$@" -o "$workdir/orig.o" "$fixture" 2>"$workdir/cc.log" ||
-		skip "fixture does not build here: $(tail -1 "$workdir/cc.log")"
+		probe_skip "fixture does not build here: $(tail -1 "$workdir/cc.log")"
 	$CC $FIXTURE_CFLAGS "$@" -DPATCHED -o "$workdir/patched.o" "$fixture" 2>"$workdir/cc.log" ||
-		skip "fixture does not build here: $(tail -1 "$workdir/cc.log")"
+		probe_skip "fixture does not build here: $(tail -1 "$workdir/cc.log")"
 }
 
 # run_diff [expected exit status]
@@ -226,16 +273,20 @@ partial_link()
 
 # find_thinlto_toolchain
 #
-# Set $THIN_CC and $THIN_LD to a clang and lld from the same LLVM release.  A
+# Set $THIN_LD to an lld from the same LLVM release as $CC (or THIN_CC).  A
 # mismatched pair fails with "Invalid summary version", which reads like a
 # broken test rather than a broken environment.
+#
+# ThinLTO is clang-only; callers must use clang_only before calling this.
+# Only $CC (or an explicit THIN_CC override) is consulted -- the harness does
+# not search for a second compiler beside a gcc $CC.
 find_thinlto_toolchain()
 {
-	local cc ld ver
+	local cc ver ld
 
-	for cc in "${THIN_CC:-}" "$CC" clang; do
+	for cc in "${THIN_CC:-}" "$CC"; do
 		[ -n "$cc" ] || continue
-		command -v "${cc%% *}" >/dev/null 2>&1 || continue
+		command -v "${cc%% *}" >/dev/null 2>&1 || return 1
 
 		ver=$($cc -dumpversion 2>/dev/null | cut -d. -f1)
 
tools/objtool/tests/run-tests.sh +127 -21

171 lines not on this page · raw message

Signature · 1 line
2.53.0-Meta
merge bot Applied
#11 lore raw

[tip: objtool/core] objtool/klp: Classify klp test outcomes

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:     6fdf5af30f1e092b83df6b37ca63947babded5b4
Gitweb:        https://git.kernel.org/tip/6fdf5af30f1e092b83df6b37ca63947babded5b4
Author:        Song Liu <[email protected]>
AuthorDate:    Wed, 16 Sep 2026 11:42:57 -07:00
Committer:     Josh Poimboeuf <[email protected]>
CommitterDate: Wed, 16 Sep 2026 17:13:26 -07:00

objtool/klp: Classify klp test outcomes

A test could pass, fail, or skip, and the runner reported only the exit status of the last one to fail. Skips are the interesting case: they are how a suite quietly stops testing anything.

Three kinds, and the runner counts them separately:

declared the test said in advance it does not apply here, e.g. gcc_only
on a clang run. Expected indefinitely.
probe the construct did not turn up in the built object this time.
Weaker: one which becomes permanent is a fixture that stopped testing anything.
undeclared counted as a failure. A test which gives up for a reason it
never declared is a hole, not an outcome.

xfail and xpass come with them, so a known failure is reported rather than commented out and forgotten, and one which starts passing says so instead of going quietly green.

The result line is what gets classified, not the whole of a test's output:
objtool warns on stderr and the runner captures it, and a stray line ahead of the result would otherwise leave the exit status to decide -- counting an expected failure, which exits 0, as a pass.

Every test owes the plan exactly one result line, so a substituted verdict replaces the test's own rather than being printed beside it, and a test which dies before reporting gets a result of its own instead of being inferred from its exit status.

Also: a TAP version line, LC_ALL=C so the order tests run in and the behaviour of grep's character ranges inside them do not depend on the invoking shell's locale, and fail() on stdout with every other verdict.

---
 tools/objtool/tests/lib.sh       |  67 ++++++++++++--
 tools/objtool/tests/run-tests.sh | 148 +++++++++++++++++++++++++-----
 2 files changed, 186 insertions(+), 29 deletions(-)
tools/objtool/tests/lib.sh +59 -8
index fdea9b7..1531caa 100644
@@ -139,8 +139,38 @@ test_name="$(basename "$0" .sh)"
 workdir=
 
 pass() { echo "ok - $test_name${1:+: $1}"; exit 0; }
-fail() { echo "not ok - $test_name: $1" >&2; exit 1; }
-skip() { echo "ok - $test_name # SKIP $1"; exit 0; }
+fail() { echo "not ok - $test_name: $1"; exit 1; }
+
+# Two kinds of skip, and the runner tells them apart.
+#
+#   declared_skip  the test said in advance it does not apply here, e.g.
+#                  gcc_only on a clang run.  Expected indefinitely.
+#   probe_skip     the construct did not turn up in the built object this
+#                  time.  Weaker: it may appear on another compiler version,
+#                  and one which becomes permanent is a fixture that quietly
+#                  stopped testing anything.
+#
+# A bare skip() is neither, and the runner counts it as a failure: a test which
+# gives up for a reason it never declared is a hole, not an outcome.
+declared_skip() { echo "ok - $test_name # SKIP (declared) $*"; exit 0; }
+probe_skip()    { echo "ok - $test_name # SKIP (probe) $*"; exit 0; }
+skip()          { echo "ok - $test_name # SKIP $*"; exit 0; }
+
+# TAP directives.  A test which is known to fail reports it rather than being
+# commented out and forgotten, and one which starts passing again says so
+# instead of quietly going green: the expectation has to be removed by hand,
+# which is the point.
+xfail()
+{
+	echo "not ok - $test_name${1:+: $1} # TODO known failure"
+	exit 0
+}
+
+xpass()
+{
+	echo "ok - $test_name${1:+: $1} # TODO expected failure, but passed"
+	exit 1
+}
 
 cleanup() { [ -n "$workdir" ] && rm -rf "$workdir"; }
 
@@ -170,6 +200,23 @@ export_syms()
 	done
 }
 
+# gcc_only / clang_only <reason>
+gcc_only()
+{
+	case "$($CC --version 2>/dev/null | head -1)" in
+	*[Gg][Cc][Cc]*)	return 0 ;;
+	esac
+	declared_skip "gcc only${1:+: $1}"
+}
+
+clang_only()
+{
+	case "$($CC --version 2>/dev/null | head -1)" in
+	*clang*)	return 0 ;;
+	esac
+	declared_skip "clang only${1:+: $1}"
+}
+
 # build_pair <fixture.c> [cflags...]
 build_pair()
 {
@@ -178,9 +225,9 @@ build_pair()
 	[ -f "$fixture" ] || fail "missing fixture $fixture"
 
 	$CC $FIXTURE_CFLAGS "$@" -o "$workdir/orig.o" "$fixture" 2>"$workdir/cc.log" ||
-		skip "fixture does not build here: $(tail -1 "$workdir/cc.log")"
+		probe_skip "fixture does not build here: $(tail -1 "$workdir/cc.log")"
 	$CC $FIXTURE_CFLAGS "$@" -DPATCHED -o "$workdir/patched.o" "$fixture" 2>"$workdir/cc.log" ||
-		skip "fixture does not build here: $(tail -1 "$workdir/cc.log")"
+		probe_skip "fixture does not build here: $(tail -1 "$workdir/cc.log")"
 }
 
 # run_diff [expected exit status]
@@ -226,16 +273,20 @@ partial_link()
 
 # find_thinlto_toolchain
 #
-# Set $THIN_CC and $THIN_LD to a clang and lld from the same LLVM release.  A
+# Set $THIN_LD to an lld from the same LLVM release as $CC (or THIN_CC).  A
 # mismatched pair fails with "Invalid summary version", which reads like a
 # broken test rather than a broken environment.
+#
+# ThinLTO is clang-only; callers must use clang_only before calling this.
+# Only $CC (or an explicit THIN_CC override) is consulted -- the harness does
+# not search for a second compiler beside a gcc $CC.
 find_thinlto_toolchain()
 {
-	local cc ld ver
+	local cc ver ld
 
-	for cc in "${THIN_CC:-}" "$CC" clang; do
+	for cc in "${THIN_CC:-}" "$CC"; do
 		[ -n "$cc" ] || continue
-		command -v "${cc%% *}" >/dev/null 2>&1 || continue
+		command -v "${cc%% *}" >/dev/null 2>&1 || return 1
 
 		ver=$($cc -dumpversion 2>/dev/null | cut -d. -f1)
 
tools/objtool/tests/run-tests.sh +127 -21

171 lines not on this page · raw message

merge bot Applied
#12 lore raw

[tip: objtool/core] objtool/klp: Classify klp test outcomes

In reply to Song Liu
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:     317cec905af82e9ccca93cec661e88b1d3968a43
Gitweb:        https://git.kernel.org/tip/317cec905af82e9ccca93cec661e88b1d3968a43
Author:        Song Liu <[email protected]>
AuthorDate:    Wed, 16 Sep 2026 11:42:57 -07:00
Committer:     Ingo Molnar <[email protected]>
CommitterDate: Mon, 21 Sep 2026 10:55:09 +02:00

objtool/klp: Classify klp test outcomes

A test could pass, fail, or skip, and the runner reported only the exit status of the last one to fail. Skips are the interesting case: they are how a suite quietly stops testing anything.

Three kinds, and the runner counts them separately:

declared the test said in advance it does not apply here, e.g. gcc_only
on a clang run. Expected indefinitely.
probe the construct did not turn up in the built object this time.
Weaker: one which becomes permanent is a fixture that stopped testing anything.
undeclared counted as a failure. A test which gives up for a reason it
never declared is a hole, not an outcome.

xfail and xpass come with them, so a known failure is reported rather than commented out and forgotten, and one which starts passing says so instead of going quietly green.

The result line is what gets classified, not the whole of a test's output:
objtool warns on stderr and the runner captures it, and a stray line ahead of the result would otherwise leave the exit status to decide -- counting an expected failure, which exits 0, as a pass.

Every test owes the plan exactly one result line, so a substituted verdict replaces the test's own rather than being printed beside it, and a test which dies before reporting gets a result of its own instead of being inferred from its exit status.

Also: a TAP version line, LC_ALL=C so the order tests run in and the behaviour of grep's character ranges inside them do not depend on the invoking shell's locale, and fail() on stdout with every other verdict.

---
 tools/objtool/tests/lib.sh       |  67 ++++++++++++--
 tools/objtool/tests/run-tests.sh | 148 +++++++++++++++++++++++++-----
 2 files changed, 186 insertions(+), 29 deletions(-)
tools/objtool/tests/lib.sh +59 -8
index fdea9b7..1531caa 100644
@@ -139,8 +139,38 @@ test_name="$(basename "$0" .sh)"
 workdir=
 
 pass() { echo "ok - $test_name${1:+: $1}"; exit 0; }
-fail() { echo "not ok - $test_name: $1" >&2; exit 1; }
-skip() { echo "ok - $test_name # SKIP $1"; exit 0; }
+fail() { echo "not ok - $test_name: $1"; exit 1; }
+
+# Two kinds of skip, and the runner tells them apart.
+#
+#   declared_skip  the test said in advance it does not apply here, e.g.
+#                  gcc_only on a clang run.  Expected indefinitely.
+#   probe_skip     the construct did not turn up in the built object this
+#                  time.  Weaker: it may appear on another compiler version,
+#                  and one which becomes permanent is a fixture that quietly
+#                  stopped testing anything.
+#
+# A bare skip() is neither, and the runner counts it as a failure: a test which
+# gives up for a reason it never declared is a hole, not an outcome.
+declared_skip() { echo "ok - $test_name # SKIP (declared) $*"; exit 0; }
+probe_skip()    { echo "ok - $test_name # SKIP (probe) $*"; exit 0; }
+skip()          { echo "ok - $test_name # SKIP $*"; exit 0; }
+
+# TAP directives.  A test which is known to fail reports it rather than being
+# commented out and forgotten, and one which starts passing again says so
+# instead of quietly going green: the expectation has to be removed by hand,
+# which is the point.
+xfail()
+{
+	echo "not ok - $test_name${1:+: $1} # TODO known failure"
+	exit 0
+}
+
+xpass()
+{
+	echo "ok - $test_name${1:+: $1} # TODO expected failure, but passed"
+	exit 1
+}
 
 cleanup() { [ -n "$workdir" ] && rm -rf "$workdir"; }
 
@@ -170,6 +200,23 @@ export_syms()
 	done
 }
 
+# gcc_only / clang_only <reason>
+gcc_only()
+{
+	case "$($CC --version 2>/dev/null | head -1)" in
+	*[Gg][Cc][Cc]*)	return 0 ;;
+	esac
+	declared_skip "gcc only${1:+: $1}"
+}
+
+clang_only()
+{
+	case "$($CC --version 2>/dev/null | head -1)" in
+	*clang*)	return 0 ;;
+	esac
+	declared_skip "clang only${1:+: $1}"
+}
+
 # build_pair <fixture.c> [cflags...]
 build_pair()
 {
@@ -178,9 +225,9 @@ build_pair()
 	[ -f "$fixture" ] || fail "missing fixture $fixture"
 
 	$CC $FIXTURE_CFLAGS "$@" -o "$workdir/orig.o" "$fixture" 2>"$workdir/cc.log" ||
-		skip "fixture does not build here: $(tail -1 "$workdir/cc.log")"
+		probe_skip "fixture does not build here: $(tail -1 "$workdir/cc.log")"
 	$CC $FIXTURE_CFLAGS "$@" -DPATCHED -o "$workdir/patched.o" "$fixture" 2>"$workdir/cc.log" ||
-		skip "fixture does not build here: $(tail -1 "$workdir/cc.log")"
+		probe_skip "fixture does not build here: $(tail -1 "$workdir/cc.log")"
 }
 
 # run_diff [expected exit status]
@@ -226,16 +273,20 @@ partial_link()
 
 # find_thinlto_toolchain
 #
-# Set $THIN_CC and $THIN_LD to a clang and lld from the same LLVM release.  A
+# Set $THIN_LD to an lld from the same LLVM release as $CC (or THIN_CC).  A
 # mismatched pair fails with "Invalid summary version", which reads like a
 # broken test rather than a broken environment.
+#
+# ThinLTO is clang-only; callers must use clang_only before calling this.
+# Only $CC (or an explicit THIN_CC override) is consulted -- the harness does
+# not search for a second compiler beside a gcc $CC.
 find_thinlto_toolchain()
 {
-	local cc ld ver
+	local cc ver ld
 
-	for cc in "${THIN_CC:-}" "$CC" clang; do
+	for cc in "${THIN_CC:-}" "$CC"; do
 		[ -n "$cc" ] || continue
-		command -v "${cc%% *}" >/dev/null 2>&1 || continue
+		command -v "${cc%% *}" >/dev/null 2>&1 || return 1
 
 		ver=$($cc -dumpversion 2>/dev/null | cut -d. -f1)
 
tools/objtool/tests/run-tests.sh +127 -21

171 lines not on this page · raw message

author maintainer
#13 lore raw

PATCH v5 5/58 objtool/klp: Build klp test fixtures through the harness

In reply to Song Liu

Compiling a fixture is the one thing every test does, and it has more invariants than it looks.

- The flags describe the kernel a fixture stands in for, and each is written down with its reason. That substitution is the whole mechanism by which these tests cover configurations without building a kernel -- objtool reads no .config, so a configuration reaches it only as compiler flags and the bytes they produce -- and a flag with no stated motive is indistinguishable from a mistake.

- -c is not one of them. Producing an object rather than a program is the helper's contract, not something a test may reconsider, so it lives at the compile and an override cannot drop it.

- A fixture which will not compile is a failure, not a skip. It is far more often a mistake in the fixture than a compiler which cannot express the construct, and the two are indistinguishable once reported as a skip.

- A newly produced object has no checksums in it, so producing one invalidates the record that checksumming has already been done. Left to itself that invariant ends up in each test which rebuilds.

build_one handles a single object for the tests which need more than two or different names; build_pair and build_module_pair are expressed in terms of it, so none of the above can be lost by going around them.

run_checksum comes out of run_diff for the same reason: a test which wants checksums without a diff should not have to run one.

Assisted-by Claude:claude-opus-5
---
 tools/objtool/tests/lib.sh | 205 +++++++++++++++++++++++++++++++++----
 1 file changed, 186 insertions(+), 19 deletions(-)
tools/objtool/tests/lib.sh +186 -19
index 1531caab4627..a4513ae8dfce 100644
@@ -131,13 +131,35 @@ EOF
 
 [ -n "${KLP_TEST_PREFLIGHT:-}" ] || klp_preflight
 
-# klp-build compiles the kernel this way; klp diff needs per-symbol sections to
-# extract individual functions.
-FIXTURE_CFLAGS="-c -O2 -ffunction-sections -fdata-sections -fno-asynchronous-unwind-tables"
+# What every fixture is built with.  These describe the kernel a fixture stands
+# in for; -c is build_one's contract rather than a property of that kernel, so
+# it lives at the compile where an override cannot drop it.
+#
+#   -O2					the kernel's default
+#   -ffunction-sections -fdata-sections	klp-build passes these itself, through
+#					KCFLAGS, whatever the configuration
+#   -fno-asynchronous-unwind-tables	arch/x86/Makefile sets this always, so
+#					kernel objects carry no .eh_frame
+#   -fno-common				the kernel's Makefile sets it, so an
+#					uninitialised global there lands in
+#					.bss rather than being SHN_COMMON,
+#					which has no section and so no
+#					checksum
+#
+# A test overrides it; see tools/objtool/Documentation/klp-write-tests.txt.
+FIXTURE_CFLAGS="-O2 -ffunction-sections -fdata-sections -fno-common \
+		-fno-asynchronous-unwind-tables"
 
 test_name="$(basename "$0" .sh)"
 workdir=
 
+# The pair run_diff() and the checksum helpers work on.  build_pair() names
+# them again and make_vmlinux_pair() repoints orig_obj at the image it links,
+# but a test which builds its objects itself with build_one() sets neither, so
+# the default belongs here.
+orig_obj=orig.o
+patched_obj=patched.o
+
 pass() { echo "ok - $test_name${1:+: $1}"; exit 0; }
 fail() { echo "not ok - $test_name: $1"; exit 1; }
 
@@ -217,17 +239,78 @@ clang_only()
 	declared_skip "clang only${1:+: $1}"
 }
 
+# build_one <fixture.c> <output object> [cflags...]
+build_one()
+{
+	local fixture out
+	fixture="$FIXTURES_DIR/$1"
+	out="$workdir/$2"
+	shift 2
+
+	[ -f "$fixture" ] || fail "missing fixture $fixture"
+
+	# run_checksum only runs once per workdir.  A fresh object has no
+	# checksums in it, so anything built now needs that to happen again.
+	rm -f "$workdir/.checksummed"
+
+	$CC -c $FIXTURE_CFLAGS "$@" -o "$out" "$fixture" 2>"$workdir/cc.log" ||
+		fail "$(basename "$fixture") does not build: $(tail -1 "$workdir/cc.log")"
+}
+
 # build_pair <fixture.c> [cflags...]
 build_pair()
 {
-	local fixture="$FIXTURES_DIR/$1"; shift
+	local fixture="$1"; shift
 
-	[ -f "$fixture" ] || fail "missing fixture $fixture"
+	# Name what this builds.  A test may run several segments, and
+	# make_vmlinux_pair() repoints orig_obj at the image it links, so
+	# without this the next run_diff() would still be reading that.
+	orig_obj=orig.o
+	patched_obj=patched.o
+
+	build_one "$fixture" orig.o "$@"
+	build_one "$fixture" patched.o "$@" -DPATCHED
+}
 
-	$CC $FIXTURE_CFLAGS "$@" -o "$workdir/orig.o" "$fixture" 2>"$workdir/cc.log" ||
-		probe_skip "fixture does not build here: $(tail -1 "$workdir/cc.log")"
-	$CC $FIXTURE_CFLAGS "$@" -DPATCHED -o "$workdir/patched.o" "$fixture" 2>"$workdir/cc.log" ||
-		probe_skip "fixture does not build here: $(tail -1 "$workdir/cc.log")"
+# run_objtool_check <objtool arguments...>
+#
+# Run objtool's ordinary check pass over the pair, as the kernel build does.
+#
+# Some of what klp diff consumes is produced by this pass rather than by the
+# compiler: .static_call_sites, .mcount_loc, .ibt_endbr_seal, ORC.
+#
+# Only module objects see it before klp-build -- with CONFIG_KLP_BUILD the
+# per-object pass is deferred, so built-in objects reach klp diff exactly as
+# the compiler left them.
+run_objtool_check()
+{
+	local obj
+
+	# This rewrites both objects, so checksums taken before it describe
+	# something that no longer exists.  As in build_one(), drop the marker
+	# so run_checksum() takes them again.
+	rm -f "$workdir/.checksummed"
+
+	for obj in "$orig_obj" "$patched_obj"; do
+		"$OBJTOOL" "$@" "$workdir/$obj" ||
+			fail "objtool $* failed on $obj"
+	done
+}
+
+run_checksum()
+{
+	# Checksums live in the objects, and a test may ask for them more than
+	# once -- diffing the same pair again with a different Module.symvers,
+	# say.  objtool does the right thing when asked twice, leaving the
+	# object alone, but it says so, and that warning would be most of what
+	# a passing run prints.  Remember instead, and keep quiet.
+	[ -e "$workdir/.checksummed" ] && return 0
+
+	"$OBJTOOL" klp checksum "$workdir/$orig_obj" ||
+		fail "klp checksum $orig_obj failed"
+	"$OBJTOOL" klp checksum "$workdir/$patched_obj" ||
+		fail "klp checksum $patched_obj failed"
+	touch "$workdir/.checksummed"
 }
 
 # run_diff [expected exit status]
@@ -235,18 +318,10 @@ run_diff()
 {
 	local expect="${1:-0}" rc=0
 
-	# Checksums live in the objects, so only generate them once even when a
-	# test diffs the same pair again with a different Module.symvers.
-	if [ ! -e "$workdir/.checksummed" ]; then
-		"$OBJTOOL" klp checksum "$workdir/orig.o" ||
-			fail "klp checksum orig.o failed"
-		"$OBJTOOL" klp checksum "$workdir/patched.o" ||
-			fail "klp checksum patched.o failed"
-		touch "$workdir/.checksummed"
-	fi
+	run_checksum
 
 	# klp diff looks for Module.symvers relative to the working directory.
-	( cd "$workdir" && "$OBJTOOL" klp diff orig.o patched.o out.o ) \
+	( cd "$workdir" && "$OBJTOOL" klp diff "$orig_obj" "$patched_obj" out.o ) \
 		> "$workdir/diff.log" 2>&1 || rc=$?
 
 	[ "$rc" = "$expect" ] ||
@@ -267,10 +342,102 @@ partial_link()
 {
 	local out="$1"; shift
 
+	rm -f "$workdir/.checksummed"
+
 	$CC -r -nostdlib -o "$out" "$@" 2>/dev/null ||
 		$CC -r -nostdlib -fuse-ld=lld -o "$out" "$@" 2>/dev/null
 }
 
+# link_vmlinux <output> <object...>
+#
+# Link objects into an executable, the way the kernel's final link produces
+# vmlinux from vmlinux.o.  Entry point 0 and no libc: nothing runs it, it only
+# has to be a linked image with resolved addresses.
+#
+# The sub-sections have to come out in name order rather than object order,
+# the way the kernel's linker script gathers .text.unlikely and .data.. apart
+# from the rest.  That reordering is the entire reason .klp.symid exists: a
+# link which preserves order cannot tell a correct sympos from one that merely
+# counted, and the caller checks the two orders really did diverge.
+#
+# A linker script rather than --sort-section=name, because lld accepts that
+# option and ignores it -- so on a host where only lld can link the target, the
+# test would quietly stop testing the thing it is named for.
+#
+# Three attempts because a cross run has neither $LD nor the compiler's default
+# linker able to touch the target: on an arm64 host linking x86 objects, only
+# lld will do it.
+link_vmlinux()
+{
+	local out="$1" lds="$workdir/sort.lds"; shift
+
+	echo 'SECTIONS { .data : { *(SORT_BY_NAME(.data.*)) } }' > "$lds"
+
+	$LD -e 0 -T "$lds" -o "$out" "$@" 2>/dev/null ||
+		$CC -nostdlib -Wl,-e,0 -Wl,-T,"$lds" \
+			-o "$out" "$@" 2>/dev/null ||
+		$CC -nostdlib -fuse-ld=lld -Wl,-e,0 -Wl,-T,"$lds" \
+			-o "$out" "$@" 2>/dev/null
+}
+
+# make_vmlinux_pair <orig object...> -- <patched object...>
+#
+# Build the vmlinux.o / vmlinux pair klp diff needs to resolve sympos the way
+# it does for built-in code, and point the diff at it.
+#
+# For a module, sympos is a count in symbol table order, which klp diff can do
+# from the object alone.  vmlinux is different: the final link reorders
+# sub-sections, so the position comes from the linked image, bridged by
+# .klp.symid.  klp diff only looks for that when the object it was handed is
+# called vmlinux.o and a vmlinux sits beside it -- so both the name and the
+# linked image matter.
+make_vmlinux_pair()
+{
+	local orig=() patched=() seen= arg
+
+	for arg in "$@"; do
+		if [ "$arg" = -- ]; then seen=y; continue; fi
+		if [ -n "$seen" ]; then patched+=( "$arg" ); else orig+=( "$arg" ); fi
+	done
+
+	# Both sides have to have been named.  Without this, forgetting the --
+	# leaves one list empty, the link of nothing fails, and the test skips
+	# saying the toolchain cannot link -- which is a test bug wearing the
+	# costume of an environment one.
+	[ "${#orig[@]}" -gt 0 ] && [ "${#patched[@]}" -gt 0 ] ||
+		fail "make_vmlinux_pair needs objects either side of --"
+
+	partial_link "$workdir/vmlinux.o" "${orig[@]}" ||
+		probe_skip "partial link unavailable"
+	partial_link "$workdir/patched.o" "${patched[@]}" ||
+		probe_skip "partial link unavailable"
+
+	"$OBJTOOL" --klp-symids --link "$workdir/vmlinux.o" ||
+		fail "objtool --klp-symids failed"
+
+	link_vmlinux "$workdir/vmlinux" "$workdir/vmlinux.o" ||
+		probe_skip "cannot link a vmlinux here"
+
+	orig_obj=vmlinux.o
+}
+
+# build_module_pair <fixture.c> <module name> [cflags...]
+#
+# Build the pair as objects belonging to a module rather than to vmlinux.  klp
+# diff reads the object's module name from .modinfo, and that decides which
+# object a relocation is attributed to and whether a reference counts as
+# cross-module, so a good deal of the code has a module path the vmlinux
+# fixtures never reach.
+#
+# The fixture defines its .modinfo name from MODNAME.  Passing that through
+# -D needs two levels of quoting, which is easy to get wrong at the call site.
+build_module_pair()
+{
+	local fixture="$1" modname="$2"; shift 2
+
+	build_pair "$fixture" -DMODNAME="\"$modname\"" "$@"
+}
+
 # find_thinlto_toolchain
 #
 # Set $THIN_LD to an lld from the same LLVM release as $CC (or THIN_CC).  A
Signature · 1 line
2.53.0-Meta
merge bot Applied
#14 lore raw

[tip: objtool/core] objtool/klp: Build klp test fixtures through the harness

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:     18289c2240be1f7122a7e696c05475c09b64f904
Gitweb:        https://git.kernel.org/tip/18289c2240be1f7122a7e696c05475c09b64f904
Author:        Song Liu <[email protected]>
AuthorDate:    Wed, 16 Sep 2026 11:42:58 -07:00
Committer:     Josh Poimboeuf <[email protected]>
CommitterDate: Wed, 16 Sep 2026 17:13:26 -07:00

objtool/klp: Build klp test fixtures through the harness

Compiling a fixture is the one thing every test does, and it has more invariants than it looks.

- The flags describe the kernel a fixture stands in for, and each is written down with its reason. That substitution is the whole mechanism by which these tests cover configurations without building a kernel -- objtool reads no .config, so a configuration reaches it only as compiler flags and the bytes they produce -- and a flag with no stated motive is indistinguishable from a mistake.

- -c is not one of them. Producing an object rather than a program is the helper's contract, not something a test may reconsider, so it lives at the compile and an override cannot drop it.

- A fixture which will not compile is a failure, not a skip. It is far more often a mistake in the fixture than a compiler which cannot express the construct, and the two are indistinguishable once reported as a skip.

- A newly produced object has no checksums in it, so producing one invalidates the record that checksumming has already been done. Left to itself that invariant ends up in each test which rebuilds.

build_one handles a single object for the tests which need more than two or different names; build_pair and build_module_pair are expressed in terms of it, so none of the above can be lost by going around them.

run_checksum comes out of run_diff for the same reason: a test which wants checksums without a diff should not have to run one.

---
 tools/objtool/tests/lib.sh | 205 ++++++++++++++++++++++++++++++++----
 1 file changed, 186 insertions(+), 19 deletions(-)
tools/objtool/tests/lib.sh +186 -19
index 1531caa..a4513ae 100644
@@ -131,13 +131,35 @@ EOF
 
 [ -n "${KLP_TEST_PREFLIGHT:-}" ] || klp_preflight
 
-# klp-build compiles the kernel this way; klp diff needs per-symbol sections to
-# extract individual functions.
-FIXTURE_CFLAGS="-c -O2 -ffunction-sections -fdata-sections -fno-asynchronous-unwind-tables"
+# What every fixture is built with.  These describe the kernel a fixture stands
+# in for; -c is build_one's contract rather than a property of that kernel, so
+# it lives at the compile where an override cannot drop it.
+#
+#   -O2					the kernel's default
+#   -ffunction-sections -fdata-sections	klp-build passes these itself, through
+#					KCFLAGS, whatever the configuration
+#   -fno-asynchronous-unwind-tables	arch/x86/Makefile sets this always, so
+#					kernel objects carry no .eh_frame
+#   -fno-common				the kernel's Makefile sets it, so an
+#					uninitialised global there lands in
+#					.bss rather than being SHN_COMMON,
+#					which has no section and so no
+#					checksum
+#
+# A test overrides it; see tools/objtool/Documentation/klp-write-tests.txt.
+FIXTURE_CFLAGS="-O2 -ffunction-sections -fdata-sections -fno-common \
+		-fno-asynchronous-unwind-tables"
 
 test_name="$(basename "$0" .sh)"
 workdir=
 
+# The pair run_diff() and the checksum helpers work on.  build_pair() names
+# them again and make_vmlinux_pair() repoints orig_obj at the image it links,
+# but a test which builds its objects itself with build_one() sets neither, so
+# the default belongs here.
+orig_obj=orig.o
+patched_obj=patched.o
+
 pass() { echo "ok - $test_name${1:+: $1}"; exit 0; }
 fail() { echo "not ok - $test_name: $1"; exit 1; }
 
@@ -217,17 +239,78 @@ clang_only()
 	declared_skip "clang only${1:+: $1}"
 }
 
+# build_one <fixture.c> <output object> [cflags...]
+build_one()
+{
+	local fixture out
+	fixture="$FIXTURES_DIR/$1"
+	out="$workdir/$2"
+	shift 2
+
+	[ -f "$fixture" ] || fail "missing fixture $fixture"
+
+	# run_checksum only runs once per workdir.  A fresh object has no
+	# checksums in it, so anything built now needs that to happen again.
+	rm -f "$workdir/.checksummed"
+
+	$CC -c $FIXTURE_CFLAGS "$@" -o "$out" "$fixture" 2>"$workdir/cc.log" ||
+		fail "$(basename "$fixture") does not build: $(tail -1 "$workdir/cc.log")"
+}
+
 # build_pair <fixture.c> [cflags...]
 build_pair()
 {
-	local fixture="$FIXTURES_DIR/$1"; shift
+	local fixture="$1"; shift
 
-	[ -f "$fixture" ] || fail "missing fixture $fixture"
+	# Name what this builds.  A test may run several segments, and
+	# make_vmlinux_pair() repoints orig_obj at the image it links, so
+	# without this the next run_diff() would still be reading that.
+	orig_obj=orig.o
+	patched_obj=patched.o
+
+	build_one "$fixture" orig.o "$@"
+	build_one "$fixture" patched.o "$@" -DPATCHED
+}
 
-	$CC $FIXTURE_CFLAGS "$@" -o "$workdir/orig.o" "$fixture" 2>"$workdir/cc.log" ||
-		probe_skip "fixture does not build here: $(tail -1 "$workdir/cc.log")"
-	$CC $FIXTURE_CFLAGS "$@" -DPATCHED -o "$workdir/patched.o" "$fixture" 2>"$workdir/cc.log" ||
-		probe_skip "fixture does not build here: $(tail -1 "$workdir/cc.log")"
+# run_objtool_check <objtool arguments...>
+#
+# Run objtool's ordinary check pass over the pair, as the kernel build does.
+#
+# Some of what klp diff consumes is produced by this pass rather than by the
+# compiler: .static_call_sites, .mcount_loc, .ibt_endbr_seal, ORC.
+#
+# Only module objects see it before klp-build -- with CONFIG_KLP_BUILD the
+# per-object pass is deferred, so built-in objects reach klp diff exactly as
+# the compiler left them.
+run_objtool_check()
+{
+	local obj
+
+	# This rewrites both objects, so checksums taken before it describe
+	# something that no longer exists.  As in build_one(), drop the marker
+	# so run_checksum() takes them again.
+	rm -f "$workdir/.checksummed"
+
+	for obj in "$orig_obj" "$patched_obj"; do
+		"$OBJTOOL" "$@" "$workdir/$obj" ||
+			fail "objtool $* failed on $obj"
+	done
+}
+
+run_checksum()
+{
+	# Checksums live in the objects, and a test may ask for them more than
+	# once -- diffing the same pair again with a different Module.symvers,
+	# say.  objtool does the right thing when asked twice, leaving the
+	# object alone, but it says so, and that warning would be most of what
+	# a passing run prints.  Remember instead, and keep quiet.
+	[ -e "$workdir/.checksummed" ] && return 0
+
+	"$OBJTOOL" klp checksum "$workdir/$orig_obj" ||
+		fail "klp checksum $orig_obj failed"
+	"$OBJTOOL" klp checksum "$workdir/$patched_obj" ||
+		fail "klp checksum $patched_obj failed"
+	touch "$workdir/.checksummed"
 }
 
 # run_diff [expected exit status]
@@ -235,18 +318,10 @@ run_diff()
 {
 	local expect="${1:-0}" rc=0
 
-	# Checksums live in the objects, so only generate them once even when a
-	# test diffs the same pair again with a different Module.symvers.
-	if [ ! -e "$workdir/.checksummed" ]; then
-		"$OBJTOOL" klp checksum "$workdir/orig.o" ||
-			fail "klp checksum orig.o failed"
-		"$OBJTOOL" klp checksum "$workdir/patched.o" ||
-			fail "klp checksum patched.o failed"
-		touch "$workdir/.checksummed"
-	fi
+	run_checksum
 
 	# klp diff looks for Module.symvers relative to the working directory.
-	( cd "$workdir" && "$OBJTOOL" klp diff orig.o patched.o out.o ) \
+	( cd "$workdir" && "$OBJTOOL" klp diff "$orig_obj" "$patched_obj" out.o ) \
 		> "$workdir/diff.log" 2>&1 || rc=$?
 
 	[ "$rc" = "$expect" ] ||
@@ -267,10 +342,102 @@ partial_link()
 {
 	local out="$1"; shift
 
+	rm -f "$workdir/.checksummed"
+
 	$CC -r -nostdlib -o "$out" "$@" 2>/dev/null ||
 		$CC -r -nostdlib -fuse-ld=lld -o "$out" "$@" 2>/dev/null
 }
 
+# link_vmlinux <output> <object...>
+#
+# Link objects into an executable, the way the kernel's final link produces
+# vmlinux from vmlinux.o.  Entry point 0 and no libc: nothing runs it, it only
+# has to be a linked image with resolved addresses.
+#
+# The sub-sections have to come out in name order rather than object order,
+# the way the kernel's linker script gathers .text.unlikely and .data.. apart
+# from the rest.  That reordering is the entire reason .klp.symid exists: a
+# link which preserves order cannot tell a correct sympos from one that merely
+# counted, and the caller checks the two orders really did diverge.
+#
+# A linker script rather than --sort-section=name, because lld accepts that
+# option and ignores it -- so on a host where only lld can link the target, the
+# test would quietly stop testing the thing it is named for.
+#
+# Three attempts because a cross run has neither $LD nor the compiler's default
+# linker able to touch the target: on an arm64 host linking x86 objects, only
+# lld will do it.
+link_vmlinux()
+{
+	local out="$1" lds="$workdir/sort.lds"; shift
+
+	echo 'SECTIONS { .data : { *(SORT_BY_NAME(.data.*)) } }' > "$lds"
+
+	$LD -e 0 -T "$lds" -o "$out" "$@" 2>/dev/null ||
+		$CC -nostdlib -Wl,-e,0 -Wl,-T,"$lds" \
+			-o "$out" "$@" 2>/dev/null ||
+		$CC -nostdlib -fuse-ld=lld -Wl,-e,0 -Wl,-T,"$lds" \
+			-o "$out" "$@" 2>/dev/null
+}
+
+# make_vmlinux_pair <orig object...> -- <patched object...>
+#
+# Build the vmlinux.o / vmlinux pair klp diff needs to resolve sympos the way
+# it does for built-in code, and point the diff at it.
+#
+# For a module, sympos is a count in symbol table order, which klp diff can do
+# from the object alone.  vmlinux is different: the final link reorders
+# sub-sections, so the position comes from the linked image, bridged by
+# .klp.symid.  klp diff only looks for that when the object it was handed is
+# called vmlinux.o and a vmlinux sits beside it -- so both the name and the
+# linked image matter.
+make_vmlinux_pair()
+{
+	local orig=() patched=() seen= arg
+
+	for arg in "$@"; do
+		if [ "$arg" = -- ]; then seen=y; continue; fi
+		if [ -n "$seen" ]; then patched+=( "$arg" ); else orig+=( "$arg" ); fi
+	done
+
+	# Both sides have to have been named.  Without this, forgetting the --
+	# leaves one list empty, the link of nothing fails, and the test skips
+	# saying the toolchain cannot link -- which is a test bug wearing the
+	# costume of an environment one.
+	[ "${#orig[@]}" -gt 0 ] && [ "${#patched[@]}" -gt 0 ] ||
+		fail "make_vmlinux_pair needs objects either side of --"
+
+	partial_link "$workdir/vmlinux.o" "${orig[@]}" ||
+		probe_skip "partial link unavailable"
+	partial_link "$workdir/patched.o" "${patched[@]}" ||
+		probe_skip "partial link unavailable"
+
+	"$OBJTOOL" --klp-symids --link "$workdir/vmlinux.o" ||
+		fail "objtool --klp-symids failed"
+
+	link_vmlinux "$workdir/vmlinux" "$workdir/vmlinux.o" ||
+		probe_skip "cannot link a vmlinux here"
+
+	orig_obj=vmlinux.o
+}
+
+# build_module_pair <fixture.c> <module name> [cflags...]
+#
+# Build the pair as objects belonging to a module rather than to vmlinux.  klp
+# diff reads the object's module name from .modinfo, and that decides which
+# object a relocation is attributed to and whether a reference counts as
+# cross-module, so a good deal of the code has a module path the vmlinux
+# fixtures never reach.
+#
+# The fixture defines its .modinfo name from MODNAME.  Passing that through
+# -D needs two levels of quoting, which is easy to get wrong at the call site.
+build_module_pair()
+{
+	local fixture="$1" modname="$2"; shift 2
+
+	build_pair "$fixture" -DMODNAME="\"$modname\"" "$@"
+}
+
 # find_thinlto_toolchain
 #
 # Set $THIN_LD to an lld from the same LLVM release as $CC (or THIN_CC).  A
merge bot Applied
#15 lore raw

[tip: objtool/core] objtool/klp: Build klp test fixtures through the harness

In reply to Song Liu
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:     ae04b6d0f9bf308d1e80cd8d7fb0f917ae52c2ef
Gitweb:        https://git.kernel.org/tip/ae04b6d0f9bf308d1e80cd8d7fb0f917ae52c2ef
Author:        Song Liu <[email protected]>
AuthorDate:    Wed, 16 Sep 2026 11:42:58 -07:00
Committer:     Ingo Molnar <[email protected]>
CommitterDate: Mon, 21 Sep 2026 11:00:49 +02:00

objtool/klp: Build klp test fixtures through the harness

Compiling a fixture is the one thing every test does, and it has more invariants than it looks.

- The flags describe the kernel a fixture stands in for, and each is written down with its reason. That substitution is the whole mechanism by which these tests cover configurations without building a kernel -- objtool reads no .config, so a configuration reaches it only as compiler flags and the bytes they produce -- and a flag with no stated motive is indistinguishable from a mistake.

- -c is not one of them. Producing an object rather than a program is the helper's contract, not something a test may reconsider, so it lives at the compile and an override cannot drop it.

- A fixture which will not compile is a failure, not a skip. It is far more often a mistake in the fixture than a compiler which cannot express the construct, and the two are indistinguishable once reported as a skip.

- A newly produced object has no checksums in it, so producing one invalidates the record that checksumming has already been done. Left to itself that invariant ends up in each test which rebuilds.

build_one handles a single object for the tests which need more than two or different names; build_pair and build_module_pair are expressed in terms of it, so none of the above can be lost by going around them.

run_checksum comes out of run_diff for the same reason: a test which wants checksums without a diff should not have to run one.

---
 tools/objtool/tests/lib.sh | 205 ++++++++++++++++++++++++++++++++----
 1 file changed, 186 insertions(+), 19 deletions(-)
tools/objtool/tests/lib.sh +186 -19
index 1531caa..a4513ae 100644
@@ -131,13 +131,35 @@ EOF
 
 [ -n "${KLP_TEST_PREFLIGHT:-}" ] || klp_preflight
 
-# klp-build compiles the kernel this way; klp diff needs per-symbol sections to
-# extract individual functions.
-FIXTURE_CFLAGS="-c -O2 -ffunction-sections -fdata-sections -fno-asynchronous-unwind-tables"
+# What every fixture is built with.  These describe the kernel a fixture stands
+# in for; -c is build_one's contract rather than a property of that kernel, so
+# it lives at the compile where an override cannot drop it.
+#
+#   -O2					the kernel's default
+#   -ffunction-sections -fdata-sections	klp-build passes these itself, through
+#					KCFLAGS, whatever the configuration
+#   -fno-asynchronous-unwind-tables	arch/x86/Makefile sets this always, so
+#					kernel objects carry no .eh_frame
+#   -fno-common				the kernel's Makefile sets it, so an
+#					uninitialised global there lands in
+#					.bss rather than being SHN_COMMON,
+#					which has no section and so no
+#					checksum
+#
+# A test overrides it; see tools/objtool/Documentation/klp-write-tests.txt.
+FIXTURE_CFLAGS="-O2 -ffunction-sections -fdata-sections -fno-common \
+		-fno-asynchronous-unwind-tables"
 
 test_name="$(basename "$0" .sh)"
 workdir=
 
+# The pair run_diff() and the checksum helpers work on.  build_pair() names
+# them again and make_vmlinux_pair() repoints orig_obj at the image it links,
+# but a test which builds its objects itself with build_one() sets neither, so
+# the default belongs here.
+orig_obj=orig.o
+patched_obj=patched.o
+
 pass() { echo "ok - $test_name${1:+: $1}"; exit 0; }
 fail() { echo "not ok - $test_name: $1"; exit 1; }
 
@@ -217,17 +239,78 @@ clang_only()
 	declared_skip "clang only${1:+: $1}"
 }
 
+# build_one <fixture.c> <output object> [cflags...]
+build_one()
+{
+	local fixture out
+	fixture="$FIXTURES_DIR/$1"
+	out="$workdir/$2"
+	shift 2
+
+	[ -f "$fixture" ] || fail "missing fixture $fixture"
+
+	# run_checksum only runs once per workdir.  A fresh object has no
+	# checksums in it, so anything built now needs that to happen again.
+	rm -f "$workdir/.checksummed"
+
+	$CC -c $FIXTURE_CFLAGS "$@" -o "$out" "$fixture" 2>"$workdir/cc.log" ||
+		fail "$(basename "$fixture") does not build: $(tail -1 "$workdir/cc.log")"
+}
+
 # build_pair <fixture.c> [cflags...]
 build_pair()
 {
-	local fixture="$FIXTURES_DIR/$1"; shift
+	local fixture="$1"; shift
 
-	[ -f "$fixture" ] || fail "missing fixture $fixture"
+	# Name what this builds.  A test may run several segments, and
+	# make_vmlinux_pair() repoints orig_obj at the image it links, so
+	# without this the next run_diff() would still be reading that.
+	orig_obj=orig.o
+	patched_obj=patched.o
+
+	build_one "$fixture" orig.o "$@"
+	build_one "$fixture" patched.o "$@" -DPATCHED
+}
 
-	$CC $FIXTURE_CFLAGS "$@" -o "$workdir/orig.o" "$fixture" 2>"$workdir/cc.log" ||
-		probe_skip "fixture does not build here: $(tail -1 "$workdir/cc.log")"
-	$CC $FIXTURE_CFLAGS "$@" -DPATCHED -o "$workdir/patched.o" "$fixture" 2>"$workdir/cc.log" ||
-		probe_skip "fixture does not build here: $(tail -1 "$workdir/cc.log")"
+# run_objtool_check <objtool arguments...>
+#
+# Run objtool's ordinary check pass over the pair, as the kernel build does.
+#
+# Some of what klp diff consumes is produced by this pass rather than by the
+# compiler: .static_call_sites, .mcount_loc, .ibt_endbr_seal, ORC.
+#
+# Only module objects see it before klp-build -- with CONFIG_KLP_BUILD the
+# per-object pass is deferred, so built-in objects reach klp diff exactly as
+# the compiler left them.
+run_objtool_check()
+{
+	local obj
+
+	# This rewrites both objects, so checksums taken before it describe
+	# something that no longer exists.  As in build_one(), drop the marker
+	# so run_checksum() takes them again.
+	rm -f "$workdir/.checksummed"
+
+	for obj in "$orig_obj" "$patched_obj"; do
+		"$OBJTOOL" "$@" "$workdir/$obj" ||
+			fail "objtool $* failed on $obj"
+	done
+}
+
+run_checksum()
+{
+	# Checksums live in the objects, and a test may ask for them more than
+	# once -- diffing the same pair again with a different Module.symvers,
+	# say.  objtool does the right thing when asked twice, leaving the
+	# object alone, but it says so, and that warning would be most of what
+	# a passing run prints.  Remember instead, and keep quiet.
+	[ -e "$workdir/.checksummed" ] && return 0
+
+	"$OBJTOOL" klp checksum "$workdir/$orig_obj" ||
+		fail "klp checksum $orig_obj failed"
+	"$OBJTOOL" klp checksum "$workdir/$patched_obj" ||
+		fail "klp checksum $patched_obj failed"
+	touch "$workdir/.checksummed"
 }
 
 # run_diff [expected exit status]
@@ -235,18 +318,10 @@ run_diff()
 {
 	local expect="${1:-0}" rc=0
 
-	# Checksums live in the objects, so only generate them once even when a
-	# test diffs the same pair again with a different Module.symvers.
-	if [ ! -e "$workdir/.checksummed" ]; then
-		"$OBJTOOL" klp checksum "$workdir/orig.o" ||
-			fail "klp checksum orig.o failed"
-		"$OBJTOOL" klp checksum "$workdir/patched.o" ||
-			fail "klp checksum patched.o failed"
-		touch "$workdir/.checksummed"
-	fi
+	run_checksum
 
 	# klp diff looks for Module.symvers relative to the working directory.
-	( cd "$workdir" && "$OBJTOOL" klp diff orig.o patched.o out.o ) \
+	( cd "$workdir" && "$OBJTOOL" klp diff "$orig_obj" "$patched_obj" out.o ) \
 		> "$workdir/diff.log" 2>&1 || rc=$?
 
 	[ "$rc" = "$expect" ] ||
@@ -267,10 +342,102 @@ partial_link()
 {
 	local out="$1"; shift
 
+	rm -f "$workdir/.checksummed"
+
 	$CC -r -nostdlib -o "$out" "$@" 2>/dev/null ||
 		$CC -r -nostdlib -fuse-ld=lld -o "$out" "$@" 2>/dev/null
 }
 
+# link_vmlinux <output> <object...>
+#
+# Link objects into an executable, the way the kernel's final link produces
+# vmlinux from vmlinux.o.  Entry point 0 and no libc: nothing runs it, it only
+# has to be a linked image with resolved addresses.
+#
+# The sub-sections have to come out in name order rather than object order,
+# the way the kernel's linker script gathers .text.unlikely and .data.. apart
+# from the rest.  That reordering is the entire reason .klp.symid exists: a
+# link which preserves order cannot tell a correct sympos from one that merely
+# counted, and the caller checks the two orders really did diverge.
+#
+# A linker script rather than --sort-section=name, because lld accepts that
+# option and ignores it -- so on a host where only lld can link the target, the
+# test would quietly stop testing the thing it is named for.
+#
+# Three attempts because a cross run has neither $LD nor the compiler's default
+# linker able to touch the target: on an arm64 host linking x86 objects, only
+# lld will do it.
+link_vmlinux()
+{
+	local out="$1" lds="$workdir/sort.lds"; shift
+
+	echo 'SECTIONS { .data : { *(SORT_BY_NAME(.data.*)) } }' > "$lds"
+
+	$LD -e 0 -T "$lds" -o "$out" "$@" 2>/dev/null ||
+		$CC -nostdlib -Wl,-e,0 -Wl,-T,"$lds" \
+			-o "$out" "$@" 2>/dev/null ||
+		$CC -nostdlib -fuse-ld=lld -Wl,-e,0 -Wl,-T,"$lds" \
+			-o "$out" "$@" 2>/dev/null
+}
+
+# make_vmlinux_pair <orig object...> -- <patched object...>
+#
+# Build the vmlinux.o / vmlinux pair klp diff needs to resolve sympos the way
+# it does for built-in code, and point the diff at it.
+#
+# For a module, sympos is a count in symbol table order, which klp diff can do
+# from the object alone.  vmlinux is different: the final link reorders
+# sub-sections, so the position comes from the linked image, bridged by
+# .klp.symid.  klp diff only looks for that when the object it was handed is
+# called vmlinux.o and a vmlinux sits beside it -- so both the name and the
+# linked image matter.
+make_vmlinux_pair()
+{
+	local orig=() patched=() seen= arg
+
+	for arg in "$@"; do
+		if [ "$arg" = -- ]; then seen=y; continue; fi
+		if [ -n "$seen" ]; then patched+=( "$arg" ); else orig+=( "$arg" ); fi
+	done
+
+	# Both sides have to have been named.  Without this, forgetting the --
+	# leaves one list empty, the link of nothing fails, and the test skips
+	# saying the toolchain cannot link -- which is a test bug wearing the
+	# costume of an environment one.
+	[ "${#orig[@]}" -gt 0 ] && [ "${#patched[@]}" -gt 0 ] ||
+		fail "make_vmlinux_pair needs objects either side of --"
+
+	partial_link "$workdir/vmlinux.o" "${orig[@]}" ||
+		probe_skip "partial link unavailable"
+	partial_link "$workdir/patched.o" "${patched[@]}" ||
+		probe_skip "partial link unavailable"
+
+	"$OBJTOOL" --klp-symids --link "$workdir/vmlinux.o" ||
+		fail "objtool --klp-symids failed"
+
+	link_vmlinux "$workdir/vmlinux" "$workdir/vmlinux.o" ||
+		probe_skip "cannot link a vmlinux here"
+
+	orig_obj=vmlinux.o
+}
+
+# build_module_pair <fixture.c> <module name> [cflags...]
+#
+# Build the pair as objects belonging to a module rather than to vmlinux.  klp
+# diff reads the object's module name from .modinfo, and that decides which
+# object a relocation is attributed to and whether a reference counts as
+# cross-module, so a good deal of the code has a module path the vmlinux
+# fixtures never reach.
+#
+# The fixture defines its .modinfo name from MODNAME.  Passing that through
+# -D needs two levels of quoting, which is easy to get wrong at the call site.
+build_module_pair()
+{
+	local fixture="$1" modname="$2"; shift 2
+
+	build_pair "$fixture" -DMODNAME="\"$modname\"" "$@"
+}
+
 # find_thinlto_toolchain
 #
 # Set $THIN_LD to an lld from the same LLVM release as $CC (or THIN_CC).  A
author maintainer
#16 lore raw

PATCH v5 6/58 objtool/klp: Grow the klp test harness vocabulary

In reply to Song Liu

Assertions for what klp diff produces, and for what went into it.

The output side covers the things a livepatch is made of: cloned sections and symbols, klp symbols and their sympos, tombstones, relocations by section and by count, the converted .klp.rela sections and their SHF_RELA_LIVEPATCH flag, SHN_LIVEPATCH symbols, recorded checksums, and klp diff's own diagnostics -- a rejection for the wrong reason is not a pass.

The input side matters just as much, and is easier to forget. A test which asserts only on the output passes when the compiler never emitted the construct under test, and reads as coverage it does not have. So there are two forms, and the difference between them is a statement about why the thing might be absent:

  require_*  the compiler cannot produce it here     -> skip
  assert_*   the fixture is supposed to produce it   -> fail

Names are quoted before they reach grep. Nearly every name here contains dots -- .text.target, .klp.rela.vmlinux -- and an unescaped dot matches any character, so an assertion for one section could be satisfied by a different one whose name merely lines up.

Assisted-by Claude:claude-opus-5
---
 tools/objtool/tests/lib.sh | 364 ++++++++++++++++++++++++++++++++++++-
 1 file changed, 360 insertions(+), 4 deletions(-)
tools/objtool/tests/lib.sh +360 -4
index a4513ae8dfce..817915e38a35 100644
@@ -216,9 +216,42 @@ setup()
 export_syms()
 {
 	: > "$workdir/Module.symvers"
+	add_exports vmlinux "$@"
+}
+
+# add_exports <object> [symbol...]
+#
+# Append exports owned by one object, without clearing what is already there,
+# so a test can describe a kernel where several objects export things.
+#
+# Which object owns a symbol is not cosmetic: a reference to a vmlinux symbol
+# is applied when the patch module loads, and a reference to a module's symbol
+# when that patched module loads, so klp diff files them in different sections.
+add_exports()
+{
+	local owner="$1"; shift
+
+	add_exports_ns "$owner" "" "$@"
+}
+
+# add_exports_ns <object> <namespace> [symbol...]
+#
+# Exports in a symbol namespace, the last field of a Module.symvers line.
+#
+# A "module:<names>" namespace is EXPORT_SYMBOL_FOR_MODULES(), where the module
+# loader grants access by matching the importing module's name against the
+# list.  A livepatch module is never on that list, so such a symbol has to be
+# referenced the way an unexported one is.  Ordinary namespaces are not
+# special here.
+add_exports_ns()
+{
+	local owner="$1" ns="$2"; shift 2
+
+	local sym
+
 	for sym in "$@"; do
-		printf '0x00000000\t%s\tvmlinux\tEXPORT_SYMBOL\t\n' \
-			"$sym" >> "$workdir/Module.symvers"
+		printf '0x00000000\t%s\t%s\tEXPORT_SYMBOL\t%s\n' \
+			"$sym" "$owner" "$ns" >> "$workdir/Module.symvers"
 	done
 }
 
@@ -481,12 +514,87 @@ out_relocs()   { $READELF -r -W "$workdir/out.o" 2>/dev/null; }
 out_symbols()  { $READELF -s -W "$workdir/out.o" 2>/dev/null; }
 diff_log()     { cat "$workdir/diff.log"; }
 
+# out_strings <section>
+#
+# The strings in one section of the output, for the names livepatch matches on.
+out_strings() { $READELF -p "$1" "$workdir/out.o" 2>/dev/null; }
+
+# Checks on the input objects, to run before klp diff.  The two forms differ in
+# what an absent construct means:
+#
+#   require_*  the compiler cannot produce it here	-> skip
+#   assert_*   the fixture is supposed to produce it	-> fail
+
+in_sections() { $READELF -S -W "$workdir/$1" 2>/dev/null; }
+in_symbols()  { $READELF -s -W "$workdir/$1" 2>/dev/null; }
+in_relocs()   { $READELF -r -W "$workdir/$1" 2>/dev/null; }
+
+# count_input_symbols <object> <name>
+#
+# How many object symbols of exactly that name the input has.  Deliberately not
+# a grep: readelf lists section symbols too, and a newer binutils prints their
+# name -- ".data.<name>" -- where an older one leaves the column blank.  A dot
+# is not a word character, so "grep -w <name>" counts that line as well, and
+# the same object gives a different answer depending on which readelf reads it.
+count_input_symbols()
+{
+	in_symbols "$1" | awk -v n="$2" '$4 == "OBJECT" && $8 == n' | wc -l
+}
+
+# re_quote <string>
+#
+# A string as a literal basic regular expression.  Nearly every name these
+# assertions match on contains a dot -- .text.target, .klp.rela.vmlinux -- and
+# an unescaped dot matches any character, so an assertion for one section can be
+# satisfied by a different one whose name merely lines up.
+re_quote() { printf '%s' "$1" | sed 's|[].[^$*\\/]|\\&|g'; }
+
+has_input_section() { in_sections "$1" | grep -q "[[:space:]]$(re_quote "$2")[[:space:]]"; }
+has_input_symbol()  { in_symbols "$1" | awk -v n="$2" '$NF == n' | grep -q .; }
+
+assert_input_section()
+{
+	local obj
+
+	for obj in "$orig_obj" "$patched_obj"; do
+		has_input_section "$obj" "$1" ||
+			fail "fixture produced no section '$1' in $obj"
+	done
+}
+
+assert_input_symbol()
+{
+	local obj
+
+	for obj in "$orig_obj" "$patched_obj"; do
+		has_input_symbol "$obj" "$1" ||
+			fail "fixture produced no symbol '$1' in $obj"
+	done
+}
+
+require_input_section()
+{
+	local obj
+
+	for obj in "$orig_obj" "$patched_obj"; do
+		has_input_section "$obj" "$1" ||
+			probe_skip "compiler produced no section '$1' here"
+	done
+}
+
 assert_section()
 {
-	out_sections | grep -q "[[:space:]]$1[[:space:]]" ||
+	out_sections | grep -q "[[:space:]]$(re_quote "$1")[[:space:]]" ||
 		fail "expected section '$1' in output"
 }
 
+assert_no_section()
+{
+	out_sections | grep -q "[[:space:]]$(re_quote "$1")[[:space:]]" &&
+		fail "unexpected section '$1' in output"
+	return 0
+}
+
 assert_patched()
 {
 	assert_section ".text.$1"
@@ -494,7 +602,255 @@ assert_patched()
 
 assert_not_patched()
 {
-	out_sections | grep -q "[[:space:]].text.$1[[:space:]]" &&
+	out_sections | grep -q "[[:space:]]$(re_quote ".text.$1")[[:space:]]" &&
 		fail "function '$1' should not have been cloned"
 	return 0
 }
+
+# section_relocs <section>
+#
+# The relocations against one section.  readelf prints every relocation section
+# in turn, so a test asking about ".smp_locks" has to cut its block out of the
+# listing first.
+section_relocs()
+{
+	local sec="${1//./\\.}"
+
+	out_relocs | awk "/rela$sec'/,/^\$/"
+}
+
+assert_reloc_sym()
+{
+	section_relocs "$1" | awk -v n="$2" '$5 == n' | grep -q . ||
+		fail "expected a relocation to '$2' in '$1'"
+}
+
+assert_no_reloc_sym()
+{
+	section_relocs "$1" | awk -v n="$2" '$5 == n' | grep -q . &&
+		fail "unexpected relocation to '$2' in '$1'"
+	return 0
+}
+
+# assert_reloc_count <section> <count>
+#
+# Counts relocation entries, not header or blank lines: whether a special
+# section entry was extracted once, twice or not at all is usually the whole
+# question.
+#
+# A count of zero is ambiguous on its own -- a section with no relocations and
+# no section at all both read as zero -- so require the section to exist.  A
+# test expecting nothing there wants assert_no_section.
+assert_reloc_count()
+{
+	local n
+
+	assert_section "$1"
+
+	n="$(section_relocs "$1" | grep -cE '^[0-9a-f]{8,}')"
+	[ "$n" = "$2" ] ||
+		fail "expected $2 relocations in '$1', found $n"
+}
+
+# assert_klp_sym <symbol> [object]
+#
+# A klp symbol is named .klp.sym.<object>.<symbol>,<sympos>.  The object
+# defaults to any, since most tests care that the reference was converted at
+# all rather than which object it resolved against.
+assert_klp_sym()
+{
+	out_symbols | grep -q "\.klp\.sym\.${2:-[^.]*}\.$(re_quote "$1")," ||
+		fail "expected klp symbol for '$1'"
+}
+
+# assert_klp_sympos <symbol> <sympos>
+#
+# The number after the comma in .klp.sym.<object>.<symbol>,<sympos> says which
+# of several same-named symbols livepatch should resolve to, counting from 1;
+# 0 means the name is unique and no disambiguation is needed.  Resolving to the
+# wrong one is not a load failure, it is a patch quietly wired to the wrong
+# object.
+assert_klp_sympos()
+{
+	out_symbols | grep -qE "\.klp\.sym\.[^.]+\.$(re_quote "$1"),$2([[:space:]]|\$)" ||
+		fail "expected klp symbol for '$1' with sympos $2, found:$(
+			out_symbols | grep -o "\.klp\.sym\.[^.]*\.$(re_quote "$1"),[0-9]*" |
+			sort -u | tr '\n' ' ')"
+}
+
+assert_no_klp_sym()
+{
+	out_symbols | grep -q "\.klp\.sym\.${2:-[^.]*}\.$(re_quote "$1")," &&
+		fail "unexpected klp symbol for '$1'"
+	return 0
+}
+
+assert_tombstone()
+{
+	out_symbols | grep -qE "\.klp\.tombstone\.$(re_quote "$1")([[:space:]]|\$)" ||
+		fail "expected a tombstone for '$1'"
+}
+
+assert_symbol()
+{
+	out_symbols | awk -v n="$1" '$NF == n' | grep -q . ||
+		fail "expected symbol '$1' in output"
+}
+
+assert_no_symbol()
+{
+	out_symbols | awk -v n="$1" '$NF == n' | grep -q . &&
+		fail "unexpected symbol '$1' in output"
+	return 0
+}
+
+# assert_diff_log <regex>
+#
+# klp diff's combined output, for tests asserting on a diagnostic.  Error
+# messages are part of the interface when the whole point is that a construct
+# gets rejected, and a rejection for the wrong reason is not a pass.
+assert_diff_log()
+{
+	diff_log | grep -qE -- "$1" ||
+		fail "expected '$1' in klp diff output: $(tail -2 "$workdir/diff.log")"
+}
+
+# checksum_of <object> <symbol>
+#
+# The checksum "klp checksum" recorded for one symbol, as a hex string.
+#
+# .discard.sym_checksum is an array of { u64 addr; u64 checksum; }, where addr
+# is the target of a relocation naming the symbol.  Nothing in the section
+# itself says which symbol an entry belongs to, so the relocation is what
+# locates the entry; the checksum is the eight bytes after it.
+# Callers use this in a command substitution, where fail() would only exit the
+# subshell and the test would carry on with an empty checksum.  So this returns
+# non-zero and prints nothing, and the assertions below check for that.  For
+# the same reason it does not run run_checksum() itself: that one does call
+# fail(), and from in here the message would be captured as the checksum
+# rather than ending the test.  The caller runs it first.
+checksum_of()
+{
+	local obj="$workdir/$1" sym="$2" off
+
+	off="$($READELF -rW "$obj" 2>/dev/null |
+	       awk -v s="$sym" '/rela\.discard\.sym_checksum/,/^$/ {
+			if ($5 == s) { print $1; exit }
+	       }')"
+
+	[ -n "$off" ] || return 1
+
+	$OBJCOPY -O binary --only-section=.discard.sym_checksum \
+		"$obj" "$workdir/checksums.bin" 2>/dev/null || return 1
+
+	dd if="$workdir/checksums.bin" bs=1 skip=$((16#$off + 8)) count=8 \
+		status=none | od -An -tx1 | tr -d ' \n'
+}
+
+# assert_checksum_differs <symbol> / assert_checksum_matches <symbol>
+#
+# Compare what klp checksum recorded for a symbol in the original against the
+# patched object.  This is what decides whether klp diff treats a function as
+# changed, so a test asserting only that the right functions were cloned cannot
+# tell a correct checksum from one which happens to differ.
+checksum_pair()
+{
+	run_checksum
+
+	orig_checksum="$(checksum_of "$orig_obj" "$1")"
+	patched_checksum="$(checksum_of "$patched_obj" "$1")"
+
+	[ -n "$orig_checksum" ] ||
+		fail "no checksum recorded for '$1' in $orig_obj"
+	[ -n "$patched_checksum" ] ||
+		fail "no checksum recorded for '$1' in $patched_obj"
+}
+
+assert_checksum_differs()
+{
+	checksum_pair "$1"
+
+	[ "$orig_checksum" != "$patched_checksum" ] ||
+		fail "checksum for '$1' unchanged at $orig_checksum, expected it to differ"
+}
+
+assert_checksum_matches()
+{
+	checksum_pair "$1"
+
+	[ "$orig_checksum" = "$patched_checksum" ] ||
+		fail "checksum for '$1' changed from $orig_checksum to" \
+		     "$patched_checksum, expected no change"
+}
+
+# run_post_link [expected exit status]
+#
+# klp post-link runs last in a livepatch build, converting the intermediate
+# __klp_relocs.* sections into the .klp.rela.* form the kernel consumes.  It
+# needs nothing but an object containing those sections, which is what klp diff
+# produces, so it runs on out.o here rather than on a built module.  Rewrites
+# out.o in place, so the out_* helpers show the result afterwards.
+run_post_link()
+{
+	local expect="${1:-0}" rc=0
+
+	"$OBJTOOL" klp post-link "$workdir/out.o" \
+		> "$workdir/post-link.log" 2>&1 || rc=$?
+
+	[ "$rc" = "$expect" ] ||
+		fail "klp post-link exited $rc, expected $expect:" \
+		     "$(tail -2 "$workdir/post-link.log")"
+}
+
+# The flags readelf prints for a section, or nothing when it has none.  The
+# leading "[nn]" index is stripped first so the columns can be counted.
+section_flags()
+{
+	out_sections | sed 's/^ *\[[ 0-9]*\] *//' |
+		awk -v s="$1" '$1 == s && $7 ~ /^[A-Za-z]+$/ { print $7 }'
+}
+
+# assert_section_flag <section> <letter>
+#
+# SHF_RELA_LIVEPATCH is OS-specific, so readelf renders it as "o".  A klp rela
+# section which lost it is an ordinary rela section, which the linker may apply
+# and the livepatch code will not.
+assert_section_flag()
+{
+	local flags; flags="$(section_flags "$1")"
+
+	[ -n "$flags" ] ||
+		fail "section '$1' has no flags, expected '$2'"
+	case "$flags" in
+	*"$2"*)	;;
+	*)	fail "section '$1' has flags '$flags', expected '$2'" ;;
+	esac
+}
+
+# assert_klp_rela <object> <section>
+#
+# post-link names the converted sections .klp.rela.<object>.<section>, one per
+# base section.  Also checks SHF_RELA_LIVEPATCH, since the name alone is not
+# what makes the kernel process it.
+assert_klp_rela()
+{
+	local name=".klp.rela.$1.$2"
+
+	out_sections | grep -q "[[:space:]]$(re_quote "$name")[[:space:]]" ||
+		fail "expected section '$name' in output"
+
+	assert_section_flag "$name" o
+}
+
+# assert_livepatch_sym <symbol>
+#
+# Symbols a klp relocation resolves against live in SHN_LIVEPATCH, which
+# readelf prints as "OS [0xff20]" -- llvm-readelf without the space, so match
+# either.  The kernel resolves these itself at patch load; anything else is a
+# symbol the module loader will try, and fail, to resolve normally.
+assert_livepatch_sym()
+{
+	out_symbols | grep -E 'OS ?\[0xff20\]' |
+		grep -qE "\.klp\.sym\.[^.]+\.$(re_quote "$1")," ||
+		fail "expected a klp symbol for '$1' in SHN_LIVEPATCH"
+}
Signature · 1 line
2.53.0-Meta
merge bot Applied
#17 lore raw

[tip: objtool/core] objtool/klp: Grow the klp test harness vocabulary

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:     9e57c64b4a77f60d51f2f9740268103057ef9587
Gitweb:        https://git.kernel.org/tip/9e57c64b4a77f60d51f2f9740268103057ef9587
Author:        Song Liu <[email protected]>
AuthorDate:    Wed, 16 Sep 2026 11:42:59 -07:00
Committer:     Josh Poimboeuf <[email protected]>
CommitterDate: Wed, 16 Sep 2026 17:13:26 -07:00

objtool/klp: Grow the klp test harness vocabulary

Assertions for what klp diff produces, and for what went into it.

The output side covers the things a livepatch is made of: cloned sections and symbols, klp symbols and their sympos, tombstones, relocations by section and by count, the converted .klp.rela sections and their SHF_RELA_LIVEPATCH flag, SHN_LIVEPATCH symbols, recorded checksums, and klp diff's own diagnostics -- a rejection for the wrong reason is not a pass.

The input side matters just as much, and is easier to forget. A test which asserts only on the output passes when the compiler never emitted the construct under test, and reads as coverage it does not have. So there are two forms, and the difference between them is a statement about why the thing might be absent:

  require_*  the compiler cannot produce it here     -> skip
  assert_*   the fixture is supposed to produce it   -> fail

Names are quoted before they reach grep. Nearly every name here contains dots -- .text.target, .klp.rela.vmlinux -- and an unescaped dot matches any character, so an assertion for one section could be satisfied by a different one whose name merely lines up.

---
 tools/objtool/tests/lib.sh | 364 +++++++++++++++++++++++++++++++++++-
 1 file changed, 360 insertions(+), 4 deletions(-)
tools/objtool/tests/lib.sh +360 -4
index a4513ae..817915e 100644
@@ -216,9 +216,42 @@ setup()
 export_syms()
 {
 	: > "$workdir/Module.symvers"
+	add_exports vmlinux "$@"
+}
+
+# add_exports <object> [symbol...]
+#
+# Append exports owned by one object, without clearing what is already there,
+# so a test can describe a kernel where several objects export things.
+#
+# Which object owns a symbol is not cosmetic: a reference to a vmlinux symbol
+# is applied when the patch module loads, and a reference to a module's symbol
+# when that patched module loads, so klp diff files them in different sections.
+add_exports()
+{
+	local owner="$1"; shift
+
+	add_exports_ns "$owner" "" "$@"
+}
+
+# add_exports_ns <object> <namespace> [symbol...]
+#
+# Exports in a symbol namespace, the last field of a Module.symvers line.
+#
+# A "module:<names>" namespace is EXPORT_SYMBOL_FOR_MODULES(), where the module
+# loader grants access by matching the importing module's name against the
+# list.  A livepatch module is never on that list, so such a symbol has to be
+# referenced the way an unexported one is.  Ordinary namespaces are not
+# special here.
+add_exports_ns()
+{
+	local owner="$1" ns="$2"; shift 2
+
+	local sym
+
 	for sym in "$@"; do
-		printf '0x00000000\t%s\tvmlinux\tEXPORT_SYMBOL\t\n' \
-			"$sym" >> "$workdir/Module.symvers"
+		printf '0x00000000\t%s\t%s\tEXPORT_SYMBOL\t%s\n' \
+			"$sym" "$owner" "$ns" >> "$workdir/Module.symvers"
 	done
 }
 
@@ -481,12 +514,87 @@ out_relocs()   { $READELF -r -W "$workdir/out.o" 2>/dev/null; }
 out_symbols()  { $READELF -s -W "$workdir/out.o" 2>/dev/null; }
 diff_log()     { cat "$workdir/diff.log"; }
 
+# out_strings <section>
+#
+# The strings in one section of the output, for the names livepatch matches on.
+out_strings() { $READELF -p "$1" "$workdir/out.o" 2>/dev/null; }
+
+# Checks on the input objects, to run before klp diff.  The two forms differ in
+# what an absent construct means:
+#
+#   require_*  the compiler cannot produce it here	-> skip
+#   assert_*   the fixture is supposed to produce it	-> fail
+
+in_sections() { $READELF -S -W "$workdir/$1" 2>/dev/null; }
+in_symbols()  { $READELF -s -W "$workdir/$1" 2>/dev/null; }
+in_relocs()   { $READELF -r -W "$workdir/$1" 2>/dev/null; }
+
+# count_input_symbols <object> <name>
+#
+# How many object symbols of exactly that name the input has.  Deliberately not
+# a grep: readelf lists section symbols too, and a newer binutils prints their
+# name -- ".data.<name>" -- where an older one leaves the column blank.  A dot
+# is not a word character, so "grep -w <name>" counts that line as well, and
+# the same object gives a different answer depending on which readelf reads it.
+count_input_symbols()
+{
+	in_symbols "$1" | awk -v n="$2" '$4 == "OBJECT" && $8 == n' | wc -l
+}
+
+# re_quote <string>
+#
+# A string as a literal basic regular expression.  Nearly every name these
+# assertions match on contains a dot -- .text.target, .klp.rela.vmlinux -- and
+# an unescaped dot matches any character, so an assertion for one section can be
+# satisfied by a different one whose name merely lines up.
+re_quote() { printf '%s' "$1" | sed 's|[].[^$*\\/]|\\&|g'; }
+
+has_input_section() { in_sections "$1" | grep -q "[[:space:]]$(re_quote "$2")[[:space:]]"; }
+has_input_symbol()  { in_symbols "$1" | awk -v n="$2" '$NF == n' | grep -q .; }
+
+assert_input_section()
+{
+	local obj
+
+	for obj in "$orig_obj" "$patched_obj"; do
+		has_input_section "$obj" "$1" ||
+			fail "fixture produced no section '$1' in $obj"
+	done
+}
+
+assert_input_symbol()
+{
+	local obj
+
+	for obj in "$orig_obj" "$patched_obj"; do
+		has_input_symbol "$obj" "$1" ||
+			fail "fixture produced no symbol '$1' in $obj"
+	done
+}
+
+require_input_section()
+{
+	local obj
+
+	for obj in "$orig_obj" "$patched_obj"; do
+		has_input_section "$obj" "$1" ||
+			probe_skip "compiler produced no section '$1' here"
+	done
+}
+
 assert_section()
 {
-	out_sections | grep -q "[[:space:]]$1[[:space:]]" ||
+	out_sections | grep -q "[[:space:]]$(re_quote "$1")[[:space:]]" ||
 		fail "expected section '$1' in output"
 }
 
+assert_no_section()
+{
+	out_sections | grep -q "[[:space:]]$(re_quote "$1")[[:space:]]" &&
+		fail "unexpected section '$1' in output"
+	return 0
+}
+
 assert_patched()
 {
 	assert_section ".text.$1"
@@ -494,7 +602,255 @@ assert_patched()
 
 assert_not_patched()
 {
-	out_sections | grep -q "[[:space:]].text.$1[[:space:]]" &&
+	out_sections | grep -q "[[:space:]]$(re_quote ".text.$1")[[:space:]]" &&
 		fail "function '$1' should not have been cloned"
 	return 0
 }
+
+# section_relocs <section>
+#
+# The relocations against one section.  readelf prints every relocation section
+# in turn, so a test asking about ".smp_locks" has to cut its block out of the
+# listing first.
+section_relocs()
+{
+	local sec="${1//./\\.}"
+
+	out_relocs | awk "/rela$sec'/,/^\$/"
+}
+
+assert_reloc_sym()
+{
+	section_relocs "$1" | awk -v n="$2" '$5 == n' | grep -q . ||
+		fail "expected a relocation to '$2' in '$1'"
+}
+
+assert_no_reloc_sym()
+{
+	section_relocs "$1" | awk -v n="$2" '$5 == n' | grep -q . &&
+		fail "unexpected relocation to '$2' in '$1'"
+	return 0
+}
+
+# assert_reloc_count <section> <count>
+#
+# Counts relocation entries, not header or blank lines: whether a special
+# section entry was extracted once, twice or not at all is usually the whole
+# question.
+#
+# A count of zero is ambiguous on its own -- a section with no relocations and
+# no section at all both read as zero -- so require the section to exist.  A
+# test expecting nothing there wants assert_no_section.
+assert_reloc_count()
+{
+	local n
+
+	assert_section "$1"
+
+	n="$(section_relocs "$1" | grep -cE '^[0-9a-f]{8,}')"
+	[ "$n" = "$2" ] ||
+		fail "expected $2 relocations in '$1', found $n"
+}
+
+# assert_klp_sym <symbol> [object]
+#
+# A klp symbol is named .klp.sym.<object>.<symbol>,<sympos>.  The object
+# defaults to any, since most tests care that the reference was converted at
+# all rather than which object it resolved against.
+assert_klp_sym()
+{
+	out_symbols | grep -q "\.klp\.sym\.${2:-[^.]*}\.$(re_quote "$1")," ||
+		fail "expected klp symbol for '$1'"
+}
+
+# assert_klp_sympos <symbol> <sympos>
+#
+# The number after the comma in .klp.sym.<object>.<symbol>,<sympos> says which
+# of several same-named symbols livepatch should resolve to, counting from 1;
+# 0 means the name is unique and no disambiguation is needed.  Resolving to the
+# wrong one is not a load failure, it is a patch quietly wired to the wrong
+# object.
+assert_klp_sympos()
+{
+	out_symbols | grep -qE "\.klp\.sym\.[^.]+\.$(re_quote "$1"),$2([[:space:]]|\$)" ||
+		fail "expected klp symbol for '$1' with sympos $2, found:$(
+			out_symbols | grep -o "\.klp\.sym\.[^.]*\.$(re_quote "$1"),[0-9]*" |
+			sort -u | tr '\n' ' ')"
+}
+
+assert_no_klp_sym()
+{
+	out_symbols | grep -q "\.klp\.sym\.${2:-[^.]*}\.$(re_quote "$1")," &&
+		fail "unexpected klp symbol for '$1'"
+	return 0
+}
+
+assert_tombstone()
+{
+	out_symbols | grep -qE "\.klp\.tombstone\.$(re_quote "$1")([[:space:]]|\$)" ||
+		fail "expected a tombstone for '$1'"
+}
+
+assert_symbol()
+{
+	out_symbols | awk -v n="$1" '$NF == n' | grep -q . ||
+		fail "expected symbol '$1' in output"
+}
+
+assert_no_symbol()
+{
+	out_symbols | awk -v n="$1" '$NF == n' | grep -q . &&
+		fail "unexpected symbol '$1' in output"
+	return 0
+}
+
+# assert_diff_log <regex>
+#
+# klp diff's combined output, for tests asserting on a diagnostic.  Error
+# messages are part of the interface when the whole point is that a construct
+# gets rejected, and a rejection for the wrong reason is not a pass.
+assert_diff_log()
+{
+	diff_log | grep -qE -- "$1" ||
+		fail "expected '$1' in klp diff output: $(tail -2 "$workdir/diff.log")"
+}
+
+# checksum_of <object> <symbol>
+#
+# The checksum "klp checksum" recorded for one symbol, as a hex string.
+#
+# .discard.sym_checksum is an array of { u64 addr; u64 checksum; }, where addr
+# is the target of a relocation naming the symbol.  Nothing in the section
+# itself says which symbol an entry belongs to, so the relocation is what
+# locates the entry; the checksum is the eight bytes after it.
+# Callers use this in a command substitution, where fail() would only exit the
+# subshell and the test would carry on with an empty checksum.  So this returns
+# non-zero and prints nothing, and the assertions below check for that.  For
+# the same reason it does not run run_checksum() itself: that one does call
+# fail(), and from in here the message would be captured as the checksum
+# rather than ending the test.  The caller runs it first.
+checksum_of()
+{
+	local obj="$workdir/$1" sym="$2" off
+
+	off="$($READELF -rW "$obj" 2>/dev/null |
+	       awk -v s="$sym" '/rela\.discard\.sym_checksum/,/^$/ {
+			if ($5 == s) { print $1; exit }
+	       }')"
+
+	[ -n "$off" ] || return 1
+
+	$OBJCOPY -O binary --only-section=.discard.sym_checksum \
+		"$obj" "$workdir/checksums.bin" 2>/dev/null || return 1
+
+	dd if="$workdir/checksums.bin" bs=1 skip=$((16#$off + 8)) count=8 \
+		status=none | od -An -tx1 | tr -d ' \n'
+}
+
+# assert_checksum_differs <symbol> / assert_checksum_matches <symbol>
+#
+# Compare what klp checksum recorded for a symbol in the original against the
+# patched object.  This is what decides whether klp diff treats a function as
+# changed, so a test asserting only that the right functions were cloned cannot
+# tell a correct checksum from one which happens to differ.
+checksum_pair()
+{
+	run_checksum
+
+	orig_checksum="$(checksum_of "$orig_obj" "$1")"
+	patched_checksum="$(checksum_of "$patched_obj" "$1")"
+
+	[ -n "$orig_checksum" ] ||
+		fail "no checksum recorded for '$1' in $orig_obj"
+	[ -n "$patched_checksum" ] ||
+		fail "no checksum recorded for '$1' in $patched_obj"
+}
+
+assert_checksum_differs()
+{
+	checksum_pair "$1"
+
+	[ "$orig_checksum" != "$patched_checksum" ] ||
+		fail "checksum for '$1' unchanged at $orig_checksum, expected it to differ"
+}
+
+assert_checksum_matches()
+{
+	checksum_pair "$1"
+
+	[ "$orig_checksum" = "$patched_checksum" ] ||
+		fail "checksum for '$1' changed from $orig_checksum to" \
+		     "$patched_checksum, expected no change"
+}
+
+# run_post_link [expected exit status]
+#
+# klp post-link runs last in a livepatch build, converting the intermediate
+# __klp_relocs.* sections into the .klp.rela.* form the kernel consumes.  It
+# needs nothing but an object containing those sections, which is what klp diff
+# produces, so it runs on out.o here rather than on a built module.  Rewrites
+# out.o in place, so the out_* helpers show the result afterwards.
+run_post_link()
+{
+	local expect="${1:-0}" rc=0
+
+	"$OBJTOOL" klp post-link "$workdir/out.o" \
+		> "$workdir/post-link.log" 2>&1 || rc=$?
+
+	[ "$rc" = "$expect" ] ||
+		fail "klp post-link exited $rc, expected $expect:" \
+		     "$(tail -2 "$workdir/post-link.log")"
+}
+
+# The flags readelf prints for a section, or nothing when it has none.  The
+# leading "[nn]" index is stripped first so the columns can be counted.
+section_flags()
+{
+	out_sections | sed 's/^ *\[[ 0-9]*\] *//' |
+		awk -v s="$1" '$1 == s && $7 ~ /^[A-Za-z]+$/ { print $7 }'
+}
+
+# assert_section_flag <section> <letter>
+#
+# SHF_RELA_LIVEPATCH is OS-specific, so readelf renders it as "o".  A klp rela
+# section which lost it is an ordinary rela section, which the linker may apply
+# and the livepatch code will not.
+assert_section_flag()
+{
+	local flags; flags="$(section_flags "$1")"
+
+	[ -n "$flags" ] ||
+		fail "section '$1' has no flags, expected '$2'"
+	case "$flags" in
+	*"$2"*)	;;
+	*)	fail "section '$1' has flags '$flags', expected '$2'" ;;
+	esac
+}
+
+# assert_klp_rela <object> <section>
+#
+# post-link names the converted sections .klp.rela.<object>.<section>, one per
+# base section.  Also checks SHF_RELA_LIVEPATCH, since the name alone is not
+# what makes the kernel process it.
+assert_klp_rela()
+{
+	local name=".klp.rela.$1.$2"
+
+	out_sections | grep -q "[[:space:]]$(re_quote "$name")[[:space:]]" ||
+		fail "expected section '$name' in output"
+
+	assert_section_flag "$name" o
+}
+
+# assert_livepatch_sym <symbol>
+#
+# Symbols a klp relocation resolves against live in SHN_LIVEPATCH, which
+# readelf prints as "OS [0xff20]" -- llvm-readelf without the space, so match
+# either.  The kernel resolves these itself at patch load; anything else is a
+# symbol the module loader will try, and fail, to resolve normally.
+assert_livepatch_sym()
+{
+	out_symbols | grep -E 'OS ?\[0xff20\]' |
+		grep -qE "\.klp\.sym\.[^.]+\.$(re_quote "$1")," ||
+		fail "expected a klp symbol for '$1' in SHN_LIVEPATCH"
+}
merge bot Applied
#18 lore raw

[tip: objtool/core] objtool/klp: Grow the klp test harness vocabulary

In reply to Song Liu
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:     2ab0faeb71936be1f53a8222cd5d0a1bcada5b82
Gitweb:        https://git.kernel.org/tip/2ab0faeb71936be1f53a8222cd5d0a1bcada5b82
Author:        Song Liu <[email protected]>
AuthorDate:    Wed, 16 Sep 2026 11:42:59 -07:00
Committer:     Ingo Molnar <[email protected]>
CommitterDate: Mon, 21 Sep 2026 11:01:01 +02:00

objtool/klp: Grow the klp test harness vocabulary

Assertions for what klp diff produces, and for what went into it.

The output side covers the things a livepatch is made of: cloned sections and symbols, klp symbols and their sympos, tombstones, relocations by section and by count, the converted .klp.rela sections and their SHF_RELA_LIVEPATCH flag, SHN_LIVEPATCH symbols, recorded checksums, and klp diff's own diagnostics -- a rejection for the wrong reason is not a pass.

The input side matters just as much, and is easier to forget. A test which asserts only on the output passes when the compiler never emitted the construct under test, and reads as coverage it does not have. So there are two forms, and the difference between them is a statement about why the thing might be absent:

  require_*  the compiler cannot produce it here     -> skip
  assert_*   the fixture is supposed to produce it   -> fail

Names are quoted before they reach grep. Nearly every name here contains dots -- .text.target, .klp.rela.vmlinux -- and an unescaped dot matches any character, so an assertion for one section could be satisfied by a different one whose name merely lines up.

---
 tools/objtool/tests/lib.sh | 364 +++++++++++++++++++++++++++++++++++-
 1 file changed, 360 insertions(+), 4 deletions(-)
tools/objtool/tests/lib.sh +360 -4
index a4513ae..817915e 100644
@@ -216,9 +216,42 @@ setup()
 export_syms()
 {
 	: > "$workdir/Module.symvers"
+	add_exports vmlinux "$@"
+}
+
+# add_exports <object> [symbol...]
+#
+# Append exports owned by one object, without clearing what is already there,
+# so a test can describe a kernel where several objects export things.
+#
+# Which object owns a symbol is not cosmetic: a reference to a vmlinux symbol
+# is applied when the patch module loads, and a reference to a module's symbol
+# when that patched module loads, so klp diff files them in different sections.
+add_exports()
+{
+	local owner="$1"; shift
+
+	add_exports_ns "$owner" "" "$@"
+}
+
+# add_exports_ns <object> <namespace> [symbol...]
+#
+# Exports in a symbol namespace, the last field of a Module.symvers line.
+#
+# A "module:<names>" namespace is EXPORT_SYMBOL_FOR_MODULES(), where the module
+# loader grants access by matching the importing module's name against the
+# list.  A livepatch module is never on that list, so such a symbol has to be
+# referenced the way an unexported one is.  Ordinary namespaces are not
+# special here.
+add_exports_ns()
+{
+	local owner="$1" ns="$2"; shift 2
+
+	local sym
+
 	for sym in "$@"; do
-		printf '0x00000000\t%s\tvmlinux\tEXPORT_SYMBOL\t\n' \
-			"$sym" >> "$workdir/Module.symvers"
+		printf '0x00000000\t%s\t%s\tEXPORT_SYMBOL\t%s\n' \
+			"$sym" "$owner" "$ns" >> "$workdir/Module.symvers"
 	done
 }
 
@@ -481,12 +514,87 @@ out_relocs()   { $READELF -r -W "$workdir/out.o" 2>/dev/null; }
 out_symbols()  { $READELF -s -W "$workdir/out.o" 2>/dev/null; }
 diff_log()     { cat "$workdir/diff.log"; }
 
+# out_strings <section>
+#
+# The strings in one section of the output, for the names livepatch matches on.
+out_strings() { $READELF -p "$1" "$workdir/out.o" 2>/dev/null; }
+
+# Checks on the input objects, to run before klp diff.  The two forms differ in
+# what an absent construct means:
+#
+#   require_*  the compiler cannot produce it here	-> skip
+#   assert_*   the fixture is supposed to produce it	-> fail
+
+in_sections() { $READELF -S -W "$workdir/$1" 2>/dev/null; }
+in_symbols()  { $READELF -s -W "$workdir/$1" 2>/dev/null; }
+in_relocs()   { $READELF -r -W "$workdir/$1" 2>/dev/null; }
+
+# count_input_symbols <object> <name>
+#
+# How many object symbols of exactly that name the input has.  Deliberately not
+# a grep: readelf lists section symbols too, and a newer binutils prints their
+# name -- ".data.<name>" -- where an older one leaves the column blank.  A dot
+# is not a word character, so "grep -w <name>" counts that line as well, and
+# the same object gives a different answer depending on which readelf reads it.
+count_input_symbols()
+{
+	in_symbols "$1" | awk -v n="$2" '$4 == "OBJECT" && $8 == n' | wc -l
+}
+
+# re_quote <string>
+#
+# A string as a literal basic regular expression.  Nearly every name these
+# assertions match on contains a dot -- .text.target, .klp.rela.vmlinux -- and
+# an unescaped dot matches any character, so an assertion for one section can be
+# satisfied by a different one whose name merely lines up.
+re_quote() { printf '%s' "$1" | sed 's|[].[^$*\\/]|\\&|g'; }
+
+has_input_section() { in_sections "$1" | grep -q "[[:space:]]$(re_quote "$2")[[:space:]]"; }
+has_input_symbol()  { in_symbols "$1" | awk -v n="$2" '$NF == n' | grep -q .; }
+
+assert_input_section()
+{
+	local obj
+
+	for obj in "$orig_obj" "$patched_obj"; do
+		has_input_section "$obj" "$1" ||
+			fail "fixture produced no section '$1' in $obj"
+	done
+}
+
+assert_input_symbol()
+{
+	local obj
+
+	for obj in "$orig_obj" "$patched_obj"; do
+		has_input_symbol "$obj" "$1" ||
+			fail "fixture produced no symbol '$1' in $obj"
+	done
+}
+
+require_input_section()
+{
+	local obj
+
+	for obj in "$orig_obj" "$patched_obj"; do
+		has_input_section "$obj" "$1" ||
+			probe_skip "compiler produced no section '$1' here"
+	done
+}
+
 assert_section()
 {
-	out_sections | grep -q "[[:space:]]$1[[:space:]]" ||
+	out_sections | grep -q "[[:space:]]$(re_quote "$1")[[:space:]]" ||
 		fail "expected section '$1' in output"
 }
 
+assert_no_section()
+{
+	out_sections | grep -q "[[:space:]]$(re_quote "$1")[[:space:]]" &&
+		fail "unexpected section '$1' in output"
+	return 0
+}
+
 assert_patched()
 {
 	assert_section ".text.$1"
@@ -494,7 +602,255 @@ assert_patched()
 
 assert_not_patched()
 {
-	out_sections | grep -q "[[:space:]].text.$1[[:space:]]" &&
+	out_sections | grep -q "[[:space:]]$(re_quote ".text.$1")[[:space:]]" &&
 		fail "function '$1' should not have been cloned"
 	return 0
 }
+
+# section_relocs <section>
+#
+# The relocations against one section.  readelf prints every relocation section
+# in turn, so a test asking about ".smp_locks" has to cut its block out of the
+# listing first.
+section_relocs()
+{
+	local sec="${1//./\\.}"
+
+	out_relocs | awk "/rela$sec'/,/^\$/"
+}
+
+assert_reloc_sym()
+{
+	section_relocs "$1" | awk -v n="$2" '$5 == n' | grep -q . ||
+		fail "expected a relocation to '$2' in '$1'"
+}
+
+assert_no_reloc_sym()
+{
+	section_relocs "$1" | awk -v n="$2" '$5 == n' | grep -q . &&
+		fail "unexpected relocation to '$2' in '$1'"
+	return 0
+}
+
+# assert_reloc_count <section> <count>
+#
+# Counts relocation entries, not header or blank lines: whether a special
+# section entry was extracted once, twice or not at all is usually the whole
+# question.
+#
+# A count of zero is ambiguous on its own -- a section with no relocations and
+# no section at all both read as zero -- so require the section to exist.  A
+# test expecting nothing there wants assert_no_section.
+assert_reloc_count()
+{
+	local n
+
+	assert_section "$1"
+
+	n="$(section_relocs "$1" | grep -cE '^[0-9a-f]{8,}')"
+	[ "$n" = "$2" ] ||
+		fail "expected $2 relocations in '$1', found $n"
+}
+
+# assert_klp_sym <symbol> [object]
+#
+# A klp symbol is named .klp.sym.<object>.<symbol>,<sympos>.  The object
+# defaults to any, since most tests care that the reference was converted at
+# all rather than which object it resolved against.
+assert_klp_sym()
+{
+	out_symbols | grep -q "\.klp\.sym\.${2:-[^.]*}\.$(re_quote "$1")," ||
+		fail "expected klp symbol for '$1'"
+}
+
+# assert_klp_sympos <symbol> <sympos>
+#
+# The number after the comma in .klp.sym.<object>.<symbol>,<sympos> says which
+# of several same-named symbols livepatch should resolve to, counting from 1;
+# 0 means the name is unique and no disambiguation is needed.  Resolving to the
+# wrong one is not a load failure, it is a patch quietly wired to the wrong
+# object.
+assert_klp_sympos()
+{
+	out_symbols | grep -qE "\.klp\.sym\.[^.]+\.$(re_quote "$1"),$2([[:space:]]|\$)" ||
+		fail "expected klp symbol for '$1' with sympos $2, found:$(
+			out_symbols | grep -o "\.klp\.sym\.[^.]*\.$(re_quote "$1"),[0-9]*" |
+			sort -u | tr '\n' ' ')"
+}
+
+assert_no_klp_sym()
+{
+	out_symbols | grep -q "\.klp\.sym\.${2:-[^.]*}\.$(re_quote "$1")," &&
+		fail "unexpected klp symbol for '$1'"
+	return 0
+}
+
+assert_tombstone()
+{
+	out_symbols | grep -qE "\.klp\.tombstone\.$(re_quote "$1")([[:space:]]|\$)" ||
+		fail "expected a tombstone for '$1'"
+}
+
+assert_symbol()
+{
+	out_symbols | awk -v n="$1" '$NF == n' | grep -q . ||
+		fail "expected symbol '$1' in output"
+}
+
+assert_no_symbol()
+{
+	out_symbols | awk -v n="$1" '$NF == n' | grep -q . &&
+		fail "unexpected symbol '$1' in output"
+	return 0
+}
+
+# assert_diff_log <regex>
+#
+# klp diff's combined output, for tests asserting on a diagnostic.  Error
+# messages are part of the interface when the whole point is that a construct
+# gets rejected, and a rejection for the wrong reason is not a pass.
+assert_diff_log()
+{
+	diff_log | grep -qE -- "$1" ||
+		fail "expected '$1' in klp diff output: $(tail -2 "$workdir/diff.log")"
+}
+
+# checksum_of <object> <symbol>
+#
+# The checksum "klp checksum" recorded for one symbol, as a hex string.
+#
+# .discard.sym_checksum is an array of { u64 addr; u64 checksum; }, where addr
+# is the target of a relocation naming the symbol.  Nothing in the section
+# itself says which symbol an entry belongs to, so the relocation is what
+# locates the entry; the checksum is the eight bytes after it.
+# Callers use this in a command substitution, where fail() would only exit the
+# subshell and the test would carry on with an empty checksum.  So this returns
+# non-zero and prints nothing, and the assertions below check for that.  For
+# the same reason it does not run run_checksum() itself: that one does call
+# fail(), and from in here the message would be captured as the checksum
+# rather than ending the test.  The caller runs it first.
+checksum_of()
+{
+	local obj="$workdir/$1" sym="$2" off
+
+	off="$($READELF -rW "$obj" 2>/dev/null |
+	       awk -v s="$sym" '/rela\.discard\.sym_checksum/,/^$/ {
+			if ($5 == s) { print $1; exit }
+	       }')"
+
+	[ -n "$off" ] || return 1
+
+	$OBJCOPY -O binary --only-section=.discard.sym_checksum \
+		"$obj" "$workdir/checksums.bin" 2>/dev/null || return 1
+
+	dd if="$workdir/checksums.bin" bs=1 skip=$((16#$off + 8)) count=8 \
+		status=none | od -An -tx1 | tr -d ' \n'
+}
+
+# assert_checksum_differs <symbol> / assert_checksum_matches <symbol>
+#
+# Compare what klp checksum recorded for a symbol in the original against the
+# patched object.  This is what decides whether klp diff treats a function as
+# changed, so a test asserting only that the right functions were cloned cannot
+# tell a correct checksum from one which happens to differ.
+checksum_pair()
+{
+	run_checksum
+
+	orig_checksum="$(checksum_of "$orig_obj" "$1")"
+	patched_checksum="$(checksum_of "$patched_obj" "$1")"
+
+	[ -n "$orig_checksum" ] ||
+		fail "no checksum recorded for '$1' in $orig_obj"
+	[ -n "$patched_checksum" ] ||
+		fail "no checksum recorded for '$1' in $patched_obj"
+}
+
+assert_checksum_differs()
+{
+	checksum_pair "$1"
+
+	[ "$orig_checksum" != "$patched_checksum" ] ||
+		fail "checksum for '$1' unchanged at $orig_checksum, expected it to differ"
+}
+
+assert_checksum_matches()
+{
+	checksum_pair "$1"
+
+	[ "$orig_checksum" = "$patched_checksum" ] ||
+		fail "checksum for '$1' changed from $orig_checksum to" \
+		     "$patched_checksum, expected no change"
+}
+
+# run_post_link [expected exit status]
+#
+# klp post-link runs last in a livepatch build, converting the intermediate
+# __klp_relocs.* sections into the .klp.rela.* form the kernel consumes.  It
+# needs nothing but an object containing those sections, which is what klp diff
+# produces, so it runs on out.o here rather than on a built module.  Rewrites
+# out.o in place, so the out_* helpers show the result afterwards.
+run_post_link()
+{
+	local expect="${1:-0}" rc=0
+
+	"$OBJTOOL" klp post-link "$workdir/out.o" \
+		> "$workdir/post-link.log" 2>&1 || rc=$?
+
+	[ "$rc" = "$expect" ] ||
+		fail "klp post-link exited $rc, expected $expect:" \
+		     "$(tail -2 "$workdir/post-link.log")"
+}
+
+# The flags readelf prints for a section, or nothing when it has none.  The
+# leading "[nn]" index is stripped first so the columns can be counted.
+section_flags()
+{
+	out_sections | sed 's/^ *\[[ 0-9]*\] *//' |
+		awk -v s="$1" '$1 == s && $7 ~ /^[A-Za-z]+$/ { print $7 }'
+}
+
+# assert_section_flag <section> <letter>
+#
+# SHF_RELA_LIVEPATCH is OS-specific, so readelf renders it as "o".  A klp rela
+# section which lost it is an ordinary rela section, which the linker may apply
+# and the livepatch code will not.
+assert_section_flag()
+{
+	local flags; flags="$(section_flags "$1")"
+
+	[ -n "$flags" ] ||
+		fail "section '$1' has no flags, expected '$2'"
+	case "$flags" in
+	*"$2"*)	;;
+	*)	fail "section '$1' has flags '$flags', expected '$2'" ;;
+	esac
+}
+
+# assert_klp_rela <object> <section>
+#
+# post-link names the converted sections .klp.rela.<object>.<section>, one per
+# base section.  Also checks SHF_RELA_LIVEPATCH, since the name alone is not
+# what makes the kernel process it.
+assert_klp_rela()
+{
+	local name=".klp.rela.$1.$2"
+
+	out_sections | grep -q "[[:space:]]$(re_quote "$name")[[:space:]]" ||
+		fail "expected section '$name' in output"
+
+	assert_section_flag "$name" o
+}
+
+# assert_livepatch_sym <symbol>
+#
+# Symbols a klp relocation resolves against live in SHN_LIVEPATCH, which
+# readelf prints as "OS [0xff20]" -- llvm-readelf without the space, so match
+# either.  The kernel resolves these itself at patch load; anything else is a
+# symbol the module loader will try, and fail, to resolve normally.
+assert_livepatch_sym()
+{
+	out_symbols | grep -E 'OS ?\[0xff20\]' |
+		grep -qE "\.klp\.sym\.[^.]+\.$(re_quote "$1")," ||
+		fail "expected a klp symbol for '$1' in SHN_LIVEPATCH"
+}
author maintainer
#19 lore raw

PATCH v5 7/58 objtool/klp: Give each run one working directory, one per test inside it

In reply to Song Liu

Each test made its own mktemp directory, so a run scattered them through /tmp among everything else using the same names, and there was no way to inspect what a failing test built -- the objects are gone the moment it exits, which is right every time but the one that matters.

Give the run one directory and each test a subdirectory of it, named for the test and nested the way the source is:

/tmp/klp-tests.3zC6oyfd/

    generic/test-basic/{orig.o,patched.o,out.o,Module.symvers,...}
    x86/test-kcfi/...

--keep then reports one path instead of forty, and removing it is one command. A test run by hand still falls back to a temp directory of its own, and still says where that went.

Detecting a leak comes free. Cleanup is now "remove each test's directory, then rmdir the run's", and the rmdir fails if anything is left -- so a test which dies without running its own cleanup is reported rather than quietly leaving something behind.

preflight names the directory the tests build under, since mktemp honours TMPDIR and a run in a container is otherwise silent about where its work went. The runner says what to do only when it is relevant: on a failure without --keep, that the option exists; with it, how many directories are waiting. Usage text is not read while something is broken.

Assisted-by Claude:claude-opus-5
---
 tools/objtool/tests/lib.sh       | 23 ++++++++++++++++++-----
 tools/objtool/tests/run-tests.sh | 26 ++++++++++++++++++++++++--
 2 files changed, 42 insertions(+), 7 deletions(-)
tools/objtool/tests/lib.sh +18 -5
index 817915e38a35..82e6b0d4c670 100644
@@ -126,6 +126,7 @@ klp_preflight()
 #   objtool   $OBJTOOL (klp: yes)
 #   compiler  $cc_version
 #   arch      $KLP_TEST_ARCH$([ "$arch" = "$host" ] || echo "  (host $host, cross)")
+#   tmpdir    ${TMPDIR:-/tmp}  (each test builds in a fresh directory here)
 EOF
 }
 
@@ -194,15 +195,27 @@ xpass()
 	exit 1
 }
 
-cleanup() { [ -n "$workdir" ] && rm -rf "$workdir"; }
+cleanup()
+{
+	[ -n "$workdir" ] || return 0
+
+	if [ -n "${KLP_TEST_KEEP:-}" ]; then
+		[ -n "${KLP_TEST_WORKDIR:-}" ] || echo "# kept $workdir"
+		return 0
+	fi
+
+	rm -rf "$workdir"
+}
 
 # setup [exported symbol...]
 setup()
 {
-	# The environment was checked once when this file was sourced, so there
-	# is nothing to verify here: objtool exists at the resolved path, has
-	# klp support, and $CC works.
-	workdir="$(mktemp -d)" || fail "mktemp failed"
+	if [ -n "${KLP_TEST_WORKDIR:-}" ]; then
+		workdir="$KLP_TEST_WORKDIR"
+		mkdir -p "$workdir" || fail "cannot create $workdir"
+	else
+		workdir="$(mktemp -d)" || fail "mktemp failed"
+	fi
 	trap cleanup EXIT
 
 	export_syms "$@"
tools/objtool/tests/run-tests.sh +24 -2
index 6b937fc7f5bd..e6f1ac1b5d0d 100755
@@ -23,13 +23,17 @@ export LC_ALL=C
 usage()
 {
 	cat <<EOF
-usage: $(basename "$0") [test...]
+usage: $(basename "$0") [-k|--keep] [test...]
 
 Run the objtool klp tests for this architecture: everything in generic/, plus
 everything in the directory named for it.  With no arguments, runs all of them.
 A test may be named with or without its "test-" prefix and ".sh" suffix, and is
 looked for in both directories.
 
+Options:
+    -k, --keep    do not delete each test's working directory; print its path,
+                  so the objects a failing test built can be looked at
+
 Environment:
     OBJTOOL       objtool binary to test (default ../objtool)
     CC            compiler used to build fixtures (default gcc)
@@ -45,6 +49,7 @@ cd "$(dirname "$0")" || exit 1
 while [ $# -gt 0 ]; do
 	case "$1" in
 	-h|--help)	usage ;;
+	-k|--keep)	export KLP_TEST_KEEP=1; shift ;;
 	--)		shift; break ;;
 	-*)		echo "unknown option: $1" >&2; usage 1 ;;
 	*)		break ;;
@@ -98,12 +103,18 @@ else
 	done
 fi
 
+# One directory for the whole run, one per test inside it, mirroring the
+# source layout.  A run then leaves a single thing behind instead of 39
+# scattered among everything else using mktemp.
+rundir="$(mktemp -d "${TMPDIR:-/tmp}/klp-tests.XXXXXXXX")" ||
+	{ echo "Bail out! cannot create a working directory" >&2; exit 1; }
+
 echo "1..${#tests[@]}"
 
 pass=0 fail=0 static_skip=0 probe_skip=0 xfail=0 xpass=0
 
 for t in "${tests[@]}"; do
-	out="$(./"$t" 2>&1)"
+	out="$(KLP_TEST_WORKDIR="$rundir/${t%.sh}" ./"$t" 2>&1)"
 	rc=$?
 
 	# A test prints one result line, but it is not necessarily the only
@@ -156,4 +167,15 @@ done
 echo "# pass:$pass fail:$fail static-skip:$static_skip" \
      "probe-skip:$probe_skip xfail:$xfail xpass:$xpass"
 
+# A failure is the one time the objects matter, and by default they are
+# already gone.  Say so then rather than in the usage text nobody reads while
+# something is broken.
+if [ -n "${KLP_TEST_KEEP:-}" ]; then
+	echo "# working directories kept in $rundir -- inspect, then rm -rf it"
+elif ! rmdir "$rundir"/*/ "$rundir" 2>/dev/null; then
+	echo "# $rundir was not empty; a test did not clean up after itself"
+elif [ "$fail" != 0 ] || [ "$xpass" != 0 ]; then
+	echo "# re-run with --keep to hold on to what a failing test built"
+fi
+
 [ "$fail" = 0 ] && [ "$xpass" = 0 ]
Signature · 1 line
2.53.0-Meta
merge bot Applied
#20 lore raw

[tip: objtool/core] objtool/klp: Give each run one working directory, one per test inside it

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:     00de45f4de3f39e191a7a81be2f38f7e325535ab
Gitweb:        https://git.kernel.org/tip/00de45f4de3f39e191a7a81be2f38f7e325535ab
Author:        Song Liu <[email protected]>
AuthorDate:    Wed, 16 Sep 2026 11:43:00 -07:00
Committer:     Josh Poimboeuf <[email protected]>
CommitterDate: Wed, 16 Sep 2026 17:13:26 -07:00

objtool/klp: Give each run one working directory, one per test inside it

Each test made its own mktemp directory, so a run scattered them through /tmp among everything else using the same names, and there was no way to inspect what a failing test built -- the objects are gone the moment it exits, which is right every time but the one that matters.

Give the run one directory and each test a subdirectory of it, named for the test and nested the way the source is:

/tmp/klp-tests.3zC6oyfd/

    generic/test-basic/{orig.o,patched.o,out.o,Module.symvers,...}
    x86/test-kcfi/...

--keep then reports one path instead of forty, and removing it is one command. A test run by hand still falls back to a temp directory of its own, and still says where that went.

Detecting a leak comes free. Cleanup is now "remove each test's directory, then rmdir the run's", and the rmdir fails if anything is left -- so a test which dies without running its own cleanup is reported rather than quietly leaving something behind.

preflight names the directory the tests build under, since mktemp honours TMPDIR and a run in a container is otherwise silent about where its work went. The runner says what to do only when it is relevant: on a failure without --keep, that the option exists; with it, how many directories are waiting. Usage text is not read while something is broken.

---
 tools/objtool/tests/lib.sh       | 23 ++++++++++++++++++-----
 tools/objtool/tests/run-tests.sh | 26 ++++++++++++++++++++++++--
 2 files changed, 42 insertions(+), 7 deletions(-)
tools/objtool/tests/lib.sh +18 -5
index 817915e..82e6b0d 100644
@@ -126,6 +126,7 @@ klp_preflight()
 #   objtool   $OBJTOOL (klp: yes)
 #   compiler  $cc_version
 #   arch      $KLP_TEST_ARCH$([ "$arch" = "$host" ] || echo "  (host $host, cross)")
+#   tmpdir    ${TMPDIR:-/tmp}  (each test builds in a fresh directory here)
 EOF
 }
 
@@ -194,15 +195,27 @@ xpass()
 	exit 1
 }
 
-cleanup() { [ -n "$workdir" ] && rm -rf "$workdir"; }
+cleanup()
+{
+	[ -n "$workdir" ] || return 0
+
+	if [ -n "${KLP_TEST_KEEP:-}" ]; then
+		[ -n "${KLP_TEST_WORKDIR:-}" ] || echo "# kept $workdir"
+		return 0
+	fi
+
+	rm -rf "$workdir"
+}
 
 # setup [exported symbol...]
 setup()
 {
-	# The environment was checked once when this file was sourced, so there
-	# is nothing to verify here: objtool exists at the resolved path, has
-	# klp support, and $CC works.
-	workdir="$(mktemp -d)" || fail "mktemp failed"
+	if [ -n "${KLP_TEST_WORKDIR:-}" ]; then
+		workdir="$KLP_TEST_WORKDIR"
+		mkdir -p "$workdir" || fail "cannot create $workdir"
+	else
+		workdir="$(mktemp -d)" || fail "mktemp failed"
+	fi
 	trap cleanup EXIT
 
 	export_syms "$@"
tools/objtool/tests/run-tests.sh +24 -2
index 6b937fc..e6f1ac1 100755
@@ -23,13 +23,17 @@ export LC_ALL=C
 usage()
 {
 	cat <<EOF
-usage: $(basename "$0") [test...]
+usage: $(basename "$0") [-k|--keep] [test...]
 
 Run the objtool klp tests for this architecture: everything in generic/, plus
 everything in the directory named for it.  With no arguments, runs all of them.
 A test may be named with or without its "test-" prefix and ".sh" suffix, and is
 looked for in both directories.
 
+Options:
+    -k, --keep    do not delete each test's working directory; print its path,
+                  so the objects a failing test built can be looked at
+
 Environment:
     OBJTOOL       objtool binary to test (default ../objtool)
     CC            compiler used to build fixtures (default gcc)
@@ -45,6 +49,7 @@ cd "$(dirname "$0")" || exit 1
 while [ $# -gt 0 ]; do
 	case "$1" in
 	-h|--help)	usage ;;
+	-k|--keep)	export KLP_TEST_KEEP=1; shift ;;
 	--)		shift; break ;;
 	-*)		echo "unknown option: $1" >&2; usage 1 ;;
 	*)		break ;;
@@ -98,12 +103,18 @@ else
 	done
 fi
 
+# One directory for the whole run, one per test inside it, mirroring the
+# source layout.  A run then leaves a single thing behind instead of 39
+# scattered among everything else using mktemp.
+rundir="$(mktemp -d "${TMPDIR:-/tmp}/klp-tests.XXXXXXXX")" ||
+	{ echo "Bail out! cannot create a working directory" >&2; exit 1; }
+
 echo "1..${#tests[@]}"
 
 pass=0 fail=0 static_skip=0 probe_skip=0 xfail=0 xpass=0
 
 for t in "${tests[@]}"; do
-	out="$(./"$t" 2>&1)"
+	out="$(KLP_TEST_WORKDIR="$rundir/${t%.sh}" ./"$t" 2>&1)"
 	rc=$?
 
 	# A test prints one result line, but it is not necessarily the only
@@ -156,4 +167,15 @@ done
 echo "# pass:$pass fail:$fail static-skip:$static_skip" \
      "probe-skip:$probe_skip xfail:$xfail xpass:$xpass"
 
+# A failure is the one time the objects matter, and by default they are
+# already gone.  Say so then rather than in the usage text nobody reads while
+# something is broken.
+if [ -n "${KLP_TEST_KEEP:-}" ]; then
+	echo "# working directories kept in $rundir -- inspect, then rm -rf it"
+elif ! rmdir "$rundir"/*/ "$rundir" 2>/dev/null; then
+	echo "# $rundir was not empty; a test did not clean up after itself"
+elif [ "$fail" != 0 ] || [ "$xpass" != 0 ]; then
+	echo "# re-run with --keep to hold on to what a failing test built"
+fi
+
 [ "$fail" = 0 ] && [ "$xpass" = 0 ]
merge bot Applied
#21 lore raw

[tip: objtool/core] objtool/klp: Give each run one working directory, one per test inside it

In reply to Song Liu
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:     8593055b7a4015761b3a4bbc3a64371bc42d1d12
Gitweb:        https://git.kernel.org/tip/8593055b7a4015761b3a4bbc3a64371bc42d1d12
Author:        Song Liu <[email protected]>
AuthorDate:    Wed, 16 Sep 2026 11:43:00 -07:00
Committer:     Ingo Molnar <[email protected]>
CommitterDate: Mon, 21 Sep 2026 11:01:10 +02:00

objtool/klp: Give each run one working directory, one per test inside it

Each test made its own mktemp directory, so a run scattered them through /tmp among everything else using the same names, and there was no way to inspect what a failing test built -- the objects are gone the moment it exits, which is right every time but the one that matters.

Give the run one directory and each test a subdirectory of it, named for the test and nested the way the source is:

/tmp/klp-tests.3zC6oyfd/

    generic/test-basic/{orig.o,patched.o,out.o,Module.symvers,...}
    x86/test-kcfi/...

--keep then reports one path instead of forty, and removing it is one command. A test run by hand still falls back to a temp directory of its own, and still says where that went.

Detecting a leak comes free. Cleanup is now "remove each test's directory, then rmdir the run's", and the rmdir fails if anything is left -- so a test which dies without running its own cleanup is reported rather than quietly leaving something behind.

preflight names the directory the tests build under, since mktemp honours TMPDIR and a run in a container is otherwise silent about where its work went. The runner says what to do only when it is relevant: on a failure without --keep, that the option exists; with it, how many directories are waiting. Usage text is not read while something is broken.

---
 tools/objtool/tests/lib.sh       | 23 ++++++++++++++++++-----
 tools/objtool/tests/run-tests.sh | 26 ++++++++++++++++++++++++--
 2 files changed, 42 insertions(+), 7 deletions(-)
tools/objtool/tests/lib.sh +18 -5
index 817915e..82e6b0d 100644
@@ -126,6 +126,7 @@ klp_preflight()
 #   objtool   $OBJTOOL (klp: yes)
 #   compiler  $cc_version
 #   arch      $KLP_TEST_ARCH$([ "$arch" = "$host" ] || echo "  (host $host, cross)")
+#   tmpdir    ${TMPDIR:-/tmp}  (each test builds in a fresh directory here)
 EOF
 }
 
@@ -194,15 +195,27 @@ xpass()
 	exit 1
 }
 
-cleanup() { [ -n "$workdir" ] && rm -rf "$workdir"; }
+cleanup()
+{
+	[ -n "$workdir" ] || return 0
+
+	if [ -n "${KLP_TEST_KEEP:-}" ]; then
+		[ -n "${KLP_TEST_WORKDIR:-}" ] || echo "# kept $workdir"
+		return 0
+	fi
+
+	rm -rf "$workdir"
+}
 
 # setup [exported symbol...]
 setup()
 {
-	# The environment was checked once when this file was sourced, so there
-	# is nothing to verify here: objtool exists at the resolved path, has
-	# klp support, and $CC works.
-	workdir="$(mktemp -d)" || fail "mktemp failed"
+	if [ -n "${KLP_TEST_WORKDIR:-}" ]; then
+		workdir="$KLP_TEST_WORKDIR"
+		mkdir -p "$workdir" || fail "cannot create $workdir"
+	else
+		workdir="$(mktemp -d)" || fail "mktemp failed"
+	fi
 	trap cleanup EXIT
 
 	export_syms "$@"
tools/objtool/tests/run-tests.sh +24 -2
index 6b937fc..e6f1ac1 100755
@@ -23,13 +23,17 @@ export LC_ALL=C
 usage()
 {
 	cat <<EOF
-usage: $(basename "$0") [test...]
+usage: $(basename "$0") [-k|--keep] [test...]
 
 Run the objtool klp tests for this architecture: everything in generic/, plus
 everything in the directory named for it.  With no arguments, runs all of them.
 A test may be named with or without its "test-" prefix and ".sh" suffix, and is
 looked for in both directories.
 
+Options:
+    -k, --keep    do not delete each test's working directory; print its path,
+                  so the objects a failing test built can be looked at
+
 Environment:
     OBJTOOL       objtool binary to test (default ../objtool)
     CC            compiler used to build fixtures (default gcc)
@@ -45,6 +49,7 @@ cd "$(dirname "$0")" || exit 1
 while [ $# -gt 0 ]; do
 	case "$1" in
 	-h|--help)	usage ;;
+	-k|--keep)	export KLP_TEST_KEEP=1; shift ;;
 	--)		shift; break ;;
 	-*)		echo "unknown option: $1" >&2; usage 1 ;;
 	*)		break ;;
@@ -98,12 +103,18 @@ else
 	done
 fi
 
+# One directory for the whole run, one per test inside it, mirroring the
+# source layout.  A run then leaves a single thing behind instead of 39
+# scattered among everything else using mktemp.
+rundir="$(mktemp -d "${TMPDIR:-/tmp}/klp-tests.XXXXXXXX")" ||
+	{ echo "Bail out! cannot create a working directory" >&2; exit 1; }
+
 echo "1..${#tests[@]}"
 
 pass=0 fail=0 static_skip=0 probe_skip=0 xfail=0 xpass=0
 
 for t in "${tests[@]}"; do
-	out="$(./"$t" 2>&1)"
+	out="$(KLP_TEST_WORKDIR="$rundir/${t%.sh}" ./"$t" 2>&1)"
 	rc=$?
 
 	# A test prints one result line, but it is not necessarily the only
@@ -156,4 +167,15 @@ done
 echo "# pass:$pass fail:$fail static-skip:$static_skip" \
      "probe-skip:$probe_skip xfail:$xfail xpass:$xpass"
 
+# A failure is the one time the objects matter, and by default they are
+# already gone.  Say so then rather than in the usage text nobody reads while
+# something is broken.
+if [ -n "${KLP_TEST_KEEP:-}" ]; then
+	echo "# working directories kept in $rundir -- inspect, then rm -rf it"
+elif ! rmdir "$rundir"/*/ "$rundir" 2>/dev/null; then
+	echo "# $rundir was not empty; a test did not clean up after itself"
+elif [ "$fail" != 0 ] || [ "$xpass" != 0 ]; then
+	echo "# re-run with --keep to hold on to what a failing test built"
+fi
+
 [ "$fail" = 0 ] && [ "$xpass" = 0 ]
author maintainer
#22 lore raw

PATCH v5 8/58 objtool/klp: Run the klp tests under set -u

In reply to Song Liu

Most of these assertions end in a grep, and an empty pattern matches anything. So a mistyped variable name in a test does not fail: it expands to nothing, the grep succeeds, and the test reports a pass having checked nothing. assert_section "$sectoin_nmae" becomes a search for two adjacent spaces, which readelf's column padding satisfies on every line.

Refuse unset variables. lib.sh guards the few genuinely optional expansions it has with ${x:-}.

Assisted-by Claude:claude-opus-5
---
 tools/objtool/tests/lib.sh | 2 ++
 1 file changed, 2 insertions(+)
tools/objtool/tests/lib.sh +2 -0
index 82e6b0d4c670..294b99ced357 100644
@@ -8,6 +8,8 @@
 # codegen varies between compilers and golden files would report churn instead
 # of regressions.
 
+set -u
+
 TESTS_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
 
 # Tests live in generic/ or in an architecture directory beside it, and each
Signature · 1 line
2.53.0-Meta
merge bot Applied
#23 lore raw

[tip: objtool/core] objtool/klp: Run the klp tests under set -u

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:     3c961933f3462eab9c7e34e5978de837cc86f59a
Gitweb:        https://git.kernel.org/tip/3c961933f3462eab9c7e34e5978de837cc86f59a
Author:        Song Liu <[email protected]>
AuthorDate:    Wed, 16 Sep 2026 11:43:01 -07:00
Committer:     Josh Poimboeuf <[email protected]>
CommitterDate: Wed, 16 Sep 2026 17:13:26 -07:00

objtool/klp: Run the klp tests under set -u

Most of these assertions end in a grep, and an empty pattern matches anything. So a mistyped variable name in a test does not fail: it expands to nothing, the grep succeeds, and the test reports a pass having checked nothing. assert_section "$sectoin_nmae" becomes a search for two adjacent spaces, which readelf's column padding satisfies on every line.

Refuse unset variables. lib.sh guards the few genuinely optional expansions it has with ${x:-}.

---
 tools/objtool/tests/lib.sh | 2 ++
 1 file changed, 2 insertions(+)
tools/objtool/tests/lib.sh +2 -0
index 82e6b0d..294b99c 100644
@@ -8,6 +8,8 @@
 # codegen varies between compilers and golden files would report churn instead
 # of regressions.
 
+set -u
+
 TESTS_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
 
 # Tests live in generic/ or in an architecture directory beside it, and each
merge bot Applied
#24 lore raw

[tip: objtool/core] objtool/klp: Run the klp tests under set -u

In reply to Song Liu
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:     48dafeead17e96ee5a63816580a0b92732ea32f6
Gitweb:        https://git.kernel.org/tip/48dafeead17e96ee5a63816580a0b92732ea32f6
Author:        Song Liu <[email protected]>
AuthorDate:    Wed, 16 Sep 2026 11:43:01 -07:00
Committer:     Ingo Molnar <[email protected]>
CommitterDate: Mon, 21 Sep 2026 11:01:22 +02:00

objtool/klp: Run the klp tests under set -u

Most of these assertions end in a grep, and an empty pattern matches anything. So a mistyped variable name in a test does not fail: it expands to nothing, the grep succeeds, and the test reports a pass having checked nothing. assert_section "$sectoin_nmae" becomes a search for two adjacent spaces, which readelf's column padding satisfies on every line.

Refuse unset variables. lib.sh guards the few genuinely optional expansions it has with ${x:-}.

---
 tools/objtool/tests/lib.sh | 2 ++
 1 file changed, 2 insertions(+)
tools/objtool/tests/lib.sh +2 -0
index 82e6b0d..294b99c 100644
@@ -8,6 +8,8 @@
 # codegen varies between compilers and golden files would report churn instead
 # of regressions.
 
+set -u
+
 TESTS_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
 
 # Tests live in generic/ or in an architecture directory beside it, and each
author maintainer
#25 lore raw

PATCH v5 9/58 objtool/klp: Document the klp test harness

In reply to Song Liu

Two documents, for two different readers.

klp-test-design.txt is for someone deciding whether to trust the suite or change it: what makes unit tests possible for a pipeline that normally needs two kernel builds (objtool has no configuration-dependent logic, so a test reproduces a configuration by reproducing its input), how tests are selected per architecture, and what the outcome classification is for.

klp-write-tests.txt is the procedure for adding one, and is written to be handed to someone -- or something -- with the instruction "follow this and write a test for commit <sha>", or "port the case at <location> from another harness". It leads with the rule that matters: a test is not finished until you have watched it fail with the code broken. Then the traps, each of which this suite has already fallen into -- a fixture the compiler optimised away, a named char[] which never reaches the string path because that keys on SHF_STRINGS, per-function sections hiding the movement a test was about.

Some of this was previously written as comments in lib.sh. That was the wrong place: guidance on how to write a test is read once by an author, while every comment in the harness is read by everyone who opens it. Explanations of why the code is as it is stay where they were.

Assisted-by Claude:claude-opus-5
---
 .../objtool/Documentation/klp-test-design.txt | 272 ++++++++++++++++++
 .../objtool/Documentation/klp-write-tests.txt | 266 +++++++++++++++++
 2 files changed, 538 insertions(+)
 create mode 100644 tools/objtool/Documentation/klp-test-design.txt
 create mode 100644 tools/objtool/Documentation/klp-write-tests.txt
tools/objtool/Documentation/klp-test-design.txt new file +272 -0
new file mode 100644
index 000000000000..ec56bfbc2c93
@@ -0,0 +1,272 @@
+.. SPDX-License-Identifier: GPL-2.0
+
+======================================
+Design of the objtool klp test harness
+======================================
+
+tools/objtool/tests/ holds unit tests for the klp subcommands of
+objtool -- ``klp checksum``, ``klp diff``, ``klp post-link`` and
+``--klp-symids`` -- which together turn two builds of the kernel into a
+livepatch module.
+
+This document explains how the harness is built and why.  For the rules to
+follow when adding a test, see klp-write-tests.txt.
+
+
+TL;DR
+=====
+
+One run covers one compiler and one architecture; CI runs the combinations.
+Build objtool first -- it needs libelf and libxxhash -- and the same ARCH is
+used for both steps.
+
+Natively, with gcc::
+
+    make -C tools/objtool
+    make -C tools/objtool tests
+
+Natively, with clang -- LLVM=1 additionally selects the LLVM binutils::
+
+    CC=clang make -C tools/objtool tests
+    LLVM=1 make -C tools/objtool tests
+
+Cross, with gcc -- an arm64 host running the x86 tests::
+
+    ARCH=x86_64 CROSS_COMPILE=x86_64-linux-gnu- make -C tools/objtool
+    ARCH=x86_64 CROSS_COMPILE=x86_64-linux-gnu- make -C tools/objtool tests
+
+Cross, with clang.  It defaults to the host triple however it is invoked, so
+--target= is what makes it emit x86; OBJCOPY is needed because BFD's is
+usually built for the host's target alone::
+
+    ARCH=x86_64 make -C tools/objtool
+    ARCH=x86_64 CC="clang --target=x86_64-linux-gnu" OBJCOPY=llvm-objcopy \
+            make -C tools/objtool tests
+
+A run ends with a totals line; anything other than fail:0 is a real result::
+
+    # pass:48 fail:0 static-skip:1 probe-skip:0 xfail:0 xpass:0
+
+Useful extras::
+
+    tools/objtool/tests/run-tests.sh basic          # one test, by name
+    tools/objtool/tests/run-tests.sh --keep basic   # and keep what it built
+
+
+Why unit tests are possible at all
+==================================
+
+klp-build is a pipeline: build the kernel twice, checksum both, diff them,
+link the result.  Testing that end to end means two kernel builds per case,
+which is too slow to run often and too heavy to keep in the tree.
+
+Three properties make a much cheaper test possible.
+
+**objtool has no configuration-dependent logic.**  It never reads ``.config``.
+Every ``CONFIG_`` string in its source is a comment or one error message, and
+its only build-time conditionals are driven by host libraries and the target
+architecture.  Configuration reaches objtool through exactly two channels: the
+``objtool-args-$(CONFIG_*)`` lines in scripts/Makefile.lib, and the
+contents of the object handed to it.
+
+**The klp subcommands use none of the first channel.**  Of objtool's options
+they consult three -- ``checksum``, ``debug_checksum``, ``dryrun`` -- all from
+their own command line.  So klp behaviour varies with configuration *only*
+through the input object.
+
+**Therefore a test can reproduce any configuration's behaviour by reproducing
+its input.**  Compile a small freestanding fixture with the flags that
+configuration would have used, and objtool cannot tell the difference.  No
+kernel, no ``.config``, no object cache.
+
+The whole suite runs in a few seconds.
+
+
+Shape of a test
+===============
+
+Each test compiles one fixture twice -- once plain, once with ``-DPATCHED`` --
+runs ``klp checksum`` over both, diffs them, and asserts on properties of the
+output object::
+
+    . "$(dirname "$0")/../lib.sh"
+
+    setup
+    build_pair basic.c
+
+    assert_input_symbol changed
+    run_diff
+
+    assert_patched changed
+    assert_not_patched untouched
+
+    pass "changed function cloned, unchanged function left alone"
+
+Assertions check properties, never recorded output.  Codegen varies between
+compilers and versions, so a golden file would report churn rather than
+regressions.
+
+
+Layout
+======
+
+::
+
+    tools/objtool/tests/
+        lib.sh              the harness: everything a test may call
+        run-tests.sh        selects, runs and classifies
+        generic/
+            test-*.sh
+            fixtures/*.c
+        x86/
+            test-*.sh
+            fixtures/*.c
+
+Which architecture a test is for is expressed by where it lives.  The runner
+executes ``generic/`` plus the directory matching this architecture, so a test
+which cannot apply is not run rather than running in order to report that it
+did not.  There is no ``x86_only`` helper, and no lookup letting an
+architecture fixture shadow a generic one: an architecture-specific test
+carries its own fixtures.
+
+Compilers cannot be expressed the same way, because CI varies ``CC`` over the
+same tree.  A compiler requirement stays a declaration inside the test
+(``gcc_only``, ``clang_only``).
+
+
+The environment is established once
+===================================
+
+Sourcing lib.sh runs ``klp_preflight``, which checks that objtool
+exists and has klp support, that ``$CC`` works, that the binutils are present,
+and which architecture this is.  The answers are exported, so:
+
+* ``run-tests.sh`` sources lib.sh too, and therefore knows the
+  architecture before it chooses which tests to run;
+* each test inherits the answers rather than repeating the work;
+* a test run on its own establishes them for itself.
+
+Preflight answers only whether the suite can run at all.  A suite which cannot
+run must not exit 0 looking like one which passed, so a missing objtool fails
+the whole run with a TAP ``Bail out!`` rather than skipping each test in turn.
+What a *particular* compiler can do is a different question, left to the test
+which cares.
+
+
+Outcomes
+========
+
+Output is TAP.  The distinction the harness cares most about is between kinds
+of skip, because a skip is how a suite quietly stops testing anything:
+
+``declared``
+    The test said in advance it does not apply -- ``gcc_only`` on a clang run.
+    Expected indefinitely.
+
+``probe``
+    The construct did not turn up in the built object this time.  Weaker: one
+    which becomes permanent is a fixture that has stopped testing anything.
+
+``undeclared``
+    Counted as a **failure**.  A test which gives up for a reason it never
+    declared is a hole, not an outcome.
+
+``xfail``/``xpass`` come with them, so a known failure is reported rather than
+commented out, and one which starts passing says so instead of going quietly
+green.
+
+The runner classifies the TAP result line, not everything a test printed:
+objtool warns on stderr and that output is captured, so a stray line ahead of
+the result would otherwise leave the exit status to decide -- and an expected
+failure exits 0.
+
+A run ends with a totals line::
+
+    # pass:48 fail:0 static-skip:1 probe-skip:0 xfail:0 xpass:0
+
+and reports what it left out::
+
+    # not run: 5 tests in x86/ (this run is arm64)
+
+
+Working directories
+===================
+
+A run gets one directory; each test gets a subdirectory of it, mirroring the
+source layout::
+
+    /tmp/klp-tests.XXXXXXXX/
+        generic/test-basic/{orig.o,patched.o,out.o,Module.symvers,...}
+        x86/test-kcfi/...
+
+``--keep`` leaves it and reports the one path.  Otherwise each test removes its
+own directory and the runner ``rmdir``s the run's -- which fails if anything
+was left behind, so a test which dies without cleaning up is reported rather
+than silently leaking.
+
+
+Running
+=======
+
+::
+
+    make -C tools/objtool                 # needs libelf and libxxhash
+    make -C tools/objtool tests
+
+    CC=clang make -C tools/objtool tests  # the other toolchain
+    LLVM=1 make -C tools/objtool tests    # and its binutils too
+
+    tools/objtool/tests/run-tests.sh --keep basic   # one test, keep its objects
+
+A run covers one compiler and one architecture; CI runs the combinations.
+
+Cross-compiled runs
+-------------------
+
+objtool klp is built only where ARCH_HAS_KLP is set, which today means x86 --
+so an arm64 machine cannot run any of this natively.  It can run all of it
+cross, because objtool is a host tool that only reads and rewrites ELF, and
+the tests only compile fixtures and inspect the objects.  Nothing has to
+execute target code.
+
+::
+
+    ARCH=x86_64 CROSS_COMPILE=x86_64-linux-gnu- make -C tools/objtool
+    ARCH=x86_64 CROSS_COMPILE=x86_64-linux-gnu- make -C tools/objtool tests
+
+objtool itself stays a native binary: it is built with HOSTCC, not CC, so
+setting a cross compiler cannot produce one the host is unable to run.  ARCH
+selects both the objtool target and the directory of tests to run.
+
+clang needs telling, since it defaults to the host triple however it is
+invoked.  The fixtures include no kernel headers, so no sysroot is needed:
+
+::
+
+    ARCH=x86_64 CC="clang --target=x86_64-linux-gnu" \
+            OBJCOPY=llvm-objcopy make -C tools/objtool tests
+
+CROSS_COMPILE picks the binutils, and each can be overridden on its own.
+readelf reads any target and rarely needs overriding; BFD's objcopy is usually
+built for the host's alone, hence OBJCOPY=llvm-objcopy above, or install
+binutils-multiarch.
+
+Either readelf will do.  The assertions read readelf's output, and the two
+spell some of it differently -- GNU prints "OS [0xff20]" for SHN_LIVEPATCH
+where llvm-readelf prints "OS[0xff20]" -- so they accept both.
+
+Getting this wrong is easy and the harness refuses rather than producing a
+misleading result.  "CC=clang ARCH=x86_64" alone selects the x86 tests and
+then builds arm64 objects; preflight compiles a probe object, hands it to
+objtool, and stops the run if they disagree about the architecture, or if
+ARCH does not match what the compiler emits.
+
+
+What this does not cover
+========================
+
+These are unit tests for objtool's klp subcommands.  They do not build a
+kernel, do not run scripts/livepatch/klp-build, and do not load a
+livepatch.  Behaviour which only appears when the kernel applies a patch --
+the module loader refusing a relocation, late module patching ordering -- has
+to be tested by booting, and is out of scope here.
tools/objtool/Documentation/klp-write-tests.txt new file +266 -0

266 lines not on this page · raw message

Signature · 1 line
2.53.0-Meta
merge bot Applied
#26 lore raw

[tip: objtool/core] objtool/klp: Document the klp test harness

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:     53d4c6819ada1d90863a05c613a09cb9641201d6
Gitweb:        https://git.kernel.org/tip/53d4c6819ada1d90863a05c613a09cb9641201d6
Author:        Song Liu <[email protected]>
AuthorDate:    Wed, 16 Sep 2026 11:43:02 -07:00
Committer:     Josh Poimboeuf <[email protected]>
CommitterDate: Wed, 16 Sep 2026 17:13:26 -07:00

objtool/klp: Document the klp test harness

Two documents, for two different readers.

klp-test-design.txt is for someone deciding whether to trust the suite or change it: what makes unit tests possible for a pipeline that normally needs two kernel builds (objtool has no configuration-dependent logic, so a test reproduces a configuration by reproducing its input), how tests are selected per architecture, and what the outcome classification is for.

klp-write-tests.txt is the procedure for adding one, and is written to be handed to someone -- or something -- with the instruction "follow this and write a test for commit <sha>", or "port the case at <location> from another harness". It leads with the rule that matters: a test is not finished until you have watched it fail with the code broken. Then the traps, each of which this suite has already fallen into -- a fixture the compiler optimised away, a named char[] which never reaches the string path because that keys on SHF_STRINGS, per-function sections hiding the movement a test was about.

Some of this was previously written as comments in lib.sh. That was the wrong place: guidance on how to write a test is read once by an author, while every comment in the harness is read by everyone who opens it. Explanations of why the code is as it is stay where they were.

---
 tools/objtool/Documentation/klp-test-design.txt | 272 +++++++++++++++-
 tools/objtool/Documentation/klp-write-tests.txt | 266 +++++++++++++++-
 2 files changed, 538 insertions(+)
 create mode 100644 tools/objtool/Documentation/klp-test-design.txt
 create mode 100644 tools/objtool/Documentation/klp-write-tests.txt
tools/objtool/Documentation/klp-test-design.txt new file +272 -0
new file mode 100644
index 0000000..ec56bfb
@@ -0,0 +1,272 @@
+.. SPDX-License-Identifier: GPL-2.0
+
+======================================
+Design of the objtool klp test harness
+======================================
+
+tools/objtool/tests/ holds unit tests for the klp subcommands of
+objtool -- ``klp checksum``, ``klp diff``, ``klp post-link`` and
+``--klp-symids`` -- which together turn two builds of the kernel into a
+livepatch module.
+
+This document explains how the harness is built and why.  For the rules to
+follow when adding a test, see klp-write-tests.txt.
+
+
+TL;DR
+=====
+
+One run covers one compiler and one architecture; CI runs the combinations.
+Build objtool first -- it needs libelf and libxxhash -- and the same ARCH is
+used for both steps.
+
+Natively, with gcc::
+
+    make -C tools/objtool
+    make -C tools/objtool tests
+
+Natively, with clang -- LLVM=1 additionally selects the LLVM binutils::
+
+    CC=clang make -C tools/objtool tests
+    LLVM=1 make -C tools/objtool tests
+
+Cross, with gcc -- an arm64 host running the x86 tests::
+
+    ARCH=x86_64 CROSS_COMPILE=x86_64-linux-gnu- make -C tools/objtool
+    ARCH=x86_64 CROSS_COMPILE=x86_64-linux-gnu- make -C tools/objtool tests
+
+Cross, with clang.  It defaults to the host triple however it is invoked, so
+--target= is what makes it emit x86; OBJCOPY is needed because BFD's is
+usually built for the host's target alone::
+
+    ARCH=x86_64 make -C tools/objtool
+    ARCH=x86_64 CC="clang --target=x86_64-linux-gnu" OBJCOPY=llvm-objcopy \
+            make -C tools/objtool tests
+
+A run ends with a totals line; anything other than fail:0 is a real result::
+
+    # pass:48 fail:0 static-skip:1 probe-skip:0 xfail:0 xpass:0
+
+Useful extras::
+
+    tools/objtool/tests/run-tests.sh basic          # one test, by name
+    tools/objtool/tests/run-tests.sh --keep basic   # and keep what it built
+
+
+Why unit tests are possible at all
+==================================
+
+klp-build is a pipeline: build the kernel twice, checksum both, diff them,
+link the result.  Testing that end to end means two kernel builds per case,
+which is too slow to run often and too heavy to keep in the tree.
+
+Three properties make a much cheaper test possible.
+
+**objtool has no configuration-dependent logic.**  It never reads ``.config``.
+Every ``CONFIG_`` string in its source is a comment or one error message, and
+its only build-time conditionals are driven by host libraries and the target
+architecture.  Configuration reaches objtool through exactly two channels: the
+``objtool-args-$(CONFIG_*)`` lines in scripts/Makefile.lib, and the
+contents of the object handed to it.
+
+**The klp subcommands use none of the first channel.**  Of objtool's options
+they consult three -- ``checksum``, ``debug_checksum``, ``dryrun`` -- all from
+their own command line.  So klp behaviour varies with configuration *only*
+through the input object.
+
+**Therefore a test can reproduce any configuration's behaviour by reproducing
+its input.**  Compile a small freestanding fixture with the flags that
+configuration would have used, and objtool cannot tell the difference.  No
+kernel, no ``.config``, no object cache.
+
+The whole suite runs in a few seconds.
+
+
+Shape of a test
+===============
+
+Each test compiles one fixture twice -- once plain, once with ``-DPATCHED`` --
+runs ``klp checksum`` over both, diffs them, and asserts on properties of the
+output object::
+
+    . "$(dirname "$0")/../lib.sh"
+
+    setup
+    build_pair basic.c
+
+    assert_input_symbol changed
+    run_diff
+
+    assert_patched changed
+    assert_not_patched untouched
+
+    pass "changed function cloned, unchanged function left alone"
+
+Assertions check properties, never recorded output.  Codegen varies between
+compilers and versions, so a golden file would report churn rather than
+regressions.
+
+
+Layout
+======
+
+::
+
+    tools/objtool/tests/
+        lib.sh              the harness: everything a test may call
+        run-tests.sh        selects, runs and classifies
+        generic/
+            test-*.sh
+            fixtures/*.c
+        x86/
+            test-*.sh
+            fixtures/*.c
+
+Which architecture a test is for is expressed by where it lives.  The runner
+executes ``generic/`` plus the directory matching this architecture, so a test
+which cannot apply is not run rather than running in order to report that it
+did not.  There is no ``x86_only`` helper, and no lookup letting an
+architecture fixture shadow a generic one: an architecture-specific test
+carries its own fixtures.
+
+Compilers cannot be expressed the same way, because CI varies ``CC`` over the
+same tree.  A compiler requirement stays a declaration inside the test
+(``gcc_only``, ``clang_only``).
+
+
+The environment is established once
+===================================
+
+Sourcing lib.sh runs ``klp_preflight``, which checks that objtool
+exists and has klp support, that ``$CC`` works, that the binutils are present,
+and which architecture this is.  The answers are exported, so:
+
+* ``run-tests.sh`` sources lib.sh too, and therefore knows the
+  architecture before it chooses which tests to run;
+* each test inherits the answers rather than repeating the work;
+* a test run on its own establishes them for itself.
+
+Preflight answers only whether the suite can run at all.  A suite which cannot
+run must not exit 0 looking like one which passed, so a missing objtool fails
+the whole run with a TAP ``Bail out!`` rather than skipping each test in turn.
+What a *particular* compiler can do is a different question, left to the test
+which cares.
+
+
+Outcomes
+========
+
+Output is TAP.  The distinction the harness cares most about is between kinds
+of skip, because a skip is how a suite quietly stops testing anything:
+
+``declared``
+    The test said in advance it does not apply -- ``gcc_only`` on a clang run.
+    Expected indefinitely.
+
+``probe``
+    The construct did not turn up in the built object this time.  Weaker: one
+    which becomes permanent is a fixture that has stopped testing anything.
+
+``undeclared``
+    Counted as a **failure**.  A test which gives up for a reason it never
+    declared is a hole, not an outcome.
+
+``xfail``/``xpass`` come with them, so a known failure is reported rather than
+commented out, and one which starts passing says so instead of going quietly
+green.
+
+The runner classifies the TAP result line, not everything a test printed:
+objtool warns on stderr and that output is captured, so a stray line ahead of
+the result would otherwise leave the exit status to decide -- and an expected
+failure exits 0.
+
+A run ends with a totals line::
+
+    # pass:48 fail:0 static-skip:1 probe-skip:0 xfail:0 xpass:0
+
+and reports what it left out::
+
+    # not run: 5 tests in x86/ (this run is arm64)
+
+
+Working directories
+===================
+
+A run gets one directory; each test gets a subdirectory of it, mirroring the
+source layout::
+
+    /tmp/klp-tests.XXXXXXXX/
+        generic/test-basic/{orig.o,patched.o,out.o,Module.symvers,...}
+        x86/test-kcfi/...
+
+``--keep`` leaves it and reports the one path.  Otherwise each test removes its
+own directory and the runner ``rmdir``s the run's -- which fails if anything
+was left behind, so a test which dies without cleaning up is reported rather
+than silently leaking.
+
+
+Running
+=======
+
+::
+
+    make -C tools/objtool                 # needs libelf and libxxhash
+    make -C tools/objtool tests
+
+    CC=clang make -C tools/objtool tests  # the other toolchain
+    LLVM=1 make -C tools/objtool tests    # and its binutils too
+
+    tools/objtool/tests/run-tests.sh --keep basic   # one test, keep its objects
+
+A run covers one compiler and one architecture; CI runs the combinations.
+
+Cross-compiled runs
+-------------------
+
+objtool klp is built only where ARCH_HAS_KLP is set, which today means x86 --
+so an arm64 machine cannot run any of this natively.  It can run all of it
+cross, because objtool is a host tool that only reads and rewrites ELF, and
+the tests only compile fixtures and inspect the objects.  Nothing has to
+execute target code.
+
+::
+
+    ARCH=x86_64 CROSS_COMPILE=x86_64-linux-gnu- make -C tools/objtool
+    ARCH=x86_64 CROSS_COMPILE=x86_64-linux-gnu- make -C tools/objtool tests
+
+objtool itself stays a native binary: it is built with HOSTCC, not CC, so
+setting a cross compiler cannot produce one the host is unable to run.  ARCH
+selects both the objtool target and the directory of tests to run.
+
+clang needs telling, since it defaults to the host triple however it is
+invoked.  The fixtures include no kernel headers, so no sysroot is needed:
+
+::
+
+    ARCH=x86_64 CC="clang --target=x86_64-linux-gnu" \
+            OBJCOPY=llvm-objcopy make -C tools/objtool tests
+
+CROSS_COMPILE picks the binutils, and each can be overridden on its own.
+readelf reads any target and rarely needs overriding; BFD's objcopy is usually
+built for the host's alone, hence OBJCOPY=llvm-objcopy above, or install
+binutils-multiarch.
+
+Either readelf will do.  The assertions read readelf's output, and the two
+spell some of it differently -- GNU prints "OS [0xff20]" for SHN_LIVEPATCH
+where llvm-readelf prints "OS[0xff20]" -- so they accept both.
+
+Getting this wrong is easy and the harness refuses rather than producing a
+misleading result.  "CC=clang ARCH=x86_64" alone selects the x86 tests and
+then builds arm64 objects; preflight compiles a probe object, hands it to
+objtool, and stops the run if they disagree about the architecture, or if
+ARCH does not match what the compiler emits.
+
+
+What this does not cover
+========================
+
+These are unit tests for objtool's klp subcommands.  They do not build a
+kernel, do not run scripts/livepatch/klp-build, and do not load a
+livepatch.  Behaviour which only appears when the kernel applies a patch --
+the module loader refusing a relocation, late module patching ordering -- has
+to be tested by booting, and is out of scope here.
tools/objtool/Documentation/klp-write-tests.txt new file +266 -0

266 lines not on this page · raw message

merge bot Applied
#27 lore raw

[tip: objtool/core] objtool/klp: Document the klp test harness

In reply to Song Liu
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:     2ab23a580d00fcf2a3dbb93b54b45d295aba835d
Gitweb:        https://git.kernel.org/tip/2ab23a580d00fcf2a3dbb93b54b45d295aba835d
Author:        Song Liu <[email protected]>
AuthorDate:    Wed, 16 Sep 2026 11:43:02 -07:00
Committer:     Ingo Molnar <[email protected]>
CommitterDate: Mon, 21 Sep 2026 11:01:29 +02:00

objtool/klp: Document the klp test harness

Two documents, for two different readers.

klp-test-design.txt is for someone deciding whether to trust the suite or change it: what makes unit tests possible for a pipeline that normally needs two kernel builds (objtool has no configuration-dependent logic, so a test reproduces a configuration by reproducing its input), how tests are selected per architecture, and what the outcome classification is for.

klp-write-tests.txt is the procedure for adding one, and is written to be handed to someone -- or something -- with the instruction "follow this and write a test for commit <sha>", or "port the case at <location> from another harness". It leads with the rule that matters: a test is not finished until you have watched it fail with the code broken. Then the traps, each of which this suite has already fallen into -- a fixture the compiler optimised away, a named char[] which never reaches the string path because that keys on SHF_STRINGS, per-function sections hiding the movement a test was about.

Some of this was previously written as comments in lib.sh. That was the wrong place: guidance on how to write a test is read once by an author, while every comment in the harness is read by everyone who opens it. Explanations of why the code is as it is stay where they were.

---
 tools/objtool/Documentation/klp-test-design.txt | 272 +++++++++++++++-
 tools/objtool/Documentation/klp-write-tests.txt | 266 +++++++++++++++-
 2 files changed, 538 insertions(+)
 create mode 100644 tools/objtool/Documentation/klp-test-design.txt
 create mode 100644 tools/objtool/Documentation/klp-write-tests.txt
tools/objtool/Documentation/klp-test-design.txt new file +272 -0
new file mode 100644
index 0000000..ec56bfb
@@ -0,0 +1,272 @@
+.. SPDX-License-Identifier: GPL-2.0
+
+======================================
+Design of the objtool klp test harness
+======================================
+
+tools/objtool/tests/ holds unit tests for the klp subcommands of
+objtool -- ``klp checksum``, ``klp diff``, ``klp post-link`` and
+``--klp-symids`` -- which together turn two builds of the kernel into a
+livepatch module.
+
+This document explains how the harness is built and why.  For the rules to
+follow when adding a test, see klp-write-tests.txt.
+
+
+TL;DR
+=====
+
+One run covers one compiler and one architecture; CI runs the combinations.
+Build objtool first -- it needs libelf and libxxhash -- and the same ARCH is
+used for both steps.
+
+Natively, with gcc::
+
+    make -C tools/objtool
+    make -C tools/objtool tests
+
+Natively, with clang -- LLVM=1 additionally selects the LLVM binutils::
+
+    CC=clang make -C tools/objtool tests
+    LLVM=1 make -C tools/objtool tests
+
+Cross, with gcc -- an arm64 host running the x86 tests::
+
+    ARCH=x86_64 CROSS_COMPILE=x86_64-linux-gnu- make -C tools/objtool
+    ARCH=x86_64 CROSS_COMPILE=x86_64-linux-gnu- make -C tools/objtool tests
+
+Cross, with clang.  It defaults to the host triple however it is invoked, so
+--target= is what makes it emit x86; OBJCOPY is needed because BFD's is
+usually built for the host's target alone::
+
+    ARCH=x86_64 make -C tools/objtool
+    ARCH=x86_64 CC="clang --target=x86_64-linux-gnu" OBJCOPY=llvm-objcopy \
+            make -C tools/objtool tests
+
+A run ends with a totals line; anything other than fail:0 is a real result::
+
+    # pass:48 fail:0 static-skip:1 probe-skip:0 xfail:0 xpass:0
+
+Useful extras::
+
+    tools/objtool/tests/run-tests.sh basic          # one test, by name
+    tools/objtool/tests/run-tests.sh --keep basic   # and keep what it built
+
+
+Why unit tests are possible at all
+==================================
+
+klp-build is a pipeline: build the kernel twice, checksum both, diff them,
+link the result.  Testing that end to end means two kernel builds per case,
+which is too slow to run often and too heavy to keep in the tree.
+
+Three properties make a much cheaper test possible.
+
+**objtool has no configuration-dependent logic.**  It never reads ``.config``.
+Every ``CONFIG_`` string in its source is a comment or one error message, and
+its only build-time conditionals are driven by host libraries and the target
+architecture.  Configuration reaches objtool through exactly two channels: the
+``objtool-args-$(CONFIG_*)`` lines in scripts/Makefile.lib, and the
+contents of the object handed to it.
+
+**The klp subcommands use none of the first channel.**  Of objtool's options
+they consult three -- ``checksum``, ``debug_checksum``, ``dryrun`` -- all from
+their own command line.  So klp behaviour varies with configuration *only*
+through the input object.
+
+**Therefore a test can reproduce any configuration's behaviour by reproducing
+its input.**  Compile a small freestanding fixture with the flags that
+configuration would have used, and objtool cannot tell the difference.  No
+kernel, no ``.config``, no object cache.
+
+The whole suite runs in a few seconds.
+
+
+Shape of a test
+===============
+
+Each test compiles one fixture twice -- once plain, once with ``-DPATCHED`` --
+runs ``klp checksum`` over both, diffs them, and asserts on properties of the
+output object::
+
+    . "$(dirname "$0")/../lib.sh"
+
+    setup
+    build_pair basic.c
+
+    assert_input_symbol changed
+    run_diff
+
+    assert_patched changed
+    assert_not_patched untouched
+
+    pass "changed function cloned, unchanged function left alone"
+
+Assertions check properties, never recorded output.  Codegen varies between
+compilers and versions, so a golden file would report churn rather than
+regressions.
+
+
+Layout
+======
+
+::
+
+    tools/objtool/tests/
+        lib.sh              the harness: everything a test may call
+        run-tests.sh        selects, runs and classifies
+        generic/
+            test-*.sh
+            fixtures/*.c
+        x86/
+            test-*.sh
+            fixtures/*.c
+
+Which architecture a test is for is expressed by where it lives.  The runner
+executes ``generic/`` plus the directory matching this architecture, so a test
+which cannot apply is not run rather than running in order to report that it
+did not.  There is no ``x86_only`` helper, and no lookup letting an
+architecture fixture shadow a generic one: an architecture-specific test
+carries its own fixtures.
+
+Compilers cannot be expressed the same way, because CI varies ``CC`` over the
+same tree.  A compiler requirement stays a declaration inside the test
+(``gcc_only``, ``clang_only``).
+
+
+The environment is established once
+===================================
+
+Sourcing lib.sh runs ``klp_preflight``, which checks that objtool
+exists and has klp support, that ``$CC`` works, that the binutils are present,
+and which architecture this is.  The answers are exported, so:
+
+* ``run-tests.sh`` sources lib.sh too, and therefore knows the
+  architecture before it chooses which tests to run;
+* each test inherits the answers rather than repeating the work;
+* a test run on its own establishes them for itself.
+
+Preflight answers only whether the suite can run at all.  A suite which cannot
+run must not exit 0 looking like one which passed, so a missing objtool fails
+the whole run with a TAP ``Bail out!`` rather than skipping each test in turn.
+What a *particular* compiler can do is a different question, left to the test
+which cares.
+
+
+Outcomes
+========
+
+Output is TAP.  The distinction the harness cares most about is between kinds
+of skip, because a skip is how a suite quietly stops testing anything:
+
+``declared``
+    The test said in advance it does not apply -- ``gcc_only`` on a clang run.
+    Expected indefinitely.
+
+``probe``
+    The construct did not turn up in the built object this time.  Weaker: one
+    which becomes permanent is a fixture that has stopped testing anything.
+
+``undeclared``
+    Counted as a **failure**.  A test which gives up for a reason it never
+    declared is a hole, not an outcome.
+
+``xfail``/``xpass`` come with them, so a known failure is reported rather than
+commented out, and one which starts passing says so instead of going quietly
+green.
+
+The runner classifies the TAP result line, not everything a test printed:
+objtool warns on stderr and that output is captured, so a stray line ahead of
+the result would otherwise leave the exit status to decide -- and an expected
+failure exits 0.
+
+A run ends with a totals line::
+
+    # pass:48 fail:0 static-skip:1 probe-skip:0 xfail:0 xpass:0
+
+and reports what it left out::
+
+    # not run: 5 tests in x86/ (this run is arm64)
+
+
+Working directories
+===================
+
+A run gets one directory; each test gets a subdirectory of it, mirroring the
+source layout::
+
+    /tmp/klp-tests.XXXXXXXX/
+        generic/test-basic/{orig.o,patched.o,out.o,Module.symvers,...}
+        x86/test-kcfi/...
+
+``--keep`` leaves it and reports the one path.  Otherwise each test removes its
+own directory and the runner ``rmdir``s the run's -- which fails if anything
+was left behind, so a test which dies without cleaning up is reported rather
+than silently leaking.
+
+
+Running
+=======
+
+::
+
+    make -C tools/objtool                 # needs libelf and libxxhash
+    make -C tools/objtool tests
+
+    CC=clang make -C tools/objtool tests  # the other toolchain
+    LLVM=1 make -C tools/objtool tests    # and its binutils too
+
+    tools/objtool/tests/run-tests.sh --keep basic   # one test, keep its objects
+
+A run covers one compiler and one architecture; CI runs the combinations.
+
+Cross-compiled runs
+-------------------
+
+objtool klp is built only where ARCH_HAS_KLP is set, which today means x86 --
+so an arm64 machine cannot run any of this natively.  It can run all of it
+cross, because objtool is a host tool that only reads and rewrites ELF, and
+the tests only compile fixtures and inspect the objects.  Nothing has to
+execute target code.
+
+::
+
+    ARCH=x86_64 CROSS_COMPILE=x86_64-linux-gnu- make -C tools/objtool
+    ARCH=x86_64 CROSS_COMPILE=x86_64-linux-gnu- make -C tools/objtool tests
+
+objtool itself stays a native binary: it is built with HOSTCC, not CC, so
+setting a cross compiler cannot produce one the host is unable to run.  ARCH
+selects both the objtool target and the directory of tests to run.
+
+clang needs telling, since it defaults to the host triple however it is
+invoked.  The fixtures include no kernel headers, so no sysroot is needed:
+
+::
+
+    ARCH=x86_64 CC="clang --target=x86_64-linux-gnu" \
+            OBJCOPY=llvm-objcopy make -C tools/objtool tests
+
+CROSS_COMPILE picks the binutils, and each can be overridden on its own.
+readelf reads any target and rarely needs overriding; BFD's objcopy is usually
+built for the host's alone, hence OBJCOPY=llvm-objcopy above, or install
+binutils-multiarch.
+
+Either readelf will do.  The assertions read readelf's output, and the two
+spell some of it differently -- GNU prints "OS [0xff20]" for SHN_LIVEPATCH
+where llvm-readelf prints "OS[0xff20]" -- so they accept both.
+
+Getting this wrong is easy and the harness refuses rather than producing a
+misleading result.  "CC=clang ARCH=x86_64" alone selects the x86 tests and
+then builds arm64 objects; preflight compiles a probe object, hands it to
+objtool, and stops the run if they disagree about the architecture, or if
+ARCH does not match what the compiler emits.
+
+
+What this does not cover
+========================
+
+These are unit tests for objtool's klp subcommands.  They do not build a
+kernel, do not run scripts/livepatch/klp-build, and do not load a
+livepatch.  Behaviour which only appears when the kernel applies a patch --
+the module loader refusing a relocation, late module patching ordering -- has
+to be tested by booting, and is out of scope here.
tools/objtool/Documentation/klp-write-tests.txt new file +266 -0

266 lines not on this page · raw message

author maintainer
#28 lore raw

PATCH v5 10/58 objtool: Keep failing test workdirs by default

In reply to Song Liu

From: Joe Lawrence <[email protected]>

The klp test runner deletes each test's working directory when the test finishes. On failure that removes diff.log, out.o and the fixture objects before the developer can look at them, and the only hint was to re-run (something) with --keep:

  $ make -C tools/objtool tests
  ...
  not ok - test-special-section: expected section '.kcfi_traps' in output
  ...
  # pass:49 fail:1 static-skip:1 probe-skip:0 xfail:0 xpass:0
  # re-run with --keep to hold on to what a failing test built

Change the default behavior to save failing test working directories. This is friendlier to the drive-by tester. Provide the power-user with a KEEP Makefile variable that can optionally retain 'all' or 'none' of those directories. run-tests.sh --keep remains an alias for KEEP=all.

Now that a run can be holding objects worth looking at, say where they are when it is cut short. A Ctrl-C left the run directory behind -- the tests clean up after themselves as they exit, but the two levels the runner made are its own to answer for, and nothing removed them. Take them away from a trap if the tests left them empty, and print the path if they did not:
under the new default the test that was running keeps what it had built, and that is the run most worth being told about.

The trap only ever rmdirs, so it cannot overrule what a test decided to keep; the same helper now serves the end of a normal run.

Assisted-by Claude:claude-opus-5
---
 .../objtool/Documentation/klp-test-design.txt | 14 ++-
 tools/objtool/Makefile                        |  2 +-
 tools/objtool/tests/lib.sh                    | 62 ++++++++++---
 tools/objtool/tests/run-tests.sh              | 92 +++++++++++++++----
 4 files changed, 136 insertions(+), 34 deletions(-)
tools/objtool/Documentation/klp-test-design.txt +9 -5
index ec56bfbc2c93..67d20bf0dc10 100644
@@ -199,10 +199,11 @@ source layout::
         generic/test-basic/{orig.o,patched.o,out.o,Module.symvers,...}
         x86/test-kcfi/...
 
-``--keep`` leaves it and reports the one path.  Otherwise each test removes its
-own directory and the runner ``rmdir``s the run's -- which fails if anything
-was left behind, so a test which dies without cleaning up is reported rather
-than silently leaking.
+By default (``KEEP=failed``) only failing tests keep their directories; the
+runner reports where they are.  ``KEEP=all`` keeps every test's directory;
+``KEEP=none`` removes them all.  The runner ``rmdir``s the run directory when
+it is empty -- which fails if anything was left behind unexpectedly, so a test
+which dies without cleaning up is reported rather than silently leaking.
 
 
 Running
@@ -216,7 +217,10 @@ Running
     CC=clang make -C tools/objtool tests  # the other toolchain
     LLVM=1 make -C tools/objtool tests    # and its binutils too
 
-    tools/objtool/tests/run-tests.sh --keep basic   # one test, keep its objects
+    make -C tools/objtool tests KEEP=all    # keep every test's workdir
+    make -C tools/objtool tests KEEP=none   # remove all workdirs
+
+    tools/objtool/tests/run-tests.sh basic  # one test; failures kept by default
 
 A run covers one compiler and one architecture; CI runs the combinations.
 
tools/objtool/Makefile +1 -1
index 2c200d05c276..ed5cf146ef2e 100644
@@ -153,7 +153,7 @@ mrproper: clean
 
 tests: $(OBJTOOL)
 	$(Q)OBJTOOL=$(abspath $(OBJTOOL)) ARCH=$(ARCH) CROSS_COMPILE=$(CROSS_COMPILE) \
-		$(srctree)/tools/objtool/tests/run-tests.sh
+		KEEP=$(KEEP) $(srctree)/tools/objtool/tests/run-tests.sh
 
 FORCE:
 
tools/objtool/tests/lib.sh +51 -11

100 lines not on this page · raw message

tools/objtool/tests/run-tests.sh +75 -17

144 lines not on this page · raw message

Signature · 1 line
2.53.0-Meta
merge bot Applied
#29 lore raw

[tip: objtool/core] objtool: Keep failing test workdirs by default

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:     1ed3ce15096762e5e470921bd6c9f288de2d90f5
Gitweb:        https://git.kernel.org/tip/1ed3ce15096762e5e470921bd6c9f288de2d90f5
Author:        Joe Lawrence <[email protected]>
AuthorDate:    Wed, 16 Sep 2026 11:43:03 -07:00
Committer:     Josh Poimboeuf <[email protected]>
CommitterDate: Wed, 16 Sep 2026 17:13:26 -07:00

objtool: Keep failing test workdirs by default

The klp test runner deletes each test's working directory when the test finishes. On failure that removes diff.log, out.o and the fixture objects before the developer can look at them, and the only hint was to re-run (something) with --keep:

  $ make -C tools/objtool tests
  ...
  not ok - test-special-section: expected section '.kcfi_traps' in output
  ...
  # pass:49 fail:1 static-skip:1 probe-skip:0 xfail:0 xpass:0
  # re-run with --keep to hold on to what a failing test built

Change the default behavior to save failing test working directories. This is friendlier to the drive-by tester. Provide the power-user with a KEEP Makefile variable that can optionally retain 'all' or 'none' of those directories. run-tests.sh --keep remains an alias for KEEP=all.

Now that a run can be holding objects worth looking at, say where they are when it is cut short. A Ctrl-C left the run directory behind -- the tests clean up after themselves as they exit, but the two levels the runner made are its own to answer for, and nothing removed them. Take them away from a trap if the tests left them empty, and print the path if they did not:
under the new default the test that was running keeps what it had built, and that is the run most worth being told about.

The trap only ever rmdirs, so it cannot overrule what a test decided to keep; the same helper now serves the end of a normal run.

---
 tools/objtool/Documentation/klp-test-design.txt | 14 +-
 tools/objtool/Makefile                          |  2 +-
 tools/objtool/tests/lib.sh                      | 62 +++++++++--
 tools/objtool/tests/run-tests.sh                | 92 +++++++++++++---
 4 files changed, 136 insertions(+), 34 deletions(-)
tools/objtool/Documentation/klp-test-design.txt +9 -5
index ec56bfb..67d20bf 100644
@@ -199,10 +199,11 @@ source layout::
         generic/test-basic/{orig.o,patched.o,out.o,Module.symvers,...}
         x86/test-kcfi/...
 
-``--keep`` leaves it and reports the one path.  Otherwise each test removes its
-own directory and the runner ``rmdir``s the run's -- which fails if anything
-was left behind, so a test which dies without cleaning up is reported rather
-than silently leaking.
+By default (``KEEP=failed``) only failing tests keep their directories; the
+runner reports where they are.  ``KEEP=all`` keeps every test's directory;
+``KEEP=none`` removes them all.  The runner ``rmdir``s the run directory when
+it is empty -- which fails if anything was left behind unexpectedly, so a test
+which dies without cleaning up is reported rather than silently leaking.
 
 
 Running
@@ -216,7 +217,10 @@ Running
     CC=clang make -C tools/objtool tests  # the other toolchain
     LLVM=1 make -C tools/objtool tests    # and its binutils too
 
-    tools/objtool/tests/run-tests.sh --keep basic   # one test, keep its objects
+    make -C tools/objtool tests KEEP=all    # keep every test's workdir
+    make -C tools/objtool tests KEEP=none   # remove all workdirs
+
+    tools/objtool/tests/run-tests.sh basic  # one test; failures kept by default
 
 A run covers one compiler and one architecture; CI runs the combinations.
 
tools/objtool/Makefile +1 -1
index 2c200d0..ed5cf14 100644
@@ -153,7 +153,7 @@ mrproper: clean
 
 tests: $(OBJTOOL)
 	$(Q)OBJTOOL=$(abspath $(OBJTOOL)) ARCH=$(ARCH) CROSS_COMPILE=$(CROSS_COMPILE) \
-		$(srctree)/tools/objtool/tests/run-tests.sh
+		KEEP=$(KEEP) $(srctree)/tools/objtool/tests/run-tests.sh
 
 FORCE:
 
tools/objtool/tests/lib.sh +51 -11

100 lines not on this page · raw message

tools/objtool/tests/run-tests.sh +75 -17

144 lines not on this page · raw message

merge bot Applied
#30 lore raw

[tip: objtool/core] objtool: Keep failing test workdirs by default

In reply to Song Liu
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:     9b11acaad1a63eddf4a9bf50dc9b90183bf037e1
Gitweb:        https://git.kernel.org/tip/9b11acaad1a63eddf4a9bf50dc9b90183bf037e1
Author:        Joe Lawrence <[email protected]>
AuthorDate:    Wed, 16 Sep 2026 11:43:03 -07:00
Committer:     Ingo Molnar <[email protected]>
CommitterDate: Mon, 21 Sep 2026 11:01:39 +02:00

objtool: Keep failing test workdirs by default

The klp test runner deletes each test's working directory when the test finishes. On failure that removes diff.log, out.o and the fixture objects before the developer can look at them, and the only hint was to re-run (something) with --keep:

  $ make -C tools/objtool tests
  ...
  not ok - test-special-section: expected section '.kcfi_traps' in output
  ...
  # pass:49 fail:1 static-skip:1 probe-skip:0 xfail:0 xpass:0
  # re-run with --keep to hold on to what a failing test built

Change the default behavior to save failing test working directories. This is friendlier to the drive-by tester. Provide the power-user with a KEEP Makefile variable that can optionally retain 'all' or 'none' of those directories. run-tests.sh --keep remains an alias for KEEP=all.

Now that a run can be holding objects worth looking at, say where they are when it is cut short. A Ctrl-C left the run directory behind -- the tests clean up after themselves as they exit, but the two levels the runner made are its own to answer for, and nothing removed them. Take them away from a trap if the tests left them empty, and print the path if they did not:
under the new default the test that was running keeps what it had built, and that is the run most worth being told about.

The trap only ever rmdirs, so it cannot overrule what a test decided to keep; the same helper now serves the end of a normal run.

---
 tools/objtool/Documentation/klp-test-design.txt | 14 +-
 tools/objtool/Makefile                          |  2 +-
 tools/objtool/tests/lib.sh                      | 62 +++++++++--
 tools/objtool/tests/run-tests.sh                | 92 +++++++++++++---
 4 files changed, 136 insertions(+), 34 deletions(-)
tools/objtool/Documentation/klp-test-design.txt +9 -5
index ec56bfb..67d20bf 100644
@@ -199,10 +199,11 @@ source layout::
         generic/test-basic/{orig.o,patched.o,out.o,Module.symvers,...}
         x86/test-kcfi/...
 
-``--keep`` leaves it and reports the one path.  Otherwise each test removes its
-own directory and the runner ``rmdir``s the run's -- which fails if anything
-was left behind, so a test which dies without cleaning up is reported rather
-than silently leaking.
+By default (``KEEP=failed``) only failing tests keep their directories; the
+runner reports where they are.  ``KEEP=all`` keeps every test's directory;
+``KEEP=none`` removes them all.  The runner ``rmdir``s the run directory when
+it is empty -- which fails if anything was left behind unexpectedly, so a test
+which dies without cleaning up is reported rather than silently leaking.
 
 
 Running
@@ -216,7 +217,10 @@ Running
     CC=clang make -C tools/objtool tests  # the other toolchain
     LLVM=1 make -C tools/objtool tests    # and its binutils too
 
-    tools/objtool/tests/run-tests.sh --keep basic   # one test, keep its objects
+    make -C tools/objtool tests KEEP=all    # keep every test's workdir
+    make -C tools/objtool tests KEEP=none   # remove all workdirs
+
+    tools/objtool/tests/run-tests.sh basic  # one test; failures kept by default
 
 A run covers one compiler and one architecture; CI runs the combinations.
 
tools/objtool/Makefile +1 -1
index e9a4cc8..d3db966 100644
@@ -155,7 +155,7 @@ mrproper: clean
 
 tests: $(OBJTOOL)
 	$(Q)OBJTOOL=$(abspath $(OBJTOOL)) ARCH=$(ARCH) CROSS_COMPILE=$(CROSS_COMPILE) \
-		$(srctree)/tools/objtool/tests/run-tests.sh
+		KEEP=$(KEEP) $(srctree)/tools/objtool/tests/run-tests.sh
 
 FORCE:
 
tools/objtool/tests/lib.sh +51 -11

100 lines not on this page · raw message

tools/objtool/tests/run-tests.sh +75 -17

144 lines not on this page · raw message

author maintainer
#31 lore raw

PATCH v5 11/58 objtool: Forward toolchain variables to the klp test runner

In reply to Song Liu

From: Joe Lawrence <[email protected]>

The tests target already passes ARCH and CROSS_COMPILE into run-tests.sh. lib.sh uses those to pick a default compiler and binutils:

  CC=${CC:-${CROSS_COMPILE}gcc}
  LD=${LD:-${CROSS_COMPILE}ld}
  READELF=${READELF:-${CROSS_COMPILE}readelf}
  OBJCOPY=${OBJCOPY:-${CROSS_COMPILE}objcopy}

Those defaults only apply when the variables reach the shell that sources lib.sh. The recipe passed OBJTOOL, ARCH and CROSS_COMPILE explicitly, but not CC or the binutils. Makefile-assigned values (e.g. from LLVM=1) are not visible in the recipe environment unless forwarded:

  $ LLVM=1 make -C tools/objtool tests
  ...
  # preflight
  #   compiler  gcc (GCC) ...

Pass CC, LD, READELF and OBJCOPY the same way as ARCH and CROSS_COMPILE, so fixtures are built and inspected with the toolchain make selected:

  $ LLVM=1 make -C tools/objtool tests
  ...
  # preflight
  #   compiler  clang version 21.1.8 ...
Assisted-by Claude:claude-opus-5
---
 tools/objtool/Documentation/klp-test-design.txt | 12 +++++++++++-
 tools/objtool/Makefile                          |  9 +++++++++
 2 files changed, 20 insertions(+), 1 deletion(-)
tools/objtool/Documentation/klp-test-design.txt +11 -1
index 67d20bf0dc10..2082c277197f 100644
@@ -243,7 +243,17 @@ setting a cross compiler cannot produce one the host is unable to run.  ARCH
 selects both the objtool target and the directory of tests to run.
 
 clang needs telling, since it defaults to the host triple however it is
-invoked.  The fixtures include no kernel headers, so no sysroot is needed:
+invoked.  LLVM=1 with CROSS_COMPILE does that for you -- the --target= it
+derives is forwarded to the tests -- and the fixtures include no kernel
+headers, so no sysroot is needed:
+
+::
+
+    ARCH=x86_64 CROSS_COMPILE=x86_64-linux-gnu- LLVM=1 \
+            make -C tools/objtool tests
+
+Naming the compiler by hand works too, and is what to reach for when the
+target triple is not the one CROSS_COMPILE implies:
 
 ::
 
tools/objtool/Makefile +9 -0
index ed5cf146ef2e..47afe1e8a9c5 100644
@@ -151,8 +151,17 @@ clean: $(LIBSUBCMD)-clean
 mrproper: clean
 	$(call QUIET_CLEAN, objtool) $(RM) $(OBJTOOL)
 
+# The kernel's own Makefile sets OBJCOPY, to llvm-objcopy under LLVM and to
+# $(CROSS_COMPILE)objcopy otherwise; tools/scripts/Makefile.include names only
+# LLVM_OBJCOPY and leaves OBJCOPY unset.  Forwarding it unset would hand the
+# tests an empty string, and they would fall back to GNU objcopy even when
+# asked for an LLVM toolchain.
+OBJCOPY ?= $(if $(LLVM),$(LLVM_OBJCOPY),$(CROSS_COMPILE)objcopy)
+
 tests: $(OBJTOOL)
 	$(Q)OBJTOOL=$(abspath $(OBJTOOL)) ARCH=$(ARCH) CROSS_COMPILE=$(CROSS_COMPILE) \
+		CC='$(CC) $(CLANG_CROSS_FLAGS)' LD='$(LD)' \
+		READELF='$(READELF)' OBJCOPY='$(OBJCOPY)' \
 		KEEP=$(KEEP) $(srctree)/tools/objtool/tests/run-tests.sh
 
 FORCE:
Signature · 1 line
2.53.0-Meta
merge bot Applied
#32 lore raw

[tip: objtool/core] objtool: Forward toolchain variables to the klp test runner

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:     c0c07fbcdbb1e5b8b6d9e940ab8b848530150f57
Gitweb:        https://git.kernel.org/tip/c0c07fbcdbb1e5b8b6d9e940ab8b848530150f57
Author:        Joe Lawrence <[email protected]>
AuthorDate:    Wed, 16 Sep 2026 11:43:04 -07:00
Committer:     Josh Poimboeuf <[email protected]>
CommitterDate: Wed, 16 Sep 2026 17:13:27 -07:00

objtool: Forward toolchain variables to the klp test runner

The tests target already passes ARCH and CROSS_COMPILE into run-tests.sh. lib.sh uses those to pick a default compiler and binutils:

  CC=${CC:-${CROSS_COMPILE}gcc}
  LD=${LD:-${CROSS_COMPILE}ld}
  READELF=${READELF:-${CROSS_COMPILE}readelf}
  OBJCOPY=${OBJCOPY:-${CROSS_COMPILE}objcopy}

Those defaults only apply when the variables reach the shell that sources lib.sh. The recipe passed OBJTOOL, ARCH and CROSS_COMPILE explicitly, but not CC or the binutils. Makefile-assigned values (e.g. from LLVM=1) are not visible in the recipe environment unless forwarded:

  $ LLVM=1 make -C tools/objtool tests
  ...
  # preflight
  #   compiler  gcc (GCC) ...

Pass CC, LD, READELF and OBJCOPY the same way as ARCH and CROSS_COMPILE, so fixtures are built and inspected with the toolchain make selected:

  $ LLVM=1 make -C tools/objtool tests
  ...
  # preflight
  #   compiler  clang version 21.1.8 ...
---
 tools/objtool/Documentation/klp-test-design.txt | 12 +++++++++++-
 tools/objtool/Makefile                          |  9 +++++++++
 2 files changed, 20 insertions(+), 1 deletion(-)
tools/objtool/Documentation/klp-test-design.txt +11 -1
index 67d20bf..2082c27 100644
@@ -243,7 +243,17 @@ setting a cross compiler cannot produce one the host is unable to run.  ARCH
 selects both the objtool target and the directory of tests to run.
 
 clang needs telling, since it defaults to the host triple however it is
-invoked.  The fixtures include no kernel headers, so no sysroot is needed:
+invoked.  LLVM=1 with CROSS_COMPILE does that for you -- the --target= it
+derives is forwarded to the tests -- and the fixtures include no kernel
+headers, so no sysroot is needed:
+
+::
+
+    ARCH=x86_64 CROSS_COMPILE=x86_64-linux-gnu- LLVM=1 \
+            make -C tools/objtool tests
+
+Naming the compiler by hand works too, and is what to reach for when the
+target triple is not the one CROSS_COMPILE implies:
 
 ::
 
tools/objtool/Makefile +9 -0
index ed5cf14..47afe1e 100644
@@ -151,8 +151,17 @@ clean: $(LIBSUBCMD)-clean
 mrproper: clean
 	$(call QUIET_CLEAN, objtool) $(RM) $(OBJTOOL)
 
+# The kernel's own Makefile sets OBJCOPY, to llvm-objcopy under LLVM and to
+# $(CROSS_COMPILE)objcopy otherwise; tools/scripts/Makefile.include names only
+# LLVM_OBJCOPY and leaves OBJCOPY unset.  Forwarding it unset would hand the
+# tests an empty string, and they would fall back to GNU objcopy even when
+# asked for an LLVM toolchain.
+OBJCOPY ?= $(if $(LLVM),$(LLVM_OBJCOPY),$(CROSS_COMPILE)objcopy)
+
 tests: $(OBJTOOL)
 	$(Q)OBJTOOL=$(abspath $(OBJTOOL)) ARCH=$(ARCH) CROSS_COMPILE=$(CROSS_COMPILE) \
+		CC='$(CC) $(CLANG_CROSS_FLAGS)' LD='$(LD)' \
+		READELF='$(READELF)' OBJCOPY='$(OBJCOPY)' \
 		KEEP=$(KEEP) $(srctree)/tools/objtool/tests/run-tests.sh
 
 FORCE:
merge bot Applied
#33 lore raw

[tip: objtool/core] objtool: Forward toolchain variables to the klp test runner

In reply to Song Liu
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:     913bf39ff461bc65cfc4e1e05c3d738ffc6ffc75
Gitweb:        https://git.kernel.org/tip/913bf39ff461bc65cfc4e1e05c3d738ffc6ffc75
Author:        Joe Lawrence <[email protected]>
AuthorDate:    Wed, 16 Sep 2026 11:43:04 -07:00
Committer:     Ingo Molnar <[email protected]>
CommitterDate: Mon, 21 Sep 2026 11:01:56 +02:00

objtool: Forward toolchain variables to the klp test runner

The tests target already passes ARCH and CROSS_COMPILE into run-tests.sh. lib.sh uses those to pick a default compiler and binutils:

  CC=${CC:-${CROSS_COMPILE}gcc}
  LD=${LD:-${CROSS_COMPILE}ld}
  READELF=${READELF:-${CROSS_COMPILE}readelf}
  OBJCOPY=${OBJCOPY:-${CROSS_COMPILE}objcopy}

Those defaults only apply when the variables reach the shell that sources lib.sh. The recipe passed OBJTOOL, ARCH and CROSS_COMPILE explicitly, but not CC or the binutils. Makefile-assigned values (e.g. from LLVM=1) are not visible in the recipe environment unless forwarded:

  $ LLVM=1 make -C tools/objtool tests
  ...
  # preflight
  #   compiler  gcc (GCC) ...

Pass CC, LD, READELF and OBJCOPY the same way as ARCH and CROSS_COMPILE, so fixtures are built and inspected with the toolchain make selected:

  $ LLVM=1 make -C tools/objtool tests
  ...
  # preflight
  #   compiler  clang version 21.1.8 ...
---
 tools/objtool/Documentation/klp-test-design.txt | 12 +++++++++++-
 tools/objtool/Makefile                          |  9 +++++++++
 2 files changed, 20 insertions(+), 1 deletion(-)
tools/objtool/Documentation/klp-test-design.txt +11 -1
index 67d20bf..2082c27 100644
@@ -243,7 +243,17 @@ setting a cross compiler cannot produce one the host is unable to run.  ARCH
 selects both the objtool target and the directory of tests to run.
 
 clang needs telling, since it defaults to the host triple however it is
-invoked.  The fixtures include no kernel headers, so no sysroot is needed:
+invoked.  LLVM=1 with CROSS_COMPILE does that for you -- the --target= it
+derives is forwarded to the tests -- and the fixtures include no kernel
+headers, so no sysroot is needed:
+
+::
+
+    ARCH=x86_64 CROSS_COMPILE=x86_64-linux-gnu- LLVM=1 \
+            make -C tools/objtool tests
+
+Naming the compiler by hand works too, and is what to reach for when the
+target triple is not the one CROSS_COMPILE implies:
 
 ::
 
tools/objtool/Makefile +9 -0
index d3db966..db99c47 100644
@@ -153,8 +153,17 @@ clean: $(LIBSUBCMD)-clean
 mrproper: clean
 	$(call QUIET_CLEAN, objtool) $(RM) $(OBJTOOL)
 
+# The kernel's own Makefile sets OBJCOPY, to llvm-objcopy under LLVM and to
+# $(CROSS_COMPILE)objcopy otherwise; tools/scripts/Makefile.include names only
+# LLVM_OBJCOPY and leaves OBJCOPY unset.  Forwarding it unset would hand the
+# tests an empty string, and they would fall back to GNU objcopy even when
+# asked for an LLVM toolchain.
+OBJCOPY ?= $(if $(LLVM),$(LLVM_OBJCOPY),$(CROSS_COMPILE)objcopy)
+
 tests: $(OBJTOOL)
 	$(Q)OBJTOOL=$(abspath $(OBJTOOL)) ARCH=$(ARCH) CROSS_COMPILE=$(CROSS_COMPILE) \
+		CC='$(CC) $(CLANG_CROSS_FLAGS)' LD='$(LD)' \
+		READELF='$(READELF)' OBJCOPY='$(OBJCOPY)' \
 		KEEP=$(KEEP) $(srctree)/tools/objtool/tests/run-tests.sh
 
 FORCE:
author maintainer
#34 lore raw

PATCH v5 12/58 objtool/klp: Add test for rejecting changed data

In reply to Song Liu

From: Puranjay Mohan <[email protected]>

Livepatching replaces functions. Nothing can swap a variable which live code already refers to, so a patch which changes one has to be refused rather than applied with the old value left in place.

Assisted-by Claude:claude-opus-5
---
 .../tests/generic/fixtures/changed_data.c      | 16 ++++++++++++++++
 .../objtool/tests/generic/test-changed-data.sh | 18 ++++++++++++++++++
 2 files changed, 34 insertions(+)
 create mode 100644 tools/objtool/tests/generic/fixtures/changed_data.c
 create mode 100755 tools/objtool/tests/generic/test-changed-data.sh
tools/objtool/tests/generic/fixtures/changed_data.c new file +16 -0
new file mode 100644
index 000000000000..b52461835444
@@ -0,0 +1,16 @@
+// SPDX-License-Identifier: GPL-2.0
+/* Data whose value differs between the two builds. */
+
+static const char __modinfo[]
+	__attribute__((section(".modinfo"), used, aligned(1))) = "\0name=vmlinux";
+
+#ifdef PATCHED
+int klp_test_data = 2;
+#else
+int klp_test_data = 1;
+#endif
+
+int target(int x)
+{
+	return x + klp_test_data;
+}
tools/objtool/tests/generic/test-changed-data.sh new file +18 -0
new file mode 100755
index 000000000000..c5c7381bb409
@@ -0,0 +1,18 @@
+#!/bin/bash
+# SPDX-License-Identifier: GPL-2.0
+#
+# Livepatching replaces functions, not data.  A changed data symbol must be
+# rejected.
+
+. "$(dirname "$0")/../lib.sh"
+
+setup
+build_pair changed_data.c
+run_diff 255
+
+diff_log | grep -q 'changed data: klp_test_data' ||
+	fail "expected rejection, got: $(diff_log | tail -1)"
+[ -e "$workdir/out.o" ] &&
+	fail "output object produced for a rejected input"
+
+pass "changed data symbol rejected"
Signature · 1 line
2.53.0-Meta
merge bot Applied
#35 lore raw

[tip: objtool/core] objtool/klp: Add test for rejecting changed data

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:     6a73fa640753cbf93163771c7fc70b06a165de3e
Gitweb:        https://git.kernel.org/tip/6a73fa640753cbf93163771c7fc70b06a165de3e
Author:        Puranjay Mohan <[email protected]>
AuthorDate:    Wed, 16 Sep 2026 11:43:05 -07:00
Committer:     Josh Poimboeuf <[email protected]>
CommitterDate: Wed, 16 Sep 2026 17:13:27 -07:00

objtool/klp: Add test for rejecting changed data

Livepatching replaces functions. Nothing can swap a variable which live code already refers to, so a patch which changes one has to be refused rather than applied with the old value left in place.

---
 tools/objtool/tests/generic/fixtures/changed_data.c | 16 +++++++++++-
 tools/objtool/tests/generic/test-changed-data.sh    | 18 ++++++++++++-
 2 files changed, 34 insertions(+)
 create mode 100644 tools/objtool/tests/generic/fixtures/changed_data.c
 create mode 100755 tools/objtool/tests/generic/test-changed-data.sh
tools/objtool/tests/generic/fixtures/changed_data.c new file +16 -0
new file mode 100644
index 0000000..b524618
@@ -0,0 +1,16 @@
+// SPDX-License-Identifier: GPL-2.0
+/* Data whose value differs between the two builds. */
+
+static const char __modinfo[]
+	__attribute__((section(".modinfo"), used, aligned(1))) = "\0name=vmlinux";
+
+#ifdef PATCHED
+int klp_test_data = 2;
+#else
+int klp_test_data = 1;
+#endif
+
+int target(int x)
+{
+	return x + klp_test_data;
+}
tools/objtool/tests/generic/test-changed-data.sh new file +18 -0
new file mode 100755
index 0000000..c5c7381
@@ -0,0 +1,18 @@
+#!/bin/bash
+# SPDX-License-Identifier: GPL-2.0
+#
+# Livepatching replaces functions, not data.  A changed data symbol must be
+# rejected.
+
+. "$(dirname "$0")/../lib.sh"
+
+setup
+build_pair changed_data.c
+run_diff 255
+
+diff_log | grep -q 'changed data: klp_test_data' ||
+	fail "expected rejection, got: $(diff_log | tail -1)"
+[ -e "$workdir/out.o" ] &&
+	fail "output object produced for a rejected input"
+
+pass "changed data symbol rejected"
merge bot Applied
#36 lore raw

[tip: objtool/core] objtool/klp: Add test for rejecting changed data

In reply to Song Liu
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:     b229562c2f44cdec4ce4b8b78428514bccff9dc0
Gitweb:        https://git.kernel.org/tip/b229562c2f44cdec4ce4b8b78428514bccff9dc0
Author:        Puranjay Mohan <[email protected]>
AuthorDate:    Wed, 16 Sep 2026 11:43:05 -07:00
Committer:     Ingo Molnar <[email protected]>
CommitterDate: Mon, 21 Sep 2026 11:02:11 +02:00

objtool/klp: Add test for rejecting changed data

Livepatching replaces functions. Nothing can swap a variable which live code already refers to, so a patch which changes one has to be refused rather than applied with the old value left in place.

---
 tools/objtool/tests/generic/fixtures/changed_data.c | 16 +++++++++++-
 tools/objtool/tests/generic/test-changed-data.sh    | 18 ++++++++++++-
 2 files changed, 34 insertions(+)
 create mode 100644 tools/objtool/tests/generic/fixtures/changed_data.c
 create mode 100755 tools/objtool/tests/generic/test-changed-data.sh
tools/objtool/tests/generic/fixtures/changed_data.c new file +16 -0
new file mode 100644
index 0000000..b524618
@@ -0,0 +1,16 @@
+// SPDX-License-Identifier: GPL-2.0
+/* Data whose value differs between the two builds. */
+
+static const char __modinfo[]
+	__attribute__((section(".modinfo"), used, aligned(1))) = "\0name=vmlinux";
+
+#ifdef PATCHED
+int klp_test_data = 2;
+#else
+int klp_test_data = 1;
+#endif
+
+int target(int x)
+{
+	return x + klp_test_data;
+}
tools/objtool/tests/generic/test-changed-data.sh new file +18 -0
new file mode 100755
index 0000000..c5c7381
@@ -0,0 +1,18 @@
+#!/bin/bash
+# SPDX-License-Identifier: GPL-2.0
+#
+# Livepatching replaces functions, not data.  A changed data symbol must be
+# rejected.
+
+. "$(dirname "$0")/../lib.sh"
+
+setup
+build_pair changed_data.c
+run_diff 255
+
+diff_log | grep -q 'changed data: klp_test_data' ||
+	fail "expected rejection, got: $(diff_log | tail -1)"
+[ -e "$workdir/out.o" ] &&
+	fail "output object produced for a rejected input"
+
+pass "changed data symbol rejected"
author maintainer
#37 lore raw

PATCH v5 13/58 objtool/klp: Add test for newly introduced data

In reply to Song Liu

From: Puranjay Mohan <[email protected]>

Adding data differs from changing it: nothing in the running kernel refers to a new variable, so it is safe and has to travel into the livepatch with the function using it.

Assisted-by Claude:claude-opus-5
---
 .../objtool/tests/generic/fixtures/new_data.c | 23 ++++++++++++++++
 tools/objtool/tests/generic/test-new-data.sh  | 27 +++++++++++++++++++
 2 files changed, 50 insertions(+)
 create mode 100644 tools/objtool/tests/generic/fixtures/new_data.c
 create mode 100755 tools/objtool/tests/generic/test-new-data.sh
tools/objtool/tests/generic/fixtures/new_data.c new file +23 -0
new file mode 100644
index 000000000000..ac364622f12a
@@ -0,0 +1,23 @@
+// SPDX-License-Identifier: GPL-2.0
+/* Data introduced by the patch. */
+
+static const char __modinfo[]
+	__attribute__((section(".modinfo"), used, aligned(1))) = "\0name=vmlinux";
+
+#ifdef PATCHED
+/*
+ * Not an arithmetic progression: { 1, 2, 3, 4 } indexed by x & 3 is something
+ * a compiler can compute instead of load, and then target() has no reference
+ * to the array and there is nothing for klp diff to carry.
+ */
+static const int klp_new_data[4] __attribute__((used)) = { 7, 3, 11, 5 };
+#endif
+
+int target(int x)
+{
+#ifdef PATCHED
+	return x + klp_new_data[x & 3];
+#else
+	return x;
+#endif
+}
tools/objtool/tests/generic/test-new-data.sh new file +27 -0
new file mode 100755
index 000000000000..acb68ff19c99
@@ -0,0 +1,27 @@
+#!/bin/bash
+# SPDX-License-Identifier: GPL-2.0
+#
+# Data added by the patch has no counterpart in the running kernel and must be
+# carried into the livepatch.
+
+. "$(dirname "$0")/../lib.sh"
+
+setup
+build_pair new_data.c
+
+# State the premise on both sides.  The array is new in the patched build and
+# absent from the original; if the compiler folded it into the code instead of
+# emitting it, the assertion below would fail without saying why.
+has_input_symbol "$orig_obj" klp_new_data &&
+	fail "fixture put klp_new_data in the original; nothing new to carry"
+has_input_symbol "$patched_obj" klp_new_data ||
+	fail "compiler did not emit klp_new_data; the fixture tests nothing"
+in_relocs "$patched_obj" | grep -q 'klp_new_data' ||
+	fail "target() does not reference klp_new_data; the fixture tests nothing"
+
+run_diff
+
+assert_patched target
+assert_symbol klp_new_data
+
+pass "new data carried into the patch"
Signature · 1 line
2.53.0-Meta
merge bot Applied
#38 lore raw

[tip: objtool/core] objtool/klp: Add test for newly introduced data

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:     f85da39ef5758c3da3a2893d64110444b2128958
Gitweb:        https://git.kernel.org/tip/f85da39ef5758c3da3a2893d64110444b2128958
Author:        Puranjay Mohan <[email protected]>
AuthorDate:    Wed, 16 Sep 2026 11:43:06 -07:00
Committer:     Josh Poimboeuf <[email protected]>
CommitterDate: Wed, 16 Sep 2026 17:13:27 -07:00

objtool/klp: Add test for newly introduced data

Adding data differs from changing it: nothing in the running kernel refers to a new variable, so it is safe and has to travel into the livepatch with the function using it.

---
 tools/objtool/tests/generic/fixtures/new_data.c | 23 ++++++++++++++-
 tools/objtool/tests/generic/test-new-data.sh    | 27 ++++++++++++++++-
 2 files changed, 50 insertions(+)
 create mode 100644 tools/objtool/tests/generic/fixtures/new_data.c
 create mode 100755 tools/objtool/tests/generic/test-new-data.sh
tools/objtool/tests/generic/fixtures/new_data.c new file +23 -0
new file mode 100644
index 0000000..ac36462
@@ -0,0 +1,23 @@
+// SPDX-License-Identifier: GPL-2.0
+/* Data introduced by the patch. */
+
+static const char __modinfo[]
+	__attribute__((section(".modinfo"), used, aligned(1))) = "\0name=vmlinux";
+
+#ifdef PATCHED
+/*
+ * Not an arithmetic progression: { 1, 2, 3, 4 } indexed by x & 3 is something
+ * a compiler can compute instead of load, and then target() has no reference
+ * to the array and there is nothing for klp diff to carry.
+ */
+static const int klp_new_data[4] __attribute__((used)) = { 7, 3, 11, 5 };
+#endif
+
+int target(int x)
+{
+#ifdef PATCHED
+	return x + klp_new_data[x & 3];
+#else
+	return x;
+#endif
+}
tools/objtool/tests/generic/test-new-data.sh new file +27 -0
new file mode 100755
index 0000000..acb68ff
@@ -0,0 +1,27 @@
+#!/bin/bash
+# SPDX-License-Identifier: GPL-2.0
+#
+# Data added by the patch has no counterpart in the running kernel and must be
+# carried into the livepatch.
+
+. "$(dirname "$0")/../lib.sh"
+
+setup
+build_pair new_data.c
+
+# State the premise on both sides.  The array is new in the patched build and
+# absent from the original; if the compiler folded it into the code instead of
+# emitting it, the assertion below would fail without saying why.
+has_input_symbol "$orig_obj" klp_new_data &&
+	fail "fixture put klp_new_data in the original; nothing new to carry"
+has_input_symbol "$patched_obj" klp_new_data ||
+	fail "compiler did not emit klp_new_data; the fixture tests nothing"
+in_relocs "$patched_obj" | grep -q 'klp_new_data' ||
+	fail "target() does not reference klp_new_data; the fixture tests nothing"
+
+run_diff
+
+assert_patched target
+assert_symbol klp_new_data
+
+pass "new data carried into the patch"
merge bot Applied
#39 lore raw

[tip: objtool/core] objtool/klp: Add test for newly introduced data

In reply to Song Liu
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:     f4b8bfb1285992a6ab6f3d7cd25186d64f0773ee
Gitweb:        https://git.kernel.org/tip/f4b8bfb1285992a6ab6f3d7cd25186d64f0773ee
Author:        Puranjay Mohan <[email protected]>
AuthorDate:    Wed, 16 Sep 2026 11:43:06 -07:00
Committer:     Ingo Molnar <[email protected]>
CommitterDate: Mon, 21 Sep 2026 11:02:20 +02:00

objtool/klp: Add test for newly introduced data

Adding data differs from changing it: nothing in the running kernel refers to a new variable, so it is safe and has to travel into the livepatch with the function using it.

---
 tools/objtool/tests/generic/fixtures/new_data.c | 23 ++++++++++++++-
 tools/objtool/tests/generic/test-new-data.sh    | 27 ++++++++++++++++-
 2 files changed, 50 insertions(+)
 create mode 100644 tools/objtool/tests/generic/fixtures/new_data.c
 create mode 100755 tools/objtool/tests/generic/test-new-data.sh
tools/objtool/tests/generic/fixtures/new_data.c new file +23 -0
new file mode 100644
index 0000000..ac36462
@@ -0,0 +1,23 @@
+// SPDX-License-Identifier: GPL-2.0
+/* Data introduced by the patch. */
+
+static const char __modinfo[]
+	__attribute__((section(".modinfo"), used, aligned(1))) = "\0name=vmlinux";
+
+#ifdef PATCHED
+/*
+ * Not an arithmetic progression: { 1, 2, 3, 4 } indexed by x & 3 is something
+ * a compiler can compute instead of load, and then target() has no reference
+ * to the array and there is nothing for klp diff to carry.
+ */
+static const int klp_new_data[4] __attribute__((used)) = { 7, 3, 11, 5 };
+#endif
+
+int target(int x)
+{
+#ifdef PATCHED
+	return x + klp_new_data[x & 3];
+#else
+	return x;
+#endif
+}
tools/objtool/tests/generic/test-new-data.sh new file +27 -0
new file mode 100755
index 0000000..acb68ff
@@ -0,0 +1,27 @@
+#!/bin/bash
+# SPDX-License-Identifier: GPL-2.0
+#
+# Data added by the patch has no counterpart in the running kernel and must be
+# carried into the livepatch.
+
+. "$(dirname "$0")/../lib.sh"
+
+setup
+build_pair new_data.c
+
+# State the premise on both sides.  The array is new in the patched build and
+# absent from the original; if the compiler folded it into the code instead of
+# emitting it, the assertion below would fail without saying why.
+has_input_symbol "$orig_obj" klp_new_data &&
+	fail "fixture put klp_new_data in the original; nothing new to carry"
+has_input_symbol "$patched_obj" klp_new_data ||
+	fail "compiler did not emit klp_new_data; the fixture tests nothing"
+in_relocs "$patched_obj" | grep -q 'klp_new_data' ||
+	fail "target() does not reference klp_new_data; the fixture tests nothing"
+
+run_diff
+
+assert_patched target
+assert_symbol klp_new_data
+
+pass "new data carried into the patch"
author maintainer
#40 lore raw

PATCH v5 14/58 objtool/klp: Add test for newly introduced functions

In reply to Song Liu

From: Puranjay Mohan <[email protected]>

A function added by the patch has no original to correlate against, and still has to be carried into the livepatch or the changed caller ends up referencing something which does not exist.

The helper is noinline so the case survives the optimiser; otherwise the compiler folds it into its only caller and the test covers nothing.

Assisted-by Claude:claude-opus-5
---
 .../tests/generic/fixtures/new_function.c     | 21 +++++++++++++++++++
 .../tests/generic/test-new-function.sh        | 16 ++++++++++++++
 2 files changed, 37 insertions(+)
 create mode 100644 tools/objtool/tests/generic/fixtures/new_function.c
 create mode 100755 tools/objtool/tests/generic/test-new-function.sh
tools/objtool/tests/generic/fixtures/new_function.c new file +21 -0
new file mode 100644
index 000000000000..e7886eaaff3e
@@ -0,0 +1,21 @@
+// SPDX-License-Identifier: GPL-2.0
+/* Function introduced by the patch.  noinline keeps it from being folded. */
+
+static const char __modinfo[]
+	__attribute__((section(".modinfo"), used, aligned(1))) = "\0name=vmlinux";
+
+#ifdef PATCHED
+static __attribute__((noinline)) int klp_new_helper(int x)
+{
+	return x * 7;
+}
+#endif
+
+int target(int x)
+{
+#ifdef PATCHED
+	return klp_new_helper(x);
+#else
+	return x;
+#endif
+}
tools/objtool/tests/generic/test-new-function.sh new file +16 -0
new file mode 100755
index 000000000000..b0b7f6443110
@@ -0,0 +1,16 @@
+#!/bin/bash
+# SPDX-License-Identifier: GPL-2.0
+#
+# A function added by the patch has no original to correlate against and must
+# still be carried into the livepatch.
+
+. "$(dirname "$0")/../lib.sh"
+
+setup
+build_pair new_function.c
+run_diff
+
+assert_patched target
+assert_symbol klp_new_helper
+
+pass "new function carried into the patch with its caller"
Signature · 1 line
2.53.0-Meta
merge bot Applied
#41 lore raw

[tip: objtool/core] objtool/klp: Add test for newly introduced functions

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:     10aedc2ce2edc1a95e83da123ba76ea2eba07480
Gitweb:        https://git.kernel.org/tip/10aedc2ce2edc1a95e83da123ba76ea2eba07480
Author:        Puranjay Mohan <[email protected]>
AuthorDate:    Wed, 16 Sep 2026 11:43:07 -07:00
Committer:     Josh Poimboeuf <[email protected]>
CommitterDate: Wed, 16 Sep 2026 17:13:27 -07:00

objtool/klp: Add test for newly introduced functions

A function added by the patch has no original to correlate against, and still has to be carried into the livepatch or the changed caller ends up referencing something which does not exist.

The helper is noinline so the case survives the optimiser; otherwise the compiler folds it into its only caller and the test covers nothing.

---
 tools/objtool/tests/generic/fixtures/new_function.c | 21 ++++++++++++-
 tools/objtool/tests/generic/test-new-function.sh    | 16 +++++++++-
 2 files changed, 37 insertions(+)
 create mode 100644 tools/objtool/tests/generic/fixtures/new_function.c
 create mode 100755 tools/objtool/tests/generic/test-new-function.sh
tools/objtool/tests/generic/fixtures/new_function.c new file +21 -0
new file mode 100644
index 0000000..e7886ea
@@ -0,0 +1,21 @@
+// SPDX-License-Identifier: GPL-2.0
+/* Function introduced by the patch.  noinline keeps it from being folded. */
+
+static const char __modinfo[]
+	__attribute__((section(".modinfo"), used, aligned(1))) = "\0name=vmlinux";
+
+#ifdef PATCHED
+static __attribute__((noinline)) int klp_new_helper(int x)
+{
+	return x * 7;
+}
+#endif
+
+int target(int x)
+{
+#ifdef PATCHED
+	return klp_new_helper(x);
+#else
+	return x;
+#endif
+}
tools/objtool/tests/generic/test-new-function.sh new file +16 -0
new file mode 100755
index 0000000..b0b7f64
@@ -0,0 +1,16 @@
+#!/bin/bash
+# SPDX-License-Identifier: GPL-2.0
+#
+# A function added by the patch has no original to correlate against and must
+# still be carried into the livepatch.
+
+. "$(dirname "$0")/../lib.sh"
+
+setup
+build_pair new_function.c
+run_diff
+
+assert_patched target
+assert_symbol klp_new_helper
+
+pass "new function carried into the patch with its caller"
merge bot Applied
#42 lore raw

[tip: objtool/core] objtool/klp: Add test for newly introduced functions

In reply to Song Liu
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:     960c3e352bac749c35041d683f32bdde467a2960
Gitweb:        https://git.kernel.org/tip/960c3e352bac749c35041d683f32bdde467a2960
Author:        Puranjay Mohan <[email protected]>
AuthorDate:    Wed, 16 Sep 2026 11:43:07 -07:00
Committer:     Ingo Molnar <[email protected]>
CommitterDate: Mon, 21 Sep 2026 11:02:40 +02:00

objtool/klp: Add test for newly introduced functions

A function added by the patch has no original to correlate against, and still has to be carried into the livepatch or the changed caller ends up referencing something which does not exist.

The helper is noinline so the case survives the optimiser; otherwise the compiler folds it into its only caller and the test covers nothing.

---
 tools/objtool/tests/generic/fixtures/new_function.c | 21 ++++++++++++-
 tools/objtool/tests/generic/test-new-function.sh    | 16 +++++++++-
 2 files changed, 37 insertions(+)
 create mode 100644 tools/objtool/tests/generic/fixtures/new_function.c
 create mode 100755 tools/objtool/tests/generic/test-new-function.sh
tools/objtool/tests/generic/fixtures/new_function.c new file +21 -0
new file mode 100644
index 0000000..e7886ea
@@ -0,0 +1,21 @@
+// SPDX-License-Identifier: GPL-2.0
+/* Function introduced by the patch.  noinline keeps it from being folded. */
+
+static const char __modinfo[]
+	__attribute__((section(".modinfo"), used, aligned(1))) = "\0name=vmlinux";
+
+#ifdef PATCHED
+static __attribute__((noinline)) int klp_new_helper(int x)
+{
+	return x * 7;
+}
+#endif
+
+int target(int x)
+{
+#ifdef PATCHED
+	return klp_new_helper(x);
+#else
+	return x;
+#endif
+}
tools/objtool/tests/generic/test-new-function.sh new file +16 -0
new file mode 100755
index 0000000..b0b7f64
@@ -0,0 +1,16 @@
+#!/bin/bash
+# SPDX-License-Identifier: GPL-2.0
+#
+# A function added by the patch has no original to correlate against and must
+# still be carried into the livepatch.
+
+. "$(dirname "$0")/../lib.sh"
+
+setup
+build_pair new_function.c
+run_diff
+
+assert_patched target
+assert_symbol klp_new_helper
+
+pass "new function carried into the patch with its caller"
author maintainer
#43 lore raw

PATCH v5 15/58 objtool/klp: Add test for static local correlation

In reply to Song Liu

From: Puranjay Mohan <[email protected]>

A static local must be correlated with its original rather than duplicated. The replacement has to reach the existing variable through a klp relocation; a fresh definition would discard whatever state the running kernel accumulated.

Assisted-by Claude:claude-opus-5
---
 .../tests/generic/fixtures/static_local.c     | 17 +++++++++++++
 .../tests/generic/test-static-local.sh        | 24 +++++++++++++++++++
 2 files changed, 41 insertions(+)
 create mode 100644 tools/objtool/tests/generic/fixtures/static_local.c
 create mode 100755 tools/objtool/tests/generic/test-static-local.sh
tools/objtool/tests/generic/fixtures/static_local.c new file +17 -0
new file mode 100644
index 000000000000..f2f025d00a39
@@ -0,0 +1,17 @@
+// SPDX-License-Identifier: GPL-2.0
+/* Static local in a patched function. */
+
+static const char __modinfo[]
+	__attribute__((section(".modinfo"), used, aligned(1))) = "\0name=vmlinux";
+
+int target(int x)
+{
+	static int counter;
+
+	counter += 1;
+#ifdef PATCHED
+	return x + counter + 1;
+#else
+	return x + counter;
+#endif
+}
tools/objtool/tests/generic/test-static-local.sh new file +24 -0
new file mode 100755
index 000000000000..d57efa64dfd9
@@ -0,0 +1,24 @@
+#!/bin/bash
+# SPDX-License-Identifier: GPL-2.0
+#
+# A static local must be correlated with the original, not duplicated: a second
+# copy would discard the state the running kernel accumulated.
+
+. "$(dirname "$0")/../lib.sh"
+
+setup
+build_pair static_local.c
+
+in_symbols orig.o | grep -q 'counter' ||
+	probe_skip "compiler emitted no distinct static local symbol"
+
+run_diff
+assert_patched target
+
+out_symbols | grep -q '\.klp\.sym\..*\.counter' ||
+	fail "static local not referenced through a klp relocation"
+
+out_symbols | grep 'counter' | grep -qvE 'UND|\.klp\.(sym|tombstone)' &&
+	fail "static local was given a fresh definition"
+
+pass "static local correlated rather than duplicated"
Signature · 1 line
2.53.0-Meta
merge bot Applied
#44 lore raw

[tip: objtool/core] objtool/klp: Add test for static local correlation

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:     1267e8ac29f0023ec826838f02c0703a73c42d8e
Gitweb:        https://git.kernel.org/tip/1267e8ac29f0023ec826838f02c0703a73c42d8e
Author:        Puranjay Mohan <[email protected]>
AuthorDate:    Wed, 16 Sep 2026 11:43:08 -07:00
Committer:     Josh Poimboeuf <[email protected]>
CommitterDate: Wed, 16 Sep 2026 17:13:27 -07:00

objtool/klp: Add test for static local correlation

A static local must be correlated with its original rather than duplicated. The replacement has to reach the existing variable through a klp relocation; a fresh definition would discard whatever state the running kernel accumulated.

---
 tools/objtool/tests/generic/fixtures/static_local.c | 17 +++++++++-
 tools/objtool/tests/generic/test-static-local.sh    | 24 ++++++++++++-
 2 files changed, 41 insertions(+)
 create mode 100644 tools/objtool/tests/generic/fixtures/static_local.c
 create mode 100755 tools/objtool/tests/generic/test-static-local.sh
tools/objtool/tests/generic/fixtures/static_local.c new file +17 -0
new file mode 100644
index 0000000..f2f025d
@@ -0,0 +1,17 @@
+// SPDX-License-Identifier: GPL-2.0
+/* Static local in a patched function. */
+
+static const char __modinfo[]
+	__attribute__((section(".modinfo"), used, aligned(1))) = "\0name=vmlinux";
+
+int target(int x)
+{
+	static int counter;
+
+	counter += 1;
+#ifdef PATCHED
+	return x + counter + 1;
+#else
+	return x + counter;
+#endif
+}
tools/objtool/tests/generic/test-static-local.sh new file +24 -0
new file mode 100755
index 0000000..d57efa6
@@ -0,0 +1,24 @@
+#!/bin/bash
+# SPDX-License-Identifier: GPL-2.0
+#
+# A static local must be correlated with the original, not duplicated: a second
+# copy would discard the state the running kernel accumulated.
+
+. "$(dirname "$0")/../lib.sh"
+
+setup
+build_pair static_local.c
+
+in_symbols orig.o | grep -q 'counter' ||
+	probe_skip "compiler emitted no distinct static local symbol"
+
+run_diff
+assert_patched target
+
+out_symbols | grep -q '\.klp\.sym\..*\.counter' ||
+	fail "static local not referenced through a klp relocation"
+
+out_symbols | grep 'counter' | grep -qvE 'UND|\.klp\.(sym|tombstone)' &&
+	fail "static local was given a fresh definition"
+
+pass "static local correlated rather than duplicated"
merge bot Applied
#45 lore raw

[tip: objtool/core] objtool/klp: Add test for static local correlation

In reply to Song Liu
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:     fbb79ff9a6638aeb5b7a5f7db25afd033e6edd96
Gitweb:        https://git.kernel.org/tip/fbb79ff9a6638aeb5b7a5f7db25afd033e6edd96
Author:        Puranjay Mohan <[email protected]>
AuthorDate:    Wed, 16 Sep 2026 11:43:08 -07:00
Committer:     Ingo Molnar <[email protected]>
CommitterDate: Mon, 21 Sep 2026 11:02:47 +02:00

objtool/klp: Add test for static local correlation

A static local must be correlated with its original rather than duplicated. The replacement has to reach the existing variable through a klp relocation; a fresh definition would discard whatever state the running kernel accumulated.

---
 tools/objtool/tests/generic/fixtures/static_local.c | 17 +++++++++-
 tools/objtool/tests/generic/test-static-local.sh    | 24 ++++++++++++-
 2 files changed, 41 insertions(+)
 create mode 100644 tools/objtool/tests/generic/fixtures/static_local.c
 create mode 100755 tools/objtool/tests/generic/test-static-local.sh
tools/objtool/tests/generic/fixtures/static_local.c new file +17 -0
new file mode 100644
index 0000000..f2f025d
@@ -0,0 +1,17 @@
+// SPDX-License-Identifier: GPL-2.0
+/* Static local in a patched function. */
+
+static const char __modinfo[]
+	__attribute__((section(".modinfo"), used, aligned(1))) = "\0name=vmlinux";
+
+int target(int x)
+{
+	static int counter;
+
+	counter += 1;
+#ifdef PATCHED
+	return x + counter + 1;
+#else
+	return x + counter;
+#endif
+}
tools/objtool/tests/generic/test-static-local.sh new file +24 -0
new file mode 100755
index 0000000..d57efa6
@@ -0,0 +1,24 @@
+#!/bin/bash
+# SPDX-License-Identifier: GPL-2.0
+#
+# A static local must be correlated with the original, not duplicated: a second
+# copy would discard the state the running kernel accumulated.
+
+. "$(dirname "$0")/../lib.sh"
+
+setup
+build_pair static_local.c
+
+in_symbols orig.o | grep -q 'counter' ||
+	probe_skip "compiler emitted no distinct static local symbol"
+
+run_diff
+assert_patched target
+
+out_symbols | grep -q '\.klp\.sym\..*\.counter' ||
+	fail "static local not referenced through a klp relocation"
+
+out_symbols | grep 'counter' | grep -qvE 'UND|\.klp\.(sym|tombstone)' &&
+	fail "static local was given a fresh definition"
+
+pass "static local correlated rather than duplicated"
author maintainer
#46 lore raw

PATCH v5 16/58 objtool/klp: Add test for cold function halves

In reply to Song Liu

From: Puranjay Mohan <[email protected]>

The compiler splits unlikely code into a separate foo.cold symbol. Both halves are the same function and both belong in the livepatch: carrying only the hot part leaves the cold path branching into unpatched code.

GCC needs -freorder-blocks-and-partition to split reliably. The flag is probed rather than assumed, and the test skips when the compiler declines to split at all.

Assisted-by Claude:claude-opus-5
---
 .../tests/generic/fixtures/cold_function.c    | 21 ++++++++++
 .../tests/generic/test-cold-function.sh       | 39 +++++++++++++++++++
 2 files changed, 60 insertions(+)
 create mode 100644 tools/objtool/tests/generic/fixtures/cold_function.c
 create mode 100755 tools/objtool/tests/generic/test-cold-function.sh
tools/objtool/tests/generic/fixtures/cold_function.c new file +21 -0
new file mode 100644
index 000000000000..f6d410983ce2
@@ -0,0 +1,21 @@
+// SPDX-License-Identifier: GPL-2.0
+/* Function the compiler may split into a hot part and a foo.cold part. */
+
+static const char __modinfo[]
+	__attribute__((section(".modinfo"), used, aligned(1))) = "\0name=vmlinux";
+
+static void __attribute__((cold, noinline)) slow_path(int x)
+{
+	__asm__ volatile("" :: "r"(x));
+}
+
+int target(int x)
+{
+	if (__builtin_expect(x < 0, 0))
+		slow_path(x);
+#ifdef PATCHED
+	return x + 2;
+#else
+	return x + 1;
+#endif
+}
tools/objtool/tests/generic/test-cold-function.sh new file +39 -0
new file mode 100755
index 000000000000..a02652fe5341
@@ -0,0 +1,39 @@
+#!/bin/bash
+# SPDX-License-Identifier: GPL-2.0
+#
+# Both halves of a split function belong to the patch; carrying only the hot
+# part leaves the cold path branching into unpatched code.
+
+. "$(dirname "$0")/../lib.sh"
+
+# Clang does not split functions into a cold part at all, so there is nothing
+# for this test to look at there.  A given gcc may or may not split, which is a
+# version property rather than a compiler choice -- that stays a probe below.
+gcc_only "clang does not split functions into a cold part"
+
+setup
+
+split_flag=-freorder-blocks-and-partition
+cc_supports "$split_flag" || split_flag=
+
+build_pair cold_function.c $split_flag
+
+# Find what the compiler called the cold half -- target.cold, target.cold.0,
+# depending on version -- and name it exactly from here on.
+cold_sym="$(in_symbols orig.o | awk '$NF ~ /^target\.cold/ { print $NF; exit }')"
+[ -n "$cold_sym" ] ||
+	probe_skip "compiler did not split the function into a cold part"
+
+run_diff
+
+assert_patched target
+# Match the name field exactly, and require it to be defined.  Had the cold
+# half been left behind, the branch to it would appear as an undefined
+# .klp.sym.vmlinux.target.cold,0 -- a different name, which happens to contain
+# this one.  Asking about a column instead of the name would not tell them
+# apart: readelf prints SHN_LIVEPATCH as "OS [0xff20]" and llvm-readelf as
+# "OS[0xff20]", so the fields either side of the name shift between the two.
+out_symbols | awk -v n="$cold_sym" '$NF == n && $(NF - 1) != "UND"' | grep -q . ||
+	fail "cold half ($cold_sym) was not carried into the patch"
+
+pass "cold half carried into the patch with its parent"
Signature · 1 line
2.53.0-Meta
merge bot Applied
#47 lore raw

[tip: objtool/core] objtool/klp: Add test for cold function halves

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:     97f87f3486bfde9829b8e8ae28b2b55ac151045d
Gitweb:        https://git.kernel.org/tip/97f87f3486bfde9829b8e8ae28b2b55ac151045d
Author:        Puranjay Mohan <[email protected]>
AuthorDate:    Wed, 16 Sep 2026 11:43:09 -07:00
Committer:     Josh Poimboeuf <[email protected]>
CommitterDate: Wed, 16 Sep 2026 17:13:27 -07:00

objtool/klp: Add test for cold function halves

The compiler splits unlikely code into a separate foo.cold symbol. Both halves are the same function and both belong in the livepatch: carrying only the hot part leaves the cold path branching into unpatched code.

GCC needs -freorder-blocks-and-partition to split reliably. The flag is probed rather than assumed, and the test skips when the compiler declines to split at all.

---
 tools/objtool/tests/generic/fixtures/cold_function.c | 21 ++++++-
 tools/objtool/tests/generic/test-cold-function.sh    | 39 +++++++++++-
 2 files changed, 60 insertions(+)
 create mode 100644 tools/objtool/tests/generic/fixtures/cold_function.c
 create mode 100755 tools/objtool/tests/generic/test-cold-function.sh
tools/objtool/tests/generic/fixtures/cold_function.c new file +21 -0
new file mode 100644
index 0000000..f6d4109
@@ -0,0 +1,21 @@
+// SPDX-License-Identifier: GPL-2.0
+/* Function the compiler may split into a hot part and a foo.cold part. */
+
+static const char __modinfo[]
+	__attribute__((section(".modinfo"), used, aligned(1))) = "\0name=vmlinux";
+
+static void __attribute__((cold, noinline)) slow_path(int x)
+{
+	__asm__ volatile("" :: "r"(x));
+}
+
+int target(int x)
+{
+	if (__builtin_expect(x < 0, 0))
+		slow_path(x);
+#ifdef PATCHED
+	return x + 2;
+#else
+	return x + 1;
+#endif
+}
tools/objtool/tests/generic/test-cold-function.sh new file +39 -0
new file mode 100755
index 0000000..a02652f
@@ -0,0 +1,39 @@
+#!/bin/bash
+# SPDX-License-Identifier: GPL-2.0
+#
+# Both halves of a split function belong to the patch; carrying only the hot
+# part leaves the cold path branching into unpatched code.
+
+. "$(dirname "$0")/../lib.sh"
+
+# Clang does not split functions into a cold part at all, so there is nothing
+# for this test to look at there.  A given gcc may or may not split, which is a
+# version property rather than a compiler choice -- that stays a probe below.
+gcc_only "clang does not split functions into a cold part"
+
+setup
+
+split_flag=-freorder-blocks-and-partition
+cc_supports "$split_flag" || split_flag=
+
+build_pair cold_function.c $split_flag
+
+# Find what the compiler called the cold half -- target.cold, target.cold.0,
+# depending on version -- and name it exactly from here on.
+cold_sym="$(in_symbols orig.o | awk '$NF ~ /^target\.cold/ { print $NF; exit }')"
+[ -n "$cold_sym" ] ||
+	probe_skip "compiler did not split the function into a cold part"
+
+run_diff
+
+assert_patched target
+# Match the name field exactly, and require it to be defined.  Had the cold
+# half been left behind, the branch to it would appear as an undefined
+# .klp.sym.vmlinux.target.cold,0 -- a different name, which happens to contain
+# this one.  Asking about a column instead of the name would not tell them
+# apart: readelf prints SHN_LIVEPATCH as "OS [0xff20]" and llvm-readelf as
+# "OS[0xff20]", so the fields either side of the name shift between the two.
+out_symbols | awk -v n="$cold_sym" '$NF == n && $(NF - 1) != "UND"' | grep -q . ||
+	fail "cold half ($cold_sym) was not carried into the patch"
+
+pass "cold half carried into the patch with its parent"
merge bot Applied
#48 lore raw

[tip: objtool/core] objtool/klp: Add test for cold function halves

In reply to Song Liu
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:     76e7630d90d0d5ff402e06607662b1f9e34eff6c
Gitweb:        https://git.kernel.org/tip/76e7630d90d0d5ff402e06607662b1f9e34eff6c
Author:        Puranjay Mohan <[email protected]>
AuthorDate:    Wed, 16 Sep 2026 11:43:09 -07:00
Committer:     Ingo Molnar <[email protected]>
CommitterDate: Mon, 21 Sep 2026 11:02:54 +02:00

objtool/klp: Add test for cold function halves

The compiler splits unlikely code into a separate foo.cold symbol. Both halves are the same function and both belong in the livepatch: carrying only the hot part leaves the cold path branching into unpatched code.

GCC needs -freorder-blocks-and-partition to split reliably. The flag is probed rather than assumed, and the test skips when the compiler declines to split at all.

---
 tools/objtool/tests/generic/fixtures/cold_function.c | 21 ++++++-
 tools/objtool/tests/generic/test-cold-function.sh    | 39 +++++++++++-
 2 files changed, 60 insertions(+)
 create mode 100644 tools/objtool/tests/generic/fixtures/cold_function.c
 create mode 100755 tools/objtool/tests/generic/test-cold-function.sh
tools/objtool/tests/generic/fixtures/cold_function.c new file +21 -0
new file mode 100644
index 0000000..f6d4109
@@ -0,0 +1,21 @@
+// SPDX-License-Identifier: GPL-2.0
+/* Function the compiler may split into a hot part and a foo.cold part. */
+
+static const char __modinfo[]
+	__attribute__((section(".modinfo"), used, aligned(1))) = "\0name=vmlinux";
+
+static void __attribute__((cold, noinline)) slow_path(int x)
+{
+	__asm__ volatile("" :: "r"(x));
+}
+
+int target(int x)
+{
+	if (__builtin_expect(x < 0, 0))
+		slow_path(x);
+#ifdef PATCHED
+	return x + 2;
+#else
+	return x + 1;
+#endif
+}
tools/objtool/tests/generic/test-cold-function.sh new file +39 -0
new file mode 100755
index 0000000..a02652f
@@ -0,0 +1,39 @@
+#!/bin/bash
+# SPDX-License-Identifier: GPL-2.0
+#
+# Both halves of a split function belong to the patch; carrying only the hot
+# part leaves the cold path branching into unpatched code.
+
+. "$(dirname "$0")/../lib.sh"
+
+# Clang does not split functions into a cold part at all, so there is nothing
+# for this test to look at there.  A given gcc may or may not split, which is a
+# version property rather than a compiler choice -- that stays a probe below.
+gcc_only "clang does not split functions into a cold part"
+
+setup
+
+split_flag=-freorder-blocks-and-partition
+cc_supports "$split_flag" || split_flag=
+
+build_pair cold_function.c $split_flag
+
+# Find what the compiler called the cold half -- target.cold, target.cold.0,
+# depending on version -- and name it exactly from here on.
+cold_sym="$(in_symbols orig.o | awk '$NF ~ /^target\.cold/ { print $NF; exit }')"
+[ -n "$cold_sym" ] ||
+	probe_skip "compiler did not split the function into a cold part"
+
+run_diff
+
+assert_patched target
+# Match the name field exactly, and require it to be defined.  Had the cold
+# half been left behind, the branch to it would appear as an undefined
+# .klp.sym.vmlinux.target.cold,0 -- a different name, which happens to contain
+# this one.  Asking about a column instead of the name would not tell them
+# apart: readelf prints SHN_LIVEPATCH as "OS [0xff20]" and llvm-readelf as
+# "OS[0xff20]", so the fields either side of the name shift between the two.
+out_symbols | awk -v n="$cold_sym" '$NF == n && $(NF - 1) != "UND"' | grep -q . ||
+	fail "cold half ($cold_sym) was not carried into the patch"
+
+pass "cold half carried into the patch with its parent"
author maintainer
#49 lore raw

PATCH v5 17/58 objtool/klp: Add test for special section extraction

In reply to Song Liu

From: Puranjay Mohan <[email protected]>

create_fake_symbols() gives each special section entry a symbol so entries can be extracted individually. Entries with ANNOTATE_DATA_SPECIAL are handled first; the rest have their boundaries derived from the entry or relocation size.

The second pass has to key off whether the first one created symbols, not off whether the section already has something at offset 0. Clang puts an assembler-local label at the start of .kcfi_traps, and treating that as already handled means nothing is extracted: klp diff still reports the changed function and succeeds, but the special section is missing from the module.

The fixture reproduces the shape without needing CFI or x86.

Assisted-by Claude:claude-opus-5
---
 .../tests/generic/fixtures/special_section.c  | 24 +++++++++++++++++++
 .../tests/generic/test-special-section.sh     | 20 ++++++++++++++++
 2 files changed, 44 insertions(+)
 create mode 100644 tools/objtool/tests/generic/fixtures/special_section.c
 create mode 100755 tools/objtool/tests/generic/test-special-section.sh
tools/objtool/tests/generic/fixtures/special_section.c new file +24 -0
new file mode 100644
index 000000000000..d28c5541e337
@@ -0,0 +1,24 @@
+// SPDX-License-Identifier: GPL-2.0
+/*
+ * Special section entry with no ANNOTATE_DATA_SPECIAL annotation and a local
+ * label at offset 0, the shape Clang produces for .kcfi_traps.
+ */
+
+static const char __modinfo[]
+	__attribute__((section(".modinfo"), used, aligned(1))) = "\0name=vmlinux";
+
+int target(int x)
+{
+	asm volatile(
+		"1:\n\t"
+		".pushsection	.kcfi_traps, \"a\"\n\t"
+		".balign	4\n\t"
+		"trap_marker:\n\t"
+		".long		1b - .\n\t"
+		".popsection\n\t");
+#ifdef PATCHED
+	return x + 2;
+#else
+	return x + 1;
+#endif
+}
tools/objtool/tests/generic/test-special-section.sh new file +20 -0
new file mode 100755
index 000000000000..b6a9139c0062
@@ -0,0 +1,20 @@
+#!/bin/bash
+# SPDX-License-Identifier: GPL-2.0
+#
+# A .kcfi_traps entry belonging to a patched function must be extracted even
+# without ANNOTATE_DATA_SPECIAL and with a local label already at offset 0.
+
+. "$(dirname "$0")/../lib.sh"
+
+setup
+build_pair special_section.c
+
+in_symbols orig.o | grep -q 'trap_marker' ||
+	probe_skip "fixture produced no .kcfi_traps on this arch"
+
+run_diff
+
+assert_patched target
+assert_section ".kcfi_traps"
+
+pass ".kcfi_traps extracted despite a local label at offset 0"
Signature · 1 line
2.53.0-Meta
merge bot Applied
#50 lore raw

[tip: objtool/core] objtool/klp: Add test for special section extraction

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:     51b7456cf2c3c10ba8ff2dc57fbf2e37243302ec
Gitweb:        https://git.kernel.org/tip/51b7456cf2c3c10ba8ff2dc57fbf2e37243302ec
Author:        Puranjay Mohan <[email protected]>
AuthorDate:    Wed, 16 Sep 2026 11:43:10 -07:00
Committer:     Josh Poimboeuf <[email protected]>
CommitterDate: Wed, 16 Sep 2026 17:13:27 -07:00

objtool/klp: Add test for special section extraction

create_fake_symbols() gives each special section entry a symbol so entries can be extracted individually. Entries with ANNOTATE_DATA_SPECIAL are handled first; the rest have their boundaries derived from the entry or relocation size.

The second pass has to key off whether the first one created symbols, not off whether the section already has something at offset 0. Clang puts an assembler-local label at the start of .kcfi_traps, and treating that as already handled means nothing is extracted: klp diff still reports the changed function and succeeds, but the special section is missing from the module.

The fixture reproduces the shape without needing CFI or x86.

---
 tools/objtool/tests/generic/fixtures/special_section.c | 24 +++++++++-
 tools/objtool/tests/generic/test-special-section.sh    | 20 ++++++++-
 2 files changed, 44 insertions(+)
 create mode 100644 tools/objtool/tests/generic/fixtures/special_section.c
 create mode 100755 tools/objtool/tests/generic/test-special-section.sh
tools/objtool/tests/generic/fixtures/special_section.c new file +24 -0
new file mode 100644
index 0000000..d28c554
@@ -0,0 +1,24 @@
+// SPDX-License-Identifier: GPL-2.0
+/*
+ * Special section entry with no ANNOTATE_DATA_SPECIAL annotation and a local
+ * label at offset 0, the shape Clang produces for .kcfi_traps.
+ */
+
+static const char __modinfo[]
+	__attribute__((section(".modinfo"), used, aligned(1))) = "\0name=vmlinux";
+
+int target(int x)
+{
+	asm volatile(
+		"1:\n\t"
+		".pushsection	.kcfi_traps, \"a\"\n\t"
+		".balign	4\n\t"
+		"trap_marker:\n\t"
+		".long		1b - .\n\t"
+		".popsection\n\t");
+#ifdef PATCHED
+	return x + 2;
+#else
+	return x + 1;
+#endif
+}
tools/objtool/tests/generic/test-special-section.sh new file +20 -0
new file mode 100755
index 0000000..b6a9139
@@ -0,0 +1,20 @@
+#!/bin/bash
+# SPDX-License-Identifier: GPL-2.0
+#
+# A .kcfi_traps entry belonging to a patched function must be extracted even
+# without ANNOTATE_DATA_SPECIAL and with a local label already at offset 0.
+
+. "$(dirname "$0")/../lib.sh"
+
+setup
+build_pair special_section.c
+
+in_symbols orig.o | grep -q 'trap_marker' ||
+	probe_skip "fixture produced no .kcfi_traps on this arch"
+
+run_diff
+
+assert_patched target
+assert_section ".kcfi_traps"
+
+pass ".kcfi_traps extracted despite a local label at offset 0"
merge bot Applied
#51 lore raw

[tip: objtool/core] objtool/klp: Add test for special section extraction

In reply to Song Liu
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:     996edd14fb2003461295c8c48e9df7ef373bc492
Gitweb:        https://git.kernel.org/tip/996edd14fb2003461295c8c48e9df7ef373bc492
Author:        Puranjay Mohan <[email protected]>
AuthorDate:    Wed, 16 Sep 2026 11:43:10 -07:00
Committer:     Ingo Molnar <[email protected]>
CommitterDate: Mon, 21 Sep 2026 11:03:00 +02:00

objtool/klp: Add test for special section extraction

create_fake_symbols() gives each special section entry a symbol so entries can be extracted individually. Entries with ANNOTATE_DATA_SPECIAL are handled first; the rest have their boundaries derived from the entry or relocation size.

The second pass has to key off whether the first one created symbols, not off whether the section already has something at offset 0. Clang puts an assembler-local label at the start of .kcfi_traps, and treating that as already handled means nothing is extracted: klp diff still reports the changed function and succeeds, but the special section is missing from the module.

The fixture reproduces the shape without needing CFI or x86.

---
 tools/objtool/tests/generic/fixtures/special_section.c | 24 +++++++++-
 tools/objtool/tests/generic/test-special-section.sh    | 20 ++++++++-
 2 files changed, 44 insertions(+)
 create mode 100644 tools/objtool/tests/generic/fixtures/special_section.c
 create mode 100755 tools/objtool/tests/generic/test-special-section.sh
tools/objtool/tests/generic/fixtures/special_section.c new file +24 -0
new file mode 100644
index 0000000..d28c554
@@ -0,0 +1,24 @@
+// SPDX-License-Identifier: GPL-2.0
+/*
+ * Special section entry with no ANNOTATE_DATA_SPECIAL annotation and a local
+ * label at offset 0, the shape Clang produces for .kcfi_traps.
+ */
+
+static const char __modinfo[]
+	__attribute__((section(".modinfo"), used, aligned(1))) = "\0name=vmlinux";
+
+int target(int x)
+{
+	asm volatile(
+		"1:\n\t"
+		".pushsection	.kcfi_traps, \"a\"\n\t"
+		".balign	4\n\t"
+		"trap_marker:\n\t"
+		".long		1b - .\n\t"
+		".popsection\n\t");
+#ifdef PATCHED
+	return x + 2;
+#else
+	return x + 1;
+#endif
+}
tools/objtool/tests/generic/test-special-section.sh new file +20 -0
new file mode 100755
index 0000000..b6a9139
@@ -0,0 +1,20 @@
+#!/bin/bash
+# SPDX-License-Identifier: GPL-2.0
+#
+# A .kcfi_traps entry belonging to a patched function must be extracted even
+# without ANNOTATE_DATA_SPECIAL and with a local label already at offset 0.
+
+. "$(dirname "$0")/../lib.sh"
+
+setup
+build_pair special_section.c
+
+in_symbols orig.o | grep -q 'trap_marker' ||
+	probe_skip "fixture produced no .kcfi_traps on this arch"
+
+run_diff
+
+assert_patched target
+assert_section ".kcfi_traps"
+
+pass ".kcfi_traps extracted despite a local label at offset 0"
author maintainer
#52 lore raw

PATCH v5 18/58 objtool/klp: Add test for selective special section extraction

In reply to Song Liu

From: Puranjay Mohan <[email protected]>

Two functions contribute entries to one special section but only one is patched. Cloning the neighbouring entry drags in whatever it points at, which is how a livepatch ends up holding relocations against unrelated code.

Assisted-by Claude:claude-opus-5
---
 .../generic/fixtures/special_section_shared.c | 31 +++++++++++++++++++
 .../generic/test-special-section-shared.sh    | 26 ++++++++++++++++
 2 files changed, 57 insertions(+)
 create mode 100644 tools/objtool/tests/generic/fixtures/special_section_shared.c
 create mode 100755 tools/objtool/tests/generic/test-special-section-shared.sh
tools/objtool/tests/generic/fixtures/special_section_shared.c new file +31 -0
new file mode 100644
index 000000000000..f54e24f862c6
@@ -0,0 +1,31 @@
+// SPDX-License-Identifier: GPL-2.0
+/* Two functions contribute to one special section; only one is patched. */
+
+static const char __modinfo[]
+	__attribute__((section(".modinfo"), used, aligned(1))) = "\0name=vmlinux";
+
+int other(int x)
+{
+	asm volatile(
+		"2:\n\t"
+		".pushsection	.kcfi_traps, \"a\"\n\t"
+		".balign	4\n\t"
+		".long		2b - .\n\t"
+		".popsection\n\t");
+	return x * 5;
+}
+
+int target(int x)
+{
+	asm volatile(
+		"1:\n\t"
+		".pushsection	.kcfi_traps, \"a\"\n\t"
+		".balign	4\n\t"
+		".long		1b - .\n\t"
+		".popsection\n\t");
+#ifdef PATCHED
+	return x + 2;
+#else
+	return x + 1;
+#endif
+}
tools/objtool/tests/generic/test-special-section-shared.sh new file +26 -0
new file mode 100755
index 000000000000..05c6110b6aef
@@ -0,0 +1,26 @@
+#!/bin/bash
+# SPDX-License-Identifier: GPL-2.0
+#
+# Only the patched function's special section entry may be extracted.
+
+. "$(dirname "$0")/../lib.sh"
+
+setup
+build_pair special_section_shared.c
+
+has_input_section orig.o .kcfi_traps ||
+	probe_skip "fixture produced no .kcfi_traps on this arch"
+
+run_diff
+
+assert_patched     target
+assert_not_patched other
+assert_section     ".kcfi_traps"
+
+entries="$(out_relocs | awk '/rela\.kcfi_traps/,/^$/' | grep -c 'target')"
+[ "$entries" = 1 ] || fail "expected one .kcfi_traps entry, found $entries"
+
+out_relocs | awk '/rela\.kcfi_traps/,/^$/' | grep -q 'other' &&
+	fail "the untouched function's entry was dragged in"
+
+pass "only the patched function's entry extracted"
Signature · 1 line
2.53.0-Meta
merge bot Applied
#53 lore raw

[tip: objtool/core] objtool/klp: Add test for selective special section extraction

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:     2b77d5104c9b201709a07a58a31a2944dc325da2
Gitweb:        https://git.kernel.org/tip/2b77d5104c9b201709a07a58a31a2944dc325da2
Author:        Puranjay Mohan <[email protected]>
AuthorDate:    Wed, 16 Sep 2026 11:43:11 -07:00
Committer:     Josh Poimboeuf <[email protected]>
CommitterDate: Wed, 16 Sep 2026 17:13:27 -07:00

objtool/klp: Add test for selective special section extraction

Two functions contribute entries to one special section but only one is patched. Cloning the neighbouring entry drags in whatever it points at, which is how a livepatch ends up holding relocations against unrelated code.

---
 tools/objtool/tests/generic/fixtures/special_section_shared.c | 31 +++++++-
 tools/objtool/tests/generic/test-special-section-shared.sh    | 26 ++++++-
 2 files changed, 57 insertions(+)
 create mode 100644 tools/objtool/tests/generic/fixtures/special_section_shared.c
 create mode 100755 tools/objtool/tests/generic/test-special-section-shared.sh
tools/objtool/tests/generic/fixtures/special_section_shared.c new file +31 -0
new file mode 100644
index 0000000..f54e24f
@@ -0,0 +1,31 @@
+// SPDX-License-Identifier: GPL-2.0
+/* Two functions contribute to one special section; only one is patched. */
+
+static const char __modinfo[]
+	__attribute__((section(".modinfo"), used, aligned(1))) = "\0name=vmlinux";
+
+int other(int x)
+{
+	asm volatile(
+		"2:\n\t"
+		".pushsection	.kcfi_traps, \"a\"\n\t"
+		".balign	4\n\t"
+		".long		2b - .\n\t"
+		".popsection\n\t");
+	return x * 5;
+}
+
+int target(int x)
+{
+	asm volatile(
+		"1:\n\t"
+		".pushsection	.kcfi_traps, \"a\"\n\t"
+		".balign	4\n\t"
+		".long		1b - .\n\t"
+		".popsection\n\t");
+#ifdef PATCHED
+	return x + 2;
+#else
+	return x + 1;
+#endif
+}
tools/objtool/tests/generic/test-special-section-shared.sh new file +26 -0
new file mode 100755
index 0000000..05c6110
@@ -0,0 +1,26 @@
+#!/bin/bash
+# SPDX-License-Identifier: GPL-2.0
+#
+# Only the patched function's special section entry may be extracted.
+
+. "$(dirname "$0")/../lib.sh"
+
+setup
+build_pair special_section_shared.c
+
+has_input_section orig.o .kcfi_traps ||
+	probe_skip "fixture produced no .kcfi_traps on this arch"
+
+run_diff
+
+assert_patched     target
+assert_not_patched other
+assert_section     ".kcfi_traps"
+
+entries="$(out_relocs | awk '/rela\.kcfi_traps/,/^$/' | grep -c 'target')"
+[ "$entries" = 1 ] || fail "expected one .kcfi_traps entry, found $entries"
+
+out_relocs | awk '/rela\.kcfi_traps/,/^$/' | grep -q 'other' &&
+	fail "the untouched function's entry was dragged in"
+
+pass "only the patched function's entry extracted"
merge bot Applied
#54 lore raw

[tip: objtool/core] objtool/klp: Add test for selective special section extraction

In reply to Song Liu
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:     229ad17366de138ae8c4492d0c965d93bc848f4c
Gitweb:        https://git.kernel.org/tip/229ad17366de138ae8c4492d0c965d93bc848f4c
Author:        Puranjay Mohan <[email protected]>
AuthorDate:    Wed, 16 Sep 2026 11:43:11 -07:00
Committer:     Ingo Molnar <[email protected]>
CommitterDate: Mon, 21 Sep 2026 11:03:07 +02:00

objtool/klp: Add test for selective special section extraction

Two functions contribute entries to one special section but only one is patched. Cloning the neighbouring entry drags in whatever it points at, which is how a livepatch ends up holding relocations against unrelated code.

---
 tools/objtool/tests/generic/fixtures/special_section_shared.c | 31 +++++++-
 tools/objtool/tests/generic/test-special-section-shared.sh    | 26 ++++++-
 2 files changed, 57 insertions(+)
 create mode 100644 tools/objtool/tests/generic/fixtures/special_section_shared.c
 create mode 100755 tools/objtool/tests/generic/test-special-section-shared.sh
tools/objtool/tests/generic/fixtures/special_section_shared.c new file +31 -0
new file mode 100644
index 0000000..f54e24f
@@ -0,0 +1,31 @@
+// SPDX-License-Identifier: GPL-2.0
+/* Two functions contribute to one special section; only one is patched. */
+
+static const char __modinfo[]
+	__attribute__((section(".modinfo"), used, aligned(1))) = "\0name=vmlinux";
+
+int other(int x)
+{
+	asm volatile(
+		"2:\n\t"
+		".pushsection	.kcfi_traps, \"a\"\n\t"
+		".balign	4\n\t"
+		".long		2b - .\n\t"
+		".popsection\n\t");
+	return x * 5;
+}
+
+int target(int x)
+{
+	asm volatile(
+		"1:\n\t"
+		".pushsection	.kcfi_traps, \"a\"\n\t"
+		".balign	4\n\t"
+		".long		1b - .\n\t"
+		".popsection\n\t");
+#ifdef PATCHED
+	return x + 2;
+#else
+	return x + 1;
+#endif
+}
tools/objtool/tests/generic/test-special-section-shared.sh new file +26 -0
new file mode 100755
index 0000000..05c6110
@@ -0,0 +1,26 @@
+#!/bin/bash
+# SPDX-License-Identifier: GPL-2.0
+#
+# Only the patched function's special section entry may be extracted.
+
+. "$(dirname "$0")/../lib.sh"
+
+setup
+build_pair special_section_shared.c
+
+has_input_section orig.o .kcfi_traps ||
+	probe_skip "fixture produced no .kcfi_traps on this arch"
+
+run_diff
+
+assert_patched     target
+assert_not_patched other
+assert_section     ".kcfi_traps"
+
+entries="$(out_relocs | awk '/rela\.kcfi_traps/,/^$/' | grep -c 'target')"
+[ "$entries" = 1 ] || fail "expected one .kcfi_traps entry, found $entries"
+
+out_relocs | awk '/rela\.kcfi_traps/,/^$/' | grep -q 'other' &&
+	fail "the untouched function's entry was dragged in"
+
+pass "only the patched function's entry extracted"
author maintainer
#55 lore raw

PATCH v5 19/58 objtool/klp: Add test for jump table key relocations

In reply to Song Liu

From: Puranjay Mohan <[email protected]>

A cloned __jump_table entry must keep a relocation in its key slot. objtool parses the table again after klp diff to convert the static branch's scaffold instruction, and an empty slot leaves it unable to do so. The scaffold then stays as emitted and the module trips BUG() in __jump_label_patch() once the key's state differs from its compile-time default.

Check both halves for a vmlinux-owned key: unexported gives a tombstone plus a klp relocation, exported gives an ordinary relocation and no klp machinery.

The fixture defines the key as an STT_OBJECT, which is what the kernel emits. validate_special_section_klp_reloc() ignores anything else, so a fixture using an undefined extern would skip the interesting paths.

Assisted-by Claude:claude-opus-5
---
 .../tests/generic/fixtures/jump_label.c       | 76 +++++++++++++++++++
 .../tests/generic/test-jump-label-key.sh      | 44 +++++++++++
 2 files changed, 120 insertions(+)
 create mode 100644 tools/objtool/tests/generic/fixtures/jump_label.c
 create mode 100755 tools/objtool/tests/generic/test-jump-label-key.sh
tools/objtool/tests/generic/fixtures/jump_label.c new file +76 -0
new file mode 100644
index 000000000000..ecd3c06912af
@@ -0,0 +1,76 @@
+// SPDX-License-Identifier: GPL-2.0
+/*
+ * Static branch in a patched function.  The jump table entry is written out by
+ * hand, mirroring JUMP_TABLE_ENTRY(), so the fixture builds without kernel
+ * headers.  The key is an STT_OBJECT; anything else is ignored by
+ * validate_special_section_klp_reloc().
+ *
+ * MODNAME selects whether the key is taken to belong to vmlinux or a module.
+ *
+ * NEW_KEY puts the whole static branch behind PATCHED, so the patch introduces
+ * one where the original had none -- a different question from patching code
+ * that already has a key, because the __jump_table entry itself is new.
+ *
+ * KEY_NAME renames the key.  Two names are special to
+ * validate_special_section_klp_reloc(): a __tracepoint_* key and the
+ * __UNIQUE_ID_ddebug_* one pr_debug() generates are both unsupported in a
+ * module, but are disabled with a warning rather than rejected, because the
+ * kernel is full of them and refusing outright would make ordinary functions
+ * unpatchable.
+ *
+ * STATIC_KEY makes the key file-local.  That changes the shape of the
+ * relocation rather than the meaning of the code: a reference to a static lands
+ * on the section symbol plus an addend, so the key has to be resolved from the
+ * section before it can be recognised as a key at all.
+ */
+
+#ifndef MODNAME
+#define MODNAME "vmlinux"
+#endif
+
+#ifndef KEY_NAME
+#define KEY_NAME klp_test_key
+#endif
+
+static const char __modinfo[]
+	__attribute__((section(".modinfo"), used, aligned(1))) = "\0name=" MODNAME;
+
+#ifdef STATIC_KEY
+static long KEY_NAME;
+#else
+long KEY_NAME;
+#endif
+
+int target(int x)
+{
+	int r = x;
+
+#if defined(NEW_KEY) && !defined(PATCHED)
+	/* The original has no static branch at all. */
+	return r + 1;
+#else
+	asm goto(
+		"1:	nop\n\t"
+		".pushsection	__jump_table, \"aw\"\n\t"
+		".balign	8\n\t"
+		"912:\n\t"
+		".pushsection	.discard.annotate_data, \"M\", @progbits, 8\n\t"
+		".long		912b - ., 1\n\t"
+		".popsection\n\t"
+		".long		1b - ., %l[l_yes] - .\n\t"
+		".quad		%c0 - .\n\t"
+		".popsection\n\t"
+		: : "i" (&KEY_NAME) : : l_yes);
+
+	r += 1;
+	goto out;
+l_yes:
+	r += 2;
+out:
+#endif
+#ifdef PATCHED
+	return r + 100;
+#else
+	return r;
+#endif
+}
tools/objtool/tests/generic/test-jump-label-key.sh new file +44 -0

44 lines not on this page · raw message

Signature · 1 line
2.53.0-Meta
merge bot Applied
#56 lore raw

[tip: objtool/core] objtool/klp: Add test for jump table key relocations

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:     c521de5718bedac1607a93b74bdf39240ebd4806
Gitweb:        https://git.kernel.org/tip/c521de5718bedac1607a93b74bdf39240ebd4806
Author:        Puranjay Mohan <[email protected]>
AuthorDate:    Wed, 16 Sep 2026 11:43:12 -07:00
Committer:     Josh Poimboeuf <[email protected]>
CommitterDate: Wed, 16 Sep 2026 17:13:27 -07:00

objtool/klp: Add test for jump table key relocations

A cloned __jump_table entry must keep a relocation in its key slot. objtool parses the table again after klp diff to convert the static branch's scaffold instruction, and an empty slot leaves it unable to do so. The scaffold then stays as emitted and the module trips BUG() in __jump_label_patch() once the key's state differs from its compile-time default.

Check both halves for a vmlinux-owned key: unexported gives a tombstone plus a klp relocation, exported gives an ordinary relocation and no klp machinery.

The fixture defines the key as an STT_OBJECT, which is what the kernel emits. validate_special_section_klp_reloc() ignores anything else, so a fixture using an undefined extern would skip the interesting paths.

---
 tools/objtool/tests/generic/fixtures/jump_label.c  | 76 +++++++++++++-
 tools/objtool/tests/generic/test-jump-label-key.sh | 44 ++++++++-
 2 files changed, 120 insertions(+)
 create mode 100644 tools/objtool/tests/generic/fixtures/jump_label.c
 create mode 100755 tools/objtool/tests/generic/test-jump-label-key.sh
tools/objtool/tests/generic/fixtures/jump_label.c new file +76 -0
new file mode 100644
index 0000000..ecd3c06
@@ -0,0 +1,76 @@
+// SPDX-License-Identifier: GPL-2.0
+/*
+ * Static branch in a patched function.  The jump table entry is written out by
+ * hand, mirroring JUMP_TABLE_ENTRY(), so the fixture builds without kernel
+ * headers.  The key is an STT_OBJECT; anything else is ignored by
+ * validate_special_section_klp_reloc().
+ *
+ * MODNAME selects whether the key is taken to belong to vmlinux or a module.
+ *
+ * NEW_KEY puts the whole static branch behind PATCHED, so the patch introduces
+ * one where the original had none -- a different question from patching code
+ * that already has a key, because the __jump_table entry itself is new.
+ *
+ * KEY_NAME renames the key.  Two names are special to
+ * validate_special_section_klp_reloc(): a __tracepoint_* key and the
+ * __UNIQUE_ID_ddebug_* one pr_debug() generates are both unsupported in a
+ * module, but are disabled with a warning rather than rejected, because the
+ * kernel is full of them and refusing outright would make ordinary functions
+ * unpatchable.
+ *
+ * STATIC_KEY makes the key file-local.  That changes the shape of the
+ * relocation rather than the meaning of the code: a reference to a static lands
+ * on the section symbol plus an addend, so the key has to be resolved from the
+ * section before it can be recognised as a key at all.
+ */
+
+#ifndef MODNAME
+#define MODNAME "vmlinux"
+#endif
+
+#ifndef KEY_NAME
+#define KEY_NAME klp_test_key
+#endif
+
+static const char __modinfo[]
+	__attribute__((section(".modinfo"), used, aligned(1))) = "\0name=" MODNAME;
+
+#ifdef STATIC_KEY
+static long KEY_NAME;
+#else
+long KEY_NAME;
+#endif
+
+int target(int x)
+{
+	int r = x;
+
+#if defined(NEW_KEY) && !defined(PATCHED)
+	/* The original has no static branch at all. */
+	return r + 1;
+#else
+	asm goto(
+		"1:	nop\n\t"
+		".pushsection	__jump_table, \"aw\"\n\t"
+		".balign	8\n\t"
+		"912:\n\t"
+		".pushsection	.discard.annotate_data, \"M\", @progbits, 8\n\t"
+		".long		912b - ., 1\n\t"
+		".popsection\n\t"
+		".long		1b - ., %l[l_yes] - .\n\t"
+		".quad		%c0 - .\n\t"
+		".popsection\n\t"
+		: : "i" (&KEY_NAME) : : l_yes);
+
+	r += 1;
+	goto out;
+l_yes:
+	r += 2;
+out:
+#endif
+#ifdef PATCHED
+	return r + 100;
+#else
+	return r;
+#endif
+}
tools/objtool/tests/generic/test-jump-label-key.sh new file +44 -0

44 lines not on this page · raw message

merge bot Applied
#57 lore raw

[tip: objtool/core] objtool/klp: Add test for jump table key relocations

In reply to Song Liu
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:     729bf5310766614efed12b87e8b59a63d2657cb7
Gitweb:        https://git.kernel.org/tip/729bf5310766614efed12b87e8b59a63d2657cb7
Author:        Puranjay Mohan <[email protected]>
AuthorDate:    Wed, 16 Sep 2026 11:43:12 -07:00
Committer:     Ingo Molnar <[email protected]>
CommitterDate: Mon, 21 Sep 2026 11:04:50 +02:00

objtool/klp: Add test for jump table key relocations

A cloned __jump_table entry must keep a relocation in its key slot. objtool parses the table again after klp diff to convert the static branch's scaffold instruction, and an empty slot leaves it unable to do so. The scaffold then stays as emitted and the module trips BUG() in __jump_label_patch() once the key's state differs from its compile-time default.

Check both halves for a vmlinux-owned key: unexported gives a tombstone plus a klp relocation, exported gives an ordinary relocation and no klp machinery.

The fixture defines the key as an STT_OBJECT, which is what the kernel emits. validate_special_section_klp_reloc() ignores anything else, so a fixture using an undefined extern would skip the interesting paths.

---
 tools/objtool/tests/generic/fixtures/jump_label.c  | 76 +++++++++++++-
 tools/objtool/tests/generic/test-jump-label-key.sh | 44 ++++++++-
 2 files changed, 120 insertions(+)
 create mode 100644 tools/objtool/tests/generic/fixtures/jump_label.c
 create mode 100755 tools/objtool/tests/generic/test-jump-label-key.sh
tools/objtool/tests/generic/fixtures/jump_label.c new file +76 -0
new file mode 100644
index 0000000..ecd3c06
@@ -0,0 +1,76 @@
+// SPDX-License-Identifier: GPL-2.0
+/*
+ * Static branch in a patched function.  The jump table entry is written out by
+ * hand, mirroring JUMP_TABLE_ENTRY(), so the fixture builds without kernel
+ * headers.  The key is an STT_OBJECT; anything else is ignored by
+ * validate_special_section_klp_reloc().
+ *
+ * MODNAME selects whether the key is taken to belong to vmlinux or a module.
+ *
+ * NEW_KEY puts the whole static branch behind PATCHED, so the patch introduces
+ * one where the original had none -- a different question from patching code
+ * that already has a key, because the __jump_table entry itself is new.
+ *
+ * KEY_NAME renames the key.  Two names are special to
+ * validate_special_section_klp_reloc(): a __tracepoint_* key and the
+ * __UNIQUE_ID_ddebug_* one pr_debug() generates are both unsupported in a
+ * module, but are disabled with a warning rather than rejected, because the
+ * kernel is full of them and refusing outright would make ordinary functions
+ * unpatchable.
+ *
+ * STATIC_KEY makes the key file-local.  That changes the shape of the
+ * relocation rather than the meaning of the code: a reference to a static lands
+ * on the section symbol plus an addend, so the key has to be resolved from the
+ * section before it can be recognised as a key at all.
+ */
+
+#ifndef MODNAME
+#define MODNAME "vmlinux"
+#endif
+
+#ifndef KEY_NAME
+#define KEY_NAME klp_test_key
+#endif
+
+static const char __modinfo[]
+	__attribute__((section(".modinfo"), used, aligned(1))) = "\0name=" MODNAME;
+
+#ifdef STATIC_KEY
+static long KEY_NAME;
+#else
+long KEY_NAME;
+#endif
+
+int target(int x)
+{
+	int r = x;
+
+#if defined(NEW_KEY) && !defined(PATCHED)
+	/* The original has no static branch at all. */
+	return r + 1;
+#else
+	asm goto(
+		"1:	nop\n\t"
+		".pushsection	__jump_table, \"aw\"\n\t"
+		".balign	8\n\t"
+		"912:\n\t"
+		".pushsection	.discard.annotate_data, \"M\", @progbits, 8\n\t"
+		".long		912b - ., 1\n\t"
+		".popsection\n\t"
+		".long		1b - ., %l[l_yes] - .\n\t"
+		".quad		%c0 - .\n\t"
+		".popsection\n\t"
+		: : "i" (&KEY_NAME) : : l_yes);
+
+	r += 1;
+	goto out;
+l_yes:
+	r += 2;
+out:
+#endif
+#ifdef PATCHED
+	return r + 100;
+#else
+	return r;
+#endif
+}
tools/objtool/tests/generic/test-jump-label-key.sh new file +44 -0

44 lines not on this page · raw message

author maintainer
#58 lore raw

PATCH v5 20/58 objtool/klp: Add test for rejecting module-owned static branch keys

In reply to Song Liu

From: Puranjay Mohan <[email protected]>

A static branch key belonging to a module cannot be reached with a klp
relocation: the patch may be applied after that module's static branch init has run, which corrupts the code. Emitting one anyway produces a module which loads and then BUG()s the first time the key changes state, so klp diff has to refuse it.

The fixture differs from the accepted case only in the module name recorded in .modinfo.

Assisted-by Claude:claude-opus-5
---
 .../generic/test-jump-label-module-key.sh     | 22 +++++++++++++++++++
 1 file changed, 22 insertions(+)
 create mode 100755 tools/objtool/tests/generic/test-jump-label-module-key.sh
tools/objtool/tests/generic/test-jump-label-module-key.sh new file +22 -0
new file mode 100755
index 000000000000..7c3f82cdd3c1
@@ -0,0 +1,22 @@
+#!/bin/bash
+# SPDX-License-Identifier: GPL-2.0
+#
+# A static branch key owned by a module cannot be reached with a klp
+# relocation and must be rejected.
+
+. "$(dirname "$0")/../lib.sh"
+
+setup
+build_pair jump_label.c -DMODNAME='"klp_testmod"'
+
+has_input_section orig.o __jump_table ||
+	probe_skip "fixture produced no __jump_table on this arch"
+
+run_diff 255
+
+diff_log | grep -q 'unsupported static branch key klp_test_key' ||
+	fail "expected rejection, got: $(diff_log | tail -1)"
+[ -e "$workdir/out.o" ] &&
+	fail "output object produced for a rejected input"
+
+pass "module-owned static branch key rejected"
Signature · 1 line
2.53.0-Meta
merge bot Applied
#59 lore raw

[tip: objtool/core] objtool/klp: Add test for rejecting module-owned static branch keys

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:     7be49a35ce975ef9f2ccf3aa0dc4cf92ce244918
Gitweb:        https://git.kernel.org/tip/7be49a35ce975ef9f2ccf3aa0dc4cf92ce244918
Author:        Puranjay Mohan <[email protected]>
AuthorDate:    Wed, 16 Sep 2026 11:43:13 -07:00
Committer:     Josh Poimboeuf <[email protected]>
CommitterDate: Wed, 16 Sep 2026 17:13:27 -07:00

objtool/klp: Add test for rejecting module-owned static branch keys

A static branch key belonging to a module cannot be reached with a klp
relocation: the patch may be applied after that module's static branch init has run, which corrupts the code. Emitting one anyway produces a module which loads and then BUG()s the first time the key changes state, so klp diff has to refuse it.

The fixture differs from the accepted case only in the module name recorded in .modinfo.

---
 tools/objtool/tests/generic/test-jump-label-module-key.sh | 22 +++++++-
 1 file changed, 22 insertions(+)
 create mode 100755 tools/objtool/tests/generic/test-jump-label-module-key.sh
tools/objtool/tests/generic/test-jump-label-module-key.sh new file +22 -0
new file mode 100755
index 0000000..7c3f82c
@@ -0,0 +1,22 @@
+#!/bin/bash
+# SPDX-License-Identifier: GPL-2.0
+#
+# A static branch key owned by a module cannot be reached with a klp
+# relocation and must be rejected.
+
+. "$(dirname "$0")/../lib.sh"
+
+setup
+build_pair jump_label.c -DMODNAME='"klp_testmod"'
+
+has_input_section orig.o __jump_table ||
+	probe_skip "fixture produced no __jump_table on this arch"
+
+run_diff 255
+
+diff_log | grep -q 'unsupported static branch key klp_test_key' ||
+	fail "expected rejection, got: $(diff_log | tail -1)"
+[ -e "$workdir/out.o" ] &&
+	fail "output object produced for a rejected input"
+
+pass "module-owned static branch key rejected"
merge bot Applied
#60 lore raw

[tip: objtool/core] objtool/klp: Add test for rejecting module-owned static branch keys

In reply to Song Liu
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:     bd5e5fc7d6456e0669f47a3e10150ad05ae9d249
Gitweb:        https://git.kernel.org/tip/bd5e5fc7d6456e0669f47a3e10150ad05ae9d249
Author:        Puranjay Mohan <[email protected]>
AuthorDate:    Wed, 16 Sep 2026 11:43:13 -07:00
Committer:     Ingo Molnar <[email protected]>
CommitterDate: Mon, 21 Sep 2026 11:04:58 +02:00

objtool/klp: Add test for rejecting module-owned static branch keys

A static branch key belonging to a module cannot be reached with a klp
relocation: the patch may be applied after that module's static branch init has run, which corrupts the code. Emitting one anyway produces a module which loads and then BUG()s the first time the key changes state, so klp diff has to refuse it.

The fixture differs from the accepted case only in the module name recorded in .modinfo.

---
 tools/objtool/tests/generic/test-jump-label-module-key.sh | 22 +++++++-
 1 file changed, 22 insertions(+)
 create mode 100755 tools/objtool/tests/generic/test-jump-label-module-key.sh
tools/objtool/tests/generic/test-jump-label-module-key.sh new file +22 -0
new file mode 100755
index 0000000..7c3f82c
@@ -0,0 +1,22 @@
+#!/bin/bash
+# SPDX-License-Identifier: GPL-2.0
+#
+# A static branch key owned by a module cannot be reached with a klp
+# relocation and must be rejected.
+
+. "$(dirname "$0")/../lib.sh"
+
+setup
+build_pair jump_label.c -DMODNAME='"klp_testmod"'
+
+has_input_section orig.o __jump_table ||
+	probe_skip "fixture produced no __jump_table on this arch"
+
+run_diff 255
+
+diff_log | grep -q 'unsupported static branch key klp_test_key' ||
+	fail "expected rejection, got: $(diff_log | tail -1)"
+[ -e "$workdir/out.o" ] &&
+	fail "output object produced for a rejected input"
+
+pass "module-owned static branch key rejected"
author maintainer
#61 lore raw

PATCH v5 21/58 objtool/klp: Add test for rejecting module-owned static call keys

In reply to Song Liu

From: Puranjay Mohan <[email protected]>

Static calls carry the same constraint as static branches. Check that a vmlinux-owned key is accepted and a module-owned one is refused.

Assisted-by Claude:claude-opus-5
---
 .../tests/generic/fixtures/static_call.c      | 59 +++++++++++++++++++
 .../generic/test-static-call-module-key.sh    | 36 +++++++++++
 2 files changed, 95 insertions(+)
 create mode 100644 tools/objtool/tests/generic/fixtures/static_call.c
 create mode 100755 tools/objtool/tests/generic/test-static-call-module-key.sh
tools/objtool/tests/generic/fixtures/static_call.c new file +59 -0
new file mode 100644
index 000000000000..4a0c4c25321e
@@ -0,0 +1,59 @@
+// SPDX-License-Identifier: GPL-2.0
+/*
+ * Static call site in a patched function, laid out by hand as for
+ * jump_label.c.  MODNAME selects whether the key belongs to vmlinux or a
+ * module.
+ *
+ * objtool's check pass would emit the site, and klp-write-tests.txt says to
+ * let it.  Not here: it does not emit the ANNOTATE_DATA_SPECIAL describing
+ * the entry boundaries -- in the kernel that comes from the static_call
+ * macros -- and NO_ANNOTATE below has to be able to take it away.  A fixture
+ * which varies the annotation has to write the entry that goes with it.
+ *
+ * NO_ANNOTATE drops the ANNOTATE_DATA_SPECIAL block from the patched build,
+ * leaving .static_call_sites with no annotation to describe its entry
+ * boundaries.  The section carries no entsize either, so klp diff has to fall
+ * back on the annotations it can still see -- and when the patched object is
+ * the only one that lost them, the two sides disagree about how the section is
+ * divided up.
+ *
+ * NEW_CALL puts the call site behind PATCHED, so the patch introduces one
+ * where the original had none.  The .static_call_sites entry is then new, with
+ * nothing in the original to correlate it against.
+ */
+
+#ifndef MODNAME
+#define MODNAME "vmlinux"
+#endif
+
+static const char __modinfo[]
+	__attribute__((section(".modinfo"), used, aligned(1))) = "\0name=" MODNAME;
+
+long __SCK__klp_test_call;
+
+int target(int x)
+{
+#if defined(NEW_CALL) && !defined(PATCHED)
+	/* The original has no static call at all. */
+	return x + 1;
+#else
+	__asm__ volatile(
+		"1:	nop\n\t"
+		".pushsection	.static_call_sites, \"aw\"\n\t"
+		".balign	8\n\t"
+		"912:\n\t"
+#if !(defined(PATCHED) && defined(NO_ANNOTATE))
+		".pushsection	.discard.annotate_data, \"M\", @progbits, 8\n\t"
+		".long		912b - ., 1\n\t"
+		".popsection\n\t"
+#endif
+		".long		1b - ., %c0 - .\n\t"
+		".popsection\n\t"
+		:: "i" (&__SCK__klp_test_call));
+#endif
+#ifdef PATCHED
+	return x + 2;
+#else
+	return x + 1;
+#endif
+}
tools/objtool/tests/generic/test-static-call-module-key.sh new file +36 -0
new file mode 100755
index 000000000000..260c4af72e05
@@ -0,0 +1,36 @@
+#!/bin/bash
+# SPDX-License-Identifier: GPL-2.0
+#
+# As for static branches, a static call key owned by a module must be rejected
+# while a vmlinux-owned one is accepted.
+
+. "$(dirname "$0")/../lib.sh"
+
+setup
+build_pair static_call.c
+
+has_input_section orig.o .static_call_sites ||
+	probe_skip "fixture produced no .static_call_sites on this arch"
+
+run_diff
+assert_patched target
+
+# The accepted half has to show the entry was carried, not just that the
+# function was: dropping the section silently would leave the patched call
+# unregistered, and "target was cloned" cannot tell the two apart.
+assert_section .static_call_sites
+assert_reloc_sym .static_call_sites target
+
+rm -f "$workdir/out.o"
+build_pair static_call.c -DMODNAME='"klp_testmod"'
+run_diff 255
+
+diff_log | grep -q 'unsupported static call key __SCK__klp_test_call' ||
+	fail "expected rejection, got: $(diff_log | tail -1)"
+
+# A rejection has to leave nothing behind.  out.o was removed above, so
+# anything here was written by the run which was supposed to refuse.
+[ -e "$workdir/out.o" ] &&
+	fail "output object produced for a rejected input"
+
+pass "module-owned static call key rejected, vmlinux-owned accepted"
Signature · 1 line
2.53.0-Meta
merge bot Applied
#62 lore raw

[tip: objtool/core] objtool/klp: Add test for rejecting module-owned static call keys

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:     902ccc30b888d61427a2b518ee342ae4e8449276
Gitweb:        https://git.kernel.org/tip/902ccc30b888d61427a2b518ee342ae4e8449276
Author:        Puranjay Mohan <[email protected]>
AuthorDate:    Wed, 16 Sep 2026 11:43:14 -07:00
Committer:     Josh Poimboeuf <[email protected]>
CommitterDate: Wed, 16 Sep 2026 17:13:28 -07:00

objtool/klp: Add test for rejecting module-owned static call keys

Static calls carry the same constraint as static branches. Check that a vmlinux-owned key is accepted and a module-owned one is refused.

---
 tools/objtool/tests/generic/fixtures/static_call.c         | 59 +++++++-
 tools/objtool/tests/generic/test-static-call-module-key.sh | 36 ++++-
 2 files changed, 95 insertions(+)
 create mode 100644 tools/objtool/tests/generic/fixtures/static_call.c
 create mode 100755 tools/objtool/tests/generic/test-static-call-module-key.sh
tools/objtool/tests/generic/fixtures/static_call.c new file +59 -0
new file mode 100644
index 0000000..4a0c4c2
@@ -0,0 +1,59 @@
+// SPDX-License-Identifier: GPL-2.0
+/*
+ * Static call site in a patched function, laid out by hand as for
+ * jump_label.c.  MODNAME selects whether the key belongs to vmlinux or a
+ * module.
+ *
+ * objtool's check pass would emit the site, and klp-write-tests.txt says to
+ * let it.  Not here: it does not emit the ANNOTATE_DATA_SPECIAL describing
+ * the entry boundaries -- in the kernel that comes from the static_call
+ * macros -- and NO_ANNOTATE below has to be able to take it away.  A fixture
+ * which varies the annotation has to write the entry that goes with it.
+ *
+ * NO_ANNOTATE drops the ANNOTATE_DATA_SPECIAL block from the patched build,
+ * leaving .static_call_sites with no annotation to describe its entry
+ * boundaries.  The section carries no entsize either, so klp diff has to fall
+ * back on the annotations it can still see -- and when the patched object is
+ * the only one that lost them, the two sides disagree about how the section is
+ * divided up.
+ *
+ * NEW_CALL puts the call site behind PATCHED, so the patch introduces one
+ * where the original had none.  The .static_call_sites entry is then new, with
+ * nothing in the original to correlate it against.
+ */
+
+#ifndef MODNAME
+#define MODNAME "vmlinux"
+#endif
+
+static const char __modinfo[]
+	__attribute__((section(".modinfo"), used, aligned(1))) = "\0name=" MODNAME;
+
+long __SCK__klp_test_call;
+
+int target(int x)
+{
+#if defined(NEW_CALL) && !defined(PATCHED)
+	/* The original has no static call at all. */
+	return x + 1;
+#else
+	__asm__ volatile(
+		"1:	nop\n\t"
+		".pushsection	.static_call_sites, \"aw\"\n\t"
+		".balign	8\n\t"
+		"912:\n\t"
+#if !(defined(PATCHED) && defined(NO_ANNOTATE))
+		".pushsection	.discard.annotate_data, \"M\", @progbits, 8\n\t"
+		".long		912b - ., 1\n\t"
+		".popsection\n\t"
+#endif
+		".long		1b - ., %c0 - .\n\t"
+		".popsection\n\t"
+		:: "i" (&__SCK__klp_test_call));
+#endif
+#ifdef PATCHED
+	return x + 2;
+#else
+	return x + 1;
+#endif
+}
tools/objtool/tests/generic/test-static-call-module-key.sh new file +36 -0
new file mode 100755
index 0000000..260c4af
@@ -0,0 +1,36 @@
+#!/bin/bash
+# SPDX-License-Identifier: GPL-2.0
+#
+# As for static branches, a static call key owned by a module must be rejected
+# while a vmlinux-owned one is accepted.
+
+. "$(dirname "$0")/../lib.sh"
+
+setup
+build_pair static_call.c
+
+has_input_section orig.o .static_call_sites ||
+	probe_skip "fixture produced no .static_call_sites on this arch"
+
+run_diff
+assert_patched target
+
+# The accepted half has to show the entry was carried, not just that the
+# function was: dropping the section silently would leave the patched call
+# unregistered, and "target was cloned" cannot tell the two apart.
+assert_section .static_call_sites
+assert_reloc_sym .static_call_sites target
+
+rm -f "$workdir/out.o"
+build_pair static_call.c -DMODNAME='"klp_testmod"'
+run_diff 255
+
+diff_log | grep -q 'unsupported static call key __SCK__klp_test_call' ||
+	fail "expected rejection, got: $(diff_log | tail -1)"
+
+# A rejection has to leave nothing behind.  out.o was removed above, so
+# anything here was written by the run which was supposed to refuse.
+[ -e "$workdir/out.o" ] &&
+	fail "output object produced for a rejected input"
+
+pass "module-owned static call key rejected, vmlinux-owned accepted"
merge bot Applied
#63 lore raw

[tip: objtool/core] objtool/klp: Add test for rejecting module-owned static call keys

In reply to Song Liu
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:     93d298f097a41cf1cd0a167abd664f2e90020a44
Gitweb:        https://git.kernel.org/tip/93d298f097a41cf1cd0a167abd664f2e90020a44
Author:        Puranjay Mohan <[email protected]>
AuthorDate:    Wed, 16 Sep 2026 11:43:14 -07:00
Committer:     Ingo Molnar <[email protected]>
CommitterDate: Mon, 21 Sep 2026 11:05:04 +02:00

objtool/klp: Add test for rejecting module-owned static call keys

Static calls carry the same constraint as static branches. Check that a vmlinux-owned key is accepted and a module-owned one is refused.

---
 tools/objtool/tests/generic/fixtures/static_call.c         | 59 +++++++-
 tools/objtool/tests/generic/test-static-call-module-key.sh | 36 ++++-
 2 files changed, 95 insertions(+)
 create mode 100644 tools/objtool/tests/generic/fixtures/static_call.c
 create mode 100755 tools/objtool/tests/generic/test-static-call-module-key.sh
tools/objtool/tests/generic/fixtures/static_call.c new file +59 -0
new file mode 100644
index 0000000..4a0c4c2
@@ -0,0 +1,59 @@
+// SPDX-License-Identifier: GPL-2.0
+/*
+ * Static call site in a patched function, laid out by hand as for
+ * jump_label.c.  MODNAME selects whether the key belongs to vmlinux or a
+ * module.
+ *
+ * objtool's check pass would emit the site, and klp-write-tests.txt says to
+ * let it.  Not here: it does not emit the ANNOTATE_DATA_SPECIAL describing
+ * the entry boundaries -- in the kernel that comes from the static_call
+ * macros -- and NO_ANNOTATE below has to be able to take it away.  A fixture
+ * which varies the annotation has to write the entry that goes with it.
+ *
+ * NO_ANNOTATE drops the ANNOTATE_DATA_SPECIAL block from the patched build,
+ * leaving .static_call_sites with no annotation to describe its entry
+ * boundaries.  The section carries no entsize either, so klp diff has to fall
+ * back on the annotations it can still see -- and when the patched object is
+ * the only one that lost them, the two sides disagree about how the section is
+ * divided up.
+ *
+ * NEW_CALL puts the call site behind PATCHED, so the patch introduces one
+ * where the original had none.  The .static_call_sites entry is then new, with
+ * nothing in the original to correlate it against.
+ */
+
+#ifndef MODNAME
+#define MODNAME "vmlinux"
+#endif
+
+static const char __modinfo[]
+	__attribute__((section(".modinfo"), used, aligned(1))) = "\0name=" MODNAME;
+
+long __SCK__klp_test_call;
+
+int target(int x)
+{
+#if defined(NEW_CALL) && !defined(PATCHED)
+	/* The original has no static call at all. */
+	return x + 1;
+#else
+	__asm__ volatile(
+		"1:	nop\n\t"
+		".pushsection	.static_call_sites, \"aw\"\n\t"
+		".balign	8\n\t"
+		"912:\n\t"
+#if !(defined(PATCHED) && defined(NO_ANNOTATE))
+		".pushsection	.discard.annotate_data, \"M\", @progbits, 8\n\t"
+		".long		912b - ., 1\n\t"
+		".popsection\n\t"
+#endif
+		".long		1b - ., %c0 - .\n\t"
+		".popsection\n\t"
+		:: "i" (&__SCK__klp_test_call));
+#endif
+#ifdef PATCHED
+	return x + 2;
+#else
+	return x + 1;
+#endif
+}
tools/objtool/tests/generic/test-static-call-module-key.sh new file +36 -0
new file mode 100755
index 0000000..260c4af
@@ -0,0 +1,36 @@
+#!/bin/bash
+# SPDX-License-Identifier: GPL-2.0
+#
+# As for static branches, a static call key owned by a module must be rejected
+# while a vmlinux-owned one is accepted.
+
+. "$(dirname "$0")/../lib.sh"
+
+setup
+build_pair static_call.c
+
+has_input_section orig.o .static_call_sites ||
+	probe_skip "fixture produced no .static_call_sites on this arch"
+
+run_diff
+assert_patched target
+
+# The accepted half has to show the entry was carried, not just that the
+# function was: dropping the section silently would leave the patched call
+# unregistered, and "target was cloned" cannot tell the two apart.
+assert_section .static_call_sites
+assert_reloc_sym .static_call_sites target
+
+rm -f "$workdir/out.o"
+build_pair static_call.c -DMODNAME='"klp_testmod"'
+run_diff 255
+
+diff_log | grep -q 'unsupported static call key __SCK__klp_test_call' ||
+	fail "expected rejection, got: $(diff_log | tail -1)"
+
+# A rejection has to leave nothing behind.  out.o was removed above, so
+# anything here was written by the run which was supposed to refuse.
+[ -e "$workdir/out.o" ] &&
+	fail "output object produced for a rejected input"
+
+pass "module-owned static call key rejected, vmlinux-owned accepted"
author maintainer
#64 lore raw

PATCH v5 22/58 objtool/klp: Add test for symids in discarded sections

In reply to Song Liu

From: Puranjay Mohan <[email protected]>

.klp.symid records duplicate-named locals so klp diff can work out their sympos. Symbols in sections the vmlinux link throws away have to be left out, or the table references symbols which no longer exist and the link fails:

__exitcall_foo' referenced in section .klp.symid' of vmlinux.o:
defined in discarded section `.exitcall.exit' of vmlinux.o

Two translation units are compiled from one fixture and partially linked so the result has duplicate locals, which symid_needed() requires. One duplicate is in a live section and one in .exitcall.exit.

Checking the live duplicate as well keeps the test honest: it would otherwise pass just as happily if symid generation stopped working entirely.

Assisted-by Claude:claude-opus-5
---
 .../tests/generic/fixtures/symid_discarded.c  | 25 +++++++++++
 .../tests/generic/test-symid-discarded.sh     | 44 +++++++++++++++++++
 2 files changed, 69 insertions(+)
 create mode 100644 tools/objtool/tests/generic/fixtures/symid_discarded.c
 create mode 100755 tools/objtool/tests/generic/test-symid-discarded.sh
tools/objtool/tests/generic/fixtures/symid_discarded.c new file +25 -0
new file mode 100644
index 000000000000..573cc2d4474b
@@ -0,0 +1,25 @@
+// SPDX-License-Identifier: GPL-2.0
+/*
+ * Compiled twice and partially linked so the result has duplicate locals,
+ * which is what symid_needed() requires.  dup_normal is in a live section,
+ * dup_discarded in one the vmlinux link throws away.  DISCARDED_SEC selects
+ * which discarded section, since there is more than one and each was its own
+ * bug.
+ */
+
+#ifndef DISCARDED_SEC
+#define DISCARDED_SEC ".exitcall.exit"
+#endif
+
+static const char __modinfo[]
+	__attribute__((section(".modinfo"), used, aligned(1))) = "\0name=vmlinux";
+
+static int dup_normal = 1;
+
+static void *dup_discarded
+	__attribute__((section(DISCARDED_SEC), used)) = &dup_normal;
+
+int FUNC_NAME(void)
+{
+	return dup_normal + (dup_discarded != (void *)0);
+}
tools/objtool/tests/generic/test-symid-discarded.sh new file +44 -0

44 lines not on this page · raw message

Signature · 1 line
2.53.0-Meta
merge bot Applied
#65 lore raw

[tip: objtool/core] objtool/klp: Add test for symids in discarded sections

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:     9e0b518e549b531c849d6b1cdf3725c8c503ca80
Gitweb:        https://git.kernel.org/tip/9e0b518e549b531c849d6b1cdf3725c8c503ca80
Author:        Puranjay Mohan <[email protected]>
AuthorDate:    Wed, 16 Sep 2026 11:43:15 -07:00
Committer:     Josh Poimboeuf <[email protected]>
CommitterDate: Wed, 16 Sep 2026 17:13:28 -07:00

objtool/klp: Add test for symids in discarded sections

.klp.symid records duplicate-named locals so klp diff can work out their sympos. Symbols in sections the vmlinux link throws away have to be left out, or the table references symbols which no longer exist and the link fails:

__exitcall_foo' referenced in section .klp.symid' of vmlinux.o:
defined in discarded section `.exitcall.exit' of vmlinux.o

Two translation units are compiled from one fixture and partially linked so the result has duplicate locals, which symid_needed() requires. One duplicate is in a live section and one in .exitcall.exit.

Checking the live duplicate as well keeps the test honest: it would otherwise pass just as happily if symid generation stopped working entirely.

---
 tools/objtool/tests/generic/fixtures/symid_discarded.c | 25 +++++-
 tools/objtool/tests/generic/test-symid-discarded.sh    | 44 +++++++++-
 2 files changed, 69 insertions(+)
 create mode 100644 tools/objtool/tests/generic/fixtures/symid_discarded.c
 create mode 100755 tools/objtool/tests/generic/test-symid-discarded.sh
tools/objtool/tests/generic/fixtures/symid_discarded.c new file +25 -0
new file mode 100644
index 0000000..573cc2d
@@ -0,0 +1,25 @@
+// SPDX-License-Identifier: GPL-2.0
+/*
+ * Compiled twice and partially linked so the result has duplicate locals,
+ * which is what symid_needed() requires.  dup_normal is in a live section,
+ * dup_discarded in one the vmlinux link throws away.  DISCARDED_SEC selects
+ * which discarded section, since there is more than one and each was its own
+ * bug.
+ */
+
+#ifndef DISCARDED_SEC
+#define DISCARDED_SEC ".exitcall.exit"
+#endif
+
+static const char __modinfo[]
+	__attribute__((section(".modinfo"), used, aligned(1))) = "\0name=vmlinux";
+
+static int dup_normal = 1;
+
+static void *dup_discarded
+	__attribute__((section(DISCARDED_SEC), used)) = &dup_normal;
+
+int FUNC_NAME(void)
+{
+	return dup_normal + (dup_discarded != (void *)0);
+}
tools/objtool/tests/generic/test-symid-discarded.sh new file +44 -0

44 lines not on this page · raw message

merge bot Applied
#66 lore raw

[tip: objtool/core] objtool/klp: Add test for symids in discarded sections

In reply to Song Liu
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:     e018004ab8fa4c68155da976125ed8645c075383
Gitweb:        https://git.kernel.org/tip/e018004ab8fa4c68155da976125ed8645c075383
Author:        Puranjay Mohan <[email protected]>
AuthorDate:    Wed, 16 Sep 2026 11:43:15 -07:00
Committer:     Ingo Molnar <[email protected]>
CommitterDate: Mon, 21 Sep 2026 11:05:13 +02:00

objtool/klp: Add test for symids in discarded sections

.klp.symid records duplicate-named locals so klp diff can work out their sympos. Symbols in sections the vmlinux link throws away have to be left out, or the table references symbols which no longer exist and the link fails:

__exitcall_foo' referenced in section .klp.symid' of vmlinux.o:
defined in discarded section `.exitcall.exit' of vmlinux.o

Two translation units are compiled from one fixture and partially linked so the result has duplicate locals, which symid_needed() requires. One duplicate is in a live section and one in .exitcall.exit.

Checking the live duplicate as well keeps the test honest: it would otherwise pass just as happily if symid generation stopped working entirely.

---
 tools/objtool/tests/generic/fixtures/symid_discarded.c | 25 +++++-
 tools/objtool/tests/generic/test-symid-discarded.sh    | 44 +++++++++-
 2 files changed, 69 insertions(+)
 create mode 100644 tools/objtool/tests/generic/fixtures/symid_discarded.c
 create mode 100755 tools/objtool/tests/generic/test-symid-discarded.sh
tools/objtool/tests/generic/fixtures/symid_discarded.c new file +25 -0
new file mode 100644
index 0000000..573cc2d
@@ -0,0 +1,25 @@
+// SPDX-License-Identifier: GPL-2.0
+/*
+ * Compiled twice and partially linked so the result has duplicate locals,
+ * which is what symid_needed() requires.  dup_normal is in a live section,
+ * dup_discarded in one the vmlinux link throws away.  DISCARDED_SEC selects
+ * which discarded section, since there is more than one and each was its own
+ * bug.
+ */
+
+#ifndef DISCARDED_SEC
+#define DISCARDED_SEC ".exitcall.exit"
+#endif
+
+static const char __modinfo[]
+	__attribute__((section(".modinfo"), used, aligned(1))) = "\0name=vmlinux";
+
+static int dup_normal = 1;
+
+static void *dup_discarded
+	__attribute__((section(DISCARDED_SEC), used)) = &dup_normal;
+
+int FUNC_NAME(void)
+{
+	return dup_normal + (dup_discarded != (void *)0);
+}
tools/objtool/tests/generic/test-symid-discarded.sh new file +44 -0

44 lines not on this page · raw message

author maintainer
#67 lore raw

PATCH v5 23/58 objtool/klp: Add test for rejecting references to init code/data

In reply to Song Liu

From: Puranjay Mohan <[email protected]>

Init code and data are freed once boot finishes, so a klp relocation against them can never resolve.

Assisted-by Claude:claude-opus-5
---
 .../tests/generic/fixtures/init_reference.c   | 17 +++++++++++
 .../tests/generic/test-init-reference.sh      | 29 +++++++++++++++++++
 2 files changed, 46 insertions(+)
 create mode 100644 tools/objtool/tests/generic/fixtures/init_reference.c
 create mode 100755 tools/objtool/tests/generic/test-init-reference.sh
tools/objtool/tests/generic/fixtures/init_reference.c new file +17 -0
new file mode 100644
index 000000000000..9e59bdf708d3
@@ -0,0 +1,17 @@
+// SPDX-License-Identifier: GPL-2.0
+/* Patched function referencing data in an .init section. */
+
+static const char __modinfo[]
+	__attribute__((section(".modinfo"), used, aligned(1))) = "\0name=vmlinux";
+
+/* volatile so the read cannot be folded into a constant, leaving no reference */
+static volatile int init_only __attribute__((section(".init.data"), used)) = 5;
+
+int target(int x)
+{
+#ifdef PATCHED
+	return x + init_only + 1;
+#else
+	return x + init_only;
+#endif
+}
tools/objtool/tests/generic/test-init-reference.sh new file +29 -0
new file mode 100755
index 000000000000..921cf493cd79
@@ -0,0 +1,29 @@
+#!/bin/bash
+# SPDX-License-Identifier: GPL-2.0
+#
+# Init code and data are freed after boot, so a klp relocation against them can
+# never resolve.  Such a patch must be rejected.
+
+. "$(dirname "$0")/../lib.sh"
+
+setup
+build_pair init_reference.c
+
+# The rejection can only happen if the patched build really does reference the
+# init symbol.  The fixture makes init_only volatile so the read cannot be
+# folded away, and this checks that it worked: without a relocation klp diff
+# would succeed, and the failure below would read as a missing check rather
+# than as a fixture which stopped posing the question.
+# Either spelling will do.  A file-local variable is reached through its
+# section symbol -- .init.data -- and a global one by name; which of the two
+# the compiler picks is its business, and the reference is what matters.
+in_relocs "$patched_obj" |
+	awk '$5 == ".init.data" || $5 == "init_only"' | grep -q . ||
+	fail "patched object has no reference into .init.data; the fixture tests nothing"
+
+run_diff 255
+
+diff_log | grep -q "can't patch or reference init code/data" ||
+	fail "expected rejection, got: $(diff_log | tail -1)"
+
+pass "reference to init data rejected"
Signature · 1 line
2.53.0-Meta
merge bot Applied
#68 lore raw

[tip: objtool/core] objtool/klp: Add test for rejecting references to init code/data

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:     f5e03560bd71922003384a2e24154b1d08bead1c
Gitweb:        https://git.kernel.org/tip/f5e03560bd71922003384a2e24154b1d08bead1c
Author:        Puranjay Mohan <[email protected]>
AuthorDate:    Wed, 16 Sep 2026 11:43:16 -07:00
Committer:     Josh Poimboeuf <[email protected]>
CommitterDate: Wed, 16 Sep 2026 17:13:28 -07:00

objtool/klp: Add test for rejecting references to init code/data

Init code and data are freed once boot finishes, so a klp relocation against them can never resolve.

---
 tools/objtool/tests/generic/fixtures/init_reference.c | 17 ++++++-
 tools/objtool/tests/generic/test-init-reference.sh    | 29 ++++++++++-
 2 files changed, 46 insertions(+)
 create mode 100644 tools/objtool/tests/generic/fixtures/init_reference.c
 create mode 100755 tools/objtool/tests/generic/test-init-reference.sh
tools/objtool/tests/generic/fixtures/init_reference.c new file +17 -0
new file mode 100644
index 0000000..9e59bdf
@@ -0,0 +1,17 @@
+// SPDX-License-Identifier: GPL-2.0
+/* Patched function referencing data in an .init section. */
+
+static const char __modinfo[]
+	__attribute__((section(".modinfo"), used, aligned(1))) = "\0name=vmlinux";
+
+/* volatile so the read cannot be folded into a constant, leaving no reference */
+static volatile int init_only __attribute__((section(".init.data"), used)) = 5;
+
+int target(int x)
+{
+#ifdef PATCHED
+	return x + init_only + 1;
+#else
+	return x + init_only;
+#endif
+}
tools/objtool/tests/generic/test-init-reference.sh new file +29 -0
new file mode 100755
index 0000000..921cf49
@@ -0,0 +1,29 @@
+#!/bin/bash
+# SPDX-License-Identifier: GPL-2.0
+#
+# Init code and data are freed after boot, so a klp relocation against them can
+# never resolve.  Such a patch must be rejected.
+
+. "$(dirname "$0")/../lib.sh"
+
+setup
+build_pair init_reference.c
+
+# The rejection can only happen if the patched build really does reference the
+# init symbol.  The fixture makes init_only volatile so the read cannot be
+# folded away, and this checks that it worked: without a relocation klp diff
+# would succeed, and the failure below would read as a missing check rather
+# than as a fixture which stopped posing the question.
+# Either spelling will do.  A file-local variable is reached through its
+# section symbol -- .init.data -- and a global one by name; which of the two
+# the compiler picks is its business, and the reference is what matters.
+in_relocs "$patched_obj" |
+	awk '$5 == ".init.data" || $5 == "init_only"' | grep -q . ||
+	fail "patched object has no reference into .init.data; the fixture tests nothing"
+
+run_diff 255
+
+diff_log | grep -q "can't patch or reference init code/data" ||
+	fail "expected rejection, got: $(diff_log | tail -1)"
+
+pass "reference to init data rejected"
merge bot Applied
#69 lore raw

[tip: objtool/core] objtool/klp: Add test for rejecting references to init code/data

In reply to Song Liu
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:     d6f2548ec3508fac9ad0f2a7d6f4783f9f9cd119
Gitweb:        https://git.kernel.org/tip/d6f2548ec3508fac9ad0f2a7d6f4783f9f9cd119
Author:        Puranjay Mohan <[email protected]>
AuthorDate:    Wed, 16 Sep 2026 11:43:16 -07:00
Committer:     Ingo Molnar <[email protected]>
CommitterDate: Mon, 21 Sep 2026 11:05:20 +02:00

objtool/klp: Add test for rejecting references to init code/data

Init code and data are freed once boot finishes, so a klp relocation against them can never resolve.

---
 tools/objtool/tests/generic/fixtures/init_reference.c | 17 ++++++-
 tools/objtool/tests/generic/test-init-reference.sh    | 29 ++++++++++-
 2 files changed, 46 insertions(+)
 create mode 100644 tools/objtool/tests/generic/fixtures/init_reference.c
 create mode 100755 tools/objtool/tests/generic/test-init-reference.sh
tools/objtool/tests/generic/fixtures/init_reference.c new file +17 -0
new file mode 100644
index 0000000..9e59bdf
@@ -0,0 +1,17 @@
+// SPDX-License-Identifier: GPL-2.0
+/* Patched function referencing data in an .init section. */
+
+static const char __modinfo[]
+	__attribute__((section(".modinfo"), used, aligned(1))) = "\0name=vmlinux";
+
+/* volatile so the read cannot be folded into a constant, leaving no reference */
+static volatile int init_only __attribute__((section(".init.data"), used)) = 5;
+
+int target(int x)
+{
+#ifdef PATCHED
+	return x + init_only + 1;
+#else
+	return x + init_only;
+#endif
+}
tools/objtool/tests/generic/test-init-reference.sh new file +29 -0
new file mode 100755
index 0000000..921cf49
@@ -0,0 +1,29 @@
+#!/bin/bash
+# SPDX-License-Identifier: GPL-2.0
+#
+# Init code and data are freed after boot, so a klp relocation against them can
+# never resolve.  Such a patch must be rejected.
+
+. "$(dirname "$0")/../lib.sh"
+
+setup
+build_pair init_reference.c
+
+# The rejection can only happen if the patched build really does reference the
+# init symbol.  The fixture makes init_only volatile so the read cannot be
+# folded away, and this checks that it worked: without a relocation klp diff
+# would succeed, and the failure below would read as a missing check rather
+# than as a fixture which stopped posing the question.
+# Either spelling will do.  A file-local variable is reached through its
+# section symbol -- .init.data -- and a global one by name; which of the two
+# the compiler picks is its business, and the reference is what matters.
+in_relocs "$patched_obj" |
+	awk '$5 == ".init.data" || $5 == "init_only"' | grep -q . ||
+	fail "patched object has no reference into .init.data; the fixture tests nothing"
+
+run_diff 255
+
+diff_log | grep -q "can't patch or reference init code/data" ||
+	fail "expected rejection, got: $(diff_log | tail -1)"
+
+pass "reference to init data rejected"
author maintainer
#70 lore raw

PATCH v5 24/58 objtool/klp: Add test for correlation across ThinLTO name mangling

In reply to Song Liu

From: Puranjay Mohan <[email protected]>

ThinLTO promotes the file-local symbols an imported function touches, renaming them name.llvm.<hash>. The hash is content derived, so it changes whenever the module does:

original: counter.llvm.13663304415433785070
patched: counter.llvm.10543383937958011340

Correlating the two objects therefore requires demangling the suffix; matching raw names would see two unrelated symbols and treat the variable as new.

The resulting klp relocation also has to name the original symbol, since that is the one in the running kernel's kallsyms. Naming the patched build's symbol produces a relocation which can never be resolved.

ThinLTO is a clang feature, so the test declares itself clang-only. It also needs an lld from the same LLVM release as $CC; a mismatched pair fails with "Invalid summary version", which reads like a broken test rather than a broken environment, so probe for a working lld and skip if there is none.

Assisted-by Claude:claude-opus-5
---
 .../tests/generic/fixtures/thinlto_local.c    | 39 +++++++++++++++
 .../tests/generic/test-thinlto-local.sh       | 48 +++++++++++++++++++
 2 files changed, 87 insertions(+)
 create mode 100644 tools/objtool/tests/generic/fixtures/thinlto_local.c
 create mode 100755 tools/objtool/tests/generic/test-thinlto-local.sh
tools/objtool/tests/generic/fixtures/thinlto_local.c new file +39 -0
new file mode 100644
index 000000000000..fe9f9e6bf44f
@@ -0,0 +1,39 @@
+// SPDX-License-Identifier: GPL-2.0
+/*
+ * Two translation units (TU_B selects the second) linked with ThinLTO.
+ * Importing bump() promotes the file-local counter, renaming it
+ * counter.llvm.<hash>.  The hash is content derived, so it differs between the
+ * original and patched builds.
+ */
+
+#ifdef TU_B
+
+extern int bump(void);
+
+int other_entry(void)
+{
+	return bump() + bump();
+}
+
+#else
+
+static const char __modinfo[]
+	__attribute__((section(".modinfo"), used, aligned(1))) = "\0name=vmlinux";
+
+static int counter;
+
+int bump(void)
+{
+	return ++counter;
+}
+
+int target(void)
+{
+#ifdef PATCHED
+	return counter + 1;
+#else
+	return counter;
+#endif
+}
+
+#endif
tools/objtool/tests/generic/test-thinlto-local.sh new file +48 -0

48 lines not on this page · raw message

Signature · 1 line
2.53.0-Meta
merge bot Applied
#71 lore raw

[tip: objtool/core] objtool/klp: Add test for correlation across ThinLTO name mangling

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:     c374c48c2d3bf0ee4fb755dab8bcd12097d28cda
Gitweb:        https://git.kernel.org/tip/c374c48c2d3bf0ee4fb755dab8bcd12097d28cda
Author:        Puranjay Mohan <[email protected]>
AuthorDate:    Wed, 16 Sep 2026 11:43:17 -07:00
Committer:     Josh Poimboeuf <[email protected]>
CommitterDate: Wed, 16 Sep 2026 17:13:28 -07:00

objtool/klp: Add test for correlation across ThinLTO name mangling

ThinLTO promotes the file-local symbols an imported function touches, renaming them name.llvm.<hash>. The hash is content derived, so it changes whenever the module does:

original: counter.llvm.13663304415433785070
patched: counter.llvm.10543383937958011340

Correlating the two objects therefore requires demangling the suffix; matching raw names would see two unrelated symbols and treat the variable as new.

The resulting klp relocation also has to name the original symbol, since that is the one in the running kernel's kallsyms. Naming the patched build's symbol produces a relocation which can never be resolved.

ThinLTO is a clang feature, so the test declares itself clang-only. It also needs an lld from the same LLVM release as $CC; a mismatched pair fails with "Invalid summary version", which reads like a broken test rather than a broken environment, so probe for a working lld and skip if there is none.

---
 tools/objtool/tests/generic/fixtures/thinlto_local.c | 39 +++++++++-
 tools/objtool/tests/generic/test-thinlto-local.sh    | 48 +++++++++++-
 2 files changed, 87 insertions(+)
 create mode 100644 tools/objtool/tests/generic/fixtures/thinlto_local.c
 create mode 100755 tools/objtool/tests/generic/test-thinlto-local.sh
tools/objtool/tests/generic/fixtures/thinlto_local.c new file +39 -0
new file mode 100644
index 0000000..fe9f9e6
@@ -0,0 +1,39 @@
+// SPDX-License-Identifier: GPL-2.0
+/*
+ * Two translation units (TU_B selects the second) linked with ThinLTO.
+ * Importing bump() promotes the file-local counter, renaming it
+ * counter.llvm.<hash>.  The hash is content derived, so it differs between the
+ * original and patched builds.
+ */
+
+#ifdef TU_B
+
+extern int bump(void);
+
+int other_entry(void)
+{
+	return bump() + bump();
+}
+
+#else
+
+static const char __modinfo[]
+	__attribute__((section(".modinfo"), used, aligned(1))) = "\0name=vmlinux";
+
+static int counter;
+
+int bump(void)
+{
+	return ++counter;
+}
+
+int target(void)
+{
+#ifdef PATCHED
+	return counter + 1;
+#else
+	return counter;
+#endif
+}
+
+#endif
tools/objtool/tests/generic/test-thinlto-local.sh new file +48 -0

48 lines not on this page · raw message

merge bot Applied
#72 lore raw

[tip: objtool/core] objtool/klp: Add test for correlation across ThinLTO name mangling

In reply to Song Liu
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:     7fd24723f1601340ee09bca93989bd1fb4515783
Gitweb:        https://git.kernel.org/tip/7fd24723f1601340ee09bca93989bd1fb4515783
Author:        Puranjay Mohan <[email protected]>
AuthorDate:    Wed, 16 Sep 2026 11:43:17 -07:00
Committer:     Ingo Molnar <[email protected]>
CommitterDate: Mon, 21 Sep 2026 11:05:27 +02:00

objtool/klp: Add test for correlation across ThinLTO name mangling

ThinLTO promotes the file-local symbols an imported function touches, renaming them name.llvm.<hash>. The hash is content derived, so it changes whenever the module does:

original: counter.llvm.13663304415433785070
patched: counter.llvm.10543383937958011340

Correlating the two objects therefore requires demangling the suffix; matching raw names would see two unrelated symbols and treat the variable as new.

The resulting klp relocation also has to name the original symbol, since that is the one in the running kernel's kallsyms. Naming the patched build's symbol produces a relocation which can never be resolved.

ThinLTO is a clang feature, so the test declares itself clang-only. It also needs an lld from the same LLVM release as $CC; a mismatched pair fails with "Invalid summary version", which reads like a broken test rather than a broken environment, so probe for a working lld and skip if there is none.

---
 tools/objtool/tests/generic/fixtures/thinlto_local.c | 39 +++++++++-
 tools/objtool/tests/generic/test-thinlto-local.sh    | 48 +++++++++++-
 2 files changed, 87 insertions(+)
 create mode 100644 tools/objtool/tests/generic/fixtures/thinlto_local.c
 create mode 100755 tools/objtool/tests/generic/test-thinlto-local.sh
tools/objtool/tests/generic/fixtures/thinlto_local.c new file +39 -0
new file mode 100644
index 0000000..fe9f9e6
@@ -0,0 +1,39 @@
+// SPDX-License-Identifier: GPL-2.0
+/*
+ * Two translation units (TU_B selects the second) linked with ThinLTO.
+ * Importing bump() promotes the file-local counter, renaming it
+ * counter.llvm.<hash>.  The hash is content derived, so it differs between the
+ * original and patched builds.
+ */
+
+#ifdef TU_B
+
+extern int bump(void);
+
+int other_entry(void)
+{
+	return bump() + bump();
+}
+
+#else
+
+static const char __modinfo[]
+	__attribute__((section(".modinfo"), used, aligned(1))) = "\0name=vmlinux";
+
+static int counter;
+
+int bump(void)
+{
+	return ++counter;
+}
+
+int target(void)
+{
+#ifdef PATCHED
+	return counter + 1;
+#else
+	return counter;
+#endif
+}
+
+#endif
tools/objtool/tests/generic/test-thinlto-local.sh new file +48 -0

48 lines not on this page · raw message

author maintainer
#73 lore raw

PATCH v5 25/58 objtool/klp: Add test for objects without .modinfo

In reply to Song Liu

From: Puranjay Mohan <[email protected]>

The module name recorded in .modinfo ends up in the livepatch's klp_object, and also decides whether a static branch key counts as belonging to vmlinux or to a module. An object without one cannot be diffed.

Assisted-by Claude:claude-opus-5
---
 .../objtool/tests/generic/fixtures/no_modinfo.c  | 11 +++++++++++
 .../tests/generic/test-missing-modinfo.sh        | 16 ++++++++++++++++
 2 files changed, 27 insertions(+)
 create mode 100644 tools/objtool/tests/generic/fixtures/no_modinfo.c
 create mode 100755 tools/objtool/tests/generic/test-missing-modinfo.sh
tools/objtool/tests/generic/fixtures/no_modinfo.c new file +11 -0
new file mode 100644
index 000000000000..e46374702b1a
@@ -0,0 +1,11 @@
+// SPDX-License-Identifier: GPL-2.0
+/* Deliberately has no .modinfo section. */
+
+int target(int x)
+{
+#ifdef PATCHED
+	return x + 2;
+#else
+	return x + 1;
+#endif
+}
tools/objtool/tests/generic/test-missing-modinfo.sh new file +16 -0
new file mode 100755
index 000000000000..6f242f7eb756
@@ -0,0 +1,16 @@
+#!/bin/bash
+# SPDX-License-Identifier: GPL-2.0
+#
+# The module name in .modinfo ends up in the livepatch's klp_object, so an
+# object without one cannot be diffed.
+
+. "$(dirname "$0")/../lib.sh"
+
+setup
+build_pair no_modinfo.c
+run_diff 255
+
+diff_log | grep -q 'modinfo' ||
+	fail "expected a complaint about .modinfo, got: $(diff_log | tail -1)"
+
+pass "object without .modinfo rejected"
Signature · 1 line
2.53.0-Meta
merge bot Applied
#74 lore raw

[tip: objtool/core] objtool/klp: Add test for objects without .modinfo

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:     6e9105c21abde36acc9d48a5e037cc3ac1d78bf1
Gitweb:        https://git.kernel.org/tip/6e9105c21abde36acc9d48a5e037cc3ac1d78bf1
Author:        Puranjay Mohan <[email protected]>
AuthorDate:    Wed, 16 Sep 2026 11:43:18 -07:00
Committer:     Josh Poimboeuf <[email protected]>
CommitterDate: Wed, 16 Sep 2026 17:13:28 -07:00

objtool/klp: Add test for objects without .modinfo

The module name recorded in .modinfo ends up in the livepatch's klp_object, and also decides whether a static branch key counts as belonging to vmlinux or to a module. An object without one cannot be diffed.

---
 tools/objtool/tests/generic/fixtures/no_modinfo.c   | 11 ++++++++-
 tools/objtool/tests/generic/test-missing-modinfo.sh | 16 ++++++++++++-
 2 files changed, 27 insertions(+)
 create mode 100644 tools/objtool/tests/generic/fixtures/no_modinfo.c
 create mode 100755 tools/objtool/tests/generic/test-missing-modinfo.sh
tools/objtool/tests/generic/fixtures/no_modinfo.c new file +11 -0
new file mode 100644
index 0000000..e463747
@@ -0,0 +1,11 @@
+// SPDX-License-Identifier: GPL-2.0
+/* Deliberately has no .modinfo section. */
+
+int target(int x)
+{
+#ifdef PATCHED
+	return x + 2;
+#else
+	return x + 1;
+#endif
+}
tools/objtool/tests/generic/test-missing-modinfo.sh new file +16 -0
new file mode 100755
index 0000000..6f242f7
@@ -0,0 +1,16 @@
+#!/bin/bash
+# SPDX-License-Identifier: GPL-2.0
+#
+# The module name in .modinfo ends up in the livepatch's klp_object, so an
+# object without one cannot be diffed.
+
+. "$(dirname "$0")/../lib.sh"
+
+setup
+build_pair no_modinfo.c
+run_diff 255
+
+diff_log | grep -q 'modinfo' ||
+	fail "expected a complaint about .modinfo, got: $(diff_log | tail -1)"
+
+pass "object without .modinfo rejected"
merge bot Applied
#75 lore raw

[tip: objtool/core] objtool/klp: Add test for objects without .modinfo

In reply to Song Liu
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:     050a0c53a6c6009be329c7034d7a4d22ea146b12
Gitweb:        https://git.kernel.org/tip/050a0c53a6c6009be329c7034d7a4d22ea146b12
Author:        Puranjay Mohan <[email protected]>
AuthorDate:    Wed, 16 Sep 2026 11:43:18 -07:00
Committer:     Ingo Molnar <[email protected]>
CommitterDate: Mon, 21 Sep 2026 11:05:34 +02:00

objtool/klp: Add test for objects without .modinfo

The module name recorded in .modinfo ends up in the livepatch's klp_object, and also decides whether a static branch key counts as belonging to vmlinux or to a module. An object without one cannot be diffed.

---
 tools/objtool/tests/generic/fixtures/no_modinfo.c   | 11 ++++++++-
 tools/objtool/tests/generic/test-missing-modinfo.sh | 16 ++++++++++++-
 2 files changed, 27 insertions(+)
 create mode 100644 tools/objtool/tests/generic/fixtures/no_modinfo.c
 create mode 100755 tools/objtool/tests/generic/test-missing-modinfo.sh
tools/objtool/tests/generic/fixtures/no_modinfo.c new file +11 -0
new file mode 100644
index 0000000..e463747
@@ -0,0 +1,11 @@
+// SPDX-License-Identifier: GPL-2.0
+/* Deliberately has no .modinfo section. */
+
+int target(int x)
+{
+#ifdef PATCHED
+	return x + 2;
+#else
+	return x + 1;
+#endif
+}
tools/objtool/tests/generic/test-missing-modinfo.sh new file +16 -0
new file mode 100755
index 0000000..6f242f7
@@ -0,0 +1,16 @@
+#!/bin/bash
+# SPDX-License-Identifier: GPL-2.0
+#
+# The module name in .modinfo ends up in the livepatch's klp_object, so an
+# object without one cannot be diffed.
+
+. "$(dirname "$0")/../lib.sh"
+
+setup
+build_pair no_modinfo.c
+run_diff 255
+
+diff_log | grep -q 'modinfo' ||
+	fail "expected a complaint about .modinfo, got: $(diff_log | tail -1)"
+
+pass "object without .modinfo rejected"
author maintainer
#76 lore raw

PATCH v5 26/58 objtool/klp: Add test for unchecksummed input

In reply to Song Liu

From: Puranjay Mohan <[email protected]>

klp diff decides what changed by comparing the per-function checksums klp checksum records in .discard.sym_checksum. Handed an object which was never checksummed it has to say so; silently concluding that nothing changed would be the worst available answer.

Assisted-by Claude:claude-opus-5
---
 .../tests/generic/test-missing-checksum.sh     | 18 ++++++++++++++++++
 1 file changed, 18 insertions(+)
 create mode 100755 tools/objtool/tests/generic/test-missing-checksum.sh
tools/objtool/tests/generic/test-missing-checksum.sh new file +18 -0
new file mode 100755
index 000000000000..89a05b1869ed
@@ -0,0 +1,18 @@
+#!/bin/bash
+# SPDX-License-Identifier: GPL-2.0
+#
+# Without .discard.sym_checksum there is nothing to compare; concluding that
+# nothing changed would be worse than failing.
+
+. "$(dirname "$0")/../lib.sh"
+
+setup
+build_pair basic.c
+
+( cd "$workdir" && "$OBJTOOL" klp diff orig.o patched.o out.o ) \
+	> "$workdir/diff.log" 2>&1 && fail "klp diff accepted an unchecksummed object"
+
+grep -q 'sym_checksum' "$workdir/diff.log" ||
+	fail "expected a complaint about the checksum section, got: $(tail -1 "$workdir/diff.log")"
+
+pass "unchecksummed input rejected"
Signature · 1 line
2.53.0-Meta
merge bot Applied
#77 lore raw

[tip: objtool/core] objtool/klp: Add test for unchecksummed input

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:     ce31e66cbb9dd05685afb1236d1d71a513a96c91
Gitweb:        https://git.kernel.org/tip/ce31e66cbb9dd05685afb1236d1d71a513a96c91
Author:        Puranjay Mohan <[email protected]>
AuthorDate:    Wed, 16 Sep 2026 11:43:19 -07:00
Committer:     Josh Poimboeuf <[email protected]>
CommitterDate: Wed, 16 Sep 2026 17:13:28 -07:00

objtool/klp: Add test for unchecksummed input

klp diff decides what changed by comparing the per-function checksums klp checksum records in .discard.sym_checksum. Handed an object which was never checksummed it has to say so; silently concluding that nothing changed would be the worst available answer.

---
 tools/objtool/tests/generic/test-missing-checksum.sh | 18 +++++++++++-
 1 file changed, 18 insertions(+)
 create mode 100755 tools/objtool/tests/generic/test-missing-checksum.sh
tools/objtool/tests/generic/test-missing-checksum.sh new file +18 -0
new file mode 100755
index 0000000..89a05b1
@@ -0,0 +1,18 @@
+#!/bin/bash
+# SPDX-License-Identifier: GPL-2.0
+#
+# Without .discard.sym_checksum there is nothing to compare; concluding that
+# nothing changed would be worse than failing.
+
+. "$(dirname "$0")/../lib.sh"
+
+setup
+build_pair basic.c
+
+( cd "$workdir" && "$OBJTOOL" klp diff orig.o patched.o out.o ) \
+	> "$workdir/diff.log" 2>&1 && fail "klp diff accepted an unchecksummed object"
+
+grep -q 'sym_checksum' "$workdir/diff.log" ||
+	fail "expected a complaint about the checksum section, got: $(tail -1 "$workdir/diff.log")"
+
+pass "unchecksummed input rejected"
merge bot Applied
#78 lore raw

[tip: objtool/core] objtool/klp: Add test for unchecksummed input

In reply to Song Liu
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:     1ecf11530c16252dca835c9bc9133f73f5225ee4
Gitweb:        https://git.kernel.org/tip/1ecf11530c16252dca835c9bc9133f73f5225ee4
Author:        Puranjay Mohan <[email protected]>
AuthorDate:    Wed, 16 Sep 2026 11:43:19 -07:00
Committer:     Ingo Molnar <[email protected]>
CommitterDate: Mon, 21 Sep 2026 11:05:41 +02:00

objtool/klp: Add test for unchecksummed input

klp diff decides what changed by comparing the per-function checksums klp checksum records in .discard.sym_checksum. Handed an object which was never checksummed it has to say so; silently concluding that nothing changed would be the worst available answer.

---
 tools/objtool/tests/generic/test-missing-checksum.sh | 18 +++++++++++-
 1 file changed, 18 insertions(+)
 create mode 100755 tools/objtool/tests/generic/test-missing-checksum.sh
tools/objtool/tests/generic/test-missing-checksum.sh new file +18 -0
new file mode 100755
index 0000000..89a05b1
@@ -0,0 +1,18 @@
+#!/bin/bash
+# SPDX-License-Identifier: GPL-2.0
+#
+# Without .discard.sym_checksum there is nothing to compare; concluding that
+# nothing changed would be worse than failing.
+
+. "$(dirname "$0")/../lib.sh"
+
+setup
+build_pair basic.c
+
+( cd "$workdir" && "$OBJTOOL" klp diff orig.o patched.o out.o ) \
+	> "$workdir/diff.log" 2>&1 && fail "klp diff accepted an unchecksummed object"
+
+grep -q 'sym_checksum' "$workdir/diff.log" ||
+	fail "expected a complaint about the checksum section, got: $(tail -1 "$workdir/diff.log")"
+
+pass "unchecksummed input rejected"
author maintainer
#79 lore raw

PATCH v5 27/58 objtool/klp: Add klp diff and post-link regression tests

In reply to Song Liu

Five tests covering behaviour the harness could reach but nothing exercised. Each was verified to fail against the code it guards, by reverting the fix or sabotaging the exact line; where a first attempt passed against broken code, the fixture was wrong and was rebuilt.

  post-link                    first coverage of the subcommand at all
  local-vs-export              local symbols must not match exports
  symvers-parse-error          Module.symvers parse error line numbers
  checksum-debug               the --debug-checksum format klp-build reads
  function-removal             the "no correlation" path

local-vs-export tests the behavior of commit 86a697572c62 ("objtool/klp:
Don't match local symbols against exports"), and symvers-parse-error that of commit 51c1de134863 ("objtool/klp: Fix line numbers in Module.symvers parse errors").

Assisted-by Claude:claude-opus-5
---
 .../tests/generic/fixtures/function_removal.c | 25 ++++++++++
 .../tests/generic/test-checksum-debug.sh      | 49 +++++++++++++++++++
 .../tests/generic/test-function-removal.sh    | 34 +++++++++++++
 .../tests/generic/test-local-vs-export.sh     | 32 ++++++++++++
 tools/objtool/tests/generic/test-post-link.sh | 42 ++++++++++++++++
 .../tests/generic/test-symvers-parse-error.sh | 23 +++++++++
 6 files changed, 205 insertions(+)
 create mode 100644 tools/objtool/tests/generic/fixtures/function_removal.c
 create mode 100755 tools/objtool/tests/generic/test-checksum-debug.sh
 create mode 100755 tools/objtool/tests/generic/test-function-removal.sh
 create mode 100755 tools/objtool/tests/generic/test-local-vs-export.sh
 create mode 100755 tools/objtool/tests/generic/test-post-link.sh
 create mode 100755 tools/objtool/tests/generic/test-symvers-parse-error.sh
tools/objtool/tests/generic/fixtures/function_removal.c new file +25 -0
new file mode 100644
index 000000000000..d65ff604c2c5
@@ -0,0 +1,25 @@
+// SPDX-License-Identifier: GPL-2.0
+/*
+ * A function the patch deletes, along with its only caller's use of it.  The
+ * original has a symbol which the patched object simply does not, so there is
+ * nothing to correlate it against.
+ */
+
+static const char __modinfo[]
+	__attribute__((section(".modinfo"), used, aligned(1))) = "\0name=vmlinux";
+
+#ifndef PATCHED
+int going_away(int x)
+{
+	return x + 7;
+}
+#endif
+
+int caller(int x)
+{
+#ifdef PATCHED
+	return x + 1;
+#else
+	return going_away(x);
+#endif
+}
tools/objtool/tests/generic/test-checksum-debug.sh new file +49 -0

49 lines not on this page · raw message

tools/objtool/tests/generic/test-function-removal.sh new file +34 -0
new file mode 100755
index 000000000000..df76e81e3936
@@ -0,0 +1,34 @@
+#!/bin/bash
+# SPDX-License-Identifier: GPL-2.0
+#
+# A patch which deletes a function leaves a symbol in the original with no
+# counterpart in the patched object.  klp diff cannot correlate it, and must
+# say so and carry on: livepatching cannot remove code from a running kernel,
+# so what matters is that the surviving caller is patched and the deleted
+# function is not dragged into the patch module.
+#
+# Cloning it would be worse than useless -- dead code in the patch, plus
+# whatever it references, resolved against a kernel where it may not exist.
+
+. "$(dirname "$0")/../lib.sh"
+
+setup
+build_pair function_removal.c
+
+# One-sided by construction: present in the original, gone from the patched.
+has_input_symbol orig.o going_away ||
+	fail "fixture has no going_away in the original"
+has_input_symbol patched.o going_away &&
+	fail "fixture still has going_away in the patched object"
+
+run_diff
+
+assert_diff_log 'no correlation: going_away'
+
+# The caller changed, so it is patched ...
+assert_patched caller
+# ... and the deleted function comes along in no form at all.
+assert_not_patched going_away
+assert_no_symbol going_away
+
+pass "deleted function reported as uncorrelated and left out of the patch"
tools/objtool/tests/generic/test-local-vs-export.sh new file +32 -0
new file mode 100755
index 000000000000..5b91101dadd6
@@ -0,0 +1,32 @@
+#!/bin/bash
+# SPDX-License-Identifier: GPL-2.0
+#
+# find_export() matched on symbol name alone, so a static function or variable
+# sharing a name with an export was mistaken for a reference to that export.
+# For a vmlinux export that means no klp relocation at all: the normal
+# relocation left behind is resolved by the module loader to the vmlinux
+# symbol, and the patched code quietly reads and writes the wrong object.
+#
+# Exports are always global, so a local symbol is never one.
+
+. "$(dirname "$0")/../lib.sh"
+
+setup
+build_pair static_local.c
+
+# The static the fixture uses.  Compilers mangle statics variously -- gcc says
+# counter.0, clang says target.counter -- so find what this one produced rather
+# than assuming a shape.
+local_sym="$(in_symbols orig.o |
+	awk '$4 == "OBJECT" && $5 == "LOCAL" && $8 ~ /counter/ { print $8; exit }')"
+[ -n "$local_sym" ] ||
+	fail "fixture produced no local 'counter' symbol"
+
+# Contrive the collision: something else exports that same name.
+export_syms "$local_sym" counter
+run_diff
+
+# Still treated as the local it is, not as the export.
+assert_klp_sym "$local_sym" vmlinux
+
+pass "local symbol not mistaken for an export of the same name"
tools/objtool/tests/generic/test-post-link.sh new file +42 -0

42 lines not on this page · raw message

tools/objtool/tests/generic/test-symvers-parse-error.sh new file +23 -0
new file mode 100755
index 000000000000..d597f28e5617
@@ -0,0 +1,23 @@
+#!/bin/bash
+# SPDX-License-Identifier: GPL-2.0
+#
+# A malformed Module.symvers has to be reported against the line it is on.
+# Module.symvers has tens of thousands of lines and is generated, so a wrong
+# line number sends whoever has to fix it to the wrong place, and "line 1" is
+# wrong in a way that looks plausible.
+
+. "$(dirname "$0")/../lib.sh"
+
+setup
+build_pair basic.c
+
+# Three well-formed lines, then one with no tabs at all.
+export_syms a b c
+echo 'this line has no fields' >> "$workdir/Module.symvers"
+
+run_diff 255
+
+assert_diff_log 'malformed Module.symvers'
+assert_diff_log 'at line 4'
+
+pass "malformed Module.symvers reported against the offending line"
Signature · 1 line
2.53.0-Meta
merge bot Applied
#80 lore raw

[tip: objtool/core] objtool/klp: Add klp diff and post-link regression tests

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:     42ccbaf4de2e07e56b39cfe432f7b453d3fb599d
Gitweb:        https://git.kernel.org/tip/42ccbaf4de2e07e56b39cfe432f7b453d3fb599d
Author:        Song Liu <[email protected]>
AuthorDate:    Wed, 16 Sep 2026 11:43:20 -07:00
Committer:     Josh Poimboeuf <[email protected]>
CommitterDate: Wed, 16 Sep 2026 17:13:28 -07:00

objtool/klp: Add klp diff and post-link regression tests

Five tests covering behaviour the harness could reach but nothing exercised. Each was verified to fail against the code it guards, by reverting the fix or sabotaging the exact line; where a first attempt passed against broken code, the fixture was wrong and was rebuilt.

  post-link                    first coverage of the subcommand at all
  local-vs-export              local symbols must not match exports
  symvers-parse-error          Module.symvers parse error line numbers
  checksum-debug               the --debug-checksum format klp-build reads
  function-removal             the "no correlation" path

local-vs-export tests the behavior of commit 86a697572c62 ("objtool/klp:
Don't match local symbols against exports"), and symvers-parse-error that of commit 51c1de134863 ("objtool/klp: Fix line numbers in Module.symvers parse errors").

---
 tools/objtool/tests/generic/fixtures/function_removal.c | 25 ++++-
 tools/objtool/tests/generic/test-checksum-debug.sh      | 49 ++++++++-
 tools/objtool/tests/generic/test-function-removal.sh    | 34 ++++++-
 tools/objtool/tests/generic/test-local-vs-export.sh     | 32 +++++-
 tools/objtool/tests/generic/test-post-link.sh           | 42 +++++++-
 tools/objtool/tests/generic/test-symvers-parse-error.sh | 23 ++++-
 6 files changed, 205 insertions(+)
 create mode 100644 tools/objtool/tests/generic/fixtures/function_removal.c
 create mode 100755 tools/objtool/tests/generic/test-checksum-debug.sh
 create mode 100755 tools/objtool/tests/generic/test-function-removal.sh
 create mode 100755 tools/objtool/tests/generic/test-local-vs-export.sh
 create mode 100755 tools/objtool/tests/generic/test-post-link.sh
 create mode 100755 tools/objtool/tests/generic/test-symvers-parse-error.sh
tools/objtool/tests/generic/fixtures/function_removal.c new file +25 -0
new file mode 100644
index 0000000..d65ff60
@@ -0,0 +1,25 @@
+// SPDX-License-Identifier: GPL-2.0
+/*
+ * A function the patch deletes, along with its only caller's use of it.  The
+ * original has a symbol which the patched object simply does not, so there is
+ * nothing to correlate it against.
+ */
+
+static const char __modinfo[]
+	__attribute__((section(".modinfo"), used, aligned(1))) = "\0name=vmlinux";
+
+#ifndef PATCHED
+int going_away(int x)
+{
+	return x + 7;
+}
+#endif
+
+int caller(int x)
+{
+#ifdef PATCHED
+	return x + 1;
+#else
+	return going_away(x);
+#endif
+}
tools/objtool/tests/generic/test-checksum-debug.sh new file +49 -0

49 lines not on this page · raw message

tools/objtool/tests/generic/test-function-removal.sh new file +34 -0
new file mode 100755
index 0000000..df76e81
@@ -0,0 +1,34 @@
+#!/bin/bash
+# SPDX-License-Identifier: GPL-2.0
+#
+# A patch which deletes a function leaves a symbol in the original with no
+# counterpart in the patched object.  klp diff cannot correlate it, and must
+# say so and carry on: livepatching cannot remove code from a running kernel,
+# so what matters is that the surviving caller is patched and the deleted
+# function is not dragged into the patch module.
+#
+# Cloning it would be worse than useless -- dead code in the patch, plus
+# whatever it references, resolved against a kernel where it may not exist.
+
+. "$(dirname "$0")/../lib.sh"
+
+setup
+build_pair function_removal.c
+
+# One-sided by construction: present in the original, gone from the patched.
+has_input_symbol orig.o going_away ||
+	fail "fixture has no going_away in the original"
+has_input_symbol patched.o going_away &&
+	fail "fixture still has going_away in the patched object"
+
+run_diff
+
+assert_diff_log 'no correlation: going_away'
+
+# The caller changed, so it is patched ...
+assert_patched caller
+# ... and the deleted function comes along in no form at all.
+assert_not_patched going_away
+assert_no_symbol going_away
+
+pass "deleted function reported as uncorrelated and left out of the patch"
tools/objtool/tests/generic/test-local-vs-export.sh new file +32 -0
new file mode 100755
index 0000000..5b91101
@@ -0,0 +1,32 @@
+#!/bin/bash
+# SPDX-License-Identifier: GPL-2.0
+#
+# find_export() matched on symbol name alone, so a static function or variable
+# sharing a name with an export was mistaken for a reference to that export.
+# For a vmlinux export that means no klp relocation at all: the normal
+# relocation left behind is resolved by the module loader to the vmlinux
+# symbol, and the patched code quietly reads and writes the wrong object.
+#
+# Exports are always global, so a local symbol is never one.
+
+. "$(dirname "$0")/../lib.sh"
+
+setup
+build_pair static_local.c
+
+# The static the fixture uses.  Compilers mangle statics variously -- gcc says
+# counter.0, clang says target.counter -- so find what this one produced rather
+# than assuming a shape.
+local_sym="$(in_symbols orig.o |
+	awk '$4 == "OBJECT" && $5 == "LOCAL" && $8 ~ /counter/ { print $8; exit }')"
+[ -n "$local_sym" ] ||
+	fail "fixture produced no local 'counter' symbol"
+
+# Contrive the collision: something else exports that same name.
+export_syms "$local_sym" counter
+run_diff
+
+# Still treated as the local it is, not as the export.
+assert_klp_sym "$local_sym" vmlinux
+
+pass "local symbol not mistaken for an export of the same name"
tools/objtool/tests/generic/test-post-link.sh new file +42 -0

42 lines not on this page · raw message

tools/objtool/tests/generic/test-symvers-parse-error.sh new file +23 -0
new file mode 100755
index 0000000..d597f28
@@ -0,0 +1,23 @@
+#!/bin/bash
+# SPDX-License-Identifier: GPL-2.0
+#
+# A malformed Module.symvers has to be reported against the line it is on.
+# Module.symvers has tens of thousands of lines and is generated, so a wrong
+# line number sends whoever has to fix it to the wrong place, and "line 1" is
+# wrong in a way that looks plausible.
+
+. "$(dirname "$0")/../lib.sh"
+
+setup
+build_pair basic.c
+
+# Three well-formed lines, then one with no tabs at all.
+export_syms a b c
+echo 'this line has no fields' >> "$workdir/Module.symvers"
+
+run_diff 255
+
+assert_diff_log 'malformed Module.symvers'
+assert_diff_log 'at line 4'
+
+pass "malformed Module.symvers reported against the offending line"
merge bot Applied
#81 lore raw

[tip: objtool/core] objtool/klp: Add klp diff and post-link regression tests

In reply to Song Liu
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:     ade23d75deb3c679760c3f0f33d9b8d8ffa9f963
Gitweb:        https://git.kernel.org/tip/ade23d75deb3c679760c3f0f33d9b8d8ffa9f963
Author:        Song Liu <[email protected]>
AuthorDate:    Wed, 16 Sep 2026 11:43:20 -07:00
Committer:     Ingo Molnar <[email protected]>
CommitterDate: Mon, 21 Sep 2026 11:05:47 +02:00

objtool/klp: Add klp diff and post-link regression tests

Five tests covering behaviour the harness could reach but nothing exercised. Each was verified to fail against the code it guards, by reverting the fix or sabotaging the exact line; where a first attempt passed against broken code, the fixture was wrong and was rebuilt.

  post-link                    first coverage of the subcommand at all
  local-vs-export              local symbols must not match exports
  symvers-parse-error          Module.symvers parse error line numbers
  checksum-debug               the --debug-checksum format klp-build reads
  function-removal             the "no correlation" path

local-vs-export tests the behavior of commit 86a697572c62 ("objtool/klp:
Don't match local symbols against exports"), and symvers-parse-error that of commit 51c1de134863 ("objtool/klp: Fix line numbers in Module.symvers parse errors").

---
 tools/objtool/tests/generic/fixtures/function_removal.c | 25 ++++-
 tools/objtool/tests/generic/test-checksum-debug.sh      | 49 ++++++++-
 tools/objtool/tests/generic/test-function-removal.sh    | 34 ++++++-
 tools/objtool/tests/generic/test-local-vs-export.sh     | 32 +++++-
 tools/objtool/tests/generic/test-post-link.sh           | 42 +++++++-
 tools/objtool/tests/generic/test-symvers-parse-error.sh | 23 ++++-
 6 files changed, 205 insertions(+)
 create mode 100644 tools/objtool/tests/generic/fixtures/function_removal.c
 create mode 100755 tools/objtool/tests/generic/test-checksum-debug.sh
 create mode 100755 tools/objtool/tests/generic/test-function-removal.sh
 create mode 100755 tools/objtool/tests/generic/test-local-vs-export.sh
 create mode 100755 tools/objtool/tests/generic/test-post-link.sh
 create mode 100755 tools/objtool/tests/generic/test-symvers-parse-error.sh
tools/objtool/tests/generic/fixtures/function_removal.c new file +25 -0
new file mode 100644
index 0000000..d65ff60
@@ -0,0 +1,25 @@
+// SPDX-License-Identifier: GPL-2.0
+/*
+ * A function the patch deletes, along with its only caller's use of it.  The
+ * original has a symbol which the patched object simply does not, so there is
+ * nothing to correlate it against.
+ */
+
+static const char __modinfo[]
+	__attribute__((section(".modinfo"), used, aligned(1))) = "\0name=vmlinux";
+
+#ifndef PATCHED
+int going_away(int x)
+{
+	return x + 7;
+}
+#endif
+
+int caller(int x)
+{
+#ifdef PATCHED
+	return x + 1;
+#else
+	return going_away(x);
+#endif
+}
tools/objtool/tests/generic/test-checksum-debug.sh new file +49 -0

49 lines not on this page · raw message

tools/objtool/tests/generic/test-function-removal.sh new file +34 -0
new file mode 100755
index 0000000..df76e81
@@ -0,0 +1,34 @@
+#!/bin/bash
+# SPDX-License-Identifier: GPL-2.0
+#
+# A patch which deletes a function leaves a symbol in the original with no
+# counterpart in the patched object.  klp diff cannot correlate it, and must
+# say so and carry on: livepatching cannot remove code from a running kernel,
+# so what matters is that the surviving caller is patched and the deleted
+# function is not dragged into the patch module.
+#
+# Cloning it would be worse than useless -- dead code in the patch, plus
+# whatever it references, resolved against a kernel where it may not exist.
+
+. "$(dirname "$0")/../lib.sh"
+
+setup
+build_pair function_removal.c
+
+# One-sided by construction: present in the original, gone from the patched.
+has_input_symbol orig.o going_away ||
+	fail "fixture has no going_away in the original"
+has_input_symbol patched.o going_away &&
+	fail "fixture still has going_away in the patched object"
+
+run_diff
+
+assert_diff_log 'no correlation: going_away'
+
+# The caller changed, so it is patched ...
+assert_patched caller
+# ... and the deleted function comes along in no form at all.
+assert_not_patched going_away
+assert_no_symbol going_away
+
+pass "deleted function reported as uncorrelated and left out of the patch"
tools/objtool/tests/generic/test-local-vs-export.sh new file +32 -0
new file mode 100755
index 0000000..5b91101
@@ -0,0 +1,32 @@
+#!/bin/bash
+# SPDX-License-Identifier: GPL-2.0
+#
+# find_export() matched on symbol name alone, so a static function or variable
+# sharing a name with an export was mistaken for a reference to that export.
+# For a vmlinux export that means no klp relocation at all: the normal
+# relocation left behind is resolved by the module loader to the vmlinux
+# symbol, and the patched code quietly reads and writes the wrong object.
+#
+# Exports are always global, so a local symbol is never one.
+
+. "$(dirname "$0")/../lib.sh"
+
+setup
+build_pair static_local.c
+
+# The static the fixture uses.  Compilers mangle statics variously -- gcc says
+# counter.0, clang says target.counter -- so find what this one produced rather
+# than assuming a shape.
+local_sym="$(in_symbols orig.o |
+	awk '$4 == "OBJECT" && $5 == "LOCAL" && $8 ~ /counter/ { print $8; exit }')"
+[ -n "$local_sym" ] ||
+	fail "fixture produced no local 'counter' symbol"
+
+# Contrive the collision: something else exports that same name.
+export_syms "$local_sym" counter
+run_diff
+
+# Still treated as the local it is, not as the export.
+assert_klp_sym "$local_sym" vmlinux
+
+pass "local symbol not mistaken for an export of the same name"
tools/objtool/tests/generic/test-post-link.sh new file +42 -0

42 lines not on this page · raw message

tools/objtool/tests/generic/test-symvers-parse-error.sh new file +23 -0
new file mode 100755
index 0000000..d597f28
@@ -0,0 +1,23 @@
+#!/bin/bash
+# SPDX-License-Identifier: GPL-2.0
+#
+# A malformed Module.symvers has to be reported against the line it is on.
+# Module.symvers has tens of thousands of lines and is generated, so a wrong
+# line number sends whoever has to fix it to the wrong place, and "line 1" is
+# wrong in a way that looks plausible.
+
+. "$(dirname "$0")/../lib.sh"
+
+setup
+build_pair basic.c
+
+# Three well-formed lines, then one with no tabs at all.
+export_syms a b c
+echo 'this line has no fields' >> "$workdir/Module.symvers"
+
+run_diff 255
+
+assert_diff_log 'malformed Module.symvers'
+assert_diff_log 'at line 4'
+
+pass "malformed Module.symvers reported against the offending line"
author maintainer
#82 lore raw

PATCH v5 28/58 objtool/klp: Add test for klp reloc section naming in module objects

In reply to Song Liu

klp diff names the intermediate __klp_relocs section after the object the relocation belongs to, and post-link turns that into .klp.rela.<object>.<sec>. Name it after the wrong object and the kernel applies the relocation when the wrong module loads, or never.

The fixture is the first here to honour MODNAME: most hardcode name=vmlinux, so passing -DMODNAME to them silently does nothing and the test quietly becomes a vmlinux test.

This tests the behavior of commit 07f14d6af9d7 ("objtool/klp: Fix cross-module klp relocation section naming").

Assisted-by Claude:claude-opus-4
Assisted-by Claude:claude-opus-5
---
 .../tests/generic/fixtures/cross_module.c     | 25 +++++++++++++++
 .../tests/generic/test-module-object.sh       | 31 +++++++++++++++++++
 2 files changed, 56 insertions(+)
 create mode 100644 tools/objtool/tests/generic/fixtures/cross_module.c
 create mode 100755 tools/objtool/tests/generic/test-module-object.sh
tools/objtool/tests/generic/fixtures/cross_module.c new file +25 -0
new file mode 100644
index 000000000000..c170bde0666f
@@ -0,0 +1,25 @@
+// SPDX-License-Identifier: GPL-2.0
+/*
+ * A function which calls out to another object.  MODNAME selects which object
+ * this one is, so a test can make the caller a module and the callee's owner
+ * something else.
+ */
+
+#ifndef MODNAME
+#define MODNAME "vmlinux"
+#endif
+
+/* klp diff takes the object's module name from .modinfo */
+static const char __modinfo[]
+	__attribute__((section(".modinfo"), used, aligned(1))) = "\0name=" MODNAME;
+
+extern int other_mod_func(int x);
+
+int target(int x)
+{
+#ifdef PATCHED
+	return other_mod_func(x) + 2;
+#else
+	return other_mod_func(x) + 1;
+#endif
+}
tools/objtool/tests/generic/test-module-object.sh new file +31 -0
new file mode 100755
index 000000000000..95c8402a523a
@@ -0,0 +1,31 @@
+#!/bin/bash
+# SPDX-License-Identifier: GPL-2.0
+#
+# A klp relocation section is named for the object being patched, not for the
+# object which happens to own the symbol being referenced.  Deriving it from
+# the symbol means a cross-module reference lands in a section for an object
+# the patch may not even touch, so the relocation is never applied and the call
+# goes somewhere arbitrary.
+
+. "$(dirname "$0")/../lib.sh"
+
+setup
+build_module_pair cross_module.c klp_testmod
+
+# The fixture has to have built as a module for any of this to mean anything.
+in_sections orig.o | grep -q '\.modinfo' ||
+	fail "fixture has no .modinfo"
+
+# other_mod_func belongs to a different module than the one being patched.
+add_exports other_mod other_mod_func
+run_diff
+
+# Named for the patched object ...
+assert_section __klp_relocs.klp_testmod
+# ... not for the object owning the symbol.
+assert_no_section __klp_relocs.other_mod
+
+run_post_link
+assert_klp_rela klp_testmod .text.target
+
+pass "klp relocation section named for the patched object"
Signature · 1 line
2.53.0-Meta
merge bot Applied
#83 lore raw

[tip: objtool/core] objtool/klp: Add test for klp reloc section naming in module objects

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:     d109afac88e4bdde300a3851ec80b3af52a72665
Gitweb:        https://git.kernel.org/tip/d109afac88e4bdde300a3851ec80b3af52a72665
Author:        Song Liu <[email protected]>
AuthorDate:    Wed, 16 Sep 2026 11:43:21 -07:00
Committer:     Josh Poimboeuf <[email protected]>
CommitterDate: Wed, 16 Sep 2026 17:13:28 -07:00

objtool/klp: Add test for klp reloc section naming in module objects

klp diff names the intermediate __klp_relocs section after the object the relocation belongs to, and post-link turns that into .klp.rela.<object>.<sec>. Name it after the wrong object and the kernel applies the relocation when the wrong module loads, or never.

The fixture is the first here to honour MODNAME: most hardcode name=vmlinux, so passing -DMODNAME to them silently does nothing and the test quietly becomes a vmlinux test.

This tests the behavior of commit 07f14d6af9d7 ("objtool/klp: Fix cross-module klp relocation section naming").

Assisted-by Claude:claude-opus-4
Assisted-by Claude:claude-opus-5
---
 tools/objtool/tests/generic/fixtures/cross_module.c | 25 ++++++++++-
 tools/objtool/tests/generic/test-module-object.sh   | 31 ++++++++++++-
 2 files changed, 56 insertions(+)
 create mode 100644 tools/objtool/tests/generic/fixtures/cross_module.c
 create mode 100755 tools/objtool/tests/generic/test-module-object.sh
tools/objtool/tests/generic/fixtures/cross_module.c new file +25 -0
new file mode 100644
index 0000000..c170bde
@@ -0,0 +1,25 @@
+// SPDX-License-Identifier: GPL-2.0
+/*
+ * A function which calls out to another object.  MODNAME selects which object
+ * this one is, so a test can make the caller a module and the callee's owner
+ * something else.
+ */
+
+#ifndef MODNAME
+#define MODNAME "vmlinux"
+#endif
+
+/* klp diff takes the object's module name from .modinfo */
+static const char __modinfo[]
+	__attribute__((section(".modinfo"), used, aligned(1))) = "\0name=" MODNAME;
+
+extern int other_mod_func(int x);
+
+int target(int x)
+{
+#ifdef PATCHED
+	return other_mod_func(x) + 2;
+#else
+	return other_mod_func(x) + 1;
+#endif
+}
tools/objtool/tests/generic/test-module-object.sh new file +31 -0
new file mode 100755
index 0000000..95c8402
@@ -0,0 +1,31 @@
+#!/bin/bash
+# SPDX-License-Identifier: GPL-2.0
+#
+# A klp relocation section is named for the object being patched, not for the
+# object which happens to own the symbol being referenced.  Deriving it from
+# the symbol means a cross-module reference lands in a section for an object
+# the patch may not even touch, so the relocation is never applied and the call
+# goes somewhere arbitrary.
+
+. "$(dirname "$0")/../lib.sh"
+
+setup
+build_module_pair cross_module.c klp_testmod
+
+# The fixture has to have built as a module for any of this to mean anything.
+in_sections orig.o | grep -q '\.modinfo' ||
+	fail "fixture has no .modinfo"
+
+# other_mod_func belongs to a different module than the one being patched.
+add_exports other_mod other_mod_func
+run_diff
+
+# Named for the patched object ...
+assert_section __klp_relocs.klp_testmod
+# ... not for the object owning the symbol.
+assert_no_section __klp_relocs.other_mod
+
+run_post_link
+assert_klp_rela klp_testmod .text.target
+
+pass "klp relocation section named for the patched object"
merge bot Applied
#84 lore raw

[tip: objtool/core] objtool/klp: Add test for klp reloc section naming in module objects

In reply to Song Liu
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:     2d17a35f6c9489884e6a5ff7cb0d6b150d413371
Gitweb:        https://git.kernel.org/tip/2d17a35f6c9489884e6a5ff7cb0d6b150d413371
Author:        Song Liu <[email protected]>
AuthorDate:    Wed, 16 Sep 2026 11:43:21 -07:00
Committer:     Ingo Molnar <[email protected]>
CommitterDate: Mon, 21 Sep 2026 11:06:08 +02:00

objtool/klp: Add test for klp reloc section naming in module objects

klp diff names the intermediate __klp_relocs section after the object the relocation belongs to, and post-link turns that into .klp.rela.<object>.<sec>. Name it after the wrong object and the kernel applies the relocation when the wrong module loads, or never.

The fixture is the first here to honour MODNAME: most hardcode name=vmlinux, so passing -DMODNAME to them silently does nothing and the test quietly becomes a vmlinux test.

This tests the behavior of commit 07f14d6af9d7 ("objtool/klp: Fix cross-module klp relocation section naming").

Assisted-by Claude:claude-opus-4
Assisted-by Claude:claude-opus-5
---
 tools/objtool/tests/generic/fixtures/cross_module.c | 25 ++++++++++-
 tools/objtool/tests/generic/test-module-object.sh   | 31 ++++++++++++-
 2 files changed, 56 insertions(+)
 create mode 100644 tools/objtool/tests/generic/fixtures/cross_module.c
 create mode 100755 tools/objtool/tests/generic/test-module-object.sh
tools/objtool/tests/generic/fixtures/cross_module.c new file +25 -0
new file mode 100644
index 0000000..c170bde
@@ -0,0 +1,25 @@
+// SPDX-License-Identifier: GPL-2.0
+/*
+ * A function which calls out to another object.  MODNAME selects which object
+ * this one is, so a test can make the caller a module and the callee's owner
+ * something else.
+ */
+
+#ifndef MODNAME
+#define MODNAME "vmlinux"
+#endif
+
+/* klp diff takes the object's module name from .modinfo */
+static const char __modinfo[]
+	__attribute__((section(".modinfo"), used, aligned(1))) = "\0name=" MODNAME;
+
+extern int other_mod_func(int x);
+
+int target(int x)
+{
+#ifdef PATCHED
+	return other_mod_func(x) + 2;
+#else
+	return other_mod_func(x) + 1;
+#endif
+}
tools/objtool/tests/generic/test-module-object.sh new file +31 -0
new file mode 100755
index 0000000..95c8402
@@ -0,0 +1,31 @@
+#!/bin/bash
+# SPDX-License-Identifier: GPL-2.0
+#
+# A klp relocation section is named for the object being patched, not for the
+# object which happens to own the symbol being referenced.  Deriving it from
+# the symbol means a cross-module reference lands in a section for an object
+# the patch may not even touch, so the relocation is never applied and the call
+# goes somewhere arbitrary.
+
+. "$(dirname "$0")/../lib.sh"
+
+setup
+build_module_pair cross_module.c klp_testmod
+
+# The fixture has to have built as a module for any of this to mean anything.
+in_sections orig.o | grep -q '\.modinfo' ||
+	fail "fixture has no .modinfo"
+
+# other_mod_func belongs to a different module than the one being patched.
+add_exports other_mod other_mod_func
+run_diff
+
+# Named for the patched object ...
+assert_section __klp_relocs.klp_testmod
+# ... not for the object owning the symbol.
+assert_no_section __klp_relocs.other_mod
+
+run_post_link
+assert_klp_rela klp_testmod .text.target
+
+pass "klp relocation section named for the patched object"
author maintainer
#85 lore raw

PATCH v5 29/58 objtool/klp: Add test for vmlinux relocs in a patched module

In reply to Song Liu

The kernel refuses a module-targeted klp relocation which names a vmlinux symbol. An EXPORT_SYMBOL_FOR_MODULES() symbol needs a klp relocation, so patching a module function that references one only loads if klp diff files that relocation under vmlinux rather than under the patched module.

This fails at load, not at build: klp-build produces a module and static checks of it find nothing wrong. Hence the assertion on which object the relocation is filed against.

Reported by Dylan Hatch, whose mod-ns-lp branch carries the kernel-side half of this case.

Assisted-by Claude:claude-opus-5
---
 .../generic/test-module-vmlinux-reloc.sh      | 40 +++++++++++++++++++
 1 file changed, 40 insertions(+)
 create mode 100755 tools/objtool/tests/generic/test-module-vmlinux-reloc.sh
tools/objtool/tests/generic/test-module-vmlinux-reloc.sh new file +40 -0
new file mode 100755
index 000000000000..635a75f6b8ba
@@ -0,0 +1,40 @@
+#!/bin/bash
+# SPDX-License-Identifier: GPL-2.0
+#
+# Patching a module, where the patched code references a vmlinux symbol which
+# needs a klp relocation.
+#
+# The kernel does not allow a module-targeted klp relocation to reference a
+# vmlinux symbol, and a symbol exported with EXPORT_SYMBOL_FOR_MODULES gets a
+# klp relocation.  Put together, filing that relocation under the patched
+# module produces a patch the kernel refuses to apply to its target.
+#
+# So it goes under vmlinux instead, and is applied when the patch module loads
+# rather than when the patched module does.  That is the opposite of the rule
+# for a reference to a module's symbol, which test-module-object covers; this
+# is the other branch of the same decision.
+
+. "$(dirname "$0")/../lib.sh"
+
+setup
+# The object being patched is a module ...
+build_module_pair cross_module.c klp_testmod
+
+# ... and the symbol it references belongs to vmlinux, exported in a way that
+# still requires a klp relocation.
+export_syms
+add_exports_ns vmlinux module:kvm other_mod_func
+run_diff
+
+# Filed against vmlinux, applied when the patch loads.
+assert_section __klp_relocs.vmlinux
+assert_klp_sym other_mod_func vmlinux
+
+# Not against the patched module: that is the relocation the kernel rejects.
+assert_no_section __klp_relocs.klp_testmod
+
+run_post_link
+assert_klp_rela vmlinux .text.target
+assert_no_section ".klp.rela.klp_testmod..text.target"
+
+pass "klp relocation to a vmlinux symbol filed under vmlinux, not the patched module"
Signature · 1 line
2.53.0-Meta
merge bot Applied
#86 lore raw

[tip: objtool/core] objtool/klp: Add test for vmlinux relocs in a patched module

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:     1c34bfb98f84554288ad4e0b82e127671edb85ef
Gitweb:        https://git.kernel.org/tip/1c34bfb98f84554288ad4e0b82e127671edb85ef
Author:        Song Liu <[email protected]>
AuthorDate:    Wed, 16 Sep 2026 11:43:22 -07:00
Committer:     Josh Poimboeuf <[email protected]>
CommitterDate: Wed, 16 Sep 2026 17:13:28 -07:00

objtool/klp: Add test for vmlinux relocs in a patched module

The kernel refuses a module-targeted klp relocation which names a vmlinux symbol. An EXPORT_SYMBOL_FOR_MODULES() symbol needs a klp relocation, so patching a module function that references one only loads if klp diff files that relocation under vmlinux rather than under the patched module.

This fails at load, not at build: klp-build produces a module and static checks of it find nothing wrong. Hence the assertion on which object the relocation is filed against.

Reported by Dylan Hatch, whose mod-ns-lp branch carries the kernel-side half of this case.

---
 tools/objtool/tests/generic/test-module-vmlinux-reloc.sh | 40 +++++++-
 1 file changed, 40 insertions(+)
 create mode 100755 tools/objtool/tests/generic/test-module-vmlinux-reloc.sh
tools/objtool/tests/generic/test-module-vmlinux-reloc.sh new file +40 -0
new file mode 100755
index 0000000..635a75f
@@ -0,0 +1,40 @@
+#!/bin/bash
+# SPDX-License-Identifier: GPL-2.0
+#
+# Patching a module, where the patched code references a vmlinux symbol which
+# needs a klp relocation.
+#
+# The kernel does not allow a module-targeted klp relocation to reference a
+# vmlinux symbol, and a symbol exported with EXPORT_SYMBOL_FOR_MODULES gets a
+# klp relocation.  Put together, filing that relocation under the patched
+# module produces a patch the kernel refuses to apply to its target.
+#
+# So it goes under vmlinux instead, and is applied when the patch module loads
+# rather than when the patched module does.  That is the opposite of the rule
+# for a reference to a module's symbol, which test-module-object covers; this
+# is the other branch of the same decision.
+
+. "$(dirname "$0")/../lib.sh"
+
+setup
+# The object being patched is a module ...
+build_module_pair cross_module.c klp_testmod
+
+# ... and the symbol it references belongs to vmlinux, exported in a way that
+# still requires a klp relocation.
+export_syms
+add_exports_ns vmlinux module:kvm other_mod_func
+run_diff
+
+# Filed against vmlinux, applied when the patch loads.
+assert_section __klp_relocs.vmlinux
+assert_klp_sym other_mod_func vmlinux
+
+# Not against the patched module: that is the relocation the kernel rejects.
+assert_no_section __klp_relocs.klp_testmod
+
+run_post_link
+assert_klp_rela vmlinux .text.target
+assert_no_section ".klp.rela.klp_testmod..text.target"
+
+pass "klp relocation to a vmlinux symbol filed under vmlinux, not the patched module"
merge bot Applied
#87 lore raw

[tip: objtool/core] objtool/klp: Add test for vmlinux relocs in a patched module

In reply to Song Liu
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:     65b0aac4125c18280efbda38174ec14bcef887b2
Gitweb:        https://git.kernel.org/tip/65b0aac4125c18280efbda38174ec14bcef887b2
Author:        Song Liu <[email protected]>
AuthorDate:    Wed, 16 Sep 2026 11:43:22 -07:00
Committer:     Ingo Molnar <[email protected]>
CommitterDate: Mon, 21 Sep 2026 11:11:36 +02:00

objtool/klp: Add test for vmlinux relocs in a patched module

The kernel refuses a module-targeted klp relocation which names a vmlinux symbol. An EXPORT_SYMBOL_FOR_MODULES() symbol needs a klp relocation, so patching a module function that references one only loads if klp diff files that relocation under vmlinux rather than under the patched module.

This fails at load, not at build: klp-build produces a module and static checks of it find nothing wrong. Hence the assertion on which object the relocation is filed against.

Reported by Dylan Hatch, whose mod-ns-lp branch carries the kernel-side half of this case.

---
 tools/objtool/tests/generic/test-module-vmlinux-reloc.sh | 40 +++++++-
 1 file changed, 40 insertions(+)
 create mode 100755 tools/objtool/tests/generic/test-module-vmlinux-reloc.sh
tools/objtool/tests/generic/test-module-vmlinux-reloc.sh new file +40 -0
new file mode 100755
index 0000000..635a75f
@@ -0,0 +1,40 @@
+#!/bin/bash
+# SPDX-License-Identifier: GPL-2.0
+#
+# Patching a module, where the patched code references a vmlinux symbol which
+# needs a klp relocation.
+#
+# The kernel does not allow a module-targeted klp relocation to reference a
+# vmlinux symbol, and a symbol exported with EXPORT_SYMBOL_FOR_MODULES gets a
+# klp relocation.  Put together, filing that relocation under the patched
+# module produces a patch the kernel refuses to apply to its target.
+#
+# So it goes under vmlinux instead, and is applied when the patch module loads
+# rather than when the patched module does.  That is the opposite of the rule
+# for a reference to a module's symbol, which test-module-object covers; this
+# is the other branch of the same decision.
+
+. "$(dirname "$0")/../lib.sh"
+
+setup
+# The object being patched is a module ...
+build_module_pair cross_module.c klp_testmod
+
+# ... and the symbol it references belongs to vmlinux, exported in a way that
+# still requires a klp relocation.
+export_syms
+add_exports_ns vmlinux module:kvm other_mod_func
+run_diff
+
+# Filed against vmlinux, applied when the patch loads.
+assert_section __klp_relocs.vmlinux
+assert_klp_sym other_mod_func vmlinux
+
+# Not against the patched module: that is the relocation the kernel rejects.
+assert_no_section __klp_relocs.klp_testmod
+
+run_post_link
+assert_klp_rela vmlinux .text.target
+assert_no_section ".klp.rela.klp_testmod..text.target"
+
+pass "klp relocation to a vmlinux symbol filed under vmlinux, not the patched module"
author maintainer
#88 lore raw

PATCH v5 30/58 objtool/klp: Add test for Module.symvers path normalization

In reply to Song Liu

Module.symvers names an export's owner by build path, and the kernel knows modules by their runtime name. Without normalizing one to the other, an export owned by a module is not recognised as owned by anything, and a reference that should become a klp relocation stays an ordinary one.

This tests the behavior of commit 8668bf91e050 ("objtool/klp: Normalize Module.symvers paths to module names").

Assisted-by Claude:claude-opus-4
Assisted-by Claude:claude-opus-5
---
 .../tests/generic/test-modname-normalize.sh   | 26 +++++++++++++++++++
 1 file changed, 26 insertions(+)
 create mode 100755 tools/objtool/tests/generic/test-modname-normalize.sh
tools/objtool/tests/generic/test-modname-normalize.sh new file +26 -0
new file mode 100755
index 000000000000..a8059bdbd667
@@ -0,0 +1,26 @@
+#!/bin/bash
+# SPDX-License-Identifier: GPL-2.0
+#
+# Module.symvers records the build-tree path of the object that exports a
+# symbol, not the name the module has at runtime: "arch/x86/kvm/kvm-intel",
+# where the kernel knows the module as "kvm_intel".
+#
+# The klp symbol name embeds the owning object, and livepatch matches it
+# against loaded modules by name.  Left unnormalized it names a module that
+# does not exist, and the relocation is never resolved -- at load time, with no
+# build-time complaint.
+
+. "$(dirname "$0")/../lib.sh"
+
+setup
+build_module_pair cross_module.c klp_testmod
+
+# A path with directory components, a dash, and no extension.
+export_syms
+add_exports "arch/x86/kvm/kvm-intel" other_mod_func
+run_diff
+
+# Directories stripped, dash to underscore.
+assert_klp_sym other_mod_func kvm_intel
+
+pass "Module.symvers paths normalized to runtime module names"
Signature · 1 line
2.53.0-Meta
merge bot Applied
#89 lore raw

[tip: objtool/core] objtool/klp: Add test for Module.symvers path normalization

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:     3a3a268e01187f836e070caeef7f7671e8cad6bf
Gitweb:        https://git.kernel.org/tip/3a3a268e01187f836e070caeef7f7671e8cad6bf
Author:        Song Liu <[email protected]>
AuthorDate:    Wed, 16 Sep 2026 11:43:23 -07:00
Committer:     Josh Poimboeuf <[email protected]>
CommitterDate: Wed, 16 Sep 2026 17:13:28 -07:00

objtool/klp: Add test for Module.symvers path normalization

Module.symvers names an export's owner by build path, and the kernel knows modules by their runtime name. Without normalizing one to the other, an export owned by a module is not recognised as owned by anything, and a reference that should become a klp relocation stays an ordinary one.

This tests the behavior of commit 8668bf91e050 ("objtool/klp: Normalize Module.symvers paths to module names").

Assisted-by Claude:claude-opus-4
Assisted-by Claude:claude-opus-5
---
 tools/objtool/tests/generic/test-modname-normalize.sh | 26 ++++++++++-
 1 file changed, 26 insertions(+)
 create mode 100755 tools/objtool/tests/generic/test-modname-normalize.sh
tools/objtool/tests/generic/test-modname-normalize.sh new file +26 -0
new file mode 100755
index 0000000..a8059bd
@@ -0,0 +1,26 @@
+#!/bin/bash
+# SPDX-License-Identifier: GPL-2.0
+#
+# Module.symvers records the build-tree path of the object that exports a
+# symbol, not the name the module has at runtime: "arch/x86/kvm/kvm-intel",
+# where the kernel knows the module as "kvm_intel".
+#
+# The klp symbol name embeds the owning object, and livepatch matches it
+# against loaded modules by name.  Left unnormalized it names a module that
+# does not exist, and the relocation is never resolved -- at load time, with no
+# build-time complaint.
+
+. "$(dirname "$0")/../lib.sh"
+
+setup
+build_module_pair cross_module.c klp_testmod
+
+# A path with directory components, a dash, and no extension.
+export_syms
+add_exports "arch/x86/kvm/kvm-intel" other_mod_func
+run_diff
+
+# Directories stripped, dash to underscore.
+assert_klp_sym other_mod_func kvm_intel
+
+pass "Module.symvers paths normalized to runtime module names"
merge bot Applied
#90 lore raw

[tip: objtool/core] objtool/klp: Add test for Module.symvers path normalization

In reply to Song Liu
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:     90949e312de909e2f2a4f72ff3221f79e891d19f
Gitweb:        https://git.kernel.org/tip/90949e312de909e2f2a4f72ff3221f79e891d19f
Author:        Song Liu <[email protected]>
AuthorDate:    Wed, 16 Sep 2026 11:43:23 -07:00
Committer:     Ingo Molnar <[email protected]>
CommitterDate: Mon, 21 Sep 2026 11:12:06 +02:00

objtool/klp: Add test for Module.symvers path normalization

Module.symvers names an export's owner by build path, and the kernel knows modules by their runtime name. Without normalizing one to the other, an export owned by a module is not recognised as owned by anything, and a reference that should become a klp relocation stays an ordinary one.

This tests the behavior of commit 8668bf91e050 ("objtool/klp: Normalize Module.symvers paths to module names").

Assisted-by Claude:claude-opus-4
Assisted-by Claude:claude-opus-5
---
 tools/objtool/tests/generic/test-modname-normalize.sh | 26 ++++++++++-
 1 file changed, 26 insertions(+)
 create mode 100755 tools/objtool/tests/generic/test-modname-normalize.sh
tools/objtool/tests/generic/test-modname-normalize.sh new file +26 -0
new file mode 100755
index 0000000..a8059bd
@@ -0,0 +1,26 @@
+#!/bin/bash
+# SPDX-License-Identifier: GPL-2.0
+#
+# Module.symvers records the build-tree path of the object that exports a
+# symbol, not the name the module has at runtime: "arch/x86/kvm/kvm-intel",
+# where the kernel knows the module as "kvm_intel".
+#
+# The klp symbol name embeds the owning object, and livepatch matches it
+# against loaded modules by name.  Left unnormalized it names a module that
+# does not exist, and the relocation is never resolved -- at load time, with no
+# build-time complaint.
+
+. "$(dirname "$0")/../lib.sh"
+
+setup
+build_module_pair cross_module.c klp_testmod
+
+# A path with directory components, a dash, and no extension.
+export_syms
+add_exports "arch/x86/kvm/kvm-intel" other_mod_func
+run_diff
+
+# Directories stripped, dash to underscore.
+assert_klp_sym other_mod_func kvm_intel
+
+pass "Module.symvers paths normalized to runtime module names"
author maintainer
#91 lore raw

PATCH v5 31/58 objtool/klp: Add test for the contents of the klp_funcs list

In reply to Song Liu

The patch list is what livepatch acts on, and asserting only that it exists does not say it is right. A function that should have been patched and is missing leaves the bug in place; one that should not be there patches code nobody changed.

The fixture changes two of three functions and asserts on all three: the two by name, and the third by its absence. It checks the strings in .rodata.klp.str1.1 as well as the relocations, since the names the kernel matches on are real strings.

Assisted-by Claude:claude-opus-4
Assisted-by Claude:claude-opus-5
---
 .../tests/generic/fixtures/klp_funcs.c        | 31 +++++++++++++
 .../tests/generic/test-klp-funcs-content.sh   | 45 +++++++++++++++++++
 2 files changed, 76 insertions(+)
 create mode 100644 tools/objtool/tests/generic/fixtures/klp_funcs.c
 create mode 100755 tools/objtool/tests/generic/test-klp-funcs-content.sh
tools/objtool/tests/generic/fixtures/klp_funcs.c new file +31 -0
new file mode 100644
index 000000000000..3f0d3e206cef
@@ -0,0 +1,31 @@
+// SPDX-License-Identifier: GPL-2.0
+/*
+ * Two changed functions and one untouched, so the patch's function list has a
+ * length worth checking and something that must not appear in it.
+ */
+
+static const char __modinfo[]
+	__attribute__((section(".modinfo"), used, aligned(1))) = "\0name=vmlinux";
+
+int first(int x)
+{
+#ifdef PATCHED
+	return x + 11;
+#else
+	return x + 1;
+#endif
+}
+
+int second(int x)
+{
+#ifdef PATCHED
+	return x + 22;
+#else
+	return x + 2;
+#endif
+}
+
+int third(int x)
+{
+	return x + 3;
+}
tools/objtool/tests/generic/test-klp-funcs-content.sh new file +45 -0

45 lines not on this page · raw message

Signature · 1 line
2.53.0-Meta
merge bot Applied
#92 lore raw

[tip: objtool/core] objtool/klp: Add test for the contents of the klp_funcs list

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:     64205061f5e240498a242e6a2f8b27e0db15dc75
Gitweb:        https://git.kernel.org/tip/64205061f5e240498a242e6a2f8b27e0db15dc75
Author:        Song Liu <[email protected]>
AuthorDate:    Wed, 16 Sep 2026 11:43:24 -07:00
Committer:     Josh Poimboeuf <[email protected]>
CommitterDate: Wed, 16 Sep 2026 17:13:29 -07:00

objtool/klp: Add test for the contents of the klp_funcs list

The patch list is what livepatch acts on, and asserting only that it exists does not say it is right. A function that should have been patched and is missing leaves the bug in place; one that should not be there patches code nobody changed.

The fixture changes two of three functions and asserts on all three: the two by name, and the third by its absence. It checks the strings in .rodata.klp.str1.1 as well as the relocations, since the names the kernel matches on are real strings.

Assisted-by Claude:claude-opus-4
Assisted-by Claude:claude-opus-5
---
 tools/objtool/tests/generic/fixtures/klp_funcs.c      | 31 +++++++-
 tools/objtool/tests/generic/test-klp-funcs-content.sh | 45 ++++++++++-
 2 files changed, 76 insertions(+)
 create mode 100644 tools/objtool/tests/generic/fixtures/klp_funcs.c
 create mode 100755 tools/objtool/tests/generic/test-klp-funcs-content.sh
tools/objtool/tests/generic/fixtures/klp_funcs.c new file +31 -0
new file mode 100644
index 0000000..3f0d3e2
@@ -0,0 +1,31 @@
+// SPDX-License-Identifier: GPL-2.0
+/*
+ * Two changed functions and one untouched, so the patch's function list has a
+ * length worth checking and something that must not appear in it.
+ */
+
+static const char __modinfo[]
+	__attribute__((section(".modinfo"), used, aligned(1))) = "\0name=vmlinux";
+
+int first(int x)
+{
+#ifdef PATCHED
+	return x + 11;
+#else
+	return x + 1;
+#endif
+}
+
+int second(int x)
+{
+#ifdef PATCHED
+	return x + 22;
+#else
+	return x + 2;
+#endif
+}
+
+int third(int x)
+{
+	return x + 3;
+}
tools/objtool/tests/generic/test-klp-funcs-content.sh new file +45 -0

45 lines not on this page · raw message

merge bot Applied
#93 lore raw

[tip: objtool/core] objtool/klp: Add test for the contents of the klp_funcs list

In reply to Song Liu
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:     35021df3834e0b51dd77e4be6ee7cbe9bcfa4825
Gitweb:        https://git.kernel.org/tip/35021df3834e0b51dd77e4be6ee7cbe9bcfa4825
Author:        Song Liu <[email protected]>
AuthorDate:    Wed, 16 Sep 2026 11:43:24 -07:00
Committer:     Ingo Molnar <[email protected]>
CommitterDate: Mon, 21 Sep 2026 11:12:06 +02:00

objtool/klp: Add test for the contents of the klp_funcs list

The patch list is what livepatch acts on, and asserting only that it exists does not say it is right. A function that should have been patched and is missing leaves the bug in place; one that should not be there patches code nobody changed.

The fixture changes two of three functions and asserts on all three: the two by name, and the third by its absence. It checks the strings in .rodata.klp.str1.1 as well as the relocations, since the names the kernel matches on are real strings.

Assisted-by Claude:claude-opus-4
Assisted-by Claude:claude-opus-5
---
 tools/objtool/tests/generic/fixtures/klp_funcs.c      | 31 +++++++-
 tools/objtool/tests/generic/test-klp-funcs-content.sh | 45 ++++++++++-
 2 files changed, 76 insertions(+)
 create mode 100644 tools/objtool/tests/generic/fixtures/klp_funcs.c
 create mode 100755 tools/objtool/tests/generic/test-klp-funcs-content.sh
tools/objtool/tests/generic/fixtures/klp_funcs.c new file +31 -0
new file mode 100644
index 0000000..3f0d3e2
@@ -0,0 +1,31 @@
+// SPDX-License-Identifier: GPL-2.0
+/*
+ * Two changed functions and one untouched, so the patch's function list has a
+ * length worth checking and something that must not appear in it.
+ */
+
+static const char __modinfo[]
+	__attribute__((section(".modinfo"), used, aligned(1))) = "\0name=vmlinux";
+
+int first(int x)
+{
+#ifdef PATCHED
+	return x + 11;
+#else
+	return x + 1;
+#endif
+}
+
+int second(int x)
+{
+#ifdef PATCHED
+	return x + 22;
+#else
+	return x + 2;
+#endif
+}
+
+int third(int x)
+{
+	return x + 3;
+}
tools/objtool/tests/generic/test-klp-funcs-content.sh new file +45 -0

45 lines not on this page · raw message

author maintainer
#94 lore raw

PATCH v5 32/58 objtool/klp: Add test for EXPORT_SYMBOL_FOR_MODULES references

In reply to Song Liu

A symbol exported with EXPORT_SYMBOL_FOR_MODULES() is reachable only by the modules named in its namespace, and a livepatch module is never one of them. So a reference to it cannot be an ordinary relocation resolved by the module loader; it has to be a klp relocation applied at patch time.

Getting this wrong is silent. The module links, loads, and reads the wrong thing, or fails to load for a reason that does not name the cause.

This tests the behavior of commit 4cd3cfb8b54f ("objtool/klp: Fix relocations for EXPORT_SYMBOL_FOR_MODULES() symbols"). Which object the resulting relocation is filed under is a separate question, and one this test cannot ask: the patched object here is vmlinux, so the vmlinux section is the one produced either way. That is covered by the module case, in "objtool/klp: Add test for vmlinux relocs in a patched module".

Assisted-by Claude:claude-opus-4
Assisted-by Claude:claude-opus-5
---
 .../generic/test-export-symbol-for-modules.sh | 39 +++++++++++++++++++
 1 file changed, 39 insertions(+)
 create mode 100755 tools/objtool/tests/generic/test-export-symbol-for-modules.sh
tools/objtool/tests/generic/test-export-symbol-for-modules.sh new file +39 -0
new file mode 100755
index 000000000000..7e7bdde6a7ac
@@ -0,0 +1,39 @@
+#!/bin/bash
+# SPDX-License-Identifier: GPL-2.0
+#
+# EXPORT_SYMBOL_FOR_MODULES() puts a vmlinux symbol in a "module:<names>"
+# namespace, and the module loader grants access by matching the importing
+# module's name against that list.  A livepatch module is never on the list, so
+# referencing such a symbol with a normal relocation fails modpost, and if that
+# is silenced, fails to load with "Unknown symbol".  It needs a klp relocation,
+# the same as an unexported symbol.
+#
+# Ordinary namespaces are not affected: copy_import_ns() propagates the patched
+# object's import tags to the patch module, so a normal relocation works.
+
+. "$(dirname "$0")/../lib.sh"
+
+setup
+build_pair cross_module.c
+
+sym=other_mod_func
+
+# Plain vmlinux export: a normal relocation is what we want.
+export_syms "$sym"
+run_diff
+assert_no_klp_sym "$sym"
+
+# Ordinary namespace: still a normal relocation.
+export_syms
+add_exports_ns vmlinux MY_NS "$sym"
+run_diff
+assert_no_klp_sym "$sym"
+
+# module: namespace: has to become a klp relocation.
+export_syms
+add_exports_ns vmlinux module:kvm "$sym"
+run_diff
+assert_klp_sym "$sym" vmlinux
+assert_section __klp_relocs.vmlinux
+
+pass "EXPORT_SYMBOL_FOR_MODULES symbol referenced with a klp relocation"
Signature · 1 line
2.53.0-Meta
merge bot Applied
#95 lore raw

[tip: objtool/core] objtool/klp: Add test for EXPORT_SYMBOL_FOR_MODULES references

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:     2ba2608572ad03357b215665b8d3c9497e124b1d
Gitweb:        https://git.kernel.org/tip/2ba2608572ad03357b215665b8d3c9497e124b1d
Author:        Song Liu <[email protected]>
AuthorDate:    Wed, 16 Sep 2026 11:43:25 -07:00
Committer:     Josh Poimboeuf <[email protected]>
CommitterDate: Wed, 16 Sep 2026 17:13:29 -07:00

objtool/klp: Add test for EXPORT_SYMBOL_FOR_MODULES references

A symbol exported with EXPORT_SYMBOL_FOR_MODULES() is reachable only by the modules named in its namespace, and a livepatch module is never one of them. So a reference to it cannot be an ordinary relocation resolved by the module loader; it has to be a klp relocation applied at patch time.

Getting this wrong is silent. The module links, loads, and reads the wrong thing, or fails to load for a reason that does not name the cause.

This tests the behavior of commit 4cd3cfb8b54f ("objtool/klp: Fix relocations for EXPORT_SYMBOL_FOR_MODULES() symbols"). Which object the resulting relocation is filed under is a separate question, and one this test cannot ask: the patched object here is vmlinux, so the vmlinux section is the one produced either way. That is covered by the module case, in "objtool/klp: Add test for vmlinux relocs in a patched module".

Assisted-by Claude:claude-opus-4
Assisted-by Claude:claude-opus-5
---
 tools/objtool/tests/generic/test-export-symbol-for-modules.sh | 39 +++++++-
 1 file changed, 39 insertions(+)
 create mode 100755 tools/objtool/tests/generic/test-export-symbol-for-modules.sh
tools/objtool/tests/generic/test-export-symbol-for-modules.sh new file +39 -0
new file mode 100755
index 0000000..7e7bdde
@@ -0,0 +1,39 @@
+#!/bin/bash
+# SPDX-License-Identifier: GPL-2.0
+#
+# EXPORT_SYMBOL_FOR_MODULES() puts a vmlinux symbol in a "module:<names>"
+# namespace, and the module loader grants access by matching the importing
+# module's name against that list.  A livepatch module is never on the list, so
+# referencing such a symbol with a normal relocation fails modpost, and if that
+# is silenced, fails to load with "Unknown symbol".  It needs a klp relocation,
+# the same as an unexported symbol.
+#
+# Ordinary namespaces are not affected: copy_import_ns() propagates the patched
+# object's import tags to the patch module, so a normal relocation works.
+
+. "$(dirname "$0")/../lib.sh"
+
+setup
+build_pair cross_module.c
+
+sym=other_mod_func
+
+# Plain vmlinux export: a normal relocation is what we want.
+export_syms "$sym"
+run_diff
+assert_no_klp_sym "$sym"
+
+# Ordinary namespace: still a normal relocation.
+export_syms
+add_exports_ns vmlinux MY_NS "$sym"
+run_diff
+assert_no_klp_sym "$sym"
+
+# module: namespace: has to become a klp relocation.
+export_syms
+add_exports_ns vmlinux module:kvm "$sym"
+run_diff
+assert_klp_sym "$sym" vmlinux
+assert_section __klp_relocs.vmlinux
+
+pass "EXPORT_SYMBOL_FOR_MODULES symbol referenced with a klp relocation"
merge bot Applied
#96 lore raw

[tip: objtool/core] objtool/klp: Add test for EXPORT_SYMBOL_FOR_MODULES references

In reply to Song Liu
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:     a87892ac05098d23e855e25c7afc128b1e9973fe
Gitweb:        https://git.kernel.org/tip/a87892ac05098d23e855e25c7afc128b1e9973fe
Author:        Song Liu <[email protected]>
AuthorDate:    Wed, 16 Sep 2026 11:43:25 -07:00
Committer:     Ingo Molnar <[email protected]>
CommitterDate: Mon, 21 Sep 2026 11:12:06 +02:00

objtool/klp: Add test for EXPORT_SYMBOL_FOR_MODULES references

A symbol exported with EXPORT_SYMBOL_FOR_MODULES() is reachable only by the modules named in its namespace, and a livepatch module is never one of them. So a reference to it cannot be an ordinary relocation resolved by the module loader; it has to be a klp relocation applied at patch time.

Getting this wrong is silent. The module links, loads, and reads the wrong thing, or fails to load for a reason that does not name the cause.

This tests the behavior of commit 4cd3cfb8b54f ("objtool/klp: Fix relocations for EXPORT_SYMBOL_FOR_MODULES() symbols"). Which object the resulting relocation is filed under is a separate question, and one this test cannot ask: the patched object here is vmlinux, so the vmlinux section is the one produced either way. That is covered by the module case, in "objtool/klp: Add test for vmlinux relocs in a patched module".

Assisted-by Claude:claude-opus-4
Assisted-by Claude:claude-opus-5
---
 tools/objtool/tests/generic/test-export-symbol-for-modules.sh | 39 +++++++-
 1 file changed, 39 insertions(+)
 create mode 100755 tools/objtool/tests/generic/test-export-symbol-for-modules.sh
tools/objtool/tests/generic/test-export-symbol-for-modules.sh new file +39 -0
new file mode 100755
index 0000000..7e7bdde
@@ -0,0 +1,39 @@
+#!/bin/bash
+# SPDX-License-Identifier: GPL-2.0
+#
+# EXPORT_SYMBOL_FOR_MODULES() puts a vmlinux symbol in a "module:<names>"
+# namespace, and the module loader grants access by matching the importing
+# module's name against that list.  A livepatch module is never on the list, so
+# referencing such a symbol with a normal relocation fails modpost, and if that
+# is silenced, fails to load with "Unknown symbol".  It needs a klp relocation,
+# the same as an unexported symbol.
+#
+# Ordinary namespaces are not affected: copy_import_ns() propagates the patched
+# object's import tags to the patch module, so a normal relocation works.
+
+. "$(dirname "$0")/../lib.sh"
+
+setup
+build_pair cross_module.c
+
+sym=other_mod_func
+
+# Plain vmlinux export: a normal relocation is what we want.
+export_syms "$sym"
+run_diff
+assert_no_klp_sym "$sym"
+
+# Ordinary namespace: still a normal relocation.
+export_syms
+add_exports_ns vmlinux MY_NS "$sym"
+run_diff
+assert_no_klp_sym "$sym"
+
+# module: namespace: has to become a klp relocation.
+export_syms
+add_exports_ns vmlinux module:kvm "$sym"
+run_diff
+assert_klp_sym "$sym" vmlinux
+assert_section __klp_relocs.vmlinux
+
+pass "EXPORT_SYMBOL_FOR_MODULES symbol referenced with a klp relocation"
author maintainer
#97 lore raw

PATCH v5 33/58 objtool/klp: Add test for new references to exported symbols

In reply to Song Liu

A patch may introduce a reference the original object did not have. That is fine when the export belongs to vmlinux, and not fine when it belongs to a module: the livepatch would gain a module dependency nobody declared, and late module patching lets the patch load first.

This tests the behavior of commit 72d76d0c18eb ("objtool/klp: Allow new references to module exports").

Assisted-by Claude:claude-opus-4
Assisted-by Claude:claude-opus-5
---
 .../tests/generic/fixtures/new_export_ref.c   | 35 ++++++++++++++
 .../tests/generic/test-new-export-ref.sh      | 46 +++++++++++++++++++
 2 files changed, 81 insertions(+)
 create mode 100644 tools/objtool/tests/generic/fixtures/new_export_ref.c
 create mode 100755 tools/objtool/tests/generic/test-new-export-ref.sh
tools/objtool/tests/generic/fixtures/new_export_ref.c new file +35 -0
new file mode 100644
index 000000000000..73210aacb4ae
@@ -0,0 +1,35 @@
+// SPDX-License-Identifier: GPL-2.0
+/*
+ * A reference which only exists in the patched build.  The symbol has no twin
+ * in the original object, so what klp diff may do with it depends entirely on
+ * whether Module.symvers says it is exported, and by what.
+ */
+
+static const char __modinfo[]
+	__attribute__((section(".modinfo"), used, aligned(1))) = "\0name=vmlinux";
+
+extern int newly_referenced(int x);
+
+/*
+ * A reference both builds have.  When Module.symvers says a module exports
+ * this one, the original already depends on that module, which is what makes
+ * a new reference to it safe -- the loader will not let the patched module
+ * load without it.  EXISTING_DEP leaves it out, for the case where there is
+ * no such dependency to inherit.
+ */
+extern int existing_dep(int x);
+
+int target(int x)
+{
+#ifdef EXISTING_DEP
+	int base = existing_dep(x);
+#else
+	int base = x;
+#endif
+
+#ifdef PATCHED
+	return newly_referenced(base);
+#else
+	return base + 1;
+#endif
+}
tools/objtool/tests/generic/test-new-export-ref.sh new file +46 -0

46 lines not on this page · raw message

Signature · 1 line
2.53.0-Meta
merge bot Applied
#98 lore raw

[tip: objtool/core] objtool/klp: Add test for new references to exported symbols

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:     b45f394ee3afd2ff0a54894f95a01f96ecc8e30a
Gitweb:        https://git.kernel.org/tip/b45f394ee3afd2ff0a54894f95a01f96ecc8e30a
Author:        Song Liu <[email protected]>
AuthorDate:    Wed, 16 Sep 2026 11:43:26 -07:00
Committer:     Josh Poimboeuf <[email protected]>
CommitterDate: Wed, 16 Sep 2026 17:13:29 -07:00

objtool/klp: Add test for new references to exported symbols

A patch may introduce a reference the original object did not have. That is fine when the export belongs to vmlinux, and not fine when it belongs to a module: the livepatch would gain a module dependency nobody declared, and late module patching lets the patch load first.

This tests the behavior of commit 72d76d0c18eb ("objtool/klp: Allow new references to module exports").

Assisted-by Claude:claude-opus-4
Assisted-by Claude:claude-opus-5
---
 tools/objtool/tests/generic/fixtures/new_export_ref.c | 35 ++++++++-
 tools/objtool/tests/generic/test-new-export-ref.sh    | 46 ++++++++++-
 2 files changed, 81 insertions(+)
 create mode 100644 tools/objtool/tests/generic/fixtures/new_export_ref.c
 create mode 100755 tools/objtool/tests/generic/test-new-export-ref.sh
tools/objtool/tests/generic/fixtures/new_export_ref.c new file +35 -0
new file mode 100644
index 0000000..73210aa
@@ -0,0 +1,35 @@
+// SPDX-License-Identifier: GPL-2.0
+/*
+ * A reference which only exists in the patched build.  The symbol has no twin
+ * in the original object, so what klp diff may do with it depends entirely on
+ * whether Module.symvers says it is exported, and by what.
+ */
+
+static const char __modinfo[]
+	__attribute__((section(".modinfo"), used, aligned(1))) = "\0name=vmlinux";
+
+extern int newly_referenced(int x);
+
+/*
+ * A reference both builds have.  When Module.symvers says a module exports
+ * this one, the original already depends on that module, which is what makes
+ * a new reference to it safe -- the loader will not let the patched module
+ * load without it.  EXISTING_DEP leaves it out, for the case where there is
+ * no such dependency to inherit.
+ */
+extern int existing_dep(int x);
+
+int target(int x)
+{
+#ifdef EXISTING_DEP
+	int base = existing_dep(x);
+#else
+	int base = x;
+#endif
+
+#ifdef PATCHED
+	return newly_referenced(base);
+#else
+	return base + 1;
+#endif
+}
tools/objtool/tests/generic/test-new-export-ref.sh new file +46 -0

46 lines not on this page · raw message

merge bot Applied
#99 lore raw

[tip: objtool/core] objtool/klp: Add test for new references to exported symbols

In reply to Song Liu
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:     6549ce0dd1be2400ecdd8693e47c189c54562a4e
Gitweb:        https://git.kernel.org/tip/6549ce0dd1be2400ecdd8693e47c189c54562a4e
Author:        Song Liu <[email protected]>
AuthorDate:    Wed, 16 Sep 2026 11:43:26 -07:00
Committer:     Ingo Molnar <[email protected]>
CommitterDate: Mon, 21 Sep 2026 11:12:06 +02:00

objtool/klp: Add test for new references to exported symbols

A patch may introduce a reference the original object did not have. That is fine when the export belongs to vmlinux, and not fine when it belongs to a module: the livepatch would gain a module dependency nobody declared, and late module patching lets the patch load first.

This tests the behavior of commit 72d76d0c18eb ("objtool/klp: Allow new references to module exports").

Assisted-by Claude:claude-opus-4
Assisted-by Claude:claude-opus-5
---
 tools/objtool/tests/generic/fixtures/new_export_ref.c | 35 ++++++++-
 tools/objtool/tests/generic/test-new-export-ref.sh    | 46 ++++++++++-
 2 files changed, 81 insertions(+)
 create mode 100644 tools/objtool/tests/generic/fixtures/new_export_ref.c
 create mode 100755 tools/objtool/tests/generic/test-new-export-ref.sh
tools/objtool/tests/generic/fixtures/new_export_ref.c new file +35 -0
new file mode 100644
index 0000000..73210aa
@@ -0,0 +1,35 @@
+// SPDX-License-Identifier: GPL-2.0
+/*
+ * A reference which only exists in the patched build.  The symbol has no twin
+ * in the original object, so what klp diff may do with it depends entirely on
+ * whether Module.symvers says it is exported, and by what.
+ */
+
+static const char __modinfo[]
+	__attribute__((section(".modinfo"), used, aligned(1))) = "\0name=vmlinux";
+
+extern int newly_referenced(int x);
+
+/*
+ * A reference both builds have.  When Module.symvers says a module exports
+ * this one, the original already depends on that module, which is what makes
+ * a new reference to it safe -- the loader will not let the patched module
+ * load without it.  EXISTING_DEP leaves it out, for the case where there is
+ * no such dependency to inherit.
+ */
+extern int existing_dep(int x);
+
+int target(int x)
+{
+#ifdef EXISTING_DEP
+	int base = existing_dep(x);
+#else
+	int base = x;
+#endif
+
+#ifdef PATCHED
+	return newly_referenced(base);
+#else
+	return base + 1;
+#endif
+}
tools/objtool/tests/generic/test-new-export-ref.sh new file +46 -0

46 lines not on this page · raw message

author maintainer
#100 lore raw

PATCH v5 34/58 objtool/klp: Add test for empty x86 alternative replacements

In reply to Song Liu

ALTERNATIVE_2("orig", "repl", ft1, "", ft2) produces a second entry whose replacement is empty. Its replacement offset still carries a relocation, but the label it points at is the end of the previous replacement -- which is also where the next one begins. The value is meaningless and only ever used with a length of zero, so cloning must not follow it.

The first version of this fixture passed with the fix reverted, because the empty entry pointed at its own end label rather than at the neighbour's replacement. It has to reach into another function's replacement to distinguish the behaviour.

This tests the behavior of commit 636f230ce21e ("objtool/klp: Ignore replacement offset of empty x86 alternatives").

Assisted-by Claude:claude-opus-4
Assisted-by Claude:claude-opus-5
---
 .../tests/x86/fixtures/empty_alternative.c    | 77 +++++++++++++++++++
 .../tests/x86/test-empty-alternative.sh       | 31 ++++++++
 2 files changed, 108 insertions(+)
 create mode 100644 tools/objtool/tests/x86/fixtures/empty_alternative.c
 create mode 100755 tools/objtool/tests/x86/test-empty-alternative.sh
tools/objtool/tests/x86/fixtures/empty_alternative.c new file +77 -0
new file mode 100644
index 000000000000..9336d74bfa92
@@ -0,0 +1,77 @@
+// SPDX-License-Identifier: GPL-2.0
+/*
+ * An x86 alternative with an empty replacement, as the second entry of
+ * ALTERNATIVE_2("orig", "repl", ft1, "", ft2) produces.  Its replacement
+ * offset still gets a relocation, but the label it points at is the end of the
+ * previous replacement, which is also where the *next* one begins -- here,
+ * neighbor()'s.  The value is meaningless; it is only ever used with a length
+ * of zero.
+ *
+ * struct alt_instr is written out by hand so the fixture builds without kernel
+ * headers: s32 instr_offset, s32 repl_offset, u32 ft_flags, u8 instrlen,
+ * u8 replacementlen.  The section carries an entsize because klp diff needs
+ * either that or an ANNOTATE_DATA_SPECIAL annotation to find entry boundaries.
+ *
+ * The replacement labels are global so the relocations name them rather than
+ * .altinstr_replacement plus an addend.
+ */
+
+static const char __modinfo[]
+	__attribute__((section(".modinfo"), used, aligned(1))) = "\0name=vmlinux";
+
+extern int neighbor_only(int x);
+
+int target(int x)
+{
+	asm volatile(
+		"661:	nop\n\t"
+		".pushsection .altinstr_replacement, \"ax\"\n\t"
+		".globl target_repl\n\t"
+		"target_repl:\n\t"
+		"	nop\n\t"
+		"target_repl_end:\n\t"
+		".popsection\n\t"
+		".pushsection .altinstructions, \"aM\", @progbits, 14\n\t"
+		/* a real replacement */
+		".long 661b - .\n\t"
+		".long target_repl - .\n\t"
+		".long 0\n\t"
+		".byte 1\n\t"
+		".byte target_repl_end - target_repl\n\t"
+		/* an empty one, pointing at neighbor()'s replacement */
+		".long 661b - .\n\t"
+		".long neighbor_repl - .\n\t"
+		".long 0\n\t"
+		".byte 1\n\t"
+		".byte 0\n\t"
+		".popsection\n\t");
+#ifdef PATCHED
+	return x + 2;
+#else
+	return x + 1;
+#endif
+}
+
+/*
+ * Unrelated, unpatched, and referencing a symbol nothing else does, so that
+ * dragging its replacement in is visible.
+ */
+int neighbor(int x)
+{
+	asm volatile(
+		"771:	nop\n\t"
+		".pushsection .altinstr_replacement, \"ax\"\n\t"
+		".globl neighbor_repl\n\t"
+		"neighbor_repl:\n\t"
+		"	call neighbor_only\n\t"
+		"neighbor_repl_end:\n\t"
+		".popsection\n\t"
+		".pushsection .altinstructions, \"aM\", @progbits, 14\n\t"
+		".long 771b - .\n\t"
+		".long neighbor_repl - .\n\t"
+		".long 0\n\t"
+		".byte 1\n\t"
+		".byte neighbor_repl_end - neighbor_repl\n\t"
+		".popsection\n\t");
+	return x;
+}
tools/objtool/tests/x86/test-empty-alternative.sh new file +31 -0
new file mode 100755
index 000000000000..9d40c3a405af
@@ -0,0 +1,31 @@
+#!/bin/bash
+# SPDX-License-Identifier: GPL-2.0
+#
+# An x86 alternative with an empty replacement still gets a relocation for its
+# replacement offset, but the label it points at is the end of the previous
+# replacement -- which is also the start of the next one.  The value is
+# meaningless, and get_alt_entry() already ignores it.
+#
+# Cloning it drags in an unrelated neighboring replacement and everything that
+# replacement references.  In the reported case an empty alternative in
+# meminfo_proc_show() pulled in one from proc_kcore_init(), emitting a klp
+# relocation against init text which is long freed by the time the patch is
+# applied.
+
+. "$(dirname "$0")/../lib.sh"
+
+setup
+build_pair empty_alternative.c
+
+assert_input_section .altinstructions
+assert_input_section .altinstr_replacement
+
+run_diff
+
+# target's own replacement comes along ...
+assert_symbol target_repl
+# ... neighbor's does not, nor what it references.
+assert_no_symbol neighbor_repl
+assert_no_symbol neighbor_only
+
+pass "empty alternative's replacement offset ignored when cloning"
Signature · 1 line
2.53.0-Meta
merge bot Applied
#101 lore raw

[tip: objtool/core] objtool/klp: Add test for empty x86 alternative replacements

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:     a249e6986f4cde3c88a09cdd44a7d88d44aea730
Gitweb:        https://git.kernel.org/tip/a249e6986f4cde3c88a09cdd44a7d88d44aea730
Author:        Song Liu <[email protected]>
AuthorDate:    Wed, 16 Sep 2026 11:43:27 -07:00
Committer:     Josh Poimboeuf <[email protected]>
CommitterDate: Wed, 16 Sep 2026 17:13:29 -07:00

objtool/klp: Add test for empty x86 alternative replacements

ALTERNATIVE_2("orig", "repl", ft1, "", ft2) produces a second entry whose replacement is empty. Its replacement offset still carries a relocation, but the label it points at is the end of the previous replacement -- which is also where the next one begins. The value is meaningless and only ever used with a length of zero, so cloning must not follow it.

The first version of this fixture passed with the fix reverted, because the empty entry pointed at its own end label rather than at the neighbour's replacement. It has to reach into another function's replacement to distinguish the behaviour.

This tests the behavior of commit 636f230ce21e ("objtool/klp: Ignore replacement offset of empty x86 alternatives").

Assisted-by Claude:claude-opus-4
Assisted-by Claude:claude-opus-5
---
 tools/objtool/tests/x86/fixtures/empty_alternative.c | 77 +++++++++++-
 tools/objtool/tests/x86/test-empty-alternative.sh    | 31 ++++-
 2 files changed, 108 insertions(+)
 create mode 100644 tools/objtool/tests/x86/fixtures/empty_alternative.c
 create mode 100755 tools/objtool/tests/x86/test-empty-alternative.sh
tools/objtool/tests/x86/fixtures/empty_alternative.c new file +77 -0
new file mode 100644
index 0000000..9336d74
@@ -0,0 +1,77 @@
+// SPDX-License-Identifier: GPL-2.0
+/*
+ * An x86 alternative with an empty replacement, as the second entry of
+ * ALTERNATIVE_2("orig", "repl", ft1, "", ft2) produces.  Its replacement
+ * offset still gets a relocation, but the label it points at is the end of the
+ * previous replacement, which is also where the *next* one begins -- here,
+ * neighbor()'s.  The value is meaningless; it is only ever used with a length
+ * of zero.
+ *
+ * struct alt_instr is written out by hand so the fixture builds without kernel
+ * headers: s32 instr_offset, s32 repl_offset, u32 ft_flags, u8 instrlen,
+ * u8 replacementlen.  The section carries an entsize because klp diff needs
+ * either that or an ANNOTATE_DATA_SPECIAL annotation to find entry boundaries.
+ *
+ * The replacement labels are global so the relocations name them rather than
+ * .altinstr_replacement plus an addend.
+ */
+
+static const char __modinfo[]
+	__attribute__((section(".modinfo"), used, aligned(1))) = "\0name=vmlinux";
+
+extern int neighbor_only(int x);
+
+int target(int x)
+{
+	asm volatile(
+		"661:	nop\n\t"
+		".pushsection .altinstr_replacement, \"ax\"\n\t"
+		".globl target_repl\n\t"
+		"target_repl:\n\t"
+		"	nop\n\t"
+		"target_repl_end:\n\t"
+		".popsection\n\t"
+		".pushsection .altinstructions, \"aM\", @progbits, 14\n\t"
+		/* a real replacement */
+		".long 661b - .\n\t"
+		".long target_repl - .\n\t"
+		".long 0\n\t"
+		".byte 1\n\t"
+		".byte target_repl_end - target_repl\n\t"
+		/* an empty one, pointing at neighbor()'s replacement */
+		".long 661b - .\n\t"
+		".long neighbor_repl - .\n\t"
+		".long 0\n\t"
+		".byte 1\n\t"
+		".byte 0\n\t"
+		".popsection\n\t");
+#ifdef PATCHED
+	return x + 2;
+#else
+	return x + 1;
+#endif
+}
+
+/*
+ * Unrelated, unpatched, and referencing a symbol nothing else does, so that
+ * dragging its replacement in is visible.
+ */
+int neighbor(int x)
+{
+	asm volatile(
+		"771:	nop\n\t"
+		".pushsection .altinstr_replacement, \"ax\"\n\t"
+		".globl neighbor_repl\n\t"
+		"neighbor_repl:\n\t"
+		"	call neighbor_only\n\t"
+		"neighbor_repl_end:\n\t"
+		".popsection\n\t"
+		".pushsection .altinstructions, \"aM\", @progbits, 14\n\t"
+		".long 771b - .\n\t"
+		".long neighbor_repl - .\n\t"
+		".long 0\n\t"
+		".byte 1\n\t"
+		".byte neighbor_repl_end - neighbor_repl\n\t"
+		".popsection\n\t");
+	return x;
+}
tools/objtool/tests/x86/test-empty-alternative.sh new file +31 -0
new file mode 100755
index 0000000..9d40c3a
@@ -0,0 +1,31 @@
+#!/bin/bash
+# SPDX-License-Identifier: GPL-2.0
+#
+# An x86 alternative with an empty replacement still gets a relocation for its
+# replacement offset, but the label it points at is the end of the previous
+# replacement -- which is also the start of the next one.  The value is
+# meaningless, and get_alt_entry() already ignores it.
+#
+# Cloning it drags in an unrelated neighboring replacement and everything that
+# replacement references.  In the reported case an empty alternative in
+# meminfo_proc_show() pulled in one from proc_kcore_init(), emitting a klp
+# relocation against init text which is long freed by the time the patch is
+# applied.
+
+. "$(dirname "$0")/../lib.sh"
+
+setup
+build_pair empty_alternative.c
+
+assert_input_section .altinstructions
+assert_input_section .altinstr_replacement
+
+run_diff
+
+# target's own replacement comes along ...
+assert_symbol target_repl
+# ... neighbor's does not, nor what it references.
+assert_no_symbol neighbor_repl
+assert_no_symbol neighbor_only
+
+pass "empty alternative's replacement offset ignored when cloning"