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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
author maintainer
#103 lore raw

PATCH v5 35/58 objtool/klp: Add test for recorded checksum values

In reply to Song Liu

Whether klp diff treats a function as changed is decided by its checksum, and until now nothing looked at one. A test asserting only that the right functions were cloned cannot tell a correct checksum from one that happens to differ.

Asserts both directions -- the changed function's checksum moves, the untouched one's does not -- and that checksumming identical input twice gives the same answer, since otherwise every rebuild reports spurious changes.

Assisted-by Claude:claude-opus-4
Assisted-by Claude:claude-opus-5
---
 .../tests/generic/test-checksum-value.sh      | 37 +++++++++++++++++++
 1 file changed, 37 insertions(+)
 create mode 100755 tools/objtool/tests/generic/test-checksum-value.sh
tools/objtool/tests/generic/test-checksum-value.sh new file +37 -0
new file mode 100755
index 000000000000..feae6a12e98d
@@ -0,0 +1,37 @@
+#!/bin/bash
+# SPDX-License-Identifier: GPL-2.0
+#
+# The per-function checksums klp checksum records are what klp diff uses to
+# decide which functions changed.  A checksum covering too little misses a real
+# change and the patch silently omits the function; one covering too much, or
+# unstable across identical input, clones functions nobody patched and drags
+# their dependencies in with them.
+#
+# test-basic covers which functions got cloned, which is downstream of this and
+# passes for either kind of wrong checksum as long as the two errors do not
+# happen to cancel.  This checks the checksums themselves.
+
+. "$(dirname "$0")/../lib.sh"
+
+setup
+build_pair basic.c
+
+assert_input_symbol changed
+assert_input_symbol untouched
+
+run_checksum
+
+# The edited function's checksum has to move, the untouched one's must not.
+assert_checksum_differs changed
+assert_checksum_matches untouched
+
+# And it has to be a function of the code, not of the build: checksumming the
+# same input twice has to give the same answer, or every rebuild reports
+# spurious changes.
+first="$(checksum_of orig.o changed)"
+build_pair basic.c
+run_checksum
+[ "$(checksum_of orig.o changed)" = "$first" ] ||
+	fail "checksum for 'changed' differs between builds of identical source"
+
+pass "checksums track the changed function and are stable across rebuilds"
Signature · 1 line
2.53.0-Meta
author maintainer
#106 lore raw

PATCH v5 36/58 objtool/klp: Add test for position-independent checksums

In reply to Song Liu

A function that only moves has not changed, and its checksum must not move with it. Otherwise every patch reports as changed everything that shifted because something ahead of it grew.

The fixture is built with -fno-function-sections, overriding the harness
default: with per-function sections every function sits at offset 0 of its own section and nothing ever moves, so the test would prove nothing. It also calls across to another function rather than looping within itself -- a loop branch keeps the same displacement wherever the function goes, so it is not position-dependent to begin with.

This tests the behavior of commit cca84cb12908 ("objtool/klp: Fix position-dependent checksums for non-relocated jumps/calls").

Assisted-by Claude:claude-opus-4
Assisted-by Claude:claude-opus-5
---
 .../generic/fixtures/checksum_position.c      | 42 ++++++++++++++++
 .../tests/generic/test-checksum-position.sh   | 50 +++++++++++++++++++
 2 files changed, 92 insertions(+)
 create mode 100644 tools/objtool/tests/generic/fixtures/checksum_position.c
 create mode 100755 tools/objtool/tests/generic/test-checksum-position.sh
tools/objtool/tests/generic/fixtures/checksum_position.c new file +42 -0
new file mode 100644
index 000000000000..4320bc220592
@@ -0,0 +1,42 @@
+// SPDX-License-Identifier: GPL-2.0
+/*
+ * A function whose position in the section changes between the two builds,
+ * without the function itself changing.
+ *
+ * target() calls callee() twice, and a call within the same section needs no
+ * relocation: the displacement is in the instruction.  It is that displacement
+ * which moves, and hashing those bytes makes the checksum move with it.  Both
+ * must therefore share a section, which is why the test passes
+ * -fno-function-sections.
+ *
+ * What has to change is the distance between the two, and PATCHED changes it
+ * by aligning them rather than by inserting a function between them.  Where a
+ * compiler puts an added function is its own business: gcc emits these in
+ * source order, so a function written between callee() and target() separates
+ * them, but clang emits target() immediately before callee() whatever the
+ * source says, and an added function lands ahead of both.  That moves target()
+ * without moving it relative to callee(), the displacement comes out identical
+ * in both builds, and the test passes without having asked anything.
+ *
+ * Alignment moves the functions apart on both, and moves neither function's
+ * own instructions -- which is exactly the distinction under test.
+ */
+
+#ifdef PATCHED
+#define MOVED	__attribute__((aligned(64)))
+#else
+#define MOVED
+#endif
+
+static const char __modinfo[]
+	__attribute__((section(".modinfo"), used, aligned(1))) = "\0name=vmlinux";
+
+__attribute__((noinline)) MOVED static int callee(int x)
+{
+	return x * 5 + 1;
+}
+
+__attribute__((noinline)) MOVED int target(int x)
+{
+	return callee(x) + callee(x + 1);
+}
tools/objtool/tests/generic/test-checksum-position.sh new file +50 -0

50 lines not on this page · raw message

Signature · 1 line
2.53.0-Meta
author maintainer
#112 lore raw

PATCH v5 37/58 objtool/klp: Add test for sympos in module objects

In reply to Song Liu

klp-sympos.c had no coverage at all. sympos disambiguates same-named symbols for livepatch, counting from 1, with 0 meaning the name is unique. Resolving to the wrong one is not a load failure -- it is a patch quietly wired to the wrong object.

Covers the module path, where the position is a count in symbol table order and klp diff can work it out from the object alone.

Assisted-by Claude:claude-opus-4
Assisted-by Claude:claude-opus-5
---
 .../tests/generic/fixtures/sympos_dup.c       | 32 ++++++++++++
 tools/objtool/tests/generic/test-sympos.sh    | 51 +++++++++++++++++++
 2 files changed, 83 insertions(+)
 create mode 100644 tools/objtool/tests/generic/fixtures/sympos_dup.c
 create mode 100755 tools/objtool/tests/generic/test-sympos.sh
tools/objtool/tests/generic/fixtures/sympos_dup.c new file +32 -0
new file mode 100644
index 000000000000..7eded9b12cfc
@@ -0,0 +1,32 @@
+// SPDX-License-Identifier: GPL-2.0
+/*
+ * A static whose name recurs in every translation unit that includes it.
+ * Compiled once for a single-copy object and twice, partially linked, for one
+ * with duplicates -- which is the only case where sympos is non-zero.
+ *
+ * FUNC_NAME keeps the referencing functions distinct so both get patched.
+ * Only the first copy carries .modinfo; two would be a second thing to
+ * disambiguate and is not what this fixture is about.
+ */
+
+#ifndef FUNC_NAME
+#define FUNC_NAME use_a
+#endif
+
+#ifndef NO_MODINFO
+static const char __modinfo[]
+	__attribute__((section(".modinfo"), used, aligned(1))) = "\0name=vmlinux";
+#endif
+
+/* volatile so it survives as an STT_OBJECT rather than being folded away */
+static volatile int dup_counter = 1;
+
+int FUNC_NAME(int x)
+{
+	dup_counter += x;
+#ifdef PATCHED
+	return dup_counter + 1;
+#else
+	return dup_counter;
+#endif
+}
tools/objtool/tests/generic/test-sympos.sh new file +51 -0

51 lines not on this page · raw message

Signature · 1 line
2.53.0-Meta
author maintainer
#115 lore raw

PATCH v5 38/58 objtool/klp: Add test for sympos resolved against a linked vmlinux

In reply to Song Liu

vmlinux is not like a module: the final link reorders sub-sections, so a symbol's position has to come from the linked image rather than from symbol table order. klp diff bridges that with .klp.symid, and looks for it only when the object it was handed is called vmlinux.o with a vmlinux beside it.

This was assigned to an end-to-end test on the assumption that it needs a real kernel build. It needs "ld -r" and "ld -e 0", and takes a fraction of a second.

The fixture places the static appearing first in the symbol table at the higher address, and the link passes --sort-section=name to force the reordering the kernel's linker script performs. Without that the two ways of computing sympos agree, and a first version passed with the vmlinux path disabled.

Assisted-by Claude:claude-opus-4
Assisted-by Claude:claude-opus-5
---
 .../tests/generic/fixtures/sympos_vmlinux.c   | 40 +++++++++++++
 .../tests/generic/test-sympos-vmlinux.sh      | 57 +++++++++++++++++++
 2 files changed, 97 insertions(+)
 create mode 100644 tools/objtool/tests/generic/fixtures/sympos_vmlinux.c
 create mode 100755 tools/objtool/tests/generic/test-sympos-vmlinux.sh
tools/objtool/tests/generic/fixtures/sympos_vmlinux.c new file +40 -0
new file mode 100644
index 000000000000..d5e70994c582
@@ -0,0 +1,40 @@
+// SPDX-License-Identifier: GPL-2.0
+/*
+ * Two translation units with a same-named static, placed so that the linker
+ * puts them in the opposite order to the one they appear in the symbol table.
+ *
+ * VARSEC selects the section the static lands in.  Linking with
+ * --sort-section=name then orders them alphabetically rather than by object
+ * order, so the first symbol in the symbol table ends up at the *higher*
+ * address.  That is the whole point: counting symbol table order and reading
+ * the linked image's addresses now give different answers, which is what makes
+ * it possible to tell which one klp diff used.
+ *
+ * Only use_a is patched, so exactly one sympos is emitted and there is nothing
+ * to attribute.
+ */
+
+#ifndef FUNC_NAME
+#define FUNC_NAME use_a
+#endif
+#ifndef VARSEC
+#define VARSEC ".data.mmm"
+#endif
+
+#ifndef NO_MODINFO
+static const char __modinfo[]
+	__attribute__((section(".modinfo"), used, aligned(1))) = "\0name=vmlinux";
+#endif
+
+/* volatile so it survives as an STT_OBJECT rather than being folded away */
+static volatile int dup_counter __attribute__((section(VARSEC))) = 1;
+
+int FUNC_NAME(int x)
+{
+	dup_counter += x;
+#ifdef PATCHED
+	return dup_counter + 1;
+#else
+	return dup_counter;
+#endif
+}
tools/objtool/tests/generic/test-sympos-vmlinux.sh new file +57 -0

57 lines not on this page · raw message

Signature · 1 line
2.53.0-Meta
author maintainer
#118 lore raw

PATCH v5 39/58 objtool/klp: Add test for static locals which must not be correlated

In reply to Song Liu

Most static locals have to be correlated so the patched code keeps using the running kernel's copy. Two kinds must not: anything in .data..once, the flag behind WARN_ONCE and friends, and the well-known names the kernel generates for per-instance things (__warned, __key, __func__).

Sharing a .data..once flag means a patch inherits "already warned" from before it was applied, and the warning it was meant to surface never fires.

The fixture deliberately does not name its .data..once variable __warned:
the name rule would then catch it and the section rule would go untested. gcc spells these <var>.<id> and Clang <func>.<var>, so both are covered.

This tests the behavior of commit ff529864e738 ("objtool/klp: Fix .data..once static local non-correlation") and commit 84c304a534b8 ("objtool/klp: Fix is_uncorrelated_static_local() for Clang").

Assisted-by Claude:claude-opus-4
Assisted-by Claude:claude-opus-5
---
 .../fixtures/static_local_uncorrelated.c      | 41 +++++++++++++++++++
 .../generic/test-static-local-uncorrelated.sh | 41 +++++++++++++++++++
 2 files changed, 82 insertions(+)
 create mode 100644 tools/objtool/tests/generic/fixtures/static_local_uncorrelated.c
 create mode 100755 tools/objtool/tests/generic/test-static-local-uncorrelated.sh
tools/objtool/tests/generic/fixtures/static_local_uncorrelated.c new file +41 -0
new file mode 100644
index 000000000000..cb4cdd7a496e
@@ -0,0 +1,41 @@
+// SPDX-License-Identifier: GPL-2.0
+/*
+ * Static locals of three kinds, in one patched function.
+ *
+ * Most static locals must be correlated, so the patched code keeps using the
+ * running kernel's copy.  Two kinds must not:
+ *
+ *   - anything in .data..once, the flag behind WARN_ONCE and friends.  Sharing
+ *     it would mean a patch inherits "already warned" from before the patch.
+ *   - the well-known names the kernel generates for such things (__warned,
+ *     __key, __func__, ...), which are per-instance by nature.  gcc names them
+ *     <var>.<id> and Clang <func>.<var>, so both spellings have to be caught.
+ */
+
+static const char __modinfo[]
+	__attribute__((section(".modinfo"), used, aligned(1))) = "\0name=vmlinux";
+
+int target(int x)
+{
+	/*
+	 * A .data..once variable whose name is *not* on the list below, so
+	 * only the section can disqualify it.  Naming it __warned would let
+	 * the name rule catch it and the section rule go untested.
+	 */
+	static int once_flag __attribute__((section(".data..once")));
+	/* a never-correlate name, in an ordinary section */
+	static int __key;
+	/* and one that must be correlated */
+	static int ordinary;
+
+	if (!once_flag)
+		once_flag = 1;
+	__key += x;
+	ordinary += x;
+
+#ifdef PATCHED
+	return __key + ordinary + once_flag + 2;
+#else
+	return __key + ordinary + once_flag + 1;
+#endif
+}
tools/objtool/tests/generic/test-static-local-uncorrelated.sh new file +41 -0

41 lines not on this page · raw message

Signature · 1 line
2.53.0-Meta
author maintainer
#121 lore raw

PATCH v5 40/58 objtool/klp: Add test for __bug_table, __ex_table and __mcount_loc extraction

In reply to Song Liu

Three special sections with no coverage. An entry that is not carried into the patch is not a build failure: the patched function simply loses its WARN_ON location, its exception fixup, or its ftrace callsite, and nobody finds out until one of them is needed.

Assisted-by Claude:claude-opus-4
Assisted-by Claude:claude-opus-5
---
 .../tests/x86/fixtures/special_sections.c     | 77 +++++++++++++++++++
 .../tests/x86/test-special-sections.sh        | 42 ++++++++++
 2 files changed, 119 insertions(+)
 create mode 100644 tools/objtool/tests/x86/fixtures/special_sections.c
 create mode 100755 tools/objtool/tests/x86/test-special-sections.sh
tools/objtool/tests/x86/fixtures/special_sections.c new file +77 -0
new file mode 100644
index 000000000000..d42798848fda
@@ -0,0 +1,77 @@
+// SPDX-License-Identifier: GPL-2.0
+/*
+ * A special section entry belonging to a patched function.  SPECIAL_SEC picks
+ * which section, since klp diff treats eight of them alike and each needs
+ * extracting for the patched function and no other.
+ *
+ * The entry is written out by hand so the fixture builds without kernel
+ * headers.  Only the leading relocation matters to klp diff; the rest is
+ * padded to the section's real entry size, because the entries have to be the
+ * right length for the boundaries between them to fall in the right places.
+ *
+ * SPECIAL_RELOCS covers __ex_table, whose entries relocate both the faulting
+ * instruction and its fixup; objtool rejects one with only the first.
+ */
+
+#ifndef SPECIAL_SEC
+#define SPECIAL_SEC "__bug_table"
+#endif
+#ifndef SPECIAL_ENTSIZE
+#define SPECIAL_ENTSIZE 12
+#endif
+#ifndef SPECIAL_RELOCS
+#define SPECIAL_RELOCS 1
+#endif
+
+#define STR_(x) #x
+#define STR(x) STR_(x)
+
+static const char __modinfo[]
+	__attribute__((section(".modinfo"), used, aligned(1))) = "\0name=vmlinux";
+
+/*
+ * other() gets an entry of its own, so that "the untouched function's entry
+ * was not dragged in" is a question the section can actually answer.  With
+ * only target() contributing, there is nothing for klp diff to leave behind
+ * and the negative assertion holds however the extraction behaves.
+ */
+int other(int x)
+{
+	asm volatile(
+		"3:	nop\n\t"
+		"4:\n\t"
+		".pushsection " SPECIAL_SEC ", \"aM\", @progbits, "
+			STR(SPECIAL_ENTSIZE) "\n\t"
+		".long 3b - .\n\t"
+#if SPECIAL_RELOCS > 1
+		".long 4b - .\n\t"
+		".fill " STR(SPECIAL_ENTSIZE) " - 8, 1, 0\n\t"
+#else
+		".fill " STR(SPECIAL_ENTSIZE) " - 4, 1, 0\n\t"
+#endif
+		".popsection\n\t");
+
+	return x + 9;
+}
+
+int target(int x)
+{
+	asm volatile(
+		"1:	nop\n\t"
+		"2:\n\t"
+		".pushsection " SPECIAL_SEC ", \"aM\", @progbits, "
+			STR(SPECIAL_ENTSIZE) "\n\t"
+		".long 1b - .\n\t"
+#if SPECIAL_RELOCS > 1
+		".long 2b - .\n\t"
+		".fill " STR(SPECIAL_ENTSIZE) " - 8, 1, 0\n\t"
+#else
+		".fill " STR(SPECIAL_ENTSIZE) " - 4, 1, 0\n\t"
+#endif
+		".popsection\n\t");
+#ifdef PATCHED
+	return x + 2;
+#else
+	return x + 1;
+#endif
+}
tools/objtool/tests/x86/test-special-sections.sh new file +42 -0

42 lines not on this page · raw message

Signature · 1 line
2.53.0-Meta
author maintainer
#124 lore raw

PATCH v5 41/58 objtool/klp: Add test for kCFI prefix symbols and traps

In reply to Song Liu

Two properties, asserted separately because they fail differently:

- the __cfi_<func> prefix symbol has to be carried with the patched function, or the function has no type identity and indirect calls to it trap;
- its .kcfi_traps entry has to be extracted, or the trap is not recognised as a CFI failure and a clean report becomes an oops.

test-special-section hand-assembles a .kcfi_traps entry, which is what makes it catch commit 7df1638df97b ("objtool/klp: Fix .kcfi_traps special section extraction"). Nothing until now built real kCFI code.

This tests the behavior of commit da4326573ae8 ("objtool/klp: Fix kCFI trap handling"). Commit f7ceffd21a8a ("objtool/klp: Fix kCFI prefix finding/cloning") cannot be tested as such, its code having been rewritten by commit fe6a87e0abac ("objtool: Improve and simplify prefix symbol detection"); this guards the current implementation's behaviour instead.

Assisted-by Claude:claude-opus-4
Assisted-by Claude:claude-opus-5
---
 tools/objtool/tests/x86/fixtures/kcfi.c | 39 +++++++++++++++++++++++++
 tools/objtool/tests/x86/test-kcfi.sh    | 39 +++++++++++++++++++++++++
 2 files changed, 78 insertions(+)
 create mode 100644 tools/objtool/tests/x86/fixtures/kcfi.c
 create mode 100755 tools/objtool/tests/x86/test-kcfi.sh
tools/objtool/tests/x86/fixtures/kcfi.c new file +39 -0
new file mode 100644
index 000000000000..b62fc60634cf
@@ -0,0 +1,39 @@
+// SPDX-License-Identifier: GPL-2.0
+/*
+ * An indirect call, which under kCFI is preceded by a type check and a trap.
+ *
+ * Clang emits a __cfi_<func> prefix symbol carrying the type hash ahead of
+ * every address-taken function, and records the trap site in .kcfi_traps.
+ * Both belong to the function and both have to come with it into a patch.
+ *
+ * Needs -fsanitize=kcfi, which only Clang has.
+ */
+
+static const char __modinfo[]
+	__attribute__((section(".modinfo"), used, aligned(1))) = "\0name=vmlinux";
+
+static int impl_a(int x)
+{
+	return x + 1;
+}
+
+static int impl_b(int x)
+{
+	return x * 2;
+}
+
+__attribute__((noinline)) int (*pick(int x))(int)
+{
+	return (x & 1) ? impl_a : impl_b;
+}
+
+int target(int x)
+{
+	int (*fn)(int arg) = pick(x);
+
+#ifdef PATCHED
+	return fn(x) + 2;
+#else
+	return fn(x) + 1;
+#endif
+}
tools/objtool/tests/x86/test-kcfi.sh new file +39 -0
new file mode 100755
index 000000000000..b583ef608747
@@ -0,0 +1,39 @@
+#!/bin/bash
+# SPDX-License-Identifier: GPL-2.0
+#
+# Under kCFI an indirect call checks a type hash before jumping, and traps on a
+# mismatch.  Two things belong to the calling function and must come with it
+# into a patch:
+#
+#   - the __cfi_<func> prefix symbol holding the hash.  Lose it and the patched
+#     function has no type identity, so indirect calls to it trap.
+#   - its .kcfi_traps entry.  Lose that and the trap is not recognised as a
+#     CFI failure, so what should be a clean report becomes an oops.
+#
+# Neither shows up at build time.
+
+. "$(dirname "$0")/../lib.sh"
+
+clang_only "kCFI is a Clang feature"
+
+setup
+
+# Declared above that this is Clang's; a given Clang may still be too old.
+cc_supports -fsanitize=kcfi ||
+	probe_skip "this clang does not support -fsanitize=kcfi"
+
+build_pair kcfi.c -fsanitize=kcfi
+
+assert_input_section .kcfi_traps
+assert_input_symbol __cfi_target
+
+run_diff
+
+assert_patched target
+
+# The prefix symbol comes with its function ...
+assert_symbol __cfi_target
+# ... and so does the trap entry.
+assert_section .kcfi_traps
+
+pass "kCFI prefix symbol and trap entry carried with the patched function"
Signature · 1 line
2.53.0-Meta
author maintainer
#127 lore raw

PATCH v5 42/58 objtool/klp: Add test for symbols whose linkage the patch changes

In reply to Song Liu

A patch can move a symbol between static and global without renaming it:
dropping "static" from a helper so something else can call it, or adding it to one that is no longer shared. Correlation keys off more than the name, so a symbol whose binding moved has to still pair with itself.

Failing to is not a build failure. The symbol looks new, and a new data symbol is either rejected or cloned as a second copy -- at which point the patched code updates its own private variable while the rest of the kernel keeps reading the original.

The test covers both directions in one fixture, a function going global and a variable going static, and asserts the outcome rather than the absence of a warning: each symbol resolves back to the kernel's copy through a klp symbol, and neither is cloned into the patch.

An earlier version asserted only that no "no correlation" or "changed data" message appeared, and passed with correlation deliberately broken. What the messages say and what the patch contains are not the same question.

Verified to fail with correlation made to require matching symbol bindings.

Assisted-by Claude:claude-opus-4
Assisted-by Claude:claude-opus-5
---
 .../tests/generic/fixtures/local_to_global.c  | 34 ++++++++++
 .../generic/test-local-to-global-flip.sh      | 63 +++++++++++++++++++
 2 files changed, 97 insertions(+)
 create mode 100644 tools/objtool/tests/generic/fixtures/local_to_global.c
 create mode 100755 tools/objtool/tests/generic/test-local-to-global-flip.sh
