Skip to contentSkip to conversation

livepatch: klp-convert tool

RFC PATCH In review Joe Lawrence 5 participants 31 messages Feb 16, 2022 – Feb 7, 2023

Subsystems (4)
lore
Share & tools
lore

Joe Lawrence

author maintainer
#0 lore raw

v6 cover livepatch: klp-convert tool

This mostly a rebase update of the livepatch klp-convert tool used to generate klp-relocation types (explained in the summary below).

I'm marking this as an RFC as it hasn't been extensively tested for all livepatch supported arches. There are may be a few symbol annotation changes pending what may be implemented for the FGKASLR patchset, I've left a few TODO and // question? marks in the code, etc. At the same time, I think "CET/IBT support and live-patches" highlighted a potential need for this tooling, so I'm posting it in its current format for discussion. I'll reply to individual patches to highlight a few points of interest.

Summary
-------

Livepatches may use symbols which are not contained in its own scope, and, because of that, may end up compiled with relocations that will only be resolved during module load. Yet, when the referenced symbols are not exported, solving this relocation requires information on the object that holds the symbol (either vmlinux or modules) and its position inside the object, as an object may contain multiple symbols with the same name. Providing such information must be done accordingly to what is specified in Documentation/livepatch/module-elf-format.txt.

Currently, there is no trivial way to embed the required information as requested in the final livepatch elf object. klp-convert solves this problem in two different forms: (i) by relying on a symbol map, which is built during kernel compilation, to automatically infer the relocation targeted symbol, and, when such inference is not possible (ii) by using annotations in the elf object to convert the relocation accordingly to the specification, enabling it to be handled by the livepatch loader.

Given the above, add support for symbol mapping in the form of a symbols.klp file; add klp-convert tool; integrate klp-convert tool into kbuild; make livepatch modules discernible during kernel compilation pipeline; add data-structure and macros to enable users to annotate livepatch source code; make modpost stage compatible with livepatches; update livepatch-sample and update documentation.

The patch was tested under three use-cases:

use-case 1: There is a relocation in the lp that can be automatically resolved by klp-convert. For example. see the saved_command_line variable in lib/livepatch/test_klp_convert2.c.

use-case 2: There is a relocation in the lp that cannot be automatically resolved, as the name of the respective symbol appears in multiple objects. The livepatch contains an annotation to enable a correct relocation. See the KLP_MODULE_RELOC / KLP_SYMPOS annotation sections in lib/livepatch/test_klp_convert{1,2}.c.

use-case 3: There is a relocation in the lp that cannot be automatically resolved similarly as 2, but no annotation was provided in the livepatch, triggering an error during compilation. Reproducible by removing the KLP_MODULE_RELOC / KLP_SYMPOS annotation sections in lib/livepatch/test_klp_convert{1,2}.c.

Selftests have been added to exercise these klp-convert use-cases through several tests.

Branches
--------

Previous versions
-----------------

RFC:
https://lore.kernel.org/lkml/[email protected]/
v2:
https://lore.kernel.org/lkml/[email protected]/
v3:
https://lore.kernel.org/lkml/[email protected]/
v4:
https://lore.kernel.org/lkml/[email protected]/
v5:
(not posted)
https://github.com/joe-lawrence/klp-convert-tree/tree/klp-convert-v5-devel
v6:
https://github.com/joe-lawrence/klp-convert-tree/tree/klp-convert-v6
https://github.com/joe-lawrence/klp-convert-tree/tree/klp-convert-v6-devel

Summary of changes in v5
------------------------

[For/from Masahiro]
- rename Symbols.list to symbols.klp
- remove HOST_EXTRACFLAGS from klp-convert build
- kbuild tweaks from Masahiro Yamada
- SPDX instead of the license boilerplate

[Joe]
- a bunch of small checkpatch, clang-check fixes
- klp-convert: account for symbols shared across sections
- klp-convert: sympos endianness for cross-compile
- klp-convert: implement rela section support list
- klp-convert: update group sections sh_link
- klp-convert: flag annotations without relocations
- klp-convert: allow .rela__jump_table to vmlinux
- livepatch/selftests: Add __asm__ symbol renaming examples
- livepatch/selftests: test multiple sections
- livepatch/selftests: add static keys test

[Miroslav]
- klp-convert: use _safe list traversals only when required
- klp-convert: separate rela conversation from removal

Summary of changes in v6
------------------------

[For/from Christophe]
- klp-convert: Support for ppc32 ELF files

[Joe]
- livepatch/selftests: add data relocations test
- klp-convert: move relas to klp_rela_sec tail
- rebase for v5.17-rc1

Joao Moreira (2):
kbuild: Support for symbols.klp creation
documentation: Update on livepatch elf format

Joe Lawrence (5):
livepatch/selftests: add klp-convert livepatch/selftests: test multiple sections livepatch/selftests: add __asm__ symbol renaming examples livepatch/selftests: add data relocations test livepatch/selftests: add static keys test

Josh Poimboeuf (5):
livepatch: Create and include UAPI headers
livepatch: Add klp-convert tool
livepatch: Add klp-convert annotation helpers
modpost: Integrate klp-convert
livepatch: Add sample livepatch module

 .gitignore                                    |   2 +
 Documentation/dontdiff                        |   1 +
 Documentation/livepatch/livepatch.rst         |   3 +
 Documentation/livepatch/module-elf-format.rst |  42 +-
 MAINTAINERS                                   |   2 +
 Makefile                                      |  12 +-
 include/linux/livepatch.h                     |  13 +
 include/uapi/linux/livepatch.h                |  25 +
 kernel/livepatch/core.c                       |   4 +-
 lib/livepatch/Makefile                        |  12 +
 lib/livepatch/test_klp_convert.h              |  45 +
 lib/livepatch/test_klp_convert1.c             | 121 +++
 lib/livepatch/test_klp_convert2.c             | 110 +++
 lib/livepatch/test_klp_convert_data.c         | 190 ++++
 lib/livepatch/test_klp_convert_keys.c         |  91 ++
 lib/livepatch/test_klp_convert_keys_mod.c     |  52 +
 lib/livepatch/test_klp_convert_mod_a.c        |  31 +
 lib/livepatch/test_klp_convert_mod_b.c        |  19 +
 lib/livepatch/test_klp_convert_mod_c.c        |  36 +
 lib/livepatch/test_klp_convert_sections.c     | 120 +++
 samples/livepatch/Makefile                    |   1 +
 .../livepatch/livepatch-annotated-sample.c    |  93 ++
 scripts/Makefile                              |   1 +
 scripts/Makefile.modfinal                     |  38 +-
 scripts/Makefile.modpost                      |   5 +
 scripts/livepatch/.gitignore                  |   1 +
 scripts/livepatch/Makefile                    |   5 +
 scripts/livepatch/elf.c                       | 813 ++++++++++++++++
 scripts/livepatch/elf.h                       |  74 ++
 scripts/livepatch/klp-convert.c               | 885 ++++++++++++++++++
 scripts/livepatch/klp-convert.h               |  47 +
 scripts/livepatch/list.h                      | 391 ++++++++
 scripts/mod/modpost.c                         |  28 +-
 scripts/mod/modpost.h                         |   1 +
 .../selftests/livepatch/test-livepatch.sh     | 405 ++++++++
 35 files changed, 3708 insertions(+), 11 deletions(-)
 create mode 100644 include/uapi/linux/livepatch.h
 create mode 100644 lib/livepatch/test_klp_convert.h
 create mode 100644 lib/livepatch/test_klp_convert1.c
 create mode 100644 lib/livepatch/test_klp_convert2.c
 create mode 100644 lib/livepatch/test_klp_convert_data.c
 create mode 100644 lib/livepatch/test_klp_convert_keys.c
 create mode 100644 lib/livepatch/test_klp_convert_keys_mod.c
 create mode 100644 lib/livepatch/test_klp_convert_mod_a.c
 create mode 100644 lib/livepatch/test_klp_convert_mod_b.c
 create mode 100644 lib/livepatch/test_klp_convert_mod_c.c
 create mode 100644 lib/livepatch/test_klp_convert_sections.c
 create mode 100644 samples/livepatch/livepatch-annotated-sample.c
 create mode 100644 scripts/livepatch/.gitignore
 create mode 100644 scripts/livepatch/Makefile
 create mode 100644 scripts/livepatch/elf.c
 create mode 100644 scripts/livepatch/elf.h
 create mode 100644 scripts/livepatch/klp-convert.c
 create mode 100644 scripts/livepatch/klp-convert.h
 create mode 100644 scripts/livepatch/list.h
Signature · 1 line
2.26.3
author maintainer
#1 lore raw

RFC PATCH v6 1/12 livepatch: Create and include UAPI headers

From: Josh Poimboeuf <[email protected]>

Define klp prefixes in include/uapi/linux/livepatch.h, and use them for replacing hard-coded values in kernel/livepatch/core.c.

Update MAINTAINERS.

Note: Add defines to uapi as these are also to be used by a newly introduced klp-convert script.

---
 MAINTAINERS                    |  1 +
 include/linux/livepatch.h      |  1 +
 include/uapi/linux/livepatch.h | 15 +++++++++++++++
 kernel/livepatch/core.c        |  4 ++--
 4 files changed, 19 insertions(+), 2 deletions(-)
 create mode 100644 include/uapi/linux/livepatch.h
MAINTAINERS +1 -0
index f41088418aae..3fce79715663 100644
@@ -11132,6 +11132,7 @@ F:	arch/powerpc/include/asm/livepatch.h
 F:	arch/s390/include/asm/livepatch.h
 F:	arch/x86/include/asm/livepatch.h
 F:	include/linux/livepatch.h
+F:	include/uapi/linux/livepatch.h
 F:	kernel/livepatch/
 F:	lib/livepatch/
 F:	samples/livepatch/
include/linux/livepatch.h +1 -0
index 2614247a9781..0fb05aae091a 100644
@@ -13,6 +13,7 @@
 #include <linux/ftrace.h>
 #include <linux/completion.h>
 #include <linux/list.h>
+#include <uapi/linux/livepatch.h>
 
 #if IS_ENABLED(CONFIG_LIVEPATCH)
 
