Skip to contentSkip to conversation

livepatch: Fail object initialization on duplicate patched function

PATCH In review Petr Mladek 4 participants 27 messages Sep 8 – Oct 30

Subsystems (2)
lore
Share & tools
lore

Petr Mladek

author maintainer
#0 lore raw

v4 cover livepatch: Fail object initialization on duplicate patched function

This is v4 of the patch failing object initialization when it patches the same underlying function twice through two aliased symbols (functions sharing one address) in the same object.

Changes against [v3]:

+ Add selftest for livepatching aliased symbols [Song, Harry]

+ Only partially revert relocations when failing inside klp_apply_object_relocs() [Sashiko]

+ Cleanup changes made by klp_init_object_loaded() for failing patch on another failures in klp_module_coming() [Sashiko]

Changes against [v2]:

+ Clarify comments and the commit message [Miroslav]

+ Cleanup when klp_init_object_loaded() fails [Sashiko]

[v2] https://lore.kernel.org/r/[email protected]
[v3] https://lore.kernel.org/r/[email protected]

Harry Hsu (2):
livepatch: Fail object initialization on duplicate patched function selftests/livepatch: Test rejection of aliased symbols in one object

Petr Mladek (3):
livepatch: Move code for updating livepatch object relocations
livepatch: Clear relocations when klp_apply_object_relocs() fails
livepatch: Clean up klp_init_object_loaded() when fails

 kernel/livepatch/core.c                       | 137 ++++++++++++------
 tools/testing/selftests/livepatch/Makefile    |   3 +-
 .../testing/selftests/livepatch/test-alias.sh |  81 +++++++++++
 .../selftests/livepatch/test_modules/Makefile |   4 +-
 .../test_modules/test_klp_alias_patch.c       |  62 ++++++++
 .../test_modules/test_klp_alias_target.c      |  48 ++++++
 6 files changed, 285 insertions(+), 50 deletions(-)
 create mode 100755 tools/testing/selftests/livepatch/test-alias.sh
 create mode 100644 tools/testing/selftests/livepatch/test_modules/test_klp_alias_patch.c
 create mode 100644 tools/testing/selftests/livepatch/test_modules/test_klp_alias_target.c
Signature · 1 line
2.55.0
author maintainer
#1 lore raw

PATCH v4 1/5 livepatch: Fail object initialization on duplicate patched function

From: Harry Hsu <[email protected]>

Several symbols can share one address:

ffffffff8ed7fef0 t __do_sys_fork
ffffffff8ed7fef0 T __ia32_sys_fork
ffffffff8ed7fef0 T __x64_sys_fork

klp_find_ops() looks the ops up by func->old_func, i.e. by address, so two klp_funcs of the same livepatch naming two of these symbols resolve to the same klp_ops and are both pushed onto one ops->func_stack.

This breaks the assumption that a single livepatch contributes at most one entry to any func_stack. klp_ftrace_handler() picks the entry at the top of the stack, but when both entries belong to the same livepatch there is nothing that says which of them should be used in the PATCHED state, and the UNPATCHED state has to end up at the original function either way. klp_check_stack_func() cannot tell them apart either: it asks whether the preceding entry is the original function or another livepatch's replacement, and an aliased sibling is neither.

Patching two aliases of one function from a single livepatch was never meaningful, so fail object initialization in klp_init_object_loaded() rather than leave the redirection undefined.

Fixes 3c33f5b99d68 ("livepatch: support for repatching a function")
---
 kernel/livepatch/core.c | 17 ++++++++++++++++-
 1 file changed, 16 insertions(+), 1 deletion(-)