tools/objtool/tests/generic/fixtures/local_to_global.c new file +34 -0
new file mode 100644
index 000000000000..3c9eb9200ce5
@@ -0,0 +1,34 @@
+// SPDX-License-Identifier: GPL-2.0
+/*
+ * A function which the patch changes from static to non-static, and a variable
+ * that goes the other way.  The names are unchanged; only the binding moves.
+ */
+
+static const char __modinfo[]
+	__attribute__((section(".modinfo"), used, aligned(1))) = "\0name=vmlinux";
+
+/* noinline, or the static one is folded into its caller and has no symbol */
+#ifdef PATCHED
+__attribute__((noinline)) int flipped_up(int x)		/* was static */
+#else
+__attribute__((noinline)) static int flipped_up(int x)
+#endif
+{
+	return x + 1;
+}
+
+#ifdef PATCHED
+static volatile int flipped_down = 5;	/* was global */
+#else
+volatile int flipped_down = 5;
+#endif
+
+int caller(int x)
+{
+	flipped_down += x;
+#ifdef PATCHED
+	return flipped_up(x) + flipped_down + 2;
+#else
+	return flipped_up(x) + flipped_down + 1;
+#endif
+}
tools/objtool/tests/generic/test-local-to-global-flip.sh new file +63 -0

63 lines not on this page · raw message

Signature · 1 line
2.53.0-Meta
author maintainer
#130 lore raw

PATCH v5 43/58 objtool/klp: Test rejection of a file-local static branch key

In reply to Song Liu

A static branch key owned by a module cannot be reached with a klp reloc:
late module patching allows the livepatch module to load first, leaving the __jump_table entry unresolved for jump_label_add_module() to dereference. validate_special_section_klp_reloc() rejects it at build time.

test-jump-label-module-key covers that for a global key. A file-local one takes a different route to the same check: the compiler references a static through its section symbol plus an addend, so the key has to be resolved from the section before it can be recognised as STT_OBJECT at all. Until commit f9fb44b0ecef ("objtool/klp: Fix detection of corrupt static branch/call entries") it was not, and the reference was silently emitted.

Give the fixture a STATIC_KEY knob and cover it. The test checks that the input really does reference the key through its section, since without that it is only a second copy of the existing test.

Verified by reverting commit f9fb44b0ecef ("objtool/klp: Fix detection of corrupt static branch/call entries"): klp diff accepts the input and the test fails, under both gcc and clang.

Assisted-by Claude:claude-opus-4
Assisted-by Claude:claude-opus-5
---
 .../test-jump-label-module-static-key.sh      | 45 +++++++++++++++++++
 1 file changed, 45 insertions(+)
 create mode 100755 tools/objtool/tests/generic/test-jump-label-module-static-key.sh
tools/objtool/tests/generic/test-jump-label-module-static-key.sh new file +45 -0
new file mode 100755
index 000000000000..7bdcbaf2fa60
@@ -0,0 +1,45 @@
+#!/bin/bash
+# SPDX-License-Identifier: GPL-2.0
+#
+# A static branch key owned by a module is rejected whether the key is global
+# or file-local.
+#
+# The rejection matters because late module patching allows the livepatch
+# module to load before the module it depends on: the __jump_table klp reloc is
+# then unresolved, and jump_label_add_module() dereferences an uninitialized
+# pointer.  Catching it at build time is the only defence.
+#
+# test-jump-label-module-key covers the global key.  A file-local one reaches
+# the same check by a different route: the compiler emits the reference against
+# the section symbol plus an addend, so validate_special_section_klp_reloc()
+# has to resolve it to the underlying object before it can see a key at all.
+# Until it did, a static key was passed over as "not STT_OBJECT" and the
+# unsupported reference was emitted with nothing said.
+#
+# Fixed by f9fb44b0ecef ("objtool/klp: Fix detection of corrupt static
+# branch/call entries").
+
+. "$(dirname "$0")/../lib.sh"
+
+setup
+build_pair jump_label.c -DSTATIC_KEY -DMODNAME='"klp_testmod"'
+
+require_input_section __jump_table
+
+# The premise: the key is reached through its section symbol, not by name.
+# Without that this is just a second copy of test-jump-label-module-key.
+input_jump_relocs="$(in_relocs orig.o | awk '/rela__jump_table/,/^$/')"
+
+echo "$input_jump_relocs" | grep -q klp_test_key ||
+	fail "fixture produced no __jump_table reference to the key"
+echo "$input_jump_relocs" | grep -qE '\.(bss|data)\.klp_test_key' ||
+	probe_skip "compiler referenced the static key by name, not through its section"
+
+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 file-local static branch key rejected"
Signature · 1 line
2.53.0-Meta
author maintainer
#135 lore raw

PATCH v5 44/58 objtool/klp: Test a hand-built livepatch module's static call keys

In reply to Song Liu

__SCK__* static call keys are not exported; modules are given read-only access at load time. Livepatch modules built by klp-build do have full access to theirs, and commit 164c9201e1da ("objtool: Add base objtool support for livepatch modules") added a check on that basis -- but a livepatch module can also be written by hand, as everything under samples/livepatch is, and such a module hits an unexported key as soon as it does anything expanding to a static call. With CONFIG_MEM_ALLOC_PROFILING_DEBUG that includes allocating memory, which is how livepatch-shadow-fix1 came to fail to build.

Cover it, with the plain module as a control: it takes the same path and has always been accepted, so a test that built only the livepatch variant could not tell this fix from the check being deleted.

This is objtool's ordinary check pass rather than a klp subcommand, which is the first test here to exercise it -- and is the point, since that pass is what runs over a hand-built livepatch module during a normal kernel build.

Verified by reverting commit f495054bd12e ("objtool/klp: Fix unexported static call key access for manually built livepatch modules"): objtool reports "can't find static_call_key symbol: __SCK__klp_test_call" and the test fails, under both gcc and clang.

Assisted-by Claude:claude-opus-4
Assisted-by Claude:claude-opus-5
---
 .../tests/x86/fixtures/static_call_no_key.c   | 32 +++++++++++++++
 .../tests/x86/test-manual-klp-static-call.sh  | 40 +++++++++++++++++++
 2 files changed, 72 insertions(+)
 create mode 100644 tools/objtool/tests/x86/fixtures/static_call_no_key.c
 create mode 100755 tools/objtool/tests/x86/test-manual-klp-static-call.sh
tools/objtool/tests/x86/fixtures/static_call_no_key.c new file +32 -0
new file mode 100644
index 000000000000..748ba7c0f86d
@@ -0,0 +1,32 @@
+// SPDX-License-Identifier: GPL-2.0
+/*
+ * A static call to a trampoline whose key symbol this object cannot see.
+ *
+ * That is the normal situation for a module: __SCK__* keys are not exported,
+ * and read-only access is granted at load time instead.  objtool's static call
+ * handling has to accept it for any module, including a livepatch module built
+ * by hand rather than by klp-build.
+ *
+ * LIVEPATCH adds the .modinfo tag which makes objtool treat this as a
+ * livepatch module.
+ */
+
+static const char __modinfo[]
+	__attribute__((section(".modinfo"), used, aligned(1))) =
+#ifdef LIVEPATCH
+	"\0livepatch=Y"
+#endif
+	"\0name=klp_testmod";
+
+/*
+ * The trampoline is undefined here, exactly as it is for a module calling a
+ * static call defined in vmlinux.  No __SCK__klp_test_call accompanies it.
+ */
+extern void __SCT__klp_test_call(void);
+
+int target(int x)
+{
+	__asm__ volatile("call __SCT__klp_test_call\n\t" ::: "memory");
+
+	return x + 1;
+}
tools/objtool/tests/x86/test-manual-klp-static-call.sh new file +40 -0
new file mode 100755
index 000000000000..6c4d275e3549
@@ -0,0 +1,40 @@
+#!/bin/bash
+# SPDX-License-Identifier: GPL-2.0
+#
+# objtool's static call handling must accept a livepatch module which cannot
+# see a static call's key symbol.
+#
+# __SCK__* keys are not exported; modules get read-only access at load time
+# instead.  Livepatch modules built by klp-build do have full access to their
+# keys, and a check was added on the strength of that -- but a livepatch module
+# can also be written by hand, and samples/livepatch is full of them.  One of
+# those needs a key it cannot see as soon as it does anything that expands to a
+# static call, which with CONFIG_MEM_ALLOC_PROFILING_DEBUG includes allocating
+# memory:
+#
+#   samples/livepatch/livepatch-shadow-fix1.o: error: objtool: static_call:
+#     can't find static_call_key symbol: __SCK__WARN_trap
+#
+# The module built without the livepatch tag is the control: it takes the same
+# path and has always been accepted, so a test which only built the livepatch
+# one could not tell this fix from the check being removed altogether.
+#
+# Fixed by f495054bd12e ("objtool/klp: Fix unexported static call key access
+# for manually built livepatch modules").
+
+. "$(dirname "$0")/../lib.sh"
+
+setup
+
+# Not a klp subcommand: this is objtool's ordinary check pass, which is what
+# runs over a hand-built livepatch module during a normal kernel build.
+for tag in "" -DLIVEPATCH; do
+	build_one static_call_no_key.c mod.o $tag
+
+	"$OBJTOOL" --module --static-call "$workdir/mod.o" \
+		> "$workdir/objtool.log" 2>&1 ||
+		fail "objtool rejected a ${tag:+livepatch }module which cannot" \
+		     "see its static call key: $(tail -1 "$workdir/objtool.log")"
+done
+
+pass "livepatch module accepted without access to its static call key"
Signature · 1 line
2.53.0-Meta
author maintainer
#138 lore raw

PATCH v5 45/58 objtool/klp: Test text annotations on alternative replacements

In reply to Song Liu

The kernel annotates instructions inside an ALTERNATIVE's replacement wherever objtool has to be told something about them -- a retpoline-safe indirect branch, a deliberately absent ENDBR. klp diff dropped those annotations, for two reasons: replacement code has no real symbol, so the NOTYPE fake symbol objtool invents for it was not recognised as worth keeping a reference to, and .discard.annotate_insn was processed before .altinstructions, so the replacement it named had no clone yet.

Nothing fails at build time when the annotation goes missing. It surfaces later as objtool warning about, or rejecting, the very code the annotation was there to explain.

The fixture keeps the replacement label global, as empty_alternative.c does, so the relocations name it instead of .altinstr_replacement plus an addend -- which klp diff rejects outright. The label is still NOTYPE, which is the property under test. The test asserts the relocation as well as the section, since an entry whose relocation was dropped would otherwise pass.

Verified by reverting commit 62a7a01fde87 ("objtool/klp: Fix extraction of text annotations for alternatives"): the output has no .discard.annotate_insn at all and the test fails, under both gcc and clang.

Assisted-by Claude:claude-opus-5
---
 .../objtool/tests/x86/fixtures/alt_annotate.c | 57 +++++++++++++++++++
 .../objtool/tests/x86/test-alt-annotation.sh  | 38 +++++++++++++
 2 files changed, 95 insertions(+)
 create mode 100644 tools/objtool/tests/x86/fixtures/alt_annotate.c
 create mode 100755 tools/objtool/tests/x86/test-alt-annotation.sh
tools/objtool/tests/x86/fixtures/alt_annotate.c new file +57 -0
new file mode 100644
index 000000000000..af44d320dcb0
@@ -0,0 +1,57 @@
+// SPDX-License-Identifier: GPL-2.0
+/*
+ * An x86 alternative whose replacement instruction carries a text annotation.
+ *
+ * The kernel does this wherever an ALTERNATIVE contains something objtool has
+ * to be told about -- a retpoline-safe indirect branch, an intentionally
+ * missing ENDBR -- so the .discard.annotate_insn entry references an address
+ * inside .altinstr_replacement rather than inside a function.
+ *
+ * Two things make that awkward for klp diff, and both are why this fixture
+ * exists.  Replacement code has no real symbol: objtool invents a NOTYPE fake
+ * symbol for it, so an annotation pointing there does not reference a FUNC.
+ * And .discard.annotate_insn has to be cloned after .altinstructions, or the
+ * replacement it names has no clone to point at yet.
+ *
+ * struct alt_instr is written out by hand as in empty_alternative.c: s32
+ * instr_offset, s32 repl_offset, u32 ft_flags, u8 instrlen, u8 replacementlen,
+ * with an entsize so klp diff can find the entry boundaries.
+ * .discard.annotate_insn entries are s32 offset, s32 type; type 2 is
+ * ANNOTYPE_RETPOLINE_SAFE.
+ *
+ * The replacement label is global so the relocations name it rather than
+ * .altinstr_replacement plus an addend, which klp diff cannot convert.  It is
+ * still NOTYPE, which is the shape that matters here.
+ */
+
+static const char __modinfo[]
+	__attribute__((section(".modinfo"), used, aligned(1))) = "\0name=vmlinux";
+
+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"
+		/* The annotation lands inside the replacement. */
+		".pushsection .discard.annotate_insn, \"M\", @progbits, 8\n\t"
+		".long target_repl - .\n\t"
+		".long 2\n\t"
+		".popsection\n\t"
+		"target_repl_end:\n\t"
+		".popsection\n\t"
+		".pushsection .altinstructions, \"aM\", @progbits, 14\n\t"
+		".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"
+		".popsection\n\t");
+#ifdef PATCHED
+	return x + 2;
+#else
+	return x + 1;
+#endif
+}
tools/objtool/tests/x86/test-alt-annotation.sh new file +38 -0
new file mode 100755
index 000000000000..96760e6df9e5
@@ -0,0 +1,38 @@
+#!/bin/bash
+# SPDX-License-Identifier: GPL-2.0
+#
+# A text annotation on an instruction inside an alternative's replacement must
+# be carried into the patch.
+#
+# The kernel annotates replacement code wherever objtool has to be told
+# something about it -- a retpoline-safe indirect branch, a deliberately absent
+# ENDBR.  Two things made klp diff drop those annotations:
+#
+#   - replacement code has no real symbol, so objtool invents a NOTYPE fake
+#     one, and the extraction only kept references to FUNC symbols;
+#   - .discard.annotate_insn was processed before .altinstructions, so the
+#     replacement it referenced had no clone to point at yet.
+#
+# Nothing fails at build time when the annotation goes missing.  It surfaces
+# later as objtool warning about, or rejecting, the patched code it was there
+# to explain.
+#
+# Fixed by 62a7a01fde87 ("objtool/klp: Fix extraction of text annotations for
+# alternatives").
+
+. "$(dirname "$0")/../lib.sh"
+
+setup
+build_pair alt_annotate.c
+
+assert_input_section .altinstructions
+assert_input_section .discard.annotate_insn
+
+run_diff
+
+# The annotation has to survive, and to still name the replacement.  Checking
+# only the section would pass on an entry whose relocation was dropped.
+assert_section .discard.annotate_insn
+assert_reloc_sym .discard.annotate_insn target_repl
+
+pass "text annotation on an alternative replacement carried into the patch"
Signature · 1 line
2.53.0-Meta
author maintainer
#141 lore raw

PATCH v5 46/58 objtool/klp: Add test for data object checksums

In reply to Song Liu

klp checksum hashes a data symbol's length, its bytes, and every relocation it carries -- as the target's name and adjusted addend, except a reference into a string section, which contributes the string's contents instead. Nothing covered any of it.

Each is load-bearing, and the failure is always the same shape: a checksum which ignores one calls a changed object unchanged, klp diff leaves it out of the patch, and the patched code goes on reading the kernel's old copy. The string case cannot be caught by hashing bytes: the pointer is identical, same section and same offset, and only the text it refers to moved.

One fixture, six variants applied to the patched build alone. Each was verified by sabotaging the line it covers and watching the test fail:

  raw bytes            initialiser change
  length               a .bss object grows; its bytes are never hashed
  string contents      literal edited in place, pointer untouched
  reloc target name    pointer moved to another function
  reloc addend         same array, different index
  section-symbol path  the same, via a static's section symbol

Two of those needed the fixture rebuilding. An initialised array does not isolate the length, because growing one changes the hashed bytes too -- hence .bss, where there are none. And a named char[] does not reach the contents-hashing path at all: that keys on SHF_STRINGS, which the compiler sets on the mergeable section a literal lands in and not on an array given a section of its own.

Assisted-by Claude:claude-opus-4
Assisted-by Claude:claude-opus-5
---
 .../tests/generic/fixtures/checksum_data.c    | 116 ++++++++++++++++++
 .../tests/generic/test-checksum-data.sh       |  61 +++++++++
 2 files changed, 177 insertions(+)
 create mode 100644 tools/objtool/tests/generic/fixtures/checksum_data.c
 create mode 100755 tools/objtool/tests/generic/test-checksum-data.sh
tools/objtool/tests/generic/fixtures/checksum_data.c new file +116 -0
new file mode 100644
index 000000000000..6310af5c02d3
@@ -0,0 +1,116 @@
+// SPDX-License-Identifier: GPL-2.0
+/*
+ * Data objects whose checksums must move for reasons the raw bytes do not
+ * show.
+ *
+ * checksum_update_object() hashes a data symbol's length and its bytes, and
+ * then walks its relocations: a reference into a string section contributes
+ * the string's *contents*, and any other reference contributes the target
+ * symbol's name and the adjusted addend.  So three changes that leave the
+ * object's own bytes identical still have to change its checksum:
+ *
+ * Each variant is selected by a -D on the patched build only, so the original
+ * is always the baseline:
+ *
+ *   WHICH_FUNC   the function pointer points somewhere else
+ *   WHICH_STR    the string pointer points at a different literal
+ *   STR_CONTENT  the string it points at is edited in place
+ *   WHICH_SLOT   the same array, at a different index: addend only
+ *   WHICH_PRIV   likewise, but a static, reached through its section symbol
+ *
+ * The last is the interesting one.  Nothing in the pointer changes -- same
+ * section, same offset -- so a checksum that hashed only the relocation and
+ * not what it referred to would call the object unchanged, and the patched
+ * kernel would keep the old string.
+ */
+
+static const char __modinfo[]
+	__attribute__((section(".modinfo"), used, aligned(1))) = "\0name=vmlinux";
+
+int callee_a(int x);
+int callee_b(int x);
+int callee_a(int x) { return x + 1; }
+int callee_b(int x) { return x + 2; }
+
+/*
+ * String *literals*, not named arrays.  The contents-hashing path keys on
+ * SHF_STRINGS, which the compiler sets on the mergeable .rodata.str1.1 a
+ * literal lands in and not on a named char[] given a section of its own.  A
+ * fixture using the latter exercises the ordinary name-and-addend path and
+ * reports nothing when the text changes.
+ */
+#if defined(PATCHED) && defined(STR_CONTENT)
+#define MESSAGE "edited"
+#else
+#define MESSAGE "original"
+#endif
+
+/* A plain data object: only its own bytes decide the checksum. */
+#if defined(PATCHED) && defined(PLAIN_VALUE)
+int plain = 43;
+#else
+int plain = 42;
+#endif
+
+/*
+ * A .bss object, where length is the only thing there is to hash: the section
+ * has no data, so the bytes are skipped and only sym->len distinguishes this
+ * from an object of another size.  An initialised array would not isolate it
+ * -- growing one changes the hashed bytes as well.
+ */
+#if defined(PATCHED) && defined(LONGER)
+char sized[4];
+#else
+char sized[2];
+#endif
+
+/*
+ * A reference into the middle of an array: same target symbol, different
+ * addend.  Nothing else in the object changes, so this is the only way to see
+ * whether the addend is hashed at all.
+ */
+int slots[4];
+
+/*
+ * A file-local array.  A reference to a static lands on its section symbol
+ * plus an offset, so the hash has to resolve that back to the underlying
+ * object before it has a name to hash at all -- a different code path from the
+ * global above, and one that silently contributes nothing when it fails.
+ */
+static int priv_slots[4];
+
+struct desc {
+	int (*fn)(int arg);
+	const char *str;
+	int *slot;
+	int *priv;
+};
+
+const struct desc descriptor = {
+#if defined(PATCHED) && defined(WHICH_FUNC)
+	.fn = callee_b,
+#else
+	.fn = callee_a,
+#endif
+#if defined(PATCHED) && defined(WHICH_STR)
+	.str = "a different literal",
+#else
+	.str = MESSAGE,
+#endif
+#if defined(PATCHED) && defined(WHICH_SLOT)
+	.slot = &slots[2],
+#else
+	.slot = &slots[1],
+#endif
+#if defined(PATCHED) && defined(WHICH_PRIV)
+	.priv = &priv_slots[3],
+#else
+	.priv = &priv_slots[1],
+#endif
+};
+
+int target(int x)
+{
+	return descriptor.fn(x) + plain + sized[0] + (int)descriptor.str[0] +
+	       *descriptor.slot + *descriptor.priv;
+}
tools/objtool/tests/generic/test-checksum-data.sh new file +61 -0

61 lines not on this page · raw message

Signature · 1 line
2.53.0-Meta
author maintainer
#144 lore raw

PATCH v5 47/58 objtool/klp: Add test for symbols with no checksum entry of their own

In reply to Song Liu

.discard.sym_checksum is an array of { address, checksum } looked up by the address a relocation points at, so the invariant is one entry per address. calculate_checksums() skips zero-length symbols, aliases and cold parts to keep it, and nothing checked that it does.

A duplicate entry is not a build failure. It makes the lookup ambiguous, and whichever checksum loses is never consulted again -- so a function whose code changed can be read as unchanged and dropped from the patch.

The alias skip is verified the usual way: remove it and the test fails. The other two are not isolated, and the test says so rather than implying otherwise. A zero-length symbol is excluded by several of the guards at once -- its section has no data either -- so removing any one of them changes nothing observable; the assertion stands as a check on the behaviour, not on the line that produces it. The cold-part skip needs a compiler that splits functions and is not reached here at all.

Which of an aliased pair keeps the entry falls out of symbol table order, so the test requires exactly one of the two rather than naming a winner -- as written first it named real_function and failed, because gcc kept the alias.

Assisted-by Claude:claude-opus-4
Assisted-by Claude:claude-opus-5
---
 .../tests/generic/fixtures/checksum_skip.c    | 47 +++++++++++
 .../tests/generic/test-checksum-skip.sh       | 81 +++++++++++++++++++
 2 files changed, 128 insertions(+)
 create mode 100644 tools/objtool/tests/generic/fixtures/checksum_skip.c
 create mode 100755 tools/objtool/tests/generic/test-checksum-skip.sh
tools/objtool/tests/generic/fixtures/checksum_skip.c new file +47 -0
new file mode 100644
index 000000000000..973bdc10295d
@@ -0,0 +1,47 @@
+// SPDX-License-Identifier: GPL-2.0
+/*
+ * Symbols calculate_checksums() must not give an entry of their own.
+ *
+ * Three kinds are skipped, for two different reasons:
+ *
+ *   zero-length   there is nothing to hash, and an entry keyed on the
+ *                 symbol's address would collide with whatever really lives
+ *                 there.
+ *   alias         a second name for an address already checksummed.
+ *   cold part     hashed as part of its parent, which func_for_each_insn()
+ *                 walks into, so a separate entry would double-count it.
+ *
+ * An entry per address is the invariant: .discard.sym_checksum is looked up by
+ * the address a relocation points at, so two entries for one address make the
+ * lookup ambiguous and one of the two checksums unreachable.
+ */
+
+static const char __modinfo[]
+	__attribute__((section(".modinfo"), used, aligned(1))) = "\0name=vmlinux";
+
+/* Zero-length: an object symbol of size 0, in a section of its own. */
+extern char empty_marker[];
+__asm__(".pushsection .data.empty_marker,\"aw\",@progbits\n"
+	".globl empty_marker\n"
+	".type empty_marker, @object\n"
+	"empty_marker:\n"
+	".size empty_marker, 0\n"
+	".popsection\n");
+
+int real_function(int x);
+int real_function(int x)
+{
+#ifdef PATCHED
+	return x + 2;
+#else
+	return x + 1;
+#endif
+}
+
+/* Alias: a second name for real_function's address. */
+int alias_function(int x) __attribute__((alias("real_function")));
+
+int target(int x)
+{
+	return real_function(x) + alias_function(x) + (int)(long)empty_marker;
+}
tools/objtool/tests/generic/test-checksum-skip.sh new file +81 -0

81 lines not on this page · raw message

Signature · 1 line
2.53.0-Meta
author maintainer
#147 lore raw