include/uapi/linux/livepatch.h new file +15 -0
new file mode 100644
index 000000000000..e19430918a07
@@ -0,0 +1,15 @@
+/* SPDX-License-Identifier: GPL-2.0 WITH Linux-syscall-note */
+
+/*
+ * livepatch.h - Kernel Live Patching Core
+ *
+ * Copyright (C) 2016 Josh Poimboeuf <[email protected]>
+ */
+
+#ifndef _UAPI_LIVEPATCH_H
+#define _UAPI_LIVEPATCH_H
+
+#define KLP_RELA_PREFIX		".klp.rela."
+#define KLP_SYM_PREFIX		".klp.sym."
+
+#endif /* _UAPI_LIVEPATCH_H */
kernel/livepatch/core.c +2 -2
index 585494ec464f..79b380777a0b 100644
@@ -227,7 +227,7 @@ static int klp_resolve_symbols(Elf64_Shdr *sechdrs, const char *strtab,
 
 		/* Format: .klp.sym.sym_objname.sym_name,sympos */
 		cnt = sscanf(strtab + sym->st_name,
-			     ".klp.sym.%55[^.].%127[^,],%lu",
+			     KLP_SYM_PREFIX "%55[^.].%127[^,],%lu",
 			     sym_objname, sym_name, &sympos);
 		if (cnt != 3) {
 			pr_err("symbol %s has an incorrectly formatted name\n",
@@ -298,7 +298,7 @@ int klp_apply_section_relocs(struct module *pmod, Elf_Shdr *sechdrs,
 	 * See comment in klp_resolve_symbols() for an explanation
 	 * of the selected field width value.
 	 */
-	cnt = sscanf(shstrtab + sec->sh_name, ".klp.rela.%55[^.]",
+	cnt = sscanf(shstrtab + sec->sh_name, KLP_RELA_PREFIX "%55[^.]",
 		     sec_objname);
 	if (cnt != 1) {
 		pr_err("section %s has an incorrectly formatted name\n",
Signature · 1 line
2.26.3
maintainer Reviewed-by on v6 1/12
#2 lore raw

Re: [RFC PATCH v6 01/12] livepatch: Create and include UAPI headers

Quoted 5 lines · Joe Lawrence

From: Josh Poimboeuf <[email protected]>

Define klp prefixes in include/uapi/linux/livepatch.h, and use them for replacing hard-coded values in kernel/livepatch/core.c.

Quoted 8 lines

Update MAINTAINERS.

Note: Add defines to uapi as these are also to be used by a newly introduced klp-convert script.

Looks straightforward:

Best Regards,
Petr

author maintainer
#3 lore raw

RFC PATCH v6 2/12 kbuild: Support for symbols.klp creation

In reply to Joe Lawrence

From: Joao Moreira <[email protected]>

For automatic resolution of livepatch relocations, a file called symbols.klp is used. This file maps symbols within every compiled kernel object allowing the identification of symbols whose name is unique, thus relocation can be automatically inferred, or providing information that helps developers when code annotation is required for solving the matter.

Add support for creating symbols.klp in the main Makefile. First, ensure that built-in is compiled when CONFIG_LIVEPATCH is enabled (as required to achieve a complete symbols.klp file). Define the command to build symbols.klp (cmd_klp_map) and hook it in the modules rule.

As it is undesirable to have symbols from livepatch objects inside symbols.klp, make livepatches discernible by modifying scripts/Makefile.build to create a .livepatch file for each livepatch in $(MODVERDIR). This file then used by cmd_klp_map to identify and bypass livepatches.

For identifying livepatches during the build process, a flag variable LIVEPATCH_$(basetarget).o is considered in scripts/Makefile.build. This way, set this flag for the livepatch sample Makefile in samples/livepatch/Makefile.

Finally, Add a clean rule to ensure that symbols.klp is removed during clean.

Notes:

To achieve a correct symbols.klp file, all kernel objects must be considered, thus, its construction require these objects to be priorly built. On the other hand, invoking scripts/Makefile.modpost without having a complete symbols.klp in place would occasionally lead to in-tree livepatches being post-processed incorrectly. To prevent this from becoming a circular dependency, the construction of symbols.klp uses non-post-processed kernel objects and such does not cause harm as the symbols normally referenced from within livepatches are visible at this stage. Also due to these requirements, the spot in-between modules compilation and the invocation of scripts/Makefile.modpost was picked for hooking cmd_klp_map.

The approach based on .livepatch files was proposed as an alternative to using MODULE_INFO statements. This approach was originally proposed by Miroslav Benes as a workaround for identifying livepathes without depending on modinfo during the modpost stage. It was moved to this patch as the approach also shown to be useful while building symbols.klp.

---
 .gitignore             |  1 +
 Documentation/dontdiff |  1 +
 Makefile               | 24 ++++++++++++++++++++++--
 3 files changed, 24 insertions(+), 2 deletions(-)
.gitignore +1 -0
index 7afd412dadd2..50638a15a527 100644
@@ -61,6 +61,7 @@ modules.order
 /vmlinux.symvers
 /vmlinux-gdb.py
 /vmlinuz
+/symbols.klp
 /System.map
 /Module.markers
 /modules.builtin
Documentation/dontdiff +1 -0
index 910b30a2a7d9..25c656fdd99f 100644
@@ -76,6 +76,7 @@ Module.markers
 Module.symvers
 PENDING
 SCCS
+symbols.klp
 System.map*
 TAGS
 aconf
Makefile +22 -2
index 0fb4f94a6885..64ec4bc8172c 100644
@@ -639,8 +639,13 @@ KBUILD_MODULES :=
 KBUILD_BUILTIN := 1
 
 # If we have only "make modules", don't compile built-in objects.
+# When we're building livepatch modules, we need to consider the
+# built-in objects during the descend as well, as built-in objects may
+# hold symbols which are referenced from livepatches and are required by
+# klp-convert post-processing tool for resolving these cases.
+
 ifeq ($(MAKECMDGOALS),modules)
-  KBUILD_BUILTIN :=
+  KBUILD_BUILTIN := $(if $(CONFIG_LIVEPATCH),1)
 endif
 
 # If we have "make <whatever> modules", compile modules
@@ -1487,7 +1492,7 @@ MRPROPER_FILES += include/config include/generated          \
 		  arch/$(SRCARCH)/include/generated .tmp_objdiff \
 		  debian snap tar-install \
 		  .config .config.old .version \
-		  Module.symvers \
+		  Module.symvers symbols.klp \
 		  certs/signing_key.pem \
 		  certs/x509.genkey \
 		  vmlinux-gdb.py \
@@ -1742,7 +1747,22 @@ PHONY += modules modules_install
 
 ifdef CONFIG_MODULES
 
+quiet_cmd_klp_map = KLP     symbols.klp
+
+define cmd_klp_map
+	$(shell echo "klp-convert-symbol-data.0.1" > $(objtree)/symbols.klp)				\
+	$(shell echo "*vmlinux" >> $(objtree)/symbols.klp)						\
+	$(shell nm -f posix $(objtree)/vmlinux | cut -d\  -f1 >> $(objtree)/symbols.klp)		\
+	$(foreach ko, $(sort $(shell cat modules.order)),						\
+		$(eval mod = $(patsubst %.ko,%.mod,$(ko)))						\
+		$(eval obj = $(patsubst %.ko,%.o,$(ko)))						\
+		$(if $(shell grep -o LIVEPATCH $(mod)),,						\
+			$(shell echo "*$(shell basename -s .ko $(ko))" >> $(objtree)/symbols.klp)	\
+			$(shell nm -f posix $(obj) | cut -d\  -f1 >> $(objtree)/symbols.klp)))
+endef
+
 modules: modules_check
+	$(if $(CONFIG_LIVEPATCH), $(call cmd,klp_map))
 	$(Q)$(MAKE) -f $(srctree)/scripts/Makefile.modpost
 
 PHONY += modules_check
Signature · 1 line
2.26.3
maintainer
#4 lore raw

Re: [RFC PATCH v6 02/12] kbuild: Support for symbols.klp creation

Quoted 20 lines · Joe Lawrence

From: Joao Moreira <[email protected]>

For automatic resolution of livepatch relocations, a file called symbols.klp is used. This file maps symbols within every compiled kernel object allowing the identification of symbols whose name is unique, thus relocation can be automatically inferred, or providing information that helps developers when code annotation is required for solving the matter.

Add support for creating symbols.klp in the main Makefile. First, ensure that built-in is compiled when CONFIG_LIVEPATCH is enabled (as required to achieve a complete symbols.klp file). Define the command to build symbols.klp (cmd_klp_map) and hook it in the modules rule.

As it is undesirable to have symbols from livepatch objects inside symbols.klp, make livepatches discernible by modifying scripts/Makefile.build to create a .livepatch file for each livepatch in $(MODVERDIR). This file then used by cmd_klp_map to identify and bypass livepatches.

Quoted 4 lines

For identifying livepatches during the build process, a flag variable LIVEPATCH_$(basetarget).o is considered in scripts/Makefile.build. This way, set this flag for the livepatch sample Makefile in samples/livepatch/Makefile.

I do not see the related code in scripts/Makefile.build.

Quoted 10 lines

Finally, Add a clean rule to ensure that symbols.klp is removed during clean.

Notes:

To achieve a correct symbols.klp file, all kernel objects must be considered, thus, its construction require these objects to be priorly built. On the other hand, invoking scripts/Makefile.modpost without having a complete symbols.klp in place would occasionally lead to in-tree livepatches being post-processed incorrectly.

Honestly, I do not understand what it exactly means that "in-tree livepatches would occasionally be post-processed incorrectly".

Is it the problem that modpost is not able to handle the unresolved symbols that have to be updated by klp-convert?

Quoted 8 lines

To prevent this
from becoming a circular dependency, the construction of symbols.klp uses non-post-processed kernel objects and such does not cause harm as the symbols normally referenced from within livepatches are visible at this stage. Also due to these requirements, the spot in-between modules compilation and the invocation of scripts/Makefile.modpost was picked for hooking cmd_klp_map.

Quoted 6 lines

The approach based on .livepatch files was proposed as an alternative to using MODULE_INFO statements. This approach was originally proposed by Miroslav Benes as a workaround for identifying livepathes without depending on modinfo during the modpost stage. It was moved to this patch as the approach also shown to be useful while building symbols.klp.

All the tricky code is removed in the 5th patch. My understanding is that the problem causing the cyclic dependency is solved by modifying modpost.

It looks like this patch is outdated and mostly obsoleted. On the other hand, the commit message in 5th patch is too short.

What about merging the two patches and updating the commit message?

Best Regards,
Petr

#5 lore raw

Re: [RFC PATCH v6 02/12] kbuild: Support for symbols.klp creation

Quoted 60 lines · On Thu, Apr 14, 2022 at 11:35:42AM +0200 Petr Mladek wrote:
Quoted 20 lines · Joe Lawrence

From: Joao Moreira <[email protected]>

For automatic resolution of livepatch relocations, a file called symbols.klp is used. This file maps symbols within every compiled kernel object allowing the identification of symbols whose name is unique, thus relocation can be automatically inferred, or providing information that helps developers when code annotation is required for solving the matter.

Add support for creating symbols.klp in the main Makefile. First, ensure that built-in is compiled when CONFIG_LIVEPATCH is enabled (as required to achieve a complete symbols.klp file). Define the command to build symbols.klp (cmd_klp_map) and hook it in the modules rule.

As it is undesirable to have symbols from livepatch objects inside symbols.klp, make livepatches discernible by modifying scripts/Makefile.build to create a .livepatch file for each livepatch in $(MODVERDIR). This file then used by cmd_klp_map to identify and bypass livepatches.

Quoted 4 lines

For identifying livepatches during the build process, a flag variable LIVEPATCH_$(basetarget).o is considered in scripts/Makefile.build. This way, set this flag for the livepatch sample Makefile in samples/livepatch/Makefile.

I do not see the related code in scripts/Makefile.build.

Quoted 10 lines

Finally, Add a clean rule to ensure that symbols.klp is removed during clean.

Notes:

To achieve a correct symbols.klp file, all kernel objects must be considered, thus, its construction require these objects to be priorly built. On the other hand, invoking scripts/Makefile.modpost without having a complete symbols.klp in place would occasionally lead to in-tree livepatches being post-processed incorrectly.

Honestly, I do not understand what it exactly means that "in-tree livepatches would occasionally be post-processed incorrectly".

Is it the problem that modpost is not able to handle the unresolved symbols that have to be updated by klp-convert?

Quoted 8 lines

To prevent this
from becoming a circular dependency, the construction of symbols.klp uses non-post-processed kernel objects and such does not cause harm as the symbols normally referenced from within livepatches are visible at this stage. Also due to these requirements, the spot in-between modules compilation and the invocation of scripts/Makefile.modpost was picked for hooking cmd_klp_map.

Quoted 6 lines

The approach based on .livepatch files was proposed as an alternative to using MODULE_INFO statements. This approach was originally proposed by Miroslav Benes as a workaround for identifying livepathes without depending on modinfo during the modpost stage. It was moved to this patch as the approach also shown to be useful while building symbols.klp.

Quoted 8 lines

All the tricky code is removed in the 5th patch. My understanding is that the problem causing the cyclic dependency is solved by modifying modpost.

It looks like this patch is outdated and mostly obsoleted. On the other hand, the commit message in 5th patch is too short.

What about merging the two patches and updating the commit message?

+1

Yes, please merge those patches. These '$(shell ...)' side-effect lines in the definition of 'cmd_klp_map' are quite confusing.

Kind regards,
Nicolas

author maintainer
#6 lore raw

Re: [RFC PATCH v6 02/12] kbuild: Support for symbols.klp creation

Quoted 68 lines · Nicolas Schier
Quoted 67 lines · On Thu, Apr 14, 2022 at 11:35:42AM +0200 Petr Mladek wrote:
Quoted 20 lines · Joe Lawrence

From: Joao Moreira <[email protected]>

For automatic resolution of livepatch relocations, a file called symbols.klp is used. This file maps symbols within every compiled kernel object allowing the identification of symbols whose name is unique, thus relocation can be automatically inferred, or providing information that helps developers when code annotation is required for solving the matter.

Add support for creating symbols.klp in the main Makefile. First, ensure that built-in is compiled when CONFIG_LIVEPATCH is enabled (as required to achieve a complete symbols.klp file). Define the command to build symbols.klp (cmd_klp_map) and hook it in the modules rule.

As it is undesirable to have symbols from livepatch objects inside symbols.klp, make livepatches discernible by modifying scripts/Makefile.build to create a .livepatch file for each livepatch in $(MODVERDIR). This file then used by cmd_klp_map to identify and bypass livepatches.

Quoted 4 lines

For identifying livepatches during the build process, a flag variable LIVEPATCH_$(basetarget).o is considered in scripts/Makefile.build. This way, set this flag for the livepatch sample Makefile in samples/livepatch/Makefile.

I do not see the related code in scripts/Makefile.build.

Quoted 10 lines

Finally, Add a clean rule to ensure that symbols.klp is removed during clean.

Notes:

To achieve a correct symbols.klp file, all kernel objects must be considered, thus, its construction require these objects to be priorly built. On the other hand, invoking scripts/Makefile.modpost without having a complete symbols.klp in place would occasionally lead to in-tree livepatches being post-processed incorrectly.

Honestly, I do not understand what it exactly means that "in-tree livepatches would occasionally be post-processed incorrectly".

Is it the problem that modpost is not able to handle the unresolved symbols that have to be updated by klp-convert?

Quoted 8 lines

To prevent this
from becoming a circular dependency, the construction of symbols.klp uses non-post-processed kernel objects and such does not cause harm as the symbols normally referenced from within livepatches are visible at this stage. Also due to these requirements, the spot in-between modules compilation and the invocation of scripts/Makefile.modpost was picked for hooking cmd_klp_map.

Quoted 6 lines

The approach based on .livepatch files was proposed as an alternative to using MODULE_INFO statements. This approach was originally proposed by Miroslav Benes as a workaround for identifying livepathes without depending on modinfo during the modpost stage. It was moved to this patch as the approach also shown to be useful while building symbols.klp.

All the tricky code is removed in the 5th patch. My understanding is that the problem causing the cyclic dependency is solved by modifying modpost.

It looks like this patch is outdated and mostly obsoleted. On the other hand, the commit message in 5th patch is too short.

Quoted 7 lines
Quoted 1 line

What about merging the two patches and updating the commit message?

+1

Yes, please merge those patches. These '$(shell ...)' side-effect lines in the definition of 'cmd_klp_map' are quite confusing.

Sure. Admittedly the kbuild integration is most confusing to me, so I leaned heavily on Joao's original notes and Masahiro's gracious tips and refactored code. I'll try cutting to the final version in later patches rather than providing all the (confusing) code evolution along the way.

Thanks,

-- Joe

author maintainer
#7 lore raw

RFC PATCH v6 3/12 livepatch: Add klp-convert tool

In reply to Joe Lawrence

From: Josh Poimboeuf <[email protected]>

Livepatches may use symbols which are not contained in its own scope, and, because of that, may end up compiled with relocations that will only be resolved during module load. Yet, when the referenced symbols are not exported, solving this relocation requires information on the object that holds the symbol (either vmlinux or modules) and its position inside the object, as an object may contain multiple symbols with the same name. Providing such information must be done accordingly to what is specified in Documentation/livepatch/module-elf-format.txt.

Currently, there is no trivial way to embed the required information as requested in the final livepatch elf object. klp-convert solves this problem in two different forms: (i) by relying on symbols.klp, which is built during kernel compilation, to automatically infer the relocation targeted symbol, and, when such inference is not possible (ii) by using annotations in the elf object to convert the relocation accordingly to the specification, enabling it to be handled by the livepatch loader.

Given the above, create scripts/livepatch to hold tools developed for livepatches and add source files for klp-convert there.

The core file of klp-convert is scripts/livepatch/klp-convert.c, which implements the heuristics used to solve the relocations and the conversion of unresolved symbols into the expected format, as defined in [1].

klp-convert receives as arguments the symbols.klp file, an input livepatch module to be converted and the output name for the converted livepatch. When it starts running, klp-convert parses symbols.klp and builds two internal lists of symbols, one containing the exported and another containing the non-exported symbols. Then, by parsing the rela sections in the elf object, klp-convert identifies which symbols must be converted, which are those unresolved and that do not have a corresponding exported symbol, and attempts to convert them accordingly to the specification.

By using symbols.klp, klp-convert identifies which symbols have names that only appear in a single kernel object, thus being capable of resolving these cases without the intervention of the developer. When various homonymous symbols exist through kernel objects, it is not possible to infer the right one, thus klp-convert falls back into using developer annotations. If these were not provided, then the tool will print a list with all acceptable targets for the symbol being processed.

Annotations in the context of klp-convert are accessible as struct klp_module_reloc entries in sections named .klp.module_relocs.<objname>. These entries are pairs of symbol references and positions which are to be resolved against definitions in <objname>.

Define the structure klp_module_reloc in include/linux/uapi/livepatch.h allowing developers to annotate the livepatch source code with it.

klp-convert relies on libelf and on a list implementation. Add files scripts/livepatch/elf.c and scripts/livepatch/elf.h, which are a libelf interfacing layer and scripts/livepatch/list.h, which is a list implementation.

Update Makefiles to correctly support the compilation of the new tool, update MAINTAINERS file and add a .gitignore file.

[1] - Documentation/livepatch/module-elf-format.txt

---
 MAINTAINERS                     |   1 +
 include/uapi/linux/livepatch.h  |  10 +
 scripts/Makefile                |   1 +
 scripts/livepatch/.gitignore    |   1 +
 scripts/livepatch/Makefile      |   5 +
 scripts/livepatch/elf.c         | 813 +++++++++++++++++++++++++++++
 scripts/livepatch/elf.h         |  74 +++
 scripts/livepatch/klp-convert.c | 885 ++++++++++++++++++++++++++++++++
 scripts/livepatch/klp-convert.h |  47 ++
 scripts/livepatch/list.h        | 391 ++++++++++++++
 10 files changed, 2228 insertions(+)
 create mode 100644 scripts/livepatch/.gitignore
 create mode 100644 scripts/livepatch/Makefile
 create mode 100644 scripts/livepatch/elf.c
 create mode 100644 scripts/livepatch/elf.h
 create mode 100644 scripts/livepatch/klp-convert.c
 create mode 100644 scripts/livepatch/klp-convert.h
 create mode 100644 scripts/livepatch/list.h
MAINTAINERS +1 -0
index 3fce79715663..a25a5dad12b6 100644
@@ -11136,6 +11136,7 @@ F:	include/uapi/linux/livepatch.h
 F:	kernel/livepatch/
 F:	lib/livepatch/
 F:	samples/livepatch/
+F:	scripts/livepatch/
 F:	tools/testing/selftests/livepatch/
 
 LLC (802.2)
include/uapi/linux/livepatch.h +10 -0
index e19430918a07..2ee98e985c2a 100644
@@ -9,7 +9,17 @@
 #ifndef _UAPI_LIVEPATCH_H
 #define _UAPI_LIVEPATCH_H
 
+#include <linux/types.h>
+
 #define KLP_RELA_PREFIX		".klp.rela."
 #define KLP_SYM_PREFIX		".klp.sym."
 
+struct klp_module_reloc {
+	union {
+		void *sym;
+		__u64 sym64;	/* Force 64-bit width */
+	};
+	__u32 sympos;
+} __packed;
+
 #endif /* _UAPI_LIVEPATCH_H */
scripts/Makefile +1 -0
index ce5aa9030b74..5e2c71b4b1e0 100644
@@ -38,6 +38,7 @@ targets += module.lds
 subdir-$(CONFIG_GCC_PLUGINS) += gcc-plugins
 subdir-$(CONFIG_MODVERSIONS) += genksyms
 subdir-$(CONFIG_SECURITY_SELINUX) += selinux
+subdir-$(CONFIG_LIVEPATCH)   += livepatch
 
 # Let clean descend into subdirs
 subdir-	+= basic dtc gdb kconfig mod
scripts/livepatch/.gitignore new file +1 -0
new file mode 100644
index 000000000000..dc22fe4b6a5b
@@ -0,0 +1 @@
+klp-convert
scripts/livepatch/Makefile new file +5 -0
new file mode 100644
index 000000000000..71dce0f3e893
@@ -0,0 +1,5 @@
+hostprogs-always-y		:= klp-convert
+
+klp-convert-objs		:= klp-convert.o elf.o
+
+HOSTLDLIBS_klp-convert		:= -lelf
scripts/livepatch/elf.c new file +813 -0

813 lines not on this page · raw message

scripts/livepatch/elf.h new file +74 -0

74 lines not on this page · raw message

scripts/livepatch/klp-convert.c new file +885 -0

885 lines not on this page · raw message

scripts/livepatch/klp-convert.h new file +47 -0

47 lines not on this page · raw message

scripts/livepatch/list.h new file +391 -0

391 lines not on this page · raw message

Signature · 1 line
2.26.3
author maintainer
#8 lore raw

Re: [RFC PATCH v6 03/12] livepatch: Add klp-convert tool

Quoted 34 lines · Joe Lawrence

[ ... snip ... ]

scripts/livepatch/klp-convert.c new file +31 -0
+/*
+ * Checks if rela conversion is supported in given section
+ */
+static bool supported_section(struct section *sec, char *object_name)
+{
+#if 0
+	/*
+	 * klp-relocations forbidden in sections that otherwise would
+	 * match in allowed_prefixes[]
+	 */
+	static const char * const not_allowed[] = {
+		".rela.data.rel.ro",
+		".rela.data.rel.ro.local",
+		".rela.data..ro_after_init",
+		NULL
+	};
+#endif
+
+	/* klp-relocations allowed in sections only for vmlinux */
+	static const char * const allowed_vmlinux[] = {
+		".rela__jump_table",
+		NULL
+	};
+
+	/* klp-relocations allowed in sections with prefixes */
+	static const char * const allowed_prefixes[] = {
+		".rela.data",
+		".rela.rodata",	// supported ???
+		".rela.sdata",
+		".rela.text",
+		".rela.toc",

scripts/livepatch/klp-convert.c line 752

Quoted 10 lines
scripts/livepatch/klp-convert.c new file +10 -0
+		NULL
+	};
+
+	const char * const *name;
+
+#if 0
+	for (name = not_allowed; *name; name++)
+		if (strcmp(sec->name, *name) == 0)
+			return false;
+#endif

I wasn't sure if relocations in .rela.<read-only> sections should be supported or not, particularly in the late relocation use case. For most, I think they can be easily avoided by the livepatch author changing the storage class for the C pointer that is relocated. On the other hand, this may be disruptive to automated tools like kpatch-build... or maybe there is no issue at all for late relocating .rela.<read-only>?

-- Joe

author maintainer
#9 lore raw

Re: [RFC PATCH v6 03/12] livepatch: Add klp-convert tool

In reply to Joe Lawrence
Quoted 29 lines · Joe Lawrence
include/uapi/linux/livepatch.h +10 -0
index e19430918a07..2ee98e985c2a 100644
@@ -9,7 +9,17 @@
 #ifndef _UAPI_LIVEPATCH_H
 #define _UAPI_LIVEPATCH_H
 
+#include <linux/types.h>
+
 #define KLP_RELA_PREFIX		".klp.rela."
 #define KLP_SYM_PREFIX		".klp.sym."
 
+struct klp_module_reloc {
+	union {
+		void *sym;
+		__u64 sym64;	/* Force 64-bit width */
+	};
+	__u32 sympos;
+} __packed;
+
 
[ ... snip ... ]
scripts/livepatch/klp-convert.h new file +0 -0
new file mode 100644
index 000000000000..35b9dc4e32c4

scripts/livepatch/klp-convert.h line 47

Quoted 10 lines
scripts/livepatch/klp-convert.h new file +7 -0
 
[ ... snip ... ]
 
+struct klp_module_reloc {
+	union {
+		void *sym;
+		uint64_t sym64;	/* Force 64-bit width */
+	};
+	uint32_t sympos;
+} __packed;

This was a hack I added to force a consistent width for the symbol pointer in case the user was building for 32-bit. The actual void *sym64 value itself is not so interesting as it's only needed for the compiler to create a relocation (later resolved by klp-convert). That said, sympos is used by klp-convert, and I bet it's not endian-safe here.

Better suggestions welcome :)

-- Joe

maintainer
#10 lore raw

elf API: was: Re: [RFC PATCH v6 03/12] livepatch: Add klp-convert tool

In reply to Joe Lawrence
Quoted 41 lines · Joe Lawrence

From: Josh Poimboeuf <[email protected]>
klp-convert relies on libelf and on a list implementation. Add files scripts/livepatch/elf.c and scripts/livepatch/elf.h, which are a libelf interfacing layer and scripts/livepatch/list.h, which is a list implementation.

scripts/livepatch/elf.c new file +33 -0
+static int update_shstrtab(struct elf *elf)
+{
+	struct section *shstrtab, *sec;
+	size_t orig_size, new_size = 0, offset, len;
+	char *buf;
+
+	shstrtab = find_section_by_name(elf, ".shstrtab");
+	if (!shstrtab) {
+		WARN("can't find .shstrtab");
+		return -1;
+	}
+
+	orig_size = new_size = shstrtab->size;
+
+	list_for_each_entry(sec, &elf->sections, list) {
+		if (sec->sh.sh_name != -1)
+			continue;
+		new_size += strlen(sec->name) + 1;
+	}
+
+	if (new_size == orig_size)
+		return 0;
+
+	buf = malloc(new_size);
+	if (!buf) {
+		WARN("malloc failed");
+		return -1;
+	}
+	memcpy(buf, (void *)shstrtab->data, orig_size);
+
+	offset = orig_size;
+	list_for_each_entry(sec, &elf->sections, list) {
+		if (sec->sh.sh_name != -1)

scripts/livepatch/elf.c line 346

Quoted 10 lines
scripts/livepatch/elf.c new file +10 -0
+			continue;
+		sec->sh.sh_name = offset;
+		len = strlen(sec->name) + 1;
+		memcpy(buf + offset, sec->name, len);
+		offset += len;
+	}
+
+	shstrtab->elf_data->d_buf = shstrtab->data = buf;
+	shstrtab->elf_data->d_size = shstrtab->size = new_size;
+	shstrtab->sh.sh_size = new_size;

All the update_*() functions have the same pattern. They replace the original buffer with a bigger one when needed. And the pointer to the original buffer gets lost.

I guess that the original buffer could not be freed because it is part of a bigger allocated blob. Or it might even be a file mapped to memory.

It looks like a memory leak. We could probably ignore it. But there is another related danger, see below.

Quoted 3 lines
scripts/livepatch/elf.c new file +3 -0
+	return 1;
+}
+

[...]

scripts/livepatch/elf.c line 698

Quoted 6 lines
scripts/livepatch/elf.c new file +6 -0
+int elf_write_file(struct elf *elf, const char *file)
+{
+	int ret_shstrtab;
+	int ret_strtab;
+	int ret_symtab;
+	int ret_relas;

We do not free the bigger buffers when something goes wrong. Also this is not that important. But it is easy to fix:

We might do:

	int ret_shstrtab = 0;
	int ret_strtab = 0;
	int ret_symtab = 0;
	int ret_relas = 0;

scripts/livepatch/elf.c line 707

Quoted 9 lines
scripts/livepatch/elf.c new file +9 -0
+	int ret;
+
+	ret_shstrtab = update_shstrtab(elf);
+	if (ret_shstrtab < 0)
+		return ret_shstrtab;
+
+	ret_strtab = update_strtab(elf);
+	if (ret_strtab < 0)
+		return ret_strtab;
	if (ret_strtab < 0) {
		ret = ret_strtab;
		goto out;
	}

scripts/livepatch/elf.c line 711

Quoted 3 lines
scripts/livepatch/elf.c new file +3 -0
+	ret_symtab = update_symtab(elf);
+	if (ret_symtab < 0)
+		return ret_symtab;
	if (ret_symtab < 0) {
		ret = ret_symtab;
		goto out;
	}

scripts/livepatch/elf.c line 715

Quoted 3 lines
scripts/livepatch/elf.c new file +3 -0
+	ret_relas = update_relas(elf);
+	if (ret_relas < 0)
+		return ret_relas;
	if (ret_relas < 0) {
		ret = ret_relas;
		goto out;
	}

scripts/livepatch/elf.c line 721

Quoted 5 lines
scripts/livepatch/elf.c new file +5 -0
+	update_groups(elf);
+
+	ret = write_file(elf, file);
+	if (ret)
+		return ret;

Continue even when write_file(elf, file) returns an error.

out:

scripts/livepatch/elf.c

Quoted 10 lines
scripts/livepatch/elf.c new file +10 -0
+	if (ret_relas > 0)
+		free_relas(elf);
+	if (ret_symtab > 0)
+		free_symtab(elf);
+	if (ret_strtab > 0)
+		free_strtab(elf);
+	if (ret_shstrtab > 0)
+		free_shstrtab(elf);
+
+	return ret;

Another problem is that the free_*() functions release the bigger buffers. But they do not put back the original ones. Also all the updated offsets and indexes point to the bigger buffers. As a result the structures can't be made consistent any longer.

I am not sure if there is an easy way to fix it. IMHO, proper solution is not worth a big effort. klp-convert frees everthing after writing the elf file.

Well, we should at least make a comment above elf_write_file() about that the structures are damaged in this way.

Finally, my main concern:

It brings a question whether the written data were consistent.

I am not familiar with the elf format. I quess that it is rather stable. But there might still be some differences between architectures or some new extensions that might need special handing.

I do not see any big consistency checks in the gelf_update_ehdr(), elf_update(), or elf_end() functions that are used when writing the changes.

But there seems to be some thorough consistency checks provided by:

    readelf --enable-checks

It currently see these warnings:

$> readelf --lint lib/livepatch/test_klp_convert2.ko >/dev/null
readelf: Warning: Section '.note.GNU-stack': has a size of zero - is this intended ?

$> readelf --lint lib/livepatch/test_klp_callbacks_mod.ko >/dev/null
readelf: Warning: Section '.data': has a size of zero - is this intended ?
readelf: Warning: Section '.note.GNU-stack': has a size of zero - is this intended ?

$> readelf --lint lib/test_printf.ko >/dev/null
readelf: Warning: Section '.text': has a size of zero - is this intended ?
readelf: Warning: Section '.data': has a size of zero - is this intended ?
readelf: Warning: Section '.note.GNU-stack': has a size of zero - is this intended ?

But I see this warnings even without this patchset. I wonder if it might really help to find problems introduced by klp-convert or if it would be a waste of time.

Best Regards,
Petr

author maintainer
#11 lore raw

Re: elf API: was: Re: [RFC PATCH v6 03/12] livepatch: Add klp-convert tool

Quoted 57 lines · Petr Mladek
Quoted 41 lines · Joe Lawrence

From: Josh Poimboeuf <[email protected]>
klp-convert relies on libelf and on a list implementation. Add files scripts/livepatch/elf.c and scripts/livepatch/elf.h, which are a libelf interfacing layer and scripts/livepatch/list.h, which is a list implementation.

scripts/livepatch/elf.c new file +33 -0
+static int update_shstrtab(struct elf *elf)
+{
+	struct section *shstrtab, *sec;
+	size_t orig_size, new_size = 0, offset, len;
+	char *buf;
+
+	shstrtab = find_section_by_name(elf, ".shstrtab");
+	if (!shstrtab) {
+		WARN("can't find .shstrtab");
+		return -1;
+	}
+
+	orig_size = new_size = shstrtab->size;
+
+	list_for_each_entry(sec, &elf->sections, list) {
+		if (sec->sh.sh_name != -1)
+			continue;
+		new_size += strlen(sec->name) + 1;
+	}
+
+	if (new_size == orig_size)
+		return 0;
+
+	buf = malloc(new_size);
+	if (!buf) {
+		WARN("malloc failed");
+		return -1;
+	}
+	memcpy(buf, (void *)shstrtab->data, orig_size);
+
+	offset = orig_size;
+	list_for_each_entry(sec, &elf->sections, list) {
+		if (sec->sh.sh_name != -1)

scripts/livepatch/elf.c line 346

Quoted 10 lines
scripts/livepatch/elf.c new file +10 -0
+			continue;
+		sec->sh.sh_name = offset;
+		len = strlen(sec->name) + 1;
+		memcpy(buf + offset, sec->name, len);
+		offset += len;
+	}
+
+	shstrtab->elf_data->d_buf = shstrtab->data = buf;
+	shstrtab->elf_data->d_size = shstrtab->size = new_size;
+	shstrtab->sh.sh_size = new_size;

All the update_*() functions have the same pattern. They replace the original buffer with a bigger one when needed. And the pointer to the original buffer gets lost.

Quoted 7 lines

I guess that the original buffer could not be freed because it is part of a bigger allocated blob. Or it might even be a file mapped to memory.

It looks like a memory leak. We could probably ignore it. But there is another related danger, see below.

Hi Petr,

Looking at this code, I would agree that it looks very suspicious with respect to leaking memory. Then I remembered that I had been testing with valgrind and it hadn't reported any lost allocations.

I was confused, so to verify, I fired up gdb with conditional breakpoints (when the passed pointer was one of the clobbered X-Y->d_buf pointers) on glibc's __GI___libc_free() and found that these buffers were all handled by libelf's elf_end() function:

	/* The section data is allocated if we couldn't mmap
	   the file.  */
	if (elf->map_address == NULL)
	  free (scn->rawdata_base);

The program, in the name of efficiency or developer expediency (I dunno, I didn't create it), ends up creating a few file representations:

1) libelf's internal representation of the input ELF file
2) klp-convert's structures (see elf.h)
a) derived from the previous (1)
b) modified for klp-relocations
3) klp-convert's new Elf structure for the output ELF file (see write_file())
a) information from (2b) is used to create consistent structures

And so representation (2) ends up with some data values (enums, etc.) from (1) which is OK. In a few places, however, it copies the buffer pointers from (1)... and then as you noticed, may need to realloc them for step (2b). Now buffer ownership is muddled and depends on the runtime situation.

Do you think it would be worth some refactoring to try and keep library and program allocated memory separate? In cases where klp-convert only needs to read memory, perhaps a naming or scoping convention could help. For those re-allocations, I can't think of anything clever aside from separate buffers or noting original (ie, library) pointer values.

Quoted 67 lines
Quoted 3 lines
scripts/livepatch/elf.c new file +3 -0
+	return 1;
+}
+

[...]

scripts/livepatch/elf.c line 698

Quoted 6 lines
scripts/livepatch/elf.c new file +6 -0
+int elf_write_file(struct elf *elf, const char *file)
+{
+	int ret_shstrtab;
+	int ret_strtab;
+	int ret_symtab;
+	int ret_relas;

We do not free the bigger buffers when something goes wrong. Also this is not that important. But it is easy to fix:

We might do:

	int ret_shstrtab = 0;
	int ret_strtab = 0;
	int ret_symtab = 0;
	int ret_relas = 0;

scripts/livepatch/elf.c line 707

Quoted 9 lines
scripts/livepatch/elf.c new file +9 -0
+	int ret;
+
+	ret_shstrtab = update_shstrtab(elf);
+	if (ret_shstrtab < 0)
+		return ret_shstrtab;
+
+	ret_strtab = update_strtab(elf);
+	if (ret_strtab < 0)
+		return ret_strtab;
	if (ret_strtab < 0) {
		ret = ret_strtab;
		goto out;
	}

scripts/livepatch/elf.c line 711

Quoted 3 lines
scripts/livepatch/elf.c new file +3 -0
+	ret_symtab = update_symtab(elf);
+	if (ret_symtab < 0)
+		return ret_symtab;
	if (ret_symtab < 0) {
		ret = ret_symtab;
		goto out;
	}

scripts/livepatch/elf.c line 715

Quoted 3 lines
scripts/livepatch/elf.c new file +3 -0
+	ret_relas = update_relas(elf);
+	if (ret_relas < 0)
+		return ret_relas;
	if (ret_relas < 0) {
		ret = ret_relas;
		goto out;
	}

scripts/livepatch/elf.c line 721

Quoted 5 lines
scripts/livepatch/elf.c new file +5 -0
+	update_groups(elf);
+
+	ret = write_file(elf, file);
+	if (ret)
+		return ret;

Continue even when write_file(elf, file) returns an error.

out:

Quoted 10 lines

scripts/livepatch/elf.c

Quoted 10 lines
scripts/livepatch/elf.c new file +10 -0
+	if (ret_relas > 0)
+		free_relas(elf);
+	if (ret_symtab > 0)
+		free_symtab(elf);
+	if (ret_strtab > 0)
+		free_strtab(elf);
+	if (ret_shstrtab > 0)
+		free_shstrtab(elf);
+
+	return ret;

Yes, that's a good recommendation. I think this would improve the error handling and isn't too hard to implement.

Quoted 11 lines

Another problem is that the free_*() functions release the bigger buffers. But they do not put back the original ones. Also all the updated offsets and indexes point to the bigger buffers. As a result the structures can't be made consistent any longer.

I am not sure if there is an easy way to fix it. IMHO, proper solution is not worth a big effort. klp-convert frees everthing after writing the elf file.

Well, we should at least make a comment above elf_write_file() about that the structures are damaged in this way.

The assumption in the code seems to be that elf_write_file() and the update_*() functions it calls would only ever be done once.

And then, I think, that the new output file Elf structure created by write_file() and passed to elf_update(), would have consistent offset and indexes since the klp-converted structures are iterated in order as appropriate gelf_update_*() are called.

If something else looks amiss, please point it out and I can try to verify using my tests.

Quoted 11 lines

Finally, my main concern:

It brings a question whether the written data were consistent.

I am not familiar with the elf format. I quess that it is rather stable. But there might still be some differences between architectures or some new extensions that might need special handing.

I do not see any big consistency checks in the gelf_update_ehdr(), elf_update(), or elf_end() functions that are used when writing the changes.

If you have specifics in mind, I can verify empirically and research if/how libelf abstracts this for us or not (endianness in cross-arch scenarios, for example).

Quoted 13 lines

But there seems to be some thorough consistency checks provided by:

    readelf --enable-checks

It currently see these warnings:

$> readelf --lint lib/livepatch/test_klp_convert2.ko >/dev/null
readelf: Warning: Section '.note.GNU-stack': has a size of zero - is this intended ?

$> readelf --lint lib/livepatch/test_klp_callbacks_mod.ko >/dev/null
readelf: Warning: Section '.data': has a size of zero - is this intended ?
readelf: Warning: Section '.note.GNU-stack': has a size of zero - is this intended ?

Quoted 8 lines

$> readelf --lint lib/test_printf.ko >/dev/null
readelf: Warning: Section '.text': has a size of zero - is this intended ?
readelf: Warning: Section '.data': has a size of zero - is this intended ?
readelf: Warning: Section '.note.GNU-stack': has a size of zero - is this intended ?

But I see this warnings even without this patchset. I wonder if it might really help to find problems introduced by klp-convert or if it would be a waste of time.

Interesting, I didn't know about readelf --enable-checks / --lint. Do you know if this is any different from elflint?

In any case, I can take a look at those, but as you noticed, it looks like all of the complaints also crop up outside of klp-convert cases. I wonder if kernel linker script is unconditionally creating those zero-sized sections?

-- Joe

Reviewed-by on v6 3/12
#12 lore raw

Re: [RFC PATCH v6 03/12] livepatch: Add klp-convert tool

In reply to Joe Lawrence
Quoted 1 line · Joe Lawrence

From: Josh Poimboeuf <[email protected]>

All the comments bellow are suggestions. Besides them being addressed or not:

Quoted 15 lines
scripts/livepatch/klp-convert.c new file +15 -0
+
+/*
+ * User provided sympos annotation checks:
+ * - do two or more elements in usr_symbols have the same object and
+ *   name, but different symbol position
+ * - are there any usr_symbols without a rela?
+ */
+static bool sympos_sanity_check(struct elf *klp_elf)
+{
+	bool sane = true;
+	struct sympos *sp, *aux;
+	struct section *sec;
+	struct rela *rela;
+
+	list_for_each_entry(sp, &usr_symbols, list) {

scripts/livepatch/klp-convert.c line 240

Quoted 10 lines
scripts/livepatch/klp-convert.c new file +10 -0
+		bool found_rela = false;
+
+		aux = list_next_entry(sp, list);
+		list_for_each_entry_from(aux, &usr_symbols, list) {
+			if (sp->pos != aux->pos &&
+			    strcmp(sp->object_name, aux->object_name) == 0 &&
+			    strcmp(sp->symbol_name, aux->symbol_name) == 0) {
+				WARN("Conflicting KLP_SYMPOS definition: %s.%s,%d vs. %s.%s,%d.",
+				sp->object_name, sp->symbol_name, sp->pos,
+				aux->object_name, aux->symbol_name, aux->pos);

The WARN message could be simplified by mentioning the different position, something like:

	WARN("Conflicting KLP_SYMPOS definition: %s.%s %d vs. %d.",
	sp->object_name, sp->symbol_name, sp->pos aux->pos);
Quoted 4 lines
scripts/livepatch/klp-convert.c new file +4 -0
+				sane = false;
+			}
+		}
+

scripts/livepatch/klp-convert.c line 254

Quoted 10 lines
scripts/livepatch/klp-convert.c new file +10 -0
+		list_for_each_entry(sec, &klp_elf->sections, list) {
+			list_for_each_entry(rela, &sec->relas, list) {
+				if (!strcmp(sp->symbol_name, rela->sym->name)) {
+					found_rela = true;
+					break;
+				}
+			}
+		}
+		if (!found_rela) {
+			//sane = false;

At this point I believe that sane should be assigned to false to help the user to know that the specified symbol isn't being used in the livepatch.

Quoted 8 lines
scripts/livepatch/klp-convert.c new file +8 -0
+			WARN("Couldn't find rela for annotated symbol: %s",
+				sp->symbol_name);
+		}
+
+
+	}
+	return sane;
+}

<snip>

Quoted 20 lines
scripts/livepatch/klp-convert.c new file +20 -0
+/*
+ * Searches for symbol in symbols list and returns its sympos if it is unique,
+ * otherwise prints a list with all considered valid sympos
+ */
+static struct symbol_entry *find_sym_entry_by_name(char *name)
+{
+	struct symbol_entry *found = NULL;
+	struct symbol_entry *e;
+
+	list_for_each_entry(e, &symbols, list) {
+		if (strcmp(e->symbol_name, name) == 0) {
+
+			/*
+			 * If there exist multiple symbols with the same
+			 * name then user-provided sympos is required
+			 */
+			if (found) {
+				WARN("Define KLP_SYMPOS for the symbol: %s",
+						e->symbol_name);
+

scripts/livepatch/klp-convert.c line 400

Quoted 10 lines
scripts/livepatch/klp-convert.c new file +10 -0
+				print_valid_module_relocs(name);
+				return NULL;
+			}
+			found = e;
+		}
+	}
+	if (found)
+		return found;
+
+	return NULL;

Since found is either NULL or points to a symbol, the if condition can be removed and return found directly.

Quoted 4 lines
scripts/livepatch/klp-convert.c new file +4 -0
+}
+
+/* Checks if sympos is valid, otherwise prints valid sympos list */
+static bool valid_sympos(struct sympos *sp)

<snip>

Quoted 19 lines
scripts/livepatch/klp-convert.c new file +19 -0
+
+/* Returns the right sympos respective to a symbol to be relocated */
+static bool find_sympos(struct symbol *s, struct sympos *sp)
+{
+	struct symbol_entry *entry;
+	struct converted_sym *cs;
+
+	/* did we already convert this symbol? */
+	list_for_each_entry(cs, &converted_symbols, list) {
+		if (cs->symbol == s) {
+			*sp = cs->sympos;
+			return true;
+		}
+	}
+
+	/* did the user specified via annotation? */
+	if (get_usr_sympos(s, sp)) {
+		if (valid_sympos(sp)) {
+			remember_sympos(s, sp);

scripts/livepatch/klp-convert.c line 503

Quoted 10 lines
scripts/livepatch/klp-convert.c new file +10 -0
+			return true;
+		}
+		return false;
+	}
+
+	/* search symbol in symbols list */
+	entry = find_sym_entry_by_name(s->name);
+	if (entry) {
+		sp->symbol_name = entry->symbol_name;
+		sp->object_name = entry->object_name;

At this point I believe that it would be good to have a comment about sympos being 0 means that the symbol wasn't specified by the user, so sympos 0 means that the symbol is unique.

Quoted 6 lines
scripts/livepatch/klp-convert.c new file +6 -0
+		sp->pos = 0;
+		remember_sympos(s, sp);
+		return true;
+	}
+	return false;
+}

<snip>

author maintainer
#13 lore raw

RFC PATCH v6 4/12 livepatch: Add klp-convert annotation helpers

In reply to Joe Lawrence

From: Josh Poimboeuf <[email protected]>

Define macros KLP_MODULE_RELOC and KLP_SYMPOS in include/linux/livepatch.h to improve user-friendliness of the livepatch annotation process.

---
 include/linux/livepatch.h | 12 ++++++++++++
 1 file changed, 12 insertions(+)
include/linux/livepatch.h +12 -0
index 0fb05aae091a..3abb09bd807a 100644
@@ -237,6 +237,18 @@ int klp_apply_section_relocs(struct module *pmod, Elf_Shdr *sechdrs,
 			     unsigned int symindex, unsigned int secindex,
 			     const char *objname);
 
+/* Used to annotate symbol relocations in livepatches */
+#define KLP_MODULE_RELOC(obj)						\
+	struct klp_module_reloc						\
+	__section(".klp.module_relocs." #obj)				\
+	__aligned(4)
+
+#define KLP_SYMPOS(symbol, pos)						\
+	{								\
+		.sym = &symbol,						\
+		.sympos = pos,						\
+	}
+
 #else /* !CONFIG_LIVEPATCH */
 
 static inline int klp_module_coming(struct module *mod) { return 0; }
Signature · 1 line
2.26.3
author maintainer
#14 lore raw

RFC PATCH v6 5/12 modpost: Integrate klp-convert

In reply to Joe Lawrence

From: Josh Poimboeuf <[email protected]>

Create cmd_klp_convert and hook it into scripts/Makefile.modpost. cmd_klp_convert invokes klp-convert with the right arguments for the conversion of unresolved symbols inside a livepatch.

---
 .gitignore                |  1 +
 Makefile                  | 18 ++----------------
 scripts/Makefile.modfinal | 38 +++++++++++++++++++++++++++++++++++++-
 scripts/Makefile.modpost  |  5 +++++
 scripts/mod/modpost.c     | 28 ++++++++++++++++++++++++++--
 scripts/mod/modpost.h     |  1 +
 6 files changed, 72 insertions(+), 19 deletions(-)
.gitignore +1 -0
index 50638a15a527..eb0179d00260 100644
@@ -48,6 +48,7 @@
 *.xz
 *.zst
 Module.symvers
+modules.livepatch
 modules.order
 
 #
Makefile +2 -16
index 64ec4bc8172c..31d5b6f608d9 100644
@@ -1089,6 +1089,7 @@ PHONY += prepare0
 export extmod_prefix = $(if $(KBUILD_EXTMOD),$(KBUILD_EXTMOD)/)
 export MODORDER := $(extmod_prefix)modules.order
 export MODULES_NSDEPS := $(extmod_prefix)modules.nsdeps
+export MODULES_LIVEPATCH := $(extmod-prefix)modules.livepatch
 
 ifeq ($(KBUILD_EXTMOD),)
 core-y			+= kernel/ certs/ mm/ fs/ ipc/ security/ crypto/
@@ -1485,7 +1486,7 @@ endif # CONFIG_MODULES
 # Directories & files removed with 'make clean'
 CLEAN_FILES += include/ksym vmlinux.symvers modules-only.symvers \
 	       modules.builtin modules.builtin.modinfo modules.nsdeps \
-	       compile_commands.json .thinlto-cache
+	       compile_commands.json .thinlto-cache modules.livepatch
 
 # Directories & files removed with 'make mrproper'
 MRPROPER_FILES += include/config include/generated          \
@@ -1747,22 +1748,7 @@ PHONY += modules modules_install
 
 ifdef CONFIG_MODULES
 
-quiet_cmd_klp_map = KLP     symbols.klp
-
-define cmd_klp_map
-	$(shell echo "klp-convert-symbol-data.0.1" > $(objtree)/symbols.klp)				\
-	$(shell echo "*vmlinux" >> $(objtree)/symbols.klp)						\
-	$(shell nm -f posix $(objtree)/vmlinux | cut -d\  -f1 >> $(objtree)/symbols.klp)		\
-	$(foreach ko, $(sort $(shell cat modules.order)),						\
-		$(eval mod = $(patsubst %.ko,%.mod,$(ko)))						\
-		$(eval obj = $(patsubst %.ko,%.o,$(ko)))						\
-		$(if $(shell grep -o LIVEPATCH $(mod)),,						\
-			$(shell echo "*$(shell basename -s .ko $(ko))" >> $(objtree)/symbols.klp)	\
-			$(shell nm -f posix $(obj) | cut -d\  -f1 >> $(objtree)/symbols.klp)))
-endef
-
 modules: modules_check
-	$(if $(CONFIG_LIVEPATCH), $(call cmd,klp_map))
 	$(Q)$(MAKE) -f $(srctree)/scripts/Makefile.modpost
 
 PHONY += modules_check
scripts/Makefile.modfinal +37 -1
index 7f39599e9fae..cb31262436ba 100644
@@ -14,6 +14,8 @@ include $(srctree)/scripts/Makefile.lib
 
 # find all modules listed in modules.order
 modules := $(sort $(shell cat $(MODORDER)))
+modules-klp := $(sort $(shell cat $(MODULES_LIVEPATCH)))
+modules-no-klp := $(filter-out $(modules-klp), $(modules))
 
 __modfinal: $(modules)
 	@:
@@ -56,7 +58,7 @@ if_changed_except = $(if $(call newer_prereqs_except,$(2))$(cmd-check),      \
 
 
 # Re-generate module BTFs if either module's .ko or vmlinux changed
-$(modules): %.ko: %$(mod-prelink-ext).o %.mod.o scripts/module.lds $(if $(KBUILD_BUILTIN),vmlinux) FORCE
+$(modules-no-klp): %.ko: %$(mod-prelink-ext).o %.mod.o scripts/module.lds $(if $(KBUILD_BUILTIN),vmlinux) FORCE
 	+$(call if_changed_except,ld_ko_o,vmlinux)
 ifdef CONFIG_DEBUG_INFO_BTF_MODULES
 	+$(if $(newer-prereqs),$(call cmd,btf_ko))
@@ -64,6 +66,40 @@ endif
 
 targets += $(modules) $(modules:.ko=.mod.o)
 
+# Live Patch
+# ---------------------------------------------------------------------------
+
+%.tmp.ko: %.o %.mod.o symbols.klp FORCE
+	+$(call if_changed,ld_ko_o)
+
+quiet_cmd_klp_convert = KLP     $@
+      cmd_klp_convert = scripts/livepatch/klp-convert symbols.klp $< $@
+
+$(modules-klp): %.ko: %.tmp.ko FORCE
+	$(call if_changed,klp_convert)
+
+targets += $(modules-klp:.ko=.tmp.ko)
+
+ifeq ($(KBUILD_EXTMOD),)
+# Read out modules.{order,livepatch} instead of expanding $(modules-no-klp).
+# Otherwise, allmodconfig would fail with "Argument list too long".
+filechk_klp_map = \
+	echo "klp-convert-symbol-data.0.1";		\
+	echo "*vmlinux";				\
+	$(NM) -f posix vmlinux | cut -d\  -f1;		\
+	sort $(MODORDER) $(MODULES_LIVEPATCH) |		\
+	uniq -u |					\
+	sed 's/\.ko$$//' |    			  	\
+	while read o;					\
+	do						\
+		echo "*$$(basename $$o)";		\
+		$(NM) -f posix $$o.o | cut -d\  -f1;	\
+	done
+
+symbols.klp: FORCE
+	$(call filechk,klp_map)
+endif
+
 # Add FORCE to the prequisites of a target to force it to be always rebuilt.
 # ---------------------------------------------------------------------------
 
scripts/Makefile.modpost +5 -0
index 48585c4d04ad..c5df629de7b2 100644
@@ -48,6 +48,7 @@ MODPOST = scripts/mod/modpost								\
 	$(if $(CONFIG_MODVERSIONS),-m)							\
 	$(if $(CONFIG_MODULE_SRCVERSION_ALL),-a)					\
 	$(if $(CONFIG_SECTION_MISMATCH_WARN_ONLY),,-E)					\
+	$(if $(CONFIG_LIVEPATCH),-l $(MODULES_LIVEPATCH))				\
 	-o $@
 
 ifdef MODPOST_VMLINUX
@@ -136,6 +137,10 @@ $(output-symdump): $(MODORDER) $(input-symdump) $(modules:.ko=$(mod-prelink-ext)
 targets += $(output-symdump)
 
 __modpost: $(output-symdump)
+ifndef CONFIG_LIVEPATCH
+	$(Q)rm -f $(MODULES_LIVEPATCH)
+	$(Q)touch $(MODULES_LIVEPATCH)
+endif
 ifneq ($(KBUILD_MODPOST_NOFINAL),1)
 	$(Q)$(MAKE) -f $(srctree)/scripts/Makefile.modfinal
 endif
scripts/mod/modpost.c +26 -2
index 6bfa33217914..1034b673c95c 100644
@@ -2051,6 +2051,10 @@ static void read_symbols(const char *modname)
 		handle_moddevtable(mod, &info, sym, symname);
 	}
 
+	/* Livepatch modules have unresolved symbols resolved by klp-convert */
+	if (get_modinfo(&info, "livepatch"))
+		mod->livepatch = 1;
+
 	for (sym = info.symtab_start; sym < info.symtab_stop; sym++) {
 		symname = remove_dot(info.strtab + sym->st_name);
 
@@ -2170,7 +2174,7 @@ static void check_exports(struct module *mod)
 		const char *basename;
 		exp = find_symbol(s->name);
 		if (!exp || exp->module == mod) {
-			if (!s->weak && nr_unresolved++ < MAX_UNRESOLVED_REPORTS)
+			if (!s->weak && !mod->livepatch && nr_unresolved++ < MAX_UNRESOLVED_REPORTS)
 				modpost_log(warn_unresolved ? LOG_WARN : LOG_ERROR,
 					    "\"%s\" [%s.ko] undefined!\n",
 					    s->name, mod->name);
@@ -2502,6 +2506,20 @@ static void write_namespace_deps_files(const char *fname)
 	free(ns_deps_buf.p);
 }
 
+static void write_livepatch_modules(const char *fname)
+{
+	struct buffer buf = { };
+	struct module *mod;
+
+	for (mod = modules; mod; mod = mod->next) {
+		if (mod->livepatch)
+			buf_printf(&buf, "%s.ko\n", mod->name);
+	}
+
+	write_if_changed(&buf, fname);
+	free(buf.p);
+}
+
 struct dump_list {
 	struct dump_list *next;
 	const char *file;
@@ -2513,12 +2531,13 @@ int main(int argc, char **argv)
 	struct buffer buf = { };
 	char *missing_namespace_deps = NULL;
 	char *dump_write = NULL, *files_source = NULL;
+	char *livepatch_modules = NULL;
 	int opt;
 	int n;
 	struct dump_list *dump_read_start = NULL;
 	struct dump_list **dump_read_iter = &dump_read_start;
 
-	while ((opt = getopt(argc, argv, "ei:mnT:o:awENd:")) != -1) {
+	while ((opt = getopt(argc, argv, "ei:l:mnT:o:awENd:")) != -1) {
 		switch (opt) {
 		case 'e':
 			external_module = 1;
@@ -2529,6 +2548,9 @@ int main(int argc, char **argv)
 			(*dump_read_iter)->file = optarg;
 			dump_read_iter = &(*dump_read_iter)->next;
 			break;
+		case 'l':
+			livepatch_modules = optarg;
+			break;
 		case 'm':
 			modversions = 1;
 			break;
@@ -2605,6 +2627,8 @@ int main(int argc, char **argv)
 
 	if (dump_write)
 		write_dump(dump_write);
+	if (livepatch_modules)
+		write_livepatch_modules(livepatch_modules);
 	if (sec_mismatch_count && !sec_mismatch_warn_only)
 		error("Section mismatches detected.\n"
 		      "Set CONFIG_SECTION_MISMATCH_WARN_ONLY=y to allow them.\n");
scripts/mod/modpost.h +1 -0
index 0c47ff95c0e2..8c7e7e546158 100644
@@ -123,6 +123,7 @@ struct module {
 	int seen;
 	int has_init;
 	int has_cleanup;
+	int livepatch;
 	struct buffer dev_table_buf;
 	char	     srcversion[25];
 	// Missing namespace dependencies
Signature · 1 line
2.26.3
author maintainer
#15 lore raw

RFC PATCH v6 6/12 livepatch: Add sample livepatch module

In reply to Joe Lawrence

From: Josh Poimboeuf <[email protected]>

Add a new livepatch sample in samples/livepatch/ to make use of symbols that must be post-processed to enable load-time relocation resolution. As the new sample is to be used as an example, it is annotated with KLP_MODULE_RELOC and with KLP_SYMPOS macros.

The livepatch sample updates the function cmdline_proc_show to print the string referenced by the symbol saved_command_line appended by the string "livepatch=1".

Update livepatch-sample.c to remove livepatch MODULE_INFO statement.

---
 samples/livepatch/Makefile                    |  1 +
 .../livepatch/livepatch-annotated-sample.c    | 93 +++++++++++++++++++
 2 files changed, 94 insertions(+)
 create mode 100644 samples/livepatch/livepatch-annotated-sample.c
samples/livepatch/Makefile +1 -0
index 9f853eeb6140..f2b41f4d6c16 100644
@@ -6,3 +6,4 @@ obj-$(CONFIG_SAMPLE_LIVEPATCH) += livepatch-shadow-fix2.o
 obj-$(CONFIG_SAMPLE_LIVEPATCH) += livepatch-callbacks-demo.o
 obj-$(CONFIG_SAMPLE_LIVEPATCH) += livepatch-callbacks-mod.o
 obj-$(CONFIG_SAMPLE_LIVEPATCH) += livepatch-callbacks-busymod.o
+obj-$(CONFIG_SAMPLE_LIVEPATCH) += livepatch-annotated-sample.o
samples/livepatch/livepatch-annotated-sample.c new file +93 -0

93 lines not on this page · raw message

Signature · 1 line
2.26.3
Reviewed-by on v6 6/12
#16 lore raw

Re: [RFC PATCH v6 06/12] livepatch: Add sample livepatch module

Quoted 7 lines · Joe Lawrence

From: Josh Poimboeuf <[email protected]>

Add a new livepatch sample in samples/livepatch/ to make use of symbols that must be post-processed to enable load-time relocation resolution. As the new sample is to be used as an example, it is annotated with KLP_MODULE_RELOC and with KLP_SYMPOS macros.

Quoted 5 lines

The livepatch sample updates the function cmdline_proc_show to print the string referenced by the symbol saved_command_line appended by the string "livepatch=1".

Update livepatch-sample.c to remove livepatch MODULE_INFO statement.

LGTM.

Quoted 121 lines
---
 samples/livepatch/Makefile                    |  1 +
 .../livepatch/livepatch-annotated-sample.c    | 93 +++++++++++++++++++
 2 files changed, 94 insertions(+)
 create mode 100644 samples/livepatch/livepatch-annotated-sample.c
samples/livepatch/Makefile +1 -0
index 9f853eeb6140..f2b41f4d6c16 100644
@@ -6,3 +6,4 @@ obj-$(CONFIG_SAMPLE_LIVEPATCH) += livepatch-shadow-fix2.o
 obj-$(CONFIG_SAMPLE_LIVEPATCH) += livepatch-callbacks-demo.o
 obj-$(CONFIG_SAMPLE_LIVEPATCH) += livepatch-callbacks-mod.o
 obj-$(CONFIG_SAMPLE_LIVEPATCH) += livepatch-callbacks-busymod.o
+obj-$(CONFIG_SAMPLE_LIVEPATCH) += livepatch-annotated-sample.o
samples/livepatch/livepatch-annotated-sample.c new file +93 -0
new file mode 100644
index 000000000000..4fe0e16423c7
@@ -0,0 +1,93 @@
+// SPDX-License-Identifier: GPL-2.0-or-later
+/*
+ * Copyright (C) 2014 Seth Jennings <[email protected]>
+ */
+
+/*
+ * livepatch-annotated-sample.c - Kernel Live Patching Sample Module
+ */
+
+#define pr_fmt(fmt) KBUILD_MODNAME ": " fmt
+
+#include <linux/module.h>
+#include <linux/kernel.h>
+#include <linux/livepatch.h>
+
+/*
+ * This (dumb) live patch overrides the function that prints the
+ * kernel boot cmdline when /proc/cmdline is read.
+ *
+ * This livepatch uses the symbol saved_command_line whose relocation
+ * must be resolved during load time. To enable that, this module
+ * must be post-processed by a tool called klp-convert, which embeds
+ * information to be used by the loader to solve the relocation.
+ *
+ * The module is annotated with KLP_MODULE_RELOC/KLP_SYMPOS macros.
+ * These annotations are used by klp-convert to infer that the symbol
+ * saved_command_line is in the object vmlinux.
+ *
+ * As saved_command_line has no other homonimous symbol across
+ * kernel objects, this annotation is not a requirement, and can be
+ * suppressed with no harm to klp-convert. Yet, it is kept here as an
+ * example on how to annotate livepatch modules that contain symbols
+ * whose names are used in more than one kernel object.
+ *
+ * Example:
+ *
+ * $ cat /proc/cmdline
+ * <your cmdline>
+ *
+ * $ insmod livepatch-sample.ko
+ * $ cat /proc/cmdline
+ * <your cmdline> livepatch=1
+ *
+ * $ echo 0 > /sys/kernel/livepatch/livepatch_sample/enabled
+ * $ cat /proc/cmdline
+ * <your cmdline>
+ */
+
+extern char *saved_command_line;
+
+#include <linux/seq_file.h>
+static int livepatch_cmdline_proc_show(struct seq_file *m, void *v)
+{
+	seq_printf(m, "%s livepatch=1\n", saved_command_line);
+	return 0;
+}
+
+KLP_MODULE_RELOC(vmlinux) vmlinux_relocs[] = {
+	KLP_SYMPOS(saved_command_line, 0)
+};
+
+static struct klp_func funcs[] = {
+	{
+		.old_name = "cmdline_proc_show",
+		.new_func = livepatch_cmdline_proc_show,
+	}, { }
+};
+
+static struct klp_object objs[] = {
+	{
+		/* name being NULL means vmlinux */
+		.funcs = funcs,
+	}, { }
+};
+
+static struct klp_patch patch = {
+	.mod = THIS_MODULE,
+	.objs = objs,
+};
+
+static int livepatch_init(void)
+{
+	return klp_enable_patch(&patch);
+}
+
+static void livepatch_exit(void)
+{
+}
+
+module_init(livepatch_init);
+module_exit(livepatch_exit);
+MODULE_LICENSE("GPL");
+MODULE_INFO(livepatch, "Y");
Signature · 1 line
2.26.3
author maintainer
#17 lore raw

RFC PATCH v6 7/12 documentation: Update on livepatch elf format

In reply to Joe Lawrence

From: Joao Moreira <[email protected]>

Add a section to Documentation/livepatch/module-elf-format.rst describing how klp-convert works for fixing relocations.

---
 Documentation/livepatch/livepatch.rst         |  3 ++
 Documentation/livepatch/module-elf-format.rst | 42 +++++++++++++++++--
 2 files changed, 42 insertions(+), 3 deletions(-)
Documentation/livepatch/livepatch.rst +3 -0
index 68e3651e8af9..6b317a57c276 100644
@@ -261,6 +261,9 @@ into three levels:
     absolute position in the database, but rather the order it has been found
     only for a particular object ( vmlinux or a kernel module ). Note that
     kallsyms allows for searching symbols according to the object name.
+    Uniquely named symbols may use a symbol position of 0.  Non-unique
+    symbols need to specify their object / kallsyms position, starting
+    at position 1.
 
   - struct klp_object defines an array of patched functions (struct
     klp_func) in the same object. Where the object is either vmlinux
Documentation/livepatch/module-elf-format.rst +39 -3

60 lines not on this page · raw message

Signature · 1 line
2.26.3
author maintainer
#18 lore raw

RFC PATCH v6 8/12 livepatch/selftests: add klp-convert

In reply to Joe Lawrence

Add a simple klp-convert livepatch selftest that exercises various symbol homonym sympos scenarios.

---
 lib/livepatch/Makefile                        |   7 +
 lib/livepatch/test_klp_convert.h              |  14 ++
 lib/livepatch/test_klp_convert1.c             | 113 +++++++++++++++
 lib/livepatch/test_klp_convert2.c             | 110 ++++++++++++++
 lib/livepatch/test_klp_convert_mod_a.c        |  25 ++++
 lib/livepatch/test_klp_convert_mod_b.c        |  13 ++
 .../selftests/livepatch/test-livepatch.sh     | 134 ++++++++++++++++++
 7 files changed, 416 insertions(+)
 create mode 100644 lib/livepatch/test_klp_convert.h
 create mode 100644 lib/livepatch/test_klp_convert1.c
 create mode 100644 lib/livepatch/test_klp_convert2.c
 create mode 100644 lib/livepatch/test_klp_convert_mod_a.c
 create mode 100644 lib/livepatch/test_klp_convert_mod_b.c
lib/livepatch/Makefile +7 -0
index dcc912b3478f..ced00515ff84 100644
@@ -7,8 +7,15 @@ obj-$(CONFIG_TEST_LIVEPATCH) += test_klp_atomic_replace.o \
 				test_klp_callbacks_demo2.o \
 				test_klp_callbacks_busy.o \
 				test_klp_callbacks_mod.o \
+				test_klp_convert1.o \
+				test_klp_convert2.o \
+				test_klp_convert_mod.o \
 				test_klp_livepatch.o \
 				test_klp_shadow_vars.o \
 				test_klp_state.o \
 				test_klp_state2.o \
 				test_klp_state3.o
+
+test_klp_convert_mod-y := \
+	test_klp_convert_mod_a.o \
+	test_klp_convert_mod_b.o
lib/livepatch/test_klp_convert.h new file +14 -0
new file mode 100644
index 000000000000..5d97bc546d6e
@@ -0,0 +1,14 @@
+/* SPDX-License-Identifier: GPL-2.0 */
+
+#ifndef _TEST_KLP_CONVERT_
+#define _TEST_KLP_CONVERT_
+
+/* klp-convert symbols - vmlinux */
+extern char *saved_command_line;
+/* klp-convert symbols - test_klp_convert_mod.ko */
+extern char driver_name[];
+extern char homonym_string[];
+extern const char *get_homonym_string(void);
+extern const char *test_klp_get_driver_name(void);
+
+#endif
lib/livepatch/test_klp_convert1.c new file +113 -0

113 lines not on this page · raw message

lib/livepatch/test_klp_convert2.c new file +110 -0

110 lines not on this page · raw message

lib/livepatch/test_klp_convert_mod_a.c new file +25 -0
new file mode 100644
index 000000000000..ae5e911fbb9b
@@ -0,0 +1,25 @@
+// SPDX-License-Identifier: GPL-2.0
+// Copyright (C) 2019 Joe Lawrence <[email protected]>
+
+#define pr_fmt(fmt) KBUILD_MODNAME ": " fmt
+
+#include <linux/module.h>
+#include <linux/kernel.h>
+
+/* Unique symbols that don't need sympos annotation */
+static const char driver_name[] = KBUILD_MODNAME;
+__used static const char *test_klp_get_driver_name(void)
+{
+	return driver_name;
+}
+
+/* Common symbol names that need sympos */
+static const char homonym_string[] = "homonym string A";
+__used static const char *get_homonym_string(void)
+{
+	return homonym_string;
+}
+
+MODULE_LICENSE("GPL");
+MODULE_AUTHOR("Joe Lawrence <[email protected]>");
+MODULE_DESCRIPTION("Livepatch test: klp-convert module");
lib/livepatch/test_klp_convert_mod_b.c new file +13 -0
new file mode 100644
index 000000000000..5eca8a4cae38
@@ -0,0 +1,13 @@
+// SPDX-License-Identifier: GPL-2.0
+// Copyright (C) 2019 Joe Lawrence <[email protected]>
+
+/*
+ * A second compilation unit to provide another set of similarly named
+ * symbols, forcing a livepatch to use sympos annotations.
+ */
+
+static const char homonym_string[] = "homonym string B";
+__used static const char *get_homonym_string(void)
+{
+	return homonym_string;
+}
tools/testing/selftests/livepatch/test-livepatch.sh +134 -0

144 lines not on this page · raw message

Signature · 1 line
2.26.3
#19 lore raw

Re: [RFC PATCH v6 08/12] livepatch/selftests: add klp-convert

[If your patch is applied to the wrong git tree, kindly drop us a note. And when submitting patch, we suggest to use '--base' as documented in https://git-scm.com/docs/git-format-patch]

Hi Joe,

[FYI, it's a private test report for your RFC patch.]
[auto build test WARNING on shuah-kselftest/next]
[also build test WARNING on linux/master masahiroy-kbuild/for-next linus/master v5.17-rc4] [cannot apply to next-20220216]
[If your patch is applied to the wrong git tree, kindly drop us a note.
And when submitting patch, we suggest to use '--base' as documented in
https://git-scm.com/docs/git-format-patch]

url:    https://github.com/0day-ci/linux/commits/Joe-Lawrence/livepatch-klp-convert-tool/20220217-004100
base:   https://git.kernel.org/pub/scm/linux/kernel/git/shuah/linux-kselftest.git next
config: x86_64-allyesconfig (https://download.01.org/0day-ci/archive/20220217/202202170629.9vC9IsP0-lkp(a)intel.com/config)
compiler: gcc-9 (Debian 9.3.0-22) 9.3.0

reproduce (this is a W=1 build):
# https://github.com/0day-ci/linux/commit/ea5129d2a3f776835ce3721f966f72d39426188c
git remote add linux-review https://github.com/0day-ci/linux
git fetch --no-tags linux-review Joe-Lawrence/livepatch-klp-convert-tool/20220217-004100 git checkout ea5129d2a3f776835ce3721f966f72d39426188c
# save the config file to linux build tree
mkdir build_dir
make W=1 O=build_dir ARCH=x86_64 SHELL=/bin/bash lib/livepatch/

If you fix the issue, kindly add following tag as appropriate

All warnings (new ones prefixed by >>):

>> lib/livepatch/test_klp_convert1.c:11:6: warning: no previous prototype for 'print_saved_command_line' [-Wmissing-prototypes]
      11 | void print_saved_command_line(void)
         |      ^~~~~~~~~~~~~~~~~~~~~~~~
>> lib/livepatch/test_klp_convert1.c:16:6: warning: no previous prototype for 'print_driver_name' [-Wmissing-prototypes]
      16 | void print_driver_name(void)
         |      ^~~~~~~~~~~~~~~~~
>> lib/livepatch/test_klp_convert1.c:22:6: warning: no previous prototype for 'print_homonym_string' [-Wmissing-prototypes]
      22 | void print_homonym_string(void)
         |      ^~~~~~~~~~~~~~~~~~~~
--
>> lib/livepatch/test_klp_convert2.c:11:6: warning: no previous prototype for 'print_saved_command_line' [-Wmissing-prototypes]
      11 | void print_saved_command_line(void)
         |      ^~~~~~~~~~~~~~~~~~~~~~~~
>> lib/livepatch/test_klp_convert2.c:16:6: warning: no previous prototype for 'print_driver_name' [-Wmissing-prototypes]
      16 | void print_driver_name(void)
         |      ^~~~~~~~~~~~~~~~~
>> lib/livepatch/test_klp_convert2.c:22:6: warning: no previous prototype for 'print_homonym_string' [-Wmissing-prototypes]

22 | void print_homonym_string(void)
| ^~~~~~~~~~~~~~~~~~~~

vim +/print_saved_command_line +11 lib/livepatch/test_klp_convert1.c

    10	
  > 11	void print_saved_command_line(void)
    12	{
    13		pr_info("saved_command_line, 0: %s\n", saved_command_line);
    14	}
    15	
  > 16	void print_driver_name(void)
    17	{
    18		pr_info("driver_name, 0: %s\n", driver_name);
    19		pr_info("test_klp_get_driver_name(), 0: %s\n", test_klp_get_driver_name());
    20	}
    21	
  > 22	void print_homonym_string(void)
    23	{
    24		pr_info("homonym_string, 1: %s\n", homonym_string);
    25		pr_info("get_homonym_string(), 1: %s\n", get_homonym_string());
    26	}
    27	

---
0-DAY CI Kernel Test Service, Intel Corporation
https://lists.01.org/hyperkitty/list/kbuild-all(a)lists.01.org

author maintainer
#20 lore raw

RFC PATCH v6 9/12 livepatch/selftests: test multiple sections

In reply to Joe Lawrence

Add a test case in which klp-convert needs to convert a symbol that is shared across ELF sections. Special sections like .altinstructions do this. It is possible that symbols may be shared across various .text sections as well.

---
 lib/livepatch/Makefile                        |   1 +
 lib/livepatch/test_klp_convert_sections.c     | 120 ++++++++++++++++++
 .../selftests/livepatch/test-livepatch.sh     |  43 +++++++
 3 files changed, 164 insertions(+)
 create mode 100644 lib/livepatch/test_klp_convert_sections.c
lib/livepatch/Makefile +1 -0
index ced00515ff84..77e21317d4da 100644
@@ -9,6 +9,7 @@ obj-$(CONFIG_TEST_LIVEPATCH) += test_klp_atomic_replace.o \
 				test_klp_callbacks_mod.o \
 				test_klp_convert1.o \
 				test_klp_convert2.o \
+				test_klp_convert_sections.o \
 				test_klp_convert_mod.o \
 				test_klp_livepatch.o \
 				test_klp_shadow_vars.o \
lib/livepatch/test_klp_convert_sections.c new file +120 -0

120 lines not on this page · raw message

tools/testing/selftests/livepatch/test-livepatch.sh +43 -0

47 lines not on this page · raw message

Signature · 1 line
2.26.3
#21 lore raw

Re: [RFC PATCH v6 09/12] livepatch/selftests: test multiple sections

[If your patch is applied to the wrong git tree, kindly drop us a note. And when submitting patch, we suggest to use '--base' as documented in https://git-scm.com/docs/git-format-patch]

Hi Joe,

[FYI, it's a private test report for your RFC patch.]
[auto build test WARNING on shuah-kselftest/next]
[also build test WARNING on linux/master masahiroy-kbuild/for-next linus/master v5.17-rc4] [cannot apply to next-20220216]
[If your patch is applied to the wrong git tree, kindly drop us a note.
And when submitting patch, we suggest to use '--base' as documented in
https://git-scm.com/docs/git-format-patch]

url:    https://github.com/0day-ci/linux/commits/Joe-Lawrence/livepatch-klp-convert-tool/20220217-004100
base:   https://git.kernel.org/pub/scm/linux/kernel/git/shuah/linux-kselftest.git next
config: x86_64-allyesconfig (https://download.01.org/0day-ci/archive/20220217/202202170852.PMAObvOm-lkp(a)intel.com/config)
compiler: gcc-9 (Debian 9.3.0-22) 9.3.0

reproduce (this is a W=1 build):
# https://github.com/0day-ci/linux/commit/0050faf33dc7bb450c8c62ac3dd69ee8dc7d0f9b
git remote add linux-review https://github.com/0day-ci/linux
git fetch --no-tags linux-review Joe-Lawrence/livepatch-klp-convert-tool/20220217-004100 git checkout 0050faf33dc7bb450c8c62ac3dd69ee8dc7d0f9b
# save the config file to linux build tree
mkdir build_dir
make W=1 O=build_dir ARCH=x86_64 SHELL=/bin/bash lib/livepatch/

If you fix the issue, kindly add following tag as appropriate

All warnings (new ones prefixed by >>):

>> lib/livepatch/test_klp_convert_sections.c:20:6: warning: no previous prototype for 'print_saved_command_line' [-Wmissing-prototypes]
      20 | void print_saved_command_line(void)
         |      ^~~~~~~~~~~~~~~~~~~~~~~~
>> lib/livepatch/test_klp_convert_sections.c:26:6: warning: no previous prototype for 'print_saved_command_line2' [-Wmissing-prototypes]
      26 | void print_saved_command_line2(void)
         |      ^~~~~~~~~~~~~~~~~~~~~~~~~
>> lib/livepatch/test_klp_convert_sections.c:33:6: warning: no previous prototype for 'print_saved_command_line3' [-Wmissing-prototypes]
      33 | void print_saved_command_line3(void)
         |      ^~~~~~~~~~~~~~~~~~~~~~~~~
>> lib/livepatch/test_klp_convert_sections.c:47:6: warning: no previous prototype for 'print_via_function_pointers' [-Wmissing-prototypes]

47 | void print_via_function_pointers(void)
| ^~~~~~~~~~~~~~~~~~~~~~~~~~~

vim +/print_saved_command_line +20 lib/livepatch/test_klp_convert_sections.c

    13	
    14	/*
    15	 * Scatter references to the same symbol (saved_command_line) across a
    16	 * few different ELF sections.  At the same time, include multiple
    17	 * references within the same function.
    18	 */
    19	__section(".text.print_saved_command_line")
  > 20	void print_saved_command_line(void)
    21	{
    22		pr_info("saved_command_line (1): %s\n", saved_command_line);
    23	}
    24	
    25	__section(".text.print_saved_command_line2")
  > 26	void print_saved_command_line2(void)
    27	{
    28		pr_info("saved_command_line (1): %s\n", saved_command_line);
    29		pr_info("saved_command_line (2): %s\n", saved_command_line);
    30	}
    31	
    32	__section(".text.print_saved_command_line3")
  > 33	void print_saved_command_line3(void)
    34	{
    35		pr_info("saved_command_line (1): %s\n", saved_command_line);
    36		pr_info("saved_command_line (2): %s\n", saved_command_line);
    37		pr_info("saved_command_line (3): %s\n", saved_command_line);
    38	}
    39	
    40	/*
    41	 * Create relocations in .rela.data that need conversion, sharing
    42	 * symbols with ordinary .text relas.
    43	 */
    44	const char *(*p_test_klp_get_driver_name)(void) = test_klp_get_driver_name;
    45	const char *(*p_get_homonym_string)(void) = get_homonym_string;
    46	
  > 47	void print_via_function_pointers(void)
    48	{
    49		pr_info("test_klp_get_driver_name(): %s\n", test_klp_get_driver_name());
    50		pr_info("p_test_klp_get_driver_name(): %s\n", p_test_klp_get_driver_name());
    51		pr_info("get_homonym_string(): %s\n", get_homonym_string());
    52		pr_info("p_get_homonym_string(): %s\n", p_get_homonym_string());
    53	}
    54	

---
0-DAY CI Kernel Test Service, Intel Corporation
https://lists.01.org/hyperkitty/list/kbuild-all(a)lists.01.org

author maintainer
#22 lore raw

RFC PATCH v6 10/12 livepatch/selftests: add __asm__ symbol renaming examples

In reply to Joe Lawrence

GCC can rename symbols like static data and optimized functions, adding a suffix that includes illegal C characters. Extend the klp-convert examples to demonstrate how to use __asm__ renaming from C code to create klp-relocations to such renamed symbols.

---
 lib/livepatch/test_klp_convert.h                    | 2 ++
 lib/livepatch/test_klp_convert1.c                   | 8 ++++++++
 lib/livepatch/test_klp_convert_mod_a.c              | 6 ++++++
 lib/livepatch/test_klp_convert_mod_b.c              | 6 ++++++
 tools/testing/selftests/livepatch/test-livepatch.sh | 4 ++++
 5 files changed, 26 insertions(+)
lib/livepatch/test_klp_convert.h +2 -0
index 5d97bc546d6e..42befbfd63cb 100644
@@ -10,5 +10,7 @@ extern char driver_name[];
 extern char homonym_string[];
 extern const char *get_homonym_string(void);
 extern const char *test_klp_get_driver_name(void);
+extern char klp_string_a[] __asm__("klp_string.12345");
+extern char klp_string_b[] __asm__("klp_string.67890");
 
 #endif
lib/livepatch/test_klp_convert1.c +8 -0
index cd2d3c638258..06926cf1c609 100644
@@ -25,6 +25,12 @@ void print_homonym_string(void)
 	pr_info("get_homonym_string(), 1: %s\n", get_homonym_string());
 }
 
+void print_static_strings(void)
+{
+	pr_info("klp_string.12345 = %s\n", klp_string_a);
+	pr_info("klp_string.67890 = %s\n", klp_string_b);
+}
+
 /* provide a sysfs handle to invoke debug functions */
 static int print_debug;
 static int print_debug_set(const char *val, const struct kernel_param *kp)
@@ -32,6 +38,7 @@ static int print_debug_set(const char *val, const struct kernel_param *kp)
 	print_saved_command_line();
 	print_driver_name();
 	print_homonym_string();
+	print_static_strings();
 
 	return 0;
 }
@@ -67,6 +74,7 @@ KLP_MODULE_RELOC(test_klp_convert_mod) test_klp_convert_mod_relocs_a[] = {
 	KLP_SYMPOS(homonym_string, 1),
 	KLP_SYMPOS(get_homonym_string, 1),
 	KLP_SYMPOS(test_klp_get_driver_name, 0),
+	KLP_SYMPOS(klp_string_b, 1),
 };
 
 static struct klp_func funcs[] = {
lib/livepatch/test_klp_convert_mod_a.c +6 -0
index ae5e911fbb9b..9af0fcab0c8d 100644
@@ -20,6 +20,12 @@ __used static const char *get_homonym_string(void)
 	return homonym_string;
 }
 
+__used static void static_string_function(void)
+{
+	__used static char klp_string[] __asm__("klp_string.12345") =
+		__FILE__ " static string";
+}
+
 MODULE_LICENSE("GPL");
 MODULE_AUTHOR("Joe Lawrence <[email protected]>");
 MODULE_DESCRIPTION("Livepatch test: klp-convert module");
lib/livepatch/test_klp_convert_mod_b.c +6 -0
index 5eca8a4cae38..0a68e898fe03 100644
@@ -11,3 +11,9 @@ __used static const char *get_homonym_string(void)
 {
 	return homonym_string;
 }
+
+__used static void static_string_function(void)
+{
+	__used static char klp_string[] __asm__("klp_string.67890") =
+		__FILE__ " static string";
+}
tools/testing/selftests/livepatch/test-livepatch.sh +4 -0
index bcb8b468b80a..ec3b6c919b01 100755
@@ -200,6 +200,8 @@ $MOD_KLP_CONVERT1: driver_name, 0: $MOD_KLP_CONVERT_MOD
 $MOD_KLP_CONVERT1: test_klp_get_driver_name(), 0: $MOD_KLP_CONVERT_MOD
 $MOD_KLP_CONVERT1: homonym_string, 1: homonym string A
 $MOD_KLP_CONVERT1: get_homonym_string(), 1: homonym string A
+test_klp_convert1: klp_string.12345 = lib/livepatch/test_klp_convert_mod_a.c static string
+test_klp_convert1: klp_string.67890 = lib/livepatch/test_klp_convert_mod_b.c static string
 % echo 0 > /sys/kernel/livepatch/$MOD_KLP_CONVERT1/enabled
 livepatch: '$MOD_KLP_CONVERT1': initializing unpatching transition
 livepatch: '$MOD_KLP_CONVERT1': starting unpatching transition
@@ -265,6 +267,8 @@ $MOD_KLP_CONVERT1: driver_name, 0: $MOD_KLP_CONVERT_MOD
 $MOD_KLP_CONVERT1: test_klp_get_driver_name(), 0: $MOD_KLP_CONVERT_MOD
 $MOD_KLP_CONVERT1: homonym_string, 1: homonym string A
 $MOD_KLP_CONVERT1: get_homonym_string(), 1: homonym string A
+test_klp_convert1: klp_string.12345 = lib/livepatch/test_klp_convert_mod_a.c static string
+test_klp_convert1: klp_string.67890 = lib/livepatch/test_klp_convert_mod_b.c static string
 % echo 0 > /sys/kernel/livepatch/$MOD_KLP_CONVERT1/enabled
 livepatch: '$MOD_KLP_CONVERT1': initializing unpatching transition
 livepatch: '$MOD_KLP_CONVERT1': starting unpatching transition
Signature · 1 line
2.26.3
author maintainer
#23 lore raw

Re: [RFC PATCH v6 10/12] livepatch/selftests: add __asm__ symbol renaming examples

Quoted 115 lines · Joe Lawrence

GCC can rename symbols like static data and optimized functions, adding a suffix that includes illegal C characters. Extend the klp-convert examples to demonstrate how to use __asm__ renaming from C code to create klp-relocations to such renamed symbols.

---
 lib/livepatch/test_klp_convert.h                    | 2 ++
 lib/livepatch/test_klp_convert1.c                   | 8 ++++++++
 lib/livepatch/test_klp_convert_mod_a.c              | 6 ++++++
 lib/livepatch/test_klp_convert_mod_b.c              | 6 ++++++
 tools/testing/selftests/livepatch/test-livepatch.sh | 4 ++++
 5 files changed, 26 insertions(+)
lib/livepatch/test_klp_convert.h +2 -0
index 5d97bc546d6e..42befbfd63cb 100644
@@ -10,5 +10,7 @@ extern char driver_name[];
 extern char homonym_string[];
 extern const char *get_homonym_string(void);
 extern const char *test_klp_get_driver_name(void);
+extern char klp_string_a[] __asm__("klp_string.12345");
+extern char klp_string_b[] __asm__("klp_string.67890");
 
 #endif
lib/livepatch/test_klp_convert1.c +8 -0
index cd2d3c638258..06926cf1c609 100644
@@ -25,6 +25,12 @@ void print_homonym_string(void)
 	pr_info("get_homonym_string(), 1: %s\n", get_homonym_string());
 }
 
+void print_static_strings(void)
+{
+	pr_info("klp_string.12345 = %s\n", klp_string_a);
+	pr_info("klp_string.67890 = %s\n", klp_string_b);
+}
+
 /* provide a sysfs handle to invoke debug functions */
 static int print_debug;
 static int print_debug_set(const char *val, const struct kernel_param *kp)
@@ -32,6 +38,7 @@ static int print_debug_set(const char *val, const struct kernel_param *kp)
 	print_saved_command_line();
 	print_driver_name();
 	print_homonym_string();
+	print_static_strings();
 
 	return 0;
 }
@@ -67,6 +74,7 @@ KLP_MODULE_RELOC(test_klp_convert_mod) test_klp_convert_mod_relocs_a[] = {
 	KLP_SYMPOS(homonym_string, 1),
 	KLP_SYMPOS(get_homonym_string, 1),
 	KLP_SYMPOS(test_klp_get_driver_name, 0),
+	KLP_SYMPOS(klp_string_b, 1),
 };
 
 static struct klp_func funcs[] = {
lib/livepatch/test_klp_convert_mod_a.c +6 -0
index ae5e911fbb9b..9af0fcab0c8d 100644
@@ -20,6 +20,12 @@ __used static const char *get_homonym_string(void)
 	return homonym_string;
 }
 
+__used static void static_string_function(void)
+{
+	__used static char klp_string[] __asm__("klp_string.12345") =
+		__FILE__ " static string";
+}
+
 MODULE_LICENSE("GPL");
 MODULE_AUTHOR("Joe Lawrence <[email protected]>");
 MODULE_DESCRIPTION("Livepatch test: klp-convert module");
lib/livepatch/test_klp_convert_mod_b.c +6 -0
index 5eca8a4cae38..0a68e898fe03 100644
@@ -11,3 +11,9 @@ __used static const char *get_homonym_string(void)
 {
 	return homonym_string;
 }
+
+__used static void static_string_function(void)
+{
+	__used static char klp_string[] __asm__("klp_string.67890") =
+		__FILE__ " static string";
+}
tools/testing/selftests/livepatch/test-livepatch.sh +4 -0
index bcb8b468b80a..ec3b6c919b01 100755
@@ -200,6 +200,8 @@ $MOD_KLP_CONVERT1: driver_name, 0: $MOD_KLP_CONVERT_MOD
 $MOD_KLP_CONVERT1: test_klp_get_driver_name(), 0: $MOD_KLP_CONVERT_MOD
 $MOD_KLP_CONVERT1: homonym_string, 1: homonym string A
 $MOD_KLP_CONVERT1: get_homonym_string(), 1: homonym string A
+test_klp_convert1: klp_string.12345 = lib/livepatch/test_klp_convert_mod_a.c static string
+test_klp_convert1: klp_string.67890 = lib/livepatch/test_klp_convert_mod_b.c static string
 % echo 0 > /sys/kernel/livepatch/$MOD_KLP_CONVERT1/enabled
 livepatch: '$MOD_KLP_CONVERT1': initializing unpatching transition
 livepatch: '$MOD_KLP_CONVERT1': starting unpatching transition
@@ -265,6 +267,8 @@ $MOD_KLP_CONVERT1: driver_name, 0: $MOD_KLP_CONVERT_MOD
 $MOD_KLP_CONVERT1: test_klp_get_driver_name(), 0: $MOD_KLP_CONVERT_MOD
 $MOD_KLP_CONVERT1: homonym_string, 1: homonym string A
 $MOD_KLP_CONVERT1: get_homonym_string(), 1: homonym string A
+test_klp_convert1: klp_string.12345 = lib/livepatch/test_klp_convert_mod_a.c static string
+test_klp_convert1: klp_string.67890 = lib/livepatch/test_klp_convert_mod_b.c static string
 % echo 0 > /sys/kernel/livepatch/$MOD_KLP_CONVERT1/enabled
 livepatch: '$MOD_KLP_CONVERT1': initializing unpatching transition
 livepatch: '$MOD_KLP_CONVERT1': starting unpatching transition
Signature · 1 line
2.26.3

I'm not sure how portable it is using __asm__("new.name"), but it seems to work with versions of GCC that I've tried. Other tools like kpatch-build can manipulate such symbols directly, but for anything that needs to feed the C compiler, some kind of workaround is needed to create klp-relocations for them.

FWIW, the trick works through the KLP_SYMPOS macro annotations as well, for example:

  void pfn_valid_part_0(void) __asm__("pfn_valid.part.0");
  KLP_MODULE_RELOC(kvm) kvm_main_relocs[] = {
  	KLP_SYMPOS(pfn_valid_part_0, 0),
  };

-- Joe

#24 lore raw

Re: [RFC PATCH v6 10/12] livepatch/selftests: add __asm__ symbol renaming examples

In reply to Joe Lawrence
[If your patch is applied to the wrong git tree, kindly drop us a note. And when submitting patch, we suggest to use '--base' as documented in https://git-scm.com/docs/git-format-patch]

Hi Joe,

[FYI, it's a private test report for your RFC patch.]
[auto build test WARNING on shuah-kselftest/next]
[also build test WARNING on linux/master masahiroy-kbuild/for-next linus/master v5.17-rc4] [cannot apply to next-20220216]
[If your patch is applied to the wrong git tree, kindly drop us a note.
And when submitting patch, we suggest to use '--base' as documented in
https://git-scm.com/docs/git-format-patch]

url:    https://github.com/0day-ci/linux/commits/Joe-Lawrence/livepatch-klp-convert-tool/20220217-004100
base:   https://git.kernel.org/pub/scm/linux/kernel/git/shuah/linux-kselftest.git next
config: x86_64-allyesconfig (https://download.01.org/0day-ci/archive/20220217/202202171022.bSGoBUDk-lkp(a)intel.com/config)
compiler: gcc-9 (Debian 9.3.0-22) 9.3.0

reproduce (this is a W=1 build):
# https://github.com/0day-ci/linux/commit/290c0e05d31c5bae75aede8758efb48f52751fea
git remote add linux-review https://github.com/0day-ci/linux
git fetch --no-tags linux-review Joe-Lawrence/livepatch-klp-convert-tool/20220217-004100 git checkout 290c0e05d31c5bae75aede8758efb48f52751fea
# save the config file to linux build tree
mkdir build_dir
make W=1 O=build_dir ARCH=x86_64 SHELL=/bin/bash lib/livepatch/

If you fix the issue, kindly add following tag as appropriate

All warnings (new ones prefixed by >>):

lib/livepatch/test_klp_convert1.c:11:6: warning: no previous prototype for 'print_saved_command_line' [-Wmissing-prototypes]
11 | void print_saved_command_line(void)
| ^~~~~~~~~~~~~~~~~~~~~~~~
lib/livepatch/test_klp_convert1.c:16:6: warning: no previous prototype for 'print_driver_name' [-Wmissing-prototypes]
16 | void print_driver_name(void)
| ^~~~~~~~~~~~~~~~~
lib/livepatch/test_klp_convert1.c:22:6: warning: no previous prototype for 'print_homonym_string' [-Wmissing-prototypes]
22 | void print_homonym_string(void)
| ^~~~~~~~~~~~~~~~~~~~

>> lib/livepatch/test_klp_convert1.c:28:6: warning: no previous prototype for 'print_static_strings' [-Wmissing-prototypes]

28 | void print_static_strings(void)
| ^~~~~~~~~~~~~~~~~~~~

vim +/print_static_strings +28 lib/livepatch/test_klp_convert1.c

    27	
  > 28	void print_static_strings(void)
    29	{
    30		pr_info("klp_string.12345 = %s\n", klp_string_a);
    31		pr_info("klp_string.67890 = %s\n", klp_string_b);
    32	}
    33	

---
0-DAY CI Kernel Test Service, Intel Corporation
https://lists.01.org/hyperkitty/list/kbuild-all(a)lists.01.org

author maintainer
#25 lore raw

RFC PATCH v6 11/12 livepatch/selftests: add data relocations test

In reply to Joe Lawrence

Add a test which creates a variety of klp-data-relocations. Note that this test case exercises late-klp-relocations for references to data. For this, we only need to adjust pointer storage classes (and not the target data) to affect where the relocation ends up.

---
 lib/livepatch/Makefile                        |   4 +-
 lib/livepatch/test_klp_convert.h              |  21 ++
 lib/livepatch/test_klp_convert_data.c         | 190 ++++++++++++++++++
 lib/livepatch/test_klp_convert_mod_c.c        |  36 ++++
 .../selftests/livepatch/test-livepatch.sh     |  97 +++++++++
 5 files changed, 347 insertions(+), 1 deletion(-)
 create mode 100644 lib/livepatch/test_klp_convert_data.c
 create mode 100644 lib/livepatch/test_klp_convert_mod_c.c
lib/livepatch/Makefile +3 -1
index 77e21317d4da..da39aaa5c8fc 100644
@@ -9,6 +9,7 @@ obj-$(CONFIG_TEST_LIVEPATCH) += test_klp_atomic_replace.o \
 				test_klp_callbacks_mod.o \
 				test_klp_convert1.o \
 				test_klp_convert2.o \
+				test_klp_convert_data.o \
 				test_klp_convert_sections.o \
 				test_klp_convert_mod.o \
 				test_klp_livepatch.o \
@@ -19,4 +20,5 @@ obj-$(CONFIG_TEST_LIVEPATCH) += test_klp_atomic_replace.o \
 
 test_klp_convert_mod-y := \
 	test_klp_convert_mod_a.o \
-	test_klp_convert_mod_b.o
+	test_klp_convert_mod_b.o \
+	test_klp_convert_mod_c.o
lib/livepatch/test_klp_convert.h +21 -0
index 42befbfd63cb..08c0f4b1dc6b 100644
@@ -12,5 +12,26 @@ extern const char *get_homonym_string(void);
 extern const char *test_klp_get_driver_name(void);
 extern char klp_string_a[] __asm__("klp_string.12345");
 extern char klp_string_b[] __asm__("klp_string.67890");
+extern int global_small;
+// .rela.data.rel.ro, .rela.rodata supported ???:
+extern int const_global_small;
+extern int static_small;
+extern int static_const_small;
+extern int global_large[];
+// .rela.data.rel.ro, .rela.rodata supported ???:
+extern int const_global_large[];
+extern int static_large[];
+extern int static_const_large[];
+extern int local_small;
+extern int const_local_small;
+extern int static_local_small;
+extern int static_const_local_small;
+extern int local_large[4];
+extern int const_local_large[4];
+extern int static_local_large[4];
+extern int static_const_local_large[4];
+// .rela.data..ro_after_init supported ???:
+extern int static_ro_after_init;
+extern int static_read_mostly;
 
 #endif
lib/livepatch/test_klp_convert_data.c new file +190 -0

190 lines not on this page · raw message

lib/livepatch/test_klp_convert_mod_c.c new file +36 -0
new file mode 100644
index 000000000000..2bf11d486548
@@ -0,0 +1,36 @@
+// SPDX-License-Identifier: GPL-2.0
+// Copyright (C) 2021 Joe Lawrence <[email protected]>
+
+#include <linux/types.h>
+
+/*
+ * test_klp_convert_data will create klp-relocations to these variables.
+ * They are named for the storage class of the variable that refers to
+ * the.  This makes it easier to correlate those symbols to the
+ * relocations that refer to them in readelf output.
+ */
+__used static int global_small = 0x1111;
+// .rela.data.rel.ro, .rela.rodata supported ???:
+__used static int const_global_small = 0x2222;
+__used static int static_small = 0x3333;
+__used static int static_const_small = 0x4444;
+
+__used static int global_large[4] = { 0x1111, 0x2222, 0x3333, 0x4444 };
+// .rela.data.rel.ro, .rela.rodata supported ???:
+__used static int const_global_large[4] = { 0x5555, 0x6666, 0x7777, 0x8888 };
+__used static int static_large[4] = { 0x9999, 0xaaaa, 0xbbbb, 0xcccc };
+__used static int static_const_large[4] = { 0xdddd, 0xeeee, 0xffff, 0x0000 };
+
+__used static int local_small = 0x1111;
+__used static int const_local_small = 0x2222;
+__used static int static_local_small = 0x3333;
+__used static int static_const_local_small = 0x4444;
+
+__used static int local_large[4] = { 0x1111, 0x2222, 0x3333, 0x4444 };
+__used static int const_local_large[4] = { 0x5555, 0x6666, 0x7777, 0x8888 };
+__used static int static_local_large[4] = { 0x9999, 0xaaaa, 0xbbbb, 0xcccc };
+__used static int static_const_local_large[4] = { 0xdddd, 0xeeee, 0xffff, 0x0000 };
+
+// .rela.data..ro_after_init supported ???:
+__used static int static_ro_after_init = 0x1111;
+__used static int static_read_mostly = 0x2222;
tools/testing/selftests/livepatch/test-livepatch.sh +97 -0

107 lines not on this page · raw message

Signature · 1 line
2.26.3
author maintainer
#26 lore raw

Re: [RFC PATCH v6 11/12] livepatch/selftests: add data relocations test

Quoted 51 lines · Joe Lawrence

[ ... snip ... ]

lib/livepatch/test_klp_convert_data.c new file +42 -0
new file mode 100644
index 000000000000..142422664159
@@ -0,0 +1,190 @@
+// SPDX-License-Identifier: GPL-2.0
+// Copyright (C) 2021 Joe Lawrence <[email protected]>
+
+#define pr_fmt(fmt) KBUILD_MODNAME ": " fmt
+
+#include <linux/module.h>
+#include <linux/kernel.h>
+#include <linux/cache.h>
+#include <linux/livepatch.h>
+#include "test_klp_convert.h"
+
+/* Small global */
+int *p_global_small = &global_small;
+
+/* Small global (const) */
+// .rela.data.rel.ro, .rela.rodata supported ???:
+int * const p_const_global_small = &const_global_small;
+
+/* Small file-static */
+static int *p_static_small = &static_small;
+
+/* Small file-static (constant) */
+static int * const p_static_const_small = &static_const_small;
+
+/* Large global */
+int *p_global_large[4] = {
+	&global_large[0], &global_large[1],
+	&global_large[2], &global_large[3],
+};
+
+/* Large global (const) */
+// .rela.data.rel.ro, .rela.rodata supported ???:
+int * const p_const_global_large[4] = {
+	&const_global_large[0], &const_global_large[1],
+	&const_global_large[2], &const_global_large[3],
+};
+
+/* Large file-static global */
+static int *p_static_large[4] = {
+	&static_large[0], &static_large[1],
+	&static_large[2], &static_large[3],
+};

lib/livepatch/test_klp_convert_data.c line 52

Quoted 10 lines
lib/livepatch/test_klp_convert_data.c new file +10 -0
+
+/* Large file-static (const) */
+static int * const p_static_const_large[4] = {
+	&static_const_large[0], &static_const_large[1],
+	&static_const_large[2], &static_const_large[3],
+};
+
+// .rela.data.rel.ro, .rela.rodata supported ???:
+static int * __ro_after_init p_static_ro_after_init = &static_ro_after_init;
+static int * __read_mostly p_static_read_mostly = &static_read_mostly;

This started getting a bit repetitive, and maybe belongs to its own set of klp-convert unit tests (as the selftests seem closer to integration type tests).

Anyway, I left in the .rela.<read-only> type relocations as mentioned in the [RFC PATCH v6 03/12] livepatch: Add klp-convert tool [1]. We can talk about whether such sections should be supported over there.

As for this test, it currently crashes ppc64le as it generates a late klp-relocation type R_PPC64_ADDR64 in a section that was marked RO. (IIRC such ppc64le data relocations to other .rela.<text> sections are safe as they aren't marked RO.)

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

-- Joe

author maintainer
#27 lore raw

RFC PATCH v6 12/12 livepatch/selftests: add static keys test

In reply to Joe Lawrence

Add a livepatch kselftest that exercises klp-convert support for static keys:

- Use static_branch_(un)likely() on vmlinux-defined keys, forcing .rela__jump_table klp-relocations for them.

- Use only static_key_enable() on module-defined keys, creating .text klp-relocations for them.

---
 lib/livepatch/Makefile                        |   2 +
 lib/livepatch/test_klp_convert.h              |   8 ++
 lib/livepatch/test_klp_convert_keys.c         |  91 +++++++++++++
 lib/livepatch/test_klp_convert_keys_mod.c     |  52 +++++++
 .../selftests/livepatch/test-livepatch.sh     | 127 ++++++++++++++++++
 5 files changed, 280 insertions(+)
 create mode 100644 lib/livepatch/test_klp_convert_keys.c
 create mode 100644 lib/livepatch/test_klp_convert_keys_mod.c
lib/livepatch/Makefile +2 -0
index da39aaa5c8fc..a3c2ac61387f 100644
@@ -11,6 +11,8 @@ obj-$(CONFIG_TEST_LIVEPATCH) += test_klp_atomic_replace.o \
 				test_klp_convert2.o \
 				test_klp_convert_data.o \
 				test_klp_convert_sections.o \
+				test_klp_convert_keys.o \
+				test_klp_convert_keys_mod.o \
 				test_klp_convert_mod.o \
 				test_klp_livepatch.o \
 				test_klp_shadow_vars.o \
lib/livepatch/test_klp_convert.h +8 -0
index 08c0f4b1dc6b..97d4c26e4c39 100644
@@ -34,4 +34,12 @@ extern int static_const_local_large[4];
 extern int static_ro_after_init;
 extern int static_read_mostly;
 
+/* klp-convert symbols - vmlinux */
+extern struct static_key_false tracepoint_printk_key;
+
+/* klp-convert symbols - test_klp_keys_mod.ko */
+extern struct static_key_true test_klp_true_key;
+extern struct static_key_false test_klp_false_key;
+
+
 #endif
lib/livepatch/test_klp_convert_keys.c new file +91 -0

91 lines not on this page · raw message

lib/livepatch/test_klp_convert_keys_mod.c new file +52 -0

52 lines not on this page · raw message

tools/testing/selftests/livepatch/test-livepatch.sh +127 -0

137 lines not on this page · raw message

Signature · 1 line
2.26.3
author maintainer
#28 lore raw
In reply to Joe Lawrence
Quoted 14 lines · Joe Lawrence

[ ... snip ... ]

 lib/livepatch/Makefile                        |  12 +
 lib/livepatch/test_klp_convert.h              |  45 +
 lib/livepatch/test_klp_convert1.c             | 121 +++
 lib/livepatch/test_klp_convert2.c             | 110 +++
 lib/livepatch/test_klp_convert_data.c         | 190 ++++
 lib/livepatch/test_klp_convert_keys.c         |  91 ++
 lib/livepatch/test_klp_convert_keys_mod.c     |  52 +
 lib/livepatch/test_klp_convert_mod_a.c        |  31 +
 lib/livepatch/test_klp_convert_mod_b.c        |  19 +
 lib/livepatch/test_klp_convert_mod_c.c        |  36 +
 lib/livepatch/test_klp_convert_sections.c     | 120 +++

A general (selftests) question: is there any build mechanism in the kernel tree that is used to *expect* build failure?

Under certain circumstances, we would need klp-convert to fail and it would be helpful to test for that. At the moment I am considered out of tree tests that could exercise the code this way, but definitely prefer anything that is already in-tree.

Thanks,

-- Joe

#29 lore raw
In reply to Joe Lawrence
Quoted 69 lines · Joe Lawrence

This mostly a rebase update of the livepatch klp-convert tool used to generate klp-relocation types (explained in the summary below).

I'm marking this as an RFC as it hasn't been extensively tested for all livepatch supported arches. There are may be a few symbol annotation changes pending what may be implemented for the FGKASLR patchset, I've left a few TODO and // question? marks in the code, etc. At the same time, I think "CET/IBT support and live-patches" highlighted a potential need for this tooling, so I'm posting it in its current format for discussion. I'll reply to individual patches to highlight a few points of interest.

Summary
-------

Livepatches may use symbols which are not contained in its own scope, and, because of that, may end up compiled with relocations that will only be resolved during module load. Yet, when the referenced symbols are not exported, solving this relocation requires information on the object that holds the symbol (either vmlinux or modules) and its position inside the object, as an object may contain multiple symbols with the same name. Providing such information must be done accordingly to what is specified in Documentation/livepatch/module-elf-format.txt.

Currently, there is no trivial way to embed the required information as requested in the final livepatch elf object. klp-convert solves this problem in two different forms: (i) by relying on a symbol map, which is built during kernel compilation, to automatically infer the relocation targeted symbol, and, when such inference is not possible (ii) by using annotations in the elf object to convert the relocation accordingly to the specification, enabling it to be handled by the livepatch loader.

Given the above, add support for symbol mapping in the form of a symbols.klp file; add klp-convert tool; integrate klp-convert tool into kbuild; make livepatch modules discernible during kernel compilation pipeline; add data-structure and macros to enable users to annotate livepatch source code; make modpost stage compatible with livepatches; update livepatch-sample and update documentation.

The patch was tested under three use-cases:

use-case 1: There is a relocation in the lp that can be automatically resolved by klp-convert. For example. see the saved_command_line variable in lib/livepatch/test_klp_convert2.c.

use-case 2: There is a relocation in the lp that cannot be automatically resolved, as the name of the respective symbol appears in multiple objects. The livepatch contains an annotation to enable a correct relocation. See the KLP_MODULE_RELOC / KLP_SYMPOS annotation sections in lib/livepatch/test_klp_convert{1,2}.c.

use-case 3: There is a relocation in the lp that cannot be automatically resolved similarly as 2, but no annotation was provided in the livepatch, triggering an error during compilation. Reproducible by removing the KLP_MODULE_RELOC / KLP_SYMPOS annotation sections in lib/livepatch/test_klp_convert{1,2}.c.

Selftests have been added to exercise these klp-convert use-cases through several tests.

Branches
--------

Previous versions
-----------------

Quoted 14 lines

RFC:
https://lore.kernel.org/lkml/[email protected]/
v2:
https://lore.kernel.org/lkml/[email protected]/
v3:
https://lore.kernel.org/lkml/[email protected]/
v4:
https://lore.kernel.org/lkml/[email protected]/
v5:
(not posted)
https://github.com/joe-lawrence/klp-convert-tree/tree/klp-convert-v5-devel
v6:
https://github.com/joe-lawrence/klp-convert-tree/tree/klp-convert-v6
https://github.com/joe-lawrence/klp-convert-tree/tree/klp-convert-v6-devel

Hi Joe,

I send reviews to some patches of the v6 batch, but there is currently a v7 in your github profile. I believe that I sent Rb for patches that are the same between versions.

The current version is almost one year older already. Do you plan to send v7 soon?

Thanks a lot!
Marcos

Quoted 117 lines

Summary of changes in v5
------------------------

[For/from Masahiro]
- rename Symbols.list to symbols.klp
- remove HOST_EXTRACFLAGS from klp-convert build
- kbuild tweaks from Masahiro Yamada
- SPDX instead of the license boilerplate

[Joe]
- a bunch of small checkpatch, clang-check fixes
- klp-convert: account for symbols shared across sections
- klp-convert: sympos endianness for cross-compile
- klp-convert: implement rela section support list
- klp-convert: update group sections sh_link
- klp-convert: flag annotations without relocations
- klp-convert: allow .rela__jump_table to vmlinux
- livepatch/selftests: Add __asm__ symbol renaming examples
- livepatch/selftests: test multiple sections
- livepatch/selftests: add static keys test

[Miroslav]
- klp-convert: use _safe list traversals only when required
- klp-convert: separate rela conversation from removal

Summary of changes in v6
------------------------

[For/from Christophe]
- klp-convert: Support for ppc32 ELF files

[Joe]
- livepatch/selftests: add data relocations test
- klp-convert: move relas to klp_rela_sec tail
- rebase for v5.17-rc1

Joao Moreira (2):
kbuild: Support for symbols.klp creation
documentation: Update on livepatch elf format

Joe Lawrence (5):
livepatch/selftests: add klp-convert livepatch/selftests: test multiple sections livepatch/selftests: add __asm__ symbol renaming examples livepatch/selftests: add data relocations test livepatch/selftests: add static keys test

Josh Poimboeuf (5):
livepatch: Create and include UAPI headers
livepatch: Add klp-convert tool
livepatch: Add klp-convert annotation helpers
modpost: Integrate klp-convert
livepatch: Add sample livepatch module

 .gitignore                                    |   2 +
 Documentation/dontdiff                        |   1 +
 Documentation/livepatch/livepatch.rst         |   3 +
 Documentation/livepatch/module-elf-format.rst |  42 +-
 MAINTAINERS                                   |   2 +
 Makefile                                      |  12 +-
 include/linux/livepatch.h                     |  13 +
 include/uapi/linux/livepatch.h                |  25 +
 kernel/livepatch/core.c                       |   4 +-
 lib/livepatch/Makefile                        |  12 +
 lib/livepatch/test_klp_convert.h              |  45 +
 lib/livepatch/test_klp_convert1.c             | 121 +++
 lib/livepatch/test_klp_convert2.c             | 110 +++
 lib/livepatch/test_klp_convert_data.c         | 190 ++++
 lib/livepatch/test_klp_convert_keys.c         |  91 ++
 lib/livepatch/test_klp_convert_keys_mod.c     |  52 +
 lib/livepatch/test_klp_convert_mod_a.c        |  31 +
 lib/livepatch/test_klp_convert_mod_b.c        |  19 +
 lib/livepatch/test_klp_convert_mod_c.c        |  36 +
 lib/livepatch/test_klp_convert_sections.c     | 120 +++
 samples/livepatch/Makefile                    |   1 +
 .../livepatch/livepatch-annotated-sample.c    |  93 ++
 scripts/Makefile                              |   1 +
 scripts/Makefile.modfinal                     |  38 +-
 scripts/Makefile.modpost                      |   5 +
 scripts/livepatch/.gitignore                  |   1 +
 scripts/livepatch/Makefile                    |   5 +
 scripts/livepatch/elf.c                       | 813 ++++++++++++++++
 scripts/livepatch/elf.h                       |  74 ++
 scripts/livepatch/klp-convert.c               | 885 ++++++++++++++++++
 scripts/livepatch/klp-convert.h               |  47 +
 scripts/livepatch/list.h                      | 391 ++++++++
 scripts/mod/modpost.c                         |  28 +-
 scripts/mod/modpost.h                         |   1 +
 .../selftests/livepatch/test-livepatch.sh     | 405 ++++++++
 35 files changed, 3708 insertions(+), 11 deletions(-)
 create mode 100644 include/uapi/linux/livepatch.h
 create mode 100644 lib/livepatch/test_klp_convert.h
 create mode 100644 lib/livepatch/test_klp_convert1.c
 create mode 100644 lib/livepatch/test_klp_convert2.c
 create mode 100644 lib/livepatch/test_klp_convert_data.c
 create mode 100644 lib/livepatch/test_klp_convert_keys.c
 create mode 100644 lib/livepatch/test_klp_convert_keys_mod.c
 create mode 100644 lib/livepatch/test_klp_convert_mod_a.c
 create mode 100644 lib/livepatch/test_klp_convert_mod_b.c
 create mode 100644 lib/livepatch/test_klp_convert_mod_c.c
 create mode 100644 lib/livepatch/test_klp_convert_sections.c
 create mode 100644 samples/livepatch/livepatch-annotated-sample.c
 create mode 100644 scripts/livepatch/.gitignore
 create mode 100644 scripts/livepatch/Makefile
 create mode 100644 scripts/livepatch/elf.c
 create mode 100644 scripts/livepatch/elf.h
 create mode 100644 scripts/livepatch/klp-convert.c
 create mode 100644 scripts/livepatch/klp-convert.h
 create mode 100644 scripts/livepatch/list.h
Signature · 1 line
2.26.3
author maintainer
#30 lore raw
Quoted 85 lines · Marcos Paulo de Souza
Quoted 69 lines · Joe Lawrence

This mostly a rebase update of the livepatch klp-convert tool used to generate klp-relocation types (explained in the summary below).

I'm marking this as an RFC as it hasn't been extensively tested for all livepatch supported arches. There are may be a few symbol annotation changes pending what may be implemented for the FGKASLR patchset, I've left a few TODO and // question? marks in the code, etc. At the same time, I think "CET/IBT support and live-patches" highlighted a potential need for this tooling, so I'm posting it in its current format for discussion. I'll reply to individual patches to highlight a few points of interest.

Summary
-------

Livepatches may use symbols which are not contained in its own scope, and, because of that, may end up compiled with relocations that will only be resolved during module load. Yet, when the referenced symbols are not exported, solving this relocation requires information on the object that holds the symbol (either vmlinux or modules) and its position inside the object, as an object may contain multiple symbols with the same name. Providing such information must be done accordingly to what is specified in Documentation/livepatch/module-elf-format.txt.

Currently, there is no trivial way to embed the required information as requested in the final livepatch elf object. klp-convert solves this problem in two different forms: (i) by relying on a symbol map, which is built during kernel compilation, to automatically infer the relocation targeted symbol, and, when such inference is not possible (ii) by using annotations in the elf object to convert the relocation accordingly to the specification, enabling it to be handled by the livepatch loader.

Given the above, add support for symbol mapping in the form of a symbols.klp file; add klp-convert tool; integrate klp-convert tool into kbuild; make livepatch modules discernible during kernel compilation pipeline; add data-structure and macros to enable users to annotate livepatch source code; make modpost stage compatible with livepatches; update livepatch-sample and update documentation.

The patch was tested under three use-cases:

use-case 1: There is a relocation in the lp that can be automatically resolved by klp-convert. For example. see the saved_command_line variable in lib/livepatch/test_klp_convert2.c.

use-case 2: There is a relocation in the lp that cannot be automatically resolved, as the name of the respective symbol appears in multiple objects. The livepatch contains an annotation to enable a correct relocation. See the KLP_MODULE_RELOC / KLP_SYMPOS annotation sections in lib/livepatch/test_klp_convert{1,2}.c.

use-case 3: There is a relocation in the lp that cannot be automatically resolved similarly as 2, but no annotation was provided in the livepatch, triggering an error during compilation. Reproducible by removing the KLP_MODULE_RELOC / KLP_SYMPOS annotation sections in lib/livepatch/test_klp_convert{1,2}.c.

Selftests have been added to exercise these klp-convert use-cases through several tests.

Branches
--------

Previous versions
-----------------

Quoted 14 lines

RFC:
https://lore.kernel.org/lkml/[email protected]/
v2:
https://lore.kernel.org/lkml/[email protected]/
v3:
https://lore.kernel.org/lkml/[email protected]/
v4:
https://lore.kernel.org/lkml/[email protected]/
v5:
(not posted)
https://github.com/joe-lawrence/klp-convert-tree/tree/klp-convert-v5-devel
v6:
https://github.com/joe-lawrence/klp-convert-tree/tree/klp-convert-v6
https://github.com/joe-lawrence/klp-convert-tree/tree/klp-convert-v6-devel

Quoted 9 lines

Hi Joe,

I send reviews to some patches of the v6 batch, but there is currently a v7 in your github profile. I believe that I sent Rb for patches that are the same between versions.

The current version is almost one year older already. Do you plan to send v7 soon?

Hi Marcos,

Thanks for the reviews and indeed, it has been a while since v6.

For v7, I would like to rebase on top of v6.2 so it includes the recent x86/ppc64le relocation fixes from Song/Josh.

There are still a fair number of design questions that I have.. but a fresh version will be much easier to test and review. I'll try to get it posted in the new few weeks.

Signature · 1 line
Joe