Skip to contentSkip to conversation

klp-convert livepatch build tooling

PATCH Superseded Joe Lawrence 7 participants 42 messages Apr 10, 2019 – May 6, 2019

Subsystems (4)

v3 of 4 Superseded Latest is v4 →

lore
Share & tools
lore

Joe Lawrence

author maintainer
#0 lore raw

v3 cover klp-convert livepatch build tooling

Hi folks,

This is the third installment of the klp-convert tool for generating and processing livepatch symbols for livepatch module builds. For those following along at home, archive links to previous versions:

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

(Note that I don't see v2 archived at lore, but that is a link to the most recent subthread that lore did catch.)

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 Symbols.list 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.

Branches
--------

Since I spent some time tinkering with v2 and accumulated a bunch of fixes, I collected them up and am posting this new version. For review purposes, I posted two branches up to github:

1 - an expanded branch that with changes separate from the original
https://github.com/joe-lawrence/linux/commits/klp-convert-v3-expanded

2 - a squashed branch of (1) that comprises v3:
https://github.com/joe-lawrence/linux/commits/klp-convert-v3

Non-trivial commits in the expanded branch have some extra commentary and details for debugging in the commit message that were dropped when squashing into their respective parent commits.

TODO
----

There are a few outstanding items that I came across while reviewing v2, but as changes started accumulating, it made sense to defer those to a later version. I'll reply to this thread individual topics to start discussion sub-threads for those.

Changelogs
----------

The commit changelogs were getting long, so I've moved them here for posterity and review purposes:

livepatch: Create and include UAPI headers
v2:
- jmoreira: split up and changelog
v3:
- joe: convert to SPDX license tags

kbuild: Support for Symbols.list creation
v3:
- jmoreira: adjust for multiobject livepatch
- joe: add klpclean to PHONY
- joe: align KLP prefix

livepatch: Add klp-convert tool
v2:
- khlebnikov: use HOSTLOADLIBES_ instead of HOSTLDFLAGS: -lelf must be at the end
- jmoreira: add support to automatic relocation conversion in klp-convert.c, changelog
v3:
- joe: convert to SPDX license tags
- jmoreira: add rela symbol name to WARNs
- jmoreira: ignore relocations to .TOC and symbols with index 0
- joe: separate and fix valid_sympos() sympos=0 and sympos=1..n checks
- joe: fix symbol use-after-frees
- joe: fix remaining valgrind leak complaints (non-error paths only)
- joe: checkpatch nits

livepatch: Add klp-convert annotation helpers
v2:
- jmoreira: split up: move KLP_MODULE_RELOC from previous patch to here, add KLP_SYMPOS, move macros from include/uapi/livepatch.h to include/linux/livepatch.h
v3:
- joe: suggested by jpoimboe, KLP_MODULE_RELOC macro should 4-byte align klp_module_reloc structures

modpost: Integrate klp-convert
v2:
- khlebnikov: save cmd_ld_ko_o into .module.cmd, if_changed_rule doesn't do that.f
- khlebnikov: fix bashisms for debian where /bin/sh is a symlink to /bin/dash
- khlebnikov: rename rule_link_module to rule_ld_ko_o, otherwise arg-check inside if_changed_rule compares cmd_link_module and cmd_ld_ko_o.
- khlebnikov: check modinfo -F livepatch only if CONFIG_LIVEPATCH is true.
- mbenes: remove modinfo call. LIVEPATCH_ in Makefile
- jmoreira: split up: move the .livepatch file-based scheme for identifying livepatches to a previous patch, as it was required for correctly building Symbols.list there.
v3:
- joe: adjust rule_ld_ko_o to call echo-cmd
- joe: rebase for v5.1
- joe: align KLP prefix

modpost: Add modinfo flag to livepatch modules
v2:
- jmoreira: fix modpost.c (add_livepatch_flag) to update module structure with livepatch flag and prevent modpost from breaking due to unresolved symbols
v3:
- joe: adjust modpost.c::get_modinfo() call for v5.0 version

livepatch: Add sample livepatch module
v3:
- joe: update all in-tree livepatches with LIVEPATCH_* modinfo flag

documentation: Update on livepatch elf format
v2:
- jmoreira: update module to use KLP_SYMPOS
- jmoreira: Comments on symbol resolution scheme
- jmoreira: Update Makefile
- jmoreira: Remove MODULE_INFO statement
- jmoreira: Changelog
v3:
- joe: rebase for v5.1
- joe: code shuffle to better match original source file

livepatch/selftests: add klp-convert
v3:
- joe: clarify sympos=0 and sympos=1..n

And now the usual git cover-letter boilerplate...

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

Joe Lawrence (1):
livepatch/selftests: add klp-convert

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

Miroslav Benes (1):
modpost: Add modinfo flag to livepatch modules

 .gitignore                                    |   1 +
 Documentation/livepatch/livepatch.txt         |   3 +
 Documentation/livepatch/module-elf-format.txt |  50 +-
 MAINTAINERS                                   |   2 +
 Makefile                                      |  30 +-
 include/linux/livepatch.h                     |  13 +
 include/uapi/linux/livepatch.h                |  22 +
 kernel/livepatch/core.c                       |   4 +-
 lib/livepatch/Makefile                        |  15 +
 lib/livepatch/test_klp_atomic_replace.c       |   1 -
 lib/livepatch/test_klp_callbacks_demo.c       |   1 -
 lib/livepatch/test_klp_callbacks_demo2.c      |   1 -
 lib/livepatch/test_klp_convert1.c             | 106 +++
 lib/livepatch/test_klp_convert2.c             | 103 +++
 lib/livepatch/test_klp_convert_mod_a.c        |  25 +
 lib/livepatch/test_klp_convert_mod_b.c        |  13 +
 lib/livepatch/test_klp_livepatch.c            |   1 -
 samples/livepatch/Makefile                    |   7 +
 .../livepatch/livepatch-annotated-sample.c    | 102 +++
 samples/livepatch/livepatch-sample.c          |   1 -
 scripts/Kbuild.include                        |   4 +-
 scripts/Makefile                              |   1 +
 scripts/Makefile.build                        |   7 +
 scripts/Makefile.modpost                      |  24 +-
 scripts/livepatch/.gitignore                  |   1 +
 scripts/livepatch/Makefile                    |   7 +
 scripts/livepatch/elf.c                       | 753 ++++++++++++++++++
 scripts/livepatch/elf.h                       |  72 ++
 scripts/livepatch/klp-convert.c               | 692 ++++++++++++++++
 scripts/livepatch/klp-convert.h               |  39 +
 scripts/livepatch/list.h                      | 391 +++++++++
 scripts/mod/modpost.c                         |  82 +-
 scripts/mod/modpost.h                         |   1 +
 .../selftests/livepatch/test-livepatch.sh     |  64 ++
 34 files changed, 2616 insertions(+), 23 deletions(-)
 create mode 100644 include/uapi/linux/livepatch.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
 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.20.1
author maintainer
#1 lore raw

PATCH v3 1/9 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 | 17 +++++++++++++++++
 kernel/livepatch/core.c        |  4 ++--
 4 files changed, 21 insertions(+), 2 deletions(-)
 create mode 100644 include/uapi/linux/livepatch.h
MAINTAINERS +1 -0
index 2359e12e4c41..65b4e8f481f0 100644
@@ -9017,6 +9017,7 @@ R:	Joe Lawrence <[email protected]>
 S:	Maintained
 F:	kernel/livepatch/
 F:	include/linux/livepatch.h
+F:	include/uapi/linux/livepatch.h
 F:	arch/x86/include/asm/livepatch.h
 F:	arch/x86/kernel/livepatch.c
 F:	Documentation/livepatch/
include/linux/livepatch.h +1 -0
index 53551f470722..16b48e8b29a2 100644
@@ -25,6 +25,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 +17 -0
new file mode 100644
index 000000000000..bb86243de805
@@ -0,0 +1,17 @@
+/* SPDX-License-Identifier: GPL-2.0 */
+
+/*
+ * livepatch.h - Kernel Live Patching Core
+ *
+ * Copyright (C) 2016 Josh Poimboeuf <[email protected]>
+ */
+
+#ifndef _UAPI_LIVEPATCH_H
+#define _UAPI_LIVEPATCH_H
+
+#include <linux/types.h>
+
+#define KLP_RELA_PREFIX		".klp.rela."
+#define KLP_SYM_PREFIX		".klp.sym."
+
+#endif /* _UAPI_LIVEPATCH_H */
kernel/livepatch/core.c +2 -2
index eb0ee10a1981..3d9ed895b252 100644
@@ -235,7 +235,7 @@ static int klp_resolve_symbols(Elf_Shdr *relasec, struct module *pmod)
 
 		/* Format: .klp.sym.objname.symname,sympos */
 		cnt = sscanf(strtab + sym->st_name,
-			     ".klp.sym.%55[^.].%127[^,],%lu",
+			     KLP_SYM_PREFIX "%55[^.].%127[^,],%lu",
 			     objname, symname, &sympos);
 		if (cnt != 3) {
 			pr_err("symbol %s has an incorrectly formatted name\n",
@@ -281,7 +281,7 @@ static int klp_write_object_relocations(struct module *pmod,
 		 * See comment in klp_resolve_symbols() for an explanation
 		 * of the selected field width value.
 		 */
-		cnt = sscanf(secname, ".klp.rela.%55[^.]", sec_objname);
+		cnt = sscanf(secname, KLP_RELA_PREFIX "%55[^.]", sec_objname);
 		if (cnt != 1) {
 			pr_err("section %s has an incorrectly formatted name\n",
 			       secname);
Signature · 1 line
2.20.1
#2 lore raw

Re: [PATCH v3 1/9] livepatch: Create and include UAPI headers

Quoted 30 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.

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 | 17 +++++++++++++++++
 kernel/livepatch/core.c        |  4 ++--
 4 files changed, 21 insertions(+), 2 deletions(-)
 create mode 100644 include/uapi/linux/livepatch.h
include/uapi/linux/livepatch.h new file +0 -0
new file mode 100644
index 000000000000..bb86243de805

include/uapi/linux/livepatch.h line 1

Quoted 1 line
include/uapi/linux/livepatch.h new file +1 -0
@@ -0,0 +1,17 @@
+/* SPDX-License-Identifier: GPL-2.0 */

In my understanding, UAPI headers should be licensed under:

/* SPDX-License-Identifier: GPL-2.0 WITH Linux-syscall-note */

include/uapi/linux/livepatch.h line 12

Quoted 11 lines
include/uapi/linux/livepatch.h new file +11 -0
+
+/*
+ * livepatch.h - Kernel Live Patching Core
+ *
+ * Copyright (C) 2016 Josh Poimboeuf <[email protected]>
+ */
+
+#ifndef _UAPI_LIVEPATCH_H
+#define _UAPI_LIVEPATCH_H
+
+#include <linux/types.h>

Why is this include needed?

include/uapi/linux/livepatch.h line 15

Quoted 2 lines
include/uapi/linux/livepatch.h new file +2 -0
+#define KLP_RELA_PREFIX                ".klp.rela."
+#define KLP_SYM_PREFIX         ".klp.sym."

These do not depend on <linux/types.h>

Quoted 2 lines
include/uapi/linux/livepatch.h new file +2 -0
+
+#endif /* _UAPI_LIVEPATCH_H */
Signature · 2 lines
Best Regards
Masahiro Yamada
author maintainer
#3 lore raw

Re: [PATCH v3 1/9] livepatch: Create and include UAPI headers

Quoted 20 lines · Masahiro Yamada
Quoted 14 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.

[ ... snip ... ]

include/uapi/linux/livepatch.h new file +0 -0
new file mode 100644
index 000000000000..bb86243de805

include/uapi/linux/livepatch.h line 1

Quoted 1 line
include/uapi/linux/livepatch.h new file +1 -0
@@ -0,0 +1,17 @@
+/* SPDX-License-Identifier: GPL-2.0 */

In my understanding, UAPI headers should be licensed under:

Quoted 3 lines

/* SPDX-License-Identifier: GPL-2.0 WITH Linux-syscall-note */

Good eye, that is an interesting licensing detail. Easy enough to update assuming Josh (original author) is fine with adding the modifier.

Quoted 15 lines

include/uapi/linux/livepatch.h line 12

Quoted 11 lines
include/uapi/linux/livepatch.h new file +11 -0
+
+/*
+ * livepatch.h - Kernel Live Patching Core
+ *
+ * Copyright (C) 2016 Josh Poimboeuf <[email protected]>
+ */
+
+#ifndef _UAPI_LIVEPATCH_H
+#define _UAPI_LIVEPATCH_H
+
+#include <linux/types.h>

Why is this include needed?

Quoted 5 lines

include/uapi/linux/livepatch.h line 15

Quoted 2 lines
include/uapi/linux/livepatch.h new file +2 -0
+#define KLP_RELA_PREFIX                ".klp.rela."
+#define KLP_SYM_PREFIX         ".klp.sym."

These do not depend on <linux/types.h>

Hmmm, types.h has been included since v1, but I just verified that removing it results in a clean build, so you are correct that it is (now) unnecessary.

Thanks,

-- Joe

#4 lore raw

Re: [PATCH v3 1/9] livepatch: Create and include UAPI headers

Quoted 21 lines · Joe Lawrence
Quoted 20 lines · Masahiro Yamada
Quoted 14 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.

[ ... snip ... ]

include/uapi/linux/livepatch.h new file +0 -0
new file mode 100644
index 000000000000..bb86243de805

include/uapi/linux/livepatch.h line 1

Quoted 1 line
include/uapi/linux/livepatch.h new file +1 -0
@@ -0,0 +1,17 @@
+/* SPDX-License-Identifier: GPL-2.0 */

In my understanding, UAPI headers should be licensed under:

Quoted 6 lines
Quoted 3 lines

/* SPDX-License-Identifier: GPL-2.0 WITH Linux-syscall-note */

Good eye, that is an interesting licensing detail. Easy enough to update assuming Josh (original author) is fine with adding the modifier.

Sure.

(and sorry, still behind on reviewing the rest of the changes...)

Signature · 1 line
Josh
maintainer
#5 lore raw

Re: [PATCH v3 1/9] livepatch: Create and include UAPI headers

In reply to Joe Lawrence
Quoted 15 lines
Quoted 15 lines

include/uapi/linux/livepatch.h line 12

Quoted 11 lines
include/uapi/linux/livepatch.h new file +11 -0
+
+/*
+ * livepatch.h - Kernel Live Patching Core
+ *
+ * Copyright (C) 2016 Josh Poimboeuf <[email protected]>
+ */
+
+#ifndef _UAPI_LIVEPATCH_H
+#define _UAPI_LIVEPATCH_H
+
+#include <linux/types.h>

Why is this include needed?

Quoted 8 lines
Quoted 5 lines

include/uapi/linux/livepatch.h line 15

Quoted 2 lines
include/uapi/linux/livepatch.h new file +2 -0
+#define KLP_RELA_PREFIX                ".klp.rela."
+#define KLP_SYM_PREFIX         ".klp.sym."

These do not depend on <linux/types.h>

Hmmm, types.h has been included since v1, but I just verified that removing it results in a clean build, so you are correct that it is (now) unnecessary.

Yes, I mentioned it while reviewing v2. Unfortunately, it seems to get lost due to unexplained submitting hiccups. Better to walk through my emails again and make sure nothing more falls through the cracks...

Miroslav

author maintainer
#6 lore raw

PATCH v3 2/9 kbuild: Support for Symbols.list creation

In reply to Joe Lawrence

From: Joao Moreira <[email protected]>

For automatic resolution of livepatch relocations, a file called Symbols.list 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.list in the main Makefile. First, ensure that built-in is compiled when CONFIG_LIVEPATCH is enabled (as required to achieve a complete Symbols.list file). Define the command to build Symbols.list (cmd_klp_map) and hook it in the modules rule.

As it is undesirable to have symbols from livepatch objects inside Symbols.list, 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.list is removed during clean.

Notes:

To achieve a correct Symbols.list 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.list 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.list 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.list.

---
 .gitignore                 |  1 +
 Makefile                   | 30 ++++++++++++++++++++++++++----
 samples/livepatch/Makefile |  1 +
 scripts/Makefile.build     |  7 +++++++
 4 files changed, 35 insertions(+), 4 deletions(-)
.gitignore +1 -0
index a20ac26aa2f5..5cd5758f5ffe 100644
@@ -45,6 +45,7 @@
 *.xz
 Module.symvers
 modules.builtin
+Symbols.list
 
 #
 # Top-level generic files
Makefile +26 -4
index 15c8251d4d5e..2c07bdd87b2f 100644
@@ -574,10 +574,13 @@ KBUILD_BUILTIN := 1
 # If we have only "make modules", don't compile built-in objects.
 # When we're building modules with modversions, we need to consider
 # the built-in objects during the descend as well, in order to
-# make sure the checksums are up to date before we record them.
+# make sure the checksums are up to date before we record them. The
+# same applies for building livepatches, 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 := $(if $(CONFIG_MODVERSIONS),1)
+  KBUILD_BUILTIN := $(if $(or $(CONFIG_MODVERSIONS), $(CONFIG_LIVEPATCH)),1)
 endif
 
 # If we have "make <whatever> modules", compile modules
@@ -1261,9 +1264,25 @@ all: modules
 # duplicate lines in modules.order files.  Those are removed
 # using awk while concatenating to the final file.
 
+quiet_cmd_klp_map = KLP     Symbols.list
+SLIST = $(objtree)/Symbols.list
+
+define cmd_klp_map
+	$(shell echo "klp-convert-symbol-data.0.1" > $(SLIST))				\
+	$(shell echo "*vmlinux" >> $(SLIST))						\
+	$(shell nm -f posix $(objtree)/vmlinux | cut -d\  -f1 >> $(SLIST))		\
+	$(foreach m, $(wildcard $(MODVERDIR)/*.mod),					\
+		$(eval mod = $(patsubst %.ko,%.o,$(shell head -n1 $(m))))		\
+		$(if $(wildcard $(MODVERDIR)/$(shell basename -s .o $(mod)).livepatch),,\
+			$(eval fmod = $(subst $(quote),_,$(subst -,_,$(mod))))		\
+			$(shell echo "*$(shell basename -s .o $(fmod))" >> $(SLIST))	\
+			$(shell nm -f posix $(mod) | cut -d\  -f1 >> $(SLIST))))
+endef
+
 PHONY += modules
 modules: $(vmlinux-dirs) $(if $(KBUILD_BUILTIN),vmlinux) modules.builtin
 	$(Q)$(AWK) '!x[$$0]++' $(vmlinux-dirs:%=$(objtree)/%/modules.order) > $(objtree)/modules.order
+	$(if $(CONFIG_LIVEPATCH), $(call cmd,klp_map))
 	@$(kecho) '  Building modules, stage 2.';
 	$(Q)$(MAKE) -f $(srctree)/scripts/Makefile.modpost
 
@@ -1350,7 +1369,7 @@ clean: rm-dirs  := $(CLEAN_DIRS)
 clean: rm-files := $(CLEAN_FILES)
 clean-dirs      := $(addprefix _clean_, . $(vmlinux-alldirs) Documentation samples)
 
-PHONY += $(clean-dirs) clean archclean vmlinuxclean
+PHONY += $(clean-dirs) clean archclean vmlinuxclean klpclean
 $(clean-dirs):
 	$(Q)$(MAKE) $(clean)=$(patsubst _clean_%,%,$@)
 
@@ -1358,7 +1377,10 @@ vmlinuxclean:
 	$(Q)$(CONFIG_SHELL) $(srctree)/scripts/link-vmlinux.sh clean
 	$(Q)$(if $(ARCH_POSTLINK), $(MAKE) -f $(ARCH_POSTLINK) clean)
 
-clean: archclean vmlinuxclean
+klpclean:
+	$(Q) rm -f $(objtree)/Symbols.list
+
+clean: archclean vmlinuxclean klpclean
 
 # mrproper - Delete all generated files, including .config
 #
samples/livepatch/Makefile +1 -0
index 2472ce39a18d..8b9b42a258ad 100644
@@ -1,3 +1,4 @@
+LIVEPATCH_livepatch-sample := y
 obj-$(CONFIG_SAMPLE_LIVEPATCH) += livepatch-sample.o
 obj-$(CONFIG_SAMPLE_LIVEPATCH) += livepatch-shadow-mod.o
 obj-$(CONFIG_SAMPLE_LIVEPATCH) += livepatch-shadow-fix1.o
scripts/Makefile.build +7 -0
index 76ca30cc4791..ca76bd2080f0 100644
@@ -246,6 +246,11 @@ cmd_gen_ksymdeps = \
 	$(CONFIG_SHELL) $(srctree)/scripts/gen_ksymdeps.sh $@ >> $(dot-target).cmd
 endif
 
+ifdef CONFIG_LIVEPATCH
+cmd_livepatch = $(if $(LIVEPATCH_$(basetarget)),		\
+	$(shell touch $(MODVERDIR)/$(basetarget).livepatch))
+endif
+
 define rule_cc_o_c
 	$(call cmd,checksrc)
 	$(call cmd_and_fixdep,cc_o_c)
@@ -280,6 +285,7 @@ $(obj)/%.o: $(src)/%.c $(recordmcount_source) $(objtool_dep) FORCE
 $(single-used-m): $(obj)/%.o: $(src)/%.c $(recordmcount_source) $(objtool_dep) FORCE
 	$(call cmd,force_checksrc)
 	$(call if_changed_rule,cc_o_c)
+	$(call cmd_livepatch)
 	@{ echo $(@:.o=.ko); echo $@; \
 	   $(cmd_undef_syms); } > $(MODVERDIR)/$(@F:.o=.mod)
 
@@ -456,6 +462,7 @@ cmd_link_multi-m = $(LD) $(ld_flags) -r -o $@ $(filter %.o,$^) $(cmd_secanalysis
 
 $(multi-used-m): FORCE
 	$(call if_changed,link_multi-m)
+	$(call cmd,livepatch)
 	@{ echo $(@:.o=.ko); echo $(filter %.o,$^); \
 	   $(cmd_undef_syms); } > $(MODVERDIR)/$(@F:.o=.mod)
 $(call multi_depend, $(multi-used-m), .o, -objs -y -m)
Signature · 1 line
2.20.1
#7 lore raw

Re: [PATCH v3 2/9] kbuild: Support for Symbols.list creation

Makefile vmlinuxclean: · line 1381

Quoted 3 lines · Joe Lawrence
Makefile +2 -1
-clean: archclean vmlinuxclean
+klpclean:
+	$(Q) rm -f $(objtree)/Symbols.list

nit: $(SLIST) can be used here.

Quoted 30 lines
Makefile +1 -0
+clean: archclean vmlinuxclean klpclean
 
 # mrproper - Delete all generated files, including .config
 #
samples/livepatch/Makefile +1 -0
index 2472ce39a18d..8b9b42a258ad 100644
@@ -1,3 +1,4 @@
+LIVEPATCH_livepatch-sample := y
 obj-$(CONFIG_SAMPLE_LIVEPATCH) += livepatch-sample.o
 obj-$(CONFIG_SAMPLE_LIVEPATCH) += livepatch-shadow-mod.o
 obj-$(CONFIG_SAMPLE_LIVEPATCH) += livepatch-shadow-fix1.o
scripts/Makefile.build +5 -0
index 76ca30cc4791..ca76bd2080f0 100644
@@ -246,6 +246,11 @@ cmd_gen_ksymdeps = \
 	$(CONFIG_SHELL) $(srctree)/scripts/gen_ksymdeps.sh $@ >> $(dot-target).cmd
 endif
 
+ifdef CONFIG_LIVEPATCH
+cmd_livepatch = $(if $(LIVEPATCH_$(basetarget)),		\
+	$(shell touch $(MODVERDIR)/$(basetarget).livepatch))
+endif
+
 define rule_cc_o_c
 	$(call cmd,checksrc)
 	$(call cmd_and_fixdep,cc_o_c)

scripts/Makefile.build $(obj)/%.o: $(src)/%.c $(recordmcount_source) $(objtool_dep) FORCE · line 288

Quoted 4 lines
scripts/Makefile.build +1 -0
@@ -280,6 +285,7 @@ $(obj)/%.o: $(src)/%.c $(recordmcount_source) $(objtool_dep) FORCE
 $(single-used-m): $(obj)/%.o: $(src)/%.c $(recordmcount_source) $(objtool_dep) FORCE
 	$(call cmd,force_checksrc)
 	$(call if_changed_rule,cc_o_c)
+	$(call cmd_livepatch)

nit: maybe use "cmd,livepatch" to be consistent with the other call of this function.

Quoted 14 lines
scripts/Makefile.build +1 -0
 	@{ echo $(@:.o=.ko); echo $@; \
 	   $(cmd_undef_syms); } > $(MODVERDIR)/$(@F:.o=.mod)
 
@@ -456,6 +462,7 @@ cmd_link_multi-m = $(LD) $(ld_flags) -r -o $@ $(filter %.o,$^) $(cmd_secanalysis
 
 $(multi-used-m): FORCE
 	$(call if_changed,link_multi-m)
+	$(call cmd,livepatch)
 	@{ echo $(@:.o=.ko); echo $(filter %.o,$^); \
 	   $(cmd_undef_syms); } > $(MODVERDIR)/$(@F:.o=.mod)
 $(call multi_depend, $(multi-used-m), .o, -objs -y -m)
Signature · 1 line
2.20.1
Signature · 1 line
 Artem
author maintainer
#8 lore raw

Re: [PATCH v3 2/9] kbuild: Support for Symbols.list creation

Quoted 28 lines · Artem Savkov

Makefile vmlinuxclean: · line 1381

Quoted 3 lines · Joe Lawrence
Makefile +2 -1
-clean: archclean vmlinuxclean
+klpclean:
+	$(Q) rm -f $(objtree)/Symbols.list

nit: $(SLIST) can be used here.

Quoted 21 lines
Makefile +1 -0
+clean: archclean vmlinuxclean klpclean
 
  # mrproper - Delete all generated files, including .config
  #
samples/livepatch/Makefile +1 -0
index 2472ce39a18d..8b9b42a258ad 100644
@@ -1,3 +1,4 @@
+LIVEPATCH_livepatch-sample := y
  obj-$(CONFIG_SAMPLE_LIVEPATCH) += livepatch-sample.o
  obj-$(CONFIG_SAMPLE_LIVEPATCH) += livepatch-shadow-mod.o
  obj-$(CONFIG_SAMPLE_LIVEPATCH) += livepatch-shadow-fix1.o
scripts/Makefile.build +0 -0
index 76ca30cc4791..ca76bd2080f0 100644
@@ -246,6 +246,11 @@ cmd_gen_ksymdeps = \
  	$(CONFIG_SHELL) $(srctree)/scripts/gen_ksymdeps.sh $@ >> $(dot-target).cmd
  endif
 
Quoted 17 lines

scripts/Makefile.build $(obj)/%.o: $(src)/%.c $(recordmcount_source) $(objtool_dep) FORCE · line 288

Quoted 13 lines
scripts/Makefile.build +6 -0
+ifdef CONFIG_LIVEPATCH
+cmd_livepatch = $(if $(LIVEPATCH_$(basetarget)),		\
+	$(shell touch $(MODVERDIR)/$(basetarget).livepatch))
+endif
+
  define rule_cc_o_c
  	$(call cmd,checksrc)
  	$(call cmd_and_fixdep,cc_o_c)
@@ -280,6 +285,7 @@ $(obj)/%.o: $(src)/%.c $(recordmcount_source) $(objtool_dep) FORCE
  $(single-used-m): $(obj)/%.o: $(src)/%.c $(recordmcount_source) $(objtool_dep) FORCE
  	$(call cmd,force_checksrc)
  	$(call if_changed_rule,cc_o_c)
+	$(call cmd_livepatch)

nit: maybe use "cmd,livepatch" to be consistent with the other call of this function.

Both of these make sense, thanks Artem.

-- Joe

maintainer
#9 lore raw

Re: [PATCH v3 2/9] kbuild: Support for Symbols.list creation

In reply to Joe Lawrence

samples/livepatch/Makefile line 4

Quoted 10 lines
samples/livepatch/Makefile +1 -0
index 2472ce39a18d..8b9b42a258ad 100644
@@ -1,3 +1,4 @@
+LIVEPATCH_livepatch-sample := y
 obj-$(CONFIG_SAMPLE_LIVEPATCH) += livepatch-sample.o
 obj-$(CONFIG_SAMPLE_LIVEPATCH) += livepatch-shadow-mod.o
 obj-$(CONFIG_SAMPLE_LIVEPATCH) += livepatch-shadow-fix1.o

We discussed this and I think there has been no conclusion yet. Shouldn't we do the same (add LIVEPATCH_) for the other samples here as well? So they are not picked up by cmd_klp_map and their symbols stored in Symbols.list?

Miroslav

author maintainer
#10 lore raw

Re: [PATCH v3 2/9] kbuild: Support for Symbols.list creation

Quoted 13 lines · Miroslav Benes

samples/livepatch/Makefile line 4

Quoted 10 lines
samples/livepatch/Makefile +1 -0
index 2472ce39a18d..8b9b42a258ad 100644
@@ -1,3 +1,4 @@
+LIVEPATCH_livepatch-sample := y
  obj-$(CONFIG_SAMPLE_LIVEPATCH) += livepatch-sample.o
  obj-$(CONFIG_SAMPLE_LIVEPATCH) += livepatch-shadow-mod.o
  obj-$(CONFIG_SAMPLE_LIVEPATCH) += livepatch-shadow-fix1.o

We discussed this and I think there has been no conclusion yet. Shouldn't we do the same (add LIVEPATCH_) for the other samples here as well?

In v2 review, I mentioned moving this hunk to ("modpost: Add modinfo flag to livepatch modules") along with the same change to the other sample modules. I didn't apply that for v3, but can do so for the next spin if it makes the commits easier to review.

-- Joe

maintainer
#11 lore raw

Re: [PATCH v3 2/9] kbuild: Support for Symbols.list creation

Quoted 15 lines · Joe Lawrence
Quoted 13 lines · Miroslav Benes

samples/livepatch/Makefile line 4

Quoted 10 lines
samples/livepatch/Makefile +1 -0
index 2472ce39a18d..8b9b42a258ad 100644
@@ -1,3 +1,4 @@
+LIVEPATCH_livepatch-sample := y
  obj-$(CONFIG_SAMPLE_LIVEPATCH) += livepatch-sample.o
  obj-$(CONFIG_SAMPLE_LIVEPATCH) += livepatch-shadow-mod.o
  obj-$(CONFIG_SAMPLE_LIVEPATCH) += livepatch-shadow-fix1.o

We discussed this and I think there has been no conclusion yet. Shouldn't we do the same (add LIVEPATCH_) for the other samples here as well?

Quoted 4 lines

In v2 review, I mentioned moving this hunk to ("modpost: Add modinfo flag to livepatch modules") along with the same change to the other sample modules. I didn't apply that for v3, but can do so for the next spin if it makes the commits easier to review.

I think it belongs here, but I may be missing something. Anyway, it is not really important, so I'd leave it up to you.

Miroslav

author maintainer
#12 lore raw

PATCH v3 3/9 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.list, 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.list file, an input livepatch module to be converted and the output name for the converted livepatch. When it starts running, klp-convert parses Symbols.list 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.list, 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  |   5 +
 scripts/Makefile                |   1 +
 scripts/livepatch/.gitignore    |   1 +
 scripts/livepatch/Makefile      |   7 +
 scripts/livepatch/elf.c         | 753 ++++++++++++++++++++++++++++++++
 scripts/livepatch/elf.h         |  72 +++
 scripts/livepatch/klp-convert.c | 692 +++++++++++++++++++++++++++++
 scripts/livepatch/klp-convert.h |  39 ++
 scripts/livepatch/list.h        | 391 +++++++++++++++++
 10 files changed, 1962 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 65b4e8f481f0..5f66ad2e54f4 100644
@@ -9023,6 +9023,7 @@ F:	arch/x86/kernel/livepatch.c
 F:	Documentation/livepatch/
 F:	Documentation/ABI/testing/sysfs-kernel-livepatch
 F:	samples/livepatch/
+F:	scripts/livepatch/
 F:	tools/testing/selftests/livepatch/
 L:	[email protected]
 T:	git git://git.kernel.org/pub/scm/linux/kernel/git/livepatching/livepatching.git
include/uapi/linux/livepatch.h +5 -0
index bb86243de805..a50ff68bec12 100644
@@ -14,4 +14,9 @@
 #define KLP_RELA_PREFIX		".klp.rela."
 #define KLP_SYM_PREFIX		".klp.sym."
 
+struct klp_module_reloc {
+	void *sym;
+	unsigned int sympos;
+} __attribute__((packed));
+
 #endif /* _UAPI_LIVEPATCH_H */
scripts/Makefile +1 -0
index 9d442ee050bd..bf9ce74b70b0 100644
@@ -39,6 +39,7 @@ build_unifdef: $(obj)/unifdef
 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 package
scripts/livepatch/.gitignore new file +1 -0
new file mode 100644
index 000000000000..dc22fe4b6a5b
@@ -0,0 +1 @@
+klp-convert
scripts/livepatch/Makefile new file +7 -0
new file mode 100644
index 000000000000..2842ecdba3fd
@@ -0,0 +1,7 @@
+hostprogs-y			:= klp-convert
+always				:= $(hostprogs-y)
+
+klp-convert-objs		:= klp-convert.o elf.o
+
+HOST_EXTRACFLAGS		:= -g -I$(INSTALL_HDR_PATH)/include -Wall
+HOSTLDLIBS_klp-convert		:= -lelf
scripts/livepatch/elf.c new file +753 -0

753 lines not on this page · raw message

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

72 lines not on this page · raw message

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

692 lines not on this page · raw message

scripts/livepatch/klp-convert.h new file +39 -0
new file mode 100644
index 000000000000..fb92b1ea4b52
@@ -0,0 +1,39 @@
+/* SPDX-License-Identifier: GPL-2.0 */
+/*
+ * Copyright (C) 2016 Josh Poimboeuf <[email protected]>
+ * Copyright (C) 2017 Joao Moreira   <[email protected]>
+ *
+ */
+
+#define SHN_LIVEPATCH		0xff20
+#define SHF_RELA_LIVEPATCH	0x00100000
+#define MODULE_NAME_LEN		(64 - sizeof(GElf_Addr))
+#define WARN(format, ...) \
+	fprintf(stderr, "klp-convert: " format "\n", ##__VA_ARGS__)
+
+/*
+ * klp-convert uses macros defined in the linux sources package. To prevent the
+ * dependency when building locally, they are defined below. Also notice that
+ * these should match the definitions from  the targeted kernel.
+ */
+
+#define KLP_RELA_PREFIX		".klp.rela."
+#define KLP_SYM_PREFIX		".klp.sym."
+
+struct symbol_entry {
+	struct list_head list;
+	char *symbol_name;
+	char *object_name;
+};
+
+struct sympos {
+	struct list_head list;
+	char *symbol_name;
+	char *object_name;
+	int pos;
+};
+
+struct klp_module_reloc {
+	void *sym;
+	unsigned int sympos;
+} __attribute__((packed));
scripts/livepatch/list.h new file +391 -0

391 lines not on this page · raw message

Signature · 1 line
2.20.1
author maintainer
#13 lore raw

Re: [PATCH v3 3/9] livepatch: Add klp-convert tool

scripts/livepatch/klp-convert.c line 613

Quoted 13 lines · Joe Lawrence

[ ... snip ... ]

scripts/livepatch/klp-convert.c new file +2 -0
new file mode 100644
index 000000000000..62bd26941081
 
[ ... snip ... ]
 
+	if (argc != 4) {
+		WARN("Usage: %s <Symbols.list> <input.ko> <out.ko>", argv[0]);
                                               ^^^^^^^^^^

nit: since we're using .klp.o prefix, should this be "input.klp.o"

-- Joe

maintainer
#14 lore raw

Re: [PATCH v3 3/9] livepatch: Add klp-convert tool

Quoted 10 lines · Joe Lawrence
Quoted 9 lines · Joe Lawrence

[ ... snip ... ]

scripts/livepatch/klp-convert.c new file +0 -0
new file mode 100644
index 000000000000..62bd26941081
Quoted 6 lines

scripts/livepatch/klp-convert.c line 613

Quoted 4 lines

[ ... snip ... ]

scripts/livepatch/klp-convert.c new file +2 -0
+	if (argc != 4) {
+		WARN("Usage: %s <Symbols.list> <input.ko> <out.ko>", argv[0]);
                                               ^^^^^^^^^^

nit: since we're using .klp.o prefix, should this be "input.klp.o"

I'd leave input.ko there. It is clear then that it is an ordinary kernel module and nothing special, but it is up to you.

I would change out.ko to output.ko for consistency.

Miroslav

author maintainer
#15 lore raw

Re: [PATCH v3 3/9] livepatch: Add klp-convert tool

In reply to Joe Lawrence
Quoted 21 lines · Joe Lawrence

[ ... snip ... ]

(quoted diff) +18 -0
+static bool convert_rela(struct section *oldsec, struct rela *r,
+		struct sympos *sp, struct elf *klp_elf)
+{
+	struct section *sec;
+	struct rela *r1, *r2;
+
+	sec = get_or_create_klp_rela_section(oldsec, sp, klp_elf);
+	if (!sec) {
+		WARN("Can't create or access klp.rela section (%s.%s)\n",
+				sp->object_name, sp->symbol_name);
+		return false;
+	}
+
+	if (!convert_klp_symbol(r->sym, sp)) {
+		WARN("Unable to convert symbol name (%s.%s)\n", sec->name,
+				r->sym->name);
+		return false;
+	}

Review

Quoted 10 lines
(quoted diff) +10 -0
+
+	/* Move the converted rela to klp rela section */
+	list_for_each_entry_safe(r1, r2, &oldsec->relas, list) {
+		if (r1->sym->name == r->sym->name) {
+			list_del(&r1->list);
+			list_add(&r1->list, &sec->relas);
+		}
+	}
+	return true;
+}

This one took a while to find and debug, but I believe that convert_rela()'s list removal is not as safe as it thinks it is.

Start with its calling context from main() below:

Quoted 10 lines
(quoted diff) +10 -0
+	list_for_each_entry_safe(sec, aux, &klp_elf->sections, list) {
+		if (!is_rela_section(sec))
+			continue;
+
+		list_for_each_entry_safe(rela, tmprela, &sec->relas, list) {
+			if (!must_convert(rela->sym))
+				continue;
+
+			if (!find_missing_position(rela->sym, &sp)) {
+				WARN("Unable to find missing symbol: %s",

Review

Quoted 10 lines
(quoted diff) +10 -0
+						rela->sym->name);
+				return -1;
+			}
+			if (!convert_rela(sec, rela, &sp, klp_elf)) {
+				WARN("Unable to convert relocation: %s",
+						rela->sym->name);
+				return -1;
+			}
+		}
+	}

AFAIK the *_safe list traversals, they cache the ->next value at the beginning of each iteration, so that one could blow the current element in position away. The cached ->next value is then assigned when moving to the next iteration.

But notice how convert_rela() looks through the entire list of relocations, moving each rela with a matching symbol?

Consider a slight tweak to samples/livepatch-annotated.c:

static int livepatch_cmdline_proc_show(struct seq_file *m, void *v) {
+ if (saved_command_line)
+ saved_command_line[0] = '\0';
+

          seq_printf(m, "%s livepatch=1\n", saved_command_line);
          return 0;

}

On my system, this generates relocations like this:

% eu-readelf --relocs samples/livepatch/livepatch-annotated-sample.o
Relocation section [ 2] '.rela.text' for section [ 1] '.text' at offset 0x98 contains 9 entries:

    Offset              Type            Value               Addend Name
    0x0000000000000001  X86_64_PC32     000000000000000000      -4 __fentry__
    0x0000000000000008  X86_64_PC32     000000000000000000      -4 saved_command_line
    0x0000000000000017  X86_64_PC32     000000000000000000      -4 saved_command_line
    0x000000000000001e  X86_64_32S      000000000000000000      +0 .rodata.str1.1
    0x0000000000000023  X86_64_PC32     000000000000000000      -4 seq_printf
    0x0000000000000031  X86_64_PC32     000000000000000000      -4 __fentry__
    0x0000000000000038  X86_64_32S      000000000000000000      +0 .data
    0x0000000000000051  X86_64_PC32     000000000000000000      -4 __fentry__
    0x000000000000003d  X86_64_PC32     000000000000000000      -4 klp_enable_patch

We now have back-to-back rela's with sym->name = "saved_command_line". When the first is converted, convert_rela() will move both of them to the klp rela section. The linked list values may be consistent, but the cached ->next value will be bogus and the in-flight-traversal will run off the rails.

I think we can work around it with a combination of 1) only moving a single rela symbol at a time in convert_rela and 2) processing the second (third, etc.) a little bit more so that they are moved individually.

I hacked this together and it works against the livepatch-annotate.c test above so far...

-->8-- -->8-- -->8-- -->8-- -->8-- -->8-- -->8-- -->8-- -->8-- -->8--

scripts/livepatch/klp-convert.c +6 -4
index 82c27d219372..126395f1c0cd 100644
@@ -517,6 +517,7 @@ static bool convert_rela(struct section *oldsec, struct rela *r,
 		if (r1->sym->name == r->sym->name) {
 			list_del(&r1->list);
 			list_add(&r1->list, &sec->relas);
+			break;
 		}
 	}
 	return true;
@@ -549,8 +550,8 @@ static bool is_converted(char *sname)
 }
 
 /*
- * Checks if symbol must be converted (conditions):
- * not resolved, not already converted or isn't an exported symbol
+ * Checks if symbol must be or was already converted (conditions):
+ * not resolved or isn't an exported symbol
  */
 static bool must_convert(struct symbol *sym)
 {
@@ -566,7 +567,7 @@ static bool must_convert(struct symbol *sym)
 	if (strcmp(sym->name, ".TOC.") == 0)
 		return false;
 
-	return (!(is_converted(sym->name) || is_exported(sym->name)));
+	return (!is_exported(sym->name));
 }
 
 /* Checks if a section is a klp rela section */
@@ -640,7 +641,8 @@ int main(int argc, const char **argv)
 			if (!must_convert(rela->sym))
 				continue;
 
-			if (!find_missing_position(rela->sym, &sp)) {
+			if (!is_converted(rela->sym->name) &&
+			    !find_missing_position(rela->sym, &sp)) {
 				WARN("Unable to find missing symbol: %s",
 						rela->sym->name);
 				return -1;
Signature · 1 line
2.20.1
maintainer
#16 lore raw

Re: [PATCH v3 3/9] livepatch: Add klp-convert tool

Quoted 95 lines · Joe Lawrence
Quoted 21 lines · Joe Lawrence

[ ... snip ... ]

(quoted diff) +18 -0
+static bool convert_rela(struct section *oldsec, struct rela *r,
+		struct sympos *sp, struct elf *klp_elf)
+{
+	struct section *sec;
+	struct rela *r1, *r2;
+
+	sec = get_or_create_klp_rela_section(oldsec, sp, klp_elf);
+	if (!sec) {
+		WARN("Can't create or access klp.rela section (%s.%s)\n",
+				sp->object_name, sp->symbol_name);
+		return false;
+	}
+
+	if (!convert_klp_symbol(r->sym, sp)) {
+		WARN("Unable to convert symbol name (%s.%s)\n", sec->name,
+				r->sym->name);
+		return false;
+	}

Review

Quoted 10 lines
(quoted diff) +10 -0
+
+	/* Move the converted rela to klp rela section */
+	list_for_each_entry_safe(r1, r2, &oldsec->relas, list) {
+		if (r1->sym->name == r->sym->name) {
+			list_del(&r1->list);
+			list_add(&r1->list, &sec->relas);
+		}
+	}
+	return true;
+}

This one took a while to find and debug, but I believe that convert_rela()'s list removal is not as safe as it thinks it is.

Start with its calling context from main() below:

Quoted 10 lines
(quoted diff) +10 -0
+	list_for_each_entry_safe(sec, aux, &klp_elf->sections, list) {
+		if (!is_rela_section(sec))
+			continue;
+
+		list_for_each_entry_safe(rela, tmprela, &sec->relas, list) {
+			if (!must_convert(rela->sym))
+				continue;
+
+			if (!find_missing_position(rela->sym, &sp)) {
+				WARN("Unable to find missing symbol: %s",

Review

Quoted 10 lines
(quoted diff) +10 -0
+						rela->sym->name);
+				return -1;
+			}
+			if (!convert_rela(sec, rela, &sp, klp_elf)) {
+				WARN("Unable to convert relocation: %s",
+						rela->sym->name);
+				return -1;
+			}
+		}
+	}

AFAIK the *_safe list traversals, they cache the ->next value at the beginning of each iteration, so that one could blow the current element in position away. The cached ->next value is then assigned when moving to the next iteration.

But notice how convert_rela() looks through the entire list of relocations, moving each rela with a matching symbol?

Consider a slight tweak to samples/livepatch-annotated.c:

  static int livepatch_cmdline_proc_show(struct seq_file *m, void *v)
  {
(quoted diff) +3 -0
+         if (saved_command_line)
+                 saved_command_line[0] = '\0';
+
          seq_printf(m, "%s livepatch=1\n", saved_command_line);
          return 0;
  }

On my system, this generates relocations like this:

% eu-readelf --relocs samples/livepatch/livepatch-annotated-sample.o
Relocation section [ 2] '.rela.text' for section [ 1] '.text' at offset 0x98 contains 9 entries:

    Offset              Type            Value               Addend Name
    0x0000000000000001  X86_64_PC32     000000000000000000      -4 __fentry__
    0x0000000000000008  X86_64_PC32     000000000000000000      -4 saved_command_line
    0x0000000000000017  X86_64_PC32     000000000000000000      -4 saved_command_line
    0x000000000000001e  X86_64_32S      000000000000000000      +0 .rodata.str1.1
    0x0000000000000023  X86_64_PC32     000000000000000000      -4 seq_printf
    0x0000000000000031  X86_64_PC32     000000000000000000      -4 __fentry__
    0x0000000000000038  X86_64_32S      000000000000000000      +0 .data
    0x0000000000000051  X86_64_PC32     000000000000000000      -4 __fentry__
    0x000000000000003d  X86_64_PC32     000000000000000000      -4 klp_enable_patch
Quoted 5 lines

We now have back-to-back rela's with sym->name = "saved_command_line". When the first is converted, convert_rela() will move both of them to the klp rela section. The linked list values may be consistent, but the cached ->next value will be bogus and the in-flight-traversal will run off the rails.

Yep, valid, if I'm reading the code correctly.

Quoted 15 lines

I think we can work around it with a combination of 1) only moving a single rela symbol at a time in convert_rela and 2) processing the second (third, etc.) a little bit more so that they are moved individually.

I hacked this together and it works against the livepatch-annotate.c test above so far...

-->8-- -->8-- -->8-- -->8-- -->8-- -->8-- -->8-- -->8-- -->8-- -->8--

scripts/livepatch/klp-convert.c +0 -0
index 82c27d219372..126395f1c0cd 100644

scripts/livepatch/klp-convert.c static bool convert_rela(struct section *oldsec, struct rela *r, · line 523

Quoted 7 lines
scripts/livepatch/klp-convert.c +1 -0
@@ -517,6 +517,7 @@ static bool convert_rela(struct section *oldsec, struct rela *r,
 		if (r1->sym->name == r->sym->name) {
 			list_del(&r1->list);
 			list_add(&r1->list, &sec->relas);
+			break;
 		}
 	}
 	return true;

Couldn't we remove the loop all together instead of breaking it?

	list_del(&r->list);
	list_add(&r->list, &sec->relas);

could be sufficient.

Quoted 21 lines
scripts/livepatch/klp-convert.c +3 -3
@@ -549,8 +550,8 @@ static bool is_converted(char *sname)
 }
 
 /*
- * Checks if symbol must be converted (conditions):
- * not resolved, not already converted or isn't an exported symbol
+ * Checks if symbol must be or was already converted (conditions):
+ * not resolved or isn't an exported symbol
  */
 static bool must_convert(struct symbol *sym)
 {
@@ -566,7 +567,7 @@ static bool must_convert(struct symbol *sym)
 	if (strcmp(sym->name, ".TOC.") == 0)
 		return false;
 
-	return (!(is_converted(sym->name) || is_exported(sym->name)));
+	return (!is_exported(sym->name));
 }
 
 /* Checks if a section is a klp rela section */

scripts/livepatch/klp-convert.c int main(int argc, const char **argv) · line 648

Quoted 9 lines
scripts/livepatch/klp-convert.c +2 -1
@@ -640,7 +641,8 @@ int main(int argc, const char **argv)
 			if (!must_convert(rela->sym))
 				continue;
 
-			if (!find_missing_position(rela->sym, &sp)) {
+			if (!is_converted(rela->sym->name) &&
+			    !find_missing_position(rela->sym, &sp)) {
 				WARN("Unable to find missing symbol: %s",
 						rela->sym->name);
 				return -1;

Looks good.

Miroslav

author maintainer
#17 lore raw

Re: [PATCH v3 3/9] livepatch: Add klp-convert tool

Quoted 16 lines · Miroslav Benes

scripts/livepatch/klp-convert.c static bool convert_rela(struct section *oldsec, struct rela *r, · line 523

Quoted 12 lines · Joe Lawrence
scripts/livepatch/klp-convert.c +1 -0
index 82c27d219372..126395f1c0cd 100644
@@ -517,6 +517,7 @@ static bool convert_rela(struct section *oldsec, struct rela *r,
  		if (r1->sym->name == r->sym->name) {
  			list_del(&r1->list);
  			list_add(&r1->list, &sec->relas);
+			break;
  		}
  	}
  	return true;

Couldn't we remove the loop all together instead of breaking it?

Quoted 4 lines
	list_del(&r->list);
	list_add(&r->list, &sec->relas);

could be sufficient.

Ah yea, good point.

Quoted 25 lines
Quoted 25 lines
scripts/livepatch/klp-convert.c +3 -3
@@ -549,8 +550,8 @@ static bool is_converted(char *sname)
  }
 
  /*
- * Checks if symbol must be converted (conditions):
- * not resolved, not already converted or isn't an exported symbol
+ * Checks if symbol must be or was already converted (conditions):
+ * not resolved or isn't an exported symbol
   */
  static bool must_convert(struct symbol *sym)
  {
@@ -566,7 +567,7 @@ static bool must_convert(struct symbol *sym)
  	if (strcmp(sym->name, ".TOC.") == 0)
  		return false;
 
-	return (!(is_converted(sym->name) || is_exported(sym->name)));
+	return (!is_exported(sym->name));
  }
 
  /* Checks if a section is a klp rela section */
@@ -640,7 +641,8 @@ int main(int argc, const char **argv)
  			if (!must_convert(rela->sym))
  				continue;
 
Quoted 8 lines

scripts/livepatch/klp-convert.c int main(int argc, const char **argv) · line 648

Quoted 6 lines
scripts/livepatch/klp-convert.c +2 -1
-			if (!find_missing_position(rela->sym, &sp)) {
+			if (!is_converted(rela->sym->name) &&
+			    !find_missing_position(rela->sym, &sp)) {
  				WARN("Unable to find missing symbol: %s",
  						rela->sym->name);
  				return -1;

Looks good.

There were a few additional spots I needed to update (like main's section walk doesn't need to re-convert klp_rela_sections, and likewise, convert_rela doesn't need to re-convert_klp_symbol), but I will include with v4 for a real review.

Thanks,

-- Joe

author maintainer
#18 lore raw

PATCH v3 4/9 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 16b48e8b29a2..947cfc2d1980 100644
@@ -236,6 +236,18 @@ void *klp_shadow_get_or_alloc(void *obj, unsigned long id,
 void klp_shadow_free(void *obj, unsigned long id, klp_shadow_dtor_t dtor);
 void klp_shadow_free_all(unsigned long id, klp_shadow_dtor_t dtor);
 
+/* Used to annotate symbol relocations in livepatches */
+#define KLP_MODULE_RELOC(obj)						\
+	struct klp_module_reloc						\
+	__attribute__((__section__(".klp.module_relocs." #obj)))	\
+	__attribute__((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.20.1
author maintainer
#19 lore raw

Re: [PATCH v3 4/9] livepatch: Add klp-convert annotation helpers

Quoted 22 lines · 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 +1 -0
index 16b48e8b29a2..947cfc2d1980 100644
@@ -236,6 +236,18 @@ void *klp_shadow_get_or_alloc(void *obj, unsigned long id,
 void klp_shadow_free(void *obj, unsigned long id, klp_shadow_dtor_t dtor);
 void klp_shadow_free_all(unsigned long id, klp_shadow_dtor_t dtor);
 
+/* Used to annotate symbol relocations in livepatches */

include/linux/livepatch.h void *klp_shadow_get_or_alloc(void *obj, unsigned long id, · line 249

Quoted 10 lines
include/linux/livepatch.h +10 -0
+#define KLP_MODULE_RELOC(obj)						\
+	struct klp_module_reloc						\
+	__attribute__((__section__(".klp.module_relocs." #obj)))	\
+	__attribute__((aligned (4)))
+
+#define KLP_SYMPOS(symbol, pos)						\
+	{								\
+		.sym = &symbol,						\
+		.sympos = pos,						\
+	},
        ^^

nit: if we dropped the trailing array comma delimiter from KLP_SYMPOS macro, the invocations would look more intuitively like an array. For example:

  KLP_MODULE_RELOC(test_klp_convert_mod) test_klp_convert_mod_relocs_a[] = {
  	KLP_SYMPOS(driver_name, 0),
  	KLP_SYMPOS(homonym_string, 2),
  	KLP_SYMPOS(get_homonym_string, 2),
  };

But I could not figure out a good regex to reference if other such kernel preprocessor macros include or exclude the delimiter. Are there reasons to include it?

-- Joe

maintainer
#20 lore raw

Re: [PATCH v3 4/9] livepatch: Add klp-convert annotation helpers

Quoted 44 lines · Joe Lawrence
Quoted 22 lines · 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 +1 -0
index 16b48e8b29a2..947cfc2d1980 100644
@@ -236,6 +236,18 @@ void *klp_shadow_get_or_alloc(void *obj, unsigned long id,
 void klp_shadow_free(void *obj, unsigned long id, klp_shadow_dtor_t dtor);
 void klp_shadow_free_all(unsigned long id, klp_shadow_dtor_t dtor);
 
+/* Used to annotate symbol relocations in livepatches */

include/linux/livepatch.h void *klp_shadow_get_or_alloc(void *obj, unsigned long id, · line 249

Quoted 10 lines
include/linux/livepatch.h +10 -0
+#define KLP_MODULE_RELOC(obj)						\
+	struct klp_module_reloc						\
+	__attribute__((__section__(".klp.module_relocs." #obj)))	\
+	__attribute__((aligned (4)))
+
+#define KLP_SYMPOS(symbol, pos)						\
+	{								\
+		.sym = &symbol,						\
+		.sympos = pos,						\
+	},
        ^^

nit: if we dropped the trailing array comma delimiter from KLP_SYMPOS macro, the invocations would look more intuitively like an array. For example:

  KLP_MODULE_RELOC(test_klp_convert_mod) test_klp_convert_mod_relocs_a[] = {
  	KLP_SYMPOS(driver_name, 0),
  	KLP_SYMPOS(homonym_string, 2),
  	KLP_SYMPOS(get_homonym_string, 2),
  };
Quoted 3 lines

But I could not figure out a good regex to reference if other such kernel preprocessor macros include or exclude the delimiter. Are there reasons to include it?

No, I don't think so. We should change it. Good catch.

Miroslav

author maintainer
#21 lore raw

PATCH v3 5/9 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.

---
 scripts/Kbuild.include   |  4 +++-
 scripts/Makefile.modpost | 16 +++++++++++++++-
 scripts/mod/modpost.c    |  6 +++++-
 scripts/mod/modpost.h    |  1 +
 4 files changed, 24 insertions(+), 3 deletions(-)
scripts/Kbuild.include +3 -1
index 7484b9d8272f..f8b7d12e44c9 100644
@@ -236,6 +236,8 @@ endif
 # (needed for the shell)
 make-cmd = $(call escsq,$(subst $(pound),$$(pound),$(subst $$,$$$$,$(cmd_$(1)))))
 
+save-cmd = printf '%s\n' 'cmd_$@ := $(make-cmd)' > $(dot-target).cmd
+
 # Find any prerequisites that is newer than target or that does not exist.
 # PHONY targets skipped in both cases.
 any-prereq = $(filter-out $(PHONY),$?) $(filter-out $(PHONY) $(wildcard $^),$^)
@@ -243,7 +245,7 @@ any-prereq = $(filter-out $(PHONY),$?) $(filter-out $(PHONY) $(wildcard $^),$^)
 # Execute command if command has changed or prerequisite(s) are updated.
 if_changed = $(if $(strip $(any-prereq) $(arg-check)),                       \
 	$(cmd);                                                              \
-	printf '%s\n' 'cmd_$@ := $(make-cmd)' > $(dot-target).cmd, @:)
+	$(save-cmd), @:)
 
 # Execute the command and also postprocess generated .d dependencies file.
 if_changed_dep = $(if $(strip $(any-prereq) $(arg-check)),$(cmd_and_fixdep),@:)
scripts/Makefile.modpost +15 -1
index 6b7f354f189a..1e8bb7442689 100644
@@ -124,8 +124,22 @@ quiet_cmd_ld_ko_o = LD [M]  $@
                  -o $@ $(real-prereqs) ;                                \
 	$(if $(ARCH_POSTLINK), $(MAKE) -f $(ARCH_POSTLINK) $@, true)
 
+SLIST = $(objtree)/Symbols.list
+KLP_CONVERT = scripts/livepatch/klp-convert
+quiet_cmd_klp_convert = KLP     $@
+      cmd_klp_convert = mv $@ $(@:.ko=.klp.o);				\
+			$(KLP_CONVERT) $(SLIST) $(@:.ko=.klp.o) $@
+
+define rule_ld_ko_o
+	$(call echo-cmd,ld_ko_o) $(cmd_ld_ko_o) ;			\
+	$(call save-cmd,ld_ko_o) ;					\
+	$(if $(CONFIG_LIVEPATCH),					\
+	  $(if $(wildcard $(MODVERDIR)/$(basetarget).livepatch),	\
+	    $(call echo-cmd,klp_convert) $(cmd_klp_convert) ))
+endef
+
 $(modules): %.ko :%.o %.mod.o FORCE
-	+$(call if_changed,ld_ko_o)
+	+$(call if_changed_rule,ld_ko_o)
 
 targets += $(modules)
 
scripts/mod/modpost.c +5 -1
index f277e116e0eb..374b22c76ec5 100644
@@ -1974,6 +1974,10 @@ static void read_symbols(const char *modname)
 		license = get_next_modinfo(&info, "license", license);
 	}
 
+	/* 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);
 
@@ -2101,7 +2105,7 @@ static int check_exports(struct module *mod)
 		const char *basename;
 		exp = find_symbol(s->name);
 		if (!exp || exp->module == mod) {
-			if (have_vmlinux && !s->weak) {
+			if (have_vmlinux && !s->weak && !mod->livepatch) {
 				if (warn_unresolved) {
 					warn("\"%s\" [%s.ko] undefined!\n",
 					     s->name, mod->name);
scripts/mod/modpost.h +1 -0
index 8453d6ac2f77..2acfaae064ec 100644
@@ -118,6 +118,7 @@ struct module {
 	int skip;
 	int has_init;
 	int has_cleanup;
+	int livepatch;
 	struct buffer dev_table_buf;
 	char	     srcversion[25];
 	int is_dot_o;
Signature · 1 line
2.20.1
author maintainer
#22 lore raw

Re: [PATCH v3 5/9] modpost: Integrate klp-convert

Quoted 20 lines · Joe Lawrence

[ ... snip ... ]

scripts/Makefile.modpost +9 -0
index 6b7f354f189a..1e8bb7442689 100644
@@ -124,8 +124,22 @@ quiet_cmd_ld_ko_o = LD [M]  $@
                  -o $@ $(real-prereqs) ;                                \
 	$(if $(ARCH_POSTLINK), $(MAKE) -f $(ARCH_POSTLINK) $@, true)
 
+SLIST = $(objtree)/Symbols.list
+KLP_CONVERT = scripts/livepatch/klp-convert
+quiet_cmd_klp_convert = KLP     $@
+      cmd_klp_convert = mv $@ $(@:.ko=.klp.o);				\
+			$(KLP_CONVERT) $(SLIST) $(@:.ko=.klp.o) $@
+
+define rule_ld_ko_o
+	$(call echo-cmd,ld_ko_o) $(cmd_ld_ko_o) ;			\
+	$(call save-cmd,ld_ko_o) ;					\

scripts/Makefile.modpost quiet_cmd_ld_ko_o = LD [M] $@ · line 144

Quoted 10 lines
scripts/Makefile.modpost +6 -1
+	$(if $(CONFIG_LIVEPATCH),					\
+	  $(if $(wildcard $(MODVERDIR)/$(basetarget).livepatch),	\
+	    $(call echo-cmd,klp_convert) $(cmd_klp_convert) ))
+endef
+
 $(modules): %.ko :%.o %.mod.o FORCE
-	+$(call if_changed,ld_ko_o)
+	+$(call if_changed_rule,ld_ko_o)
 
 targets += $(modules)

I just noticed that rule_ld_ko_o produces verbose output when linking modules:

  % make
  ...
  echo '  LD [M]  drivers/ata/ata_generic.ko'; ld -r -m elf_x86_64  -z max-page-size=0x200000 -T ./scripts/module-common.lds  --build-id  -o drivers/ata/ata_generic.ko drivers/ata/ata_generic.o drivers/ata/ata_generic.mod.o ;  true ; printf '%s\n' 'cmd_drivers/ata/ata_generic.ko := ld -r -m elf_x86_64  -z max-page-size=0x200000 -T ./scripts/module-common.lds  --build-id  -o drivers/ata/ata_generic.ko drivers/ata/ata_generic.o drivers/ata/ata_generic.mod.o ;  true' > drivers/ata/.ata_generic.ko.cmd ;  
    LD [M]  drivers/ata/ata_generic.ko

so I think we need to use the $(Q) macro to respect the KBUILD_VERBOSE and V kbuild settings.

Masahiro, does something like this look correct?

Thanks,

-- Joe

-->8-- -->8-- -->8-- -->8-- -->8-- -->8-- -->8-- -->8-- -->8-- -->8--

From 5c8a2c58c7be98c0a9156155f201b88cc61bf0bd Mon Sep 17 00:00:00 2001
From: Joe Lawrence <[email protected]>
Date: Thu, 11 Apr 2019 11:32:37 -0400
Subject: [PATCH] [squash] modpost: fix rule_ld_ko_o verbosity

Note: squash with ("modpost: Integrate klp-convert")

rule_ld_ko_o should include $(Q) to honor build verbosity setting. Cargo-cult-stolen from 70923bd26c73 ("perf tools: Make flex/bison calls honour V=1").

[joe: quiet down rule_ld_ko_o]

---
 scripts/Makefile.modpost | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)
scripts/Makefile.modpost +1 -1
index 9fe4c5760aca..f2aee6b8dcfd 100644
@@ -135,11 +135,11 @@ KLP_CONVERT = scripts/livepatch/klp-convert
 quiet_cmd_klp_convert = KLP     $@
       cmd_klp_convert = mv $@ $(@:.ko=.klp.o);				\
 			$(KLP_CONVERT) $(SLIST) $(@:.ko=.klp.o) $@
 
 define rule_ld_ko_o
-	$(call echo-cmd,ld_ko_o) $(cmd_ld_ko_o) ;			\
+	$(Q)$(call echo-cmd,ld_ko_o) $(cmd_ld_ko_o) ;			\
 	$(call save-cmd,ld_ko_o) ;					\
 	$(if $(CONFIG_LIVEPATCH),					\
 	  $(if $(wildcard $(MODVERDIR)/$(basetarget).livepatch),	\
 	    $(call echo-cmd,klp_convert) $(cmd_klp_convert) ))
 endef
Signature · 1 line
2.20.1
author maintainer
#23 lore raw

PATCH v3 6/9 modpost: Add modinfo flag to livepatch modules

In reply to Joe Lawrence

From: Miroslav Benes <[email protected]>

Currently, livepatch infrastructure in the kernel relies on MODULE_INFO(livepatch, "Y") statement in a livepatch module. Then the kernel module loader knows a module is indeed livepatch module and can behave accordingly.

klp-convert, on the other hand relies on LIVEPATCH_* statement in the module's Makefile for exactly the same reason.

Remove dependency on modinfo and generate MODULE_INFO flag automatically in modpost when LIVEPATCH_* is defined in the module's Makefile. Generate a list of all built livepatch modules based on the .livepatch file and store it in (MODVERDIR)/livepatchmods. Give this list as an argument for modpost which will use it to identify livepatch modules.

As MODULE_INFO is no longer needed, remove it.

---
 lib/livepatch/Makefile                   |  5 ++
 lib/livepatch/test_klp_atomic_replace.c  |  1 -
 lib/livepatch/test_klp_callbacks_demo.c  |  1 -
 lib/livepatch/test_klp_callbacks_demo2.c |  1 -
 lib/livepatch/test_klp_livepatch.c       |  1 -
 samples/livepatch/Makefile               |  4 ++
 samples/livepatch/livepatch-sample.c     |  1 -
 scripts/Makefile.modpost                 |  8 ++-
 scripts/mod/modpost.c                    | 84 ++++++++++++++++++++++--
 9 files changed, 94 insertions(+), 12 deletions(-)
lib/livepatch/Makefile +5 -0
index 26900ddaef82..513d200b7942 100644
@@ -2,6 +2,11 @@
 #
 # Makefile for livepatch test code.
 
+LIVEPATCH_test_klp_atomic_replace := y
+LIVEPATCH_test_klp_callbacks_demo := y
+LIVEPATCH_test_klp_callbacks_demo2 := y
+LIVEPATCH_test_klp_livepatch := y
+
 obj-$(CONFIG_TEST_LIVEPATCH) += test_klp_atomic_replace.o \
 				test_klp_callbacks_demo.o \
 				test_klp_callbacks_demo2.o \
lib/livepatch/test_klp_atomic_replace.c +0 -1
index 5af7093ca00c..3bf08a1b7b12 100644
@@ -52,6 +52,5 @@ static void test_klp_atomic_replace_exit(void)
 module_init(test_klp_atomic_replace_init);
 module_exit(test_klp_atomic_replace_exit);
 MODULE_LICENSE("GPL");
-MODULE_INFO(livepatch, "Y");
 MODULE_AUTHOR("Joe Lawrence <[email protected]>");
 MODULE_DESCRIPTION("Livepatch test: atomic replace");
lib/livepatch/test_klp_callbacks_demo.c +0 -1
index 3fd8fe1cd1cc..76e2f51a6771 100644
@@ -116,6 +116,5 @@ static void test_klp_callbacks_demo_exit(void)
 module_init(test_klp_callbacks_demo_init);
 module_exit(test_klp_callbacks_demo_exit);
 MODULE_LICENSE("GPL");
-MODULE_INFO(livepatch, "Y");
 MODULE_AUTHOR("Joe Lawrence <[email protected]>");
 MODULE_DESCRIPTION("Livepatch test: livepatch demo");
lib/livepatch/test_klp_callbacks_demo2.c +0 -1
index 5417573e80af..76db98fc3071 100644
@@ -88,6 +88,5 @@ static void test_klp_callbacks_demo2_exit(void)
 module_init(test_klp_callbacks_demo2_init);
 module_exit(test_klp_callbacks_demo2_exit);
 MODULE_LICENSE("GPL");
-MODULE_INFO(livepatch, "Y");
 MODULE_AUTHOR("Joe Lawrence <[email protected]>");
 MODULE_DESCRIPTION("Livepatch test: livepatch demo2");
lib/livepatch/test_klp_livepatch.c +0 -1
index aff08199de71..d94d0ae232db 100644
@@ -46,6 +46,5 @@ static void test_klp_livepatch_exit(void)
 module_init(test_klp_livepatch_init);
 module_exit(test_klp_livepatch_exit);
 MODULE_LICENSE("GPL");
-MODULE_INFO(livepatch, "Y");
 MODULE_AUTHOR("Seth Jennings <[email protected]>");
 MODULE_DESCRIPTION("Livepatch test: livepatch module");
samples/livepatch/Makefile +4 -0
index 8b9b42a258ad..5fb3280bbdc4 100644
@@ -1,4 +1,8 @@
 LIVEPATCH_livepatch-sample := y
+LIVEPATCH_livepatch-shadow-fix1 := y
+LIVEPATCH_livepatch-shadow-fix2 := y
+LIVEPATCH_livepatch-callbacks-demo := y
+
 obj-$(CONFIG_SAMPLE_LIVEPATCH) += livepatch-sample.o
 obj-$(CONFIG_SAMPLE_LIVEPATCH) += livepatch-shadow-mod.o
 obj-$(CONFIG_SAMPLE_LIVEPATCH) += livepatch-shadow-fix1.o
samples/livepatch/livepatch-sample.c +0 -1
index 01c9cf003ca2..8900a175046b 100644
@@ -79,4 +79,3 @@ static void livepatch_exit(void)
 module_init(livepatch_init);
 module_exit(livepatch_exit);
 MODULE_LICENSE("GPL");
-MODULE_INFO(livepatch, "Y");
scripts/Makefile.modpost +7 -1
index 1e8bb7442689..9fe4c5760aca 100644
@@ -65,6 +65,11 @@ MODLISTCMD := find $(MODVERDIR) -name '*.mod' | xargs -r grep -h '\.ko$$' | sort
 __modules := $(shell $(MODLISTCMD))
 modules   := $(patsubst %.o,%.ko, $(wildcard $(__modules:.ko=.o)))
 
+# find all .livepatch files listed in $(MODVERDIR)/
+ifdef CONFIG_LIVEPATCH
+$(shell find $(MODVERDIR) -name '*.livepatch' | xargs -r -I{} basename {} .livepatch > $(MODVERDIR)/livepatchmods)
+endif
+
 # Stop after building .o files if NOFINAL is set. Makes compile tests quicker
 _modpost: $(if $(KBUILD_MODPOST_NOFINAL), $(modules:.ko:.o),$(modules))
 
@@ -78,7 +83,8 @@ modpost = scripts/mod/modpost                    \
  $(if $(KBUILD_EXTRA_SYMBOLS), $(patsubst %, -e %,$(KBUILD_EXTRA_SYMBOLS))) \
  $(if $(KBUILD_EXTMOD),-o $(modulesymfile))      \
  $(if $(CONFIG_SECTION_MISMATCH_WARN_ONLY),,-E)  \
- $(if $(KBUILD_EXTMOD)$(KBUILD_MODPOST_WARN),-w)
+ $(if $(KBUILD_EXTMOD)$(KBUILD_MODPOST_WARN),-w) \
+ $(if $(CONFIG_LIVEPATCH),-l $(MODVERDIR)/livepatchmods)
 
 MODPOST_OPT=$(subst -i,-n,$(filter -i,$(MAKEFLAGS)))
 
scripts/mod/modpost.c +78 -6

129 lines not on this page · raw message

Signature · 1 line
2.20.1
maintainer
#24 lore raw

Re: [PATCH v3 6/9] modpost: Add modinfo flag to livepatch modules

samples/livepatch/Makefile line 4

Quoted 10 lines
samples/livepatch/Makefile +3 -0
index 8b9b42a258ad..5fb3280bbdc4 100644
@@ -1,4 +1,8 @@
 LIVEPATCH_livepatch-sample := y
+LIVEPATCH_livepatch-shadow-fix1 := y
+LIVEPATCH_livepatch-shadow-fix2 := y
+LIVEPATCH_livepatch-callbacks-demo := y

You could also remove MODULE_INFO(livepatch, "Y") from the three files.

Miroslav

author maintainer
#25 lore raw

PATCH v3 7/9 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                    |   2 +
 .../livepatch/livepatch-annotated-sample.c    | 102 ++++++++++++++++++
 2 files changed, 104 insertions(+)
 create mode 100644 samples/livepatch/livepatch-annotated-sample.c
samples/livepatch/Makefile +2 -0
index 5fb3280bbdc4..dea530840725 100644
@@ -2,6 +2,7 @@ LIVEPATCH_livepatch-sample := y
 LIVEPATCH_livepatch-shadow-fix1 := y
 LIVEPATCH_livepatch-shadow-fix2 := y
 LIVEPATCH_livepatch-callbacks-demo := y
+LIVEPATCH_livepatch-annotated-sample := y
 
 obj-$(CONFIG_SAMPLE_LIVEPATCH) += livepatch-sample.o
 obj-$(CONFIG_SAMPLE_LIVEPATCH) += livepatch-shadow-mod.o
@@ -10,3 +11,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 +102 -0

102 lines not on this page · raw message

Signature · 1 line
2.20.1
author maintainer
#26 lore raw

PATCH v3 8/9 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.txt describing how klp-convert works for fixing relocations.

---
 Documentation/livepatch/livepatch.txt         |  3 ++
 Documentation/livepatch/module-elf-format.txt | 50 ++++++++++++++++---
 2 files changed, 47 insertions(+), 6 deletions(-)
Documentation/livepatch/livepatch.txt +3 -0
index 4627b41ff02e..873c11aee038 100644
@@ -274,6 +274,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.txt +44 -6

81 lines not on this page · raw message

Signature · 1 line
2.20.1
author maintainer
#27 lore raw

PATCH v3 9/9 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                        |  10 ++
 lib/livepatch/test_klp_convert1.c             | 106 ++++++++++++++++++
 lib/livepatch/test_klp_convert2.c             | 103 +++++++++++++++++
 lib/livepatch/test_klp_convert_mod_a.c        |  25 +++++
 lib/livepatch/test_klp_convert_mod_b.c        |  13 +++
 .../selftests/livepatch/test-livepatch.sh     |  64 +++++++++++
 6 files changed, 321 insertions(+)
 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 +10 -0
index 513d200b7942..b19253c72d72 100644
@@ -5,6 +5,8 @@
 LIVEPATCH_test_klp_atomic_replace := y
 LIVEPATCH_test_klp_callbacks_demo := y
 LIVEPATCH_test_klp_callbacks_demo2 := y
+LIVEPATCH_test_klp_convert1 := y
+LIVEPATCH_test_klp_convert2 := y
 LIVEPATCH_test_klp_livepatch := y
 
 obj-$(CONFIG_TEST_LIVEPATCH) += test_klp_atomic_replace.o \
@@ -12,9 +14,17 @@ 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_convert_mod-y := \
+	test_klp_convert_mod_a.o \
+	test_klp_convert_mod_b.o
+
 # Target modules to be livepatched require CC_FLAGS_FTRACE
 CFLAGS_test_klp_callbacks_busy.o	+= $(CC_FLAGS_FTRACE)
 CFLAGS_test_klp_callbacks_mod.o		+= $(CC_FLAGS_FTRACE)
+CFLAGS_test_klp_convert_mod.o		+= $(CC_FLAGS_FTRACE)
lib/livepatch/test_klp_convert1.c new file +106 -0

106 lines not on this page · raw message

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

103 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..b2db9942fbd2
@@ -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 *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..a3d529ff5f1f
@@ -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 char homonym_string[] = "homonym string B";
+__used static char *get_homonym_string(void)
+{
+	return homonym_string;
+}
tools/testing/selftests/livepatch/test-livepatch.sh +64 -0

74 lines not on this page · raw message

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

Hi folks,

This is the third installment of the klp-convert tool for generating and processing livepatch symbols for livepatch module builds. For those following along at home, archive links to previous versions:

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

(Note that I don't see v2 archived at lore, but that is a link to the most recent subthread that lore did catch.)

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 Symbols.list 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.

Branches
--------

Since I spent some time tinkering with v2 and accumulated a bunch of fixes, I collected them up and am posting this new version. For review purposes, I posted two branches up to github:

1 - an expanded branch that with changes separate from the original
https://github.com/joe-lawrence/linux/commits/klp-convert-v3-expanded

2 - a squashed branch of (1) that comprises v3:
https://github.com/joe-lawrence/linux/commits/klp-convert-v3

Non-trivial commits in the expanded branch have some extra commentary and details for debugging in the commit message that were dropped when squashing into their respective parent commits.

TODO
----

There are a few outstanding items that I came across while reviewing v2, but as changes started accumulating, it made sense to defer those to a later version. I'll reply to this thread individual topics to start discussion sub-threads for those.

Changelogs
----------

The commit changelogs were getting long, so I've moved them here for posterity and review purposes:

livepatch: Create and include UAPI headers
v2:
- jmoreira: split up and changelog
v3:
- joe: convert to SPDX license tags

kbuild: Support for Symbols.list creation
v3:
- jmoreira: adjust for multiobject livepatch
- joe: add klpclean to PHONY
- joe: align KLP prefix

livepatch: Add klp-convert tool
v2:
- khlebnikov: use HOSTLOADLIBES_ instead of HOSTLDFLAGS: -lelf must be at the end
- jmoreira: add support to automatic relocation conversion in klp-convert.c, changelog
v3:
- joe: convert to SPDX license tags
- jmoreira: add rela symbol name to WARNs
- jmoreira: ignore relocations to .TOC and symbols with index 0
- joe: separate and fix valid_sympos() sympos=0 and sympos=1..n checks
- joe: fix symbol use-after-frees
- joe: fix remaining valgrind leak complaints (non-error paths only)
- joe: checkpatch nits

livepatch: Add klp-convert annotation helpers
v2:
- jmoreira: split up: move KLP_MODULE_RELOC from previous patch to here, add KLP_SYMPOS, move macros from include/uapi/livepatch.h to include/linux/livepatch.h
v3:
- joe: suggested by jpoimboe, KLP_MODULE_RELOC macro should 4-byte align klp_module_reloc structures

modpost: Integrate klp-convert
v2:
- khlebnikov: save cmd_ld_ko_o into .module.cmd, if_changed_rule doesn't do that.f
- khlebnikov: fix bashisms for debian where /bin/sh is a symlink to /bin/dash
- khlebnikov: rename rule_link_module to rule_ld_ko_o, otherwise arg-check inside if_changed_rule compares cmd_link_module and cmd_ld_ko_o.
- khlebnikov: check modinfo -F livepatch only if CONFIG_LIVEPATCH is true.
- mbenes: remove modinfo call. LIVEPATCH_ in Makefile
- jmoreira: split up: move the .livepatch file-based scheme for identifying livepatches to a previous patch, as it was required for correctly building Symbols.list there.
v3:
- joe: adjust rule_ld_ko_o to call echo-cmd
- joe: rebase for v5.1
- joe: align KLP prefix

modpost: Add modinfo flag to livepatch modules
v2:
- jmoreira: fix modpost.c (add_livepatch_flag) to update module structure with livepatch flag and prevent modpost from breaking due to unresolved symbols
v3:
- joe: adjust modpost.c::get_modinfo() call for v5.0 version

livepatch: Add sample livepatch module
v3:
- joe: update all in-tree livepatches with LIVEPATCH_* modinfo flag

documentation: Update on livepatch elf format
v2:
- jmoreira: update module to use KLP_SYMPOS
- jmoreira: Comments on symbol resolution scheme
- jmoreira: Update Makefile
- jmoreira: Remove MODULE_INFO statement
- jmoreira: Changelog
v3:
- joe: rebase for v5.1
- joe: code shuffle to better match original source file

livepatch/selftests: add klp-convert
v3:
- joe: clarify sympos=0 and sympos=1..n

And now the usual git cover-letter boilerplate...

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

Joe Lawrence (1):
livepatch/selftests: add klp-convert

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

Miroslav Benes (1):
modpost: Add modinfo flag to livepatch modules

 .gitignore                                    |   1 +
 Documentation/livepatch/livepatch.txt         |   3 +
 Documentation/livepatch/module-elf-format.txt |  50 +-
 MAINTAINERS                                   |   2 +
 Makefile                                      |  30 +-
 include/linux/livepatch.h                     |  13 +
 include/uapi/linux/livepatch.h                |  22 +
 kernel/livepatch/core.c                       |   4 +-
 lib/livepatch/Makefile                        |  15 +
 lib/livepatch/test_klp_atomic_replace.c       |   1 -
 lib/livepatch/test_klp_callbacks_demo.c       |   1 -
 lib/livepatch/test_klp_callbacks_demo2.c      |   1 -
 lib/livepatch/test_klp_convert1.c             | 106 +++
 lib/livepatch/test_klp_convert2.c             | 103 +++
 lib/livepatch/test_klp_convert_mod_a.c        |  25 +
 lib/livepatch/test_klp_convert_mod_b.c        |  13 +
 lib/livepatch/test_klp_livepatch.c            |   1 -
 samples/livepatch/Makefile                    |   7 +
 .../livepatch/livepatch-annotated-sample.c    | 102 +++
 samples/livepatch/livepatch-sample.c          |   1 -
 scripts/Kbuild.include                        |   4 +-
 scripts/Makefile                              |   1 +
 scripts/Makefile.build                        |   7 +
 scripts/Makefile.modpost                      |  24 +-
 scripts/livepatch/.gitignore                  |   1 +
 scripts/livepatch/Makefile                    |   7 +
 scripts/livepatch/elf.c                       | 753 ++++++++++++++++++
 scripts/livepatch/elf.h                       |  72 ++
 scripts/livepatch/klp-convert.c               | 692 ++++++++++++++++
 scripts/livepatch/klp-convert.h               |  39 +
 scripts/livepatch/list.h                      | 391 +++++++++
 scripts/mod/modpost.c                         |  82 +-
 scripts/mod/modpost.h                         |   1 +
 .../selftests/livepatch/test-livepatch.sh     |  64 ++
 34 files changed, 2616 insertions(+), 23 deletions(-)
 create mode 100644 include/uapi/linux/livepatch.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
Quoted 11 lines
 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.20.1

[ cc += Jason and Evgenii ]

Apologies for the long brain dump, but I promised to reply to this thread with some of the larger TODO issues I came across with this patchset. Static key support is probably the most complicated item, so there is a lot of debugging output I can provide.

See the tl;dr and Future Work sections for the executive summary.

Static key support
==================

tl;dr
-----

Livepatch symbols are created when building livepatch modules that reference the (non-exported) static keys of a target object.

When loading a livepatch that contains klp-converted static key symbols, the module loader crashes.

Testing setup
-------------

The easiest way to see the source and repro is to grab this branch:

https://github.com/joe-lawrence/linux/commits/klp-convert-v4-static-keys

and note these last two commits:

- livepatch/klp-convert: abort on static key conversion: this will prevent klp-convert from converting any relocations to the __jump_table. Revert this commit to see the crash. If we don't have a fix before merging, I would suggest a temporary abort like this to avoid silently creating dangerous livepatches.

- livepatch/selftests: add livepatch static keys: this adds the self-test which will repro the crash.

I added a new livepatch selftest to verify klp-convert and static key
behavior: it consists of two kernel modules: test_klp_static_keys_mod.ko and livepatch module that patches it, test_klp_static_keys.ko.

The base module contains a few different types of static keys: default true / false, exported / not-exported, and one created by the trace event macro infrastructure.

The livepatch module references each of these, relying upon klp-convert. This module also provides its own static key for reference.

test_klp_static_keys_mod.ko
---------------------------
module_key (false) - exported
module_key2 (true) <----
TRACE_EVENT(test_klp_static_keys) <-- |
| |
| | klp-convert resolves

  test_klp_static_keys.ko - livepatch     | |  these references
  -----------------------------------     | |
    klp_key (true)                        | |
    test_klp_static_keys -----------------  |
    module_key2 ----------------------------
    module_key

Currently .klp symbols are created as well as a relocation section for those symbols in the their corresponding .text locations.

test_klp_static_keys_mod.ko
---------------------------

  % eu-readelf --symbols lib/livepatch/test_klp_static_keys_mod.ko | \
        grep -e '__tracepoint_test_klp_static_keys' -e '\<module_key[2]*\>'
     49: 0000000000000010     16 OBJECT  LOCAL  DEFAULT       44 module_key
     65: 0000000000000010     16 OBJECT  LOCAL  DEFAULT       32 module_key2
     96: 0000000000000000     48 OBJECT  GLOBAL DEFAULT       40 __tracepoint_test_klp_static_keys

test_klp_static_keys.klp.o
--------------------------

  % eu-readelf --symbols lib/livepatch/test_klp_static_keys.klp.o | \
        grep -e '__tracepoint_test_klp_static_keys' -e '\<module_key[2]*\>'
     71: 0000000000000000      0 NOTYPE  GLOBAL DEFAULT    UNDEF __tracepoint_test_klp_static_keys
     78: 0000000000000000      0 NOTYPE  GLOBAL DEFAULT    UNDEF module_key2
     84: 0000000000000000      0 NOTYPE  GLOBAL DEFAULT    UNDEF module_key

Lots of __tracepoint_test_klp_static_keys relocations since each module function registers an event when it is called:

% eu-readelf --reloc lib/livepatch/test_klp_static_keys.klp.o
Relocation section [ 4] '.rela.text' for section [ 3] '.text' at offset 0x2e7d8 contains 88 entries:

    Offset              Type            Value               Addend Name
    ...
    0x000000000000002c  X86_64_32S      000000000000000000      +0 module_key2
    ...
    0x000000000000007c  X86_64_PC32     000000000000000000     +36 __tracepoint_test_klp_static_keys
    ...
    0x00000000000000d9  X86_64_PC32     000000000000000000     +36 __tracepoint_test_klp_static_keys
    ...
    0x0000000000000169  X86_64_PC32     000000000000000000     +36 __tracepoint_test_klp_static_keys
    ...
    0x00000000000001f9  X86_64_PC32     000000000000000000     +36 __tracepoint_test_klp_static_keys
    ...
    0x000000000000028c  X86_64_32S      000000000000000000      +0 module_key
    ...
    0x00000000000002dc  X86_64_PC32     000000000000000000     +36 __tracepoint_test_klp_static_keys
    ...
    0x000000000000038c  X86_64_PC32     000000000000000000     +36 __tracepoint_test_klp_static_keys
    ...
    0x00000000000003eb  X86_64_PC32     000000000000000000     +36 __tracepoint_test_klp_static_keys

Relocations generated for the __jump_table itself, note that I grouped each jump entry <code, target, key> relocation set:

Relocation section [19] '.rela__jump_table' for section [18] '__jump_table' at offset 0x2fb28 contains 30 entries:

    Offset              Type            Value               Addend Name
    000000000000000000  X86_64_PC32     000000000000000000     +12 .text
    0x0000000000000004  X86_64_PC32     000000000000000000    +102 .text
    0x0000000000000008  X86_64_PC64     000000000000000000      +8 __tracepoint_test_klp_static_keys
    0x0000000000000010  X86_64_PC32     000000000000000000    +188 .text
    0x0000000000000014  X86_64_PC32     000000000000000000    +195 .text
    0x0000000000000018  X86_64_PC64     000000000000000000      +8 __tracepoint_test_klp_static_keys
    0x0000000000000020  X86_64_PC32     000000000000000000    +304 .text
    0x0000000000000024  X86_64_PC32     000000000000000000      +0 .text.unlikely
    0x0000000000000028  X86_64_PC64     000000000000000000     +16 .bss
    0x0000000000000030  X86_64_PC32     000000000000000000    +332 .text
    0x0000000000000034  X86_64_PC32     000000000000000000    +339 .text
    0x0000000000000038  X86_64_PC64     000000000000000000      +8 __tracepoint_test_klp_static_keys
    0x0000000000000040  X86_64_PC32     000000000000000000    +448 .text
    0x0000000000000044  X86_64_PC32     000000000000000000     +52 .text.unlikely
    0x0000000000000048  X86_64_PC64     000000000000000000      +0 module_key
    0x0000000000000050  X86_64_PC32     000000000000000000    +476 .text
    0x0000000000000054  X86_64_PC32     000000000000000000    +483 .text
    0x0000000000000058  X86_64_PC64     000000000000000000      +8 __tracepoint_test_klp_static_keys
    0x0000000000000060  X86_64_PC32     000000000000000000    +592 .text
    0x0000000000000064  X86_64_PC32     000000000000000000    +104 .text.unlikely
    0x0000000000000068  X86_64_PC64     000000000000000000      +1 module_key2
    0x0000000000000070  X86_64_PC32     000000000000000000    +620 .text
    0x0000000000000074  X86_64_PC32     000000000000000000    +710 .text
    0x0000000000000078  X86_64_PC64     000000000000000000      +8 __tracepoint_test_klp_static_keys
    0x0000000000000080  X86_64_PC32     000000000000000000    +796 .text
    0x0000000000000084  X86_64_PC32     000000000000000000    +886 .text
    0x0000000000000088  X86_64_PC64     000000000000000000      +8 __tracepoint_test_klp_static_keys
    0x0000000000000090  X86_64_PC32     000000000000000000    +962 .text
    0x0000000000000094  X86_64_PC32     000000000000000000    +981 .text
    0x0000000000000098  X86_64_PC64     000000000000000000      +8 __tracepoint_test_klp_static_keys

test_klp_static_keys.ko
-----------------------

Finally klp-convert has transformed a bunch of symbols for us:

  % eu-readelf --symbols lib/livepatch/test_klp_static_keys.ko | \
        grep -e '__tracepoint_test_klp_static_keys' -e '\<module_key[2]*\>'
     71: 0000000000000000      0 NOTYPE  GLOBAL DEFAULT   LOOS+0 .klp.sym.test_klp_static_keys_mod.__tracepoint_test_klp_static_keys,0
     78: 0000000000000000      0 NOTYPE  GLOBAL DEFAULT   LOOS+0 .klp.sym.test_klp_static_keys_mod.module_key2,0
     84: 0000000000000000      0 NOTYPE  GLOBAL DEFAULT    UNDEF module_key
  % eu-readelf --reloc lib/livepatch/test_klp_static_keys.ko

Relocation section [19] '.rela__jump_table' for section [18] '__jump_table' at offset 0x2480 contains 30 entries:

    Offset              Type            Value               Addend Name
    000000000000000000  X86_64_PC32     000000000000000000     +12 .text
    0x0000000000000004  X86_64_PC32     000000000000000000    +102 .text
    0x0000000000000008  X86_64_PC64     000000000000000000      +8 .klp.sym.test_klp_static_keys_mod.__tracepoint_test_klp_static_keys,0
    0x0000000000000010  X86_64_PC32     000000000000000000    +188 .text
    0x0000000000000014  X86_64_PC32     000000000000000000    +195 .text
    0x0000000000000018  X86_64_PC64     000000000000000000      +8 .klp.sym.test_klp_static_keys_mod.__tracepoint_test_klp_static_keys,0
    0x0000000000000020  X86_64_PC32     000000000000000000    +304 .text
    0x0000000000000024  X86_64_PC32     000000000000000000      +0 .text.unlikely
    0x0000000000000028  X86_64_PC64     000000000000000000     +16 .bss
    0x0000000000000030  X86_64_PC32     000000000000000000    +332 .text
    0x0000000000000034  X86_64_PC32     000000000000000000    +339 .text
    0x0000000000000038  X86_64_PC64     000000000000000000      +8 .klp.sym.test_klp_static_keys_mod.__tracepoint_test_klp_static_keys,0
    0x0000000000000040  X86_64_PC32     000000000000000000    +448 .text
    0x0000000000000044  X86_64_PC32     000000000000000000     +52 .text.unlikely
    0x0000000000000048  X86_64_PC64     000000000000000000      +0 module_key
    0x0000000000000050  X86_64_PC32     000000000000000000    +476 .text
    0x0000000000000054  X86_64_PC32     000000000000000000    +483 .text
    0x0000000000000058  X86_64_PC64     000000000000000000      +8 .klp.sym.test_klp_static_keys_mod.__tracepoint_test_klp_static_keys,0
    0x0000000000000060  X86_64_PC32     000000000000000000    +592 .text
    0x0000000000000064  X86_64_PC32     000000000000000000    +104 .text.unlikely
    0x0000000000000068  X86_64_PC64     000000000000000000      +1 .klp.sym.test_klp_static_keys_mod.module_key2,0
    0x0000000000000070  X86_64_PC32     000000000000000000    +620 .text
    0x0000000000000074  X86_64_PC32     000000000000000000    +710 .text
    0x0000000000000078  X86_64_PC64     000000000000000000      +8 .klp.sym.test_klp_static_keys_mod.__tracepoint_test_klp_static_keys,0
    0x0000000000000080  X86_64_PC32     000000000000000000    +796 .text
    0x0000000000000084  X86_64_PC32     000000000000000000    +886 .text
    0x0000000000000088  X86_64_PC64     000000000000000000      +8 .klp.sym.test_klp_static_keys_mod.__tracepoint_test_klp_static_keys,0
    0x0000000000000090  X86_64_PC32     000000000000000000    +962 .text
    0x0000000000000094  X86_64_PC32     000000000000000000    +981 .text
    0x0000000000000098  X86_64_PC64     000000000000000000      +8 .klp.sym.test_klp_static_keys_mod.__tracepoint_test_klp_static_keys,0

And here's our final set of klp-converted relocations which include the unexported trace point symbol and module_key2 symbols:

Relocation section [44] '.klp.rela.test_klp_static_keys_mod..text' for section [ 3] '.text' at offset 0x55c18 contains 12 entries:

    Offset              Type            Value               Addend Name
    ...
    0x00000000000003eb  X86_64_PC32     000000000000000000     +36 .klp.sym.test_klp_static_keys_mod.__tracepoint_test_klp_static_keys,0
    0x000000000000038c  X86_64_PC32     000000000000000000     +36 .klp.sym.test_klp_static_keys_mod.__tracepoint_test_klp_static_keys,0
    0x00000000000002dc  X86_64_PC32     000000000000000000     +36 .klp.sym.test_klp_static_keys_mod.__tracepoint_test_klp_static_keys,0
    0x00000000000001f9  X86_64_PC32     000000000000000000     +36 .klp.sym.test_klp_static_keys_mod.__tracepoint_test_klp_static_keys,0
    0x0000000000000169  X86_64_PC32     000000000000000000     +36 .klp.sym.test_klp_static_keys_mod.__tracepoint_test_klp_static_keys,0
    0x00000000000000d9  X86_64_PC32     000000000000000000     +36 .klp.sym.test_klp_static_keys_mod.__tracepoint_test_klp_static_keys,0
    0x000000000000007c  X86_64_PC32     000000000000000000     +36 .klp.sym.test_klp_static_keys_mod.__tracepoint_test_klp_static_keys,0
    0x000000000000002c  X86_64_32S      000000000000000000      +0 .klp.sym.test_klp_static_keys_mod.module_key2,0
    ...

Current behavior
----------------

Not good. The livepatch successfully builds but crashes on load:

% insmod lib/livepatch/test_klp_static_keys_mod.ko % insmod lib/livepatch/test_klp_static_keys.ko

  BUG: unable to handle kernel NULL pointer dereference at 0000000000000010
  #PF error: [normal kernel read fault]
  PGD 0 P4D 0
  Oops: 0000 [#1] SMP PTI
  CPU: 3 PID: 9367 Comm: insmod Tainted: G            E K   5.1.0-rc4+ #4
  Hardware name: QEMU Standard PC (i440FX + PIIX, 1996), BIOS ?-20180724_192412-buildhw-07.phx2.fedoraproject.org-1.fc29 04/01/2014
  RIP: 0010:jump_label_apply_nops+0x3b/0x60
  Code: 02 00 00 48 c1 e5 04 48 01 dd 48 39 eb 74 3a 72 0b eb 36 48 83 c3 10 48 39 dd 76 2d 48 8b 43 08 48 89 c2 83 e0 01 48 83 e2 fc <48> 8b 54 13 10 83 e2 01 38 c2 75 dd 48 89 df 31 f6 48 83 c3 10 e8
  RSP: 0018:ffffa8874068fcf8 EFLAGS: 00010206
  RAX: 0000000000000000 RBX: ffffffffc07fd000 RCX: 000000000000000d
  RDX: 000000003f803000 RSI: ffffffffa5077be0 RDI: ffffffffc07fe540
  RBP: ffffffffc07fd0a0 R08: ffffa88740f43878 R09: ffffa88740eed000
  R10: 0000000000055a4b R11: ffffa88740f43878 R12: ffffa88740f430b8
  R13: 0000000000000000 R14: ffffa88740f42df8 R15: 0000000000042b01
  FS:  00007f4f1dafb740(0000) GS:ffff9a81fbb80000(0000) knlGS:0000000000000000
  CS:  0010 DS: 0000 ES: 0000 CR0: 0000000080050033
  CR2: 0000000000000010 CR3: 00000000b5d8a000 CR4: 00000000000006e0
  Call Trace:
   module_finalize+0x184/0x1c0
   load_module+0x1400/0x1910
   ? kernel_read_file+0x18d/0x1c0
   ? __do_sys_finit_module+0xa8/0x110
   __do_sys_finit_module+0xa8/0x110
   do_syscall_64+0x55/0x1a0
   entry_SYSCALL_64_after_hwframe+0x44/0xa9
  RIP: 0033:0x7f4f1cae82bd

Future work
-----------

At the very least, I think this call-chain ordering is wrong for livepatch static key symbols:

load_module

    apply_relocations

    post_relocation
      module_finalize
        jump_label_apply_nops                                         <<

    ...

    prepare_coming_module
      blocking_notifier_call_chain(&module_notify_list, MODULE_STATE_COMING, mod);
        jump_label_module_notify
          case MODULE_STATE_COMING
            jump_label_add_module                                     <<

    do_init_module

      do_one_initcall(mod->init)
        __init patch_init [kpatch-patch]
          klp_register_patch
            klp_init_patch
              klp_for_each_object(patch, obj)
                klp_init_object
                  klp_init_object_loaded
                    klp_write_object_relocations                      <<

      blocking_notifier_call_chain(&module_notify_list, MODULE_STATE_LIVE, mod);
        jump_label_module_notify
          case MODULE_STATE_LIVE
            jump_label_invalidate_module_init

where klp_write_object_relocations() is called way *after* jump_label_apply_nops() and jump_label_add_module().

Detection
---------

I have been tinkering with some prototype code to defer jump_label_apply_nops() and jump_label_add_module(), but it has been slow going. I think the jist of it is that we're going to need to call these dynamically when individual klp_objects are patched, not when the livepatch module itself loads. If anyone with static key expertise wants to jump in here, let me know.

In the meantime, I cooked up a potential followup commit to detect conversion of static key symbols and klp-convert failure. It basically runs through the output .ko's ELF symbols and verifies that none of the converted ones can be found as a .rela__jump_table relocated symbol. It accurately catches the problematic references in test_klp_static_keys.ko thus far.

This was based on a similar issue reported as a bug against kpatch-build, in which Josh wrote code to detect this scenario:

https://github.com/dynup/kpatch/issues/946
https://github.com/jpoimboe/kpatch/commit/2cd2d27607566aee9590c367e615207ce1ce24c6

I can post ("livepatch/klp-convert: abort on static key conversion") here as a follow commit if it looks reasonable and folks wish to review it... or we can try and tackle static keys before merging klp-convert.

-- Joe

maintainer
#29 lore raw

[...]

Quoted 74 lines

Current behavior
----------------

Not good. The livepatch successfully builds but crashes on load:

% insmod lib/livepatch/test_klp_static_keys_mod.ko % insmod lib/livepatch/test_klp_static_keys.ko

  BUG: unable to handle kernel NULL pointer dereference at 0000000000000010
  #PF error: [normal kernel read fault]
  PGD 0 P4D 0
  Oops: 0000 [#1] SMP PTI
  CPU: 3 PID: 9367 Comm: insmod Tainted: G            E K   5.1.0-rc4+ #4
  Hardware name: QEMU Standard PC (i440FX + PIIX, 1996), BIOS ?-20180724_192412-buildhw-07.phx2.fedoraproject.org-1.fc29 04/01/2014
  RIP: 0010:jump_label_apply_nops+0x3b/0x60
  Code: 02 00 00 48 c1 e5 04 48 01 dd 48 39 eb 74 3a 72 0b eb 36 48 83 c3 10 48 39 dd 76 2d 48 8b 43 08 48 89 c2 83 e0 01 48 83 e2 fc <48> 8b 54 13 10 83 e2 01 38 c2 75 dd 48 89 df 31 f6 48 83 c3 10 e8
  RSP: 0018:ffffa8874068fcf8 EFLAGS: 00010206
  RAX: 0000000000000000 RBX: ffffffffc07fd000 RCX: 000000000000000d
  RDX: 000000003f803000 RSI: ffffffffa5077be0 RDI: ffffffffc07fe540
  RBP: ffffffffc07fd0a0 R08: ffffa88740f43878 R09: ffffa88740eed000
  R10: 0000000000055a4b R11: ffffa88740f43878 R12: ffffa88740f430b8
  R13: 0000000000000000 R14: ffffa88740f42df8 R15: 0000000000042b01
  FS:  00007f4f1dafb740(0000) GS:ffff9a81fbb80000(0000) knlGS:0000000000000000
  CS:  0010 DS: 0000 ES: 0000 CR0: 0000000080050033
  CR2: 0000000000000010 CR3: 00000000b5d8a000 CR4: 00000000000006e0
  Call Trace:
   module_finalize+0x184/0x1c0
   load_module+0x1400/0x1910
   ? kernel_read_file+0x18d/0x1c0
   ? __do_sys_finit_module+0xa8/0x110
   __do_sys_finit_module+0xa8/0x110
   do_syscall_64+0x55/0x1a0
   entry_SYSCALL_64_after_hwframe+0x44/0xa9
  RIP: 0033:0x7f4f1cae82bd

Future work
-----------

At the very least, I think this call-chain ordering is wrong for livepatch static key symbols:

load_module

    apply_relocations

    post_relocation
      module_finalize
        jump_label_apply_nops                                         <<

    ...

    prepare_coming_module
      blocking_notifier_call_chain(&module_notify_list, MODULE_STATE_COMING, mod);
        jump_label_module_notify
          case MODULE_STATE_COMING
            jump_label_add_module                                     <<

    do_init_module

      do_one_initcall(mod->init)
        __init patch_init [kpatch-patch]
          klp_register_patch
            klp_init_patch
              klp_for_each_object(patch, obj)
                klp_init_object
                  klp_init_object_loaded
                    klp_write_object_relocations                      <<

      blocking_notifier_call_chain(&module_notify_list, MODULE_STATE_LIVE, mod);
        jump_label_module_notify
          case MODULE_STATE_LIVE
            jump_label_invalidate_module_init
Quoted 2 lines

where klp_write_object_relocations() is called way *after* jump_label_apply_nops() and jump_label_add_module().

Quick look, but it seems quite similar to the problem we had with apply_alternatives(). See arch/x86/kernel/livepatch.c and the commit which introduced it.

I think, we should do the same for jump labels. Add jump_label_apply_nops() from module_finalize() to arch_klp_init_object_loaded() and convert jump_table ELF section so its processing is delayed.

Which leads me another TODO... klp-convert does not convert even .altinstructions and .parainstructions sections, so it has that problem as well. If I remember, it was on Josh's TODO list when he first introduced klp-convert. See [email protected].

The selftest for the alternatives would be appreciated too. One day.

And of course we should look at the other supported architectures and their module_finalize() functions. I have it on my TODO list somewhere, but you know how it works with those :/. I am sure there are more hidden surprises there.

Quoted 20 lines

Detection
---------

I have been tinkering with some prototype code to defer jump_label_apply_nops() and jump_label_add_module(), but it has been slow going. I think the jist of it is that we're going to need to call these dynamically when individual klp_objects are patched, not when the livepatch module itself loads. If anyone with static key expertise wants to jump in here, let me know.

In the meantime, I cooked up a potential followup commit to detect conversion of static key symbols and klp-convert failure. It basically runs through the output .ko's ELF symbols and verifies that none of the converted ones can be found as a .rela__jump_table relocated symbol. It accurately catches the problematic references in test_klp_static_keys.ko thus far.

This was based on a similar issue reported as a bug against kpatch-build, in which Josh wrote code to detect this scenario:

Quoted 6 lines

https://github.com/dynup/kpatch/issues/946
https://github.com/jpoimboe/kpatch/commit/2cd2d27607566aee9590c367e615207ce1ce24c6

I can post ("livepatch/klp-convert: abort on static key conversion") here as a follow commit if it looks reasonable and folks wish to review it... or we can try and tackle static keys before merging klp-convert.

Good idea. I'd rather fix it, but I think it could be a lot of work, so something like this patch seems to be a good idea.

Thanks
Miroslav

author maintainer
#30 lore raw
Quoted 6 lines · Miroslav Benes

[ ... snip ... ]

Quick look, but it seems quite similar to the problem we had with apply_alternatives(). See arch/x86/kernel/livepatch.c and the commit which introduced it.

That was an interesting diversion :) I think I grok the idea as:

The kernel supports a few different code-patching methods:

- SMP locks
- alternatives
- paravirt
- jump labels

and we need to ensure that they do not prematurely operate on unresolved klp-relocations. The solution that led to arch/x86/kernel/livepatch.c introduces "klp.arch" sections that rename such klp-relocations *and* their associated special section data structures. Processing is then deferred until after a relevant klp_object is loaded.

Quoted 4 lines

I think, we should do the same for jump labels. Add jump_label_apply_nops() from module_finalize() to arch_klp_init_object_loaded() and convert jump_table ELF section so its processing is delayed.

Nod. Tthat sounds about right. There may be some more work yet in the static keys API as well, but I'm not 100%.

Quoted 4 lines

Which leads me another TODO... klp-convert does not convert even .altinstructions and .parainstructions sections, so it has that problem as well. If I remember, it was on Josh's TODO list when he first introduced klp-convert. See [email protected].

In the RFC, Josh highlights a somewhat difficult problem regarding these special sections -- how to associate these special section data structures and their relocations to a specific klp_object.

If I understand his suggestion, he proposed annotating livepatch module replacement functions as to stuff them into specially named ELF sections (which would include the klp_object name) and then bypass the existing livepatch registration API. No minor change.

With that in mind, I'm starting to think of a game plan for klp-convert like:

- phase 1: detect /abort unsupported sections

- phase 2: manual annotations in livepatch modules (like KLP_MODULE_RELOC / SYMPOS, but for special sections) so that klp-convert can start building "klp.arch" sections

- phase 3: livepatch API change above to support somewhat more automatic generation of phase 2 annotations

Quoted 1 line

The selftest for the alternatives would be appreciated too. One day.

In the course of understanding the background behind arch/x86/kernel/livepatch.c, I wrote a bunch of livepatch selftests that try out simple examples of those special sections.

For alternatives, I did something like:

  /* TODO: find reliably true/false features */
  #define TRUE_FEATURE	(X86_FEATURE_FPU)
  #define FALSE_FEATURE	(X86_FEATURE_VME)

...

klp_function1()
klp_function2()
klp_new_function()

  	asm (ALTERNATIVE("call klp_function1", "call klp_function2", TRUE_FEATURE));
  	asm (ALTERNATIVE("call klp_function1", "call klp_function2", FALSE_FEATURE));

  	asm (ALTERNATIVE("call mod_function1", "call mod_function2", TRUE_FEATURE));
  	asm (ALTERNATIVE("call mod_function1", "call mod_function2", FALSE_FEATURE));
  	asm (ALTERNATIVE("call mod_function2", "call mod_function1", TRUE_FEATURE));
  	asm (ALTERNATIVE("call mod_function2", "call mod_function1", FALSE_FEATURE));

so that I could see what kind of relocations were generated for default and non-default instructions as well as module-local and then unexported-extern functions.

Once we have klp-convert supporting these conversions, I think something like that would suffice. In the meantime, I'm not sure how to create "klp.arch" sectioned ELFs without something like kpatch-build.

Quoted 4 lines

And of course we should look at the other supported architectures and their module_finalize() functions. I have it on my TODO list somewhere, but you know how it works with those :/. I am sure there are more hidden surprises there.

Hmm, well powerpc and s390 do appear to have processing for special sections as well ... but for the moment, I'm going to focus on x86 as that seems like enough work for now :)

Quoted 9 lines
Quoted 6 lines

Detection
---------

I can post ("livepatch/klp-convert: abort on static key conversion") here as a follow commit if it looks reasonable and folks wish to review it... or we can try and tackle static keys before merging klp-convert.

Good idea. I'd rather fix it, but I think it could be a lot of work, so something like this patch seems to be a good idea.

I'm thinking of adding this in a commit so klp-convert can intercept these sections:

  static bool is_section_supported(char *sname)
  {
          if (strcmp(sname, ".rela.altinstructions") == 0)
                  return false;
          if (strcmp(sname, ".rela.parainstructions") == 0)
                  return false;
          if (strcmp(sname, ".rela__jump_table") == 0)
                  return false;
          return true;
  }

Right now my v4 collection has a bunch of small fixups and nitpick corrections. It feels like a good resting place for now before embarking on special section support, what do you think?

-- Joe

maintainer
#31 lore raw
Quoted 17 lines · Joe Lawrence
Quoted 6 lines · Miroslav Benes

[ ... snip ... ]

Quick look, but it seems quite similar to the problem we had with apply_alternatives(). See arch/x86/kernel/livepatch.c and the commit which introduced it.

That was an interesting diversion :) I think I grok the idea as:

The kernel supports a few different code-patching methods:

- SMP locks
- alternatives
- paravirt
- jump labels

Quoted 5 lines

and we need to ensure that they do not prematurely operate on unresolved klp-relocations. The solution that led to arch/x86/kernel/livepatch.c introduces "klp.arch" sections that rename such klp-relocations *and* their associated special section data structures. Processing is then deferred until after a relevant klp_object is loaded.

Correct.

Quoted 25 lines
Quoted 4 lines

I think, we should do the same for jump labels. Add jump_label_apply_nops() from module_finalize() to arch_klp_init_object_loaded() and convert jump_table ELF section so its processing is delayed.

Nod. Tthat sounds about right. There may be some more work yet in the static keys API as well, but I'm not 100%.

Quoted 4 lines

Which leads me another TODO... klp-convert does not convert even .altinstructions and .parainstructions sections, so it has that problem as well. If I remember, it was on Josh's TODO list when he first introduced klp-convert. See [email protected].

In the RFC, Josh highlights a somewhat difficult problem regarding these special sections -- how to associate these special section data structures and their relocations to a specific klp_object.

If I understand his suggestion, he proposed annotating livepatch module replacement functions as to stuff them into specially named ELF sections (which would include the klp_object name) and then bypass the existing livepatch registration API. No minor change.

With that in mind, I'm starting to think of a game plan for klp-convert like:

Quoted 8 lines

- phase 1: detect /abort unsupported sections

- phase 2: manual annotations in livepatch modules (like KLP_MODULE_RELOC / SYMPOS, but for special sections) so that klp-convert can start building "klp.arch" sections

- phase 3: livepatch API change above to support somewhat more automatic generation of phase 2 annotations

Looks good to me. First, I'd focus on something which covers (hopefully) a vast majority cases and then we can do the rest. So yes, this seems to be a good plan.

Quoted 8 lines
Quoted 4 lines

And of course we should look at the other supported architectures and their module_finalize() functions. I have it on my TODO list somewhere, but you know how it works with those :/. I am sure there are more hidden surprises there.

Hmm, well powerpc and s390 do appear to have processing for special sections as well ... but for the moment, I'm going to focus on x86 as that seems like enough work for now :)

Yes, please :).

Quoted 24 lines
Quoted 9 lines
Quoted 6 lines

Detection
---------

I can post ("livepatch/klp-convert: abort on static key conversion") here as a follow commit if it looks reasonable and folks wish to review it... or we can try and tackle static keys before merging klp-convert.

Good idea. I'd rather fix it, but I think it could be a lot of work, so something like this patch seems to be a good idea.

I'm thinking of adding this in a commit so klp-convert can intercept these sections:

  static bool is_section_supported(char *sname)
  {
          if (strcmp(sname, ".rela.altinstructions") == 0)
                  return false;
          if (strcmp(sname, ".rela.parainstructions") == 0)
                  return false;
          if (strcmp(sname, ".rela__jump_table") == 0)
                  return false;
          return true;
  }
Quoted 3 lines

Right now my v4 collection has a bunch of small fixups and nitpick corrections. It feels like a good resting place for now before embarking on special section support, what do you think?

Yes.

Thanks
Miroslav

#32 lore raw
In reply to Joe Lawrence
Quoted 15 lines · Joe Lawrence

Hi folks,

This is the third installment of the klp-convert tool for generating and processing livepatch symbols for livepatch module builds. For those following along at home, archive links to previous versions:

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

(Note that I don't see v2 archived at lore, but that is a link to the most recent subthread that lore did catch.)

Quoted 9 lines

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.

Could we get some details with examples or a sample, sorry I might be dense and missing simple information. The problem being solved is not clear to me from the changelog.

Quoted 27 lines

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 Symbols.list 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.

Quoted 6 lines

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.

Are these a part of the series?

Balbir Singh

Quoted 188 lines

Branches
--------

Since I spent some time tinkering with v2 and accumulated a bunch of fixes, I collected them up and am posting this new version. For review purposes, I posted two branches up to github:

1 - an expanded branch that with changes separate from the original
https://github.com/joe-lawrence/linux/commits/klp-convert-v3-expanded

2 - a squashed branch of (1) that comprises v3:
https://github.com/joe-lawrence/linux/commits/klp-convert-v3

Non-trivial commits in the expanded branch have some extra commentary and details for debugging in the commit message that were dropped when squashing into their respective parent commits.

TODO
----

There are a few outstanding items that I came across while reviewing v2, but as changes started accumulating, it made sense to defer those to a later version. I'll reply to this thread individual topics to start discussion sub-threads for those.

Changelogs
----------

The commit changelogs were getting long, so I've moved them here for posterity and review purposes:

livepatch: Create and include UAPI headers
v2:
- jmoreira: split up and changelog
v3:
- joe: convert to SPDX license tags

kbuild: Support for Symbols.list creation
v3:
- jmoreira: adjust for multiobject livepatch
- joe: add klpclean to PHONY
- joe: align KLP prefix

livepatch: Add klp-convert tool
v2:
- khlebnikov: use HOSTLOADLIBES_ instead of HOSTLDFLAGS: -lelf must be at the end
- jmoreira: add support to automatic relocation conversion in klp-convert.c, changelog
v3:
- joe: convert to SPDX license tags
- jmoreira: add rela symbol name to WARNs
- jmoreira: ignore relocations to .TOC and symbols with index 0
- joe: separate and fix valid_sympos() sympos=0 and sympos=1..n checks
- joe: fix symbol use-after-frees
- joe: fix remaining valgrind leak complaints (non-error paths only)
- joe: checkpatch nits

livepatch: Add klp-convert annotation helpers
v2:
- jmoreira: split up: move KLP_MODULE_RELOC from previous patch to here, add KLP_SYMPOS, move macros from include/uapi/livepatch.h to include/linux/livepatch.h
v3:
- joe: suggested by jpoimboe, KLP_MODULE_RELOC macro should 4-byte align klp_module_reloc structures

modpost: Integrate klp-convert
v2:
- khlebnikov: save cmd_ld_ko_o into .module.cmd, if_changed_rule doesn't do that.f
- khlebnikov: fix bashisms for debian where /bin/sh is a symlink to /bin/dash
- khlebnikov: rename rule_link_module to rule_ld_ko_o, otherwise arg-check inside if_changed_rule compares cmd_link_module and cmd_ld_ko_o.
- khlebnikov: check modinfo -F livepatch only if CONFIG_LIVEPATCH is true.
- mbenes: remove modinfo call. LIVEPATCH_ in Makefile
- jmoreira: split up: move the .livepatch file-based scheme for identifying livepatches to a previous patch, as it was required for correctly building Symbols.list there.
v3:
- joe: adjust rule_ld_ko_o to call echo-cmd
- joe: rebase for v5.1
- joe: align KLP prefix

modpost: Add modinfo flag to livepatch modules
v2:
- jmoreira: fix modpost.c (add_livepatch_flag) to update module structure with livepatch flag and prevent modpost from breaking due to unresolved symbols
v3:
- joe: adjust modpost.c::get_modinfo() call for v5.0 version

livepatch: Add sample livepatch module
v3:
- joe: update all in-tree livepatches with LIVEPATCH_* modinfo flag

documentation: Update on livepatch elf format
v2:
- jmoreira: update module to use KLP_SYMPOS
- jmoreira: Comments on symbol resolution scheme
- jmoreira: Update Makefile
- jmoreira: Remove MODULE_INFO statement
- jmoreira: Changelog
v3:
- joe: rebase for v5.1
- joe: code shuffle to better match original source file

livepatch/selftests: add klp-convert
v3:
- joe: clarify sympos=0 and sympos=1..n

And now the usual git cover-letter boilerplate...

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

Joe Lawrence (1):
livepatch/selftests: add klp-convert

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

Miroslav Benes (1):
modpost: Add modinfo flag to livepatch modules

 .gitignore                                    |   1 +
 Documentation/livepatch/livepatch.txt         |   3 +
 Documentation/livepatch/module-elf-format.txt |  50 +-
 MAINTAINERS                                   |   2 +
 Makefile                                      |  30 +-
 include/linux/livepatch.h                     |  13 +
 include/uapi/linux/livepatch.h                |  22 +
 kernel/livepatch/core.c                       |   4 +-
 lib/livepatch/Makefile                        |  15 +
 lib/livepatch/test_klp_atomic_replace.c       |   1 -
 lib/livepatch/test_klp_callbacks_demo.c       |   1 -
 lib/livepatch/test_klp_callbacks_demo2.c      |   1 -
 lib/livepatch/test_klp_convert1.c             | 106 +++
 lib/livepatch/test_klp_convert2.c             | 103 +++
 lib/livepatch/test_klp_convert_mod_a.c        |  25 +
 lib/livepatch/test_klp_convert_mod_b.c        |  13 +
 lib/livepatch/test_klp_livepatch.c            |   1 -
 samples/livepatch/Makefile                    |   7 +
 .../livepatch/livepatch-annotated-sample.c    | 102 +++
 samples/livepatch/livepatch-sample.c          |   1 -
 scripts/Kbuild.include                        |   4 +-
 scripts/Makefile                              |   1 +
 scripts/Makefile.build                        |   7 +
 scripts/Makefile.modpost                      |  24 +-
 scripts/livepatch/.gitignore                  |   1 +
 scripts/livepatch/Makefile                    |   7 +
 scripts/livepatch/elf.c                       | 753 ++++++++++++++++++
 scripts/livepatch/elf.h                       |  72 ++
 scripts/livepatch/klp-convert.c               | 692 ++++++++++++++++
 scripts/livepatch/klp-convert.h               |  39 +
 scripts/livepatch/list.h                      | 391 +++++++++
 scripts/mod/modpost.c                         |  82 +-
 scripts/mod/modpost.h                         |   1 +
 .../selftests/livepatch/test-livepatch.sh     |  64 ++
 34 files changed, 2616 insertions(+), 23 deletions(-)
 create mode 100644 include/uapi/linux/livepatch.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
 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.20.1
maintainer
#33 lore raw
Quoted 27 lines · Balbir Singh
Quoted 15 lines · Joe Lawrence

Hi folks,

This is the third installment of the klp-convert tool for generating and processing livepatch symbols for livepatch module builds. For those following along at home, archive links to previous versions:

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

(Note that I don't see v2 archived at lore, but that is a link to the most recent subthread that lore did catch.)

Quoted 9 lines

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.

Quoted 3 lines

Could we get some details with examples or a sample, sorry I might be dense and missing simple information. The problem being solved is not clear to me from the changelog.

The patch set tries to solve the problem described in Documentation/livepatch/module-elf-format.txt. Currently, there is no tool in upstream to automatically generate the relocation records. kpatch-build can do it and we'd like to have it as well. klp-convert should thus do the job.

The sample module is introduced in patch 7 and you can look at the selftests in patch 9 too.

Maybe we can describe the problem better in the cover letter, but on the other hand patch changelogs are more important and they are good (well, in my opinion of course).

Quoted 35 lines
Quoted 27 lines

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 Symbols.list 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.

Quoted 6 lines

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.

Quoted 1 line

Are these a part of the series?

Yes, see 9/9.

Regards,
Miroslav

author maintainer
#34 lore raw
In reply to Balbir Singh
Quoted 5 lines · Balbir Singh

Could we get some details with examples or a sample, sorry I might be dense and missing simple information. The problem being solved is not clear to me from the changelog.

Hi Balbir,

I see that Miroslav has already pointed to documentation, samples and self-tests for the patchset, but here is a summary in my own words:

kpatch-build constructs livepatch kernel modules by comparing a reference build with a patched build, combing through ELF object sections and extracting new and changed sections that include patched code.

An alternative approach is "source-based", in which a livepatch kernel module is built (mostly entirely) using the kernel's build infrastructure. Sources for a livepatch are gathered ahead of time and then built like an ordinary kernel module.

In either approach, there lies the problem of symbol visibility: how can a livepatch resolve symbols that a kernel module ordinarily can't. For example, file local or simply unexported symbols in across the kernel and other modules. Enter the concept of "livepatch symbols" described in module-elf-format.txt.

kpatch-build already creates such "livepatch symbols" (see its create_klp_relasecs_and_syms()) and the livepatching core kernel code already knows how resolve such symbols at klp_object patch time (see klp_write_object_relocations()).

The klp-convert tool and this supporting patchset would empower source-based-constructed livepatch modules to do the same.

-- Joe

author maintainer
#35 lore raw
In reply to Joe Lawrence
Quoted 15 lines · Joe Lawrence

Hi folks,

This is the third installment of the klp-convert tool for generating and processing livepatch symbols for livepatch module builds. For those following along at home, archive links to previous versions:

RFC:

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

(Note that I don't see v2 archived at lore, but that is a link to the most recent subthread that lore did catch.)

Quoted 8 lines

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.

Hi Miroslav,

I noticed that some binutils programs like gdb, objdump, etc. don't like the .ko kernel objects that we're generating from this patchset, specifically those with the additional '.klp.rela.<obj>..text' livepatch symbol relocation sections.

For reference, I opened a new bugzilla with more details here:
https://sourceware.org/bugzilla/show_bug.cgi?id=24456

And was about to ping the binutils mailing list about the assertion that is tripping in bfd/elf.c. The thought occurred to me that you guys might already be carrying a patch to workaround this issue?

-- Joe

maintainer
#36 lore raw
Quoted 27 lines · Joe Lawrence
Quoted 15 lines · Joe Lawrence

Hi folks,

This is the third installment of the klp-convert tool for generating and processing livepatch symbols for livepatch module builds. For those following along at home, archive links to previous versions:

RFC:

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

(Note that I don't see v2 archived at lore, but that is a link to the most recent subthread that lore did catch.)

Quoted 8 lines

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.

Hi Miroslav,

Quoted 7 lines

I noticed that some binutils programs like gdb, objdump, etc. don't like the .ko kernel objects that we're generating from this patchset, specifically those with the additional '.klp.rela.<obj>..text' livepatch symbol relocation sections.

For reference, I opened a new bugzilla with more details here:
https://sourceware.org/bugzilla/show_bug.cgi?id=24456

Another great catch.

Quoted 3 lines

And was about to ping the binutils mailing list about the assertion that is tripping in bfd/elf.c. The thought occurred to me that you guys might already be carrying a patch to workaround this issue?

No, unfortunately we don't. At least I don't know about anything and a quick test on openSUSE Leap 15.0 confirms it (objdump -D gives "bad value").

Thanks
Miroslav

author maintainer
#37 lore raw
In reply to Joe Lawrence
Quoted 10 lines · Joe Lawrence

[ ... snip ... ]

TODO
----

There are a few outstanding items that I came across while reviewing v2, but as changes started accumulating, it made sense to defer those to a later version. I'll reply to this thread individual topics to start discussion sub-threads for those.

Multiple object files
=====================

For v3, we tweaked the build scripts so that we could successfully build a klp-converted livepatch module from multiple object files.

One interesting use-case is supporting two livepatch symbols of the same name, but different object/position values.

An example target kernel module might be layed out like this:

test_klp_convert_mod.ko << target module is comprised of

                                     two object files, each defining
    test_klp_convert_mod_a.o         their own local get_homonym_string()
      get_homonym_string()           function and homonym_string[]
      homonym_string[]               character arrays.

    test_klp_convert_mod_b.o
      get_homonym_string()
      homonym_string[]

A look at interesting parts of the the module's symbol table:

  % eu-readelf --symbols lib/livepatch/test_klp_convert_mod.ko | \
        grep -e 'homonym' -e test_klp_convert_mod_
     29: 0000000000000000      0 FILE    LOCAL  DEFAULT      ABS test_klp_convert_mod_a.c
     32: 0000000000000010      8 FUNC    LOCAL  DEFAULT        3 get_homonym_string
     33: 0000000000000000     17 OBJECT  LOCAL  DEFAULT        5 homonym_string
     37: 0000000000000000      0 FILE    LOCAL  DEFAULT      ABS test_klp_convert_mod_b.c
     38: 0000000000000020      8 FUNC    LOCAL  DEFAULT        3 get_homonym_string
     39: 0000000000000000     17 OBJECT  LOCAL  DEFAULT       11 homonym_string

suggests that any livepatch module that wishes to resolve to test_klp_convert_mod_a.c :: get_homonym_string() should include an annotation like:

file_a.c:

      KLP_MODULE_RELOC(test_klp_convert_mod) relocs_a[] = {
            KLP_SYMPOS(get_homonym_string, 1),
      };

and to resolve test_klp_convert_mod_b.c :: get_homonym_string():

file_b.c:

      KLP_MODULE_RELOC(test_klp_convert_mod) relocs_b[] = {
            KLP_SYMPOS(get_homonym_string, 2),
      };

Unfortunately klp-convert v3 will fail to build such livepatch module, regardless of sympos values:

klp-convert: Conflicting KLP_SYMPOS definition: vmlinux.state_show,2 vs. vmlinux.state_show,1.
klp-convert: Unable to load user-provided sympos
make[1]: *** [scripts/Makefile.modpost:148: lib/livepatch/test_klp_convert_multi_objs.ko] Error 255

This abort message can be traced to sympos_sanity_check() as it verifies that there no duplicate symbol names found in its list of user specified symbols (ie, those needing to be converted).

Common sympos
-------------

New test case and related fixup can be found here:

https://github.com/joe-lawrence/linux/commits/klp-convert-v4-multiple-objs

To better debug this issue, I added another selftest that demonstrates this configuration in isolation. "show_state" is a popular kernel function name (my VM reported 5 instances in kallsyms) so I chose that symbol name.

Initially I specified the *same* symbol position (1) in both .c file KLP_SYMPOS annotations. At the very least, we can trivially patch klp-convert v3 to support annotations for the the same symbol <object, name, position> value across object files.

Result: a small tweak to sympos_sanity_check() to relax its symbol uniqueness verification: allow for duplicate <object, name, position> instances. Now it will only complain when a supplied symbol references the same <object, name> but a different <position>.

scripts/livepatch/klp-convert.c +7 -2
index 82c27d219372..713835dfc9ec 100644
@@ -194,7 +194,10 @@ static void clear_sympos_annontations(struct elf *klp_elf)
 	}
 }
 
-/* Checks if two or more elements in usr_symbols have the same name */
+/*
+ * Checks if two or more elements in usr_symbols have the same
+ * object and name, but different symbol position
+ */
 static bool sympos_sanity_check(void)
 {
 	bool sane = true;
@@ -203,7 +206,9 @@ static bool sympos_sanity_check(void)
 	list_for_each_entry(sp, &usr_symbols, list) {
 		aux = list_next_entry(sp, list);
 		list_for_each_entry_from(aux, &usr_symbols, list) {
-			if (strcmp(sp->symbol_name, aux->symbol_name) == 0) {
+			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);

Unique sympos
-------------

But even with the above workaround, specifying unique symbol positions will (and should) result in a klp-convert complaint.

When modifying the test module with unique symbol position annotation values (1 and 2 respectively):

test_klp_convert_multi_objs_a.c:

    extern void *state_show;
    ...
    KLP_MODULE_RELOC(vmlinux) vmlinux_relocs_b[] = {
            KLP_SYMPOS(state_show, 1)
    };

test_klp_convert_multi_objs_b.c:

    extern void *state_show;
    ...
    KLP_MODULE_RELOC(vmlinux) vmlinux_relocs_b[] = {
            KLP_SYMPOS(state_show, 2)
    };

Each object file's symbol table contains a "state_show" instance:

  % eu-readelf --symbols lib/livepatch/test_klp_convert_multi_objs_a.o | grep '\<state_show\>'
     30: 0000000000000000      0 NOTYPE  GLOBAL DEFAULT    UNDEF state_show

  % eu-readelf --symbols lib/livepatch/test_klp_convert_multi_objs_b.o | grep '\<state_show\>'
     20: 0000000000000000      0 NOTYPE  GLOBAL DEFAULT    UNDEF state_show

and the intermediate test_klp_convert_multi_objs.klp.o file contains a combined .klp.module_relocs.vmlinux relocation section with two KLP_SYMPOS structures, each with a unique <sympos> value:

  % objcopy -O binary --only-section=.klp.module_relocs.vmlinux \
      lib/livepatch/test_klp_convert_multi_objs.klp.o >(hexdump)

0000000 0000 0000 0000 0000 0001 0000 0000 0000
0000010 0000 0000 0002 0000

but the symbol tables were merged, sorted and non-unique symbols removed, leaving a *single* unresolved "state_show" instance:

  % eu-readelf --symbols lib/livepatch/test_klp_convert_multi_objs.klp.o | grep '\<state_show\>'
     53: 0000000000000000      0 NOTYPE  GLOBAL DEFAULT    UNDEF state_show

which means that even though we have separate relocations for each "state_show" instance:

Relocation section [ 6] '.rela.text.unlikely' for section [ 5] '.text.unlikely' at offset 0x44510 contains 11 entries:

    Offset              Type            Value               Addend Name
    0x0000000000000003  X86_64_32S      000000000000000000      +0 state_show
    ...
    0x0000000000000034  X86_64_32S      000000000000000000      +0 state_show
    ...

they share the same rela->sym and there is no way to distinguish which one correlates to which KLP_SYMPOS structure.

Future Work
-----------

I don't see an easy way to support multiple homonym <object, name> symbols with unique <position> values in the current livepatch module Elf format. The only solutions that come to mind right now include renaming homonym symbols somehow to retain the relocation->symbol relationship when separate object files are combined. Perhaps an intermediate linker step could make annotated symbols unique in some way to achieve this. /thinking out loud

In the meantime, the unique symbol <position> case is already detected and with a little tweaking we could support multiple common symbol <position> values.

-- Joe

maintainer
#38 lore raw

[...]

Quoted 22 lines

Result: a small tweak to sympos_sanity_check() to relax its symbol uniqueness verification: allow for duplicate <object, name, position> instances. Now it will only complain when a supplied symbol references the same <object, name> but a different <position>.

scripts/livepatch/klp-convert.c +4 -1
index 82c27d219372..713835dfc9ec 100644
@@ -194,7 +194,10 @@ static void clear_sympos_annontations(struct elf *klp_elf)
 	}
 }
 
-/* Checks if two or more elements in usr_symbols have the same name */
+/*
+ * Checks if two or more elements in usr_symbols have the same
+ * object and name, but different symbol position
+ */
 static bool sympos_sanity_check(void)
 {
 	bool sane = true;

scripts/livepatch/klp-convert.c static bool sympos_sanity_check(void) · line 214

Quoted 10 lines
scripts/livepatch/klp-convert.c +3 -1
@@ -203,7 +206,9 @@ static bool sympos_sanity_check(void)
 	list_for_each_entry(sp, &usr_symbols, list) {
 		aux = list_next_entry(sp, list);
 		list_for_each_entry_from(aux, &usr_symbols, list) {
-			if (strcmp(sp->symbol_name, aux->symbol_name) == 0) {
+			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);

Looks good and I'd definitely include it in v4.

Quoted 67 lines

Unique sympos
-------------

But even with the above workaround, specifying unique symbol positions will (and should) result in a klp-convert complaint.

When modifying the test module with unique symbol position annotation values (1 and 2 respectively):

test_klp_convert_multi_objs_a.c:

    extern void *state_show;
    ...
    KLP_MODULE_RELOC(vmlinux) vmlinux_relocs_b[] = {
            KLP_SYMPOS(state_show, 1)
    };

test_klp_convert_multi_objs_b.c:

    extern void *state_show;
    ...
    KLP_MODULE_RELOC(vmlinux) vmlinux_relocs_b[] = {
            KLP_SYMPOS(state_show, 2)
    };

Each object file's symbol table contains a "state_show" instance:

  % eu-readelf --symbols lib/livepatch/test_klp_convert_multi_objs_a.o | grep '\<state_show\>'
     30: 0000000000000000      0 NOTYPE  GLOBAL DEFAULT    UNDEF state_show

  % eu-readelf --symbols lib/livepatch/test_klp_convert_multi_objs_b.o | grep '\<state_show\>'
     20: 0000000000000000      0 NOTYPE  GLOBAL DEFAULT    UNDEF state_show

and the intermediate test_klp_convert_multi_objs.klp.o file contains a combined .klp.module_relocs.vmlinux relocation section with two KLP_SYMPOS structures, each with a unique <sympos> value:

  % objcopy -O binary --only-section=.klp.module_relocs.vmlinux \
      lib/livepatch/test_klp_convert_multi_objs.klp.o >(hexdump)

0000000 0000 0000 0000 0000 0001 0000 0000 0000
0000010 0000 0000 0002 0000

but the symbol tables were merged, sorted and non-unique symbols removed, leaving a *single* unresolved "state_show" instance:

  % eu-readelf --symbols lib/livepatch/test_klp_convert_multi_objs.klp.o | grep '\<state_show\>'
     53: 0000000000000000      0 NOTYPE  GLOBAL DEFAULT    UNDEF state_show

which means that even though we have separate relocations for each "state_show" instance:

Relocation section [ 6] '.rela.text.unlikely' for section [ 5] '.text.unlikely' at offset 0x44510 contains 11 entries:

    Offset              Type            Value               Addend Name
    0x0000000000000003  X86_64_32S      000000000000000000      +0 state_show
    ...
    0x0000000000000034  X86_64_32S      000000000000000000      +0 state_show
    ...

they share the same rela->sym and there is no way to distinguish which one correlates to which KLP_SYMPOS structure.

Future Work
-----------

Quoted 7 lines

I don't see an easy way to support multiple homonym <object, name> symbols with unique <position> values in the current livepatch module Elf format. The only solutions that come to mind right now include renaming homonym symbols somehow to retain the relocation->symbol relationship when separate object files are combined. Perhaps an intermediate linker step could make annotated symbols unique in some way to achieve this. /thinking out loud

I'd set this aside for now and we can return to it later. I think it could be quite rare in practice.

I was thinking about renaming the symbol too. We can extend the symbol naming convention we have now and deal with it in klp_resolve_symbols(), but maybe Josh will come up with something clever and cleaner.

Miroslav

#39 lore raw
Quoted 112 lines · Miroslav Benes

[...]

Quoted 22 lines

Result: a small tweak to sympos_sanity_check() to relax its symbol uniqueness verification: allow for duplicate <object, name, position> instances. Now it will only complain when a supplied symbol references the same <object, name> but a different <position>.

scripts/livepatch/klp-convert.c +4 -1
index 82c27d219372..713835dfc9ec 100644
@@ -194,7 +194,10 @@ static void clear_sympos_annontations(struct elf *klp_elf)
  	}
  }
 
-/* Checks if two or more elements in usr_symbols have the same name */
+/*
+ * Checks if two or more elements in usr_symbols have the same
+ * object and name, but different symbol position
+ */
  static bool sympos_sanity_check(void)
  {
  	bool sane = true;

scripts/livepatch/klp-convert.c static bool sympos_sanity_check(void) · line 214

Quoted 10 lines
scripts/livepatch/klp-convert.c +3 -1
@@ -203,7 +206,9 @@ static bool sympos_sanity_check(void)
  	list_for_each_entry(sp, &usr_symbols, list) {
  		aux = list_next_entry(sp, list);
  		list_for_each_entry_from(aux, &usr_symbols, list) {
-			if (strcmp(sp->symbol_name, aux->symbol_name) == 0) {
+			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);

Looks good and I'd definitely include it in v4.

Quoted 67 lines

Unique sympos
-------------

But even with the above workaround, specifying unique symbol positions will (and should) result in a klp-convert complaint.

When modifying the test module with unique symbol position annotation values (1 and 2 respectively):

   test_klp_convert_multi_objs_a.c:

     extern void *state_show;
     ...
     KLP_MODULE_RELOC(vmlinux) vmlinux_relocs_b[] = {
             KLP_SYMPOS(state_show, 1)
     };

   test_klp_convert_multi_objs_b.c:

     extern void *state_show;
     ...
     KLP_MODULE_RELOC(vmlinux) vmlinux_relocs_b[] = {
             KLP_SYMPOS(state_show, 2)
     };

Each object file's symbol table contains a "state_show" instance:

   % eu-readelf --symbols lib/livepatch/test_klp_convert_multi_objs_a.o | grep '\<state_show\>'
      30: 0000000000000000      0 NOTYPE  GLOBAL DEFAULT    UNDEF state_show

   % eu-readelf --symbols lib/livepatch/test_klp_convert_multi_objs_b.o | grep '\<state_show\>'
      20: 0000000000000000      0 NOTYPE  GLOBAL DEFAULT    UNDEF state_show

and the intermediate test_klp_convert_multi_objs.klp.o file contains a combined .klp.module_relocs.vmlinux relocation section with two KLP_SYMPOS structures, each with a unique <sympos> value:

   % objcopy -O binary --only-section=.klp.module_relocs.vmlinux \
       lib/livepatch/test_klp_convert_multi_objs.klp.o >(hexdump)
   0000000 0000 0000 0000 0000 0001 0000 0000 0000
   0000010 0000 0000 0002 0000

but the symbol tables were merged, sorted and non-unique symbols removed, leaving a *single* unresolved "state_show" instance:

   % eu-readelf --symbols lib/livepatch/test_klp_convert_multi_objs.klp.o | grep '\<state_show\>'
      53: 0000000000000000      0 NOTYPE  GLOBAL DEFAULT    UNDEF state_show

which means that even though we have separate relocations for each "state_show" instance:

   Relocation section [ 6] '.rela.text.unlikely' for section [ 5] '.text.unlikely' at offset 0x44510 contains 11 entries:
     Offset              Type            Value               Addend Name
     0x0000000000000003  X86_64_32S      000000000000000000      +0 state_show
     ...
     0x0000000000000034  X86_64_32S      000000000000000000      +0 state_show
     ...

they share the same rela->sym and there is no way to distinguish which one correlates to which KLP_SYMPOS structure.

Future Work
-----------

Quoted 7 lines

I don't see an easy way to support multiple homonym <object, name> symbols with unique <position> values in the current livepatch module Elf format. The only solutions that come to mind right now include renaming homonym symbols somehow to retain the relocation->symbol relationship when separate object files are combined. Perhaps an intermediate linker step could make annotated symbols unique in some way to achieve this. /thinking out loud

Quoted 6 lines

I'd set this aside for now and we can return to it later. I think it could be quite rare in practice.

I was thinking about renaming the symbol too. We can extend the symbol naming convention we have now and deal with it in klp_resolve_symbols(), but maybe Josh will come up with something clever and cleaner.

I think this could work well, but (sorry if I understood Joe's idea wrongly) not as a linker step. Instead of modifying the linker, I think we could create another tool and plug it into the kbuild pipeline prior to the livepatch module linking. This way, we would parse the .o elf files, check for homonyms and rename them based on a convention that is later understood by klp-convert, as suggested.

If I am not missing something, this would fix the case where we have homonyms pointing to the same or different positions, without additional user intervention other then adding the SYMPOS annotations.

If you consider this to be useful I can start experiencing.

Quoted 3 lines

Miroslav

#40 lore raw
Quoted 25 lines · Joao Moreira
Quoted 11 lines
Quoted 10 lines

Future Work
-----------

I don't see an easy way to support multiple homonym <object, name> symbols with unique <position> values in the current livepatch module Elf format. The only solutions that come to mind right now include renaming homonym symbols somehow to retain the relocation->symbol relationship when separate object files are combined. Perhaps an intermediate linker step could make annotated symbols unique in some way to achieve this. /thinking out loud

Quoted 6 lines

I'd set this aside for now and we can return to it later. I think it could be quite rare in practice.

I was thinking about renaming the symbol too. We can extend the symbol naming convention we have now and deal with it in klp_resolve_symbols(), but maybe Josh will come up with something clever and cleaner.

I think this could work well, but (sorry if I understood Joe's idea wrongly) not as a linker step. Instead of modifying the linker, I think we could create another tool and plug it into the kbuild pipeline prior to the livepatch module linking. This way, we would parse the .o elf files, check for homonyms and rename them based on a convention that is later understood by klp-convert, as suggested.

Quoted 5 lines

If I am not missing something, this would fix the case where we have homonyms pointing to the same or different positions, without additional user intervention other then adding the SYMPOS annotations.

If you consider this to be useful I can start experiencing.

I tend to agree with Miroslav that it's probably ok to ignore this issue for now, as long as klp-convert can detect it and spit out an error. I assume the patch author could work around it with a kallsyms hack. If we encounter it much in the real world then we could figure out a solution at that point.

Signature · 1 line
Josh
author maintainer
#41 lore raw
In reply to Joao Moreira
Quoted 10 lines · Joao Moreira
Quoted 10 lines
Quoted 10 lines

Future Work
-----------

I don't see an easy way to support multiple homonym <object, name> symbols with unique <position> values in the current livepatch module Elf format. The only solutions that come to mind right now include renaming homonym symbols somehow to retain the relocation->symbol relationship when separate object files are combined. Perhaps an intermediate linker step could make annotated symbols unique in some way to achieve this. /thinking out loud

Quoted 2 lines
Quoted 2 lines

I'd set this aside for now and we can return to it later. I think it could be quite rare in practice.

I agree, especially since we can detect this corner case and abort the translation.

Quoted 9 lines
Quoted 3 lines

I was thinking about renaming the symbol too. We can extend the symbol naming convention we have now and deal with it in klp_resolve_symbols(), but maybe Josh will come up with something clever and cleaner.

I think this could work well, but (sorry if I understood Joe's idea wrongly) not as a linker step. Instead of modifying the linker, I think we could create another tool and plug it into the kbuild pipeline prior to the livepatch module linking. This way, we would parse the .o elf files, check for homonyms and rename them based on a convention that is later understood by klp-convert, as suggested.

My knowledge of the build tools is limited, so there was a bunch of hand-waving you couldn't see when I wrote that paragraph :) But yes, that is basically the idea: plugging into the kbuild pipeline to give these some kinda of .o-unique prefix that klp-convert would interpret and strip accordingly.

Quoted 6 lines

If I am not missing something, this would fix the case where we have homonyms pointing to the same or different positions, without additional user intervention other then adding the SYMPOS annotations.

If you consider this to be useful I can start experiencing.

It's not the highest priority, but even a prototype of how to insert a script into the pipeline to achieve this would be massively time saving for myself. If renaming looks easy, we could try to work into the initial klp-convert patchset... if not, save it for a follow up enhancement.

Thanks,

-- Joe