PATCH v5 48/58 objtool/klp: Add test for a static branch introduced by the patch

In reply to Song Liu

Patching a function which already has a static branch and adding one to a function which had none are different cases. In the second the __jump_table entry is itself new, so there is nothing in the original to correlate it against: klp diff has to carry the entry into the patch from scratch and reach the key the way it reaches any other vmlinux symbol.

Dropping it is silent. The patched function keeps a static branch the kernel never patches, so it takes the same arm forever whatever the key is set to.

Give the fixture a NEW_KEY knob which puts the whole branch behind PATCHED, and assert the premise -- that the original really has no __jump_table -- before asserting the result, since otherwise this is just a second copy of test-jump-label-key.

Verified by making klp diff skip __jump_table when cloning special
sections: the test fails.

Assisted-by Claude:claude-opus-4
Assisted-by Claude:claude-opus-5
---
 .../tests/generic/test-jump-label-new-key.sh  | 51 +++++++++++++++++++
 1 file changed, 51 insertions(+)
 create mode 100755 tools/objtool/tests/generic/test-jump-label-new-key.sh
tools/objtool/tests/generic/test-jump-label-new-key.sh new file +51 -0
new file mode 100755
index 000000000000..3bc6005fc776
@@ -0,0 +1,51 @@
+#!/bin/bash
+# SPDX-License-Identifier: GPL-2.0
+#
+# A patch may introduce a static branch where the original function had none.
+#
+# That is not the same case as patching a function which already has one.  The
+# __jump_table entry is itself new, so there is no counterpart in the original
+# to correlate it against: klp diff has to carry the entry and the key into the
+# patch from scratch, and the key has to be reached the way any other reference
+# to a vmlinux symbol is.
+#
+# Get it wrong and the entry is dropped, leaving a static branch the kernel
+# never patches -- the code takes the wrong arm forever, silently.
+#
+# Where the key lives still decides whether that is allowed, exactly as it does
+# for a key the original already had: a module-owned one cannot be reached, so
+# introducing one has to stop the build rather than emit an entry nothing will
+# resolve.
+#
+# Covers the same ground as corpus/x86_64/static-branch-vmlinux-new and
+# static-branch-module-new in Joe Lawrence's klp-build unit test corpus.
+
+. "$(dirname "$0")/../lib.sh"
+
+setup klp_test_key
+build_pair jump_label.c -DNEW_KEY
+
+# The premise: the original really has no jump table, and the patched one does.
+has_input_section orig.o __jump_table &&
+	fail "fixture put a __jump_table in the original; nothing new to add"
+has_input_section patched.o __jump_table ||
+	probe_skip "compiler produced no __jump_table on this arch"
+
+run_diff
+
+assert_patched target
+assert_section __jump_table
+assert_reloc_sym __jump_table target
+
+# The same new branch, with the key owned by a module.  Drop the vmlinux export
+# first: while it is exported the key is reachable and being new changes
+# nothing, which is what the first version of this got wrong.
+export_syms
+rm -f "$workdir/out.o"
+build_pair jump_label.c -DNEW_KEY -DMODNAME='"klp_testmod"'
+run_diff 255
+assert_diff_log 'unsupported static branch key klp_test_key'
+[ -e "$workdir/out.o" ] &&
+	fail "output object produced for a rejected input"
+
+pass "static branch introduced by the patch carried in, or rejected for a module key"
Signature · 1 line
2.53.0-Meta
author maintainer
#150 lore raw

PATCH v5 49/58 objtool/klp: Add test for tracepoint and pr_debug static branch keys

In reply to Song Liu

A module-owned static branch key is normally fatal, because late module patching lets the livepatch load before the module it depends on and jump_label_add_module() then dereferences an unresolved entry.

Tracepoints and pr_debug() generate such keys everywhere, so refusing them outright would make any function containing a trace_*() call or a pr_debug() unpatchable. klp diff drops the entry, warns, and carries on:
the patched code works with that one tracepoint or debug print permanently off.

Both halves matter, and the test asserts both. A build which fails is a function nobody can patch; an entry left in place is the corruption the rejection exists to prevent.

Give the fixture a KEY_NAME knob so the same static branch can be built with either special name. Verified by removing each exemption in turn -- the test fails for both. That the entry is then dropped is asserted but not isolated, and the test says so.

Assisted-by Claude:claude-opus-4
Assisted-by Claude:claude-opus-5
---
 .../generic/test-jump-label-exempt-keys.sh    | 51 +++++++++++++++++++
 1 file changed, 51 insertions(+)
 create mode 100755 tools/objtool/tests/generic/test-jump-label-exempt-keys.sh
tools/objtool/tests/generic/test-jump-label-exempt-keys.sh new file +51 -0
new file mode 100755
index 000000000000..fa2f913d860b
@@ -0,0 +1,51 @@
+#!/bin/bash
+# SPDX-License-Identifier: GPL-2.0
+#
+# Two kinds of module-owned static branch key are disabled with a warning
+# instead of rejected.
+#
+# A module-local key is normally fatal: late module patching lets the livepatch
+# load before the module it depends on, so the unresolved __jump_table entry is
+# dereferenced by jump_label_add_module().  test-jump-label-module-key covers
+# that rejection.
+#
+# Tracepoints and pr_debug() generate such keys everywhere, though, and
+# refusing them outright would make any function containing a trace_*() call or
+# a pr_debug() unpatchable.  So klp diff drops the entry, says so, and carries
+# on: the patched code keeps working with that one tracepoint or debug print
+# permanently off.
+#
+# Both halves matter.  A build that fails is a function nobody can patch; an
+# entry left in place is the memory corruption the rejection exists to prevent.
+#
+# The two exemptions are isolated: remove either and this fails.  That the
+# entry is then dropped is asserted but not isolated -- making the caller keep
+# it anyway produces no output difference here, so that assertion stands as a
+# check on the behaviour rather than on the line which produces it.
+#
+# Covers the same ground as corpus/x86_64/static-call-module-tracepoint and
+# pr-debug-unsupported in Joe Lawrence's klp-build unit test corpus.
+
+. "$(dirname "$0")/../lib.sh"
+
+setup
+
+# check <key name> <expected warning>
+check()
+{
+	build_pair jump_label.c -DKEY_NAME="$1" -DMODNAME='"klp_testmod"'
+	require_input_section __jump_table
+
+	# Accepted, not rejected: this is the whole point.
+	run_diff
+	assert_diff_log "$2"
+
+	# And the entry is gone, not merely complained about.
+	assert_patched target
+	assert_no_section __jump_table
+}
+
+check __tracepoint_klp_test        'disabling unsupported tracepoint klp_test'
+check __UNIQUE_ID_ddebug_klp_test  'disabling unsupported pr_debug'
+
+pass "tracepoint and pr_debug keys disabled with a warning, not rejected"
Signature · 1 line
2.53.0-Meta
author maintainer
#153 lore raw

PATCH v5 50/58 objtool/klp: Add test for a static call introduced by the patch

In reply to Song Liu

The counterpart to the static branch case: a patch may add a static call to a function which had none, so the .static_call_sites entry is new and there is nothing in the original to correlate it against.

Where the key lives still decides whether that is allowed. A vmlinux key is reachable; a module-owned one is not, for the same reason an existing module key is not -- late module patching lets the livepatch load first and the unresolved entry is dereferenced when the module arrives. Both halves are here because they fail in opposite directions: dropping the new entry leaves a static call the kernel never patches, and accepting a new module-owned one is the corruption the check exists to prevent.

Both halves are one test over one fixture: built with -DNEW_CALL the key is vmlinux's and the new entry has to be carried in; built with -DMODNAME as well the key belongs to a module, klp diff has to reject it, and no output object may be left behind. The premise is asserted first -- the original must have no .static_call_sites at all -- since otherwise this is a second copy of test-static-call-module-key.

Covers the same ground as corpus/x86_64/static-call-vmlinux-new and corpus/x86_64/static-call-module-new in Joe Lawrence's klp-build unit test corpus.

Assisted-by Claude:claude-opus-4
Assisted-by Claude:claude-opus-5
---
 .../tests/generic/test-static-call-new.sh     | 45 +++++++++++++++++++
 1 file changed, 45 insertions(+)
 create mode 100755 tools/objtool/tests/generic/test-static-call-new.sh
tools/objtool/tests/generic/test-static-call-new.sh new file +45 -0
new file mode 100755
index 000000000000..f7d2b39c0fec
@@ -0,0 +1,45 @@
+#!/bin/bash
+# SPDX-License-Identifier: GPL-2.0
+#
+# A patch may introduce a static call where the original function had none.
+#
+# The .static_call_sites entry is then new, with nothing in the original to
+# correlate it against, so klp diff has to carry it into the patch from
+# scratch.  Where the key lives still decides whether that is allowed: a
+# vmlinux key is reachable, and a module-owned one is not, for the same reason
+# an existing module key is not -- late module patching lets the livepatch load
+# first, and the unresolved entry is dereferenced when the module arrives.
+#
+# Both halves are here because they fail in opposite directions.  Dropping the
+# new entry leaves a static call the kernel never patches; accepting a new
+# module-owned one is the corruption the check exists to prevent.
+#
+# Covers the same ground as corpus/x86_64/static-call-vmlinux-new and
+# static-call-module-new in Joe Lawrence's klp-build unit test corpus.
+
+. "$(dirname "$0")/../lib.sh"
+
+setup
+build_pair static_call.c -DNEW_CALL
+
+# The premise: the original really has no static call, the patched one does.
+has_input_section orig.o .static_call_sites &&
+	fail "fixture put a .static_call_sites in the original; nothing new to add"
+has_input_section patched.o .static_call_sites ||
+	probe_skip "compiler produced no .static_call_sites on this arch"
+
+run_diff
+assert_patched target
+assert_section .static_call_sites
+assert_reloc_sym .static_call_sites target
+
+# The same new call, with the key owned by a module: not reachable, so the
+# build has to stop rather than emit a relocation nothing will resolve.
+rm -f "$workdir/out.o"
+build_pair static_call.c -DNEW_CALL -DMODNAME='"klp_testmod"'
+run_diff 255
+assert_diff_log 'unsupported static call key __SCK__klp_test_call'
+[ -e "$workdir/out.o" ] &&
+	fail "output object produced for a rejected input"
+
+pass "static call introduced by the patch carried in, or rejected for a module key"
Signature · 1 line
2.53.0-Meta
author maintainer
#156 lore raw

PATCH v5 51/58 objtool/klp: Add test for instruction operand checksums

In reply to Song Liu

checksum_update_insn() hashes an instruction's bytes and then what any relocation on it refers to: a string section contributes the string's contents, anything else the target symbol's name and adjusted addend, with a reference to a static resolved through its section symbol first.

None of that shows up in the bytes. A rel32 operand is zero in the object and supplied by the relocation, so calling a different function, editing a literal the code passes, or reading a different index of an array all leave the encoded instruction byte-identical. A checksum stopping at the bytes reports the function unchanged and the patch silently does not contain the fix.

test-checksum-position is the other half: what must *not* change the checksum when a function merely moves.

Each of the four is verified by sabotaging the line it covers. The static case needed a writer the compiler cannot see through -- without one it proves the array is never written, folds every read to zero, and emits no relocation at all, so the reference under test does not exist and the variant passes having compared two identical objects.

Assisted-by Claude:claude-opus-4
Assisted-by Claude:claude-opus-5
---
 .../tests/generic/fixtures/checksum_insn.c    | 78 +++++++++++++++++++
 .../tests/generic/test-checksum-insn.sh       | 49 ++++++++++++
 2 files changed, 127 insertions(+)
 create mode 100644 tools/objtool/tests/generic/fixtures/checksum_insn.c
 create mode 100755 tools/objtool/tests/generic/test-checksum-insn.sh
tools/objtool/tests/generic/fixtures/checksum_insn.c new file +78 -0
new file mode 100644
index 000000000000..10f70a74a976
@@ -0,0 +1,78 @@
+// SPDX-License-Identifier: GPL-2.0
+/*
+ * Instruction operands whose change must move a function's checksum even
+ * though the instruction bytes themselves do not.
+ *
+ * checksum_update_insn() hashes the raw bytes and then, when the instruction
+ * carries a relocation, what that relocation refers to: a string section
+ * contributes the string's contents, anything else the target symbol's name
+ * and the adjusted addend.  A reference to a static arrives as a section
+ * symbol and has to be resolved back to the object first.
+ *
+ * The bytes are identical in every case below -- a rel32 operand is zero in
+ * the object and supplied by the relocation -- so a checksum that stopped at
+ * the bytes would call all of these unchanged.
+ *
+ * Each variant applies to the patched build only:
+ *
+ *   WHICH_CALL    calls a different function
+ *   STR_CONTENT   passes a literal whose text was edited
+ *   WHICH_SLOT    reads a different index of a global array: addend only
+ *   WHICH_PRIV    the same, for a static, reached through its section symbol
+ */
+
+static const char __modinfo[]
+	__attribute__((section(".modinfo"), used, aligned(1))) = "\0name=vmlinux";
+
+int callee_a(int x);
+int callee_b(int x);
+int sink(const char *s);
+
+int slots[4];
+
+/*
+ * A file-local array, plus a writer the compiler cannot see through.  Without
+ * one it can prove the array is never written, folds every read to zero, and
+ * emits no relocation at all -- so the reference this is here to exercise does
+ * not exist.
+ */
+static int priv_slots[4];
+
+void set_priv(int i, int v);
+void set_priv(int i, int v)
+{
+	priv_slots[i] = v;
+}
+
+#if defined(PATCHED) && defined(STR_CONTENT)
+#define MESSAGE "edited"
+#else
+#define MESSAGE "original"
+#endif
+
+int target(int x)
+{
+	int r;
+
+#if defined(PATCHED) && defined(WHICH_CALL)
+	r = callee_b(x);
+#else
+	r = callee_a(x);
+#endif
+
+	r += sink(MESSAGE);
+
+#if defined(PATCHED) && defined(WHICH_SLOT)
+	r += slots[2];
+#else
+	r += slots[1];
+#endif
+
+#if defined(PATCHED) && defined(WHICH_PRIV)
+	r += priv_slots[3];
+#else
+	r += priv_slots[1];
+#endif
+
+	return r;
+}
tools/objtool/tests/generic/test-checksum-insn.sh new file +49 -0

49 lines not on this page · raw message

Signature · 1 line
2.53.0-Meta
author maintainer
#159 lore raw

PATCH v5 52/58 objtool/klp: Add test for alternative replacement code in checksums

In reply to Song Liu

checksum_update_insn() walks insn->alts after hashing the instruction
itself: the alternative's type, and where the replacement forms a group, its feature number and every instruction in it. A patch which edits only the replacement -- code that runs on some CPUs and not others -- still has to move the function's checksum.

When it does not, klp diff calls the function unchanged and leaves it out. The patch ships the old replacement, and the bug is fixed only on machines whose CPU takes the other arm. Which machines those are depends on the feature bit, so it presents as a machine-specific bug rather than a missing patch.

insn->alts is built by objtool's check pass, not by the compiler, so the pair goes through that first. --mcount is the action used: it is the cheapest one that does not also need --link.

Two of the three paths are isolated. Skipping the alts walk and dropping the feature hash both make this fail, and the second of those only exists inside the alt_group branch, so reaching it proves the grouped path is taken. The alternative's type is hashed but not varied here -- the fixture emits one kind of alternative -- so that line is covered without being isolated, as is the in_alt recursion guard, which wants nested alternatives.

Assisted-by Claude:claude-opus-4
Assisted-by Claude:claude-opus-5
---
 .../objtool/tests/x86/fixtures/checksum_alt.c | 66 +++++++++++++++++++
 tools/objtool/tests/x86/test-checksum-alt.sh  | 45 +++++++++++++
 2 files changed, 111 insertions(+)
 create mode 100644 tools/objtool/tests/x86/fixtures/checksum_alt.c
 create mode 100755 tools/objtool/tests/x86/test-checksum-alt.sh
tools/objtool/tests/x86/fixtures/checksum_alt.c new file +66 -0
new file mode 100644
index 000000000000..ed342d94eb9e
@@ -0,0 +1,66 @@
+// SPDX-License-Identifier: GPL-2.0
+/*
+ * An x86 alternative whose replacement code is part of the patched function's
+ * checksum.
+ *
+ * checksum_update_insn() walks insn->alts after hashing the instruction
+ * itself, hashing the alternative's type and, when the replacement forms a
+ * group, its feature number and every instruction in it.  So editing only the
+ * replacement -- code the CPU may or may not ever run -- has to move the
+ * function's checksum.
+ *
+ * It is reached through objtool's own alternative handling, so the object has
+ * to go through the check pass first: insn->alts is built there, not by the
+ * compiler.
+ *
+ * struct alt_instr is written out by hand as in empty_alternative.c: s32
+ * instr_offset, s32 repl_offset, u32 ft_flags, u8 instrlen, u8 replacementlen.
+ *
+ * Variants, applied to the patched build only:
+ *
+ *   ALT_REPL     the replacement instruction changes; the original does not
+ *   ALT_FEATURE  the feature number changes; no code changes at all
+ */
+
+static const char __modinfo[]
+	__attribute__((section(".modinfo"), used, aligned(1))) = "\0name=vmlinux";
+
+/*
+ * Both spellings are two bytes, because a replacement may not be longer than
+ * the instruction it replaces: "xchg %ax, %ax" is 66 90 and two nops are
+ * 90 90.  The original below is padded to match.
+ */
+#if defined(PATCHED) && defined(ALT_REPL)
+#define REPL_INSN "	nop\n\t	nop\n\t"
+#else
+#define REPL_INSN "	xchg %ax, %ax\n\t"
+#endif
+
+#if defined(PATCHED) && defined(ALT_FEATURE)
+#define FEATURE "7"
+#else
+#define FEATURE "3"
+#endif
+
+int target(int x)
+{
+	asm volatile(
+		"661:	nop\n\t"
+		"	nop\n\t"
+		"662:\n\t"
+		".pushsection .altinstr_replacement, \"ax\"\n\t"
+		".globl target_repl\n\t"
+		"target_repl:\n\t"
+		REPL_INSN
+		"target_repl_end:\n\t"
+		".popsection\n\t"
+		".pushsection .altinstructions, \"aM\", @progbits, 14\n\t"
+		".long 661b - .\n\t"
+		".long target_repl - .\n\t"
+		".long " FEATURE "\n\t"
+		".byte 662b - 661b\n\t"
+		".byte target_repl_end - target_repl\n\t"
+		".popsection\n\t");
+
+	return x + 1;
+}
tools/objtool/tests/x86/test-checksum-alt.sh new file +45 -0

45 lines not on this page · raw message

Signature · 1 line
2.53.0-Meta
author maintainer
#162 lore raw

PATCH v5 53/58 objtool/klp: Add test for the alignment of cloned data sections

In reply to Song Liu

A cloned data section has to keep its sh_addralign. Plenty of kernel data is aligned for correctness rather than speed -- per-CPU variables, anything touched by an aligned vector move, structures padded to own a cacheline -- and a clone that lands under-aligned either faults on first use or silently shares a line it was laid out to avoid. Neither shows up until the patch is loaded on hardware that cares.

The fixture's data is new in the patched build, so klp diff has to clone it rather than reference the kernel's copy, and it asserts that premise before asserting the result.

Commit 2f2600decb30 ("objtool/klp: fix data alignment in __clone_symbol()") cannot be reverted to check this -- the revert is a no-op against the current code, which has been rewritten since. Verified instead by forcing the clone's alignment to 1, which the test reports as "alignment 1, expected 64".

Assisted-by Claude:claude-opus-4
Assisted-by Claude:claude-opus-5
---
 .../tests/generic/fixtures/data_alignment.c   | 29 ++++++++++++++
 .../tests/generic/test-data-alignment.sh      | 40 +++++++++++++++++++
 2 files changed, 69 insertions(+)
 create mode 100644 tools/objtool/tests/generic/fixtures/data_alignment.c
 create mode 100755 tools/objtool/tests/generic/test-data-alignment.sh
tools/objtool/tests/generic/fixtures/data_alignment.c new file +29 -0
new file mode 100644
index 000000000000..900253dfb2cb
@@ -0,0 +1,29 @@
+// SPDX-License-Identifier: GPL-2.0
+/*
+ * Data with an alignment stricter than its size.
+ *
+ * A cloned data section has to keep its sh_addralign.  The kernel has plenty
+ * of data whose alignment is a correctness property rather than an
+ * optimisation -- per-CPU variables, anything touched by an aligned SSE move,
+ * cacheline-aligned locks -- and a clone that lands under-aligned faults or
+ * silently shares a cacheline it was written to avoid.
+ *
+ * The object is new in the patched build, so klp diff has to clone it rather
+ * than reference the kernel's copy.
+ */
+
+static const char __modinfo[]
+	__attribute__((section(".modinfo"), used, aligned(1))) = "\0name=vmlinux";
+
+#ifdef PATCHED
+int aligned_data[2] __attribute__((aligned(64))) = { 1, 2 };
+#endif
+
+int target(int x)
+{
+#ifdef PATCHED
+	return x + aligned_data[0];
+#else
+	return x;
+#endif
+}
tools/objtool/tests/generic/test-data-alignment.sh new file +40 -0
new file mode 100755
index 000000000000..8e389544a3b1
@@ -0,0 +1,40 @@
+#!/bin/bash
+# SPDX-License-Identifier: GPL-2.0
+#
+# A cloned data section keeps its alignment.
+#
+# Plenty of kernel data is aligned for correctness rather than speed: per-CPU
+# variables, anything touched by an aligned vector move, structures padded to
+# own a cacheline. A clone that lands under-aligned either faults on first use
+# or silently shares a line it was laid out to avoid, and neither shows up
+# until the patch is loaded on hardware that cares.
+#
+# Fixed by 2f2600decb30 ("objtool/klp: Fix alignment of cloned data
+# sections").
+#
+# Covers the same ground as corpus/x86_64/cloned-data-alignment in Joe
+# Lawrence's klp-build unit test corpus.
+
+. "$(dirname "$0")/../lib.sh"
+
+setup
+build_pair data_alignment.c
+
+# The premise: the compiler really did over-align it, and the object is new in
+# the patch so it has to be cloned rather than referenced.
+want="$(in_sections patched.o | sed 's/^ *\[[ 0-9]*\] *//' |
+	awk '$1 == ".data.aligned_data" { print $NF }')"
+[ "$want" = 64 ] ||
+	probe_skip "compiler gave .data.aligned_data alignment '$want', not 64"
+has_input_section orig.o .data.aligned_data &&
+	fail "fixture put aligned_data in the original; nothing to clone"
+
+run_diff
+assert_section .data.aligned_data
+
+got="$(out_sections | sed 's/^ *\[[ 0-9]*\] *//' |
+       awk '$1 == ".data.aligned_data" { print $NF }')"
+[ "$got" = "$want" ] ||
+	fail "cloned .data.aligned_data has alignment $got, expected $want"
+
+pass "cloned data section keeps its alignment"
Signature · 1 line
2.53.0-Meta
author maintainer
#165 lore raw

PATCH v5 54/58 objtool/klp: Add test for a patch which strips a data annotation

In reply to Song Liu

klp diff needs entry boundaries for a special section: either an entsize, or ANNOTATE_DATA_SPECIAL annotations naming where each entry starts. .static_call_sites has no entsize, so the annotations are all there is -- and a patch can remove the last one in a translation unit while leaving the section itself in place, so that only the patched side has lost them.

The section still has to be handled. Dropping it leaves the patched function's static call unregistered; misreading its boundaries attaches the entry to the wrong code. Neither is reported at build time.

Give the fixture a NO_ANNOTATE knob and assert the premise -- annotation present in the original, absent in the patched object, section present in both -- before asserting the result.