kernel/livepatch/core.c +16 -1
index a240d1144e89..a6762cbe74b7 100644
@@ -863,7 +863,7 @@ static void klp_clear_object_relocs(struct klp_patch *patch,
 static int klp_init_object_loaded(struct klp_patch *patch,
 				  struct klp_object *obj)
 {
-	struct klp_func *func;
+	struct klp_func *func, *prev_func;
 	int ret;
 
 	if (klp_is_module(obj)) {
@@ -885,6 +885,21 @@ static int klp_init_object_loaded(struct klp_patch *patch,
 		if (ret)
 			return ret;
 
+		/*
+		 * Aliased symbols share one address, so they would resolve to
+		 * the same klp_ops and stack up on a single ops->func_stack,
+		 * leaving the redirection ambiguous.
+		 */
+		klp_for_each_func(obj, prev_func) {
+			if (prev_func == func)
+				break;
+			if (prev_func->old_func == func->old_func) {
+				pr_err("'%s' and '%s' resolve to the same address, aliased symbols are not supported\n",
+				       prev_func->old_name, func->old_name);
+				return -EINVAL;
+			}
+		}
+
 		ret = kallsyms_lookup_size_offset((unsigned long)func->old_func,
 						  &func->old_size, NULL);
 		if (!ret) {
Signature · 1 line
2.55.0
#2 lore raw
Thank you for your contribution! Sashiko AI review found 1 potential issue(s) to consider: - [High] Atomic replace patches will fail to load if previous patches targeted aliased functions. --

Thank you for your contribution! Sashiko AI review found 1 potential issue(s) to consider:
- [High] Atomic replace patches will fail to load if previous patches targeted aliased functions. --

commit e5553650270f93e11fe885d264a3829802223d3a
Author: Harry Hsu <[email protected]>

livepatch: Fail object initialization on duplicate patched function

This commit introduces a check to prevent patching multiple aliases of a function within a single livepatch. It fails object initialization if aliases resolving to the same address are detected.

Quoted 4 lines
kernel/livepatch/core.c +0 -0
index a240d1144e89c..a6762cbe74b70 100644

[ ... ]

Quoted 6 lines
kernel/livepatch/core.c +2 -0
@@ -885,6 +885,21 @@ static int klp_init_object_loaded(struct klp_patch *patch,
 		if (ret)
 			return ret;
 
+		/*
+		 * Aliased symbols share one address, so they would resolve to

kernel/livepatch/core.c static int klp_init_object_loaded(struct klp_patch *patch, · line 899

Quoted 10 lines
kernel/livepatch/core.c +10 -0
+		 * the same klp_ops and stack up on a single ops->func_stack,
+		 * leaving the redirection ambiguous.
+		 */
+		klp_for_each_func(obj, prev_func) {
+			if (prev_func == func)
+				break;
+			if (prev_func->old_func == func->old_func) {
+				pr_err("'%s' and '%s' resolve to the same address, aliased symbols are not supported\n",
+				       prev_func->old_name, func->old_name);
+				return -EINVAL;

[Severity: High]
Will this check inadvertently reject nop functions generated by an atomic replace patch when previous patches targeted aliased functions?

If previously loaded livepatches targeted aliased functions (for example, one patch targets __do_sys_fork and another targets __x64_sys_fork), they were permitted since they resided in different patches.

When an atomic replace patch is loaded, klp_add_nops() loops over all previously patched functions and adds nops for them to the new patch. Since nop deduplication is based on old_name, nops for both aliases are added.

Later, this check in klp_init_object_loaded() resolves their addresses and finds duplicate old_func addresses. This causes the initialization to fail with -EINVAL, which prevents the system from atomically replacing existing livepatches and might force a reboot if the old patches cannot be safely disabled manually.

Quoted 4 lines
kernel/livepatch/core.c +3 -0
+			}
+		}
+
 		ret = kallsyms_lookup_size_offset((unsigned long)func->old_func,
Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=1
author maintainer
#3 lore raw
Quoted 47 lines · On Tue 2026-09-08 12:17:44, [email protected] wrote:

Thank you for your contribution! Sashiko AI review found 1 potential issue(s) to consider:
- [High] Atomic replace patches will fail to load if previous patches targeted aliased functions. --

commit e5553650270f93e11fe885d264a3829802223d3a
Author: Harry Hsu <[email protected]>

livepatch: Fail object initialization on duplicate patched function

This commit introduces a check to prevent patching multiple aliases of a function within a single livepatch. It fails object initialization if aliases resolving to the same address are detected.

Quoted 4 lines
kernel/livepatch/core.c +0 -0
index a240d1144e89c..a6762cbe74b70 100644

[ ... ]

Quoted 6 lines
kernel/livepatch/core.c +2 -0
@@ -885,6 +885,21 @@ static int klp_init_object_loaded(struct klp_patch *patch,
 		if (ret)
 			return ret;
 
+		/*
+		 * Aliased symbols share one address, so they would resolve to

kernel/livepatch/core.c static int klp_init_object_loaded(struct klp_patch *patch, · line 899

Quoted 10 lines
kernel/livepatch/core.c +10 -0
+		 * the same klp_ops and stack up on a single ops->func_stack,
+		 * leaving the redirection ambiguous.
+		 */
+		klp_for_each_func(obj, prev_func) {
+			if (prev_func == func)
+				break;
+			if (prev_func->old_func == func->old_func) {
+				pr_err("'%s' and '%s' resolve to the same address, aliased symbols are not supported\n",
+				       prev_func->old_name, func->old_name);
+				return -EINVAL;

[Severity: High]
Will this check inadvertently reject nop functions generated by an atomic replace patch when previous patches targeted aliased functions?

If previously loaded livepatches targeted aliased functions (for example, one patch targets __do_sys_fork and another targets __x64_sys_fork), they were permitted since they resided in different patches.

When an atomic replace patch is loaded, klp_add_nops() loops over all previously patched functions and adds nops for them to the new patch. Since nop deduplication is based on old_name, nops for both aliases are added.

Quoted 5 lines

Later, this check in klp_init_object_loaded() resolves their addresses and finds duplicate old_func addresses. This causes the initialization to fail with -EINVAL, which prevents the system from atomically replacing existing livepatches and might force a reboot if the old patches cannot be safely disabled manually.

Wow, this is a nice catch. I would say that it is a corner case but the problem seems to exist. Now, the question is how to deal with it.

I see three possibilities:

1. We might detect the aliases in klp_find_func() and create only one "nop" entry or do not create it all.

2. The problem might be easier to solve after adding the provides/obsoletes, aka replace set, feature [1]. It should prevent loading the other livepatch for the aliased symbol in the 1st place.

3. Just document the problem as a limitation. It might be hit only when installing more liveapatches in parallel that current wild way.

I personally prefer to wait for the provides/requires feature.

[1] https://lore.kernel.org/all/[email protected]/

Best Regards,
Petr

Quoted 7 lines
Quoted 4 lines
kernel/livepatch/core.c +3 -0
+			}
+		}
+
 		ret = kallsyms_lookup_size_offset((unsigned long)func->old_func,
Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=1
maintainer
#4 lore raw
Quoted 67 lines · Petr Mladek
Quoted 47 lines · On Tue 2026-09-08 12:17:44, [email protected] wrote:

Thank you for your contribution! Sashiko AI review found 1 potential issue(s) to consider:
- [High] Atomic replace patches will fail to load if previous patches targeted aliased functions. --

commit e5553650270f93e11fe885d264a3829802223d3a
Author: Harry Hsu <[email protected]>

livepatch: Fail object initialization on duplicate patched function

This commit introduces a check to prevent patching multiple aliases of a function within a single livepatch. It fails object initialization if aliases resolving to the same address are detected.

Quoted 4 lines
kernel/livepatch/core.c +0 -0
index a240d1144e89c..a6762cbe74b70 100644

[ ... ]

Quoted 6 lines
kernel/livepatch/core.c +2 -0
@@ -885,6 +885,21 @@ static int klp_init_object_loaded(struct klp_patch *patch,
 		if (ret)
 			return ret;
 
+		/*
+		 * Aliased symbols share one address, so they would resolve to

kernel/livepatch/core.c static int klp_init_object_loaded(struct klp_patch *patch, · line 899

Quoted 10 lines
kernel/livepatch/core.c +10 -0
+		 * the same klp_ops and stack up on a single ops->func_stack,
+		 * leaving the redirection ambiguous.
+		 */
+		klp_for_each_func(obj, prev_func) {
+			if (prev_func == func)
+				break;
+			if (prev_func->old_func == func->old_func) {
+				pr_err("'%s' and '%s' resolve to the same address, aliased symbols are not supported\n",
+				       prev_func->old_name, func->old_name);
+				return -EINVAL;

[Severity: High]
Will this check inadvertently reject nop functions generated by an atomic replace patch when previous patches targeted aliased functions?

If previously loaded livepatches targeted aliased functions (for example, one patch targets __do_sys_fork and another targets __x64_sys_fork), they were permitted since they resided in different patches.

When an atomic replace patch is loaded, klp_add_nops() loops over all previously patched functions and adds nops for them to the new patch. Since nop deduplication is based on old_name, nops for both aliases are added.

Quoted 5 lines

Later, this check in klp_init_object_loaded() resolves their addresses and finds duplicate old_func addresses. This causes the initialization to fail with -EINVAL, which prevents the system from atomically replacing existing livepatches and might force a reboot if the old patches cannot be safely disabled manually.

Wow, this is a nice catch. I would say that it is a corner case but the problem seems to exist. Now, the question is how to deal with it.

I see three possibilities:

1. We might detect the aliases in klp_find_func() and create only one "nop" entry or do not create it all.

2. The problem might be easier to solve after adding the provides/obsoletes, aka replace set, feature [1]. It should prevent loading the other livepatch for the aliased symbol in the 1st place.

Quoted 5 lines

3. Just document the problem as a limitation. It might be hit only when installing more liveapatches in parallel that current wild way.

I personally prefer to wait for the provides/requires feature.

Perhaps.

Could we also check prev_func/func->nop in the check in klp_init_object_loaded() and have a pass if true?

Miroslav

#5 lore raw

Thanks for catching this.

I've updated the duplicate-address check in klp_init_object_loaded() to only reject the pair when both klp_funcs are nops:

    if (prev_func->old_func == func->old_func) {
            if (prev_func->nop && func->nop)
                    continue;
            pr_err(...);
            return -EINVAL;
    }

nops added by klp_add_nops() for two replaced aliases are interchangeable. Both just fall through to the original function, so allowing that combination fixes exactly the scenario you described: an atomic replace patch that inherits nops for __do_sys_fork and __x64_sys_fork from two separate previous patches will now load fine.

The check still rejects two non-nop funcs that resolve to the same address, since that's still genuinely ambiguous. It also still rejects a non-nop func colliding with an auto-generated nop for its alias. klp_add_nops() always appends nops after the explicitly-listed funcs, and klp_patch_func() always pushes new entries onto the head of ops->func_stack, so allowing that combination would let the nop silently land on top and disable the real replacement instead of failing loudly.

Petr, do you have any further changes on your side for this series? And once this fix gets an Ack, would you like me to send v5, or would it be more convenient for you to fold my commit in and send it together with yours? Happy to go either way, just let me know what works best for you.

Harry

#6 lore raw
In reply to Miroslav Benes
Quoted 2 lines · Miroslav Benes

Could we also check prev_func/func->nop in the check in klp_init_object_loaded() and have a pass if true?

Thanks for the suggestion.

Yes, I've updated the check to skip the pair when both klp_funcs are nops. Two nops added by klp_add_nops() for replaced aliases are interchangeable, so an atomic replace patch that inherits nops for __do_sys_fork and __x64_sys_fork from two previous patches now loads fine. A non-nop func colliding with a nop (or another non-nop func) is still rejected, since the nop would land on top of the real replacement on ops->func_stack and silently disable it.

The incremental change on top of v4 1/5 is:

kernel/livepatch/core.c +2 -0
@@ -894,6 +894,8 @@ static int klp_init_object_loaded(struct klp_patch *patch,
 			if (prev_func == func)
 				break;
 			if (prev_func->old_func == func->old_func) {
+				if (prev_func->nop && func->nop)
+					continue;
 				pr_err("'%s' and '%s' resolve to the same address, aliased symbols are not supported\n",
 				       prev_func->old_name, func->old_name);
 				return -EINVAL;

If this direction looks good, I'll resend the series. Petr, should I just bundle everything into a v5, or do you have changes on your side that I should wait for?

P.S. Sorry for the second mail. I forgot to quote the message I was replying to in my first one.

Harry

author maintainer
#7 lore raw
Quoted 29 lines · Harry Hsu
Quoted 2 lines · Miroslav Benes

Could we also check prev_func/func->nop in the check in klp_init_object_loaded() and have a pass if true?

Thanks for the suggestion.

Yes, I've updated the check to skip the pair when both klp_funcs are nops. Two nops added by klp_add_nops() for replaced aliases are interchangeable, so an atomic replace patch that inherits nops for __do_sys_fork and __x64_sys_fork from two previous patches now loads fine. A non-nop func colliding with a nop (or another non-nop func) is still rejected, since the nop would land on top of the real replacement on ops->func_stack and silently disable it.

The incremental change on top of v4 1/5 is:

kernel/livepatch/core.c +2 -0
@@ -894,6 +894,8 @@ static int klp_init_object_loaded(struct klp_patch *patch,
 			if (prev_func == func)
 				break;
 			if (prev_func->old_func == func->old_func) {
+				if (prev_func->nop && func->nop)
+					continue;
 				pr_err("'%s' and '%s' resolve to the same address, aliased symbols are not supported\n",
 				       prev_func->old_name, func->old_name);
 				return -EINVAL;
Quoted 3 lines

If this direction looks good, I'll resend the series. Petr, should I just bundle everything into a v5, or do you have changes on your side that I should wait for?

I am afraid that this is still not enough.

Problem:

It would work when the livepatch gets applied the nops are removed.

But it might cause problems when the transition gets reverted in the middle. All processes should go back to use the previous implementations (original code or previous livepatch). But the ftrace handler would just go back from one nop to the other.

Solutions:

1. A solution would be to create only one not in the first place.

2. It seems that we are close to the scoped atomic replace feature. It will prevent loading conflicting livepatches in parallel. Well, it currently checks only the function names. We should add another another check which would detect the conflict also by the alias.

Best Regards,
Petr

PS: I am sorry for the late reply. This patchset is far from trivial
because it handles several levels of "what will happen if" and makes my head spin. And it has lower priority because it handles corner cases.

Also I always forget all the details before I get an answer. It seems that we are all in the same trap. ;-)

maintainer
#8 lore raw
Quoted 36 lines · Petr Mladek
Quoted 29 lines · Harry Hsu
Quoted 2 lines · Miroslav Benes

Could we also check prev_func/func->nop in the check in klp_init_object_loaded() and have a pass if true?

Thanks for the suggestion.

Yes, I've updated the check to skip the pair when both klp_funcs are nops. Two nops added by klp_add_nops() for replaced aliases are interchangeable, so an atomic replace patch that inherits nops for __do_sys_fork and __x64_sys_fork from two previous patches now loads fine. A non-nop func colliding with a nop (or another non-nop func) is still rejected, since the nop would land on top of the real replacement on ops->func_stack and silently disable it.

The incremental change on top of v4 1/5 is:

kernel/livepatch/core.c +2 -0
@@ -894,6 +894,8 @@ static int klp_init_object_loaded(struct klp_patch *patch,
 			if (prev_func == func)
 				break;
 			if (prev_func->old_func == func->old_func) {
+				if (prev_func->nop && func->nop)
+					continue;
 				pr_err("'%s' and '%s' resolve to the same address, aliased symbols are not supported\n",
 				       prev_func->old_name, func->old_name);
 				return -EINVAL;
Quoted 3 lines

If this direction looks good, I'll resend the series. Petr, should I just bundle everything into a v5, or do you have changes on your side that I should wait for?

I am afraid that this is still not enough.

Quoted 8 lines

Problem:

It would work when the livepatch gets applied the nops are removed.

But it might cause problems when the transition gets reverted in the middle. All processes should go back to use the previous implementations (original code or previous livepatch). But the ftrace handler would just go back from one nop to the other.

Hm, you are right. There will be two nop functions on the stack in this case and the redirection in the handler would not work.

Quoted 3 lines

Solutions:

1. A solution would be to create only one not in the first place.

Not a bad idea.

Quoted 5 lines

2. It seems that we are close to the scoped atomic replace feature. It will prevent loading conflicting livepatches in parallel. Well, it currently checks only the function names. We should add another another check which would detect the conflict also by the alias.

-ETOOMANYDEPENDENCIESBETWEENPATCHSETS. If the first solution is not difficult to implement, it might be better.

Quoted 7 lines

PS: I am sorry for the late reply. This patchset is far from trivial
because it handles several levels of "what will happen if" and makes my head spin. And it has lower priority because it handles corner cases.

Also I always forget all the details before I get an answer. It seems that we are all in the same trap. ;-)

Yes, it took me a while to page it all in again :).

Miroslav

author maintainer
#9 lore raw

PATCH v4 2/5 selftests/livepatch: Test rejection of aliased symbols in one object

In reply to Petr Mladek

From: Harry Hsu <[email protected]>

klp_init_object_loaded() now rejects an object whose klp_funcs resolve to the same address, because aliased symbols would push two klp_funcs of one livepatch onto a single ops->func_stack and leave the redirection ambiguous.

Add a target module providing test_klp_alias_show() together with its __alias() sibling, and a livepatch naming both of them. Two test cases cover both callers of klp_init_object_loaded(): the klp_enable_patch() path, where the target module is loaded before the livepatch, and the klp_module_coming() path, where the livepatch is loaded first and the module loader has to refuse the target module.

---
 tools/testing/selftests/livepatch/Makefile    |  3 +-
 .../testing/selftests/livepatch/test-alias.sh | 81 +++++++++++++++++++
 .../selftests/livepatch/test_modules/Makefile |  4 +-
 .../test_modules/test_klp_alias_patch.c       | 62 ++++++++++++++
 .../test_modules/test_klp_alias_target.c      | 48 +++++++++++
 5 files changed, 196 insertions(+), 2 deletions(-)
 create mode 100755 tools/testing/selftests/livepatch/test-alias.sh
 create mode 100644 tools/testing/selftests/livepatch/test_modules/test_klp_alias_patch.c
 create mode 100644 tools/testing/selftests/livepatch/test_modules/test_klp_alias_target.c
tools/testing/selftests/livepatch/Makefile +2 -1
index a080eb54a215..ddbeff4cb53d 100644
@@ -11,7 +11,8 @@ TEST_PROGS := \
 	test-ftrace.sh \
 	test-sysfs.sh \
 	test-syscall.sh \
-	test-kprobe.sh
+	test-kprobe.sh \
+	test-alias.sh
 
 TEST_FILES := settings
 
tools/testing/selftests/livepatch/test-alias.sh new file +81 -0

81 lines not on this page · raw message

tools/testing/selftests/livepatch/test_modules/Makefile +3 -1
index a13d398585dc..532403e2b5ff 100644
@@ -1,7 +1,9 @@
 TESTMODS_DIR := $(realpath $(dir $(abspath $(lastword $(MAKEFILE_LIST)))))
 KDIR ?= /lib/modules/$(shell uname -r)/build
 
-obj-m += test_klp_atomic_replace.o \
+obj-m += test_klp_alias_patch.o \
+	test_klp_alias_target.o \
+	test_klp_atomic_replace.o \
 	test_klp_callbacks_busy.o \
 	test_klp_callbacks_demo.o \
 	test_klp_callbacks_demo2.o \
tools/testing/selftests/livepatch/test_modules/test_klp_alias_patch.c new file +62 -0

62 lines not on this page · raw message

tools/testing/selftests/livepatch/test_modules/test_klp_alias_target.c new file +48 -0

48 lines not on this page · raw message

Signature · 1 line
2.55.0
maintainer Acked-by on v4 2/5
#10 lore raw

Re: [PATCH v4 2/5] selftests/livepatch: Test rejection of aliased symbols in one object

Quoted 5 lines · Petr Mladek

klp_init_object_loaded() now rejects an object whose klp_funcs resolve to the same address, because aliased symbols would push two klp_funcs of one livepatch onto a single ops->func_stack and leave the redirection ambiguous.

Quoted 8 lines

Add a target module providing test_klp_alias_show() together with its __alias() sibling, and a livepatch naming both of them. Two test cases cover both callers of klp_init_object_loaded(): the klp_enable_patch() path, where the target module is loaded before the livepatch, and the klp_module_coming() path, where the livepatch is loaded first and the module loader has to refuse the target module.

[...]

Signature · 1 line
Miroslav
author maintainer
#11 lore raw

PATCH v4 3/5 livepatch: Move code for updating livepatch object relocations

In reply to Petr Mladek

klp_free_object_loaded() is supposed to clear changes made by klp_init_object_loaded(). It should call klp_clear_object_relocs() which is currently defined later.

Move the code for updating object relocations up.

This is just a preparation step. No functional changes.

---
 kernel/livepatch/core.c | 72 ++++++++++++++++++++---------------------
 1 file changed, 36 insertions(+), 36 deletions(-)
kernel/livepatch/core.c +36 -36
index a6762cbe74b7..a6796cd6b65f 100644
@@ -342,6 +342,42 @@ int klp_apply_section_relocs(struct module *pmod, Elf_Shdr *sechdrs,
 					secndx, objname, true);
 }
 
+static int klp_write_object_relocs(struct klp_patch *patch,
+				   struct klp_object *obj,
+				   bool apply)
+{
+	int i, ret;
+	struct klp_modinfo *info = patch->mod->klp_info;
+
+	for (i = 1; i < info->hdr.e_shnum; i++) {
+		Elf_Shdr *sec = info->sechdrs + i;
+
+		if (!(sec->sh_flags & SHF_RELA_LIVEPATCH))
+			continue;
+
+		ret = klp_write_section_relocs(patch->mod, info->sechdrs,
+					       info->secstrings,
+					       patch->mod->core_kallsyms.strtab,
+					       info->symndx, i, obj->name, apply);
+		if (ret)
+			return ret;
+	}
+
+	return 0;
+}
+
+static int klp_apply_object_relocs(struct klp_patch *patch,
+				   struct klp_object *obj)
+{
+	return klp_write_object_relocs(patch, obj, true);
+}
+
+static void klp_clear_object_relocs(struct klp_patch *patch,
+				    struct klp_object *obj)
+{
+	klp_write_object_relocs(patch, obj, false);
+}
+
 /*
  * Sysfs Interface
  *
@@ -823,42 +859,6 @@ static int klp_init_func(struct klp_object *obj, struct klp_func *func)
 			   func->old_sympos ? func->old_sympos : 1);
 }
 
-static int klp_write_object_relocs(struct klp_patch *patch,
-				   struct klp_object *obj,
-				   bool apply)
-{
-	int i, ret;
-	struct klp_modinfo *info = patch->mod->klp_info;
-
-	for (i = 1; i < info->hdr.e_shnum; i++) {
-		Elf_Shdr *sec = info->sechdrs + i;
-
-		if (!(sec->sh_flags & SHF_RELA_LIVEPATCH))
-			continue;
-
-		ret = klp_write_section_relocs(patch->mod, info->sechdrs,
-					       info->secstrings,
-					       patch->mod->core_kallsyms.strtab,
-					       info->symndx, i, obj->name, apply);
-		if (ret)
-			return ret;
-	}
-
-	return 0;
-}
-
-static int klp_apply_object_relocs(struct klp_patch *patch,
-				   struct klp_object *obj)
-{
-	return klp_write_object_relocs(patch, obj, true);
-}
-
-static void klp_clear_object_relocs(struct klp_patch *patch,
-				    struct klp_object *obj)
-{
-	klp_write_object_relocs(patch, obj, false);
-}
-
 /* parts of the initialization that is done only when the object is loaded */
 static int klp_init_object_loaded(struct klp_patch *patch,
 				  struct klp_object *obj)
Signature · 1 line
2.55.0
maintainer Acked-by on v4 3/5
#12 lore raw

Re: [PATCH v4 3/5] livepatch: Move code for updating livepatch object relocations

Quoted 9 lines · Petr Mladek

klp_free_object_loaded() is supposed to clear changes made by klp_init_object_loaded(). It should call klp_clear_object_relocs() which is currently defined later.

Move the code for updating object relocations up.

This is just a preparation step. No functional changes.

[...]

Signature · 1 line
Miroslav
author maintainer
#13 lore raw

PATCH v4 4/5 livepatch: Clear relocations when klp_apply_object_relocs() fails

In reply to Petr Mladek

When a module is loaded, klp_module_coming() updates all enabled livepatches. If an error occurs, it delegates cleanup to klp_cleanup_module_patches_limited(). However, this cleanup loop skips the partially updated patch, leaving any changes made prior to failure unreverted.

One unhandled failure path occurs inside klp_apply_object_relocs(). On architectures like x86_64, apply_relocate_add() performs a verification step using memcmp() to check that memory contains the expected relocated or zeroed value. If relocations left behind by a failed patch are not cleared, subsequent patch operations or reloads can fail this validation.

Introduce klp_write_object_relocs_limited() to unwind and clear only the relocations that were successfully applied before klp_write_object_relocs() encountered an error.

There is no need to clear relocations for other objects in the failing patch because klp_module_coming() operates strictly on the specific module being loaded.

---
 kernel/livepatch/core.c | 23 ++++++++++++++++++-----
 1 file changed, 18 insertions(+), 5 deletions(-)
kernel/livepatch/core.c +18 -5
index a6796cd6b65f..714f97fdd271 100644
@@ -342,14 +342,17 @@ int klp_apply_section_relocs(struct module *pmod, Elf_Shdr *sechdrs,
 					secndx, objname, true);
 }
 
-static int klp_write_object_relocs(struct klp_patch *patch,
-				   struct klp_object *obj,
-				   bool apply)
+static int klp_write_object_relocs_limited(struct klp_patch *patch,
+					   struct klp_object *obj,
+					   bool apply, int limit)
 {
 	int i, ret;
 	struct klp_modinfo *info = patch->mod->klp_info;
 
-	for (i = 1; i < info->hdr.e_shnum; i++) {
+	if (!limit || limit > info->hdr.e_shnum)
+		limit = info->hdr.e_shnum;
+
+	for (i = 1; i < limit; i++) {
 		Elf_Shdr *sec = info->sechdrs + i;
 
 		if (!(sec->sh_flags & SHF_RELA_LIVEPATCH))
@@ -359,13 +362,23 @@ static int klp_write_object_relocs(struct klp_patch *patch,
 					       info->secstrings,
 					       patch->mod->core_kallsyms.strtab,
 					       info->symndx, i, obj->name, apply);
-		if (ret)
+		if (ret) {
+			if (apply)
+				klp_write_object_relocs_limited(patch, obj, false, i);
 			return ret;
+		}
 	}
 
 	return 0;
 }
 
+static int klp_write_object_relocs(struct klp_patch *patch,
+				   struct klp_object *obj,
+				   bool apply)
+{
+	return klp_write_object_relocs_limited(patch, obj, apply, 0);
+}
+
 static int klp_apply_object_relocs(struct klp_patch *patch,
 				   struct klp_object *obj)
 {
Signature · 1 line
2.55.0
#14 lore raw

Re: [PATCH v4 4/5] livepatch: Clear relocations when klp_apply_object_relocs() fails

Thank you for your contribution! Sashiko AI review found 1 potential issue(s) to consider: - [Medium] Off-by-one error in the rollback loop leaves the failing section's partially applied relocations…

Thank you for your contribution! Sashiko AI review found 1 potential issue(s) to consider:
- [Medium] Off-by-one error in the rollback loop leaves the failing section's partially applied relocations uncleared. --

commit d297505bb4b1d833ec93725770d65ac1044abcad
Author: Petr Mladek <[email protected]>

livepatch: Clear relocations when klp_apply_object_relocs() fails

This commit introduces klp_write_object_relocs_limited() to unwind and clear only the relocations that were successfully applied before klp_write_object_relocs() encountered an error. This prevents partially applied patches from leaving un-reverted changes that cause subsequent patch operations to fail validation.

Quoted 5 lines
kernel/livepatch/core.c +0 -0
index a6796cd6b65fd..714f97fdd271a 100644
@@ -342,14 +342,17 @@ int klp_apply_section_relocs(struct module *pmod, Elf_Shdr *sechdrs,

[ ... ]

Quoted 13 lines
kernel/livepatch/core.c +7 -1
+static int klp_write_object_relocs_limited(struct klp_patch *patch,
+					   struct klp_object *obj,
+					   bool apply, int limit)
 {
 	int i, ret;
 	struct klp_modinfo *info = patch->mod->klp_info;
 
-	for (i = 1; i < info->hdr.e_shnum; i++) {
+	if (!limit || limit > info->hdr.e_shnum)
+		limit = info->hdr.e_shnum;
+
+	for (i = 1; i < limit; i++) {
 		Elf_Shdr *sec = info->sechdrs + i;

[ ... ]

kernel/livepatch/core.c static int klp_write_object_relocs(struct klp_patch *patch, · line 367

Quoted 4 lines
kernel/livepatch/core.c +3 -1
-		if (ret)
+		if (ret) {
+			if (apply)
+				klp_write_object_relocs_limited(patch, obj, false, i);

[Severity: Medium]
When an error occurs in klp_write_section_relocs(), the rollback is triggered with the failing section index passed as the limit. Since the rollback loop iterates with a strict less-than bounds check against this limit, will this skip the rollback for any relocations that were successfully applied within the failing section itself before it encountered the error?

It looks like this could leave partially applied relocations permanently in memory within the failing section, causing future module loads to fail validation.

Quoted 6 lines
kernel/livepatch/core.c +1 -0
 			return ret;
+		}
 	}
 
 	return 0;
 }
Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=4
author maintainer
#15 lore raw

Re: [PATCH v4 4/5] livepatch: Clear relocations when klp_apply_object_relocs() fails

Quoted 49 lines · On Tue 2026-09-08 12:18:10, [email protected] wrote:

Thank you for your contribution! Sashiko AI review found 1 potential issue(s) to consider:
- [Medium] Off-by-one error in the rollback loop leaves the failing section's partially applied relocations uncleared. --

commit d297505bb4b1d833ec93725770d65ac1044abcad
Author: Petr Mladek <[email protected]>

livepatch: Clear relocations when klp_apply_object_relocs() fails

This commit introduces klp_write_object_relocs_limited() to unwind and clear only the relocations that were successfully applied before klp_write_object_relocs() encountered an error. This prevents partially applied patches from leaving un-reverted changes that cause subsequent patch operations to fail validation.

Quoted 5 lines
kernel/livepatch/core.c +0 -0
index a6796cd6b65fd..714f97fdd271a 100644
@@ -342,14 +342,17 @@ int klp_apply_section_relocs(struct module *pmod, Elf_Shdr *sechdrs,

[ ... ]

Quoted 13 lines
kernel/livepatch/core.c +7 -1
+static int klp_write_object_relocs_limited(struct klp_patch *patch,
+					   struct klp_object *obj,
+					   bool apply, int limit)
 {
 	int i, ret;
 	struct klp_modinfo *info = patch->mod->klp_info;
 
-	for (i = 1; i < info->hdr.e_shnum; i++) {
+	if (!limit || limit > info->hdr.e_shnum)
+		limit = info->hdr.e_shnum;
+
+	for (i = 1; i < limit; i++) {
 		Elf_Shdr *sec = info->sechdrs + i;

[ ... ]

kernel/livepatch/core.c static int klp_write_object_relocs(struct klp_patch *patch, · line 367

Quoted 4 lines
kernel/livepatch/core.c +3 -1
-		if (ret)
+		if (ret) {
+			if (apply)
+				klp_write_object_relocs_limited(patch, obj, false, i);

[Severity: Medium]
When an error occurs in klp_write_section_relocs(), the rollback is triggered with the failing section index passed as the limit. Since the rollback loop iterates with a strict less-than bounds check against this limit, will this skip the rollback for any relocations that were successfully applied within the failing section itself before it encountered the error?

Quoted 3 lines

It looks like this could leave partially applied relocations permanently in memory within the failing section, causing future module loads to fail validation.

Sigh, I did not go deep enough. And it goes down to the arch-specific implementations, in particular arch/x86/kernel/module.c:

static int __write_relocate_add(Elf64_Shdr *sechdrs,
const char *strtab,
unsigned int symindex,
unsigned int relsec,
struct module *me,
void *(*write)(void *dest, const void *src, size_t len), bool apply)
{
[...]

	for (i = 0; i < sechdrs[relsec].sh_size / sizeof(*rel); i++) {
[...]
			if (memcmp(loc, &zero, size)) {
				pr_err("x86/modules: Invalid relocation target, existing value is nonzero for sec %u, idx %u, type %d, loc %lx, val %llx\n",
				       relsec, i, (int)ELF64_R_TYPE(rel[i].r_info),
				       (unsigned long)loc, val);
				return -ENOEXEC;
			}
			write(loc, &val, size);
		} else {
			if (memcmp(loc, &val, size)) {
				pr_warn("x86/modules: Invalid relocation target, existing value does not match expected value for sec %u, idx %u, type %d, loc %lx, val %llx\n",
					relsec, i, (int)ELF64_R_TYPE(rel[i].r_info),
					(unsigned long)loc, val);
				return -ENOEXEC;
			}
			write(loc, &zero, size);
		}

[...]

We would need to implement the revert at this level. IMHO, it could be done separately.

I used Gemini LLM to check it and it seems that x86_64 is the only architecture with these permissive checks. It seems that all other architectures just write the new value without checking the existing one.

Would you go this way and try to get patch into x86 code? Should I do it in v5 or separately?

Best Regards,
Petr

PS: I would prefer to go with unless it causes regression
and fix this "later". We could not endlessly delay fixes because of Sashiko finding pre-existing problems.

Quoted 9 lines
Quoted 6 lines
kernel/livepatch/core.c +1 -0
 			return ret;
+		}
 	}
 
 	return 0;
 }
Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=4
maintainer
#16 lore raw

Re: [PATCH v4 4/5] livepatch: Clear relocations when klp_apply_object_relocs() fails

In reply to Petr Mladek
Quoted 12 lines · Petr Mladek

When a module is loaded, klp_module_coming() updates all enabled livepatches. If an error occurs, it delegates cleanup to klp_cleanup_module_patches_limited(). However, this cleanup loop skips the partially updated patch, leaving any changes made prior to failure unreverted.

One unhandled failure path occurs inside klp_apply_object_relocs(). On architectures like x86_64, apply_relocate_add() performs a verification step using memcmp() to check that memory contains the expected relocated or zeroed value. If relocations left behind by a failed patch are not cleared, subsequent patch operations or reloads can fail this validation.

Quoted 7 lines

Introduce klp_write_object_relocs_limited() to unwind and clear only the relocations that were successfully applied before klp_write_object_relocs() encountered an error.

There is no need to clear relocations for other objects in the failing patch because klp_module_coming() operates strictly on the specific module being loaded.

Hm, I spent some quite time on that and I am not sure if I deciphered everything correctly.

It seems to me that all error handling in those paths you are mentioning above is correct and the only problematic thing is that klp_apply_object_relocs() in klp_init_object_loaded() returns ret immediately which leaves partially applied relocations in case of an error. Following calls in klp_init_object_loaded() go through err: label where klp_free_object_loaded() is called which should be fine.

Is it correct?

Wouldn't be better to be somehow consistent and clean up right in the error path of klp_apply_object_relocs() call in klp_init_object_loaded() similarly to what is already there. After all we want to clean the object.

But I also see why you want to do it this way. It only seems more fragile to me.

Miroslav

maintainer
#17 lore raw

Re: [PATCH v4 4/5] livepatch: Clear relocations when klp_apply_object_relocs() fails

Quoted 32 lines · Miroslav Benes
Quoted 12 lines · Petr Mladek

When a module is loaded, klp_module_coming() updates all enabled livepatches. If an error occurs, it delegates cleanup to klp_cleanup_module_patches_limited(). However, this cleanup loop skips the partially updated patch, leaving any changes made prior to failure unreverted.

One unhandled failure path occurs inside klp_apply_object_relocs(). On architectures like x86_64, apply_relocate_add() performs a verification step using memcmp() to check that memory contains the expected relocated or zeroed value. If relocations left behind by a failed patch are not cleared, subsequent patch operations or reloads can fail this validation.

Quoted 7 lines

Introduce klp_write_object_relocs_limited() to unwind and clear only the relocations that were successfully applied before klp_write_object_relocs() encountered an error.

There is no need to clear relocations for other objects in the failing patch because klp_module_coming() operates strictly on the specific module being loaded.

Hm, I spent some quite time on that and I am not sure if I deciphered everything correctly.

It seems to me that all error handling in those paths you are mentioning above is correct and the only problematic thing is that klp_apply_object_relocs() in klp_init_object_loaded() returns ret immediately which leaves partially applied relocations in case of an error. Following calls in klp_init_object_loaded() go through err: label where klp_free_object_loaded() is called which should be fine.

Quoted 8 lines

Is it correct?

Wouldn't be better to be somehow consistent and clean up right in the error path of klp_apply_object_relocs() call in klp_init_object_loaded() similarly to what is already there. After all we want to clean the object.

But I also see why you want to do it this way. It only seems more fragile to me.

And only now I realized that I checked with 5/5 already applied by mistake. The above still stands though and at least I reviewed 5/5 as well.

Miroslav

author maintainer
#18 lore raw

Re: [PATCH v4 4/5] livepatch: Clear relocations when klp_apply_object_relocs() fails

In reply to Miroslav Benes
Quoted 32 lines · Miroslav Benes
Quoted 12 lines · Petr Mladek

When a module is loaded, klp_module_coming() updates all enabled livepatches. If an error occurs, it delegates cleanup to klp_cleanup_module_patches_limited(). However, this cleanup loop skips the partially updated patch, leaving any changes made prior to failure unreverted.

One unhandled failure path occurs inside klp_apply_object_relocs(). On architectures like x86_64, apply_relocate_add() performs a verification step using memcmp() to check that memory contains the expected relocated or zeroed value. If relocations left behind by a failed patch are not cleared, subsequent patch operations or reloads can fail this validation.

Quoted 7 lines

Introduce klp_write_object_relocs_limited() to unwind and clear only the relocations that were successfully applied before klp_write_object_relocs() encountered an error.

There is no need to clear relocations for other objects in the failing patch because klp_module_coming() operates strictly on the specific module being loaded.

Hm, I spent some quite time on that and I am not sure if I deciphered everything correctly.

It seems to me that all error handling in those paths you are mentioning above is correct and the only problematic thing is that klp_apply_object_relocs() in klp_init_object_loaded() returns ret immediately which leaves partially applied relocations in case of an error. Following calls in klp_init_object_loaded() go through err: label where klp_free_object_loaded() is called which should be fine.

Quoted 5 lines

Is it correct?

Wouldn't be better to be somehow consistent and clean up right in the error path of klp_apply_object_relocs() call in klp_init_object_loaded() similarly to what is already there. After all we want to clean the object.

In fact, this is exactly what klp_write_object_relocs_limited() does. The new _limited() variant of the function is used just in two locations:

1. It implements the original klp_write_object_relocs() where it is called "unlimited".

2. It is used recursively in its own error path.

I did this trick to avoid code duplication in the error path.

I agree that is is not obvious. I should mention it in the commit message. And probably even add a comment into the code.

Or would you prefer another solution, please?

Best Regards,
Petr

maintainer
#19 lore raw

Re: [PATCH v4 4/5] livepatch: Clear relocations when klp_apply_object_relocs() fails

Quoted 46 lines · Petr Mladek
Quoted 32 lines · Miroslav Benes
Quoted 12 lines · Petr Mladek

When a module is loaded, klp_module_coming() updates all enabled livepatches. If an error occurs, it delegates cleanup to klp_cleanup_module_patches_limited(). However, this cleanup loop skips the partially updated patch, leaving any changes made prior to failure unreverted.

One unhandled failure path occurs inside klp_apply_object_relocs(). On architectures like x86_64, apply_relocate_add() performs a verification step using memcmp() to check that memory contains the expected relocated or zeroed value. If relocations left behind by a failed patch are not cleared, subsequent patch operations or reloads can fail this validation.

Quoted 7 lines

Introduce klp_write_object_relocs_limited() to unwind and clear only the relocations that were successfully applied before klp_write_object_relocs() encountered an error.

There is no need to clear relocations for other objects in the failing patch because klp_module_coming() operates strictly on the specific module being loaded.

Hm, I spent some quite time on that and I am not sure if I deciphered everything correctly.

It seems to me that all error handling in those paths you are mentioning above is correct and the only problematic thing is that klp_apply_object_relocs() in klp_init_object_loaded() returns ret immediately which leaves partially applied relocations in case of an error. Following calls in klp_init_object_loaded() go through err: label where klp_free_object_loaded() is called which should be fine.

Quoted 5 lines

Is it correct?

Wouldn't be better to be somehow consistent and clean up right in the error path of klp_apply_object_relocs() call in klp_init_object_loaded() similarly to what is already there. After all we want to clean the object.

In fact, this is exactly what klp_write_object_relocs_limited() does. The new _limited() variant of the function is used just in two locations:

1. It implements the original klp_write_object_relocs() where it is called "unlimited".

Quoted 8 lines

2. It is used recursively in its own error path.

I did this trick to avoid code duplication in the error path.

I agree that is is not obvious. I should mention it in the commit message. And probably even add a comment into the code.

Or would you prefer another solution, please?

I will admit that I do not understand what I meant back then. Your solution seems correct to me now.

Miroslav

author maintainer
#20 lore raw

PATCH v4 5/5 livepatch: Clean up klp_init_object_loaded() when fails

In reply to Petr Mladek

When loading a module, klp_module_coming() updates all enabled patches. If an error occurs, klp_cleanup_module_patches_limited() cleans up fully processed patches, but skips the patch that failed midway.

The current code is a bit messy. The changes done by klp_init_object_loaded() should get cleared by klp_free_object_loaded(). But this function also clears obj->mod which is set by klp_module_coming(). And relocations are cleared separately.

Fix the situations by updating klp_free_object_loaded(). It should revert all and only changes made by klp_init_object_loaded(). This requires some shuffling:

+ Clear obj->mod explicitly in klp_cleanup_module_patches_limited() and do not rely on klp_free_object_loaded().

+ Clear relocations in klp_free_object_loaded(). Remove the explicit call from klp_cleanup_module_patches_limited(). This requires adding the @patch parameter.

Next, klp_init_object_loaded() has to clear its own changes on failure. It just returns an error when relocations failed because they clear their own mess. It could call klp_free_object_loaded() in other situations because all relocations were done and other values are just cleared.

Finally, in klp_module_coming(), avoid code duplication by goto targets. There is no need to clear relocations for other objects in the failing patch because klp_module_coming() operates strictly on the specific module being loaded.

---
 kernel/livepatch/core.c | 37 +++++++++++++++++++++++++------------
 1 file changed, 25 insertions(+), 12 deletions(-)
kernel/livepatch/core.c +25 -12
index 714f97fdd271..87b2331486d4 100644
@@ -738,18 +738,20 @@ static void __klp_free_funcs(struct klp_object *obj, bool nops_only)
 }
 
 /* Clean up when a patched object is unloaded */
-static void klp_free_object_loaded(struct klp_object *obj)
+static void klp_free_object_loaded(struct klp_patch *patch,
+				   struct klp_object *obj)
 {
 	struct klp_func *func;
 
-	obj->mod = NULL;
-
 	klp_for_each_func(obj, func) {
 		func->old_func = NULL;
 
 		if (func->nop)
 			func->new_func = NULL;
 	}
+
+	if (klp_is_module(obj))
+		klp_clear_object_relocs(patch, obj);
 }
 
 static void __klp_free_objects(struct klp_patch *patch, bool nops_only)
@@ -896,7 +898,7 @@ static int klp_init_object_loaded(struct klp_patch *patch,
 					     func->old_sympos,
 					     (unsigned long *)&func->old_func);
 		if (ret)
-			return ret;
+			goto err;
 
 		/*
 		 * Aliased symbols share one address, so they would resolve to
@@ -909,7 +911,8 @@ static int klp_init_object_loaded(struct klp_patch *patch,
 			if (prev_func->old_func == func->old_func) {
 				pr_err("'%s' and '%s' resolve to the same address, aliased symbols are not supported\n",
 				       prev_func->old_name, func->old_name);
-				return -EINVAL;
+				ret = -EINVAL;
+				goto err;
 			}
 		}
 
@@ -918,7 +921,8 @@ static int klp_init_object_loaded(struct klp_patch *patch,
 		if (!ret) {
 			pr_err("kallsyms size lookup failed for '%s'\n",
 			       func->old_name);
-			return -ENOENT;
+			ret = -ENOENT;
+			goto err;
 		}
 
 		if (func->nop)
@@ -929,11 +933,17 @@ static int klp_init_object_loaded(struct klp_patch *patch,
 		if (!ret) {
 			pr_err("kallsyms size lookup failed for '%s' replacement\n",
 			       func->old_name);
-			return -ENOENT;
+			ret = -ENOENT;
+			goto err;
 		}
 	}
 
 	return 0;
+
+err:
+	klp_free_object_loaded(patch, obj);
+
+	return ret;
 }
 
 static int klp_init_object(struct klp_patch *patch, struct klp_object *obj)
@@ -1287,8 +1297,8 @@ static void klp_cleanup_module_patches_limited(struct module *mod,
 			klp_unpatch_object(obj);
 
 			klp_post_unpatch_callback(obj);
-			klp_clear_object_relocs(patch, obj);
-			klp_free_object_loaded(obj);
+			klp_free_object_loaded(patch, obj);
+			obj->mod = NULL;
 			break;
 		}
 	}
@@ -1337,7 +1347,7 @@ int klp_module_coming(struct module *mod)
 			if (ret) {
 				pr_warn("pre-patch callback failed for object '%s'\n",
 					obj->name);
-				goto err;
+				goto err_free_object;
 			}
 
 			ret = klp_patch_object(obj);
@@ -1345,8 +1355,7 @@ int klp_module_coming(struct module *mod)
 				pr_warn("failed to apply patch '%s' to module '%s' (%d)\n",
 					patch->mod->name, obj->mod->name, ret);
 
-				klp_post_unpatch_callback(obj);
-				goto err;
+				goto err_unpatch_callback;
 			}
 
 			if (patch != klp_transition_patch)
@@ -1360,6 +1369,10 @@ int klp_module_coming(struct module *mod)
 
 	return 0;
 
+err_unpatch_callback:
+	klp_post_unpatch_callback(obj);
+err_free_object:
+	klp_free_object_loaded(patch, obj);
 err:
 	/*
 	 * If a patch is unsuccessfully applied, return
Signature · 1 line
2.55.0
#21 lore raw

Re: [PATCH v4 5/5] livepatch: Clean up klp_init_object_loaded() when fails

Thank you for your contribution! Sashiko AI review found 1 potential issue(s) to consider: - [High] Partial relocations are not reverted when apply_relocate_add() fails midway, leading to permanent…

Thank you for your contribution! Sashiko AI review found 1 potential issue(s) to consider:
- [High] Partial relocations are not reverted when apply_relocate_add() fails midway, leading to permanent state corruption. --

commit 3f6df1b4ed699e839abbdc8919a6c7de5d1850c8
Author: Petr Mladek <[email protected]>

livepatch: Clean up klp_init_object_loaded() when fails

When loading a module, klp_module_coming() updates all enabled patches. If an error occurs, klp_cleanup_module_patches_limited() cleans up fully processed patches, but skips the patch that failed midway. This commit updates klp_free_object_loaded() to revert all and only changes made by klp_init_object_loaded().

Quoted 5 lines

Next, klp_init_object_loaded() has to clear its own changes on failure. It just returns an error when relocations failed because they clear their own mess. It could call klp_free_object_loaded() in other situations because all relocations were done and other values are just cleared.

[Severity: High]
Does this actually clear its own mess completely? Looking at how relocations are rolled back in klp_write_object_relocs_limited(), which was introduced earlier in this series:

kernel/livepatch/core.c:klp_write_object_relocs_limited() {
    ...
		ret = klp_write_section_relocs(patch->mod, info->sechdrs,
					       info->secstrings,
					       patch->mod->core_kallsyms.strtab,
					       info->symndx, i, obj->name, apply);
		if (ret) {
			if (apply)
				klp_write_object_relocs_limited(patch, obj, false, i);
			return ret;
		}
    ...
}

By passing i as the limit to the rollback function, the rollback loop:

	for (i = 1; i < limit; i++) {

will terminate at i - 1. Doesn't this skip the rollback for the partially applied section i?

If apply_relocate_add succeeds on relocations 0 to k-1 in section i, but fails on relocation k, these partial relocations remain permanently applied in the livepatch module's text.

Subsequent attempts to load the target module will fail immediately at relocation 0 due to non-zero target memory, converting a potentially transient address-space layout failure into a permanent -ENOEXEC on retry.

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

Re: [PATCH v4 5/5] livepatch: Clean up klp_init_object_loaded() when fails

Quoted 45 lines · On Tue 2026-09-08 12:25:48, [email protected] wrote:

Thank you for your contribution! Sashiko AI review found 1 potential issue(s) to consider:
- [High] Partial relocations are not reverted when apply_relocate_add() fails midway, leading to permanent state corruption. --

commit 3f6df1b4ed699e839abbdc8919a6c7de5d1850c8
Author: Petr Mladek <[email protected]>

livepatch: Clean up klp_init_object_loaded() when fails

When loading a module, klp_module_coming() updates all enabled patches. If an error occurs, klp_cleanup_module_patches_limited() cleans up fully processed patches, but skips the patch that failed midway. This commit updates klp_free_object_loaded() to revert all and only changes made by klp_init_object_loaded().

Quoted 5 lines

Next, klp_init_object_loaded() has to clear its own changes on failure. It just returns an error when relocations failed because they clear their own mess. It could call klp_free_object_loaded() in other situations because all relocations were done and other values are just cleared.

[Severity: High]
Does this actually clear its own mess completely? Looking at how relocations are rolled back in klp_write_object_relocs_limited(), which was introduced earlier in this series:

kernel/livepatch/core.c:klp_write_object_relocs_limited() {
    ...
		ret = klp_write_section_relocs(patch->mod, info->sechdrs,
					       info->secstrings,
					       patch->mod->core_kallsyms.strtab,
					       info->symndx, i, obj->name, apply);
		if (ret) {
			if (apply)
				klp_write_object_relocs_limited(patch, obj, false, i);
			return ret;
		}
    ...
}

By passing i as the limit to the rollback function, the rollback loop:

Quoted 8 lines
	for (i = 1; i < limit; i++) {

will terminate at i - 1. Doesn't this skip the rollback for the partially applied section i?

If apply_relocate_add succeeds on relocations 0 to k-1 in section i, but fails on relocation k, these partial relocations remain permanently applied in the livepatch module's text.

This is the same problem which was reported for the 4th patch. It would need to handled in the arch-code, namely
in __write_relocate_add() in arch/x86/kernel/module.c.

Best Regards,
Petr

Quoted 3 lines

Subsequent attempts to load the target module will fail immediately at relocation 0 due to non-zero target memory, converting a potentially transient address-space layout failure into a permanent -ENOEXEC on retry.

maintainer Acked-by on v4 5/5
#23 lore raw

Re: [PATCH v4 5/5] livepatch: Clean up klp_init_object_loaded() when fails

In reply to Petr Mladek
Quoted 10 lines · Petr Mladek

When loading a module, klp_module_coming() updates all enabled patches. If an error occurs, klp_cleanup_module_patches_limited() cleans up fully processed patches, but skips the patch that failed midway.

The current code is a bit messy. The changes done by klp_init_object_loaded() should get cleared by klp_free_object_loaded(). But this function also clears obj->mod which is set by klp_module_coming(). And relocations are cleared separately.

[...]

Signature · 1 line
Miroslav
author maintainer
#24 lore raw
In reply to Petr Mladek
Quoted 3 lines · Petr Mladek

This is v4 of the patch failing object initialization when it patches the same underlying function twice through two aliased symbols (functions sharing one address) in the same object.

I wonder how to move forward with this patchset. There seems to be three unresolved problems:

1. How to handle aliased functions when replacing two livepatches with aliased symbols, aka two NOPs on the same stack [1].

My take: I would fix this later on top of scoped atomic replace.
The aliased symbols should conflict.

2. Fix the low-level __write_relocate_add() to clean its own mess on failure.

My take: I would fix this a follow up patch.

3. Better describe the purpose of klp_write_object_relocs_limited(). Or clean its own mess a better way (code duplication)?

My take: This requires v5.

[1] https://lore.kernel.org/all/[email protected]/
[2] https://lore.kernel.org/all/[email protected]/
[3] https://lore.kernel.org/all/[email protected]/

Best Regards,
Petr

#25 lore raw
Quoted 11 lines · Petr Mladek

I wonder how to move forward with this patchset. There seems to be three unresolved problems:

1. How to handle aliased functions when replacing two livepatches with aliased symbols, aka two NOPs on the same stack [1].

My take: I would fix this later on top of scoped atomic replace.
The aliased symbols should conflict.
2. Fix the low-level __write_relocate_add() to clean its own mess on failure.

Quoted 6 lines

My take: I would fix this a follow up patch.

3. Better describe the purpose of klp_write_object_relocs_limited(). Or clean its own mess a better way (code duplication)?

My take: This requires v5.

For 1, I have a proposal to create only one NOP in the first place, as in your solution 1 from the earlier mail.

Recap: The problem
-----------

Take two livepatches that are already loaded:
A patches __do_sys_fork
B patches __x64_sys_fork (same address as __do_sys_fork)

and an atomic replace livepatch C that patches neither of them. klp_add_nops() finds the functions by name and sympos only, so C inherits two NOPs. Both resolve to the same address and end up on the same ops->func_stack: [A, B, nop1, nop2]. When the transition is reverted, the stack goes from nop2 to nop1 instead of back to B.

Proposal
--------

klp_add_nops() runs from klp_init_patch() before klp_init_object(), so the new NOPs have no address yet. But func->old_func of the old livepatches is already resolved when their object is loaded. So the address can be used as a hint when the NOPs are created:

1. Copy the already resolved address of the old function into the

     new NOP (func->old_func) as an address hint.

2. Do not create another NOP when a NOP with the same address already exists in the object.

The hint is overwritten by klp_find_object_symbol() in klp_init_object_loaded() with the same value. It is cleared again by klp_free_object_loaded(), so it never outlives the loaded object.

A sketch of the change in kernel/livepatch/core.c:

+/*
+ * Return true when @obj already has a nop whose address hint is @addr.
+ * The hint is only set when the livepatched object was already loaded.
+ */
+static bool klp_nop_exists_at(struct klp_object *obj, void *addr) +{
+ struct klp_func *func;
+
+ if (!addr)
+ return false;
+
+ klp_for_each_func(obj, func) {
+ if (func->nop && func->old_func == addr)
+ return true;
+ }
+
+ return false;
+}
+
static int klp_add_object_nops(struct klp_patch *patch,
struct klp_object *old_obj)
{
@@
klp_for_each_func(old_obj, old_func) {
func = klp_find_func(obj, old_func);
if (func)
continue;

+ /*
+ * Aliased symbols resolve to the same address. A single nop
+ * is enough. More nops on the same ops->func_stack would
+ * break reverting the transition.
+ */
+ if (klp_nop_exists_at(obj, old_func->old_func))
+ continue;
+
func = klp_alloc_func_nop(old_func, obj); if (!func)
return -ENOMEM;
+
+ /* Address hint for klp_nop_exists_at(). */
+ func->old_func = old_func->old_func;
}

That's only one way I can come up with :D

Best Regards,
Harry

author maintainer
#26 lore raw
Quoted 37 lines · Harry Hsu
Quoted 11 lines · Petr Mladek

I wonder how to move forward with this patchset. There seems to be three unresolved problems:

1. How to handle aliased functions when replacing two livepatches with aliased symbols, aka two NOPs on the same stack [1].

My take: I would fix this later on top of scoped atomic replace.
The aliased symbols should conflict.
2. Fix the low-level __write_relocate_add() to clean its own mess on failure.

Quoted 6 lines

My take: I would fix this a follow up patch.

3. Better describe the purpose of klp_write_object_relocs_limited(). Or clean its own mess a better way (code duplication)?

My take: This requires v5.

For 1, I have a proposal to create only one NOP in the first place, as in your solution 1 from the earlier mail.

Recap: The problem
-----------

Take two livepatches that are already loaded:
A patches __do_sys_fork
B patches __x64_sys_fork (same address as __do_sys_fork)

and an atomic replace livepatch C that patches neither of them. klp_add_nops() finds the functions by name and sympos only, so C inherits two NOPs. Both resolve to the same address and end up on the same ops->func_stack: [A, B, nop1, nop2]. When the transition is reverted, the stack goes from nop2 to nop1 instead of back to B.

Quoted 6 lines

Proposal
--------

klp_add_nops() runs from klp_init_patch() before klp_init_object(), so the new NOPs have no address yet. But func->old_func of the old livepatches is already resolved when their object is loaded.

Hmm, this is not good. It would be better to have an universal solution which would work even when the livepatched object (module) gets loaded later.

A solution might be to detect this in klp_init_object_loaded() and free the duplicated NOP there. I am not 100% sure that this would work but it might be worth investigating.

Best Regards,
Petr