Skip to contentSkip to conversation

livepatch: Allow user to specify functions to search for on a stack

PATCH Superseded Miroslav Benes 5 participants 14 messages Nov 19, 2021 – Dec 3, 2021

Subsystems (3)

v1 of 2 Superseded Latest is v2 →

lore
Share & tools
lore

Miroslav Benes

author maintainer
#0 lore raw

cover livepatch: Allow user to specify functions to search for on a stack

livepatch's consistency model requires that no live patched function must be found on any task's stack during a transition process after a live patch is applied. It is achieved by walking through stacks of all blocked tasks.

The user might also want to define more functions to search for without them being patched at all. It may either help with preparing a live patch, which would otherwise require additional touches to achieve the consistency, or it can be used to overcome deficiencies the stack checking inherently has. For example, GCC may optimize a function so that a part of it is moved to a different section and the function would jump to it. This child function would not be found on a stack in this case, but it may be important to search for it so that, again, the consistency is achieved.

The patch set adds a new API which allows the user to specify such functions.

The first patch is only preparatory. The main work is in the second one. The third patch adds a test.

Originally, I wanted to add it all to klp_patch struct, but it makes more sense to do it on klp_object level. It is also easier to reuse as much of the existing code as possible in that case.

I am not good with naming so bike-shedding is welcome. Reviews even more.

Miroslav Benes (3):
livepatch: Move the initialization of old_func to a new function
livepatch: Allow user to specify functions to search for on a stack selftests/livepatch: Test of the API for specifying functions to
search for on a stack

 include/linux/livepatch.h                     | 11 +++
 kernel/livepatch/core.c                       | 50 ++++++++---
 kernel/livepatch/transition.c                 | 21 +++--
 lib/Kconfig.debug                             |  1 +
 lib/livepatch/Makefile                        |  4 +-
 lib/livepatch/test_klp_funcstack_demo.c       | 61 +++++++++++++
 lib/livepatch/test_klp_funcstack_mod.c        | 72 +++++++++++++++
 tools/testing/selftests/livepatch/Makefile    |  3 +-
 .../selftests/livepatch/test-func-stack.sh    | 88 +++++++++++++++++++
 9 files changed, 293 insertions(+), 18 deletions(-)
 create mode 100644 lib/livepatch/test_klp_funcstack_demo.c
 create mode 100644 lib/livepatch/test_klp_funcstack_mod.c
 create mode 100755 tools/testing/selftests/livepatch/test-func-stack.sh
Signature · 1 line
2.33.1
author maintainer
#1 lore raw

PATCH 1/3 livepatch: Move the initialization of old_func to a new function

struct klp_func will be used not only for functions to be patched but also for functions which must not be found on a stack. Move the initialization of needed struct members to a separate function, so the code can be reused.

---
 kernel/livepatch/core.c | 34 +++++++++++++++++++++++-----------
 1 file changed, 23 insertions(+), 11 deletions(-)
kernel/livepatch/core.c +23 -11
index 335d988bd811..3d8e3caf9f92 100644
@@ -767,6 +767,28 @@ static int klp_apply_object_relocs(struct klp_patch *patch,
 	return 0;
 }
 
+static int klp_init_old_func(struct klp_object *obj,
+			     struct klp_func *func)
+{
+	int ret;
+
+	ret = klp_find_object_symbol(obj->name, func->old_name,
+				     func->old_sympos,
+				     (unsigned long *)&func->old_func);
+	if (ret)
+		return ret;
+
+	ret = kallsyms_lookup_size_offset((unsigned long)func->old_func,
+					  &func->old_size, NULL);
+	if (!ret) {
+		pr_err("kallsyms size lookup failed for '%s'\n",
+		       func->old_name);
+		return -ENOENT;
+	}
+
+	return 0;
+}
+
 /* 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)
@@ -787,20 +809,10 @@ static int klp_init_object_loaded(struct klp_patch *patch,
 	}
 
 	klp_for_each_func(obj, func) {
-		ret = klp_find_object_symbol(obj->name, func->old_name,
-					     func->old_sympos,
-					     (unsigned long *)&func->old_func);
+		ret = klp_init_old_func(obj, func);
 		if (ret)
 			return ret;
 
-		ret = kallsyms_lookup_size_offset((unsigned long)func->old_func,
-						  &func->old_size, NULL);
-		if (!ret) {
-			pr_err("kallsyms size lookup failed for '%s'\n",
-			       func->old_name);
-			return -ENOENT;
-		}
-
 		if (func->nop)
 			func->new_func = func->old_func;
 
Signature · 1 line
2.33.1
author maintainer
#2 lore raw

PATCH 2/3 livepatch: Allow user to specify functions to search for on a stack

In reply to Miroslav Benes

livepatch's consistency model requires that no live patched function must be found on any task's stack during a transition process after a live patch is applied. It is achieved by walking through stacks of all blocked tasks.

The user might also want to define more functions to search for without them being patched at all. It may either help with preparing a live patch, which would otherwise require additional touches to achieve the consistency, or it can be used to overcome deficiencies the stack checking inherently has. For example, GCC may optimize a function so that a part of it is moved to a different section and the function would jump to it. This child function would not be found on a stack in this case, but it may be important to search for it so that, again, the consistency is achieved.

Allow the user to specify such functions on klp_object level.

---
 include/linux/livepatch.h     | 11 +++++++++++
 kernel/livepatch/core.c       | 16 ++++++++++++++++
 kernel/livepatch/transition.c | 21 ++++++++++++++++-----
 3 files changed, 43 insertions(+), 5 deletions(-)
include/linux/livepatch.h +11 -0
index 2614247a9781..89df578af8c3 100644
@@ -106,9 +106,11 @@ struct klp_callbacks {
  * struct klp_object - kernel object structure for live patching
  * @name:	module name (or NULL for vmlinux)
  * @funcs:	function entries for functions to be patched in the object
+ * @funcs_stack:	function entries for functions to be stack checked
  * @callbacks:	functions to be executed pre/post (un)patching
  * @kobj:	kobject for sysfs resources
  * @func_list:	dynamic list of the function entries
+ * @func_stack_list:	dynamic list of the function entries for stack checking
  * @node:	list node for klp_patch obj_list
  * @mod:	kernel module associated with the patched object
  *		(NULL for vmlinux)
@@ -119,11 +121,13 @@ struct klp_object {
 	/* external */
 	const char *name;
 	struct klp_func *funcs;