Fixed by commit 3de711fba73a ("objtool/klp: Fix create_fake_symbols() skipping entsize-based sections"). Verified by making klp diff skip .static_call_sites when cloning special sections: the test fails.

Assisted-by Claude:claude-opus-4
Assisted-by Claude:claude-opus-5
---
 .../test-static-call-annotate-stripped.sh     | 42 +++++++++++++++++++
 1 file changed, 42 insertions(+)
 create mode 100755 tools/objtool/tests/generic/test-static-call-annotate-stripped.sh
tools/objtool/tests/generic/test-static-call-annotate-stripped.sh new file +42 -0
new file mode 100755
index 000000000000..818b047ed4b6
@@ -0,0 +1,42 @@
+#!/bin/bash
+# SPDX-License-Identifier: GPL-2.0
+#
+# A patch may remove the last ANNOTATE_DATA_SPECIAL in a translation unit while
+# leaving the special section it described in place.
+#
+# klp diff needs entry boundaries for a special section: either an entsize, or
+# annotations naming where each entry starts.  .static_call_sites has no
+# entsize, so the annotations are all there is -- and when the patched object
+# is the only side that lost them, the two sides no longer agree on how the
+# section divides up.
+#
+# The section must still be handled.  Dropping it would leave the patched
+# function's static call unregistered; misreading its boundaries would attach
+# the entry to the wrong code.  Either way nothing is reported at build time.
+#
+# Fixed by commit 3de711fba73a ("objtool/klp: Fix create_fake_symbols()
+# skipping entsize-based sections").
+#
+# Covers the same ground as corpus/x86_64/static-call-annotate-stripped in Joe
+# Lawrence's klp-build unit test corpus.
+
+. "$(dirname "$0")/../lib.sh"
+
+setup
+build_pair static_call.c -DNO_ANNOTATE
+
+# The premise: the original describes its entry, the patched one no longer
+# does, and both still have the section itself.
+has_input_section orig.o .discard.annotate_data ||
+	fail "fixture produced no annotation in the original"
+has_input_section patched.o .discard.annotate_data &&
+	fail "patched object still has the annotation; nothing was stripped"
+assert_input_section .static_call_sites
+
+run_diff
+
+assert_patched target
+assert_section .static_call_sites
+assert_reloc_sym .static_call_sites target
+
+pass "static call site kept when the patch strips its data annotation"
Signature · 1 line
2.53.0-Meta
author maintainer
#168 lore raw

PATCH v5 55/58 objtool/klp: Add test for absolute and __ADDRESSABLE symbols

In reply to Song Liu

A SHN_ABS symbol has no section, so any walk of sym->sec which does not check dereferences NULL, and the kernel has plenty of them -- from linker scripts and from .set in assembly. __ADDRESSABLE() emits a pointer into .discard.addressable purely to keep a symbol referenced; it means nothing to a livepatch and is discarded at link time, but it is a relocation like any other and gets looked at.

Neither is what the patch changes. What this guards against is not a wrong answer but a crash or an error on input the kernel produces routinely, which would make every function near one unpatchable.

Not isolated to a single line, and the test says so: the absolute symbol here has zero length, so it is excluded before the section check is reached and removing that check alone changes nothing observable.

Assisted-by Claude:claude-opus-4
Assisted-by Claude:claude-opus-5
---
 .../generic/fixtures/abs_and_addressable.c    | 44 ++++++++++++++++
 .../tests/generic/test-abs-and-addressable.sh | 50 +++++++++++++++++++
 2 files changed, 94 insertions(+)
 create mode 100644 tools/objtool/tests/generic/fixtures/abs_and_addressable.c
 create mode 100755 tools/objtool/tests/generic/test-abs-and-addressable.sh
tools/objtool/tests/generic/fixtures/abs_and_addressable.c new file +44 -0
new file mode 100644
index 000000000000..6392ff99af42
@@ -0,0 +1,44 @@
+// SPDX-License-Identifier: GPL-2.0
+/*
+ * Two constructs which appear all over the kernel and must not upset klp
+ * checksum or klp diff.
+ *
+ * An absolute symbol (SHN_ABS) has no section, so anything walking sym->sec
+ * without checking dereferences NULL.  The kernel makes them with linker
+ * scripts and with .set in asm; VDSO and the fixed-address per-cpu bases are
+ * the usual sources.
+ *
+ * __ADDRESSABLE() emits a pointer into .discard.addressable purely to keep a
+ * symbol referenced.  It is discarded at link time and means nothing to a
+ * livepatch, but the pointer is a relocation like any other and has to survive
+ * being looked at.
+ *
+ * Neither is the subject of the patch; the point is that their presence does
+ * not disturb the function that is.
+ */
+
+static const char __modinfo[]
+	__attribute__((section(".modinfo"), used, aligned(1))) = "\0name=vmlinux";
+
+/* SHN_ABS, referenced from code. */
+extern char abs_sym[];
+__asm__(".globl abs_sym\n"
+	".set abs_sym, 0x1234\n");
+
+int helper(int x);
+int helper(int x) { return x + 1; }
+
+/* The shape of __ADDRESSABLE(helper). */
+__asm__(".pushsection .discard.addressable, \"aw\"\n"
+	".balign 8\n"
+	".quad helper\n"
+	".popsection\n");
+
+int target(int x)
+{
+#ifdef PATCHED
+	return helper(x) + (int)(long)abs_sym + 1;
+#else
+	return helper(x) + (int)(long)abs_sym;
+#endif
+}
tools/objtool/tests/generic/test-abs-and-addressable.sh new file +50 -0

50 lines not on this page · raw message

Signature · 1 line
2.53.0-Meta
author maintainer
#171 lore raw

PATCH v5 56/58 objtool/klp: Add test for UBSAN metadata in an unchanged function

In reply to Song Liu

Every instrumented operation gets a per-callsite metadata object in an anonymous data section -- .data..Lubsan_data and .data..Lubsan_type from GCC, .data..L__unnamed_ from Clang -- whose names are compiler-generated and mean nothing across a rebuild. is_uncorrelated_section() exists so klp diff does not try to pair them up, and nothing tested it.

The failure it prevents is a false positive, which is the direction this suite has least coverage of. Metadata belonging to a function nobody touched compares as different and drags that function into the patch. That is not a build failure: it is a larger livepatch than intended, pulling in dependencies with it, and every extra function is one more that can fail to correlate or to apply.

The fixture is built with -fsanitize=shift, which both compilers instrument; neither emits a bounds check for an index it can prove in range. One function changes, the other is byte-identical and carries instrumentation of its own, and the test asserts the second is left alone.

Verified by removing each rule from is_uncorrelated_section() in turn, which splits neatly by toolchain: dropping the .data..Lubsan rule fails the test under gcc, dropping .data..L__unnamed_ fails it under clang. One test, two code paths, each checked by the compiler that reaches it.

Assisted-by Claude:claude-opus-4
Assisted-by Claude:claude-opus-5
---
 .../tests/generic/fixtures/ubsan_noise.c      | 49 +++++++++++++++++++
 .../objtool/tests/generic/test-ubsan-noise.sh | 48 ++++++++++++++++++
 2 files changed, 97 insertions(+)
 create mode 100644 tools/objtool/tests/generic/fixtures/ubsan_noise.c
 create mode 100755 tools/objtool/tests/generic/test-ubsan-noise.sh
tools/objtool/tests/generic/fixtures/ubsan_noise.c new file +49 -0
new file mode 100644
index 000000000000..bf5999254163
@@ -0,0 +1,49 @@
+// SPDX-License-Identifier: GPL-2.0
+/*
+ * A translation unit built with UBSAN, where only one of two functions is
+ * patched.
+ *
+ * Every instrumented operation gets a per-callsite metadata object in an
+ * anonymous data section -- .data..Lubsan_data and .data..Lubsan_type from
+ * GCC, .data..L__unnamed_ from Clang -- and a call to a __ubsan_handle_*
+ * routine.  The names are compiler-generated and carry no meaning across a
+ * rebuild, so klp diff has to treat those sections as uncorrelated rather than
+ * pairing them up by name.
+ *
+ * untouched() is byte-identical in both builds and exists to catch the false
+ * positive: if the metadata were correlated by name, its shifts would look
+ * changed and it would be dragged into the patch.
+ *
+ * The shifts are what draw the instrumentation.  A bounds check would do as
+ * well but neither compiler emits one for an index it can prove in range.
+ */
+
+static const char __modinfo[]
+	__attribute__((section(".modinfo"), used, aligned(1))) = "\0name=vmlinux";
+
+int shift_by(int v, int n);
+
+int untouched(int v, int n)
+{
+	int s = 0;
+
+	s += v << (n & 31);
+	s += v << ((n + 1) & 31);
+	s += shift_by(v, n);
+
+	return s;
+}
+
+int touched(int v, int n)
+{
+	int s = 0;
+
+	s += v << (n & 31);
+#ifdef PATCHED
+	s += v << ((n + 3) & 31);
+#else
+	s += v << ((n + 2) & 31);
+#endif
+
+	return s;
+}
tools/objtool/tests/generic/test-ubsan-noise.sh new file +48 -0

48 lines not on this page · raw message

Signature · 1 line
2.53.0-Meta
author maintainer
#174 lore raw

PATCH v5 57/58 objtool/klp: Add test for Clang switch jump tables

In reply to Song Liu

For a dense enough switch Clang emits the targets as a table in .rodata..Lswitch.table.<function> -- named after the function but not part of it. The patched function indexes into that table, so a clone which does not bring it along jumps through whatever the kernel's copy holds, which after a patch that changed the switch is the wrong set of targets. An indirect jump to a stale address reports nothing at build or load time.

The fixture asserts its own premise twice over, since both halves depend on what this Clang chose to do: that a table was built rather than a chain of comparisons, and that the added case actually changed it.

objtool has no switch-specific code -- the table is carried by the general mechanism for data a cloned function references -- so this guards that mechanism reaching an easily-mishandled shape rather than a particular line, and the test says so. Making the table uncorrelated, the nearest available sabotage, does not change the outcome.

Assisted-by Claude:claude-opus-4
Assisted-by Claude:claude-opus-5
---
 .../tests/generic/fixtures/switch_rodata.c    | 31 +++++++++++
 .../tests/generic/test-switch-rodata.sh       | 53 +++++++++++++++++++
 2 files changed, 84 insertions(+)
 create mode 100644 tools/objtool/tests/generic/fixtures/switch_rodata.c
 create mode 100755 tools/objtool/tests/generic/test-switch-rodata.sh
tools/objtool/tests/generic/fixtures/switch_rodata.c new file +31 -0
new file mode 100644
index 000000000000..817ddac92d81
@@ -0,0 +1,31 @@
+// SPDX-License-Identifier: GPL-2.0
+/*
+ * A switch dense enough that Clang builds a jump table for it, in a section of
+ * its own: .rodata..Lswitch.table.<function>.
+ *
+ * The table belongs to the function and has to travel with it.  It is named
+ * after the function but is not part of it, so klp diff has to associate the
+ * two rather than treating the table as unrelated data.
+ *
+ * The patch adds a case, which changes the table's contents and length.
+ */
+
+static const char __modinfo[]
+	__attribute__((section(".modinfo"), used, aligned(1))) = "\0name=vmlinux";
+const char *status_to_string(unsigned int c)
+{
+	switch (c) {
+	case 0: return "idle";
+	case 1: return "running";
+	case 2: return "stopped";
+	case 3: return "error";
+	case 4: return "paused";
+	case 5: return "waiting";
+	case 6: return "starting";
+	case 7: return "stopping";
+#ifdef PATCHED
+	case 8: return "completed";
+#endif
+	}
+	return "unknown";
+}
tools/objtool/tests/generic/test-switch-rodata.sh new file +53 -0

53 lines not on this page · raw message

Signature · 1 line
2.53.0-Meta
author maintainer
#177 lore raw

PATCH v5 58/58 objtool/klp: Add test for ThinLTO symbols sharing a demangled name

In reply to Song Liu

A file-local symbol which ThinLTO has to make visible is renamed helper.llvm.<hash>. With two such helpers in one link, the original and the patched object hold two each, all four spelled differently, and demangling gives "helper" for every one of them -- so the name alone cannot say which corresponds to which.

Three translation units, two with a static helper of the same name and a third calling into both, which is what forces the promotion. Only one helper changes: paired correctly that means exactly one is cloned, and paired the wrong way round the other is, or both are. Had both bodies changed, both would be cloned either way and the test would prove nothing -- which is how the first version of this was written.

The outcome is asserted, not the machinery. With the clang tested here the pairing survives disabling the .llvm.<hash> suffix map and stubbing out llvm_suffix() entirely, so no single-line sabotage distinguishes it; the tiered matcher this case was written for is not needed for this shape. The test says so rather than implying otherwise.

Assisted-by Claude:claude-opus-4
Assisted-by Claude:claude-opus-5
---
 .../generic/fixtures/thinlto_ambiguity.c      | 57 ++++++++++++++
 .../tests/generic/test-thinlto-ambiguity.sh   | 77 +++++++++++++++++++
 2 files changed, 134 insertions(+)
 create mode 100644 tools/objtool/tests/generic/fixtures/thinlto_ambiguity.c
 create mode 100755 tools/objtool/tests/generic/test-thinlto-ambiguity.sh
tools/objtool/tests/generic/fixtures/thinlto_ambiguity.c new file +57 -0
new file mode 100644
index 000000000000..b88830f41a92
@@ -0,0 +1,57 @@
+// SPDX-License-Identifier: GPL-2.0
+/*
+ * Three translation units linked with ThinLTO, two of which have a file-local
+ * helper of the same name.
+ *
+ * TU_C calls into both of the others, so ThinLTO imports entry_a and entry_b
+ * and with them the static helper each one calls.  A file-local symbol which
+ * has to become visible is renamed helper.llvm.<hash>, and the hash is content
+ * derived -- so the two helpers get different hashes from each other, and
+ * TU_A's gets a different one again after the patch changes it.  Only TU_A's
+ * changes: were both bodies to change, both would be cloned whichever way
+ * they were paired, and the pairing would not be observable.
+ *
+ * That leaves klp diff with two symbols in the original and two in the patched
+ * object, all four named differently, which have to be paired up correctly.
+ * Demangling alone gives "helper" for all of them; something else has to
+ * decide which is which.
+ *
+ * Only TU_A's helper changes.  That is what makes a wrong pairing observable:
+ * paired correctly, one helper is changed and the other is not, so exactly one
+ * is cloned.  Paired the wrong way round, both look changed -- or the wrong
+ * one does.  If both bodies changed the outcome would be the same either way
+ * and the test would prove nothing.
+ *
+ * BASE differs between the two so their bodies are not identical to begin
+ * with.
+ */
+
+#if defined(TU_C)
+extern int entry_a(int x);
+extern int entry_b(int x);
+int glue(int x) { return entry_a(x) + entry_b(x + 1); }
+#else
+#ifdef TU_B
+#define ENTRY entry_b
+#define BASE 5
+#else
+#define ENTRY entry_a
+#define BASE 10
+static const char __modinfo[]
+	__attribute__((section(".modinfo"), used, aligned(1))) = "\0name=vmlinux";
+#endif
+static __attribute__((noinline)) int helper(int x, int len)
+{
+	int sum = 0, i;
+
+	for (i = 0; i < len; i++)
+#if defined(PATCHED) && !defined(TU_B)
+		sum += i * 2 + BASE;	/* only TU_A's helper changes */
+#else
+		sum += i + BASE;
+#endif
+	return sum + x;
+}
+
+int ENTRY(int x) { return helper(x, 4); }
+#endif
tools/objtool/tests/generic/test-thinlto-ambiguity.sh new file +77 -0

77 lines not on this page · raw message

Signature · 1 line
2.53.0-Meta
#131 lore raw

Re: [PATCH v5 43/58] objtool/klp: Test rejection of a file-local static branch key

In reply to Song Liu
Thank you for your contribution! Sashiko AI review found 1 potential issue(s) to consider: - [Low] invalid AI attribution tags in commit message --

Thank you for your contribution! Sashiko AI review found 1 potential issue(s) to consider:
- [Low] invalid AI attribution tags in commit message
--

commit 31c30fc01ab7bac006cdecfa960b5321f80c4604
Author: Song Liu <[email protected]>

objtool/klp: Test rejection of a file-local static branch key

This commit adds a test to ensure that a static branch key owned by a module is properly rejected when accessed via a livepatch relocation. It adds a knob to cover file-local keys and verifies that the input references the key through its section symbol.

Quoted 3 lines
Assisted-by Claude:claude-opus-4
Assisted-by Claude:claude-opus-5

[Severity: Low]
This isn't a bug, but the commit message uses non-standard Assisted-by tags with pseudonyms and no valid email addresses. Should these attribution tags be removed or replaced with standard trailer formats before submission?

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

Re: [PATCH v5 36/58] objtool/klp: Add test for position-independent checksums

In reply to Song Liu
Thank you for your contribution! Sashiko AI review found 1 potential issue(s) to consider: - [Low] objtool/klp: test script comments mismatch C fixture implementation --

Thank you for your contribution! Sashiko AI review found 1 potential issue(s) to consider:
- [Low] objtool/klp: test script comments mismatch C fixture implementation --

commit 7722f94b411608f4277261adb44a750295859754

Author: Song Liu <[email protected]>
Date:   Wed Sep 16 18:43:29 2026 +0000

objtool/klp: Add test for position-independent checksums

A function that only moves has not changed, and its checksum must not move with it. Otherwise every patch reports as changed everything that shifted because something ahead of it grew.

Quoted 8 lines
tools/objtool/tests/generic/test-checksum-position.sh new file +2 -0
new file mode 100755
index 0000000000000..d05e28014e1e6
@@ -0,0 +1,50 @@
+#!/bin/bash
+# SPDX-License-Identifier: GPL-2.0

[ ... ]

tools/objtool/tests/generic/test-checksum-position.sh line 13

Quoted 8 lines
tools/objtool/tests/generic/test-checksum-position.sh new file +8 -0
+# A jump or call without a relocation encodes its target as an offset from the
+# instruction.  Hashing those bytes makes the checksum change whenever anything
+# ahead of the function changes size -- so an unrelated edit elsewhere in the
+# file reports this function as changed too, and the patch grows to include it
+# and everything it references.  Nothing fails; the livepatch is just larger and
+# riskier than the patch it came from.
+#
+# Here the "patch" adds a function ahead of target() and changes nothing else.

[Severity: Low]
Is this comment accurate given that the C fixture uses __attribute__((aligned(64))) instead of adding a new function?

It appears the C code in checksum_position.c explicitly states that PATCHED changes the distance by aligning the functions rather than by inserting a function between them.

Quoted 5 lines
tools/objtool/tests/generic/test-checksum-position.sh new file +5 -0
+
+. "$(dirname "$0")/../lib.sh"
+
+setup
+

tools/objtool/tests/generic/test-checksum-position.sh line 28

Quoted 10 lines
tools/objtool/tests/generic/test-checksum-position.sh new file +10 -0
+# -fno-function-sections, or each function is at offset 0 of its own section
+# and target() never moves.
+build_pair checksum_position.c -fno-function-sections
+
+assert_input_symbol target
+
+# The fixture is only meaningful if target() actually moved.
+# What has to change is the displacement target's calls encode, and that is
+# the distance to callee() -- not target's own offset.  A compiler which put
+# the added function ahead of both would move target and leave the distance

[Severity: Low]
Does this explanation still apply?

Like the comment above, this seems to continue explaining the mechanism based on an obsolete added function approach rather than the alignment approach documented in the C fixture.

Quoted 7 lines
tools/objtool/tests/generic/test-checksum-position.sh new file +7 -0
+# alone, and then the bytes are identical and the checksum matches for the
+# uninteresting reason.  Ask about the distance.
+sym_off()   # $1 object, $2 symbol
+{
+	in_symbols "$1" | awk -v n="$2" '$NF == n { print $2; exit }'
+}
+

tools/objtool/tests/generic/test-checksum-position.sh line 45

