2 * core.c - Kernel Live Patching Core
4 * Copyright (C) 2014 Seth Jennings <sjenning@redhat.com>
5 * Copyright (C) 2014 SUSE
7 * This program is free software; you can redistribute it and/or
8 * modify it under the terms of the GNU General Public License
9 * as published by the Free Software Foundation; either version 2
10 * of the License, or (at your option) any later version.
12 * This program is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 * GNU General Public License for more details.
17 * You should have received a copy of the GNU General Public License
18 * along with this program; if not, see <http://www.gnu.org/licenses/>.
21 #define pr_fmt(fmt) KBUILD_MODNAME ": " fmt
23 #include <linux/module.h>
24 #include <linux/kernel.h>
25 #include <linux/mutex.h>
26 #include <linux/slab.h>
27 #include <linux/list.h>
28 #include <linux/kallsyms.h>
29 #include <linux/livepatch.h>
30 #include <linux/elf.h>
31 #include <linux/moduleloader.h>
32 #include <linux/completion.h>
33 #include <linux/memory.h>
34 #include <asm/cacheflush.h>
37 #include "transition.h"
40 * klp_mutex is a coarse lock which serializes access to klp data. All
41 * accesses to klp-related variables and structures must have mutex protection,
42 * except within the following functions which carefully avoid the need for it:
44 * - klp_ftrace_handler()
45 * - klp_update_patch_state()
47 DEFINE_MUTEX(klp_mutex);
49 static LIST_HEAD(klp_patches);
51 static struct kobject *klp_root_kobj;
53 static bool klp_is_module(struct klp_object *obj)
58 /* sets obj->mod if object is not vmlinux and module is found */
59 static void klp_find_object_module(struct klp_object *obj)
63 if (!klp_is_module(obj))
66 mutex_lock(&module_mutex);
68 * We do not want to block removal of patched modules and therefore
69 * we do not take a reference here. The patches are removed by
70 * klp_module_going() instead.
72 mod = find_module(obj->name);
74 * Do not mess work of klp_module_coming() and klp_module_going().
75 * Note that the patch might still be needed before klp_module_going()
76 * is called. Module functions can be called even in the GOING state
77 * until mod->exit() finishes. This is especially important for
78 * patches that modify semantic of the functions.
80 if (mod && mod->klp_alive)
83 mutex_unlock(&module_mutex);
86 static bool klp_is_patch_registered(struct klp_patch *patch)
88 struct klp_patch *mypatch;
90 list_for_each_entry(mypatch, &klp_patches, list)
97 static bool klp_initialized(void)
99 return !!klp_root_kobj;
102 struct klp_find_arg {
110 static int klp_find_callback(void *data, const char *name,
111 struct module *mod, unsigned long addr)
113 struct klp_find_arg *args = data;
115 if ((mod && !args->objname) || (!mod && args->objname))
118 if (strcmp(args->name, name))
121 if (args->objname && strcmp(args->objname, mod->name))
128 * Finish the search when the symbol is found for the desired position
129 * or the position is not defined for a non-unique symbol.
131 if ((args->pos && (args->count == args->pos)) ||
132 (!args->pos && (args->count > 1)))
138 static int klp_find_object_symbol(const char *objname, const char *name,
139 unsigned long sympos, unsigned long *addr)
141 struct klp_find_arg args = {
149 mutex_lock(&module_mutex);
151 module_kallsyms_on_each_symbol(klp_find_callback, &args);
153 kallsyms_on_each_symbol(klp_find_callback, &args);
154 mutex_unlock(&module_mutex);
157 * Ensure an address was found. If sympos is 0, ensure symbol is unique;
158 * otherwise ensure the symbol position count matches sympos.
161 pr_err("symbol '%s' not found in symbol table\n", name);
162 else if (args.count > 1 && sympos == 0) {
163 pr_err("unresolvable ambiguity for symbol '%s' in object '%s'\n",
165 } else if (sympos != args.count && sympos > 0) {
166 pr_err("symbol position %lu for symbol '%s' in object '%s' not found\n",
167 sympos, name, objname ? objname : "vmlinux");
177 static int klp_resolve_symbols(Elf_Shdr *relasec, struct module *pmod)
179 int i, cnt, vmlinux, ret;
180 char objname[MODULE_NAME_LEN];
181 char symname[KSYM_NAME_LEN];
182 char *strtab = pmod->core_kallsyms.strtab;
185 unsigned long sympos, addr;
188 * Since the field widths for objname and symname in the sscanf()
189 * call are hard-coded and correspond to MODULE_NAME_LEN and
190 * KSYM_NAME_LEN respectively, we must make sure that MODULE_NAME_LEN
191 * and KSYM_NAME_LEN have the values we expect them to have.
193 * Because the value of MODULE_NAME_LEN can differ among architectures,
194 * we use the smallest/strictest upper bound possible (56, based on
195 * the current definition of MODULE_NAME_LEN) to prevent overflows.
197 BUILD_BUG_ON(MODULE_NAME_LEN < 56 || KSYM_NAME_LEN != 128);
199 relas = (Elf_Rela *) relasec->sh_addr;
200 /* For each rela in this klp relocation section */
201 for (i = 0; i < relasec->sh_size / sizeof(Elf_Rela); i++) {
202 sym = pmod->core_kallsyms.symtab + ELF_R_SYM(relas[i].r_info);
203 if (sym->st_shndx != SHN_LIVEPATCH) {
204 pr_err("symbol %s is not marked as a livepatch symbol\n",
205 strtab + sym->st_name);
209 /* Format: .klp.sym.objname.symname,sympos */
210 cnt = sscanf(strtab + sym->st_name,
211 ".klp.sym.%55[^.].%127[^,],%lu",
212 objname, symname, &sympos);
214 pr_err("symbol %s has an incorrectly formatted name\n",
215 strtab + sym->st_name);
219 /* klp_find_object_symbol() treats a NULL objname as vmlinux */
220 vmlinux = !strcmp(objname, "vmlinux");
221 ret = klp_find_object_symbol(vmlinux ? NULL : objname,
222 symname, sympos, &addr);
226 sym->st_value = addr;
232 static int klp_write_object_relocations(struct module *pmod,
233 struct klp_object *obj)
236 const char *objname, *secname;
237 char sec_objname[MODULE_NAME_LEN];
240 if (WARN_ON(!klp_is_object_loaded(obj)))
243 objname = klp_is_module(obj) ? obj->name : "vmlinux";
245 /* For each klp relocation section */
246 for (i = 1; i < pmod->klp_info->hdr.e_shnum; i++) {
247 sec = pmod->klp_info->sechdrs + i;
248 secname = pmod->klp_info->secstrings + sec->sh_name;
249 if (!(sec->sh_flags & SHF_RELA_LIVEPATCH))
253 * Format: .klp.rela.sec_objname.section_name
254 * See comment in klp_resolve_symbols() for an explanation
255 * of the selected field width value.
257 cnt = sscanf(secname, ".klp.rela.%55[^.]", sec_objname);
259 pr_err("section %s has an incorrectly formatted name\n",
265 if (strcmp(objname, sec_objname))
268 ret = klp_resolve_symbols(sec, pmod);
272 ret = apply_relocate_add(pmod->klp_info->sechdrs,
273 pmod->core_kallsyms.strtab,
274 pmod->klp_info->symndx, i, pmod);
282 static int __klp_disable_patch(struct klp_patch *patch)
284 struct klp_object *obj;
286 if (WARN_ON(!patch->enabled))
289 if (klp_transition_patch)
292 /* enforce stacking: only the last enabled patch can be disabled */
293 if (!list_is_last(&patch->list, &klp_patches) &&
294 list_next_entry(patch, list)->enabled)
297 klp_init_transition(patch, KLP_UNPATCHED);
299 klp_for_each_object(patch, obj)
301 klp_pre_unpatch_callback(obj);
304 * Enforce the order of the func->transition writes in
305 * klp_init_transition() and the TIF_PATCH_PENDING writes in
306 * klp_start_transition(). In the rare case where klp_ftrace_handler()
307 * is called shortly after klp_update_patch_state() switches the task,
308 * this ensures the handler sees that func->transition is set.
312 klp_start_transition();
313 klp_try_complete_transition();
314 patch->enabled = false;
320 * klp_disable_patch() - disables a registered patch
321 * @patch: The registered, enabled patch to be disabled
323 * Unregisters the patched functions from ftrace.
325 * Return: 0 on success, otherwise error
327 int klp_disable_patch(struct klp_patch *patch)
331 mutex_lock(&klp_mutex);
333 if (!klp_is_patch_registered(patch)) {
338 if (!patch->enabled) {
343 ret = __klp_disable_patch(patch);
346 mutex_unlock(&klp_mutex);
349 EXPORT_SYMBOL_GPL(klp_disable_patch);
351 static int __klp_enable_patch(struct klp_patch *patch)
353 struct klp_object *obj;
356 if (klp_transition_patch)
359 if (WARN_ON(patch->enabled))
362 /* enforce stacking: only the first disabled patch can be enabled */
363 if (patch->list.prev != &klp_patches &&
364 !list_prev_entry(patch, list)->enabled)
368 * A reference is taken on the patch module to prevent it from being
371 if (!try_module_get(patch->mod))
374 pr_notice("enabling patch '%s'\n", patch->mod->name);
376 klp_init_transition(patch, KLP_PATCHED);
379 * Enforce the order of the func->transition writes in
380 * klp_init_transition() and the ops->func_stack writes in
381 * klp_patch_object(), so that klp_ftrace_handler() will see the
382 * func->transition updates before the handler is registered and the
383 * new funcs become visible to the handler.
387 klp_for_each_object(patch, obj) {
388 if (!klp_is_object_loaded(obj))
391 ret = klp_pre_patch_callback(obj);
393 pr_warn("pre-patch callback failed for object '%s'\n",
394 klp_is_module(obj) ? obj->name : "vmlinux");
398 ret = klp_patch_object(obj);
400 pr_warn("failed to patch object '%s'\n",
401 klp_is_module(obj) ? obj->name : "vmlinux");
406 klp_start_transition();
407 klp_try_complete_transition();
408 patch->enabled = true;
412 pr_warn("failed to enable patch '%s'\n", patch->mod->name);
414 klp_cancel_transition();
419 * klp_enable_patch() - enables a registered patch
420 * @patch: The registered, disabled patch to be enabled
422 * Performs the needed symbol lookups and code relocations,
423 * then registers the patched functions with ftrace.
425 * Return: 0 on success, otherwise error
427 int klp_enable_patch(struct klp_patch *patch)
431 mutex_lock(&klp_mutex);
433 if (!klp_is_patch_registered(patch)) {
438 ret = __klp_enable_patch(patch);
441 mutex_unlock(&klp_mutex);
444 EXPORT_SYMBOL_GPL(klp_enable_patch);
449 * /sys/kernel/livepatch
450 * /sys/kernel/livepatch/<patch>
451 * /sys/kernel/livepatch/<patch>/enabled
452 * /sys/kernel/livepatch/<patch>/transition
453 * /sys/kernel/livepatch/<patch>/signal
454 * /sys/kernel/livepatch/<patch>/force
455 * /sys/kernel/livepatch/<patch>/<object>
456 * /sys/kernel/livepatch/<patch>/<object>/<function,sympos>
459 static ssize_t enabled_store(struct kobject *kobj, struct kobj_attribute *attr,
460 const char *buf, size_t count)
462 struct klp_patch *patch;
466 ret = kstrtobool(buf, &enabled);
470 patch = container_of(kobj, struct klp_patch, kobj);
472 mutex_lock(&klp_mutex);
474 if (!klp_is_patch_registered(patch)) {
476 * Module with the patch could either disappear meanwhile or is
477 * not properly initialized yet.
483 if (patch->enabled == enabled) {
484 /* already in requested state */
489 if (patch == klp_transition_patch) {
490 klp_reverse_transition();
491 } else if (enabled) {
492 ret = __klp_enable_patch(patch);
496 ret = __klp_disable_patch(patch);
501 mutex_unlock(&klp_mutex);
506 mutex_unlock(&klp_mutex);
510 static ssize_t enabled_show(struct kobject *kobj,
511 struct kobj_attribute *attr, char *buf)
513 struct klp_patch *patch;
515 patch = container_of(kobj, struct klp_patch, kobj);
516 return snprintf(buf, PAGE_SIZE-1, "%d\n", patch->enabled);
519 static ssize_t transition_show(struct kobject *kobj,
520 struct kobj_attribute *attr, char *buf)
522 struct klp_patch *patch;
524 patch = container_of(kobj, struct klp_patch, kobj);
525 return snprintf(buf, PAGE_SIZE-1, "%d\n",
526 patch == klp_transition_patch);
529 static ssize_t signal_store(struct kobject *kobj, struct kobj_attribute *attr,
530 const char *buf, size_t count)
532 struct klp_patch *patch;
536 ret = kstrtobool(buf, &val);
543 mutex_lock(&klp_mutex);
545 patch = container_of(kobj, struct klp_patch, kobj);
546 if (patch != klp_transition_patch) {
547 mutex_unlock(&klp_mutex);
553 mutex_unlock(&klp_mutex);
558 static ssize_t force_store(struct kobject *kobj, struct kobj_attribute *attr,
559 const char *buf, size_t count)
561 struct klp_patch *patch;
565 ret = kstrtobool(buf, &val);
572 mutex_lock(&klp_mutex);
574 patch = container_of(kobj, struct klp_patch, kobj);
575 if (patch != klp_transition_patch) {
576 mutex_unlock(&klp_mutex);
580 klp_force_transition();
582 mutex_unlock(&klp_mutex);
587 static struct kobj_attribute enabled_kobj_attr = __ATTR_RW(enabled);
588 static struct kobj_attribute transition_kobj_attr = __ATTR_RO(transition);
589 static struct kobj_attribute signal_kobj_attr = __ATTR_WO(signal);
590 static struct kobj_attribute force_kobj_attr = __ATTR_WO(force);
591 static struct attribute *klp_patch_attrs[] = {
592 &enabled_kobj_attr.attr,
593 &transition_kobj_attr.attr,
594 &signal_kobj_attr.attr,
595 &force_kobj_attr.attr,
599 static void klp_kobj_release_patch(struct kobject *kobj)
601 struct klp_patch *patch;
603 patch = container_of(kobj, struct klp_patch, kobj);
604 complete(&patch->finish);
607 static struct kobj_type klp_ktype_patch = {
608 .release = klp_kobj_release_patch,
609 .sysfs_ops = &kobj_sysfs_ops,
610 .default_attrs = klp_patch_attrs,
613 static void klp_kobj_release_object(struct kobject *kobj)
617 static struct kobj_type klp_ktype_object = {
618 .release = klp_kobj_release_object,
619 .sysfs_ops = &kobj_sysfs_ops,
622 static void klp_kobj_release_func(struct kobject *kobj)
626 static struct kobj_type klp_ktype_func = {
627 .release = klp_kobj_release_func,
628 .sysfs_ops = &kobj_sysfs_ops,
632 * Free all functions' kobjects in the array up to some limit. When limit is
633 * NULL, all kobjects are freed.
635 static void klp_free_funcs_limited(struct klp_object *obj,
636 struct klp_func *limit)
638 struct klp_func *func;
640 for (func = obj->funcs; func->old_name && func != limit; func++)
641 kobject_put(&func->kobj);
644 /* Clean up when a patched object is unloaded */
645 static void klp_free_object_loaded(struct klp_object *obj)
647 struct klp_func *func;
651 klp_for_each_func(obj, func)
656 * Free all objects' kobjects in the array up to some limit. When limit is
657 * NULL, all kobjects are freed.
659 static void klp_free_objects_limited(struct klp_patch *patch,
660 struct klp_object *limit)
662 struct klp_object *obj;
664 for (obj = patch->objs; obj->funcs && obj != limit; obj++) {
665 klp_free_funcs_limited(obj, NULL);
666 kobject_put(&obj->kobj);
670 static void klp_free_patch(struct klp_patch *patch)
672 klp_free_objects_limited(patch, NULL);
673 if (!list_empty(&patch->list))
674 list_del(&patch->list);
677 static int klp_init_func(struct klp_object *obj, struct klp_func *func)
679 if (!func->old_name || !func->new_func)
682 if (strlen(func->old_name) >= KSYM_NAME_LEN)
685 INIT_LIST_HEAD(&func->stack_node);
686 func->patched = false;
687 func->transition = false;
689 /* The format for the sysfs directory is <function,sympos> where sympos
690 * is the nth occurrence of this symbol in kallsyms for the patched
691 * object. If the user selects 0 for old_sympos, then 1 will be used
692 * since a unique symbol will be the first occurrence.
694 return kobject_init_and_add(&func->kobj, &klp_ktype_func,
695 &obj->kobj, "%s,%lu", func->old_name,
696 func->old_sympos ? func->old_sympos : 1);
699 /* Arches may override this to finish any remaining arch-specific tasks */
700 void __weak arch_klp_init_object_loaded(struct klp_patch *patch,
701 struct klp_object *obj)
705 /* parts of the initialization that is done only when the object is loaded */
706 static int klp_init_object_loaded(struct klp_patch *patch,
707 struct klp_object *obj)
709 struct klp_func *func;
712 mutex_lock(&text_mutex);
714 module_disable_ro(patch->mod);
715 ret = klp_write_object_relocations(patch->mod, obj);
717 module_enable_ro(patch->mod, true);
718 mutex_unlock(&text_mutex);
722 arch_klp_init_object_loaded(patch, obj);
723 module_enable_ro(patch->mod, true);
725 mutex_unlock(&text_mutex);
727 klp_for_each_func(obj, func) {
728 ret = klp_find_object_symbol(obj->name, func->old_name,
734 ret = kallsyms_lookup_size_offset(func->old_addr,
735 &func->old_size, NULL);
737 pr_err("kallsyms size lookup failed for '%s'\n",
742 ret = kallsyms_lookup_size_offset((unsigned long)func->new_func,
743 &func->new_size, NULL);
745 pr_err("kallsyms size lookup failed for '%s' replacement\n",
754 static int klp_init_object(struct klp_patch *patch, struct klp_object *obj)
756 struct klp_func *func;
763 if (klp_is_module(obj) && strlen(obj->name) >= MODULE_NAME_LEN)
766 obj->patched = false;
769 klp_find_object_module(obj);
771 name = klp_is_module(obj) ? obj->name : "vmlinux";
772 ret = kobject_init_and_add(&obj->kobj, &klp_ktype_object,
773 &patch->kobj, "%s", name);
777 klp_for_each_func(obj, func) {
778 ret = klp_init_func(obj, func);
783 if (klp_is_object_loaded(obj)) {
784 ret = klp_init_object_loaded(patch, obj);
792 klp_free_funcs_limited(obj, func);
793 kobject_put(&obj->kobj);
797 static int klp_init_patch(struct klp_patch *patch)
799 struct klp_object *obj;
805 mutex_lock(&klp_mutex);
807 patch->enabled = false;
808 init_completion(&patch->finish);
810 ret = kobject_init_and_add(&patch->kobj, &klp_ktype_patch,
811 klp_root_kobj, "%s", patch->mod->name);
813 mutex_unlock(&klp_mutex);
817 klp_for_each_object(patch, obj) {
818 ret = klp_init_object(patch, obj);
823 list_add_tail(&patch->list, &klp_patches);
825 mutex_unlock(&klp_mutex);
830 klp_free_objects_limited(patch, obj);
832 mutex_unlock(&klp_mutex);
834 kobject_put(&patch->kobj);
835 wait_for_completion(&patch->finish);
841 * klp_unregister_patch() - unregisters a patch
842 * @patch: Disabled patch to be unregistered
844 * Frees the data structures and removes the sysfs interface.
846 * Return: 0 on success, otherwise error
848 int klp_unregister_patch(struct klp_patch *patch)
852 mutex_lock(&klp_mutex);
854 if (!klp_is_patch_registered(patch)) {
859 if (patch->enabled) {
864 klp_free_patch(patch);
866 mutex_unlock(&klp_mutex);
868 kobject_put(&patch->kobj);
869 wait_for_completion(&patch->finish);
873 mutex_unlock(&klp_mutex);
876 EXPORT_SYMBOL_GPL(klp_unregister_patch);
879 * klp_register_patch() - registers a patch
880 * @patch: Patch to be registered
882 * Initializes the data structure associated with the patch and
883 * creates the sysfs interface.
885 * There is no need to take the reference on the patch module here. It is done
886 * later when the patch is enabled.
888 * Return: 0 on success, otherwise error
890 int klp_register_patch(struct klp_patch *patch)
892 if (!patch || !patch->mod)
895 if (!is_livepatch_module(patch->mod)) {
896 pr_err("module %s is not marked as a livepatch module\n",
901 if (!klp_initialized())
904 if (!klp_have_reliable_stack()) {
905 pr_err("This architecture doesn't have support for the livepatch consistency model.\n");
909 return klp_init_patch(patch);
911 EXPORT_SYMBOL_GPL(klp_register_patch);
914 * Remove parts of patches that touch a given kernel module. The list of
915 * patches processed might be limited. When limit is NULL, all patches
918 static void klp_cleanup_module_patches_limited(struct module *mod,
919 struct klp_patch *limit)
921 struct klp_patch *patch;
922 struct klp_object *obj;
924 list_for_each_entry(patch, &klp_patches, list) {
928 klp_for_each_object(patch, obj) {
929 if (!klp_is_module(obj) || strcmp(obj->name, mod->name))
933 * Only unpatch the module if the patch is enabled or
936 if (patch->enabled || patch == klp_transition_patch) {
938 if (patch != klp_transition_patch)
939 klp_pre_unpatch_callback(obj);
941 pr_notice("reverting patch '%s' on unloading module '%s'\n",
942 patch->mod->name, obj->mod->name);
943 klp_unpatch_object(obj);
945 klp_post_unpatch_callback(obj);
948 klp_free_object_loaded(obj);
954 int klp_module_coming(struct module *mod)
957 struct klp_patch *patch;
958 struct klp_object *obj;
960 if (WARN_ON(mod->state != MODULE_STATE_COMING))
963 mutex_lock(&klp_mutex);
965 * Each module has to know that klp_module_coming()
966 * has been called. We never know what module will
967 * get patched by a new patch.
969 mod->klp_alive = true;
971 list_for_each_entry(patch, &klp_patches, list) {
972 klp_for_each_object(patch, obj) {
973 if (!klp_is_module(obj) || strcmp(obj->name, mod->name))
978 ret = klp_init_object_loaded(patch, obj);
980 pr_warn("failed to initialize patch '%s' for module '%s' (%d)\n",
981 patch->mod->name, obj->mod->name, ret);
986 * Only patch the module if the patch is enabled or is
989 if (!patch->enabled && patch != klp_transition_patch)
992 pr_notice("applying patch '%s' to loading module '%s'\n",
993 patch->mod->name, obj->mod->name);
995 ret = klp_pre_patch_callback(obj);
997 pr_warn("pre-patch callback failed for object '%s'\n",
1002 ret = klp_patch_object(obj);
1004 pr_warn("failed to apply patch '%s' to module '%s' (%d)\n",
1005 patch->mod->name, obj->mod->name, ret);
1007 klp_post_unpatch_callback(obj);
1011 if (patch != klp_transition_patch)
1012 klp_post_patch_callback(obj);
1018 mutex_unlock(&klp_mutex);
1024 * If a patch is unsuccessfully applied, return
1025 * error to the module loader.
1027 pr_warn("patch '%s' failed for module '%s', refusing to load module '%s'\n",
1028 patch->mod->name, obj->mod->name, obj->mod->name);
1029 mod->klp_alive = false;
1031 klp_cleanup_module_patches_limited(mod, patch);
1032 mutex_unlock(&klp_mutex);
1037 void klp_module_going(struct module *mod)
1039 if (WARN_ON(mod->state != MODULE_STATE_GOING &&
1040 mod->state != MODULE_STATE_COMING))
1043 mutex_lock(&klp_mutex);
1045 * Each module has to know that klp_module_going()
1046 * has been called. We never know what module will
1047 * get patched by a new patch.
1049 mod->klp_alive = false;
1051 klp_cleanup_module_patches_limited(mod, NULL);
1053 mutex_unlock(&klp_mutex);
1056 static int __init klp_init(void)
1060 ret = klp_check_compiler_support();
1062 pr_info("Your compiler is too old; turning off.\n");
1066 klp_root_kobj = kobject_create_and_add("livepatch", kernel_kobj);
1073 module_init(klp_init);