+	struct klp_func *funcs_stack;
 	struct klp_callbacks callbacks;
 
 	/* internal */
 	struct kobject kobj;
 	struct list_head func_list;
+	struct list_head func_stack_list;
 	struct list_head node;
 	struct module *mod;
 	bool dynamic;
@@ -187,12 +191,19 @@ struct klp_patch {
 	     func->old_name || func->new_func || func->old_sympos; \
 	     func++)
 
+#define klp_for_each_func_stack_static(obj, func) \
+	for (func = obj->funcs_stack; \
+	     func && (func->old_name || func->old_sympos); func++)
+
 #define klp_for_each_func_safe(obj, func, tmp_func)			\
 	list_for_each_entry_safe(func, tmp_func, &obj->func_list, node)
 
 #define klp_for_each_func(obj, func)	\
 	list_for_each_entry(func, &obj->func_list, node)
 
+#define klp_for_each_func_stack(obj, func)	\
+	list_for_each_entry(func, &obj->func_stack_list, node)
+
 int klp_enable_patch(struct klp_patch *);
 
 /* Called from the module loader during module coming/going states */
kernel/livepatch/core.c +16 -0
index 3d8e3caf9f92..86fc73a06844 100644
@@ -825,6 +825,12 @@ static int klp_init_object_loaded(struct klp_patch *patch,
 		}
 	}
 
+	klp_for_each_func_stack(obj, func) {
+		ret = klp_init_old_func(obj, func);
+		if (ret)
+			return ret;
+	}
+
 	return 0;
 }
 
@@ -853,6 +859,11 @@ static int klp_init_object(struct klp_patch *patch, struct klp_object *obj)
 			return ret;
 	}
 
+	klp_for_each_func_stack(obj, func) {
+		if (strlen(func->old_name) >= KSYM_NAME_LEN)
+			return -EINVAL;
+	}
+
 	if (klp_is_object_loaded(obj))
 		ret = klp_init_object_loaded(patch, obj);
 
@@ -870,6 +881,7 @@ static void klp_init_object_early(struct klp_patch *patch,
 				  struct klp_object *obj)
 {
 	INIT_LIST_HEAD(&obj->func_list);
+	INIT_LIST_HEAD(&obj->func_stack_list);
 	kobject_init(&obj->kobj, &klp_ktype_object);
 	list_add_tail(&obj->node, &patch->obj_list);
 }
@@ -899,6 +911,10 @@ static int klp_init_patch_early(struct klp_patch *patch)
 		klp_for_each_func_static(obj, func) {
 			klp_init_func_early(obj, func);
 		}
+
+		klp_for_each_func_stack_static(obj, func) {
+			list_add_tail(&func->node, &obj->func_stack_list);
+		}
 	}
 
 	if (!try_module_get(patch->mod))