Quoted 10 lines
tools/objtool/tests/generic/test-checksum-position.sh new file +10 -0
+orig_t="$(sym_off orig.o target)";    orig_c="$(sym_off orig.o callee)"
+new_t="$(sym_off patched.o target)";  new_c="$(sym_off patched.o callee)"
+
+[ -n "$orig_t" ] && [ -n "$orig_c" ] && [ -n "$new_t" ] && [ -n "$new_c" ] ||
+	fail "target or callee missing from one of the objects"
+
+orig_gap=$(( 16#$orig_t - 16#$orig_c ))
+new_gap=$((  16#$new_t  - 16#$new_c ))
+[ "$orig_gap" != "$new_gap" ] ||
+	probe_skip "this compiler moved target() and callee() together;" \

[Severity: Low]
Should this skip message be updated as well?

It implies the functions were moved together by compiler reordering, as in the added function approach, rather than reacting to the alignment directive used in the C fixture.

Quoted 5 lines
tools/objtool/tests/generic/test-checksum-position.sh new file +5 -0
+		   "the call displacement did not change"
+
+assert_checksum_matches target
+
+pass "checksum unchanged when the function only moves"
Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=36
author maintainer
#132 lore raw

Re: [PATCH v5 43/58] objtool/klp: Test rejection of a file-local static branch key

In reply to [email protected]
Quoted 15 lines · On Wed, Sep 16, 2026 at 12:00 PM <[email protected]> wrote:

Thank you for your contribution! Sashiko AI review found 1 potential issue(s) to consider:
- [Low] invalid AI attribution tags in commit message
--

commit 31c30fc01ab7bac006cdecfa960b5321f80c4604
Author: Song Liu <[email protected]>

objtool/klp: Test rejection of a file-local static branch key

This commit adds a test to ensure that a static branch key owned by a module is properly rejected when accessed via a livepatch relocation. It adds a knob to cover file-local keys and verifies that the input references the key through its section symbol.

Quoted 8 lines
Quoted 3 lines
Assisted-by Claude:claude-opus-4
Assisted-by Claude:claude-opus-5

[Severity: Low]
This isn't a bug, but the commit message uses non-standard Assisted-by tags with pseudonyms and no valid email addresses. Should these attribution tags be removed or replaced with standard trailer formats before submission?

I think the Assisted-by tag here is OK.

Thanks,
Song

author maintainer
#108 lore raw

Re: [PATCH v5 36/58] objtool/klp: Add test for position-independent checksums

In reply to [email protected]
Quoted 87 lines · On Wed, Sep 16, 2026 at 12:01 PM <[email protected]> wrote:

Thank you for your contribution! Sashiko AI review found 1 potential issue(s) to consider:
- [Low] objtool/klp: test script comments mismatch C fixture implementation --

commit 7722f94b411608f4277261adb44a750295859754

Author: Song Liu <[email protected]>
Date:   Wed Sep 16 18:43:29 2026 +0000

objtool/klp: Add test for position-independent checksums

A function that only moves has not changed, and its checksum must not move with it. Otherwise every patch reports as changed everything that shifted because something ahead of it grew.

Quoted 8 lines
tools/objtool/tests/generic/test-checksum-position.sh new file +2 -0
new file mode 100755
index 0000000000000..d05e28014e1e6
@@ -0,0 +1,50 @@
+#!/bin/bash
+# SPDX-License-Identifier: GPL-2.0

[ ... ]

tools/objtool/tests/generic/test-checksum-position.sh

Quoted 8 lines
tools/objtool/tests/generic/test-checksum-position.sh new file +8 -0
+# A jump or call without a relocation encodes its target as an offset from the
+# instruction.  Hashing those bytes makes the checksum change whenever anything
+# ahead of the function changes size -- so an unrelated edit elsewhere in the
+# file reports this function as changed too, and the patch grows to include it
+# and everything it references.  Nothing fails; the livepatch is just larger and
+# riskier than the patch it came from.
+#
+# Here the "patch" adds a function ahead of target() and changes nothing else.

[Severity: Low]
Is this comment accurate given that the C fixture uses __attribute__((aligned(64))) instead of adding a new function?

It appears the C code in checksum_position.c explicitly states that PATCHED changes the distance by aligning the functions rather than by inserting a function between them.

Quoted 5 lines
tools/objtool/tests/generic/test-checksum-position.sh new file +5 -0
+
+. "$(dirname "$0")/../lib.sh"
+
+setup
+

tools/objtool/tests/generic/test-checksum-position.sh

Quoted 10 lines
tools/objtool/tests/generic/test-checksum-position.sh new file +10 -0
+# -fno-function-sections, or each function is at offset 0 of its own section
+# and target() never moves.
+build_pair checksum_position.c -fno-function-sections
+
+assert_input_symbol target
+
+# The fixture is only meaningful if target() actually moved.
+# What has to change is the displacement target's calls encode, and that is
+# the distance to callee() -- not target's own offset.  A compiler which put
+# the added function ahead of both would move target and leave the distance

[Severity: Low]
Does this explanation still apply?

Like the comment above, this seems to continue explaining the mechanism based on an obsolete added function approach rather than the alignment approach documented in the C fixture.

Quoted 7 lines
tools/objtool/tests/generic/test-checksum-position.sh new file +7 -0
+# alone, and then the bytes are identical and the checksum matches for the
+# uninteresting reason.  Ask about the distance.
+sym_off()   # $1 object, $2 symbol
+{
+     in_symbols "$1" | awk -v n="$2" '$NF == n { print $2; exit }'
+}
+

tools/objtool/tests/generic/test-checksum-position.sh

Quoted 10 lines
tools/objtool/tests/generic/test-checksum-position.sh new file +10 -0
+orig_t="$(sym_off orig.o target)";    orig_c="$(sym_off orig.o callee)"
+new_t="$(sym_off patched.o target)";  new_c="$(sym_off patched.o callee)"
+
+[ -n "$orig_t" ] && [ -n "$orig_c" ] && [ -n "$new_t" ] && [ -n "$new_c" ] ||
+     fail "target or callee missing from one of the objects"
+
+orig_gap=$(( 16#$orig_t - 16#$orig_c ))
+new_gap=$((  16#$new_t  - 16#$new_c ))
+[ "$orig_gap" != "$new_gap" ] ||
+     probe_skip "this compiler moved target() and callee() together;" \

[Severity: Low]
Should this skip message be updated as well?

Quoted 3 lines

It implies the functions were moved together by compiler reordering, as in the added function approach, rather than reacting to the alignment directive used in the C fixture.

Good catch here. We missed these comments/messages.

Josh,

Would you mind folding the following change in while applying the patches, so that I don't have to spam the list again?

Thanks,
Song

(quoted diff) +0 -0

w/tools/objtool/tests/generic/test-checksum-position.sh index d05e28014e1e..5ae759e719eb 100755

tools/objtool/tests/generic/test-checksum-position.sh +0 -0
@@ -10,7 +10,9 @@
 # and everything it references.  Nothing fails; the livepatch is just

larger and

 # riskier than the patch it came from.
 #
-# Here the "patch" adds a function ahead of target() and changes nothing else.
+# Here the "patch" moves target() away from callee() and changes nothing else:
+# both are aligned to 64 in the patched build, which shifts them apart without
+# touching a byte of either.  See the fixture for why it is done that way.

. "$(dirname "$0")/../lib.sh"

@@ -22,12 +24,11 @@ build_pair checksum_position.c -fno-function-sections

assert_input_symbol target

-# The fixture is only meaningful if target() actually moved.
-# What has to change is the displacement target's calls encode, and that is -# the distance to callee() -- not target's own offset. A compiler which put -# the added function ahead of both would move target and leave the distance -# alone, and then the bytes are identical and the checksum matches for the -# uninteresting reason. Ask about the distance.
+# The fixture is only meaningful if the displacement target's calls encode +# actually changed, and that is the distance to callee() -- not target's own +# offset. A compiler which shifted the two by the same amount would move +# target and leave the distance alone, and then the bytes are identical and +# the checksum matches for the uninteresting reason. Ask about the distance.
sym_off() # $1 object, $2 symbol

 {
        in_symbols "$1" | awk -v n="$2" '$NF == n { print $2; exit }'

@@ -42,8 +43,8 @@ new_t="$(sym_off patched.o target)"; new_c="$(sym_off patched.o callee)"
orig_gap=$(( 16#$orig_t - 16#$orig_c )) new_gap=$(( 16#$new_t - 16#$new_c ))
[ "$orig_gap" != "$new_gap" ] ||
- probe_skip "this compiler moved target() and callee() together;" \
- "the call displacement did not change"
+ probe_skip "this compiler kept target() and callee() the same
distance" \
+ "apart; the call displacement did not change"

assert_checksum_matches target

maintainer
#109 lore raw

Re: [PATCH v5 36/58] objtool/klp: Add test for position-independent checksums

Quoted 6 lines · Song Liu

Good catch here. We missed these comments/messages.

Josh,

Would you mind folding the following change in while applying the patches, so that I don't have to spam the list again?

Sure. It was whitespace damaged but I figured it out :-)

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

[tip: objtool/core] objtool/klp: Add test for Clang switch jump tables

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

objtool/klp: Add test for Clang switch jump tables

For a dense enough switch Clang emits the targets as a table in .rodata..Lswitch.table.<function> -- named after the function but not part of it. The patched function indexes into that table, so a clone which does not bring it along jumps through whatever the kernel's copy holds, which after a patch that changed the switch is the wrong set of targets. An indirect jump to a stale address reports nothing at build or load time.

The fixture asserts its own premise twice over, since both halves depend on what this Clang chose to do: that a table was built rather than a chain of comparisons, and that the added case actually changed it.

objtool has no switch-specific code -- the table is carried by the general mechanism for data a cloned function references -- so this guards that mechanism reaching an easily-mishandled shape rather than a particular line, and the test says so. Making the table uncorrelated, the nearest available sabotage, does not change the outcome.

Assisted-by Claude:claude-opus-4
Assisted-by Claude:claude-opus-5
---
 tools/objtool/tests/generic/fixtures/switch_rodata.c | 31 ++++++-
 tools/objtool/tests/generic/test-switch-rodata.sh    | 53 +++++++++++-
 2 files changed, 84 insertions(+)
 create mode 100644 tools/objtool/tests/generic/fixtures/switch_rodata.c
 create mode 100755 tools/objtool/tests/generic/test-switch-rodata.sh
tools/objtool/tests/generic/fixtures/switch_rodata.c new file +31 -0
new file mode 100644
index 0000000..817ddac
@@ -0,0 +1,31 @@
+// SPDX-License-Identifier: GPL-2.0
+/*
+ * A switch dense enough that Clang builds a jump table for it, in a section of
+ * its own: .rodata..Lswitch.table.<function>.
+ *
+ * The table belongs to the function and has to travel with it.  It is named
+ * after the function but is not part of it, so klp diff has to associate the
+ * two rather than treating the table as unrelated data.
+ *
+ * The patch adds a case, which changes the table's contents and length.
+ */
+
+static const char __modinfo[]
+	__attribute__((section(".modinfo"), used, aligned(1))) = "\0name=vmlinux";
+const char *status_to_string(unsigned int c)
+{
+	switch (c) {
+	case 0: return "idle";
+	case 1: return "running";
+	case 2: return "stopped";
+	case 3: return "error";
+	case 4: return "paused";
+	case 5: return "waiting";
+	case 6: return "starting";
+	case 7: return "stopping";
+#ifdef PATCHED
+	case 8: return "completed";
+#endif
+	}
+	return "unknown";
+}
tools/objtool/tests/generic/test-switch-rodata.sh new file +53 -0

53 lines not on this page · raw message

merge bot Applied
#178 lore raw

[tip: objtool/core] objtool/klp: Add test for ThinLTO symbols sharing a demangled name

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

objtool/klp: Add test for ThinLTO symbols sharing a demangled name

A file-local symbol which ThinLTO has to make visible is renamed helper.llvm.<hash>. With two such helpers in one link, the original and the patched object hold two each, all four spelled differently, and demangling gives "helper" for every one of them -- so the name alone cannot say which corresponds to which.

Three translation units, two with a static helper of the same name and a third calling into both, which is what forces the promotion. Only one helper changes: paired correctly that means exactly one is cloned, and paired the wrong way round the other is, or both are. Had both bodies changed, both would be cloned either way and the test would prove nothing -- which is how the first version of this was written.

The outcome is asserted, not the machinery. With the clang tested here the pairing survives disabling the .llvm.<hash> suffix map and stubbing out llvm_suffix() entirely, so no single-line sabotage distinguishes it; the tiered matcher this case was written for is not needed for this shape. The test says so rather than implying otherwise.

Assisted-by Claude:claude-opus-4
Assisted-by Claude:claude-opus-5
---
 tools/objtool/tests/generic/fixtures/thinlto_ambiguity.c | 57 +++++-
 tools/objtool/tests/generic/test-thinlto-ambiguity.sh    | 77 +++++++-
 2 files changed, 134 insertions(+)
 create mode 100644 tools/objtool/tests/generic/fixtures/thinlto_ambiguity.c
 create mode 100755 tools/objtool/tests/generic/test-thinlto-ambiguity.sh
tools/objtool/tests/generic/fixtures/thinlto_ambiguity.c new file +57 -0
new file mode 100644
index 0000000..b88830f
@@ -0,0 +1,57 @@
+// SPDX-License-Identifier: GPL-2.0
+/*
+ * Three translation units linked with ThinLTO, two of which have a file-local
+ * helper of the same name.
+ *
+ * TU_C calls into both of the others, so ThinLTO imports entry_a and entry_b
+ * and with them the static helper each one calls.  A file-local symbol which
+ * has to become visible is renamed helper.llvm.<hash>, and the hash is content
+ * derived -- so the two helpers get different hashes from each other, and
+ * TU_A's gets a different one again after the patch changes it.  Only TU_A's
+ * changes: were both bodies to change, both would be cloned whichever way
+ * they were paired, and the pairing would not be observable.
+ *
+ * That leaves klp diff with two symbols in the original and two in the patched
+ * object, all four named differently, which have to be paired up correctly.
+ * Demangling alone gives "helper" for all of them; something else has to
+ * decide which is which.
+ *
+ * Only TU_A's helper changes.  That is what makes a wrong pairing observable:
+ * paired correctly, one helper is changed and the other is not, so exactly one
+ * is cloned.  Paired the wrong way round, both look changed -- or the wrong
+ * one does.  If both bodies changed the outcome would be the same either way
+ * and the test would prove nothing.
+ *
+ * BASE differs between the two so their bodies are not identical to begin
+ * with.
+ */
+
+#if defined(TU_C)
+extern int entry_a(int x);
+extern int entry_b(int x);
+int glue(int x) { return entry_a(x) + entry_b(x + 1); }
+#else
+#ifdef TU_B
+#define ENTRY entry_b
+#define BASE 5
+#else
+#define ENTRY entry_a
+#define BASE 10
+static const char __modinfo[]
+	__attribute__((section(".modinfo"), used, aligned(1))) = "\0name=vmlinux";
+#endif
+static __attribute__((noinline)) int helper(int x, int len)
+{
+	int sum = 0, i;
+
+	for (i = 0; i < len; i++)
+#if defined(PATCHED) && !defined(TU_B)
+		sum += i * 2 + BASE;	/* only TU_A's helper changes */
+#else
+		sum += i + BASE;
+#endif
+	return sum + x;
+}
+
+int ENTRY(int x) { return helper(x, 4); }
+#endif
tools/objtool/tests/generic/test-thinlto-ambiguity.sh new file +77 -0

77 lines not on this page · raw message

merge bot Applied
#172 lore raw

[tip: objtool/core] objtool/klp: Add test for UBSAN metadata in an unchanged function

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

objtool/klp: Add test for UBSAN metadata in an unchanged function

Every instrumented operation gets a per-callsite metadata object in an anonymous data section -- .data..Lubsan_data and .data..Lubsan_type from GCC, .data..L__unnamed_ from Clang -- whose names are compiler-generated and mean nothing across a rebuild. is_uncorrelated_section() exists so klp diff does not try to pair them up, and nothing tested it.

The failure it prevents is a false positive, which is the direction this suite has least coverage of. Metadata belonging to a function nobody touched compares as different and drags that function into the patch. That is not a build failure: it is a larger livepatch than intended, pulling in dependencies with it, and every extra function is one more that can fail to correlate or to apply.

The fixture is built with -fsanitize=shift, which both compilers instrument; neither emits a bounds check for an index it can prove in range. One function changes, the other is byte-identical and carries instrumentation of its own, and the test asserts the second is left alone.

Verified by removing each rule from is_uncorrelated_section() in turn, which splits neatly by toolchain: dropping the .data..Lubsan rule fails the test under gcc, dropping .data..L__unnamed_ fails it under clang. One test, two code paths, each checked by the compiler that reaches it.

Assisted-by Claude:claude-opus-4
Assisted-by Claude:claude-opus-5
---
 tools/objtool/tests/generic/fixtures/ubsan_noise.c | 49 +++++++++++++-
 tools/objtool/tests/generic/test-ubsan-noise.sh    | 48 +++++++++++++-
 2 files changed, 97 insertions(+)
 create mode 100644 tools/objtool/tests/generic/fixtures/ubsan_noise.c
 create mode 100755 tools/objtool/tests/generic/test-ubsan-noise.sh
tools/objtool/tests/generic/fixtures/ubsan_noise.c new file +49 -0
new file mode 100644
index 0000000..bf59992
@@ -0,0 +1,49 @@
+// SPDX-License-Identifier: GPL-2.0
+/*
+ * A translation unit built with UBSAN, where only one of two functions is
+ * patched.
+ *
+ * Every instrumented operation gets a per-callsite metadata object in an
+ * anonymous data section -- .data..Lubsan_data and .data..Lubsan_type from
+ * GCC, .data..L__unnamed_ from Clang -- and a call to a __ubsan_handle_*
+ * routine.  The names are compiler-generated and carry no meaning across a
+ * rebuild, so klp diff has to treat those sections as uncorrelated rather than
+ * pairing them up by name.
+ *
+ * untouched() is byte-identical in both builds and exists to catch the false
+ * positive: if the metadata were correlated by name, its shifts would look
+ * changed and it would be dragged into the patch.
+ *
+ * The shifts are what draw the instrumentation.  A bounds check would do as
+ * well but neither compiler emits one for an index it can prove in range.
+ */
+
+static const char __modinfo[]
+	__attribute__((section(".modinfo"), used, aligned(1))) = "\0name=vmlinux";
+
+int shift_by(int v, int n);
+
+int untouched(int v, int n)
+{
+	int s = 0;
+
+	s += v << (n & 31);
+	s += v << ((n + 1) & 31);
+	s += shift_by(v, n);
+
+	return s;
+}
+
+int touched(int v, int n)
+{
+	int s = 0;
+
+	s += v << (n & 31);
+#ifdef PATCHED
+	s += v << ((n + 3) & 31);
+#else
+	s += v << ((n + 2) & 31);
+#endif
+
+	return s;
+}
tools/objtool/tests/generic/test-ubsan-noise.sh new file +48 -0

48 lines not on this page · raw message

merge bot Applied
#169 lore raw

[tip: objtool/core] objtool/klp: Add test for absolute and __ADDRESSABLE 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:     6f893470dc01bea8ab9033c6e310eb46902869fd
Gitweb:        https://git.kernel.org/tip/6f893470dc01bea8ab9033c6e310eb46902869fd
Author:        Song Liu <[email protected]>
AuthorDate:    Wed, 16 Sep 2026 11:43:48 -07:00
Committer:     Josh Poimboeuf <[email protected]>
CommitterDate: Wed, 16 Sep 2026 17:21:46 -07:00

objtool/klp: Add test for absolute and __ADDRESSABLE symbols

A SHN_ABS symbol has no section, so any walk of sym->sec which does not check dereferences NULL, and the kernel has plenty of them -- from linker scripts and from .set in assembly. __ADDRESSABLE() emits a pointer into .discard.addressable purely to keep a symbol referenced; it means nothing to a livepatch and is discarded at link time, but it is a relocation like any other and gets looked at.

Neither is what the patch changes. What this guards against is not a wrong answer but a crash or an error on input the kernel produces routinely, which would make every function near one unpatchable.

Not isolated to a single line, and the test says so: the absolute symbol here has zero length, so it is excluded before the section check is reached and removing that check alone changes nothing observable.

Assisted-by Claude:claude-opus-4
Assisted-by Claude:claude-opus-5
---
 tools/objtool/tests/generic/fixtures/abs_and_addressable.c | 44 ++++++-
 tools/objtool/tests/generic/test-abs-and-addressable.sh    | 50 +++++++-
 2 files changed, 94 insertions(+)
 create mode 100644 tools/objtool/tests/generic/fixtures/abs_and_addressable.c
 create mode 100755 tools/objtool/tests/generic/test-abs-and-addressable.sh
tools/objtool/tests/generic/fixtures/abs_and_addressable.c new file +44 -0
new file mode 100644
index 0000000..6392ff9
@@ -0,0 +1,44 @@
+// SPDX-License-Identifier: GPL-2.0
+/*
+ * Two constructs which appear all over the kernel and must not upset klp
+ * checksum or klp diff.
+ *
+ * An absolute symbol (SHN_ABS) has no section, so anything walking sym->sec
+ * without checking dereferences NULL.  The kernel makes them with linker
+ * scripts and with .set in asm; VDSO and the fixed-address per-cpu bases are
+ * the usual sources.
+ *
+ * __ADDRESSABLE() emits a pointer into .discard.addressable purely to keep a
+ * symbol referenced.  It is discarded at link time and means nothing to a
+ * livepatch, but the pointer is a relocation like any other and has to survive
+ * being looked at.
+ *
+ * Neither is the subject of the patch; the point is that their presence does
+ * not disturb the function that is.
+ */
+
+static const char __modinfo[]
+	__attribute__((section(".modinfo"), used, aligned(1))) = "\0name=vmlinux";
+
+/* SHN_ABS, referenced from code. */
+extern char abs_sym[];
+__asm__(".globl abs_sym\n"
+	".set abs_sym, 0x1234\n");
+
+int helper(int x);
+int helper(int x) { return x + 1; }
+
+/* The shape of __ADDRESSABLE(helper). */
+__asm__(".pushsection .discard.addressable, \"aw\"\n"
+	".balign 8\n"
+	".quad helper\n"
+	".popsection\n");
+
+int target(int x)
+{
+#ifdef PATCHED
+	return helper(x) + (int)(long)abs_sym + 1;
+#else
+	return helper(x) + (int)(long)abs_sym;
+#endif
+}
tools/objtool/tests/generic/test-abs-and-addressable.sh new file +50 -0

50 lines not on this page · raw message

merge bot Applied
#163 lore raw

[tip: objtool/core] objtool/klp: Add test for the alignment of cloned data 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:     be1044af0c4d9319427ab35aa915b9af01d7608a
Gitweb:        https://git.kernel.org/tip/be1044af0c4d9319427ab35aa915b9af01d7608a
Author:        Song Liu <[email protected]>
AuthorDate:    Wed, 16 Sep 2026 11:43:46 -07:00
Committer:     Josh Poimboeuf <[email protected]>
CommitterDate: Wed, 16 Sep 2026 17:21:46 -07:00

objtool/klp: Add test for the alignment of cloned data sections

A cloned data section has to keep its sh_addralign. Plenty of kernel data is aligned for correctness rather than speed -- per-CPU variables, anything touched by an aligned vector move, structures padded to own a cacheline -- and a clone that lands under-aligned either faults on first use or silently shares a line it was laid out to avoid. Neither shows up until the patch is loaded on hardware that cares.

The fixture's data is new in the patched build, so klp diff has to clone it rather than reference the kernel's copy, and it asserts that premise before asserting the result.

Commit 2f2600decb30 ("objtool/klp: fix data alignment in __clone_symbol()") cannot be reverted to check this -- the revert is a no-op against the current code, which has been rewritten since. Verified instead by forcing the clone's alignment to 1, which the test reports as "alignment 1, expected 64".

Assisted-by Claude:claude-opus-4
Assisted-by Claude:claude-opus-5
---
 tools/objtool/tests/generic/fixtures/data_alignment.c | 29 +++++++-
 tools/objtool/tests/generic/test-data-alignment.sh    | 40 ++++++++++-
 2 files changed, 69 insertions(+)
 create mode 100644 tools/objtool/tests/generic/fixtures/data_alignment.c
 create mode 100755 tools/objtool/tests/generic/test-data-alignment.sh
tools/objtool/tests/generic/fixtures/data_alignment.c new file +29 -0
new file mode 100644
index 0000000..900253d
@@ -0,0 +1,29 @@
+// SPDX-License-Identifier: GPL-2.0
+/*
+ * Data with an alignment stricter than its size.
+ *
+ * A cloned data section has to keep its sh_addralign.  The kernel has plenty
+ * of data whose alignment is a correctness property rather than an
+ * optimisation -- per-CPU variables, anything touched by an aligned SSE move,
+ * cacheline-aligned locks -- and a clone that lands under-aligned faults or
+ * silently shares a cacheline it was written to avoid.
+ *
+ * The object is new in the patched build, so klp diff has to clone it rather
+ * than reference the kernel's copy.
+ */
+
+static const char __modinfo[]
+	__attribute__((section(".modinfo"), used, aligned(1))) = "\0name=vmlinux";
+
+#ifdef PATCHED
+int aligned_data[2] __attribute__((aligned(64))) = { 1, 2 };
+#endif
+
+int target(int x)
+{
+#ifdef PATCHED
+	return x + aligned_data[0];
+#else
+	return x;
+#endif
+}
tools/objtool/tests/generic/test-data-alignment.sh new file +40 -0
new file mode 100755
index 0000000..8e38954
@@ -0,0 +1,40 @@
+#!/bin/bash
+# SPDX-License-Identifier: GPL-2.0
+#
+# A cloned data section keeps its alignment.
+#
+# Plenty of kernel data is aligned for correctness rather than speed: per-CPU
+# variables, anything touched by an aligned vector move, structures padded to
+# own a cacheline. A clone that lands under-aligned either faults on first use
+# or silently shares a line it was laid out to avoid, and neither shows up
+# until the patch is loaded on hardware that cares.
+#
+# Fixed by 2f2600decb30 ("objtool/klp: Fix alignment of cloned data
+# sections").
+#
+# Covers the same ground as corpus/x86_64/cloned-data-alignment in Joe
+# Lawrence's klp-build unit test corpus.
+
+. "$(dirname "$0")/../lib.sh"
+
+setup
+build_pair data_alignment.c
+
+# The premise: the compiler really did over-align it, and the object is new in
+# the patch so it has to be cloned rather than referenced.
+want="$(in_sections patched.o | sed 's/^ *\[[ 0-9]*\] *//' |
+	awk '$1 == ".data.aligned_data" { print $NF }')"
+[ "$want" = 64 ] ||
+	probe_skip "compiler gave .data.aligned_data alignment '$want', not 64"
+has_input_section orig.o .data.aligned_data &&
+	fail "fixture put aligned_data in the original; nothing to clone"
+
+run_diff
+assert_section .data.aligned_data
+
+got="$(out_sections | sed 's/^ *\[[ 0-9]*\] *//' |
+       awk '$1 == ".data.aligned_data" { print $NF }')"
+[ "$got" = "$want" ] ||
+	fail "cloned .data.aligned_data has alignment $got, expected $want"
+
+pass "cloned data section keeps its alignment"
merge bot Applied
#166 lore raw

[tip: objtool/core] objtool/klp: Add test for a patch which strips a data annotation

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

objtool/klp: Add test for a patch which strips a data annotation

klp diff needs entry boundaries for a special section: either an entsize, or ANNOTATE_DATA_SPECIAL annotations naming where each entry starts. .static_call_sites has no entsize, so the annotations are all there is -- and a patch can remove the last one in a translation unit while leaving the section itself in place, so that only the patched side has lost them.

The section still has to be handled. Dropping it leaves the patched function's static call unregistered; misreading its boundaries attaches the entry to the wrong code. Neither is reported at build time.

Give the fixture a NO_ANNOTATE knob and assert the premise -- annotation present in the original, absent in the patched object, section present in both -- before asserting the result.

Fixed by commit 3de711fba73a ("objtool/klp: Fix create_fake_symbols() skipping entsize-based sections"). Verified by making klp diff skip .static_call_sites when cloning special sections: the test fails.

Assisted-by Claude:claude-opus-4
Assisted-by Claude:claude-opus-5
---
 tools/objtool/tests/generic/test-static-call-annotate-stripped.sh | 42 ++++++++++++++++++++++++++++++++++++++++++
 1 file changed, 42 insertions(+)
 create mode 100755 tools/objtool/tests/generic/test-static-call-annotate-stripped.sh
tools/objtool/tests/generic/test-static-call-annotate-stripped.sh new file +42 -0
new file mode 100755
index 0000000..818b047
@@ -0,0 +1,42 @@
+#!/bin/bash
+# SPDX-License-Identifier: GPL-2.0
+#
+# A patch may remove the last ANNOTATE_DATA_SPECIAL in a translation unit while
+# leaving the special section it described in place.
+#
+# klp diff needs entry boundaries for a special section: either an entsize, or
+# annotations naming where each entry starts.  .static_call_sites has no
+# entsize, so the annotations are all there is -- and when the patched object
+# is the only side that lost them, the two sides no longer agree on how the
+# section divides up.
+#
+# The section must still be handled.  Dropping it would leave the patched
+# function's static call unregistered; misreading its boundaries would attach
+# the entry to the wrong code.  Either way nothing is reported at build time.
+#
+# Fixed by commit 3de711fba73a ("objtool/klp: Fix create_fake_symbols()
+# skipping entsize-based sections").
+#
+# Covers the same ground as corpus/x86_64/static-call-annotate-stripped in Joe
+# Lawrence's klp-build unit test corpus.
+
+. "$(dirname "$0")/../lib.sh"
+
+setup
+build_pair static_call.c -DNO_ANNOTATE
+
+# The premise: the original describes its entry, the patched one no longer
+# does, and both still have the section itself.
+has_input_section orig.o .discard.annotate_data ||
+	fail "fixture produced no annotation in the original"
+has_input_section patched.o .discard.annotate_data &&
+	fail "patched object still has the annotation; nothing was stripped"
+assert_input_section .static_call_sites
+
+run_diff
+
+assert_patched target
+assert_section .static_call_sites
+assert_reloc_sym .static_call_sites target
+
+pass "static call site kept when the patch strips its data annotation"
merge bot Applied
#160 lore raw

[tip: objtool/core] objtool/klp: Add test for alternative replacement code in checksums

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

objtool/klp: Add test for alternative replacement code in checksums

checksum_update_insn() walks insn->alts after hashing the instruction
itself: the alternative's type, and where the replacement forms a group, its feature number and every instruction in it. A patch which edits only the replacement -- code that runs on some CPUs and not others -- still has to move the function's checksum.

When it does not, klp diff calls the function unchanged and leaves it out. The patch ships the old replacement, and the bug is fixed only on machines whose CPU takes the other arm. Which machines those are depends on the feature bit, so it presents as a machine-specific bug rather than a missing patch.

insn->alts is built by objtool's check pass, not by the compiler, so the pair goes through that first. --mcount is the action used: it is the cheapest one that does not also need --link.

Two of the three paths are isolated. Skipping the alts walk and dropping the feature hash both make this fail, and the second of those only exists inside the alt_group branch, so reaching it proves the grouped path is taken. The alternative's type is hashed but not varied here -- the fixture emits one kind of alternative -- so that line is covered without being isolated, as is the in_alt recursion guard, which wants nested alternatives.

Assisted-by Claude:claude-opus-4
Assisted-by Claude:claude-opus-5
---
 tools/objtool/tests/x86/fixtures/checksum_alt.c | 66 ++++++++++++++++-
 tools/objtool/tests/x86/test-checksum-alt.sh    | 45 +++++++++++-
 2 files changed, 111 insertions(+)
 create mode 100644 tools/objtool/tests/x86/fixtures/checksum_alt.c
 create mode 100755 tools/objtool/tests/x86/test-checksum-alt.sh
tools/objtool/tests/x86/fixtures/checksum_alt.c new file +66 -0
new file mode 100644
index 0000000..ed342d9
@@ -0,0 +1,66 @@
+// SPDX-License-Identifier: GPL-2.0
+/*
+ * An x86 alternative whose replacement code is part of the patched function's
+ * checksum.
+ *
+ * checksum_update_insn() walks insn->alts after hashing the instruction
+ * itself, hashing the alternative's type and, when the replacement forms a
+ * group, its feature number and every instruction in it.  So editing only the
+ * replacement -- code the CPU may or may not ever run -- has to move the
+ * function's checksum.
+ *
+ * It is reached through objtool's own alternative handling, so the object has
+ * to go through the check pass first: insn->alts is built there, not by the
+ * compiler.
+ *
+ * struct alt_instr is written out by hand as in empty_alternative.c: s32
+ * instr_offset, s32 repl_offset, u32 ft_flags, u8 instrlen, u8 replacementlen.
+ *
+ * Variants, applied to the patched build only:
+ *
+ *   ALT_REPL     the replacement instruction changes; the original does not
+ *   ALT_FEATURE  the feature number changes; no code changes at all
+ */
+
+static const char __modinfo[]
+	__attribute__((section(".modinfo"), used, aligned(1))) = "\0name=vmlinux";
+
+/*
+ * Both spellings are two bytes, because a replacement may not be longer than
+ * the instruction it replaces: "xchg %ax, %ax" is 66 90 and two nops are
+ * 90 90.  The original below is padded to match.
+ */
+#if defined(PATCHED) && defined(ALT_REPL)
+#define REPL_INSN "	nop\n\t	nop\n\t"
+#else
+#define REPL_INSN "	xchg %ax, %ax\n\t"
+#endif
+
+#if defined(PATCHED) && defined(ALT_FEATURE)
+#define FEATURE "7"
+#else
+#define FEATURE "3"
+#endif
+
+int target(int x)
+{
+	asm volatile(
+		"661:	nop\n\t"
+		"	nop\n\t"
+		"662:\n\t"
+		".pushsection .altinstr_replacement, \"ax\"\n\t"
+		".globl target_repl\n\t"
+		"target_repl:\n\t"
+		REPL_INSN
+		"target_repl_end:\n\t"
+		".popsection\n\t"
+		".pushsection .altinstructions, \"aM\", @progbits, 14\n\t"
+		".long 661b - .\n\t"
+		".long target_repl - .\n\t"
+		".long " FEATURE "\n\t"
+		".byte 662b - 661b\n\t"
+		".byte target_repl_end - target_repl\n\t"
+		".popsection\n\t");
+
+	return x + 1;
+}
tools/objtool/tests/x86/test-checksum-alt.sh new file +45 -0

45 lines not on this page · raw message

merge bot Applied
#157 lore raw

[tip: objtool/core] objtool/klp: Add test for instruction operand checksums

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

objtool/klp: Add test for instruction operand checksums

checksum_update_insn() hashes an instruction's bytes and then what any relocation on it refers to: a string section contributes the string's contents, anything else the target symbol's name and adjusted addend, with a reference to a static resolved through its section symbol first.

None of that shows up in the bytes. A rel32 operand is zero in the object and supplied by the relocation, so calling a different function, editing a literal the code passes, or reading a different index of an array all leave the encoded instruction byte-identical. A checksum stopping at the bytes reports the function unchanged and the patch silently does not contain the fix.

test-checksum-position is the other half: what must *not* change the checksum when a function merely moves.

Each of the four is verified by sabotaging the line it covers. The static case needed a writer the compiler cannot see through -- without one it proves the array is never written, folds every read to zero, and emits no relocation at all, so the reference under test does not exist and the variant passes having compared two identical objects.

Assisted-by Claude:claude-opus-4
Assisted-by Claude:claude-opus-5
---
 tools/objtool/tests/generic/fixtures/checksum_insn.c | 78 +++++++++++-
 tools/objtool/tests/generic/test-checksum-insn.sh    | 49 +++++++-
 2 files changed, 127 insertions(+)
 create mode 100644 tools/objtool/tests/generic/fixtures/checksum_insn.c
 create mode 100755 tools/objtool/tests/generic/test-checksum-insn.sh
tools/objtool/tests/generic/fixtures/checksum_insn.c new file +78 -0
new file mode 100644
index 0000000..10f70a7
@@ -0,0 +1,78 @@
+// SPDX-License-Identifier: GPL-2.0
+/*
+ * Instruction operands whose change must move a function's checksum even
+ * though the instruction bytes themselves do not.
+ *
+ * checksum_update_insn() hashes the raw bytes and then, when the instruction
+ * carries a relocation, what that relocation refers to: a string section
+ * contributes the string's contents, anything else the target symbol's name
+ * and the adjusted addend.  A reference to a static arrives as a section
+ * symbol and has to be resolved back to the object first.
+ *
+ * The bytes are identical in every case below -- a rel32 operand is zero in
+ * the object and supplied by the relocation -- so a checksum that stopped at
+ * the bytes would call all of these unchanged.
+ *
+ * Each variant applies to the patched build only:
+ *
+ *   WHICH_CALL    calls a different function
+ *   STR_CONTENT   passes a literal whose text was edited
+ *   WHICH_SLOT    reads a different index of a global array: addend only
+ *   WHICH_PRIV    the same, for a static, reached through its section symbol
+ */
+
+static const char __modinfo[]
+	__attribute__((section(".modinfo"), used, aligned(1))) = "\0name=vmlinux";
+
+int callee_a(int x);
+int callee_b(int x);
+int sink(const char *s);
+
+int slots[4];
+
+/*
+ * A file-local array, plus a writer the compiler cannot see through.  Without
+ * one it can prove the array is never written, folds every read to zero, and
+ * emits no relocation at all -- so the reference this is here to exercise does
+ * not exist.
+ */
+static int priv_slots[4];
+
+void set_priv(int i, int v);
+void set_priv(int i, int v)
+{
+	priv_slots[i] = v;
+}
+
+#if defined(PATCHED) && defined(STR_CONTENT)
+#define MESSAGE "edited"
+#else
+#define MESSAGE "original"
+#endif
+
+int target(int x)
+{
+	int r;
+
+#if defined(PATCHED) && defined(WHICH_CALL)
+	r = callee_b(x);
+#else
+	r = callee_a(x);
+#endif
+
+	r += sink(MESSAGE);
+
+#if defined(PATCHED) && defined(WHICH_SLOT)
+	r += slots[2];
+#else
+	r += slots[1];
+#endif
+
+#if defined(PATCHED) && defined(WHICH_PRIV)
+	r += priv_slots[3];
+#else
+	r += priv_slots[1];
+#endif
+
+	return r;
+}
tools/objtool/tests/generic/test-checksum-insn.sh new file +49 -0

49 lines not on this page · raw message

merge bot Applied
#154 lore raw

[tip: objtool/core] objtool/klp: Add test for a static call introduced by the patch

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

objtool/klp: Add test for a static call introduced by the patch

The counterpart to the static branch case: a patch may add a static call to a function which had none, so the .static_call_sites entry is new and there is nothing in the original to correlate it against.

Where the key lives still decides whether that is allowed. A vmlinux key is reachable; a module-owned one is not, for the same reason an existing module key is not -- late module patching lets the livepatch load first and the unresolved entry is dereferenced when the module arrives. Both halves are here because they fail in opposite directions: dropping the new entry leaves a static call the kernel never patches, and accepting a new module-owned one is the corruption the check exists to prevent.

Both halves are one test over one fixture: built with -DNEW_CALL the key is vmlinux's and the new entry has to be carried in; built with -DMODNAME as well the key belongs to a module, klp diff has to reject it, and no output object may be left behind. The premise is asserted first -- the original must have no .static_call_sites at all -- since otherwise this is a second copy of test-static-call-module-key.

Covers the same ground as corpus/x86_64/static-call-vmlinux-new and corpus/x86_64/static-call-module-new in Joe Lawrence's klp-build unit test corpus.

Assisted-by Claude:claude-opus-4
Assisted-by Claude:claude-opus-5
---
 tools/objtool/tests/generic/test-static-call-new.sh | 45 ++++++++++++-
 1 file changed, 45 insertions(+)
 create mode 100755 tools/objtool/tests/generic/test-static-call-new.sh
tools/objtool/tests/generic/test-static-call-new.sh new file +45 -0
new file mode 100755
index 0000000..f7d2b39
@@ -0,0 +1,45 @@
+#!/bin/bash
+# SPDX-License-Identifier: GPL-2.0
+#
+# A patch may introduce a static call where the original function had none.
+#
+# The .static_call_sites entry is then new, with nothing in the original to
+# correlate it against, so klp diff has to carry it into the patch from
+# scratch.  Where the key lives still decides whether that is allowed: a
+# vmlinux key is reachable, and a module-owned one is not, for the same reason
+# an existing module key is not -- late module patching lets the livepatch load
+# first, and the unresolved entry is dereferenced when the module arrives.
+#
+# Both halves are here because they fail in opposite directions.  Dropping the
+# new entry leaves a static call the kernel never patches; accepting a new
+# module-owned one is the corruption the check exists to prevent.
+#
+# Covers the same ground as corpus/x86_64/static-call-vmlinux-new and
+# static-call-module-new in Joe Lawrence's klp-build unit test corpus.
+
+. "$(dirname "$0")/../lib.sh"
+
+setup
+build_pair static_call.c -DNEW_CALL
+
+# The premise: the original really has no static call, the patched one does.
+has_input_section orig.o .static_call_sites &&
+	fail "fixture put a .static_call_sites in the original; nothing new to add"
+has_input_section patched.o .static_call_sites ||
+	probe_skip "compiler produced no .static_call_sites on this arch"
+
+run_diff
+assert_patched target
+assert_section .static_call_sites
+assert_reloc_sym .static_call_sites target
+
+# The same new call, with the key owned by a module: not reachable, so the
+# build has to stop rather than emit a relocation nothing will resolve.
+rm -f "$workdir/out.o"
+build_pair static_call.c -DNEW_CALL -DMODNAME='"klp_testmod"'
+run_diff 255
+assert_diff_log 'unsupported static call key __SCK__klp_test_call'
+[ -e "$workdir/out.o" ] &&
+	fail "output object produced for a rejected input"
+
+pass "static call introduced by the patch carried in, or rejected for a module key"
merge bot Applied
#151 lore raw

[tip: objtool/core] objtool/klp: Add test for tracepoint and pr_debug 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:     de215ff9b0a848541a496cfbbe102e68c894f66a
Gitweb:        https://git.kernel.org/tip/de215ff9b0a848541a496cfbbe102e68c894f66a
Author:        Song Liu <[email protected]>
AuthorDate:    Wed, 16 Sep 2026 11:43:42 -07:00
Committer:     Josh Poimboeuf <[email protected]>
CommitterDate: Wed, 16 Sep 2026 17:21:46 -07:00

objtool/klp: Add test for tracepoint and pr_debug static branch keys

A module-owned static branch key is normally fatal, because late module patching lets the livepatch load before the module it depends on and jump_label_add_module() then dereferences an unresolved entry.

Tracepoints and pr_debug() generate such keys everywhere, so refusing them outright would make any function containing a trace_*() call or a pr_debug() unpatchable. klp diff drops the entry, warns, and carries on:
the patched code works with that one tracepoint or debug print permanently off.

Both halves matter, and the test asserts both. A build which fails is a function nobody can patch; an entry left in place is the corruption the rejection exists to prevent.

Give the fixture a KEY_NAME knob so the same static branch can be built with either special name. Verified by removing each exemption in turn -- the test fails for both. That the entry is then dropped is asserted but not isolated, and the test says so.

Assisted-by Claude:claude-opus-4
Assisted-by Claude:claude-opus-5
---
 tools/objtool/tests/generic/test-jump-label-exempt-keys.sh | 51 +++++++-
 1 file changed, 51 insertions(+)
 create mode 100755 tools/objtool/tests/generic/test-jump-label-exempt-keys.sh
tools/objtool/tests/generic/test-jump-label-exempt-keys.sh new file +51 -0
new file mode 100755
index 0000000..fa2f913
@@ -0,0 +1,51 @@
+#!/bin/bash
+# SPDX-License-Identifier: GPL-2.0
+#
+# Two kinds of module-owned static branch key are disabled with a warning
+# instead of rejected.
+#
+# A module-local key is normally fatal: late module patching lets the livepatch
+# load before the module it depends on, so the unresolved __jump_table entry is
+# dereferenced by jump_label_add_module().  test-jump-label-module-key covers
+# that rejection.
+#
+# Tracepoints and pr_debug() generate such keys everywhere, though, and
+# refusing them outright would make any function containing a trace_*() call or
+# a pr_debug() unpatchable.  So klp diff drops the entry, says so, and carries
+# on: the patched code keeps working with that one tracepoint or debug print
+# permanently off.
+#
+# Both halves matter.  A build that fails is a function nobody can patch; an
+# entry left in place is the memory corruption the rejection exists to prevent.
+#
+# The two exemptions are isolated: remove either and this fails.  That the
+# entry is then dropped is asserted but not isolated -- making the caller keep
+# it anyway produces no output difference here, so that assertion stands as a
+# check on the behaviour rather than on the line which produces it.
+#
+# Covers the same ground as corpus/x86_64/static-call-module-tracepoint and
+# pr-debug-unsupported in Joe Lawrence's klp-build unit test corpus.
+
+. "$(dirname "$0")/../lib.sh"
+
+setup
+
+# check <key name> <expected warning>
+check()
+{
+	build_pair jump_label.c -DKEY_NAME="$1" -DMODNAME='"klp_testmod"'
+	require_input_section __jump_table
+
+	# Accepted, not rejected: this is the whole point.
+	run_diff
+	assert_diff_log "$2"
+
+	# And the entry is gone, not merely complained about.
+	assert_patched target
+	assert_no_section __jump_table
+}
+
+check __tracepoint_klp_test        'disabling unsupported tracepoint klp_test'
+check __UNIQUE_ID_ddebug_klp_test  'disabling unsupported pr_debug'
+
+pass "tracepoint and pr_debug keys disabled with a warning, not rejected"
merge bot Applied
#148 lore raw

[tip: objtool/core] objtool/klp: Add test for a static branch introduced by the patch

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

objtool/klp: Add test for a static branch introduced by the patch

Patching a function which already has a static branch and adding one to a function which had none are different cases. In the second the __jump_table entry is itself new, so there is nothing in the original to correlate it against: klp diff has to carry the entry into the patch from scratch and reach the key the way it reaches any other vmlinux symbol.

Dropping it is silent. The patched function keeps a static branch the kernel never patches, so it takes the same arm forever whatever the key is set to.

Give the fixture a NEW_KEY knob which puts the whole branch behind PATCHED, and assert the premise -- that the original really has no __jump_table -- before asserting the result, since otherwise this is just a second copy of test-jump-label-key.

Verified by making klp diff skip __jump_table when cloning special
sections: the test fails.

Assisted-by Claude:claude-opus-4
Assisted-by Claude:claude-opus-5
---
 tools/objtool/tests/generic/test-jump-label-new-key.sh | 51 +++++++++-
 1 file changed, 51 insertions(+)
 create mode 100755 tools/objtool/tests/generic/test-jump-label-new-key.sh
tools/objtool/tests/generic/test-jump-label-new-key.sh new file +51 -0
new file mode 100755
index 0000000..3bc6005
@@ -0,0 +1,51 @@
+#!/bin/bash
+# SPDX-License-Identifier: GPL-2.0
+#
+# A patch may introduce a static branch where the original function had none.
+#
+# That is not the same case as patching a function which already has one.  The
+# __jump_table entry is itself new, so there is no counterpart in the original
+# to correlate it against: klp diff has to carry the entry and the key into the
+# patch from scratch, and the key has to be reached the way any other reference
+# to a vmlinux symbol is.
+#
+# Get it wrong and the entry is dropped, leaving a static branch the kernel
+# never patches -- the code takes the wrong arm forever, silently.
+#
+# Where the key lives still decides whether that is allowed, exactly as it does
+# for a key the original already had: a module-owned one cannot be reached, so
+# introducing one has to stop the build rather than emit an entry nothing will
+# resolve.
+#
+# Covers the same ground as corpus/x86_64/static-branch-vmlinux-new and
+# static-branch-module-new in Joe Lawrence's klp-build unit test corpus.
+
+. "$(dirname "$0")/../lib.sh"
+
+setup klp_test_key
+build_pair jump_label.c -DNEW_KEY
+
+# The premise: the original really has no jump table, and the patched one does.
+has_input_section orig.o __jump_table &&
+	fail "fixture put a __jump_table in the original; nothing new to add"
+has_input_section patched.o __jump_table ||
+	probe_skip "compiler produced no __jump_table on this arch"
+
+run_diff
+
+assert_patched target
+assert_section __jump_table
+assert_reloc_sym __jump_table target
+
+# The same new branch, with the key owned by a module.  Drop the vmlinux export
+# first: while it is exported the key is reachable and being new changes
+# nothing, which is what the first version of this got wrong.
+export_syms
+rm -f "$workdir/out.o"
+build_pair jump_label.c -DNEW_KEY -DMODNAME='"klp_testmod"'
+run_diff 255
+assert_diff_log 'unsupported static branch key klp_test_key'
+[ -e "$workdir/out.o" ] &&
+	fail "output object produced for a rejected input"
+
+pass "static branch introduced by the patch carried in, or rejected for a module key"
merge bot Applied
#145 lore raw

[tip: objtool/core] objtool/klp: Add test for symbols with no checksum entry of their own

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

objtool/klp: Add test for symbols with no checksum entry of their own

.discard.sym_checksum is an array of { address, checksum } looked up by the address a relocation points at, so the invariant is one entry per address. calculate_checksums() skips zero-length symbols, aliases and cold parts to keep it, and nothing checked that it does.

A duplicate entry is not a build failure. It makes the lookup ambiguous, and whichever checksum loses is never consulted again -- so a function whose code changed can be read as unchanged and dropped from the patch.

The alias skip is verified the usual way: remove it and the test fails. The other two are not isolated, and the test says so rather than implying otherwise. A zero-length symbol is excluded by several of the guards at once -- its section has no data either -- so removing any one of them changes nothing observable; the assertion stands as a check on the behaviour, not on the line that produces it. The cold-part skip needs a compiler that splits functions and is not reached here at all.

Which of an aliased pair keeps the entry falls out of symbol table order, so the test requires exactly one of the two rather than naming a winner -- as written first it named real_function and failed, because gcc kept the alias.

Assisted-by Claude:claude-opus-4
Assisted-by Claude:claude-opus-5
---
 tools/objtool/tests/generic/fixtures/checksum_skip.c | 47 ++++++-
 tools/objtool/tests/generic/test-checksum-skip.sh    | 81 +++++++++++-
 2 files changed, 128 insertions(+)
 create mode 100644 tools/objtool/tests/generic/fixtures/checksum_skip.c
 create mode 100755 tools/objtool/tests/generic/test-checksum-skip.sh
tools/objtool/tests/generic/fixtures/checksum_skip.c new file +47 -0
new file mode 100644
index 0000000..973bdc1
@@ -0,0 +1,47 @@
+// SPDX-License-Identifier: GPL-2.0
+/*
+ * Symbols calculate_checksums() must not give an entry of their own.
+ *
+ * Three kinds are skipped, for two different reasons:
+ *
+ *   zero-length   there is nothing to hash, and an entry keyed on the
+ *                 symbol's address would collide with whatever really lives
+ *                 there.
+ *   alias         a second name for an address already checksummed.
+ *   cold part     hashed as part of its parent, which func_for_each_insn()
+ *                 walks into, so a separate entry would double-count it.
+ *
+ * An entry per address is the invariant: .discard.sym_checksum is looked up by
+ * the address a relocation points at, so two entries for one address make the
+ * lookup ambiguous and one of the two checksums unreachable.
+ */
+
+static const char __modinfo[]
+	__attribute__((section(".modinfo"), used, aligned(1))) = "\0name=vmlinux";
+
+/* Zero-length: an object symbol of size 0, in a section of its own. */
+extern char empty_marker[];
+__asm__(".pushsection .data.empty_marker,\"aw\",@progbits\n"
+	".globl empty_marker\n"
+	".type empty_marker, @object\n"
+	"empty_marker:\n"
+	".size empty_marker, 0\n"
+	".popsection\n");
+
+int real_function(int x);
+int real_function(int x)
+{
+#ifdef PATCHED
+	return x + 2;
+#else
+	return x + 1;
+#endif
+}
+
+/* Alias: a second name for real_function's address. */
+int alias_function(int x) __attribute__((alias("real_function")));
+
+int target(int x)
+{
+	return real_function(x) + alias_function(x) + (int)(long)empty_marker;
+}
tools/objtool/tests/generic/test-checksum-skip.sh new file +81 -0

81 lines not on this page · raw message

merge bot Applied
#142 lore raw

[tip: objtool/core] objtool/klp: Add test for data object checksums

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

objtool/klp: Add test for data object checksums

klp checksum hashes a data symbol's length, its bytes, and every relocation it carries -- as the target's name and adjusted addend, except a reference into a string section, which contributes the string's contents instead. Nothing covered any of it.

Each is load-bearing, and the failure is always the same shape: a checksum which ignores one calls a changed object unchanged, klp diff leaves it out of the patch, and the patched code goes on reading the kernel's old copy. The string case cannot be caught by hashing bytes: the pointer is identical, same section and same offset, and only the text it refers to moved.

One fixture, six variants applied to the patched build alone. Each was verified by sabotaging the line it covers and watching the test fail:

  raw bytes            initialiser change
  length               a .bss object grows; its bytes are never hashed
  string contents      literal edited in place, pointer untouched
  reloc target name    pointer moved to another function
  reloc addend         same array, different index
  section-symbol path  the same, via a static's section symbol

Two of those needed the fixture rebuilding. An initialised array does not isolate the length, because growing one changes the hashed bytes too -- hence .bss, where there are none. And a named char[] does not reach the contents-hashing path at all: that keys on SHF_STRINGS, which the compiler sets on the mergeable section a literal lands in and not on an array given a section of its own.

Assisted-by Claude:claude-opus-4
Assisted-by Claude:claude-opus-5
---
 tools/objtool/tests/generic/fixtures/checksum_data.c | 116 ++++++++++-
 tools/objtool/tests/generic/test-checksum-data.sh    |  61 +++++-
 2 files changed, 177 insertions(+)
 create mode 100644 tools/objtool/tests/generic/fixtures/checksum_data.c
 create mode 100755 tools/objtool/tests/generic/test-checksum-data.sh
tools/objtool/tests/generic/fixtures/checksum_data.c new file +116 -0
new file mode 100644
index 0000000..6310af5
@@ -0,0 +1,116 @@
+// SPDX-License-Identifier: GPL-2.0
+/*
+ * Data objects whose checksums must move for reasons the raw bytes do not
+ * show.
+ *
+ * checksum_update_object() hashes a data symbol's length and its bytes, and
+ * then walks its relocations: a reference into a string section contributes
+ * the string's *contents*, and any other reference contributes the target
+ * symbol's name and the adjusted addend.  So three changes that leave the
+ * object's own bytes identical still have to change its checksum:
+ *
+ * Each variant is selected by a -D on the patched build only, so the original
+ * is always the baseline:
+ *
+ *   WHICH_FUNC   the function pointer points somewhere else
+ *   WHICH_STR    the string pointer points at a different literal
+ *   STR_CONTENT  the string it points at is edited in place
+ *   WHICH_SLOT   the same array, at a different index: addend only
+ *   WHICH_PRIV   likewise, but a static, reached through its section symbol
+ *
+ * The last is the interesting one.  Nothing in the pointer changes -- same
+ * section, same offset -- so a checksum that hashed only the relocation and
+ * not what it referred to would call the object unchanged, and the patched
+ * kernel would keep the old string.
+ */
+
+static const char __modinfo[]
+	__attribute__((section(".modinfo"), used, aligned(1))) = "\0name=vmlinux";
+
+int callee_a(int x);
+int callee_b(int x);
+int callee_a(int x) { return x + 1; }
+int callee_b(int x) { return x + 2; }
+
+/*
+ * String *literals*, not named arrays.  The contents-hashing path keys on
+ * SHF_STRINGS, which the compiler sets on the mergeable .rodata.str1.1 a
+ * literal lands in and not on a named char[] given a section of its own.  A
+ * fixture using the latter exercises the ordinary name-and-addend path and
+ * reports nothing when the text changes.
+ */
+#if defined(PATCHED) && defined(STR_CONTENT)
+#define MESSAGE "edited"
+#else
+#define MESSAGE "original"
+#endif
+
+/* A plain data object: only its own bytes decide the checksum. */
+#if defined(PATCHED) && defined(PLAIN_VALUE)
+int plain = 43;
+#else
+int plain = 42;
+#endif
+
+/*
+ * A .bss object, where length is the only thing there is to hash: the section
+ * has no data, so the bytes are skipped and only sym->len distinguishes this
+ * from an object of another size.  An initialised array would not isolate it
+ * -- growing one changes the hashed bytes as well.
+ */
+#if defined(PATCHED) && defined(LONGER)
+char sized[4];
+#else
+char sized[2];
+#endif
+
+/*
+ * A reference into the middle of an array: same target symbol, different
+ * addend.  Nothing else in the object changes, so this is the only way to see
+ * whether the addend is hashed at all.
+ */
+int slots[4];
+
+/*
+ * A file-local array.  A reference to a static lands on its section symbol
+ * plus an offset, so the hash has to resolve that back to the underlying
+ * object before it has a name to hash at all -- a different code path from the
+ * global above, and one that silently contributes nothing when it fails.
+ */
+static int priv_slots[4];
+
+struct desc {
+	int (*fn)(int arg);
+	const char *str;
+	int *slot;
+	int *priv;
+};
+
+const struct desc descriptor = {
+#if defined(PATCHED) && defined(WHICH_FUNC)
+	.fn = callee_b,
+#else
+	.fn = callee_a,
+#endif
+#if defined(PATCHED) && defined(WHICH_STR)
+	.str = "a different literal",
+#else
+	.str = MESSAGE,
+#endif
+#if defined(PATCHED) && defined(WHICH_SLOT)
+	.slot = &slots[2],
+#else
+	.slot = &slots[1],
+#endif
+#if defined(PATCHED) && defined(WHICH_PRIV)
+	.priv = &priv_slots[3],
+#else
+	.priv = &priv_slots[1],
+#endif
+};
+
+int target(int x)
+{
+	return descriptor.fn(x) + plain + sized[0] + (int)descriptor.str[0] +
+	       *descriptor.slot + *descriptor.priv;
+}
tools/objtool/tests/generic/test-checksum-data.sh new file +61 -0

61 lines not on this page · raw message

merge bot Applied
#139 lore raw

[tip: objtool/core] objtool/klp: Test text annotations on alternative replacements

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

objtool/klp: Test text annotations on alternative replacements

The kernel annotates instructions inside an ALTERNATIVE's replacement wherever objtool has to be told something about them -- a retpoline-safe indirect branch, a deliberately absent ENDBR. klp diff dropped those annotations, for two reasons: replacement code has no real symbol, so the NOTYPE fake symbol objtool invents for it was not recognised as worth keeping a reference to, and .discard.annotate_insn was processed before .altinstructions, so the replacement it named had no clone yet.

Nothing fails at build time when the annotation goes missing. It surfaces later as objtool warning about, or rejecting, the very code the annotation was there to explain.

The fixture keeps the replacement label global, as empty_alternative.c does, so the relocations name it instead of .altinstr_replacement plus an addend -- which klp diff rejects outright. The label is still NOTYPE, which is the property under test. The test asserts the relocation as well as the section, since an entry whose relocation was dropped would otherwise pass.

Verified by reverting commit 62a7a01fde87 ("objtool/klp: Fix extraction of text annotations for alternatives"): the output has no .discard.annotate_insn at all and the test fails, under both gcc and clang.

---
 tools/objtool/tests/x86/fixtures/alt_annotate.c | 57 ++++++++++++++++-
 tools/objtool/tests/x86/test-alt-annotation.sh  | 38 +++++++++++-
 2 files changed, 95 insertions(+)
 create mode 100644 tools/objtool/tests/x86/fixtures/alt_annotate.c
 create mode 100755 tools/objtool/tests/x86/test-alt-annotation.sh
tools/objtool/tests/x86/fixtures/alt_annotate.c new file +57 -0
new file mode 100644
index 0000000..af44d32
@@ -0,0 +1,57 @@
+// SPDX-License-Identifier: GPL-2.0
+/*
+ * An x86 alternative whose replacement instruction carries a text annotation.
+ *
+ * The kernel does this wherever an ALTERNATIVE contains something objtool has
+ * to be told about -- a retpoline-safe indirect branch, an intentionally
+ * missing ENDBR -- so the .discard.annotate_insn entry references an address
+ * inside .altinstr_replacement rather than inside a function.
+ *
+ * Two things make that awkward for klp diff, and both are why this fixture
+ * exists.  Replacement code has no real symbol: objtool invents a NOTYPE fake
+ * symbol for it, so an annotation pointing there does not reference a FUNC.
+ * And .discard.annotate_insn has to be cloned after .altinstructions, or the
+ * replacement it names has no clone to point at yet.
+ *
+ * struct alt_instr is written out by hand as in empty_alternative.c: s32
+ * instr_offset, s32 repl_offset, u32 ft_flags, u8 instrlen, u8 replacementlen,
+ * with an entsize so klp diff can find the entry boundaries.
+ * .discard.annotate_insn entries are s32 offset, s32 type; type 2 is
+ * ANNOTYPE_RETPOLINE_SAFE.
+ *
+ * The replacement label is global so the relocations name it rather than
+ * .altinstr_replacement plus an addend, which klp diff cannot convert.  It is
+ * still NOTYPE, which is the shape that matters here.
+ */
+
+static const char __modinfo[]
+	__attribute__((section(".modinfo"), used, aligned(1))) = "\0name=vmlinux";
+
+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"
+		/* The annotation lands inside the replacement. */
+		".pushsection .discard.annotate_insn, \"M\", @progbits, 8\n\t"
+		".long target_repl - .\n\t"
+		".long 2\n\t"
+		".popsection\n\t"
+		"target_repl_end:\n\t"
+		".popsection\n\t"
+		".pushsection .altinstructions, \"aM\", @progbits, 14\n\t"
+		".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"
+		".popsection\n\t");
+#ifdef PATCHED
+	return x + 2;
+#else
+	return x + 1;
+#endif
+}
tools/objtool/tests/x86/test-alt-annotation.sh new file +38 -0
new file mode 100755
index 0000000..96760e6
@@ -0,0 +1,38 @@
+#!/bin/bash
+# SPDX-License-Identifier: GPL-2.0
+#
+# A text annotation on an instruction inside an alternative's replacement must
+# be carried into the patch.
+#
+# The kernel annotates replacement code wherever objtool has to be told
+# something about it -- a retpoline-safe indirect branch, a deliberately absent
+# ENDBR.  Two things made klp diff drop those annotations:
+#
+#   - replacement code has no real symbol, so objtool invents a NOTYPE fake
+#     one, and the extraction only kept references to FUNC symbols;
+#   - .discard.annotate_insn was processed before .altinstructions, so the
+#     replacement it referenced had no clone to point at yet.
+#
+# Nothing fails at build time when the annotation goes missing.  It surfaces
+# later as objtool warning about, or rejecting, the patched code it was there
+# to explain.
+#
+# Fixed by 62a7a01fde87 ("objtool/klp: Fix extraction of text annotations for
+# alternatives").
+
+. "$(dirname "$0")/../lib.sh"
+
+setup
+build_pair alt_annotate.c
+
+assert_input_section .altinstructions
+assert_input_section .discard.annotate_insn
+
+run_diff
+
+# The annotation has to survive, and to still name the replacement.  Checking
+# only the section would pass on an entry whose relocation was dropped.
+assert_section .discard.annotate_insn
+assert_reloc_sym .discard.annotate_insn target_repl
+
+pass "text annotation on an alternative replacement carried into the patch"
merge bot Applied
#133 lore raw

[tip: objtool/core] objtool/klp: Test rejection of a file-local static branch key

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

objtool/klp: Test rejection of a file-local static branch key

A static branch key owned by a module cannot be reached with a klp reloc:
late module patching allows the livepatch module to load first, leaving the __jump_table entry unresolved for jump_label_add_module() to dereference. validate_special_section_klp_reloc() rejects it at build time.

test-jump-label-module-key covers that for a global key. A file-local one takes a different route to the same check: the compiler references a static through its section symbol plus an addend, so the key has to be resolved from the section before it can be recognised as STT_OBJECT at all. Until commit f9fb44b0ecef ("objtool/klp: Fix detection of corrupt static branch/call entries") it was not, and the reference was silently emitted.

Give the fixture a STATIC_KEY knob and cover it. The test checks that the input really does reference the key through its section, since without that it is only a second copy of the existing test.

Verified by reverting commit f9fb44b0ecef ("objtool/klp: Fix detection of corrupt static branch/call entries"): klp diff accepts the input and the test fails, under both gcc and clang.

Assisted-by Claude:claude-opus-4
Assisted-by Claude:claude-opus-5
---
 tools/objtool/tests/generic/test-jump-label-module-static-key.sh | 45 +++++++++++++++++++++++++++++++++++++++++++++
 1 file changed, 45 insertions(+)
 create mode 100755 tools/objtool/tests/generic/test-jump-label-module-static-key.sh
tools/objtool/tests/generic/test-jump-label-module-static-key.sh new file +45 -0
new file mode 100755
index 0000000..7bdcbaf
@@ -0,0 +1,45 @@
+#!/bin/bash
+# SPDX-License-Identifier: GPL-2.0
+#
+# A static branch key owned by a module is rejected whether the key is global
+# or file-local.
+#
+# The rejection matters because late module patching allows the livepatch
+# module to load before the module it depends on: the __jump_table klp reloc is
+# then unresolved, and jump_label_add_module() dereferences an uninitialized
+# pointer.  Catching it at build time is the only defence.
+#
+# test-jump-label-module-key covers the global key.  A file-local one reaches
+# the same check by a different route: the compiler emits the reference against
+# the section symbol plus an addend, so validate_special_section_klp_reloc()
+# has to resolve it to the underlying object before it can see a key at all.
+# Until it did, a static key was passed over as "not STT_OBJECT" and the
+# unsupported reference was emitted with nothing said.
+#
+# Fixed by f9fb44b0ecef ("objtool/klp: Fix detection of corrupt static
+# branch/call entries").
+
+. "$(dirname "$0")/../lib.sh"
+
+setup
+build_pair jump_label.c -DSTATIC_KEY -DMODNAME='"klp_testmod"'
+
+require_input_section __jump_table
+
+# The premise: the key is reached through its section symbol, not by name.
+# Without that this is just a second copy of test-jump-label-module-key.
+input_jump_relocs="$(in_relocs orig.o | awk '/rela__jump_table/,/^$/')"
+
+echo "$input_jump_relocs" | grep -q klp_test_key ||
+	fail "fixture produced no __jump_table reference to the key"
+echo "$input_jump_relocs" | grep -qE '\.(bss|data)\.klp_test_key' ||
+	probe_skip "compiler referenced the static key by name, not through its section"
+
+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 file-local static branch key rejected"
merge bot Applied
#136 lore raw

[tip: objtool/core] objtool/klp: Test a hand-built livepatch module's 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:     57569598499ee6fda7b5e1fd8c2e9b02b91c0636
Gitweb:        https://git.kernel.org/tip/57569598499ee6fda7b5e1fd8c2e9b02b91c0636
Author:        Song Liu <[email protected]>
AuthorDate:    Wed, 16 Sep 2026 11:43:37 -07:00
Committer:     Josh Poimboeuf <[email protected]>
CommitterDate: Wed, 16 Sep 2026 17:21:45 -07:00

objtool/klp: Test a hand-built livepatch module's static call keys

__SCK__* static call keys are not exported; modules are given read-only access at load time. Livepatch modules built by klp-build do have full access to theirs, and commit 164c9201e1da ("objtool: Add base objtool support for livepatch modules") added a check on that basis -- but a livepatch module can also be written by hand, as everything under samples/livepatch is, and such a module hits an unexported key as soon as it does anything expanding to a static call. With CONFIG_MEM_ALLOC_PROFILING_DEBUG that includes allocating memory, which is how livepatch-shadow-fix1 came to fail to build.

Cover it, with the plain module as a control: it takes the same path and has always been accepted, so a test that built only the livepatch variant could not tell this fix from the check being deleted.

This is objtool's ordinary check pass rather than a klp subcommand, which is the first test here to exercise it -- and is the point, since that pass is what runs over a hand-built livepatch module during a normal kernel build.

Verified by reverting commit f495054bd12e ("objtool/klp: Fix unexported static call key access for manually built livepatch modules"): objtool reports "can't find static_call_key symbol: __SCK__klp_test_call" and the test fails, under both gcc and clang.

Assisted-by Claude:claude-opus-4
Assisted-by Claude:claude-opus-5
---
 tools/objtool/tests/x86/fixtures/static_call_no_key.c  | 32 +++++++-
 tools/objtool/tests/x86/test-manual-klp-static-call.sh | 40 +++++++++-
 2 files changed, 72 insertions(+)
 create mode 100644 tools/objtool/tests/x86/fixtures/static_call_no_key.c
 create mode 100755 tools/objtool/tests/x86/test-manual-klp-static-call.sh
tools/objtool/tests/x86/fixtures/static_call_no_key.c new file +32 -0
new file mode 100644
index 0000000..748ba7c
@@ -0,0 +1,32 @@
+// SPDX-License-Identifier: GPL-2.0
+/*
+ * A static call to a trampoline whose key symbol this object cannot see.
+ *
+ * That is the normal situation for a module: __SCK__* keys are not exported,
+ * and read-only access is granted at load time instead.  objtool's static call
+ * handling has to accept it for any module, including a livepatch module built
+ * by hand rather than by klp-build.
+ *
+ * LIVEPATCH adds the .modinfo tag which makes objtool treat this as a
+ * livepatch module.
+ */
+
+static const char __modinfo[]
+	__attribute__((section(".modinfo"), used, aligned(1))) =
+#ifdef LIVEPATCH
+	"\0livepatch=Y"
+#endif
+	"\0name=klp_testmod";
+
+/*
+ * The trampoline is undefined here, exactly as it is for a module calling a
+ * static call defined in vmlinux.  No __SCK__klp_test_call accompanies it.
+ */
+extern void __SCT__klp_test_call(void);
+
+int target(int x)
+{
+	__asm__ volatile("call __SCT__klp_test_call\n\t" ::: "memory");
+
+	return x + 1;
+}
tools/objtool/tests/x86/test-manual-klp-static-call.sh new file +40 -0
new file mode 100755
index 0000000..6c4d275
@@ -0,0 +1,40 @@
+#!/bin/bash
+# SPDX-License-Identifier: GPL-2.0
+#
+# objtool's static call handling must accept a livepatch module which cannot
+# see a static call's key symbol.
+#
+# __SCK__* keys are not exported; modules get read-only access at load time
+# instead.  Livepatch modules built by klp-build do have full access to their
+# keys, and a check was added on the strength of that -- but a livepatch module
+# can also be written by hand, and samples/livepatch is full of them.  One of
+# those needs a key it cannot see as soon as it does anything that expands to a
+# static call, which with CONFIG_MEM_ALLOC_PROFILING_DEBUG includes allocating
+# memory:
+#
+#   samples/livepatch/livepatch-shadow-fix1.o: error: objtool: static_call:
+#     can't find static_call_key symbol: __SCK__WARN_trap
+#
+# The module built without the livepatch tag is the control: it takes the same
+# path and has always been accepted, so a test which only built the livepatch
+# one could not tell this fix from the check being removed altogether.
+#
+# Fixed by f495054bd12e ("objtool/klp: Fix unexported static call key access
+# for manually built livepatch modules").
+
+. "$(dirname "$0")/../lib.sh"
+
+setup
+
+# Not a klp subcommand: this is objtool's ordinary check pass, which is what
+# runs over a hand-built livepatch module during a normal kernel build.
+for tag in "" -DLIVEPATCH; do
+	build_one static_call_no_key.c mod.o $tag
+
+	"$OBJTOOL" --module --static-call "$workdir/mod.o" \
+		> "$workdir/objtool.log" 2>&1 ||
+		fail "objtool rejected a ${tag:+livepatch }module which cannot" \
+		     "see its static call key: $(tail -1 "$workdir/objtool.log")"
+done
+
+pass "livepatch module accepted without access to its static call key"
merge bot Applied
#128 lore raw

[tip: objtool/core] objtool/klp: Add test for symbols whose linkage the patch changes

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

objtool/klp: Add test for symbols whose linkage the patch changes

A patch can move a symbol between static and global without renaming it:
dropping "static" from a helper so something else can call it, or adding it to one that is no longer shared. Correlation keys off more than the name, so a symbol whose binding moved has to still pair with itself.

Failing to is not a build failure. The symbol looks new, and a new data symbol is either rejected or cloned as a second copy -- at which point the patched code updates its own private variable while the rest of the kernel keeps reading the original.

The test covers both directions in one fixture, a function going global and a variable going static, and asserts the outcome rather than the absence of a warning: each symbol resolves back to the kernel's copy through a klp symbol, and neither is cloned into the patch.

An earlier version asserted only that no "no correlation" or "changed data" message appeared, and passed with correlation deliberately broken. What the messages say and what the patch contains are not the same question.

Verified to fail with correlation made to require matching symbol bindings.

Assisted-by Claude:claude-opus-4
Assisted-by Claude:claude-opus-5
---
 tools/objtool/tests/generic/fixtures/local_to_global.c   | 34 ++++-
 tools/objtool/tests/generic/test-local-to-global-flip.sh | 63 +++++++-
 2 files changed, 97 insertions(+)
 create mode 100644 tools/objtool/tests/generic/fixtures/local_to_global.c
 create mode 100755 tools/objtool/tests/generic/test-local-to-global-flip.sh
tools/objtool/tests/generic/fixtures/local_to_global.c new file +34 -0
new file mode 100644
index 0000000..3c9eb92
@@ -0,0 +1,34 @@
+// SPDX-License-Identifier: GPL-2.0
+/*
+ * A function which the patch changes from static to non-static, and a variable
+ * that goes the other way.  The names are unchanged; only the binding moves.
+ */
+
+static const char __modinfo[]
+	__attribute__((section(".modinfo"), used, aligned(1))) = "\0name=vmlinux";
+
+/* noinline, or the static one is folded into its caller and has no symbol */
+#ifdef PATCHED
+__attribute__((noinline)) int flipped_up(int x)		/* was static */
+#else
+__attribute__((noinline)) static int flipped_up(int x)
+#endif
+{
+	return x + 1;
+}
+
+#ifdef PATCHED
+static volatile int flipped_down = 5;	/* was global */
+#else
+volatile int flipped_down = 5;
+#endif
+
+int caller(int x)
+{
+	flipped_down += x;
+#ifdef PATCHED
+	return flipped_up(x) + flipped_down + 2;
+#else
+	return flipped_up(x) + flipped_down + 1;
+#endif
+}
tools/objtool/tests/generic/test-local-to-global-flip.sh new file +63 -0

63 lines not on this page · raw message

merge bot Applied
#125 lore raw

[tip: objtool/core] objtool/klp: Add test for kCFI prefix symbols and traps

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

objtool/klp: Add test for kCFI prefix symbols and traps

Two properties, asserted separately because they fail differently:

- the __cfi_<func> prefix symbol has to be carried with the patched function, or the function has no type identity and indirect calls to it trap;
- its .kcfi_traps entry has to be extracted, or the trap is not recognised as a CFI failure and a clean report becomes an oops.

test-special-section hand-assembles a .kcfi_traps entry, which is what makes it catch commit 7df1638df97b ("objtool/klp: Fix .kcfi_traps special section extraction"). Nothing until now built real kCFI code.

This tests the behavior of commit da4326573ae8 ("objtool/klp: Fix kCFI trap handling"). Commit f7ceffd21a8a ("objtool/klp: Fix kCFI prefix finding/cloning") cannot be tested as such, its code having been rewritten by commit fe6a87e0abac ("objtool: Improve and simplify prefix symbol detection"); this guards the current implementation's behaviour instead.

Assisted-by Claude:claude-opus-4
Assisted-by Claude:claude-opus-5
---
 tools/objtool/tests/x86/fixtures/kcfi.c | 39 ++++++++++++++++++++++++-
 tools/objtool/tests/x86/test-kcfi.sh    | 39 ++++++++++++++++++++++++-
 2 files changed, 78 insertions(+)
 create mode 100644 tools/objtool/tests/x86/fixtures/kcfi.c
 create mode 100755 tools/objtool/tests/x86/test-kcfi.sh
tools/objtool/tests/x86/fixtures/kcfi.c new file +39 -0
new file mode 100644
index 0000000..b62fc60
@@ -0,0 +1,39 @@
+// SPDX-License-Identifier: GPL-2.0
+/*
+ * An indirect call, which under kCFI is preceded by a type check and a trap.
+ *
+ * Clang emits a __cfi_<func> prefix symbol carrying the type hash ahead of
+ * every address-taken function, and records the trap site in .kcfi_traps.
+ * Both belong to the function and both have to come with it into a patch.
+ *
+ * Needs -fsanitize=kcfi, which only Clang has.
+ */
+
+static const char __modinfo[]
+	__attribute__((section(".modinfo"), used, aligned(1))) = "\0name=vmlinux";
+
+static int impl_a(int x)
+{
+	return x + 1;
+}
+
+static int impl_b(int x)
+{
+	return x * 2;
+}
+
+__attribute__((noinline)) int (*pick(int x))(int)
+{
+	return (x & 1) ? impl_a : impl_b;
+}
+
+int target(int x)
+{
+	int (*fn)(int arg) = pick(x);
+
+#ifdef PATCHED
+	return fn(x) + 2;
+#else
+	return fn(x) + 1;
+#endif
+}
tools/objtool/tests/x86/test-kcfi.sh new file +39 -0
new file mode 100755
index 0000000..b583ef6
@@ -0,0 +1,39 @@
+#!/bin/bash
+# SPDX-License-Identifier: GPL-2.0
+#
+# Under kCFI an indirect call checks a type hash before jumping, and traps on a
+# mismatch.  Two things belong to the calling function and must come with it
+# into a patch:
+#
+#   - the __cfi_<func> prefix symbol holding the hash.  Lose it and the patched
+#     function has no type identity, so indirect calls to it trap.
+#   - its .kcfi_traps entry.  Lose that and the trap is not recognised as a
+#     CFI failure, so what should be a clean report becomes an oops.
+#
+# Neither shows up at build time.
+
+. "$(dirname "$0")/../lib.sh"
+
+clang_only "kCFI is a Clang feature"
+
+setup
+
+# Declared above that this is Clang's; a given Clang may still be too old.
+cc_supports -fsanitize=kcfi ||
+	probe_skip "this clang does not support -fsanitize=kcfi"
+
+build_pair kcfi.c -fsanitize=kcfi
+
+assert_input_section .kcfi_traps
+assert_input_symbol __cfi_target
+
+run_diff
+
+assert_patched target
+
+# The prefix symbol comes with its function ...
+assert_symbol __cfi_target
+# ... and so does the trap entry.
+assert_section .kcfi_traps
+
+pass "kCFI prefix symbol and trap entry carried with the patched function"
merge bot Applied
#122 lore raw

[tip: objtool/core] objtool/klp: Add test for __bug_table, __ex_table and __mcount_loc 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:     a441250d9e6192b89f20c26498c06d9722317977
Gitweb:        https://git.kernel.org/tip/a441250d9e6192b89f20c26498c06d9722317977
Author:        Song Liu <[email protected]>
AuthorDate:    Wed, 16 Sep 2026 11:43:33 -07:00
Committer:     Josh Poimboeuf <[email protected]>
CommitterDate: Wed, 16 Sep 2026 17:21:45 -07:00

objtool/klp: Add test for __bug_table, __ex_table and __mcount_loc extraction

Three special sections with no coverage. An entry that is not carried into the patch is not a build failure: the patched function simply loses its WARN_ON location, its exception fixup, or its ftrace callsite, and nobody finds out until one of them is needed.

Assisted-by Claude:claude-opus-4
Assisted-by Claude:claude-opus-5
---
 tools/objtool/tests/x86/fixtures/special_sections.c | 77 ++++++++++++-
 tools/objtool/tests/x86/test-special-sections.sh    | 42 +++++++-
 2 files changed, 119 insertions(+)
 create mode 100644 tools/objtool/tests/x86/fixtures/special_sections.c
 create mode 100755 tools/objtool/tests/x86/test-special-sections.sh
tools/objtool/tests/x86/fixtures/special_sections.c new file +77 -0
new file mode 100644
index 0000000..d427988
@@ -0,0 +1,77 @@
+// SPDX-License-Identifier: GPL-2.0
+/*
+ * A special section entry belonging to a patched function.  SPECIAL_SEC picks
+ * which section, since klp diff treats eight of them alike and each needs
+ * extracting for the patched function and no other.
+ *
+ * The entry is written out by hand so the fixture builds without kernel
+ * headers.  Only the leading relocation matters to klp diff; the rest is
+ * padded to the section's real entry size, because the entries have to be the
+ * right length for the boundaries between them to fall in the right places.
+ *
+ * SPECIAL_RELOCS covers __ex_table, whose entries relocate both the faulting
+ * instruction and its fixup; objtool rejects one with only the first.
+ */
+
+#ifndef SPECIAL_SEC
+#define SPECIAL_SEC "__bug_table"
+#endif
+#ifndef SPECIAL_ENTSIZE
+#define SPECIAL_ENTSIZE 12
+#endif
+#ifndef SPECIAL_RELOCS
+#define SPECIAL_RELOCS 1
+#endif
+
+#define STR_(x) #x
+#define STR(x) STR_(x)
+
+static const char __modinfo[]
+	__attribute__((section(".modinfo"), used, aligned(1))) = "\0name=vmlinux";
+
+/*
+ * other() gets an entry of its own, so that "the untouched function's entry
+ * was not dragged in" is a question the section can actually answer.  With
+ * only target() contributing, there is nothing for klp diff to leave behind
+ * and the negative assertion holds however the extraction behaves.
+ */
+int other(int x)
+{
+	asm volatile(
+		"3:	nop\n\t"
+		"4:\n\t"
+		".pushsection " SPECIAL_SEC ", \"aM\", @progbits, "
+			STR(SPECIAL_ENTSIZE) "\n\t"
+		".long 3b - .\n\t"
+#if SPECIAL_RELOCS > 1
+		".long 4b - .\n\t"
+		".fill " STR(SPECIAL_ENTSIZE) " - 8, 1, 0\n\t"
+#else
+		".fill " STR(SPECIAL_ENTSIZE) " - 4, 1, 0\n\t"
+#endif
+		".popsection\n\t");
+
+	return x + 9;
+}
+
+int target(int x)
+{
+	asm volatile(
+		"1:	nop\n\t"
+		"2:\n\t"
+		".pushsection " SPECIAL_SEC ", \"aM\", @progbits, "
+			STR(SPECIAL_ENTSIZE) "\n\t"
+		".long 1b - .\n\t"
+#if SPECIAL_RELOCS > 1
+		".long 2b - .\n\t"
+		".fill " STR(SPECIAL_ENTSIZE) " - 8, 1, 0\n\t"
+#else
+		".fill " STR(SPECIAL_ENTSIZE) " - 4, 1, 0\n\t"
+#endif
+		".popsection\n\t");
+#ifdef PATCHED
+	return x + 2;
+#else
+	return x + 1;
+#endif
+}
tools/objtool/tests/x86/test-special-sections.sh new file +42 -0

42 lines not on this page · raw message

merge bot Applied
#119 lore raw

[tip: objtool/core] objtool/klp: Add test for static locals which must not be correlated

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

objtool/klp: Add test for static locals which must not be correlated

Most static locals have to be correlated so the patched code keeps using the running kernel's copy. Two kinds must not: anything in .data..once, the flag behind WARN_ONCE and friends, and the well-known names the kernel generates for per-instance things (__warned, __key, __func__).

Sharing a .data..once flag means a patch inherits "already warned" from before it was applied, and the warning it was meant to surface never fires.

The fixture deliberately does not name its .data..once variable __warned:
the name rule would then catch it and the section rule would go untested. gcc spells these <var>.<id> and Clang <func>.<var>, so both are covered.

This tests the behavior of commit ff529864e738 ("objtool/klp: Fix .data..once static local non-correlation") and commit 84c304a534b8 ("objtool/klp: Fix is_uncorrelated_static_local() for Clang").

Assisted-by Claude:claude-opus-4
Assisted-by Claude:claude-opus-5
---
 tools/objtool/tests/generic/fixtures/static_local_uncorrelated.c | 41 +++++++++++++++++++++++++++++++++++++++++
 tools/objtool/tests/generic/test-static-local-uncorrelated.sh    | 41 +++++++++++++++++++++++++++++++++++++++++
 2 files changed, 82 insertions(+)
 create mode 100644 tools/objtool/tests/generic/fixtures/static_local_uncorrelated.c
 create mode 100755 tools/objtool/tests/generic/test-static-local-uncorrelated.sh
tools/objtool/tests/generic/fixtures/static_local_uncorrelated.c new file +41 -0
new file mode 100644
index 0000000..cb4cdd7
@@ -0,0 +1,41 @@
+// SPDX-License-Identifier: GPL-2.0
+/*
+ * Static locals of three kinds, in one patched function.
+ *
+ * Most static locals must be correlated, so the patched code keeps using the
+ * running kernel's copy.  Two kinds must not:
+ *
+ *   - anything in .data..once, the flag behind WARN_ONCE and friends.  Sharing
+ *     it would mean a patch inherits "already warned" from before the patch.
+ *   - the well-known names the kernel generates for such things (__warned,
+ *     __key, __func__, ...), which are per-instance by nature.  gcc names them
+ *     <var>.<id> and Clang <func>.<var>, so both spellings have to be caught.
+ */
+
+static const char __modinfo[]
+	__attribute__((section(".modinfo"), used, aligned(1))) = "\0name=vmlinux";
+
+int target(int x)
+{
+	/*
+	 * A .data..once variable whose name is *not* on the list below, so
+	 * only the section can disqualify it.  Naming it __warned would let
+	 * the name rule catch it and the section rule go untested.
+	 */
+	static int once_flag __attribute__((section(".data..once")));
+	/* a never-correlate name, in an ordinary section */
+	static int __key;
+	/* and one that must be correlated */
+	static int ordinary;
+
+	if (!once_flag)
+		once_flag = 1;
+	__key += x;
+	ordinary += x;
+
+#ifdef PATCHED
+	return __key + ordinary + once_flag + 2;
+#else
+	return __key + ordinary + once_flag + 1;
+#endif
+}
tools/objtool/tests/generic/test-static-local-uncorrelated.sh new file +41 -0

41 lines not on this page · raw message

merge bot Applied
#116 lore raw

[tip: objtool/core] objtool/klp: Add test for sympos resolved against a linked vmlinux

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

objtool/klp: Add test for sympos resolved against a linked vmlinux

vmlinux is not like a module: the final link reorders sub-sections, so a symbol's position has to come from the linked image rather than from symbol table order. klp diff bridges that with .klp.symid, and looks for it only when the object it was handed is called vmlinux.o with a vmlinux beside it.

This was assigned to an end-to-end test on the assumption that it needs a real kernel build. It needs "ld -r" and "ld -e 0", and takes a fraction of a second.

The fixture places the static appearing first in the symbol table at the higher address, and the link passes --sort-section=name to force the reordering the kernel's linker script performs. Without that the two ways of computing sympos agree, and a first version passed with the vmlinux path disabled.

Assisted-by Claude:claude-opus-4
Assisted-by Claude:claude-opus-5
---
 tools/objtool/tests/generic/fixtures/sympos_vmlinux.c | 40 +++++++-
 tools/objtool/tests/generic/test-sympos-vmlinux.sh    | 57 ++++++++++-
 2 files changed, 97 insertions(+)
 create mode 100644 tools/objtool/tests/generic/fixtures/sympos_vmlinux.c
 create mode 100755 tools/objtool/tests/generic/test-sympos-vmlinux.sh
tools/objtool/tests/generic/fixtures/sympos_vmlinux.c new file +40 -0
new file mode 100644
index 0000000..d5e7099
@@ -0,0 +1,40 @@
+// SPDX-License-Identifier: GPL-2.0
+/*
+ * Two translation units with a same-named static, placed so that the linker
+ * puts them in the opposite order to the one they appear in the symbol table.
+ *
+ * VARSEC selects the section the static lands in.  Linking with
+ * --sort-section=name then orders them alphabetically rather than by object
+ * order, so the first symbol in the symbol table ends up at the *higher*
+ * address.  That is the whole point: counting symbol table order and reading
+ * the linked image's addresses now give different answers, which is what makes
+ * it possible to tell which one klp diff used.
+ *
+ * Only use_a is patched, so exactly one sympos is emitted and there is nothing
+ * to attribute.
+ */
+
+#ifndef FUNC_NAME
+#define FUNC_NAME use_a
+#endif
+#ifndef VARSEC
+#define VARSEC ".data.mmm"
+#endif
+
+#ifndef NO_MODINFO
+static const char __modinfo[]
+	__attribute__((section(".modinfo"), used, aligned(1))) = "\0name=vmlinux";
+#endif
+
+/* volatile so it survives as an STT_OBJECT rather than being folded away */
+static volatile int dup_counter __attribute__((section(VARSEC))) = 1;
+
+int FUNC_NAME(int x)
+{
+	dup_counter += x;
+#ifdef PATCHED
+	return dup_counter + 1;
+#else
+	return dup_counter;
+#endif
+}
tools/objtool/tests/generic/test-sympos-vmlinux.sh new file +57 -0

57 lines not on this page · raw message

merge bot Applied
#113 lore raw

[tip: objtool/core] objtool/klp: Add test for sympos 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:     4acb0ba0ac49da65d9031ab0c0a9427d66557ebd
Gitweb:        https://git.kernel.org/tip/4acb0ba0ac49da65d9031ab0c0a9427d66557ebd
Author:        Song Liu <[email protected]>
AuthorDate:    Wed, 16 Sep 2026 11:43:30 -07:00
Committer:     Josh Poimboeuf <[email protected]>
CommitterDate: Wed, 16 Sep 2026 17:21:44 -07:00

objtool/klp: Add test for sympos in module objects

klp-sympos.c had no coverage at all. sympos disambiguates same-named symbols for livepatch, counting from 1, with 0 meaning the name is unique. Resolving to the wrong one is not a load failure -- it is a patch quietly wired to the wrong object.

Covers the module path, where the position is a count in symbol table order and klp diff can work it out from the object alone.

Assisted-by Claude:claude-opus-4
Assisted-by Claude:claude-opus-5
---
 tools/objtool/tests/generic/fixtures/sympos_dup.c | 32 +++++++++-
 tools/objtool/tests/generic/test-sympos.sh        | 51 ++++++++++++++-
 2 files changed, 83 insertions(+)
 create mode 100644 tools/objtool/tests/generic/fixtures/sympos_dup.c
 create mode 100755 tools/objtool/tests/generic/test-sympos.sh
tools/objtool/tests/generic/fixtures/sympos_dup.c new file +32 -0
new file mode 100644
index 0000000..7eded9b
@@ -0,0 +1,32 @@
+// SPDX-License-Identifier: GPL-2.0
+/*
+ * A static whose name recurs in every translation unit that includes it.
+ * Compiled once for a single-copy object and twice, partially linked, for one
+ * with duplicates -- which is the only case where sympos is non-zero.
+ *
+ * FUNC_NAME keeps the referencing functions distinct so both get patched.
+ * Only the first copy carries .modinfo; two would be a second thing to
+ * disambiguate and is not what this fixture is about.
+ */
+
+#ifndef FUNC_NAME
+#define FUNC_NAME use_a
+#endif
+
+#ifndef NO_MODINFO
+static const char __modinfo[]
+	__attribute__((section(".modinfo"), used, aligned(1))) = "\0name=vmlinux";
+#endif
+
+/* volatile so it survives as an STT_OBJECT rather than being folded away */
+static volatile int dup_counter = 1;
+
+int FUNC_NAME(int x)
+{
+	dup_counter += x;
+#ifdef PATCHED
+	return dup_counter + 1;
+#else
+	return dup_counter;
+#endif
+}
tools/objtool/tests/generic/test-sympos.sh new file +51 -0

51 lines not on this page · raw message

merge bot Applied
#110 lore raw

[tip: objtool/core] objtool/klp: Add test for position-independent checksums

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

objtool/klp: Add test for position-independent checksums

A function that only moves has not changed, and its checksum must not move with it. Otherwise every patch reports as changed everything that shifted because something ahead of it grew.

The fixture is built with -fno-function-sections, overriding the harness
default: with per-function sections every function sits at offset 0 of its own section and nothing ever moves, so the test would prove nothing. It also calls across to another function rather than looping within itself -- a loop branch keeps the same displacement wherever the function goes, so it is not position-dependent to begin with.

This tests the behavior of commit cca84cb12908 ("objtool/klp: Fix position-dependent checksums for non-relocated jumps/calls").

Assisted-by Claude:claude-opus-4
Assisted-by Claude:claude-opus-5
---
 tools/objtool/tests/generic/fixtures/checksum_position.c | 42 ++++++-
 tools/objtool/tests/generic/test-checksum-position.sh    | 51 +++++++-
 2 files changed, 93 insertions(+)
 create mode 100644 tools/objtool/tests/generic/fixtures/checksum_position.c
 create mode 100755 tools/objtool/tests/generic/test-checksum-position.sh
tools/objtool/tests/generic/fixtures/checksum_position.c new file +42 -0
new file mode 100644
index 0000000..4320bc2
@@ -0,0 +1,42 @@
+// SPDX-License-Identifier: GPL-2.0
+/*
+ * A function whose position in the section changes between the two builds,
+ * without the function itself changing.
+ *
+ * target() calls callee() twice, and a call within the same section needs no
+ * relocation: the displacement is in the instruction.  It is that displacement
+ * which moves, and hashing those bytes makes the checksum move with it.  Both
+ * must therefore share a section, which is why the test passes
+ * -fno-function-sections.
+ *
+ * What has to change is the distance between the two, and PATCHED changes it
+ * by aligning them rather than by inserting a function between them.  Where a
+ * compiler puts an added function is its own business: gcc emits these in
+ * source order, so a function written between callee() and target() separates
+ * them, but clang emits target() immediately before callee() whatever the
+ * source says, and an added function lands ahead of both.  That moves target()
+ * without moving it relative to callee(), the displacement comes out identical
+ * in both builds, and the test passes without having asked anything.
+ *
+ * Alignment moves the functions apart on both, and moves neither function's
+ * own instructions -- which is exactly the distinction under test.
+ */
+
+#ifdef PATCHED
+#define MOVED	__attribute__((aligned(64)))
+#else
+#define MOVED
+#endif
+
+static const char __modinfo[]
+	__attribute__((section(".modinfo"), used, aligned(1))) = "\0name=vmlinux";
+
+__attribute__((noinline)) MOVED static int callee(int x)
+{
+	return x * 5 + 1;
+}
+
+__attribute__((noinline)) MOVED int target(int x)
+{
+	return callee(x) + callee(x + 1);
+}
tools/objtool/tests/generic/test-checksum-position.sh new file +51 -0

51 lines not on this page · raw message

merge bot Applied
#104 lore raw

[tip: objtool/core] objtool/klp: Add test for recorded checksum values

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

objtool/klp: Add test for recorded checksum values

Whether klp diff treats a function as changed is decided by its checksum, and until now nothing looked at one. A test asserting only that the right functions were cloned cannot tell a correct checksum from one that happens to differ.

Asserts both directions -- the changed function's checksum moves, the untouched one's does not -- and that checksumming identical input twice gives the same answer, since otherwise every rebuild reports spurious changes.

Assisted-by Claude:claude-opus-4
Assisted-by Claude:claude-opus-5
---
 tools/objtool/tests/generic/test-checksum-value.sh | 37 +++++++++++++-
 1 file changed, 37 insertions(+)
 create mode 100755 tools/objtool/tests/generic/test-checksum-value.sh
tools/objtool/tests/generic/test-checksum-value.sh new file +37 -0
new file mode 100755
index 0000000..feae6a1
@@ -0,0 +1,37 @@
+#!/bin/bash
+# SPDX-License-Identifier: GPL-2.0
+#
+# The per-function checksums klp checksum records are what klp diff uses to
+# decide which functions changed.  A checksum covering too little misses a real
+# change and the patch silently omits the function; one covering too much, or
+# unstable across identical input, clones functions nobody patched and drags
+# their dependencies in with them.
+#
+# test-basic covers which functions got cloned, which is downstream of this and
+# passes for either kind of wrong checksum as long as the two errors do not
+# happen to cancel.  This checks the checksums themselves.
+
+. "$(dirname "$0")/../lib.sh"
+
+setup
+build_pair basic.c
+
+assert_input_symbol changed
+assert_input_symbol untouched
+
+run_checksum
+
+# The edited function's checksum has to move, the untouched one's must not.
+assert_checksum_differs changed
+assert_checksum_matches untouched
+
+# And it has to be a function of the code, not of the build: checksumming the
+# same input twice has to give the same answer, or every rebuild reports
+# spurious changes.
+first="$(checksum_of orig.o changed)"
+build_pair basic.c
+run_checksum
+[ "$(checksum_of orig.o changed)" = "$first" ] ||
+	fail "checksum for 'changed' differs between builds of identical source"
+
+pass "checksums track the changed function and are stable across rebuilds"
merge bot Applied
#101 lore raw

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

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:     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"
merge bot Applied
#98 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:     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
#92 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:     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
#95 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:     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
#89 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:     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
#86 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:     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
#83 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:     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
#80 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:     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
#77 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:     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
#74 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:     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
#71 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:     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
#68 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:     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
#65 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:     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
#62 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:     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
#59 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:     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
#56 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:     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
#53 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:     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
#50 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:     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
#47 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:     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
#38 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:     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
#41 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:     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
#44 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:     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
#35 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:     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
#32 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:     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
#29 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:     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
#23 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:     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
#26 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:     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
#20 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:     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 ]