kernel/livepatch/transition.c +16 -5
index 5683ac0d2566..be7afc5dc275 100644
@@ -200,7 +200,10 @@ static int klp_check_stack_func(struct klp_func *func, unsigned long *entries,
 	for (i = 0; i < nr_entries; i++) {
 		address = entries[i];
 
-		if (klp_target_state == KLP_UNPATCHED) {
+		if (!func->new_func) {
+			func_addr = (unsigned long)func->old_func;
+			func_size = func->old_size;
+		} else if (klp_target_state == KLP_UNPATCHED) {
 			 /*
 			  * Check for the to-be-unpatched function
 			  * (the func itself).
@@ -256,14 +259,22 @@ static int klp_check_stack(struct task_struct *task, const char **oldname)
 			continue;
 		klp_for_each_func(obj, func) {
 			ret = klp_check_stack_func(func, entries, nr_entries);
-			if (ret) {
-				*oldname = func->old_name;
-				return -EADDRINUSE;
-			}
+			if (ret)
+				goto err;
+		}
+
+		klp_for_each_func_stack(obj, func) {
+			ret = klp_check_stack_func(func, entries, nr_entries);
+			if (ret)
+				goto err;
 		}
 	}
 
 	return 0;
+
+err:
+	*oldname = func->old_name;
+	return -EADDRINUSE;
 }
 
 static int klp_check_and_switch_task(struct task_struct *task, void *arg)
Signature · 1 line
2.33.1
#3 lore raw
Quoted 15 lines · Miroslav Benes

livepatch's consistency model requires that no live patched function must be found on any task's stack during a transition process after a live patch is applied. It is achieved by walking through stacks of all blocked tasks.

The user might also want to define more functions to search for without them being patched at all. It may either help with preparing a live patch, which would otherwise require additional touches to achieve the consistency, or it can be used to overcome deficiencies the stack checking inherently has. For example, GCC may optimize a function so that a part of it is moved to a different section and the function would jump to it. This child function would not be found on a stack in this case, but it may be important to search for it so that, again, the consistency is achieved.

Quoted 1 line

Allow the user to specify such functions on klp_object level.

Ok, so this relies on the patch generator to DTRT but then it should work.

Thanks!

#4 lore raw
In reply to Miroslav Benes

Thanks for doing this! And at peterz-esque speed no less :-)

Quoted 9 lines · Miroslav Benes

livepatch's consistency model requires that no live patched function must be found on any task's stack during a transition process after a live patch is applied. It is achieved by walking through stacks of all blocked tasks.

The user might also want to define more functions to search for without them being patched at all. It may either help with preparing a live patch, which would otherwise require additional touches to achieve the consistency

Do we have any examples of this situation we can add to the commit log?

Quoted 21 lines

or it can be used to overcome deficiencies the stack checking inherently has. For example, GCC may optimize a function so that a part of it is moved to a different section and the function would jump to it. This child function would not be found on a stack in this case, but it may be important to search for it so that, again, the consistency is achieved.

Allow the user to specify such functions on klp_object level.

---
 include/linux/livepatch.h     | 11 +++++++++++
 kernel/livepatch/core.c       | 16 ++++++++++++++++
 kernel/livepatch/transition.c | 21 ++++++++++++++++-----
 3 files changed, 43 insertions(+), 5 deletions(-)
include/linux/livepatch.h +0 -0
index 2614247a9781..89df578af8c3 100644

include/linux/livepatch.h struct klp_callbacks { · line 109

Quoted 4 lines
include/linux/livepatch.h +1 -0
@@ -106,9 +106,11 @@ struct klp_callbacks {
  * struct klp_object - kernel object structure for live patching
  * @name:	module name (or NULL for vmlinux)
  * @funcs:	function entries for functions to be patched in the object
+ * @funcs_stack:	function entries for functions to be stack checked

So there are two arrays/lists of 'klp_func', and two implied meanings of what a 'klp_func' is and how it's initialized.

Might it be simpler and more explicit to just add a new external field to 'klp_func' and continue to have a single 'funcs' array? Similar to what we already do with the special-casing of 'nop', except it would be an external field, e.g. 'no_patch' or 'stack_only'.

Then instead of all the extra klp_for_each_func_stack_static() incantations, and the special cases in higher-level callers like klp_init_object() and klp_init_patch_early(), the lower-level functions like klp_init_func() and klp_init_func_early() can check the field to determine which initializations need to be made. Which is kind of nice IMO as it pushes that detail down more where it belongs. And makes the different types of 'klp_func' more explicit.

Signature · 1 line
Josh
author maintainer
#5 lore raw
Quoted 8 lines · Josh Poimboeuf

Thanks for doing this! And at peterz-esque speed no less :-)

Quoted 5 lines · Miroslav Benes

livepatch's consistency model requires that no live patched function must be found on any task's stack during a transition process after a live patch is applied. It is achieved by walking through stacks of all blocked tasks.

Quoted 6 lines
Quoted 4 lines

The user might also want to define more functions to search for without them being patched at all. It may either help with preparing a live patch, which would otherwise require additional touches to achieve the consistency

Do we have any examples of this situation we can add to the commit log?

I do not have anything at hand. Joe, do you remember the case you mentioned previously about adding a nop to a function?

Quoted 34 lines
Quoted 21 lines

or it can be used to overcome deficiencies the stack checking inherently has. For example, GCC may optimize a function so that a part of it is moved to a different section and the function would jump to it. This child function would not be found on a stack in this case, but it may be important to search for it so that, again, the consistency is achieved.

Allow the user to specify such functions on klp_object level.

---
 include/linux/livepatch.h     | 11 +++++++++++
 kernel/livepatch/core.c       | 16 ++++++++++++++++
 kernel/livepatch/transition.c | 21 ++++++++++++++++-----
 3 files changed, 43 insertions(+), 5 deletions(-)
include/linux/livepatch.h +0 -0
index 2614247a9781..89df578af8c3 100644

include/linux/livepatch.h struct klp_callbacks { · line 109

Quoted 4 lines
include/linux/livepatch.h +1 -0
@@ -106,9 +106,11 @@ struct klp_callbacks {
  * struct klp_object - kernel object structure for live patching
  * @name:	module name (or NULL for vmlinux)
  * @funcs:	function entries for functions to be patched in the object
+ * @funcs_stack:	function entries for functions to be stack checked

So there are two arrays/lists of 'klp_func', and two implied meanings of what a 'klp_func' is and how it's initialized.

Might it be simpler and more explicit to just add a new external field to 'klp_func' and continue to have a single 'funcs' array? Similar to what we already do with the special-casing of 'nop', except it would be an external field, e.g. 'no_patch' or 'stack_only'.

Quoted 7 lines

Then instead of all the extra klp_for_each_func_stack_static() incantations, and the special cases in higher-level callers like klp_init_object() and klp_init_patch_early(), the lower-level functions like klp_init_func() and klp_init_func_early() can check the field to determine which initializations need to be made. Which is kind of nice IMO as it pushes that detail down more where it belongs. And makes the different types of 'klp_func' more explicit.

I thought about doing this for a moment but then I was worried there would be many places which would require special-casing, so I tried to keep it separate. But yes, it would be cleaner, so definitely worth trying for v2.

Thanks

Miroslav

maintainer
#6 lore raw
Quoted 15 lines · Miroslav Benes
Quoted 13 lines · Josh Poimboeuf

Thanks for doing this! And at peterz-esque speed no less :-)

Quoted 9 lines · Miroslav Benes

livepatch's consistency model requires that no live patched function must be found on any task's stack during a transition process after a live patch is applied. It is achieved by walking through stacks of all blocked tasks.

The user might also want to define more functions to search for without them being patched at all. It may either help with preparing a live patch, which would otherwise require additional touches to achieve the consistency

Quoted 5 lines
Quoted 1 line

Do we have any examples of this situation we can add to the commit log?

I do not have anything at hand. Joe, do you remember the case you mentioned previously about adding a nop to a function?

I went looking in my inbox to see... Unfortunately the closest thing I found was a kpatchset in which we added nops to coax kpatch-build into reverting previous patch version changes. Not applicable here, but I was certain we entertained the same idea to increase the task stack check for some other problem.

Maybe adding a hypothetical scenario to the commit log would suffice?

Quoted 42 lines
Quoted 34 lines
Quoted 21 lines

or it can be used to overcome deficiencies the stack checking inherently has. For example, GCC may optimize a function so that a part of it is moved to a different section and the function would jump to it. This child function would not be found on a stack in this case, but it may be important to search for it so that, again, the consistency is achieved.

Allow the user to specify such functions on klp_object level.

---
 include/linux/livepatch.h     | 11 +++++++++++
 kernel/livepatch/core.c       | 16 ++++++++++++++++
 kernel/livepatch/transition.c | 21 ++++++++++++++++-----
 3 files changed, 43 insertions(+), 5 deletions(-)
include/linux/livepatch.h +0 -0
index 2614247a9781..89df578af8c3 100644

include/linux/livepatch.h struct klp_callbacks { · line 109

Quoted 4 lines
include/linux/livepatch.h +1 -0
@@ -106,9 +106,11 @@ struct klp_callbacks {
  * struct klp_object - kernel object structure for live patching
  * @name:	module name (or NULL for vmlinux)
  * @funcs:	function entries for functions to be patched in the object
+ * @funcs_stack:	function entries for functions to be stack checked

So there are two arrays/lists of 'klp_func', and two implied meanings of what a 'klp_func' is and how it's initialized.

Might it be simpler and more explicit to just add a new external field to 'klp_func' and continue to have a single 'funcs' array? Similar to what we already do with the special-casing of 'nop', except it would be an external field, e.g. 'no_patch' or 'stack_only'.

Quoted 7 lines

Then instead of all the extra klp_for_each_func_stack_static() incantations, and the special cases in higher-level callers like klp_init_object() and klp_init_patch_early(), the lower-level functions like klp_init_func() and klp_init_func_early() can check the field to determine which initializations need to be made. Which is kind of nice IMO as it pushes that detail down more where it belongs. And makes the different types of 'klp_func' more explicit.

Quoted 4 lines

I thought about doing this for a moment but then I was worried there would be many places which would require special-casing, so I tried to keep it separate. But yes, it would be cleaner, so definitely worth trying for v2.

I'll add that the first thing that came to mind when you raised this feature idea in the other thread was to support existing klp_funcs array with NULL new_func's. I didn't go look to see how invasive it would be, but it will be interesting to see if a single list approach turns out any simpler for v2.

Signature · 1 line
Joe
maintainer
#7 lore raw
Quoted 16 lines · Joe Lawrence
Quoted 15 lines · Miroslav Benes
Quoted 13 lines · Josh Poimboeuf

Thanks for doing this! And at peterz-esque speed no less :-)

Quoted 9 lines · Miroslav Benes

livepatch's consistency model requires that no live patched function must be found on any task's stack during a transition process after a live patch is applied. It is achieved by walking through stacks of all blocked tasks.

The user might also want to define more functions to search for without them being patched at all. It may either help with preparing a live patch, which would otherwise require additional touches to achieve the consistency

Quoted 6 lines
Quoted 4 lines
Quoted 1 line

Do we have any examples of this situation we can add to the commit log?

I do not have anything at hand. Joe, do you remember the case you mentioned previously about adding a nop to a function?

Maybe adding a hypothetical scenario to the commit log would suffice?

I wonder if we could describe a scenario based on the thread about .cold code variants, see
https://lore.kernel.org/all/20211112015003.pefl656m3zmir6ov@treble/

This feature would allow to safely livepatch already released kernels where the unwinder is not able to reliably detect a newly discovered problems.

Quoted 29 lines
Quoted 29 lines
Quoted 29 lines
Quoted 21 lines

or it can be used to overcome deficiencies the stack checking inherently has. For example, GCC may optimize a function so that a part of it is moved to a different section and the function would jump to it. This child function would not be found on a stack in this case, but it may be important to search for it so that, again, the consistency is achieved.

Allow the user to specify such functions on klp_object level.

---
 include/linux/livepatch.h     | 11 +++++++++++
 kernel/livepatch/core.c       | 16 ++++++++++++++++
 kernel/livepatch/transition.c | 21 ++++++++++++++++-----
 3 files changed, 43 insertions(+), 5 deletions(-)
include/linux/livepatch.h +0 -0
index 2614247a9781..89df578af8c3 100644

include/linux/livepatch.h struct klp_callbacks { · line 109

Quoted 4 lines
include/linux/livepatch.h +1 -0
@@ -106,9 +106,11 @@ struct klp_callbacks {
  * struct klp_object - kernel object structure for live patching
  * @name:	module name (or NULL for vmlinux)
  * @funcs:	function entries for functions to be patched in the object
+ * @funcs_stack:	function entries for functions to be stack checked

So there are two arrays/lists of 'klp_func', and two implied meanings of what a 'klp_func' is and how it's initialized.

Quoted 8 lines
Quoted 4 lines
Quoted 4 lines

Might it be simpler and more explicit to just add a new external field to 'klp_func' and continue to have a single 'funcs' array? Similar to what we already do with the special-casing of 'nop', except it would be an external field, e.g. 'no_patch' or 'stack_only'.

I'll add that the first thing that came to mind when you raised this feature idea in the other thread was to support existing klp_funcs array with NULL new_func's.

Please, solve this with the extra flag, e.g. .stack_only, as already suggested. It will help to distinguish mistakes and intentions. Also it will allow to find these symbols by grep.

Quoted 3 lines

I didn't go look to see how invasive it would be,
but it will be interesting to see if a single list approach turns out any simpler for v2.

I am not sure either. But I expect that it will be easier than the extra array.

Best Regards,
Petr

author maintainer
#8 lore raw
Quoted 24 lines · Petr Mladek
Quoted 16 lines · Joe Lawrence
Quoted 15 lines · Miroslav Benes
Quoted 13 lines · Josh Poimboeuf

Thanks for doing this! And at peterz-esque speed no less :-)

Quoted 9 lines · Miroslav Benes

livepatch's consistency model requires that no live patched function must be found on any task's stack during a transition process after a live patch is applied. It is achieved by walking through stacks of all blocked tasks.

The user might also want to define more functions to search for without them being patched at all. It may either help with preparing a live patch, which would otherwise require additional touches to achieve the consistency

Quoted 6 lines
Quoted 4 lines
Quoted 1 line

Do we have any examples of this situation we can add to the commit log?

I do not have anything at hand. Joe, do you remember the case you mentioned previously about adding a nop to a function?

Maybe adding a hypothetical scenario to the commit log would suffice?

Quoted 7 lines

I wonder if we could describe a scenario based on the thread about .cold code variants, see
https://lore.kernel.org/all/20211112015003.pefl656m3zmir6ov@treble/

This feature would allow to safely livepatch already released kernels where the unwinder is not able to reliably detect a newly discovered problems.

and is described (well, without actually using .cold suffix) a few lines below. I'll try to improve the changelog.

Quoted 34 lines
Quoted 34 lines
Quoted 33 lines
Quoted 33 lines
Quoted 21 lines

or it can be used to overcome deficiencies the stack checking inherently has. For example, GCC may optimize a function so that a part of it is moved to a different section and the function would jump to it. This child function would not be found on a stack in this case, but it may be important to search for it so that, again, the consistency is achieved.

Allow the user to specify such functions on klp_object level.

---
 include/linux/livepatch.h     | 11 +++++++++++
 kernel/livepatch/core.c       | 16 ++++++++++++++++
 kernel/livepatch/transition.c | 21 ++++++++++++++++-----
 3 files changed, 43 insertions(+), 5 deletions(-)
include/linux/livepatch.h +0 -0
index 2614247a9781..89df578af8c3 100644

include/linux/livepatch.h struct klp_callbacks { · line 109

Quoted 4 lines
include/linux/livepatch.h +1 -0
@@ -106,9 +106,11 @@ struct klp_callbacks {
  * struct klp_object - kernel object structure for live patching
  * @name:	module name (or NULL for vmlinux)
  * @funcs:	function entries for functions to be patched in the object
+ * @funcs_stack:	function entries for functions to be stack checked

So there are two arrays/lists of 'klp_func', and two implied meanings of what a 'klp_func' is and how it's initialized.

Might it be simpler and more explicit to just add a new external field to 'klp_func' and continue to have a single 'funcs' array? Similar to what we already do with the special-casing of 'nop', except it would be an external field, e.g. 'no_patch' or 'stack_only'.

Quoted 7 lines
Quoted 3 lines

I'll add that the first thing that came to mind when you raised this feature idea in the other thread was to support existing klp_funcs array with NULL new_func's.

Please, solve this with the extra flag, e.g. .stack_only, as already suggested. It will help to distinguish mistakes and intentions. Also it will allow to find these symbols by grep.

Indeed, that is what I did for v2. I used new_func being NULL fact even in v1, but I do not like it much. Extra flag is definitely more robust.

Quoted 6 lines
Quoted 3 lines

I didn't go look to see how invasive it would be,
but it will be interesting to see if a single list approach turns out any simpler for v2.

I am not sure either. But I expect that it will be easier than the extra array.

So, extra flag and one array makes certain things (initialization) definitely easier. On the other hand, there are suddenly more problems to think about (and I haven't solved them yet):

- I need to make it work with nops functions. Especially if we allow a scenario where there could be klp_object instance with just stack_only functions. Would that be useful? For example, to patch something in a module and add a stack_only for a function in vmlinux.

If yes, then the interaction with nops is not completely straightforward and also some parts of the code would have to be changed (for example how obj->patched flag is handled).

- klp_func instances are directly mirrored in sysfs. Do we want to keep stack_only functions there too? If not, it makes the whole thing slighly more difficult given how we manage kobjects.

Nothing really difficult to implement if we come up with answers.

Miroslav

maintainer
#9 lore raw
Quoted 40 lines · Miroslav Benes
Quoted 21 lines · Petr Mladek
Quoted 20 lines · Joe Lawrence
Quoted 18 lines · Miroslav Benes
Quoted 17 lines · Josh Poimboeuf

include/linux/livepatch.h struct klp_callbacks { · line 109

Quoted 9 lines
include/linux/livepatch.h +1 -0
index 2614247a9781..89df578af8c3 100644
@@ -106,9 +106,11 @@ struct klp_callbacks {
  * struct klp_object - kernel object structure for live patching
  * @name:	module name (or NULL for vmlinux)
  * @funcs:	function entries for functions to be patched in the object
+ * @funcs_stack:	function entries for functions to be stack checked

So there are two arrays/lists of 'klp_func', and two implied meanings of what a 'klp_func' is and how it's initialized.

Might it be simpler and more explicit to just add a new external field to 'klp_func' and continue to have a single 'funcs' array? Similar to what we already do with the special-casing of 'nop', except it would be an external field, e.g. 'no_patch' or 'stack_only'.

Quoted 7 lines
Quoted 3 lines

I'll add that the first thing that came to mind when you raised this feature idea in the other thread was to support existing klp_funcs array with NULL new_func's.

Please, solve this with the extra flag, e.g. .stack_only, as already suggested. It will help to distinguish mistakes and intentions. Also it will allow to find these symbols by grep.

Indeed, that is what I did for v2. I used new_func being NULL fact even in v1, but I do not like it much. Extra flag is definitely more robust.

Quoted 6 lines
Quoted 3 lines

I didn't go look to see how invasive it would be,
but it will be interesting to see if a single list approach turns out any simpler for v2.

I am not sure either. But I expect that it will be easier than the extra array.

Quoted 8 lines

So, extra flag and one array makes certain things (initialization) definitely easier. On the other hand, there are suddenly more problems to think about (and I haven't solved them yet):

- I need to make it work with nops functions. Especially if we allow a scenario where there could be klp_object instance with just stack_only functions. Would that be useful? For example, to patch something in a module and add a stack_only for a function in vmlinux.

My naive expectation is that the struct klp_func with @stack_only flag might be handled the same way on most locations, except when:

+ func->new_func is handled
+ ftrace handler is added/removed

Something like:

kernel/livepatch/core.c +4 -1
@@ -724,7 +724,7 @@ static int klp_init_func(struct klp_object *obj, struct klp_func *func)
 	 * NOPs get the address later. The patched module must be loaded,
 	 * see klp_init_object_loaded().
 	 */
-	if (!func->new_func && !func->nop)
+	if (!func->new_func && !func->nop && !func->stack_only)
 		return -EINVAL;
 
 	if (strlen(func->old_name) >= KSYM_NAME_LEN)
@@ -801,6 +801,9 @@ static int klp_init_object_loaded(struct klp_patch *patch,
 			return -ENOENT;
 		}
 
+		if (func->stack_only)
+			continue;
+
 		if (func->nop)
 			func->new_func = func->old_func;
 
kernel/livepatch/patch.c +5 -0
@@ -247,6 +247,9 @@ static void __klp_unpatch_object(struct klp_object *obj, bool nops_only)
 	struct klp_func *func;
 
 	klp_for_each_func(obj, func) {
+		if (func->stack_only)
+			continue;
+
 		if (nops_only && !func->nop)
 			continue;
 
@@ -273,6 +276,8 @@ int klp_patch_object(struct klp_object *obj)
 		return -EINVAL;
 
 	klp_for_each_func(obj, func) {
+		if (func->stack_only)
+			continue;
 		ret = klp_patch_func(func);
 		if (ret) {
 			klp_unpatch_object(obj);
Quoted 3 lines

If yes, then the interaction with nops is not completely straightforward and also some parts of the code would have to be changed (for example how obj->patched flag is handled).

I would keep func->patched disabled for @stack_only entries.

But they should not affect obj->patched state. I mean that obj->patched should be set when the patch is enabled even when there are only "stack_only" funcs.

It might look a bit unclear. A solution might be to rename the flags:

   + func->patched    ->   func->active   (and set even for @stack_only)
   + obj->patched     ->   obj->active    (same as func)

But I am not sure if it is worth it.

Quoted 3 lines

- klp_func instances are directly mirrored in sysfs. Do we want to keep stack_only functions there too? If not, it makes the whole thing slighly more difficult given how we manage kobjects.

I would keep them in sysfs. It will be easier and it does not harm.

Quoted 1 line

Nothing really difficult to implement if we come up with answers.

I am sorry for not answering this earlier. I have missed the questions :-(

Best Regards,
Petr

author maintainer
#10 lore raw

PATCH 3/3 selftests/livepatch: Test of the API for specifying functions to search for on a stack

In reply to Miroslav Benes

Add a test for the API which allows the user to specify functions which are then searched for on any tasks's stack during a transition process.

---
 lib/Kconfig.debug                             |  1 +
 lib/livepatch/Makefile                        |  4 +-
 lib/livepatch/test_klp_funcstack_demo.c       | 61 +++++++++++++
 lib/livepatch/test_klp_funcstack_mod.c        | 72 +++++++++++++++
 tools/testing/selftests/livepatch/Makefile    |  3 +-
 .../selftests/livepatch/test-func-stack.sh    | 88 +++++++++++++++++++
 6 files changed, 227 insertions(+), 2 deletions(-)
 create mode 100644 lib/livepatch/test_klp_funcstack_demo.c
 create mode 100644 lib/livepatch/test_klp_funcstack_mod.c
 create mode 100755 tools/testing/selftests/livepatch/test-func-stack.sh
lib/Kconfig.debug +1 -0
index 9ef7ce18b4f5..aa4c97098f41 100644
@@ -2529,6 +2529,7 @@ config TEST_LIVEPATCH
 	default n
 	depends on DYNAMIC_DEBUG
 	depends on LIVEPATCH
+	depends on DEBUG_FS
 	depends on m
 	help
 	  Test kernel livepatching features for correctness.  The tests will
lib/livepatch/Makefile +3 -1
index dcc912b3478f..584e3b8b5415 100644
@@ -11,4 +11,6 @@ obj-$(CONFIG_TEST_LIVEPATCH) += test_klp_atomic_replace.o \
 				test_klp_shadow_vars.o \
 				test_klp_state.o \
 				test_klp_state2.o \
-				test_klp_state3.o
+				test_klp_state3.o \
+				test_klp_funcstack_mod.o \
+				test_klp_funcstack_demo.o
lib/livepatch/test_klp_funcstack_demo.c new file +61 -0

61 lines not on this page · raw message

lib/livepatch/test_klp_funcstack_mod.c new file +72 -0

72 lines not on this page · raw message

tools/testing/selftests/livepatch/Makefile +2 -1
index 1acc9e1fa3fb..40f8a3a2e9aa 100644
@@ -6,7 +6,8 @@ TEST_PROGS := \
 	test-callbacks.sh \
 	test-shadow-vars.sh \
 	test-state.sh \
-	test-ftrace.sh
+	test-ftrace.sh \
+	test-func-stack.sh
 
 TEST_FILES := settings
 
tools/testing/selftests/livepatch/test-func-stack.sh new file +88 -0

88 lines not on this page · raw message

Signature · 1 line
2.33.1
maintainer
#11 lore raw

Re: [PATCH 3/3] selftests/livepatch: Test of the API for specifying functions to search for on a stack

Quoted 14 lines · Miroslav Benes

Add a test for the API which allows the user to specify functions which are then searched for on any tasks's stack during a transition process.

lib/livepatch/test_klp_funcstack_mod.c new file +8 -0
@@ -0,0 +1,72 @@
+// SPDX-License-Identifier: GPL-2.0
+// Copyright (C) 2021 Miroslav Benes <[email protected]>
+
+#define pr_fmt(fmt) KBUILD_MODNAME ": " fmt
+
+#include <linux/module.h>
+#include <linux/kernel.h>
+#include <linux/debugfs.h>

lib/livepatch/test_klp_funcstack_mod.c line 18

Quoted 10 lines
lib/livepatch/test_klp_funcstack_mod.c new file +10 -0
+#include <linux/delay.h>
+
+static int sleep_length = 10000;
+module_param(sleep_length, int, 0644);
+MODULE_PARM_DESC(sleep_length, "length of sleep in seconds (default=10)");
+
+static noinline void child_function(void)
+{
+	pr_info("%s enter\n", __func__);
+	msleep(sleep_length);

The hardcoded sleep is not ideal. It might be too low or non-necessary high.

If I get it correctly, we are trying to achieve here the same as busymod_work_func() in test_klp_callbacks_busy.c.

The approach with debugfs is an interesting trick. Though, I slightly prefer using the scheduled work. The workqueue API looks less tricky to me than sysfs/debugfs API. Also it does not block the module in the init() callback[*]. But I might be biased.

Anyway, it might make sense to use the same trick in both situations. It would make it easier to maintain the test modules.

[*] There is actually a race in the workqueue approach. The module init() callback should wait until the work is really scheduled and sleeping. It might be achieved by similar hand-shake like with @block_transition variable. Or completion API might be even more elegant.

lib/livepatch/test_klp_funcstack_mod.c line 31

Quoted 13 lines
lib/livepatch/test_klp_funcstack_mod.c new file +13 -0
+	pr_info("%s exit\n", __func__);
+}
+
+static noinline void child2_function(void)
+{
+	pr_info("%s\n", __func__);
+}
+
+static noinline void parent_function(void)
+{
+	pr_info("%s enter\n", __func__);
+	child_function();
+	child2_function();

This would deserve some explanation what we try to simulate here and how it is achieved. It is not easy for me even with the background that I have freshly in my mind.

Also I think about more descriptive names ;-)

What about something like this (using workqueue work and completion):

/*
* Simulate part of the caller code that is in another .elf section
* and is reached via jump. It this was really the case then the stack
* unwinder might not be able to detect that the process is sleeping
* in the caller.
*/
static void simulate_jump_part(void)

{
	pr_info("%s enter\n", __func__);

	/* Stay in the jump part unless told to leave. */
	wait_for_completion(finish_jump);

	pr_info("%s exit\n", __func__);
}

/*
* Simulate modified part of the caller code. It should never get
* livepatched when the caller is sleeping in the just_part(). */
static void simulate_modified_part(void)

{
	pr_info("%s\n", __func__);
}

static void test_not_on_stack_func_work(struct work_struct *work)

{
	pr_info("%s enter\n", __func__);

	/* Simulation ready */
	complete(work_started);

	simulate_jump_part();
	simulate_modified_part();

	pr_info("%s exit\n", __func__);
}

static int test_klp_no_on_stack_init(void)

{
	pr_info("%s\n", __func__);

	schedule_work(&work);
	wait_for_completion(&work_started);

	return 0;
}

static void test_not_on_stack_exit(void)

{
	complete(&finish_jump);
	flush_work(&work);
	pr_info("%s\n", __func__);
}

module_init(test_klp_not_on_stack_init);
module_exit(test_klp_not_on_stack_exit);

lib/livepatch/test_klp_funcstack_mod.c line 21

Quoted 3 lines
lib/livepatch/test_klp_funcstack_mod.c new file +3 -0
+	pr_info("%s exit\n", __func__);
+}
+

Best Regards,
Petr

author maintainer
#12 lore raw

Re: [PATCH 3/3] selftests/livepatch: Test of the API for specifying functions to search for on a stack

Quoted 19 lines · Petr Mladek
Quoted 18 lines · Miroslav Benes

Add a test for the API which allows the user to specify functions which are then searched for on any tasks's stack during a transition process.

lib/livepatch/test_klp_funcstack_mod.c new file +12 -0
@@ -0,0 +1,72 @@
+// SPDX-License-Identifier: GPL-2.0
+// Copyright (C) 2021 Miroslav Benes <[email protected]>
+
+#define pr_fmt(fmt) KBUILD_MODNAME ": " fmt
+
+#include <linux/module.h>
+#include <linux/kernel.h>
+#include <linux/debugfs.h>
+#include <linux/delay.h>
+
+static int sleep_length = 10000;
+module_param(sleep_length, int, 0644);
Quoted 8 lines

lib/livepatch/test_klp_funcstack_mod.c line 18

Quoted 6 lines
lib/livepatch/test_klp_funcstack_mod.c new file +6 -0
+MODULE_PARM_DESC(sleep_length, "length of sleep in seconds (default=10)");
+
+static noinline void child_function(void)
+{
+	pr_info("%s enter\n", __func__);
+	msleep(sleep_length);

The hardcoded sleep is not ideal. It might be too low or non-necessary high.

It is not.

Quoted 2 lines

If I get it correctly, we are trying to achieve here the same as busymod_work_func() in test_klp_callbacks_busy.c.

Yes.

Quoted 4 lines

The approach with debugfs is an interesting trick. Though, I slightly prefer using the scheduled work. The workqueue API looks less tricky to me than sysfs/debugfs API. Also it does not block the module in the init() callback[*]. But I might be biased.

It seemed to me that debugfs gave us more control over the process than workqueues, but I do not really care. Could you explain the blocking in the init callback? I do not follow.

Quoted 2 lines

Anyway, it might make sense to use the same trick in both situations. It would make it easier to maintain the test modules.

True. So I will rewrite it to workqueues as you are proposing below.

Quoted 25 lines

[*] There is actually a race in the workqueue approach. The module init() callback should wait until the work is really scheduled and sleeping. It might be achieved by similar hand-shake like with @block_transition variable. Or completion API might be even more elegant.

lib/livepatch/test_klp_funcstack_mod.c line 31

Quoted 13 lines
lib/livepatch/test_klp_funcstack_mod.c new file +13 -0
+	pr_info("%s exit\n", __func__);
+}
+
+static noinline void child2_function(void)
+{
+	pr_info("%s\n", __func__);
+}
+
+static noinline void parent_function(void)
+{
+	pr_info("%s enter\n", __func__);
+	child_function();
+	child2_function();

This would deserve some explanation what we try to simulate here and how it is achieved. It is not easy for me even with the background that I have freshly in my mind.

Quoted 1 line

Also I think about more descriptive names ;-)

Hey, I thought it was self-explaining :). So, yes, I started with the example given in the .fixup thread, but it is not really tied to .cold section, jumps or whatever. The setup is just used to test a new API. Moreover, the .fixup example is just a one scenario the new API tries to solve.

What you propose below, that is function names and comments, is a bit confusing for me. Especially if I did not know anything about the original issue (which will be the case in a couple of weeks when I forget everything).

So I think it I will stick to brevity unless you or someone else really insist.

I can improve tests description in tools/testing/selftests/livepatch/test-func-stack.sh if it helps anything.

Miroslav

Quoted 63 lines

What about something like this (using workqueue work and completion):

/*
* Simulate part of the caller code that is in another .elf section
* and is reached via jump. It this was really the case then the stack
* unwinder might not be able to detect that the process is sleeping
* in the caller.
*/
static void simulate_jump_part(void)

{
	pr_info("%s enter\n", __func__);

	/* Stay in the jump part unless told to leave. */
	wait_for_completion(finish_jump);

	pr_info("%s exit\n", __func__);
}

/*
* Simulate modified part of the caller code. It should never get
* livepatched when the caller is sleeping in the just_part(). */
static void simulate_modified_part(void)

{
	pr_info("%s\n", __func__);
}

static void test_not_on_stack_func_work(struct work_struct *work)

{
	pr_info("%s enter\n", __func__);

	/* Simulation ready */
	complete(work_started);

	simulate_jump_part();
	simulate_modified_part();

	pr_info("%s exit\n", __func__);
}

static int test_klp_no_on_stack_init(void)

{
	pr_info("%s\n", __func__);

	schedule_work(&work);
	wait_for_completion(&work_started);

	return 0;
}

static void test_not_on_stack_exit(void)

{
	complete(&finish_jump);
	flush_work(&work);
	pr_info("%s\n", __func__);
}

module_init(test_klp_not_on_stack_init);
module_exit(test_klp_not_on_stack_exit);

Quoted 3 lines
lib/livepatch/test_klp_funcstack_mod.c new file +3 -0
+	pr_info("%s exit\n", __func__);
+}
+
maintainer
#13 lore raw

Re: [PATCH 3/3] selftests/livepatch: Test of the API for specifying functions to search for on a stack

Quoted 6 lines · Miroslav Benes
Quoted 4 lines · Petr Mladek
Quoted 3 lines · Miroslav Benes

Add a test for the API which allows the user to specify functions which are then searched for on any tasks's stack during a transition process.

Quoted 8 lines
Quoted 4 lines

The approach with debugfs is an interesting trick. Though, I slightly prefer using the scheduled work. The workqueue API looks less tricky to me than sysfs/debugfs API. Also it does not block the module in the init() callback[*]. But I might be biased.

It seemed to me that debugfs gave us more control over the process than workqueues, but I do not really care. Could you explain the blocking in the init callback? I do not follow.

Good question about the blocking! Please, forget it. I am not sure why I thought that the module might get blocked in the module_init() script.

Quoted 30 lines
Quoted 2 lines

Anyway, it might make sense to use the same trick in both situations. It would make it easier to maintain the test modules.

True. So I will rewrite it to workqueues as you are proposing below.

Quoted 25 lines

[*] There is actually a race in the workqueue approach. The module init() callback should wait until the work is really scheduled and sleeping. It might be achieved by similar hand-shake like with @block_transition variable. Or completion API might be even more elegant.

lib/livepatch/test_klp_funcstack_mod.c line 31

Quoted 13 lines
lib/livepatch/test_klp_funcstack_mod.c new file +13 -0
+	pr_info("%s exit\n", __func__);
+}
+
+static noinline void child2_function(void)
+{
+	pr_info("%s\n", __func__);
+}
+
+static noinline void parent_function(void)
+{
+	pr_info("%s enter\n", __func__);
+	child_function();
+	child2_function();

This would deserve some explanation what we try to simulate here and how it is achieved. It is not easy for me even with the background that I have freshly in my mind.

Quoted 7 lines
Quoted 1 line

Also I think about more descriptive names ;-)

Hey, I thought it was self-explaining :). So, yes, I started with the example given in the .fixup thread, but it is not really tied to .cold section, jumps or whatever. The setup is just used to test a new API. Moreover, the .fixup example is just a one scenario the new API tries to solve.

OK, single child() function should be enough for testing the behavior. We might sleep/wait in the parent().

I think that I was confused by the two child() functions. It looked like sleeping in a child function was important. And the "same" name of the two children did not help much to understand and distinguish the purpose.

Quoted 7 lines

What you propose below, that is function names and comments, is a bit confusing for me. Especially if I did not know anything about the original issue (which will be the case in a couple of weeks when I forget everything).

So I think it I will stick to brevity unless you or someone else really insist.

No, I do not resist on the complicated exmaple. When thinking about it, the easier test case the better. It should be enough to describe the real-life purpose of the API in the patch that introduces the API.

Quoted 2 lines

I can improve tests description in tools/testing/selftests/livepatch/test-func-stack.sh if it helps anything.

Yes, please. I miss some top-level descriptions of the tested functionality, something like:

# Tests for "bla bla" feature.
# It allows to block transition of a process when it is running # parent() function and only the child() function is livepatched.

# This test does not use the feature. The transition finishes even

# before parent() exits.

# In this test case, the livepatch is instructed to check also # parent() on stack. The transition must not finish before # parent() exists.

It would be nice to have these high-level descriptions even in the test modules.

Best Regards,
Petr