1 // SPDX-License-Identifier: GPL-2.0-or-later
3 * Copyright (C) 2002 Richard Henderson
4 * Copyright (C) 2001 Rusty Russell, 2002, 2010 Rusty Russell IBM.
7 #define INCLUDE_VERMAGIC
9 #include <linux/export.h>
10 #include <linux/extable.h>
11 #include <linux/moduleloader.h>
12 #include <linux/module_signature.h>
13 #include <linux/trace_events.h>
14 #include <linux/init.h>
15 #include <linux/kallsyms.h>
16 #include <linux/file.h>
18 #include <linux/sysfs.h>
19 #include <linux/kernel.h>
20 #include <linux/kernel_read_file.h>
21 #include <linux/slab.h>
22 #include <linux/vmalloc.h>
23 #include <linux/elf.h>
24 #include <linux/proc_fs.h>
25 #include <linux/security.h>
26 #include <linux/seq_file.h>
27 #include <linux/syscalls.h>
28 #include <linux/fcntl.h>
29 #include <linux/rcupdate.h>
30 #include <linux/capability.h>
31 #include <linux/cpu.h>
32 #include <linux/moduleparam.h>
33 #include <linux/errno.h>
34 #include <linux/err.h>
35 #include <linux/vermagic.h>
36 #include <linux/notifier.h>
37 #include <linux/sched.h>
38 #include <linux/device.h>
39 #include <linux/string.h>
40 #include <linux/mutex.h>
41 #include <linux/rculist.h>
42 #include <linux/uaccess.h>
43 #include <asm/cacheflush.h>
44 #include <linux/set_memory.h>
45 #include <asm/mmu_context.h>
46 #include <linux/license.h>
47 #include <asm/sections.h>
48 #include <linux/tracepoint.h>
49 #include <linux/ftrace.h>
50 #include <linux/livepatch.h>
51 #include <linux/async.h>
52 #include <linux/percpu.h>
53 #include <linux/kmemleak.h>
54 #include <linux/jump_label.h>
55 #include <linux/pfn.h>
56 #include <linux/bsearch.h>
57 #include <linux/dynamic_debug.h>
58 #include <linux/audit.h>
59 #include <uapi/linux/module.h>
60 #include "module-internal.h"
62 #define CREATE_TRACE_POINTS
63 #include <trace/events/module.h>
65 #ifndef ARCH_SHF_SMALL
66 #define ARCH_SHF_SMALL 0
70 * Modules' sections will be aligned on page boundaries
71 * to ensure complete separation of code and data, but
72 * only when CONFIG_ARCH_HAS_STRICT_MODULE_RWX=y
74 #ifdef CONFIG_ARCH_HAS_STRICT_MODULE_RWX
75 # define debug_align(X) ALIGN(X, PAGE_SIZE)
77 # define debug_align(X) (X)
80 /* If this is set, the section belongs in the init part of the module */
81 #define INIT_OFFSET_MASK (1UL << (BITS_PER_LONG-1))
85 * 1) List of modules (also safely readable with preempt_disable),
86 * 2) module_use links,
87 * 3) module_addr_min/module_addr_max.
88 * (delete and add uses RCU list operations).
90 static DEFINE_MUTEX(module_mutex);
91 static LIST_HEAD(modules);
93 /* Work queue for freeing init sections in success case */
94 static void do_free_init(struct work_struct *w);
95 static DECLARE_WORK(init_free_wq, do_free_init);
96 static LLIST_HEAD(init_free_list);
98 #ifdef CONFIG_MODULES_TREE_LOOKUP
101 * Use a latched RB-tree for __module_address(); this allows us to use
102 * RCU-sched lookups of the address from any context.
104 * This is conditional on PERF_EVENTS || TRACING because those can really hit
105 * __module_address() hard by doing a lot of stack unwinding; potentially from
109 static __always_inline unsigned long __mod_tree_val(struct latch_tree_node *n)
111 struct module_layout *layout = container_of(n, struct module_layout, mtn.node);
113 return (unsigned long)layout->base;
116 static __always_inline unsigned long __mod_tree_size(struct latch_tree_node *n)
118 struct module_layout *layout = container_of(n, struct module_layout, mtn.node);
120 return (unsigned long)layout->size;
123 static __always_inline bool
124 mod_tree_less(struct latch_tree_node *a, struct latch_tree_node *b)
126 return __mod_tree_val(a) < __mod_tree_val(b);
129 static __always_inline int
130 mod_tree_comp(void *key, struct latch_tree_node *n)
132 unsigned long val = (unsigned long)key;
133 unsigned long start, end;
135 start = __mod_tree_val(n);
139 end = start + __mod_tree_size(n);
146 static const struct latch_tree_ops mod_tree_ops = {
147 .less = mod_tree_less,
148 .comp = mod_tree_comp,
151 static struct mod_tree_root {
152 struct latch_tree_root root;
153 unsigned long addr_min;
154 unsigned long addr_max;
155 } mod_tree __cacheline_aligned = {
159 #define module_addr_min mod_tree.addr_min
160 #define module_addr_max mod_tree.addr_max
162 static noinline void __mod_tree_insert(struct mod_tree_node *node)
164 latch_tree_insert(&node->node, &mod_tree.root, &mod_tree_ops);
167 static void __mod_tree_remove(struct mod_tree_node *node)
169 latch_tree_erase(&node->node, &mod_tree.root, &mod_tree_ops);
173 * These modifications: insert, remove_init and remove; are serialized by the
176 static void mod_tree_insert(struct module *mod)
178 mod->core_layout.mtn.mod = mod;
179 mod->init_layout.mtn.mod = mod;
181 __mod_tree_insert(&mod->core_layout.mtn);
182 if (mod->init_layout.size)
183 __mod_tree_insert(&mod->init_layout.mtn);
186 static void mod_tree_remove_init(struct module *mod)
188 if (mod->init_layout.size)
189 __mod_tree_remove(&mod->init_layout.mtn);
192 static void mod_tree_remove(struct module *mod)
194 __mod_tree_remove(&mod->core_layout.mtn);
195 mod_tree_remove_init(mod);
198 static struct module *mod_find(unsigned long addr)
200 struct latch_tree_node *ltn;
202 ltn = latch_tree_find((void *)addr, &mod_tree.root, &mod_tree_ops);
206 return container_of(ltn, struct mod_tree_node, node)->mod;
209 #else /* MODULES_TREE_LOOKUP */
211 static unsigned long module_addr_min = -1UL, module_addr_max = 0;
213 static void mod_tree_insert(struct module *mod) { }
214 static void mod_tree_remove_init(struct module *mod) { }
215 static void mod_tree_remove(struct module *mod) { }
217 static struct module *mod_find(unsigned long addr)
221 list_for_each_entry_rcu(mod, &modules, list,
222 lockdep_is_held(&module_mutex)) {
223 if (within_module(addr, mod))
230 #endif /* MODULES_TREE_LOOKUP */
233 * Bounds of module text, for speeding up __module_address.
234 * Protected by module_mutex.
236 static void __mod_update_bounds(void *base, unsigned int size)
238 unsigned long min = (unsigned long)base;
239 unsigned long max = min + size;
241 if (min < module_addr_min)
242 module_addr_min = min;
243 if (max > module_addr_max)
244 module_addr_max = max;
247 static void mod_update_bounds(struct module *mod)
249 __mod_update_bounds(mod->core_layout.base, mod->core_layout.size);
250 if (mod->init_layout.size)
251 __mod_update_bounds(mod->init_layout.base, mod->init_layout.size);
254 #ifdef CONFIG_KGDB_KDB
255 struct list_head *kdb_modules = &modules; /* kdb needs the list of modules */
256 #endif /* CONFIG_KGDB_KDB */
258 static void module_assert_mutex_or_preempt(void)
260 #ifdef CONFIG_LOCKDEP
261 if (unlikely(!debug_locks))
264 WARN_ON_ONCE(!rcu_read_lock_sched_held() &&
265 !lockdep_is_held(&module_mutex));
269 static bool sig_enforce = IS_ENABLED(CONFIG_MODULE_SIG_FORCE);
270 module_param(sig_enforce, bool_enable_only, 0644);
273 * Export sig_enforce kernel cmdline parameter to allow other subsystems rely
274 * on that instead of directly to CONFIG_MODULE_SIG_FORCE config.
276 bool is_module_sig_enforced(void)
280 EXPORT_SYMBOL(is_module_sig_enforced);
282 void set_module_sig_enforced(void)
287 /* Block module loading/unloading? */
288 int modules_disabled = 0;
289 core_param(nomodule, modules_disabled, bint, 0);
291 /* Waiting for a module to finish initializing? */
292 static DECLARE_WAIT_QUEUE_HEAD(module_wq);
294 static BLOCKING_NOTIFIER_HEAD(module_notify_list);
296 int register_module_notifier(struct notifier_block *nb)
298 return blocking_notifier_chain_register(&module_notify_list, nb);
300 EXPORT_SYMBOL(register_module_notifier);
302 int unregister_module_notifier(struct notifier_block *nb)
304 return blocking_notifier_chain_unregister(&module_notify_list, nb);
306 EXPORT_SYMBOL(unregister_module_notifier);
309 * We require a truly strong try_module_get(): 0 means success.
310 * Otherwise an error is returned due to ongoing or failed
311 * initialization etc.
313 static inline int strong_try_module_get(struct module *mod)
315 BUG_ON(mod && mod->state == MODULE_STATE_UNFORMED);
316 if (mod && mod->state == MODULE_STATE_COMING)
318 if (try_module_get(mod))
324 static inline void add_taint_module(struct module *mod, unsigned flag,
325 enum lockdep_ok lockdep_ok)
327 add_taint(flag, lockdep_ok);
328 set_bit(flag, &mod->taints);
332 * A thread that wants to hold a reference to a module only while it
333 * is running can call this to safely exit. nfsd and lockd use this.
335 void __noreturn __module_put_and_exit(struct module *mod, long code)
340 EXPORT_SYMBOL(__module_put_and_exit);
342 /* Find a module section: 0 means not found. */
343 static unsigned int find_sec(const struct load_info *info, const char *name)
347 for (i = 1; i < info->hdr->e_shnum; i++) {
348 Elf_Shdr *shdr = &info->sechdrs[i];
349 /* Alloc bit cleared means "ignore it." */
350 if ((shdr->sh_flags & SHF_ALLOC)
351 && strcmp(info->secstrings + shdr->sh_name, name) == 0)
357 /* Find a module section, or NULL. */
358 static void *section_addr(const struct load_info *info, const char *name)
360 /* Section 0 has sh_addr 0. */
361 return (void *)info->sechdrs[find_sec(info, name)].sh_addr;
364 /* Find a module section, or NULL. Fill in number of "objects" in section. */
365 static void *section_objs(const struct load_info *info,
370 unsigned int sec = find_sec(info, name);
372 /* Section 0 has sh_addr 0 and sh_size 0. */
373 *num = info->sechdrs[sec].sh_size / object_size;
374 return (void *)info->sechdrs[sec].sh_addr;
377 /* Find a module section: 0 means not found. Ignores SHF_ALLOC flag. */
378 static unsigned int find_any_sec(const struct load_info *info, const char *name)
382 for (i = 1; i < info->hdr->e_shnum; i++) {
383 Elf_Shdr *shdr = &info->sechdrs[i];
384 if (strcmp(info->secstrings + shdr->sh_name, name) == 0)
391 * Find a module section, or NULL. Fill in number of "objects" in section.
392 * Ignores SHF_ALLOC flag.
394 static __maybe_unused void *any_section_objs(const struct load_info *info,
399 unsigned int sec = find_any_sec(info, name);
401 /* Section 0 has sh_addr 0 and sh_size 0. */
402 *num = info->sechdrs[sec].sh_size / object_size;
403 return (void *)info->sechdrs[sec].sh_addr;
406 /* Provided by the linker */
407 extern const struct kernel_symbol __start___ksymtab[];
408 extern const struct kernel_symbol __stop___ksymtab[];
409 extern const struct kernel_symbol __start___ksymtab_gpl[];
410 extern const struct kernel_symbol __stop___ksymtab_gpl[];
411 extern const s32 __start___kcrctab[];
412 extern const s32 __start___kcrctab_gpl[];
413 #ifdef CONFIG_UNUSED_SYMBOLS
414 extern const struct kernel_symbol __start___ksymtab_unused[];
415 extern const struct kernel_symbol __stop___ksymtab_unused[];
416 extern const struct kernel_symbol __start___ksymtab_unused_gpl[];
417 extern const struct kernel_symbol __stop___ksymtab_unused_gpl[];
418 extern const s32 __start___kcrctab_unused[];
419 extern const s32 __start___kcrctab_unused_gpl[];
422 #ifndef CONFIG_MODVERSIONS
423 #define symversion(base, idx) NULL
425 #define symversion(base, idx) ((base != NULL) ? ((base) + (idx)) : NULL)
429 const struct kernel_symbol *start, *stop;
438 struct find_symbol_arg {
445 struct module *owner;
447 const struct kernel_symbol *sym;
448 enum mod_license license;
451 static bool check_exported_symbol(const struct symsearch *syms,
452 struct module *owner,
453 unsigned int symnum, void *data)
455 struct find_symbol_arg *fsa = data;
457 if (!fsa->gplok && syms->license == GPL_ONLY)
460 #ifdef CONFIG_UNUSED_SYMBOLS
461 if (syms->unused && fsa->warn) {
462 pr_warn("Symbol %s is marked as UNUSED, however this module is "
463 "using it.\n", fsa->name);
464 pr_warn("This symbol will go away in the future.\n");
465 pr_warn("Please evaluate if this is the right api to use and "
466 "if it really is, submit a report to the linux kernel "
467 "mailing list together with submitting your code for "
473 fsa->crc = symversion(syms->crcs, symnum);
474 fsa->sym = &syms->start[symnum];
475 fsa->license = syms->license;
479 static unsigned long kernel_symbol_value(const struct kernel_symbol *sym)
481 #ifdef CONFIG_HAVE_ARCH_PREL32_RELOCATIONS
482 return (unsigned long)offset_to_ptr(&sym->value_offset);
488 static const char *kernel_symbol_name(const struct kernel_symbol *sym)
490 #ifdef CONFIG_HAVE_ARCH_PREL32_RELOCATIONS
491 return offset_to_ptr(&sym->name_offset);
497 static const char *kernel_symbol_namespace(const struct kernel_symbol *sym)
499 #ifdef CONFIG_HAVE_ARCH_PREL32_RELOCATIONS
500 if (!sym->namespace_offset)
502 return offset_to_ptr(&sym->namespace_offset);
504 return sym->namespace;
508 static int cmp_name(const void *name, const void *sym)
510 return strcmp(name, kernel_symbol_name(sym));
513 static bool find_exported_symbol_in_section(const struct symsearch *syms,
514 struct module *owner,
517 struct find_symbol_arg *fsa = data;
518 struct kernel_symbol *sym;
520 sym = bsearch(fsa->name, syms->start, syms->stop - syms->start,
521 sizeof(struct kernel_symbol), cmp_name);
523 if (sym != NULL && check_exported_symbol(syms, owner,
524 sym - syms->start, data))
531 * Find an exported symbol and return it, along with, (optional) crc and
532 * (optional) module which owns it. Needs preempt disabled or module_mutex.
534 static bool find_symbol(struct find_symbol_arg *fsa)
536 static const struct symsearch arr[] = {
537 { __start___ksymtab, __stop___ksymtab, __start___kcrctab,
538 NOT_GPL_ONLY, false },
539 { __start___ksymtab_gpl, __stop___ksymtab_gpl,
540 __start___kcrctab_gpl,
542 #ifdef CONFIG_UNUSED_SYMBOLS
543 { __start___ksymtab_unused, __stop___ksymtab_unused,
544 __start___kcrctab_unused,
545 NOT_GPL_ONLY, true },
546 { __start___ksymtab_unused_gpl, __stop___ksymtab_unused_gpl,
547 __start___kcrctab_unused_gpl,
554 module_assert_mutex_or_preempt();
556 for (i = 0; i < ARRAY_SIZE(arr); i++)
557 if (find_exported_symbol_in_section(&arr[i], NULL, fsa))
560 list_for_each_entry_rcu(mod, &modules, list,
561 lockdep_is_held(&module_mutex)) {
562 struct symsearch arr[] = {
563 { mod->syms, mod->syms + mod->num_syms, mod->crcs,
564 NOT_GPL_ONLY, false },
565 { mod->gpl_syms, mod->gpl_syms + mod->num_gpl_syms,
568 #ifdef CONFIG_UNUSED_SYMBOLS
570 mod->unused_syms + mod->num_unused_syms,
572 NOT_GPL_ONLY, true },
573 { mod->unused_gpl_syms,
574 mod->unused_gpl_syms + mod->num_unused_gpl_syms,
575 mod->unused_gpl_crcs,
580 if (mod->state == MODULE_STATE_UNFORMED)
583 for (i = 0; i < ARRAY_SIZE(arr); i++)
584 if (find_exported_symbol_in_section(&arr[i], mod, fsa))
588 pr_debug("Failed to find symbol %s\n", fsa->name);
593 * Search for module by name: must hold module_mutex (or preempt disabled
594 * for read-only access).
596 static struct module *find_module_all(const char *name, size_t len,
601 module_assert_mutex_or_preempt();
603 list_for_each_entry_rcu(mod, &modules, list,
604 lockdep_is_held(&module_mutex)) {
605 if (!even_unformed && mod->state == MODULE_STATE_UNFORMED)
607 if (strlen(mod->name) == len && !memcmp(mod->name, name, len))
613 struct module *find_module(const char *name)
615 return find_module_all(name, strlen(name), false);
620 static inline void __percpu *mod_percpu(struct module *mod)
625 static int percpu_modalloc(struct module *mod, struct load_info *info)
627 Elf_Shdr *pcpusec = &info->sechdrs[info->index.pcpu];
628 unsigned long align = pcpusec->sh_addralign;
630 if (!pcpusec->sh_size)
633 if (align > PAGE_SIZE) {
634 pr_warn("%s: per-cpu alignment %li > %li\n",
635 mod->name, align, PAGE_SIZE);
639 mod->percpu = __alloc_reserved_percpu(pcpusec->sh_size, align);
641 pr_warn("%s: Could not allocate %lu bytes percpu data\n",
642 mod->name, (unsigned long)pcpusec->sh_size);
645 mod->percpu_size = pcpusec->sh_size;
649 static void percpu_modfree(struct module *mod)
651 free_percpu(mod->percpu);
654 static unsigned int find_pcpusec(struct load_info *info)
656 return find_sec(info, ".data..percpu");
659 static void percpu_modcopy(struct module *mod,
660 const void *from, unsigned long size)
664 for_each_possible_cpu(cpu)
665 memcpy(per_cpu_ptr(mod->percpu, cpu), from, size);
668 bool __is_module_percpu_address(unsigned long addr, unsigned long *can_addr)
675 list_for_each_entry_rcu(mod, &modules, list) {
676 if (mod->state == MODULE_STATE_UNFORMED)
678 if (!mod->percpu_size)
680 for_each_possible_cpu(cpu) {
681 void *start = per_cpu_ptr(mod->percpu, cpu);
682 void *va = (void *)addr;
684 if (va >= start && va < start + mod->percpu_size) {
686 *can_addr = (unsigned long) (va - start);
687 *can_addr += (unsigned long)
688 per_cpu_ptr(mod->percpu,
702 * is_module_percpu_address() - test whether address is from module static percpu
703 * @addr: address to test
705 * Test whether @addr belongs to module static percpu area.
707 * Return: %true if @addr is from module static percpu area
709 bool is_module_percpu_address(unsigned long addr)
711 return __is_module_percpu_address(addr, NULL);
714 #else /* ... !CONFIG_SMP */
716 static inline void __percpu *mod_percpu(struct module *mod)
720 static int percpu_modalloc(struct module *mod, struct load_info *info)
722 /* UP modules shouldn't have this section: ENOMEM isn't quite right */
723 if (info->sechdrs[info->index.pcpu].sh_size != 0)
727 static inline void percpu_modfree(struct module *mod)
730 static unsigned int find_pcpusec(struct load_info *info)
734 static inline void percpu_modcopy(struct module *mod,
735 const void *from, unsigned long size)
737 /* pcpusec should be 0, and size of that section should be 0. */
740 bool is_module_percpu_address(unsigned long addr)
745 bool __is_module_percpu_address(unsigned long addr, unsigned long *can_addr)
750 #endif /* CONFIG_SMP */
752 #define MODINFO_ATTR(field) \
753 static void setup_modinfo_##field(struct module *mod, const char *s) \
755 mod->field = kstrdup(s, GFP_KERNEL); \
757 static ssize_t show_modinfo_##field(struct module_attribute *mattr, \
758 struct module_kobject *mk, char *buffer) \
760 return scnprintf(buffer, PAGE_SIZE, "%s\n", mk->mod->field); \
762 static int modinfo_##field##_exists(struct module *mod) \
764 return mod->field != NULL; \
766 static void free_modinfo_##field(struct module *mod) \
771 static struct module_attribute modinfo_##field = { \
772 .attr = { .name = __stringify(field), .mode = 0444 }, \
773 .show = show_modinfo_##field, \
774 .setup = setup_modinfo_##field, \
775 .test = modinfo_##field##_exists, \
776 .free = free_modinfo_##field, \
779 MODINFO_ATTR(version);
780 MODINFO_ATTR(srcversion);
782 static char last_unloaded_module[MODULE_NAME_LEN+1];
784 #ifdef CONFIG_MODULE_UNLOAD
786 EXPORT_TRACEPOINT_SYMBOL(module_get);
788 /* MODULE_REF_BASE is the base reference count by kmodule loader. */
789 #define MODULE_REF_BASE 1
791 /* Init the unload section of the module. */
792 static int module_unload_init(struct module *mod)
795 * Initialize reference counter to MODULE_REF_BASE.
796 * refcnt == 0 means module is going.
798 atomic_set(&mod->refcnt, MODULE_REF_BASE);
800 INIT_LIST_HEAD(&mod->source_list);
801 INIT_LIST_HEAD(&mod->target_list);
803 /* Hold reference count during initialization. */
804 atomic_inc(&mod->refcnt);
809 /* Does a already use b? */
810 static int already_uses(struct module *a, struct module *b)
812 struct module_use *use;
814 list_for_each_entry(use, &b->source_list, source_list) {
815 if (use->source == a) {
816 pr_debug("%s uses %s!\n", a->name, b->name);
820 pr_debug("%s does not use %s!\n", a->name, b->name);
826 * - we add 'a' as a "source", 'b' as a "target" of module use
827 * - the module_use is added to the list of 'b' sources (so
828 * 'b' can walk the list to see who sourced them), and of 'a'
829 * targets (so 'a' can see what modules it targets).
831 static int add_module_usage(struct module *a, struct module *b)
833 struct module_use *use;
835 pr_debug("Allocating new usage for %s.\n", a->name);
836 use = kmalloc(sizeof(*use), GFP_ATOMIC);
842 list_add(&use->source_list, &b->source_list);
843 list_add(&use->target_list, &a->target_list);
847 /* Module a uses b: caller needs module_mutex() */
848 static int ref_module(struct module *a, struct module *b)
852 if (b == NULL || already_uses(a, b))
855 /* If module isn't available, we fail. */
856 err = strong_try_module_get(b);
860 err = add_module_usage(a, b);
868 /* Clear the unload stuff of the module. */
869 static void module_unload_free(struct module *mod)
871 struct module_use *use, *tmp;
873 mutex_lock(&module_mutex);
874 list_for_each_entry_safe(use, tmp, &mod->target_list, target_list) {
875 struct module *i = use->target;
876 pr_debug("%s unusing %s\n", mod->name, i->name);
878 list_del(&use->source_list);
879 list_del(&use->target_list);
882 mutex_unlock(&module_mutex);
885 #ifdef CONFIG_MODULE_FORCE_UNLOAD
886 static inline int try_force_unload(unsigned int flags)
888 int ret = (flags & O_TRUNC);
890 add_taint(TAINT_FORCED_RMMOD, LOCKDEP_NOW_UNRELIABLE);
894 static inline int try_force_unload(unsigned int flags)
898 #endif /* CONFIG_MODULE_FORCE_UNLOAD */
900 /* Try to release refcount of module, 0 means success. */
901 static int try_release_module_ref(struct module *mod)
905 /* Try to decrement refcnt which we set at loading */
906 ret = atomic_sub_return(MODULE_REF_BASE, &mod->refcnt);
909 /* Someone can put this right now, recover with checking */
910 ret = atomic_add_unless(&mod->refcnt, MODULE_REF_BASE, 0);
915 static int try_stop_module(struct module *mod, int flags, int *forced)
917 /* If it's not unused, quit unless we're forcing. */
918 if (try_release_module_ref(mod) != 0) {
919 *forced = try_force_unload(flags);
924 /* Mark it as dying. */
925 mod->state = MODULE_STATE_GOING;
931 * module_refcount() - return the refcount or -1 if unloading
932 * @mod: the module we're checking
935 * -1 if the module is in the process of unloading
936 * otherwise the number of references in the kernel to the module
938 int module_refcount(struct module *mod)
940 return atomic_read(&mod->refcnt) - MODULE_REF_BASE;
942 EXPORT_SYMBOL(module_refcount);
944 /* This exists whether we can unload or not */
945 static void free_module(struct module *mod);
947 SYSCALL_DEFINE2(delete_module, const char __user *, name_user,
951 char name[MODULE_NAME_LEN];
954 if (!capable(CAP_SYS_MODULE) || modules_disabled)
957 if (strncpy_from_user(name, name_user, MODULE_NAME_LEN-1) < 0)
959 name[MODULE_NAME_LEN-1] = '\0';
961 audit_log_kern_module(name);
963 if (mutex_lock_interruptible(&module_mutex) != 0)
966 mod = find_module(name);
972 if (!list_empty(&mod->source_list)) {
973 /* Other modules depend on us: get rid of them first. */
978 /* Doing init or already dying? */
979 if (mod->state != MODULE_STATE_LIVE) {
980 /* FIXME: if (force), slam module count damn the torpedoes */
981 pr_debug("%s already dying\n", mod->name);
986 /* If it has an init func, it must have an exit func to unload */
987 if (mod->init && !mod->exit) {
988 forced = try_force_unload(flags);
990 /* This module can't be removed */
996 /* Stop the machine so refcounts can't move and disable module. */
997 ret = try_stop_module(mod, flags, &forced);
1001 mutex_unlock(&module_mutex);
1002 /* Final destruction now no one is using it. */
1003 if (mod->exit != NULL)
1005 blocking_notifier_call_chain(&module_notify_list,
1006 MODULE_STATE_GOING, mod);
1007 klp_module_going(mod);
1008 ftrace_release_mod(mod);
1010 async_synchronize_full();
1012 /* Store the name of the last unloaded module for diagnostic purposes */
1013 strlcpy(last_unloaded_module, mod->name, sizeof(last_unloaded_module));
1016 /* someone could wait for the module in add_unformed_module() */
1017 wake_up_all(&module_wq);
1020 mutex_unlock(&module_mutex);
1024 static inline void print_unload_info(struct seq_file *m, struct module *mod)
1026 struct module_use *use;
1027 int printed_something = 0;
1029 seq_printf(m, " %i ", module_refcount(mod));
1032 * Always include a trailing , so userspace can differentiate
1033 * between this and the old multi-field proc format.
1035 list_for_each_entry(use, &mod->source_list, source_list) {
1036 printed_something = 1;
1037 seq_printf(m, "%s,", use->source->name);
1040 if (mod->init != NULL && mod->exit == NULL) {
1041 printed_something = 1;
1042 seq_puts(m, "[permanent],");
1045 if (!printed_something)
1049 void __symbol_put(const char *symbol)
1051 struct find_symbol_arg fsa = {
1057 if (!find_symbol(&fsa))
1059 module_put(fsa.owner);
1062 EXPORT_SYMBOL(__symbol_put);
1064 /* Note this assumes addr is a function, which it currently always is. */
1065 void symbol_put_addr(void *addr)
1067 struct module *modaddr;
1068 unsigned long a = (unsigned long)dereference_function_descriptor(addr);
1070 if (core_kernel_text(a))
1074 * Even though we hold a reference on the module; we still need to
1075 * disable preemption in order to safely traverse the data structure.
1078 modaddr = __module_text_address(a);
1080 module_put(modaddr);
1083 EXPORT_SYMBOL_GPL(symbol_put_addr);
1085 static ssize_t show_refcnt(struct module_attribute *mattr,
1086 struct module_kobject *mk, char *buffer)
1088 return sprintf(buffer, "%i\n", module_refcount(mk->mod));
1091 static struct module_attribute modinfo_refcnt =
1092 __ATTR(refcnt, 0444, show_refcnt, NULL);
1094 void __module_get(struct module *module)
1098 atomic_inc(&module->refcnt);
1099 trace_module_get(module, _RET_IP_);
1103 EXPORT_SYMBOL(__module_get);
1105 bool try_module_get(struct module *module)
1111 /* Note: here, we can fail to get a reference */
1112 if (likely(module_is_live(module) &&
1113 atomic_inc_not_zero(&module->refcnt) != 0))
1114 trace_module_get(module, _RET_IP_);
1122 EXPORT_SYMBOL(try_module_get);
1124 void module_put(struct module *module)
1130 ret = atomic_dec_if_positive(&module->refcnt);
1131 WARN_ON(ret < 0); /* Failed to put refcount */
1132 trace_module_put(module, _RET_IP_);
1136 EXPORT_SYMBOL(module_put);
1138 #else /* !CONFIG_MODULE_UNLOAD */
1139 static inline void print_unload_info(struct seq_file *m, struct module *mod)
1141 /* We don't know the usage count, or what modules are using. */
1142 seq_puts(m, " - -");
1145 static inline void module_unload_free(struct module *mod)
1149 static int ref_module(struct module *a, struct module *b)
1151 return strong_try_module_get(b);
1154 static inline int module_unload_init(struct module *mod)
1158 #endif /* CONFIG_MODULE_UNLOAD */
1160 static size_t module_flags_taint(struct module *mod, char *buf)
1165 for (i = 0; i < TAINT_FLAGS_COUNT; i++) {
1166 if (taint_flags[i].module && test_bit(i, &mod->taints))
1167 buf[l++] = taint_flags[i].c_true;
1173 static ssize_t show_initstate(struct module_attribute *mattr,
1174 struct module_kobject *mk, char *buffer)
1176 const char *state = "unknown";
1178 switch (mk->mod->state) {
1179 case MODULE_STATE_LIVE:
1182 case MODULE_STATE_COMING:
1185 case MODULE_STATE_GOING:
1191 return sprintf(buffer, "%s\n", state);
1194 static struct module_attribute modinfo_initstate =
1195 __ATTR(initstate, 0444, show_initstate, NULL);
1197 static ssize_t store_uevent(struct module_attribute *mattr,
1198 struct module_kobject *mk,
1199 const char *buffer, size_t count)
1203 rc = kobject_synth_uevent(&mk->kobj, buffer, count);
1204 return rc ? rc : count;
1207 struct module_attribute module_uevent =
1208 __ATTR(uevent, 0200, NULL, store_uevent);
1210 static ssize_t show_coresize(struct module_attribute *mattr,
1211 struct module_kobject *mk, char *buffer)
1213 return sprintf(buffer, "%u\n", mk->mod->core_layout.size);
1216 static struct module_attribute modinfo_coresize =
1217 __ATTR(coresize, 0444, show_coresize, NULL);
1219 static ssize_t show_initsize(struct module_attribute *mattr,
1220 struct module_kobject *mk, char *buffer)
1222 return sprintf(buffer, "%u\n", mk->mod->init_layout.size);
1225 static struct module_attribute modinfo_initsize =
1226 __ATTR(initsize, 0444, show_initsize, NULL);
1228 static ssize_t show_taint(struct module_attribute *mattr,
1229 struct module_kobject *mk, char *buffer)
1233 l = module_flags_taint(mk->mod, buffer);
1238 static struct module_attribute modinfo_taint =
1239 __ATTR(taint, 0444, show_taint, NULL);
1241 static struct module_attribute *modinfo_attrs[] = {
1244 &modinfo_srcversion,
1249 #ifdef CONFIG_MODULE_UNLOAD
1255 static const char vermagic[] = VERMAGIC_STRING;
1257 static int try_to_force_load(struct module *mod, const char *reason)
1259 #ifdef CONFIG_MODULE_FORCE_LOAD
1260 if (!test_taint(TAINT_FORCED_MODULE))
1261 pr_warn("%s: %s: kernel tainted.\n", mod->name, reason);
1262 add_taint_module(mod, TAINT_FORCED_MODULE, LOCKDEP_NOW_UNRELIABLE);
1269 #ifdef CONFIG_MODVERSIONS
1271 static u32 resolve_rel_crc(const s32 *crc)
1273 return *(u32 *)((void *)crc + *crc);
1276 static int check_version(const struct load_info *info,
1277 const char *symname,
1281 Elf_Shdr *sechdrs = info->sechdrs;
1282 unsigned int versindex = info->index.vers;
1283 unsigned int i, num_versions;
1284 struct modversion_info *versions;
1286 /* Exporting module didn't supply crcs? OK, we're already tainted. */
1290 /* No versions at all? modprobe --force does this. */
1292 return try_to_force_load(mod, symname) == 0;
1294 versions = (void *) sechdrs[versindex].sh_addr;
1295 num_versions = sechdrs[versindex].sh_size
1296 / sizeof(struct modversion_info);
1298 for (i = 0; i < num_versions; i++) {
1301 if (strcmp(versions[i].name, symname) != 0)
1304 if (IS_ENABLED(CONFIG_MODULE_REL_CRCS))
1305 crcval = resolve_rel_crc(crc);
1308 if (versions[i].crc == crcval)
1310 pr_debug("Found checksum %X vs module %lX\n",
1311 crcval, versions[i].crc);
1315 /* Broken toolchain. Warn once, then let it go.. */
1316 pr_warn_once("%s: no symbol version for %s\n", info->name, symname);
1320 pr_warn("%s: disagrees about version of symbol %s\n",
1321 info->name, symname);
1325 static inline int check_modstruct_version(const struct load_info *info,
1328 struct find_symbol_arg fsa = {
1329 .name = "module_layout",
1334 * Since this should be found in kernel (which can't be removed), no
1335 * locking is necessary -- use preempt_disable() to placate lockdep.
1338 if (!find_symbol(&fsa)) {
1343 return check_version(info, "module_layout", mod, fsa.crc);
1346 /* First part is kernel version, which we ignore if module has crcs. */
1347 static inline int same_magic(const char *amagic, const char *bmagic,
1351 amagic += strcspn(amagic, " ");
1352 bmagic += strcspn(bmagic, " ");
1354 return strcmp(amagic, bmagic) == 0;
1357 static inline int check_version(const struct load_info *info,
1358 const char *symname,
1365 static inline int check_modstruct_version(const struct load_info *info,
1371 static inline int same_magic(const char *amagic, const char *bmagic,
1374 return strcmp(amagic, bmagic) == 0;
1376 #endif /* CONFIG_MODVERSIONS */
1378 static char *get_modinfo(const struct load_info *info, const char *tag);
1379 static char *get_next_modinfo(const struct load_info *info, const char *tag,
1382 static int verify_namespace_is_imported(const struct load_info *info,
1383 const struct kernel_symbol *sym,
1386 const char *namespace;
1387 char *imported_namespace;
1389 namespace = kernel_symbol_namespace(sym);
1390 if (namespace && namespace[0]) {
1391 imported_namespace = get_modinfo(info, "import_ns");
1392 while (imported_namespace) {
1393 if (strcmp(namespace, imported_namespace) == 0)
1395 imported_namespace = get_next_modinfo(
1396 info, "import_ns", imported_namespace);
1398 #ifdef CONFIG_MODULE_ALLOW_MISSING_NAMESPACE_IMPORTS
1403 "%s: module uses symbol (%s) from namespace %s, but does not import it.\n",
1404 mod->name, kernel_symbol_name(sym), namespace);
1405 #ifndef CONFIG_MODULE_ALLOW_MISSING_NAMESPACE_IMPORTS
1412 static bool inherit_taint(struct module *mod, struct module *owner)
1414 if (!owner || !test_bit(TAINT_PROPRIETARY_MODULE, &owner->taints))
1417 if (mod->using_gplonly_symbols) {
1418 pr_err("%s: module using GPL-only symbols uses symbols from proprietary module %s.\n",
1419 mod->name, owner->name);
1423 if (!test_bit(TAINT_PROPRIETARY_MODULE, &mod->taints)) {
1424 pr_warn("%s: module uses symbols from proprietary module %s, inheriting taint.\n",
1425 mod->name, owner->name);
1426 set_bit(TAINT_PROPRIETARY_MODULE, &mod->taints);
1431 /* Resolve a symbol for this module. I.e. if we find one, record usage. */
1432 static const struct kernel_symbol *resolve_symbol(struct module *mod,
1433 const struct load_info *info,
1437 struct find_symbol_arg fsa = {
1439 .gplok = !(mod->taints & (1 << TAINT_PROPRIETARY_MODULE)),
1445 * The module_mutex should not be a heavily contended lock;
1446 * if we get the occasional sleep here, we'll go an extra iteration
1447 * in the wait_event_interruptible(), which is harmless.
1449 sched_annotate_sleep();
1450 mutex_lock(&module_mutex);
1451 if (!find_symbol(&fsa))
1454 if (fsa.license == GPL_ONLY)
1455 mod->using_gplonly_symbols = true;
1457 if (!inherit_taint(mod, fsa.owner)) {
1462 if (!check_version(info, name, mod, fsa.crc)) {
1463 fsa.sym = ERR_PTR(-EINVAL);
1467 err = verify_namespace_is_imported(info, fsa.sym, mod);
1469 fsa.sym = ERR_PTR(err);
1473 err = ref_module(mod, fsa.owner);
1475 fsa.sym = ERR_PTR(err);
1480 /* We must make copy under the lock if we failed to get ref. */
1481 strncpy(ownername, module_name(fsa.owner), MODULE_NAME_LEN);
1483 mutex_unlock(&module_mutex);
1487 static const struct kernel_symbol *
1488 resolve_symbol_wait(struct module *mod,
1489 const struct load_info *info,
1492 const struct kernel_symbol *ksym;
1493 char owner[MODULE_NAME_LEN];
1495 if (wait_event_interruptible_timeout(module_wq,
1496 !IS_ERR(ksym = resolve_symbol(mod, info, name, owner))
1497 || PTR_ERR(ksym) != -EBUSY,
1499 pr_warn("%s: gave up waiting for init of module %s.\n",
1506 * /sys/module/foo/sections stuff
1511 #ifdef CONFIG_KALLSYMS
1512 static inline bool sect_empty(const Elf_Shdr *sect)
1514 return !(sect->sh_flags & SHF_ALLOC) || sect->sh_size == 0;
1517 struct module_sect_attr {
1518 struct bin_attribute battr;
1519 unsigned long address;
1522 struct module_sect_attrs {
1523 struct attribute_group grp;
1524 unsigned int nsections;
1525 struct module_sect_attr attrs[];
1528 #define MODULE_SECT_READ_SIZE (3 /* "0x", "\n" */ + (BITS_PER_LONG / 4))
1529 static ssize_t module_sect_read(struct file *file, struct kobject *kobj,
1530 struct bin_attribute *battr,
1531 char *buf, loff_t pos, size_t count)
1533 struct module_sect_attr *sattr =
1534 container_of(battr, struct module_sect_attr, battr);
1535 char bounce[MODULE_SECT_READ_SIZE + 1];
1542 * Since we're a binary read handler, we must account for the
1543 * trailing NUL byte that sprintf will write: if "buf" is
1544 * too small to hold the NUL, or the NUL is exactly the last
1545 * byte, the read will look like it got truncated by one byte.
1546 * Since there is no way to ask sprintf nicely to not write
1547 * the NUL, we have to use a bounce buffer.
1549 wrote = scnprintf(bounce, sizeof(bounce), "0x%px\n",
1550 kallsyms_show_value(file->f_cred)
1551 ? (void *)sattr->address : NULL);
1552 count = min(count, wrote);
1553 memcpy(buf, bounce, count);
1558 static void free_sect_attrs(struct module_sect_attrs *sect_attrs)
1560 unsigned int section;
1562 for (section = 0; section < sect_attrs->nsections; section++)
1563 kfree(sect_attrs->attrs[section].battr.attr.name);
1567 static void add_sect_attrs(struct module *mod, const struct load_info *info)
1569 unsigned int nloaded = 0, i, size[2];
1570 struct module_sect_attrs *sect_attrs;
1571 struct module_sect_attr *sattr;
1572 struct bin_attribute **gattr;
1574 /* Count loaded sections and allocate structures */
1575 for (i = 0; i < info->hdr->e_shnum; i++)
1576 if (!sect_empty(&info->sechdrs[i]))
1578 size[0] = ALIGN(struct_size(sect_attrs, attrs, nloaded),
1579 sizeof(sect_attrs->grp.bin_attrs[0]));
1580 size[1] = (nloaded + 1) * sizeof(sect_attrs->grp.bin_attrs[0]);
1581 sect_attrs = kzalloc(size[0] + size[1], GFP_KERNEL);
1582 if (sect_attrs == NULL)
1585 /* Setup section attributes. */
1586 sect_attrs->grp.name = "sections";
1587 sect_attrs->grp.bin_attrs = (void *)sect_attrs + size[0];
1589 sect_attrs->nsections = 0;
1590 sattr = §_attrs->attrs[0];
1591 gattr = §_attrs->grp.bin_attrs[0];
1592 for (i = 0; i < info->hdr->e_shnum; i++) {
1593 Elf_Shdr *sec = &info->sechdrs[i];
1594 if (sect_empty(sec))
1596 sysfs_bin_attr_init(&sattr->battr);
1597 sattr->address = sec->sh_addr;
1598 sattr->battr.attr.name =
1599 kstrdup(info->secstrings + sec->sh_name, GFP_KERNEL);
1600 if (sattr->battr.attr.name == NULL)
1602 sect_attrs->nsections++;
1603 sattr->battr.read = module_sect_read;
1604 sattr->battr.size = MODULE_SECT_READ_SIZE;
1605 sattr->battr.attr.mode = 0400;
1606 *(gattr++) = &(sattr++)->battr;
1610 if (sysfs_create_group(&mod->mkobj.kobj, §_attrs->grp))
1613 mod->sect_attrs = sect_attrs;
1616 free_sect_attrs(sect_attrs);
1619 static void remove_sect_attrs(struct module *mod)
1621 if (mod->sect_attrs) {
1622 sysfs_remove_group(&mod->mkobj.kobj,
1623 &mod->sect_attrs->grp);
1625 * We are positive that no one is using any sect attrs
1626 * at this point. Deallocate immediately.
1628 free_sect_attrs(mod->sect_attrs);
1629 mod->sect_attrs = NULL;
1634 * /sys/module/foo/notes/.section.name gives contents of SHT_NOTE sections.
1637 struct module_notes_attrs {
1638 struct kobject *dir;
1640 struct bin_attribute attrs[];
1643 static ssize_t module_notes_read(struct file *filp, struct kobject *kobj,
1644 struct bin_attribute *bin_attr,
1645 char *buf, loff_t pos, size_t count)
1648 * The caller checked the pos and count against our size.
1650 memcpy(buf, bin_attr->private + pos, count);
1654 static void free_notes_attrs(struct module_notes_attrs *notes_attrs,
1657 if (notes_attrs->dir) {
1659 sysfs_remove_bin_file(notes_attrs->dir,
1660 ¬es_attrs->attrs[i]);
1661 kobject_put(notes_attrs->dir);
1666 static void add_notes_attrs(struct module *mod, const struct load_info *info)
1668 unsigned int notes, loaded, i;
1669 struct module_notes_attrs *notes_attrs;
1670 struct bin_attribute *nattr;
1672 /* failed to create section attributes, so can't create notes */
1673 if (!mod->sect_attrs)
1676 /* Count notes sections and allocate structures. */
1678 for (i = 0; i < info->hdr->e_shnum; i++)
1679 if (!sect_empty(&info->sechdrs[i]) &&
1680 (info->sechdrs[i].sh_type == SHT_NOTE))
1686 notes_attrs = kzalloc(struct_size(notes_attrs, attrs, notes),
1688 if (notes_attrs == NULL)
1691 notes_attrs->notes = notes;
1692 nattr = ¬es_attrs->attrs[0];
1693 for (loaded = i = 0; i < info->hdr->e_shnum; ++i) {
1694 if (sect_empty(&info->sechdrs[i]))
1696 if (info->sechdrs[i].sh_type == SHT_NOTE) {
1697 sysfs_bin_attr_init(nattr);
1698 nattr->attr.name = mod->sect_attrs->attrs[loaded].battr.attr.name;
1699 nattr->attr.mode = S_IRUGO;
1700 nattr->size = info->sechdrs[i].sh_size;
1701 nattr->private = (void *) info->sechdrs[i].sh_addr;
1702 nattr->read = module_notes_read;
1708 notes_attrs->dir = kobject_create_and_add("notes", &mod->mkobj.kobj);
1709 if (!notes_attrs->dir)
1712 for (i = 0; i < notes; ++i)
1713 if (sysfs_create_bin_file(notes_attrs->dir,
1714 ¬es_attrs->attrs[i]))
1717 mod->notes_attrs = notes_attrs;
1721 free_notes_attrs(notes_attrs, i);
1724 static void remove_notes_attrs(struct module *mod)
1726 if (mod->notes_attrs)
1727 free_notes_attrs(mod->notes_attrs, mod->notes_attrs->notes);
1732 static inline void add_sect_attrs(struct module *mod,
1733 const struct load_info *info)
1737 static inline void remove_sect_attrs(struct module *mod)
1741 static inline void add_notes_attrs(struct module *mod,
1742 const struct load_info *info)
1746 static inline void remove_notes_attrs(struct module *mod)
1749 #endif /* CONFIG_KALLSYMS */
1751 static void del_usage_links(struct module *mod)
1753 #ifdef CONFIG_MODULE_UNLOAD
1754 struct module_use *use;
1756 mutex_lock(&module_mutex);
1757 list_for_each_entry(use, &mod->target_list, target_list)
1758 sysfs_remove_link(use->target->holders_dir, mod->name);
1759 mutex_unlock(&module_mutex);
1763 static int add_usage_links(struct module *mod)
1766 #ifdef CONFIG_MODULE_UNLOAD
1767 struct module_use *use;
1769 mutex_lock(&module_mutex);
1770 list_for_each_entry(use, &mod->target_list, target_list) {
1771 ret = sysfs_create_link(use->target->holders_dir,
1772 &mod->mkobj.kobj, mod->name);
1776 mutex_unlock(&module_mutex);
1778 del_usage_links(mod);
1783 static void module_remove_modinfo_attrs(struct module *mod, int end);
1785 static int module_add_modinfo_attrs(struct module *mod)
1787 struct module_attribute *attr;
1788 struct module_attribute *temp_attr;
1792 mod->modinfo_attrs = kzalloc((sizeof(struct module_attribute) *
1793 (ARRAY_SIZE(modinfo_attrs) + 1)),
1795 if (!mod->modinfo_attrs)
1798 temp_attr = mod->modinfo_attrs;
1799 for (i = 0; (attr = modinfo_attrs[i]); i++) {
1800 if (!attr->test || attr->test(mod)) {
1801 memcpy(temp_attr, attr, sizeof(*temp_attr));
1802 sysfs_attr_init(&temp_attr->attr);
1803 error = sysfs_create_file(&mod->mkobj.kobj,
1815 module_remove_modinfo_attrs(mod, --i);
1817 kfree(mod->modinfo_attrs);
1821 static void module_remove_modinfo_attrs(struct module *mod, int end)
1823 struct module_attribute *attr;
1826 for (i = 0; (attr = &mod->modinfo_attrs[i]); i++) {
1827 if (end >= 0 && i > end)
1829 /* pick a field to test for end of list */
1830 if (!attr->attr.name)
1832 sysfs_remove_file(&mod->mkobj.kobj, &attr->attr);
1836 kfree(mod->modinfo_attrs);
1839 static void mod_kobject_put(struct module *mod)
1841 DECLARE_COMPLETION_ONSTACK(c);
1842 mod->mkobj.kobj_completion = &c;
1843 kobject_put(&mod->mkobj.kobj);
1844 wait_for_completion(&c);
1847 static int mod_sysfs_init(struct module *mod)
1850 struct kobject *kobj;
1852 if (!module_sysfs_initialized) {
1853 pr_err("%s: module sysfs not initialized\n", mod->name);
1858 kobj = kset_find_obj(module_kset, mod->name);
1860 pr_err("%s: module is already loaded\n", mod->name);
1866 mod->mkobj.mod = mod;
1868 memset(&mod->mkobj.kobj, 0, sizeof(mod->mkobj.kobj));
1869 mod->mkobj.kobj.kset = module_kset;
1870 err = kobject_init_and_add(&mod->mkobj.kobj, &module_ktype, NULL,
1873 mod_kobject_put(mod);
1879 static int mod_sysfs_setup(struct module *mod,
1880 const struct load_info *info,
1881 struct kernel_param *kparam,
1882 unsigned int num_params)
1886 err = mod_sysfs_init(mod);
1890 mod->holders_dir = kobject_create_and_add("holders", &mod->mkobj.kobj);
1891 if (!mod->holders_dir) {
1896 err = module_param_sysfs_setup(mod, kparam, num_params);
1898 goto out_unreg_holders;
1900 err = module_add_modinfo_attrs(mod);
1902 goto out_unreg_param;
1904 err = add_usage_links(mod);
1906 goto out_unreg_modinfo_attrs;
1908 add_sect_attrs(mod, info);
1909 add_notes_attrs(mod, info);
1913 out_unreg_modinfo_attrs:
1914 module_remove_modinfo_attrs(mod, -1);
1916 module_param_sysfs_remove(mod);
1918 kobject_put(mod->holders_dir);
1920 mod_kobject_put(mod);
1925 static void mod_sysfs_fini(struct module *mod)
1927 remove_notes_attrs(mod);
1928 remove_sect_attrs(mod);
1929 mod_kobject_put(mod);
1932 static void init_param_lock(struct module *mod)
1934 mutex_init(&mod->param_lock);
1936 #else /* !CONFIG_SYSFS */
1938 static int mod_sysfs_setup(struct module *mod,
1939 const struct load_info *info,
1940 struct kernel_param *kparam,
1941 unsigned int num_params)
1946 static void mod_sysfs_fini(struct module *mod)
1950 static void module_remove_modinfo_attrs(struct module *mod, int end)
1954 static void del_usage_links(struct module *mod)
1958 static void init_param_lock(struct module *mod)
1961 #endif /* CONFIG_SYSFS */
1963 static void mod_sysfs_teardown(struct module *mod)
1965 del_usage_links(mod);
1966 module_remove_modinfo_attrs(mod, -1);
1967 module_param_sysfs_remove(mod);
1968 kobject_put(mod->mkobj.drivers_dir);
1969 kobject_put(mod->holders_dir);
1970 mod_sysfs_fini(mod);
1974 * LKM RO/NX protection: protect module's text/ro-data
1975 * from modification and any data from execution.
1977 * General layout of module is:
1978 * [text] [read-only-data] [ro-after-init] [writable data]
1979 * text_size -----^ ^ ^ ^
1980 * ro_size ------------------------| | |
1981 * ro_after_init_size -----------------------------| |
1982 * size -----------------------------------------------------------|
1984 * These values are always page-aligned (as is base)
1988 * Since some arches are moving towards PAGE_KERNEL module allocations instead
1989 * of PAGE_KERNEL_EXEC, keep frob_text() and module_enable_x() outside of the
1990 * CONFIG_STRICT_MODULE_RWX block below because they are needed regardless of
1991 * whether we are strict.
1993 #ifdef CONFIG_ARCH_HAS_STRICT_MODULE_RWX
1994 static void frob_text(const struct module_layout *layout,
1995 int (*set_memory)(unsigned long start, int num_pages))
1997 BUG_ON((unsigned long)layout->base & (PAGE_SIZE-1));
1998 BUG_ON((unsigned long)layout->text_size & (PAGE_SIZE-1));
1999 set_memory((unsigned long)layout->base,
2000 layout->text_size >> PAGE_SHIFT);
2003 static void module_enable_x(const struct module *mod)
2005 frob_text(&mod->core_layout, set_memory_x);
2006 frob_text(&mod->init_layout, set_memory_x);
2008 #else /* !CONFIG_ARCH_HAS_STRICT_MODULE_RWX */
2009 static void module_enable_x(const struct module *mod) { }
2010 #endif /* CONFIG_ARCH_HAS_STRICT_MODULE_RWX */
2012 #ifdef CONFIG_STRICT_MODULE_RWX
2013 static void frob_rodata(const struct module_layout *layout,
2014 int (*set_memory)(unsigned long start, int num_pages))
2016 BUG_ON((unsigned long)layout->base & (PAGE_SIZE-1));
2017 BUG_ON((unsigned long)layout->text_size & (PAGE_SIZE-1));
2018 BUG_ON((unsigned long)layout->ro_size & (PAGE_SIZE-1));
2019 set_memory((unsigned long)layout->base + layout->text_size,
2020 (layout->ro_size - layout->text_size) >> PAGE_SHIFT);
2023 static void frob_ro_after_init(const struct module_layout *layout,
2024 int (*set_memory)(unsigned long start, int num_pages))
2026 BUG_ON((unsigned long)layout->base & (PAGE_SIZE-1));
2027 BUG_ON((unsigned long)layout->ro_size & (PAGE_SIZE-1));
2028 BUG_ON((unsigned long)layout->ro_after_init_size & (PAGE_SIZE-1));
2029 set_memory((unsigned long)layout->base + layout->ro_size,
2030 (layout->ro_after_init_size - layout->ro_size) >> PAGE_SHIFT);
2033 static void frob_writable_data(const struct module_layout *layout,
2034 int (*set_memory)(unsigned long start, int num_pages))
2036 BUG_ON((unsigned long)layout->base & (PAGE_SIZE-1));
2037 BUG_ON((unsigned long)layout->ro_after_init_size & (PAGE_SIZE-1));
2038 BUG_ON((unsigned long)layout->size & (PAGE_SIZE-1));
2039 set_memory((unsigned long)layout->base + layout->ro_after_init_size,
2040 (layout->size - layout->ro_after_init_size) >> PAGE_SHIFT);
2043 static void module_enable_ro(const struct module *mod, bool after_init)
2045 if (!rodata_enabled)
2048 set_vm_flush_reset_perms(mod->core_layout.base);
2049 set_vm_flush_reset_perms(mod->init_layout.base);
2050 frob_text(&mod->core_layout, set_memory_ro);
2052 frob_rodata(&mod->core_layout, set_memory_ro);
2053 frob_text(&mod->init_layout, set_memory_ro);
2054 frob_rodata(&mod->init_layout, set_memory_ro);
2057 frob_ro_after_init(&mod->core_layout, set_memory_ro);
2060 static void module_enable_nx(const struct module *mod)
2062 frob_rodata(&mod->core_layout, set_memory_nx);
2063 frob_ro_after_init(&mod->core_layout, set_memory_nx);
2064 frob_writable_data(&mod->core_layout, set_memory_nx);
2065 frob_rodata(&mod->init_layout, set_memory_nx);
2066 frob_writable_data(&mod->init_layout, set_memory_nx);
2069 static int module_enforce_rwx_sections(Elf_Ehdr *hdr, Elf_Shdr *sechdrs,
2070 char *secstrings, struct module *mod)
2072 const unsigned long shf_wx = SHF_WRITE|SHF_EXECINSTR;
2075 for (i = 0; i < hdr->e_shnum; i++) {
2076 if ((sechdrs[i].sh_flags & shf_wx) == shf_wx) {
2077 pr_err("%s: section %s (index %d) has invalid WRITE|EXEC flags\n",
2078 mod->name, secstrings + sechdrs[i].sh_name, i);
2086 #else /* !CONFIG_STRICT_MODULE_RWX */
2087 static void module_enable_nx(const struct module *mod) { }
2088 static void module_enable_ro(const struct module *mod, bool after_init) {}
2089 static int module_enforce_rwx_sections(Elf_Ehdr *hdr, Elf_Shdr *sechdrs,
2090 char *secstrings, struct module *mod)
2094 #endif /* CONFIG_STRICT_MODULE_RWX */
2096 #ifdef CONFIG_LIVEPATCH
2098 * Persist Elf information about a module. Copy the Elf header,
2099 * section header table, section string table, and symtab section
2100 * index from info to mod->klp_info.
2102 static int copy_module_elf(struct module *mod, struct load_info *info)
2104 unsigned int size, symndx;
2107 size = sizeof(*mod->klp_info);
2108 mod->klp_info = kmalloc(size, GFP_KERNEL);
2109 if (mod->klp_info == NULL)
2113 size = sizeof(mod->klp_info->hdr);
2114 memcpy(&mod->klp_info->hdr, info->hdr, size);
2116 /* Elf section header table */
2117 size = sizeof(*info->sechdrs) * info->hdr->e_shnum;
2118 mod->klp_info->sechdrs = kmemdup(info->sechdrs, size, GFP_KERNEL);
2119 if (mod->klp_info->sechdrs == NULL) {
2124 /* Elf section name string table */
2125 size = info->sechdrs[info->hdr->e_shstrndx].sh_size;
2126 mod->klp_info->secstrings = kmemdup(info->secstrings, size, GFP_KERNEL);
2127 if (mod->klp_info->secstrings == NULL) {
2132 /* Elf symbol section index */
2133 symndx = info->index.sym;
2134 mod->klp_info->symndx = symndx;
2137 * For livepatch modules, core_kallsyms.symtab is a complete
2138 * copy of the original symbol table. Adjust sh_addr to point
2139 * to core_kallsyms.symtab since the copy of the symtab in module
2140 * init memory is freed at the end of do_init_module().
2142 mod->klp_info->sechdrs[symndx].sh_addr = \
2143 (unsigned long) mod->core_kallsyms.symtab;
2148 kfree(mod->klp_info->sechdrs);
2150 kfree(mod->klp_info);
2154 static void free_module_elf(struct module *mod)
2156 kfree(mod->klp_info->sechdrs);
2157 kfree(mod->klp_info->secstrings);
2158 kfree(mod->klp_info);
2160 #else /* !CONFIG_LIVEPATCH */
2161 static int copy_module_elf(struct module *mod, struct load_info *info)
2166 static void free_module_elf(struct module *mod)
2169 #endif /* CONFIG_LIVEPATCH */
2171 void __weak module_memfree(void *module_region)
2174 * This memory may be RO, and freeing RO memory in an interrupt is not
2175 * supported by vmalloc.
2177 WARN_ON(in_interrupt());
2178 vfree(module_region);
2181 void __weak module_arch_cleanup(struct module *mod)
2185 void __weak module_arch_freeing_init(struct module *mod)
2189 /* Free a module, remove from lists, etc. */
2190 static void free_module(struct module *mod)
2192 trace_module_free(mod);
2194 mod_sysfs_teardown(mod);
2197 * We leave it in list to prevent duplicate loads, but make sure
2198 * that noone uses it while it's being deconstructed.
2200 mutex_lock(&module_mutex);
2201 mod->state = MODULE_STATE_UNFORMED;
2202 mutex_unlock(&module_mutex);
2204 /* Remove dynamic debug info */
2205 ddebug_remove_module(mod->name);
2207 /* Arch-specific cleanup. */
2208 module_arch_cleanup(mod);
2210 /* Module unload stuff */
2211 module_unload_free(mod);
2213 /* Free any allocated parameters. */
2214 destroy_params(mod->kp, mod->num_kp);
2216 if (is_livepatch_module(mod))
2217 free_module_elf(mod);
2219 /* Now we can delete it from the lists */
2220 mutex_lock(&module_mutex);
2221 /* Unlink carefully: kallsyms could be walking list. */
2222 list_del_rcu(&mod->list);
2223 mod_tree_remove(mod);
2224 /* Remove this module from bug list, this uses list_del_rcu */
2225 module_bug_cleanup(mod);
2226 /* Wait for RCU-sched synchronizing before releasing mod->list and buglist. */
2228 mutex_unlock(&module_mutex);
2230 /* This may be empty, but that's OK */
2231 module_arch_freeing_init(mod);
2232 module_memfree(mod->init_layout.base);
2234 percpu_modfree(mod);
2236 /* Free lock-classes; relies on the preceding sync_rcu(). */
2237 lockdep_free_key_range(mod->core_layout.base, mod->core_layout.size);
2239 /* Finally, free the core (containing the module structure) */
2240 module_memfree(mod->core_layout.base);
2243 void *__symbol_get(const char *symbol)
2245 struct find_symbol_arg fsa = {
2252 if (!find_symbol(&fsa) || strong_try_module_get(fsa.owner)) {
2257 return (void *)kernel_symbol_value(fsa.sym);
2259 EXPORT_SYMBOL_GPL(__symbol_get);
2262 * Ensure that an exported symbol [global namespace] does not already exist
2263 * in the kernel or in some other module's exported symbol table.
2265 * You must hold the module_mutex.
2267 static int verify_exported_symbols(struct module *mod)
2270 const struct kernel_symbol *s;
2272 const struct kernel_symbol *sym;
2275 { mod->syms, mod->num_syms },
2276 { mod->gpl_syms, mod->num_gpl_syms },
2277 #ifdef CONFIG_UNUSED_SYMBOLS
2278 { mod->unused_syms, mod->num_unused_syms },
2279 { mod->unused_gpl_syms, mod->num_unused_gpl_syms },
2283 for (i = 0; i < ARRAY_SIZE(arr); i++) {
2284 for (s = arr[i].sym; s < arr[i].sym + arr[i].num; s++) {
2285 struct find_symbol_arg fsa = {
2286 .name = kernel_symbol_name(s),
2289 if (find_symbol(&fsa)) {
2290 pr_err("%s: exports duplicate symbol %s"
2292 mod->name, kernel_symbol_name(s),
2293 module_name(fsa.owner));
2301 static bool ignore_undef_symbol(Elf_Half emachine, const char *name)
2304 * On x86, PIC code and Clang non-PIC code may have call foo@PLT. GNU as
2305 * before 2.37 produces an unreferenced _GLOBAL_OFFSET_TABLE_ on x86-64.
2306 * i386 has a similar problem but may not deserve a fix.
2308 * If we ever have to ignore many symbols, consider refactoring the code to
2309 * only warn if referenced by a relocation.
2311 if (emachine == EM_386 || emachine == EM_X86_64)
2312 return !strcmp(name, "_GLOBAL_OFFSET_TABLE_");
2316 /* Change all symbols so that st_value encodes the pointer directly. */
2317 static int simplify_symbols(struct module *mod, const struct load_info *info)
2319 Elf_Shdr *symsec = &info->sechdrs[info->index.sym];
2320 Elf_Sym *sym = (void *)symsec->sh_addr;
2321 unsigned long secbase;
2324 const struct kernel_symbol *ksym;
2326 for (i = 1; i < symsec->sh_size / sizeof(Elf_Sym); i++) {
2327 const char *name = info->strtab + sym[i].st_name;
2329 switch (sym[i].st_shndx) {
2331 /* Ignore common symbols */
2332 if (!strncmp(name, "__gnu_lto", 9))
2336 * We compiled with -fno-common. These are not
2337 * supposed to happen.
2339 pr_debug("Common symbol: %s\n", name);
2340 pr_warn("%s: please compile with -fno-common\n",
2346 /* Don't need to do anything */
2347 pr_debug("Absolute symbol: 0x%08lx\n",
2348 (long)sym[i].st_value);
2352 /* Livepatch symbols are resolved by livepatch */
2356 ksym = resolve_symbol_wait(mod, info, name);
2357 /* Ok if resolved. */
2358 if (ksym && !IS_ERR(ksym)) {
2359 sym[i].st_value = kernel_symbol_value(ksym);
2363 /* Ok if weak or ignored. */
2365 (ELF_ST_BIND(sym[i].st_info) == STB_WEAK ||
2366 ignore_undef_symbol(info->hdr->e_machine, name)))
2369 ret = PTR_ERR(ksym) ?: -ENOENT;
2370 pr_warn("%s: Unknown symbol %s (err %d)\n",
2371 mod->name, name, ret);
2375 /* Divert to percpu allocation if a percpu var. */
2376 if (sym[i].st_shndx == info->index.pcpu)
2377 secbase = (unsigned long)mod_percpu(mod);
2379 secbase = info->sechdrs[sym[i].st_shndx].sh_addr;
2380 sym[i].st_value += secbase;
2388 static int apply_relocations(struct module *mod, const struct load_info *info)
2393 /* Now do relocations. */
2394 for (i = 1; i < info->hdr->e_shnum; i++) {
2395 unsigned int infosec = info->sechdrs[i].sh_info;
2397 /* Not a valid relocation section? */
2398 if (infosec >= info->hdr->e_shnum)
2401 /* Don't bother with non-allocated sections */
2402 if (!(info->sechdrs[infosec].sh_flags & SHF_ALLOC))
2405 if (info->sechdrs[i].sh_flags & SHF_RELA_LIVEPATCH)
2406 err = klp_apply_section_relocs(mod, info->sechdrs,
2411 else if (info->sechdrs[i].sh_type == SHT_REL)
2412 err = apply_relocate(info->sechdrs, info->strtab,
2413 info->index.sym, i, mod);
2414 else if (info->sechdrs[i].sh_type == SHT_RELA)
2415 err = apply_relocate_add(info->sechdrs, info->strtab,
2416 info->index.sym, i, mod);
2423 /* Additional bytes needed by arch in front of individual sections */
2424 unsigned int __weak arch_mod_section_prepend(struct module *mod,
2425 unsigned int section)
2427 /* default implementation just returns zero */
2431 /* Update size with this section: return offset. */
2432 static long get_offset(struct module *mod, unsigned int *size,
2433 Elf_Shdr *sechdr, unsigned int section)
2437 *size += arch_mod_section_prepend(mod, section);
2438 ret = ALIGN(*size, sechdr->sh_addralign ?: 1);
2439 *size = ret + sechdr->sh_size;
2444 * Lay out the SHF_ALLOC sections in a way not dissimilar to how ld
2445 * might -- code, read-only data, read-write data, small data. Tally
2446 * sizes, and place the offsets into sh_entsize fields: high bit means it
2449 static void layout_sections(struct module *mod, struct load_info *info)
2451 static unsigned long const masks[][2] = {
2453 * NOTE: all executable code must be the first section
2454 * in this array; otherwise modify the text_size
2455 * finder in the two loops below
2457 { SHF_EXECINSTR | SHF_ALLOC, ARCH_SHF_SMALL },
2458 { SHF_ALLOC, SHF_WRITE | ARCH_SHF_SMALL },
2459 { SHF_RO_AFTER_INIT | SHF_ALLOC, ARCH_SHF_SMALL },
2460 { SHF_WRITE | SHF_ALLOC, ARCH_SHF_SMALL },
2461 { ARCH_SHF_SMALL | SHF_ALLOC, 0 }
2465 for (i = 0; i < info->hdr->e_shnum; i++)
2466 info->sechdrs[i].sh_entsize = ~0UL;
2468 pr_debug("Core section allocation order:\n");
2469 for (m = 0; m < ARRAY_SIZE(masks); ++m) {
2470 for (i = 0; i < info->hdr->e_shnum; ++i) {
2471 Elf_Shdr *s = &info->sechdrs[i];
2472 const char *sname = info->secstrings + s->sh_name;
2474 if ((s->sh_flags & masks[m][0]) != masks[m][0]
2475 || (s->sh_flags & masks[m][1])
2476 || s->sh_entsize != ~0UL
2477 || module_init_section(sname))
2479 s->sh_entsize = get_offset(mod, &mod->core_layout.size, s, i);
2480 pr_debug("\t%s\n", sname);
2483 case 0: /* executable */
2484 mod->core_layout.size = debug_align(mod->core_layout.size);
2485 mod->core_layout.text_size = mod->core_layout.size;
2487 case 1: /* RO: text and ro-data */
2488 mod->core_layout.size = debug_align(mod->core_layout.size);
2489 mod->core_layout.ro_size = mod->core_layout.size;
2491 case 2: /* RO after init */
2492 mod->core_layout.size = debug_align(mod->core_layout.size);
2493 mod->core_layout.ro_after_init_size = mod->core_layout.size;
2495 case 4: /* whole core */
2496 mod->core_layout.size = debug_align(mod->core_layout.size);
2501 pr_debug("Init section allocation order:\n");
2502 for (m = 0; m < ARRAY_SIZE(masks); ++m) {
2503 for (i = 0; i < info->hdr->e_shnum; ++i) {
2504 Elf_Shdr *s = &info->sechdrs[i];
2505 const char *sname = info->secstrings + s->sh_name;
2507 if ((s->sh_flags & masks[m][0]) != masks[m][0]
2508 || (s->sh_flags & masks[m][1])
2509 || s->sh_entsize != ~0UL
2510 || !module_init_section(sname))
2512 s->sh_entsize = (get_offset(mod, &mod->init_layout.size, s, i)
2513 | INIT_OFFSET_MASK);
2514 pr_debug("\t%s\n", sname);
2517 case 0: /* executable */
2518 mod->init_layout.size = debug_align(mod->init_layout.size);
2519 mod->init_layout.text_size = mod->init_layout.size;
2521 case 1: /* RO: text and ro-data */
2522 mod->init_layout.size = debug_align(mod->init_layout.size);
2523 mod->init_layout.ro_size = mod->init_layout.size;
2527 * RO after init doesn't apply to init_layout (only
2528 * core_layout), so it just takes the value of ro_size.
2530 mod->init_layout.ro_after_init_size = mod->init_layout.ro_size;
2532 case 4: /* whole init */
2533 mod->init_layout.size = debug_align(mod->init_layout.size);
2539 static void set_license(struct module *mod, const char *license)
2542 license = "unspecified";
2544 if (!license_is_gpl_compatible(license)) {
2545 if (!test_taint(TAINT_PROPRIETARY_MODULE))
2546 pr_warn("%s: module license '%s' taints kernel.\n",
2547 mod->name, license);
2548 add_taint_module(mod, TAINT_PROPRIETARY_MODULE,
2549 LOCKDEP_NOW_UNRELIABLE);
2553 /* Parse tag=value strings from .modinfo section */
2554 static char *next_string(char *string, unsigned long *secsize)
2556 /* Skip non-zero chars */
2559 if ((*secsize)-- <= 1)
2563 /* Skip any zero padding. */
2564 while (!string[0]) {
2566 if ((*secsize)-- <= 1)
2572 static char *get_next_modinfo(const struct load_info *info, const char *tag,
2576 unsigned int taglen = strlen(tag);
2577 Elf_Shdr *infosec = &info->sechdrs[info->index.info];
2578 unsigned long size = infosec->sh_size;
2581 * get_modinfo() calls made before rewrite_section_headers()
2582 * must use sh_offset, as sh_addr isn't set!
2584 char *modinfo = (char *)info->hdr + infosec->sh_offset;
2587 size -= prev - modinfo;
2588 modinfo = next_string(prev, &size);
2591 for (p = modinfo; p; p = next_string(p, &size)) {
2592 if (strncmp(p, tag, taglen) == 0 && p[taglen] == '=')
2593 return p + taglen + 1;
2598 static char *get_modinfo(const struct load_info *info, const char *tag)
2600 return get_next_modinfo(info, tag, NULL);
2603 static void setup_modinfo(struct module *mod, struct load_info *info)
2605 struct module_attribute *attr;
2608 for (i = 0; (attr = modinfo_attrs[i]); i++) {
2610 attr->setup(mod, get_modinfo(info, attr->attr.name));
2614 static void free_modinfo(struct module *mod)
2616 struct module_attribute *attr;
2619 for (i = 0; (attr = modinfo_attrs[i]); i++) {
2625 #ifdef CONFIG_KALLSYMS
2627 /* Lookup exported symbol in given range of kernel_symbols */
2628 static const struct kernel_symbol *lookup_exported_symbol(const char *name,
2629 const struct kernel_symbol *start,
2630 const struct kernel_symbol *stop)
2632 return bsearch(name, start, stop - start,
2633 sizeof(struct kernel_symbol), cmp_name);
2636 static int is_exported(const char *name, unsigned long value,
2637 const struct module *mod)
2639 const struct kernel_symbol *ks;
2641 ks = lookup_exported_symbol(name, __start___ksymtab, __stop___ksymtab);
2643 ks = lookup_exported_symbol(name, mod->syms, mod->syms + mod->num_syms);
2645 return ks != NULL && kernel_symbol_value(ks) == value;
2649 static char elf_type(const Elf_Sym *sym, const struct load_info *info)
2651 const Elf_Shdr *sechdrs = info->sechdrs;
2653 if (ELF_ST_BIND(sym->st_info) == STB_WEAK) {
2654 if (ELF_ST_TYPE(sym->st_info) == STT_OBJECT)
2659 if (sym->st_shndx == SHN_UNDEF)
2661 if (sym->st_shndx == SHN_ABS || sym->st_shndx == info->index.pcpu)
2663 if (sym->st_shndx >= SHN_LORESERVE)
2665 if (sechdrs[sym->st_shndx].sh_flags & SHF_EXECINSTR)
2667 if (sechdrs[sym->st_shndx].sh_flags & SHF_ALLOC
2668 && sechdrs[sym->st_shndx].sh_type != SHT_NOBITS) {
2669 if (!(sechdrs[sym->st_shndx].sh_flags & SHF_WRITE))
2671 else if (sechdrs[sym->st_shndx].sh_flags & ARCH_SHF_SMALL)
2676 if (sechdrs[sym->st_shndx].sh_type == SHT_NOBITS) {
2677 if (sechdrs[sym->st_shndx].sh_flags & ARCH_SHF_SMALL)
2682 if (strstarts(info->secstrings + sechdrs[sym->st_shndx].sh_name,
2689 static bool is_core_symbol(const Elf_Sym *src, const Elf_Shdr *sechdrs,
2690 unsigned int shnum, unsigned int pcpundx)
2692 const Elf_Shdr *sec;
2694 if (src->st_shndx == SHN_UNDEF
2695 || src->st_shndx >= shnum
2699 #ifdef CONFIG_KALLSYMS_ALL
2700 if (src->st_shndx == pcpundx)
2704 sec = sechdrs + src->st_shndx;
2705 if (!(sec->sh_flags & SHF_ALLOC)
2706 #ifndef CONFIG_KALLSYMS_ALL
2707 || !(sec->sh_flags & SHF_EXECINSTR)
2709 || (sec->sh_entsize & INIT_OFFSET_MASK))
2716 * We only allocate and copy the strings needed by the parts of symtab
2717 * we keep. This is simple, but has the effect of making multiple
2718 * copies of duplicates. We could be more sophisticated, see
2719 * linux-kernel thread starting with
2720 * <73defb5e4bca04a6431392cc341112b1@localhost>.
2722 static void layout_symtab(struct module *mod, struct load_info *info)
2724 Elf_Shdr *symsect = info->sechdrs + info->index.sym;
2725 Elf_Shdr *strsect = info->sechdrs + info->index.str;
2727 unsigned int i, nsrc, ndst, strtab_size = 0;
2729 /* Put symbol section at end of init part of module. */
2730 symsect->sh_flags |= SHF_ALLOC;
2731 symsect->sh_entsize = get_offset(mod, &mod->init_layout.size, symsect,
2732 info->index.sym) | INIT_OFFSET_MASK;
2733 pr_debug("\t%s\n", info->secstrings + symsect->sh_name);
2735 src = (void *)info->hdr + symsect->sh_offset;
2736 nsrc = symsect->sh_size / sizeof(*src);
2738 /* Compute total space required for the core symbols' strtab. */
2739 for (ndst = i = 0; i < nsrc; i++) {
2740 if (i == 0 || is_livepatch_module(mod) ||
2741 is_core_symbol(src+i, info->sechdrs, info->hdr->e_shnum,
2742 info->index.pcpu)) {
2743 strtab_size += strlen(&info->strtab[src[i].st_name])+1;
2748 /* Append room for core symbols at end of core part. */
2749 info->symoffs = ALIGN(mod->core_layout.size, symsect->sh_addralign ?: 1);
2750 info->stroffs = mod->core_layout.size = info->symoffs + ndst * sizeof(Elf_Sym);
2751 mod->core_layout.size += strtab_size;
2752 info->core_typeoffs = mod->core_layout.size;
2753 mod->core_layout.size += ndst * sizeof(char);
2754 mod->core_layout.size = debug_align(mod->core_layout.size);
2756 /* Put string table section at end of init part of module. */
2757 strsect->sh_flags |= SHF_ALLOC;
2758 strsect->sh_entsize = get_offset(mod, &mod->init_layout.size, strsect,
2759 info->index.str) | INIT_OFFSET_MASK;
2760 pr_debug("\t%s\n", info->secstrings + strsect->sh_name);
2762 /* We'll tack temporary mod_kallsyms on the end. */
2763 mod->init_layout.size = ALIGN(mod->init_layout.size,
2764 __alignof__(struct mod_kallsyms));
2765 info->mod_kallsyms_init_off = mod->init_layout.size;
2766 mod->init_layout.size += sizeof(struct mod_kallsyms);
2767 info->init_typeoffs = mod->init_layout.size;
2768 mod->init_layout.size += nsrc * sizeof(char);
2769 mod->init_layout.size = debug_align(mod->init_layout.size);
2773 * We use the full symtab and strtab which layout_symtab arranged to
2774 * be appended to the init section. Later we switch to the cut-down
2777 static void add_kallsyms(struct module *mod, const struct load_info *info)
2779 unsigned int i, ndst;
2783 Elf_Shdr *symsec = &info->sechdrs[info->index.sym];
2785 /* Set up to point into init section. */
2786 mod->kallsyms = mod->init_layout.base + info->mod_kallsyms_init_off;
2788 mod->kallsyms->symtab = (void *)symsec->sh_addr;
2789 mod->kallsyms->num_symtab = symsec->sh_size / sizeof(Elf_Sym);
2790 /* Make sure we get permanent strtab: don't use info->strtab. */
2791 mod->kallsyms->strtab = (void *)info->sechdrs[info->index.str].sh_addr;
2792 mod->kallsyms->typetab = mod->init_layout.base + info->init_typeoffs;
2795 * Now populate the cut down core kallsyms for after init
2796 * and set types up while we still have access to sections.
2798 mod->core_kallsyms.symtab = dst = mod->core_layout.base + info->symoffs;
2799 mod->core_kallsyms.strtab = s = mod->core_layout.base + info->stroffs;
2800 mod->core_kallsyms.typetab = mod->core_layout.base + info->core_typeoffs;
2801 src = mod->kallsyms->symtab;
2802 for (ndst = i = 0; i < mod->kallsyms->num_symtab; i++) {
2803 mod->kallsyms->typetab[i] = elf_type(src + i, info);
2804 if (i == 0 || is_livepatch_module(mod) ||
2805 is_core_symbol(src+i, info->sechdrs, info->hdr->e_shnum,
2806 info->index.pcpu)) {
2807 mod->core_kallsyms.typetab[ndst] =
2808 mod->kallsyms->typetab[i];
2810 dst[ndst++].st_name = s - mod->core_kallsyms.strtab;
2811 s += strlcpy(s, &mod->kallsyms->strtab[src[i].st_name],
2815 mod->core_kallsyms.num_symtab = ndst;
2818 static inline void layout_symtab(struct module *mod, struct load_info *info)
2822 static void add_kallsyms(struct module *mod, const struct load_info *info)
2825 #endif /* CONFIG_KALLSYMS */
2827 static void dynamic_debug_setup(struct module *mod, struct _ddebug *debug, unsigned int num)
2831 ddebug_add_module(debug, num, mod->name);
2834 static void dynamic_debug_remove(struct module *mod, struct _ddebug *debug)
2837 ddebug_remove_module(mod->name);
2840 void * __weak module_alloc(unsigned long size)
2842 return __vmalloc_node_range(size, 1, VMALLOC_START, VMALLOC_END,
2843 GFP_KERNEL, PAGE_KERNEL_EXEC, VM_FLUSH_RESET_PERMS,
2844 NUMA_NO_NODE, __builtin_return_address(0));
2847 bool __weak module_init_section(const char *name)
2849 return strstarts(name, ".init");
2852 bool __weak module_exit_section(const char *name)
2854 return strstarts(name, ".exit");
2857 #ifdef CONFIG_DEBUG_KMEMLEAK
2858 static void kmemleak_load_module(const struct module *mod,
2859 const struct load_info *info)
2863 /* only scan the sections containing data */
2864 kmemleak_scan_area(mod, sizeof(struct module), GFP_KERNEL);
2866 for (i = 1; i < info->hdr->e_shnum; i++) {
2867 /* Scan all writable sections that's not executable */
2868 if (!(info->sechdrs[i].sh_flags & SHF_ALLOC) ||
2869 !(info->sechdrs[i].sh_flags & SHF_WRITE) ||
2870 (info->sechdrs[i].sh_flags & SHF_EXECINSTR))
2873 kmemleak_scan_area((void *)info->sechdrs[i].sh_addr,
2874 info->sechdrs[i].sh_size, GFP_KERNEL);
2878 static inline void kmemleak_load_module(const struct module *mod,
2879 const struct load_info *info)
2884 #ifdef CONFIG_MODULE_SIG
2885 static int module_sig_check(struct load_info *info, int flags)
2888 const unsigned long markerlen = sizeof(MODULE_SIG_STRING) - 1;
2890 const void *mod = info->hdr;
2893 * Require flags == 0, as a module with version information
2894 * removed is no longer the module that was signed
2897 info->len > markerlen &&
2898 memcmp(mod + info->len - markerlen, MODULE_SIG_STRING, markerlen) == 0) {
2899 /* We truncate the module to discard the signature */
2900 info->len -= markerlen;
2901 err = mod_verify_sig(mod, info);
2903 info->sig_ok = true;
2909 * We don't permit modules to be loaded into the trusted kernels
2910 * without a valid signature on them, but if we're not enforcing,
2911 * certain errors are non-fatal.
2915 reason = "unsigned module";
2918 reason = "module with unsupported crypto";
2921 reason = "module with unavailable key";
2926 * All other errors are fatal, including lack of memory,
2927 * unparseable signatures, and signature check failures --
2928 * even if signatures aren't required.
2933 if (is_module_sig_enforced()) {
2934 pr_notice("Loading of %s is rejected\n", reason);
2935 return -EKEYREJECTED;
2938 return security_locked_down(LOCKDOWN_MODULE_SIGNATURE);
2940 #else /* !CONFIG_MODULE_SIG */
2941 static int module_sig_check(struct load_info *info, int flags)
2945 #endif /* !CONFIG_MODULE_SIG */
2947 static int validate_section_offset(struct load_info *info, Elf_Shdr *shdr)
2949 unsigned long secend;
2952 * Check for both overflow and offset/size being
2955 secend = shdr->sh_offset + shdr->sh_size;
2956 if (secend < shdr->sh_offset || secend > info->len)
2963 * Sanity checks against invalid binaries, wrong arch, weird elf version.
2965 * Also do basic validity checks against section offsets and sizes, the
2966 * section name string table, and the indices used for it (sh_name).
2968 static int elf_validity_check(struct load_info *info)
2971 Elf_Shdr *shdr, *strhdr;
2974 if (info->len < sizeof(*(info->hdr)))
2977 if (memcmp(info->hdr->e_ident, ELFMAG, SELFMAG) != 0
2978 || info->hdr->e_type != ET_REL
2979 || !elf_check_arch(info->hdr)
2980 || info->hdr->e_shentsize != sizeof(Elf_Shdr))
2984 * e_shnum is 16 bits, and sizeof(Elf_Shdr) is
2985 * known and small. So e_shnum * sizeof(Elf_Shdr)
2986 * will not overflow unsigned long on any platform.
2988 if (info->hdr->e_shoff >= info->len
2989 || (info->hdr->e_shnum * sizeof(Elf_Shdr) >
2990 info->len - info->hdr->e_shoff))
2993 info->sechdrs = (void *)info->hdr + info->hdr->e_shoff;
2996 * Verify if the section name table index is valid.
2998 if (info->hdr->e_shstrndx == SHN_UNDEF
2999 || info->hdr->e_shstrndx >= info->hdr->e_shnum)
3002 strhdr = &info->sechdrs[info->hdr->e_shstrndx];
3003 err = validate_section_offset(info, strhdr);
3008 * The section name table must be NUL-terminated, as required
3009 * by the spec. This makes strcmp and pr_* calls that access
3010 * strings in the section safe.
3012 info->secstrings = (void *)info->hdr + strhdr->sh_offset;
3013 if (info->secstrings[strhdr->sh_size - 1] != '\0')
3017 * The code assumes that section 0 has a length of zero and
3018 * an addr of zero, so check for it.
3020 if (info->sechdrs[0].sh_type != SHT_NULL
3021 || info->sechdrs[0].sh_size != 0
3022 || info->sechdrs[0].sh_addr != 0)
3025 for (i = 1; i < info->hdr->e_shnum; i++) {
3026 shdr = &info->sechdrs[i];
3027 switch (shdr->sh_type) {
3032 if (shdr->sh_link == SHN_UNDEF
3033 || shdr->sh_link >= info->hdr->e_shnum)
3037 err = validate_section_offset(info, shdr);
3039 pr_err("Invalid ELF section in module (section %u type %u)\n",
3044 if (shdr->sh_flags & SHF_ALLOC) {
3045 if (shdr->sh_name >= strhdr->sh_size) {
3046 pr_err("Invalid ELF section name in module (section %u type %u)\n",
3058 #define COPY_CHUNK_SIZE (16*PAGE_SIZE)
3060 static int copy_chunked_from_user(void *dst, const void __user *usrc, unsigned long len)
3063 unsigned long n = min(len, COPY_CHUNK_SIZE);
3065 if (copy_from_user(dst, usrc, n) != 0)
3075 #ifdef CONFIG_LIVEPATCH
3076 static int check_modinfo_livepatch(struct module *mod, struct load_info *info)
3078 if (get_modinfo(info, "livepatch")) {
3080 add_taint_module(mod, TAINT_LIVEPATCH, LOCKDEP_STILL_OK);
3081 pr_notice_once("%s: tainting kernel with TAINT_LIVEPATCH\n",
3087 #else /* !CONFIG_LIVEPATCH */
3088 static int check_modinfo_livepatch(struct module *mod, struct load_info *info)
3090 if (get_modinfo(info, "livepatch")) {
3091 pr_err("%s: module is marked as livepatch module, but livepatch support is disabled",
3098 #endif /* CONFIG_LIVEPATCH */
3100 static void check_modinfo_retpoline(struct module *mod, struct load_info *info)
3102 if (retpoline_module_ok(get_modinfo(info, "retpoline")))
3105 pr_warn("%s: loading module not compiled with retpoline compiler.\n",
3109 /* Sets info->hdr and info->len. */
3110 static int copy_module_from_user(const void __user *umod, unsigned long len,
3111 struct load_info *info)
3116 if (info->len < sizeof(*(info->hdr)))
3119 err = security_kernel_load_data(LOADING_MODULE, true);
3123 /* Suck in entire file: we'll want most of it. */
3124 info->hdr = __vmalloc(info->len, GFP_KERNEL | __GFP_NOWARN);
3128 if (copy_chunked_from_user(info->hdr, umod, info->len) != 0) {
3133 err = security_kernel_post_load_data((char *)info->hdr, info->len,
3134 LOADING_MODULE, "init_module");
3142 static void free_copy(struct load_info *info)
3147 static int rewrite_section_headers(struct load_info *info, int flags)
3151 /* This should always be true, but let's be sure. */
3152 info->sechdrs[0].sh_addr = 0;
3154 for (i = 1; i < info->hdr->e_shnum; i++) {
3155 Elf_Shdr *shdr = &info->sechdrs[i];
3158 * Mark all sections sh_addr with their address in the
3161 shdr->sh_addr = (size_t)info->hdr + shdr->sh_offset;
3163 #ifndef CONFIG_MODULE_UNLOAD
3164 /* Don't load .exit sections */
3165 if (module_exit_section(info->secstrings+shdr->sh_name))
3166 shdr->sh_flags &= ~(unsigned long)SHF_ALLOC;
3170 /* Track but don't keep modinfo and version sections. */
3171 info->sechdrs[info->index.vers].sh_flags &= ~(unsigned long)SHF_ALLOC;
3172 info->sechdrs[info->index.info].sh_flags &= ~(unsigned long)SHF_ALLOC;
3178 * Set up our basic convenience variables (pointers to section headers,
3179 * search for module section index etc), and do some basic section
3182 * Set info->mod to the temporary copy of the module in info->hdr. The final one
3183 * will be allocated in move_module().
3185 static int setup_load_info(struct load_info *info, int flags)
3189 /* Try to find a name early so we can log errors with a module name */
3190 info->index.info = find_sec(info, ".modinfo");
3191 if (info->index.info)
3192 info->name = get_modinfo(info, "name");
3194 /* Find internal symbols and strings. */
3195 for (i = 1; i < info->hdr->e_shnum; i++) {
3196 if (info->sechdrs[i].sh_type == SHT_SYMTAB) {
3197 info->index.sym = i;
3198 info->index.str = info->sechdrs[i].sh_link;
3199 info->strtab = (char *)info->hdr
3200 + info->sechdrs[info->index.str].sh_offset;
3205 if (info->index.sym == 0) {
3206 pr_warn("%s: module has no symbols (stripped?)\n",
3207 info->name ?: "(missing .modinfo section or name field)");
3211 info->index.mod = find_sec(info, ".gnu.linkonce.this_module");
3212 if (!info->index.mod) {
3213 pr_warn("%s: No module found in object\n",
3214 info->name ?: "(missing .modinfo section or name field)");
3217 /* This is temporary: point mod into copy of data. */
3218 info->mod = (void *)info->hdr + info->sechdrs[info->index.mod].sh_offset;
3221 * If we didn't load the .modinfo 'name' field earlier, fall back to
3222 * on-disk struct mod 'name' field.
3225 info->name = info->mod->name;
3227 if (flags & MODULE_INIT_IGNORE_MODVERSIONS)
3228 info->index.vers = 0; /* Pretend no __versions section! */
3230 info->index.vers = find_sec(info, "__versions");
3232 info->index.pcpu = find_pcpusec(info);
3237 static int check_modinfo(struct module *mod, struct load_info *info, int flags)
3239 const char *modmagic = get_modinfo(info, "vermagic");
3242 if (flags & MODULE_INIT_IGNORE_VERMAGIC)
3245 /* This is allowed: modprobe --force will invalidate it. */
3247 err = try_to_force_load(mod, "bad vermagic");
3250 } else if (!same_magic(modmagic, vermagic, info->index.vers)) {
3251 pr_err("%s: version magic '%s' should be '%s'\n",
3252 info->name, modmagic, vermagic);
3256 if (!get_modinfo(info, "intree")) {
3257 if (!test_taint(TAINT_OOT_MODULE))
3258 pr_warn("%s: loading out-of-tree module taints kernel.\n",
3260 add_taint_module(mod, TAINT_OOT_MODULE, LOCKDEP_STILL_OK);
3263 check_modinfo_retpoline(mod, info);
3265 if (get_modinfo(info, "staging")) {
3266 add_taint_module(mod, TAINT_CRAP, LOCKDEP_STILL_OK);
3267 pr_warn("%s: module is from the staging directory, the quality "
3268 "is unknown, you have been warned.\n", mod->name);
3271 err = check_modinfo_livepatch(mod, info);
3275 /* Set up license info based on the info section */
3276 set_license(mod, get_modinfo(info, "license"));
3281 static int find_module_sections(struct module *mod, struct load_info *info)
3283 mod->kp = section_objs(info, "__param",
3284 sizeof(*mod->kp), &mod->num_kp);
3285 mod->syms = section_objs(info, "__ksymtab",
3286 sizeof(*mod->syms), &mod->num_syms);
3287 mod->crcs = section_addr(info, "__kcrctab");
3288 mod->gpl_syms = section_objs(info, "__ksymtab_gpl",
3289 sizeof(*mod->gpl_syms),
3290 &mod->num_gpl_syms);
3291 mod->gpl_crcs = section_addr(info, "__kcrctab_gpl");
3293 #ifdef CONFIG_UNUSED_SYMBOLS
3294 mod->unused_syms = section_objs(info, "__ksymtab_unused",
3295 sizeof(*mod->unused_syms),
3296 &mod->num_unused_syms);
3297 mod->unused_crcs = section_addr(info, "__kcrctab_unused");
3298 mod->unused_gpl_syms = section_objs(info, "__ksymtab_unused_gpl",
3299 sizeof(*mod->unused_gpl_syms),
3300 &mod->num_unused_gpl_syms);
3301 mod->unused_gpl_crcs = section_addr(info, "__kcrctab_unused_gpl");
3303 #ifdef CONFIG_CONSTRUCTORS
3304 mod->ctors = section_objs(info, ".ctors",
3305 sizeof(*mod->ctors), &mod->num_ctors);
3307 mod->ctors = section_objs(info, ".init_array",
3308 sizeof(*mod->ctors), &mod->num_ctors);
3309 else if (find_sec(info, ".init_array")) {
3311 * This shouldn't happen with same compiler and binutils
3312 * building all parts of the module.
3314 pr_warn("%s: has both .ctors and .init_array.\n",
3320 mod->noinstr_text_start = section_objs(info, ".noinstr.text", 1,
3321 &mod->noinstr_text_size);
3323 #ifdef CONFIG_TRACEPOINTS
3324 mod->tracepoints_ptrs = section_objs(info, "__tracepoints_ptrs",
3325 sizeof(*mod->tracepoints_ptrs),
3326 &mod->num_tracepoints);
3328 #ifdef CONFIG_TREE_SRCU
3329 mod->srcu_struct_ptrs = section_objs(info, "___srcu_struct_ptrs",
3330 sizeof(*mod->srcu_struct_ptrs),
3331 &mod->num_srcu_structs);
3333 #ifdef CONFIG_BPF_EVENTS
3334 mod->bpf_raw_events = section_objs(info, "__bpf_raw_tp_map",
3335 sizeof(*mod->bpf_raw_events),
3336 &mod->num_bpf_raw_events);
3338 #ifdef CONFIG_DEBUG_INFO_BTF_MODULES
3339 mod->btf_data = any_section_objs(info, ".BTF", 1, &mod->btf_data_size);
3341 #ifdef CONFIG_JUMP_LABEL
3342 mod->jump_entries = section_objs(info, "__jump_table",
3343 sizeof(*mod->jump_entries),
3344 &mod->num_jump_entries);
3346 #ifdef CONFIG_EVENT_TRACING
3347 mod->trace_events = section_objs(info, "_ftrace_events",
3348 sizeof(*mod->trace_events),
3349 &mod->num_trace_events);
3350 mod->trace_evals = section_objs(info, "_ftrace_eval_map",
3351 sizeof(*mod->trace_evals),
3352 &mod->num_trace_evals);
3354 #ifdef CONFIG_TRACING
3355 mod->trace_bprintk_fmt_start = section_objs(info, "__trace_printk_fmt",
3356 sizeof(*mod->trace_bprintk_fmt_start),
3357 &mod->num_trace_bprintk_fmt);
3359 #ifdef CONFIG_FTRACE_MCOUNT_RECORD
3360 /* sechdrs[0].sh_size is always zero */
3361 mod->ftrace_callsites = section_objs(info, FTRACE_CALLSITE_SECTION,
3362 sizeof(*mod->ftrace_callsites),
3363 &mod->num_ftrace_callsites);
3365 #ifdef CONFIG_FUNCTION_ERROR_INJECTION
3366 mod->ei_funcs = section_objs(info, "_error_injection_whitelist",
3367 sizeof(*mod->ei_funcs),
3368 &mod->num_ei_funcs);
3370 #ifdef CONFIG_KPROBES
3371 mod->kprobes_text_start = section_objs(info, ".kprobes.text", 1,
3372 &mod->kprobes_text_size);
3373 mod->kprobe_blacklist = section_objs(info, "_kprobe_blacklist",
3374 sizeof(unsigned long),
3375 &mod->num_kprobe_blacklist);
3377 #ifdef CONFIG_HAVE_STATIC_CALL_INLINE
3378 mod->static_call_sites = section_objs(info, ".static_call_sites",
3379 sizeof(*mod->static_call_sites),
3380 &mod->num_static_call_sites);
3382 mod->extable = section_objs(info, "__ex_table",
3383 sizeof(*mod->extable), &mod->num_exentries);
3385 if (section_addr(info, "__obsparm"))
3386 pr_warn("%s: Ignoring obsolete parameters\n", mod->name);
3388 info->debug = section_objs(info, "__dyndbg",
3389 sizeof(*info->debug), &info->num_debug);
3394 static int move_module(struct module *mod, struct load_info *info)
3399 /* Do the allocs. */
3400 ptr = module_alloc(mod->core_layout.size);
3402 * The pointer to this block is stored in the module structure
3403 * which is inside the block. Just mark it as not being a
3406 kmemleak_not_leak(ptr);
3410 memset(ptr, 0, mod->core_layout.size);
3411 mod->core_layout.base = ptr;
3413 if (mod->init_layout.size) {
3414 ptr = module_alloc(mod->init_layout.size);
3416 * The pointer to this block is stored in the module structure
3417 * which is inside the block. This block doesn't need to be
3418 * scanned as it contains data and code that will be freed
3419 * after the module is initialized.
3421 kmemleak_ignore(ptr);
3423 module_memfree(mod->core_layout.base);
3426 memset(ptr, 0, mod->init_layout.size);
3427 mod->init_layout.base = ptr;
3429 mod->init_layout.base = NULL;
3431 /* Transfer each section which specifies SHF_ALLOC */
3432 pr_debug("final section addresses:\n");
3433 for (i = 0; i < info->hdr->e_shnum; i++) {
3435 Elf_Shdr *shdr = &info->sechdrs[i];
3437 if (!(shdr->sh_flags & SHF_ALLOC))
3440 if (shdr->sh_entsize & INIT_OFFSET_MASK)
3441 dest = mod->init_layout.base
3442 + (shdr->sh_entsize & ~INIT_OFFSET_MASK);
3444 dest = mod->core_layout.base + shdr->sh_entsize;
3446 if (shdr->sh_type != SHT_NOBITS)
3447 memcpy(dest, (void *)shdr->sh_addr, shdr->sh_size);
3448 /* Update sh_addr to point to copy in image. */
3449 shdr->sh_addr = (unsigned long)dest;
3450 pr_debug("\t0x%lx %s\n",
3451 (long)shdr->sh_addr, info->secstrings + shdr->sh_name);
3457 static int check_module_license_and_versions(struct module *mod)
3459 int prev_taint = test_taint(TAINT_PROPRIETARY_MODULE);
3462 * ndiswrapper is under GPL by itself, but loads proprietary modules.
3463 * Don't use add_taint_module(), as it would prevent ndiswrapper from
3464 * using GPL-only symbols it needs.
3466 if (strcmp(mod->name, "ndiswrapper") == 0)
3467 add_taint(TAINT_PROPRIETARY_MODULE, LOCKDEP_NOW_UNRELIABLE);
3469 /* driverloader was caught wrongly pretending to be under GPL */
3470 if (strcmp(mod->name, "driverloader") == 0)
3471 add_taint_module(mod, TAINT_PROPRIETARY_MODULE,
3472 LOCKDEP_NOW_UNRELIABLE);
3474 /* lve claims to be GPL but upstream won't provide source */
3475 if (strcmp(mod->name, "lve") == 0)
3476 add_taint_module(mod, TAINT_PROPRIETARY_MODULE,
3477 LOCKDEP_NOW_UNRELIABLE);
3479 if (!prev_taint && test_taint(TAINT_PROPRIETARY_MODULE))
3480 pr_warn("%s: module license taints kernel.\n", mod->name);
3482 #ifdef CONFIG_MODVERSIONS
3483 if ((mod->num_syms && !mod->crcs)
3484 || (mod->num_gpl_syms && !mod->gpl_crcs)
3485 #ifdef CONFIG_UNUSED_SYMBOLS
3486 || (mod->num_unused_syms && !mod->unused_crcs)
3487 || (mod->num_unused_gpl_syms && !mod->unused_gpl_crcs)
3490 return try_to_force_load(mod,
3491 "no versions for exported symbols");
3497 static void flush_module_icache(const struct module *mod)
3500 * Flush the instruction cache, since we've played with text.
3501 * Do it before processing of module parameters, so the module
3502 * can provide parameter accessor functions of its own.
3504 if (mod->init_layout.base)
3505 flush_icache_range((unsigned long)mod->init_layout.base,
3506 (unsigned long)mod->init_layout.base
3507 + mod->init_layout.size);
3508 flush_icache_range((unsigned long)mod->core_layout.base,
3509 (unsigned long)mod->core_layout.base + mod->core_layout.size);
3512 int __weak module_frob_arch_sections(Elf_Ehdr *hdr,
3520 /* module_blacklist is a comma-separated list of module names */
3521 static char *module_blacklist;
3522 static bool blacklisted(const char *module_name)
3527 if (!module_blacklist)
3530 for (p = module_blacklist; *p; p += len) {
3531 len = strcspn(p, ",");
3532 if (strlen(module_name) == len && !memcmp(module_name, p, len))
3539 core_param(module_blacklist, module_blacklist, charp, 0400);
3541 static struct module *layout_and_allocate(struct load_info *info, int flags)
3547 err = check_modinfo(info->mod, info, flags);
3549 return ERR_PTR(err);
3551 /* Allow arches to frob section contents and sizes. */
3552 err = module_frob_arch_sections(info->hdr, info->sechdrs,
3553 info->secstrings, info->mod);
3555 return ERR_PTR(err);
3557 err = module_enforce_rwx_sections(info->hdr, info->sechdrs,
3558 info->secstrings, info->mod);
3560 return ERR_PTR(err);
3562 /* We will do a special allocation for per-cpu sections later. */
3563 info->sechdrs[info->index.pcpu].sh_flags &= ~(unsigned long)SHF_ALLOC;
3566 * Mark ro_after_init section with SHF_RO_AFTER_INIT so that
3567 * layout_sections() can put it in the right place.
3568 * Note: ro_after_init sections also have SHF_{WRITE,ALLOC} set.
3570 ndx = find_sec(info, ".data..ro_after_init");
3572 info->sechdrs[ndx].sh_flags |= SHF_RO_AFTER_INIT;
3574 * Mark the __jump_table section as ro_after_init as well: these data
3575 * structures are never modified, with the exception of entries that
3576 * refer to code in the __init section, which are annotated as such
3577 * at module load time.
3579 ndx = find_sec(info, "__jump_table");
3581 info->sechdrs[ndx].sh_flags |= SHF_RO_AFTER_INIT;
3584 * Determine total sizes, and put offsets in sh_entsize. For now
3585 * this is done generically; there doesn't appear to be any
3586 * special cases for the architectures.
3588 layout_sections(info->mod, info);
3589 layout_symtab(info->mod, info);
3591 /* Allocate and move to the final place */
3592 err = move_module(info->mod, info);
3594 return ERR_PTR(err);
3596 /* Module has been copied to its final place now: return it. */
3597 mod = (void *)info->sechdrs[info->index.mod].sh_addr;
3598 kmemleak_load_module(mod, info);
3602 /* mod is no longer valid after this! */
3603 static void module_deallocate(struct module *mod, struct load_info *info)
3605 percpu_modfree(mod);
3606 module_arch_freeing_init(mod);
3607 module_memfree(mod->init_layout.base);
3608 module_memfree(mod->core_layout.base);
3611 int __weak module_finalize(const Elf_Ehdr *hdr,
3612 const Elf_Shdr *sechdrs,
3618 static int post_relocation(struct module *mod, const struct load_info *info)
3620 /* Sort exception table now relocations are done. */
3621 sort_extable(mod->extable, mod->extable + mod->num_exentries);
3623 /* Copy relocated percpu area over. */
3624 percpu_modcopy(mod, (void *)info->sechdrs[info->index.pcpu].sh_addr,
3625 info->sechdrs[info->index.pcpu].sh_size);
3627 /* Setup kallsyms-specific fields. */
3628 add_kallsyms(mod, info);
3630 /* Arch-specific module finalizing. */
3631 return module_finalize(info->hdr, info->sechdrs, mod);
3634 /* Is this module of this name done loading? No locks held. */
3635 static bool finished_loading(const char *name)
3641 * The module_mutex should not be a heavily contended lock;
3642 * if we get the occasional sleep here, we'll go an extra iteration
3643 * in the wait_event_interruptible(), which is harmless.
3645 sched_annotate_sleep();
3646 mutex_lock(&module_mutex);
3647 mod = find_module_all(name, strlen(name), true);
3648 ret = !mod || mod->state == MODULE_STATE_LIVE;
3649 mutex_unlock(&module_mutex);
3654 /* Call module constructors. */
3655 static void do_mod_ctors(struct module *mod)
3657 #ifdef CONFIG_CONSTRUCTORS
3660 for (i = 0; i < mod->num_ctors; i++)
3665 /* For freeing module_init on success, in case kallsyms traversing */
3666 struct mod_initfree {
3667 struct llist_node node;
3671 static void do_free_init(struct work_struct *w)
3673 struct llist_node *pos, *n, *list;
3674 struct mod_initfree *initfree;
3676 list = llist_del_all(&init_free_list);
3680 llist_for_each_safe(pos, n, list) {
3681 initfree = container_of(pos, struct mod_initfree, node);
3682 module_memfree(initfree->module_init);
3688 * This is where the real work happens.
3690 * Keep it uninlined to provide a reliable breakpoint target, e.g. for the gdb
3691 * helper command 'lx-symbols'.
3693 static noinline int do_init_module(struct module *mod)
3696 struct mod_initfree *freeinit;
3698 freeinit = kmalloc(sizeof(*freeinit), GFP_KERNEL);
3703 freeinit->module_init = mod->init_layout.base;
3706 * We want to find out whether @mod uses async during init. Clear
3707 * PF_USED_ASYNC. async_schedule*() will set it.
3709 current->flags &= ~PF_USED_ASYNC;
3712 /* Start the module */
3713 if (mod->init != NULL)
3714 ret = do_one_initcall(mod->init);
3716 goto fail_free_freeinit;
3719 pr_warn("%s: '%s'->init suspiciously returned %d, it should "
3720 "follow 0/-E convention\n"
3721 "%s: loading module anyway...\n",
3722 __func__, mod->name, ret, __func__);
3726 /* Now it's a first class citizen! */
3727 mod->state = MODULE_STATE_LIVE;
3728 blocking_notifier_call_chain(&module_notify_list,
3729 MODULE_STATE_LIVE, mod);
3731 /* Delay uevent until module has finished its init routine */
3732 kobject_uevent(&mod->mkobj.kobj, KOBJ_ADD);
3735 * We need to finish all async code before the module init sequence
3736 * is done. This has potential to deadlock. For example, a newly
3737 * detected block device can trigger request_module() of the
3738 * default iosched from async probing task. Once userland helper
3739 * reaches here, async_synchronize_full() will wait on the async
3740 * task waiting on request_module() and deadlock.
3742 * This deadlock is avoided by perfomring async_synchronize_full()
3743 * iff module init queued any async jobs. This isn't a full
3744 * solution as it will deadlock the same if module loading from
3745 * async jobs nests more than once; however, due to the various
3746 * constraints, this hack seems to be the best option for now.
3747 * Please refer to the following thread for details.
3749 * http://thread.gmane.org/gmane.linux.kernel/1420814
3751 if (!mod->async_probe_requested && (current->flags & PF_USED_ASYNC))
3752 async_synchronize_full();
3754 ftrace_free_mem(mod, mod->init_layout.base, mod->init_layout.base +
3755 mod->init_layout.size);
3756 mutex_lock(&module_mutex);
3757 /* Drop initial reference. */
3759 trim_init_extable(mod);
3760 #ifdef CONFIG_KALLSYMS
3761 /* Switch to core kallsyms now init is done: kallsyms may be walking! */
3762 rcu_assign_pointer(mod->kallsyms, &mod->core_kallsyms);
3764 module_enable_ro(mod, true);
3765 mod_tree_remove_init(mod);
3766 module_arch_freeing_init(mod);
3767 mod->init_layout.base = NULL;
3768 mod->init_layout.size = 0;
3769 mod->init_layout.ro_size = 0;
3770 mod->init_layout.ro_after_init_size = 0;
3771 mod->init_layout.text_size = 0;
3772 #ifdef CONFIG_DEBUG_INFO_BTF_MODULES
3773 /* .BTF is not SHF_ALLOC and will get removed, so sanitize pointer */
3774 mod->btf_data = NULL;
3777 * We want to free module_init, but be aware that kallsyms may be
3778 * walking this with preempt disabled. In all the failure paths, we
3779 * call synchronize_rcu(), but we don't want to slow down the success
3780 * path. module_memfree() cannot be called in an interrupt, so do the
3781 * work and call synchronize_rcu() in a work queue.
3783 * Note that module_alloc() on most architectures creates W+X page
3784 * mappings which won't be cleaned up until do_free_init() runs. Any
3785 * code such as mark_rodata_ro() which depends on those mappings to
3786 * be cleaned up needs to sync with the queued work - ie
3789 if (llist_add(&freeinit->node, &init_free_list))
3790 schedule_work(&init_free_wq);
3792 mutex_unlock(&module_mutex);
3793 wake_up_all(&module_wq);
3800 /* Try to protect us from buggy refcounters. */
3801 mod->state = MODULE_STATE_GOING;
3804 blocking_notifier_call_chain(&module_notify_list,
3805 MODULE_STATE_GOING, mod);
3806 klp_module_going(mod);
3807 ftrace_release_mod(mod);
3809 wake_up_all(&module_wq);
3813 static int may_init_module(void)
3815 if (!capable(CAP_SYS_MODULE) || modules_disabled)
3822 * We try to place it in the list now to make sure it's unique before
3823 * we dedicate too many resources. In particular, temporary percpu
3824 * memory exhaustion.
3826 static int add_unformed_module(struct module *mod)
3831 mod->state = MODULE_STATE_UNFORMED;
3834 mutex_lock(&module_mutex);
3835 old = find_module_all(mod->name, strlen(mod->name), true);
3837 if (old->state != MODULE_STATE_LIVE) {
3838 /* Wait in case it fails to load. */
3839 mutex_unlock(&module_mutex);
3840 err = wait_event_interruptible(module_wq,
3841 finished_loading(mod->name));
3849 mod_update_bounds(mod);
3850 list_add_rcu(&mod->list, &modules);
3851 mod_tree_insert(mod);
3855 mutex_unlock(&module_mutex);
3860 static int complete_formation(struct module *mod, struct load_info *info)
3864 mutex_lock(&module_mutex);
3866 /* Find duplicate symbols (must be called under lock). */
3867 err = verify_exported_symbols(mod);
3871 /* This relies on module_mutex for list integrity. */
3872 module_bug_finalize(info->hdr, info->sechdrs, mod);
3874 module_enable_ro(mod, false);
3875 module_enable_nx(mod);
3876 module_enable_x(mod);
3879 * Mark state as coming so strong_try_module_get() ignores us,
3880 * but kallsyms etc. can see us.
3882 mod->state = MODULE_STATE_COMING;
3883 mutex_unlock(&module_mutex);
3888 mutex_unlock(&module_mutex);
3892 static int prepare_coming_module(struct module *mod)
3896 ftrace_module_enable(mod);
3897 err = klp_module_coming(mod);
3901 err = blocking_notifier_call_chain_robust(&module_notify_list,
3902 MODULE_STATE_COMING, MODULE_STATE_GOING, mod);
3903 err = notifier_to_errno(err);
3905 klp_module_going(mod);
3910 static int unknown_module_param_cb(char *param, char *val, const char *modname,
3913 struct module *mod = arg;
3916 if (strcmp(param, "async_probe") == 0) {
3917 mod->async_probe_requested = true;
3921 /* Check for magic 'dyndbg' arg */
3922 ret = ddebug_dyndbg_module_param_cb(param, val, modname);
3924 pr_warn("%s: unknown parameter '%s' ignored\n", modname, param);
3929 * Allocate and load the module: note that size of section 0 is always
3930 * zero, and we rely on this for optional sections.
3932 static int load_module(struct load_info *info, const char __user *uargs,
3940 * Do the signature check (if any) first. All that
3941 * the signature check needs is info->len, it does
3942 * not need any of the section info. That can be
3943 * set up later. This will minimize the chances
3944 * of a corrupt module causing problems before
3945 * we even get to the signature check.
3947 * The check will also adjust info->len by stripping
3948 * off the sig length at the end of the module, making
3949 * checks against info->len more correct.
3951 err = module_sig_check(info, flags);
3956 * Do basic sanity checks against the ELF header and
3959 err = elf_validity_check(info);
3961 pr_err("Module has invalid ELF structures\n");
3966 * Everything checks out, so set up the section info
3967 * in the info structure.
3969 err = setup_load_info(info, flags);
3974 * Now that we know we have the correct module name, check
3975 * if it's blacklisted.
3977 if (blacklisted(info->name)) {
3979 pr_err("Module %s is blacklisted\n", info->name);
3983 err = rewrite_section_headers(info, flags);
3987 /* Check module struct version now, before we try to use module. */
3988 if (!check_modstruct_version(info, info->mod)) {
3993 /* Figure out module layout, and allocate all the memory. */
3994 mod = layout_and_allocate(info, flags);
4000 audit_log_kern_module(mod->name);
4002 /* Reserve our place in the list. */
4003 err = add_unformed_module(mod);
4007 #ifdef CONFIG_MODULE_SIG
4008 mod->sig_ok = info->sig_ok;
4010 pr_notice_once("%s: module verification failed: signature "
4011 "and/or required key missing - tainting "
4012 "kernel\n", mod->name);
4013 add_taint_module(mod, TAINT_UNSIGNED_MODULE, LOCKDEP_STILL_OK);
4017 /* To avoid stressing percpu allocator, do this once we're unique. */
4018 err = percpu_modalloc(mod, info);
4022 /* Now module is in final location, initialize linked lists, etc. */
4023 err = module_unload_init(mod);
4027 init_param_lock(mod);
4030 * Now we've got everything in the final locations, we can
4031 * find optional sections.
4033 err = find_module_sections(mod, info);
4037 err = check_module_license_and_versions(mod);
4041 /* Set up MODINFO_ATTR fields */
4042 setup_modinfo(mod, info);
4044 /* Fix up syms, so that st_value is a pointer to location. */
4045 err = simplify_symbols(mod, info);
4049 err = apply_relocations(mod, info);
4053 err = post_relocation(mod, info);
4057 flush_module_icache(mod);
4059 /* Now copy in args */
4060 mod->args = strndup_user(uargs, ~0UL >> 1);
4061 if (IS_ERR(mod->args)) {
4062 err = PTR_ERR(mod->args);
4063 goto free_arch_cleanup;
4066 dynamic_debug_setup(mod, info->debug, info->num_debug);
4068 /* Ftrace init must be called in the MODULE_STATE_UNFORMED state */
4069 ftrace_module_init(mod);
4071 /* Finally it's fully formed, ready to start executing. */
4072 err = complete_formation(mod, info);
4074 goto ddebug_cleanup;
4076 err = prepare_coming_module(mod);
4080 /* Module is ready to execute: parsing args may do that. */
4081 after_dashes = parse_args(mod->name, mod->args, mod->kp, mod->num_kp,
4083 unknown_module_param_cb);
4084 if (IS_ERR(after_dashes)) {
4085 err = PTR_ERR(after_dashes);
4086 goto coming_cleanup;
4087 } else if (after_dashes) {
4088 pr_warn("%s: parameters '%s' after `--' ignored\n",
4089 mod->name, after_dashes);
4092 /* Link in to sysfs. */
4093 err = mod_sysfs_setup(mod, info, mod->kp, mod->num_kp);
4095 goto coming_cleanup;
4097 if (is_livepatch_module(mod)) {
4098 err = copy_module_elf(mod, info);
4103 /* Get rid of temporary copy. */
4107 trace_module_load(mod);
4109 return do_init_module(mod);
4112 mod_sysfs_teardown(mod);
4114 mod->state = MODULE_STATE_GOING;
4115 destroy_params(mod->kp, mod->num_kp);
4116 blocking_notifier_call_chain(&module_notify_list,
4117 MODULE_STATE_GOING, mod);
4118 klp_module_going(mod);
4120 mod->state = MODULE_STATE_GOING;
4121 /* module_bug_cleanup needs module_mutex protection */
4122 mutex_lock(&module_mutex);
4123 module_bug_cleanup(mod);
4124 mutex_unlock(&module_mutex);
4127 ftrace_release_mod(mod);
4128 dynamic_debug_remove(mod, info->debug);
4132 module_arch_cleanup(mod);
4136 module_unload_free(mod);
4138 mutex_lock(&module_mutex);
4139 /* Unlink carefully: kallsyms could be walking list. */
4140 list_del_rcu(&mod->list);
4141 mod_tree_remove(mod);
4142 wake_up_all(&module_wq);
4143 /* Wait for RCU-sched synchronizing before releasing mod->list. */
4145 mutex_unlock(&module_mutex);
4147 /* Free lock-classes; relies on the preceding sync_rcu() */
4148 lockdep_free_key_range(mod->core_layout.base, mod->core_layout.size);
4150 module_deallocate(mod, info);
4156 SYSCALL_DEFINE3(init_module, void __user *, umod,
4157 unsigned long, len, const char __user *, uargs)
4160 struct load_info info = { };
4162 err = may_init_module();
4166 pr_debug("init_module: umod=%p, len=%lu, uargs=%p\n",
4169 err = copy_module_from_user(umod, len, &info);
4173 return load_module(&info, uargs, 0);
4176 SYSCALL_DEFINE3(finit_module, int, fd, const char __user *, uargs, int, flags)
4178 struct load_info info = { };
4182 err = may_init_module();
4186 pr_debug("finit_module: fd=%d, uargs=%p, flags=%i\n", fd, uargs, flags);
4188 if (flags & ~(MODULE_INIT_IGNORE_MODVERSIONS
4189 |MODULE_INIT_IGNORE_VERMAGIC))
4192 err = kernel_read_file_from_fd(fd, 0, &hdr, INT_MAX, NULL,
4199 return load_module(&info, uargs, flags);
4202 static inline int within(unsigned long addr, void *start, unsigned long size)
4204 return ((void *)addr >= start && (void *)addr < start + size);
4207 #ifdef CONFIG_KALLSYMS
4209 * This ignores the intensely annoying "mapping symbols" found
4210 * in ARM ELF files: $a, $t and $d.
4212 static inline int is_arm_mapping_symbol(const char *str)
4214 if (str[0] == '.' && str[1] == 'L')
4216 return str[0] == '$' && strchr("axtd", str[1])
4217 && (str[2] == '\0' || str[2] == '.');
4220 static const char *kallsyms_symbol_name(struct mod_kallsyms *kallsyms, unsigned int symnum)
4222 return kallsyms->strtab + kallsyms->symtab[symnum].st_name;
4226 * Given a module and address, find the corresponding symbol and return its name
4227 * while providing its size and offset if needed.
4229 static const char *find_kallsyms_symbol(struct module *mod,
4231 unsigned long *size,
4232 unsigned long *offset)
4234 unsigned int i, best = 0;
4235 unsigned long nextval, bestval;
4236 struct mod_kallsyms *kallsyms = rcu_dereference_sched(mod->kallsyms);
4238 /* At worse, next value is at end of module */
4239 if (within_module_init(addr, mod))
4240 nextval = (unsigned long)mod->init_layout.base+mod->init_layout.text_size;
4242 nextval = (unsigned long)mod->core_layout.base+mod->core_layout.text_size;
4244 bestval = kallsyms_symbol_value(&kallsyms->symtab[best]);
4247 * Scan for closest preceding symbol, and next symbol. (ELF
4248 * starts real symbols at 1).
4250 for (i = 1; i < kallsyms->num_symtab; i++) {
4251 const Elf_Sym *sym = &kallsyms->symtab[i];
4252 unsigned long thisval = kallsyms_symbol_value(sym);
4254 if (sym->st_shndx == SHN_UNDEF)
4258 * We ignore unnamed symbols: they're uninformative
4259 * and inserted at a whim.
4261 if (*kallsyms_symbol_name(kallsyms, i) == '\0'
4262 || is_arm_mapping_symbol(kallsyms_symbol_name(kallsyms, i)))
4265 if (thisval <= addr && thisval > bestval) {
4269 if (thisval > addr && thisval < nextval)
4277 *size = nextval - bestval;
4279 *offset = addr - bestval;
4281 return kallsyms_symbol_name(kallsyms, best);
4284 void * __weak dereference_module_function_descriptor(struct module *mod,
4291 * For kallsyms to ask for address resolution. NULL means not found. Careful
4292 * not to lock to avoid deadlock on oopses, simply disable preemption.
4294 const char *module_address_lookup(unsigned long addr,
4295 unsigned long *size,
4296 unsigned long *offset,
4300 const char *ret = NULL;
4304 mod = __module_address(addr);
4307 *modname = mod->name;
4309 ret = find_kallsyms_symbol(mod, addr, size, offset);
4311 /* Make a copy in here where it's safe */
4313 strncpy(namebuf, ret, KSYM_NAME_LEN - 1);
4321 int lookup_module_symbol_name(unsigned long addr, char *symname)
4326 list_for_each_entry_rcu(mod, &modules, list) {
4327 if (mod->state == MODULE_STATE_UNFORMED)
4329 if (within_module(addr, mod)) {
4332 sym = find_kallsyms_symbol(mod, addr, NULL, NULL);
4336 strlcpy(symname, sym, KSYM_NAME_LEN);
4346 int lookup_module_symbol_attrs(unsigned long addr, unsigned long *size,
4347 unsigned long *offset, char *modname, char *name)
4352 list_for_each_entry_rcu(mod, &modules, list) {
4353 if (mod->state == MODULE_STATE_UNFORMED)
4355 if (within_module(addr, mod)) {
4358 sym = find_kallsyms_symbol(mod, addr, size, offset);
4362 strlcpy(modname, mod->name, MODULE_NAME_LEN);
4364 strlcpy(name, sym, KSYM_NAME_LEN);
4374 int module_get_kallsym(unsigned int symnum, unsigned long *value, char *type,
4375 char *name, char *module_name, int *exported)
4380 list_for_each_entry_rcu(mod, &modules, list) {
4381 struct mod_kallsyms *kallsyms;
4383 if (mod->state == MODULE_STATE_UNFORMED)
4385 kallsyms = rcu_dereference_sched(mod->kallsyms);
4386 if (symnum < kallsyms->num_symtab) {
4387 const Elf_Sym *sym = &kallsyms->symtab[symnum];
4389 *value = kallsyms_symbol_value(sym);
4390 *type = kallsyms->typetab[symnum];
4391 strlcpy(name, kallsyms_symbol_name(kallsyms, symnum), KSYM_NAME_LEN);
4392 strlcpy(module_name, mod->name, MODULE_NAME_LEN);
4393 *exported = is_exported(name, *value, mod);
4397 symnum -= kallsyms->num_symtab;
4403 /* Given a module and name of symbol, find and return the symbol's value */
4404 static unsigned long find_kallsyms_symbol_value(struct module *mod, const char *name)
4407 struct mod_kallsyms *kallsyms = rcu_dereference_sched(mod->kallsyms);
4409 for (i = 0; i < kallsyms->num_symtab; i++) {
4410 const Elf_Sym *sym = &kallsyms->symtab[i];
4412 if (strcmp(name, kallsyms_symbol_name(kallsyms, i)) == 0 &&
4413 sym->st_shndx != SHN_UNDEF)
4414 return kallsyms_symbol_value(sym);
4419 /* Look for this name: can be of form module:name. */
4420 unsigned long module_kallsyms_lookup_name(const char *name)
4424 unsigned long ret = 0;
4426 /* Don't lock: we're in enough trouble already. */
4428 if ((colon = strnchr(name, MODULE_NAME_LEN, ':')) != NULL) {
4429 if ((mod = find_module_all(name, colon - name, false)) != NULL)
4430 ret = find_kallsyms_symbol_value(mod, colon+1);
4432 list_for_each_entry_rcu(mod, &modules, list) {
4433 if (mod->state == MODULE_STATE_UNFORMED)
4435 if ((ret = find_kallsyms_symbol_value(mod, name)) != 0)
4443 #ifdef CONFIG_LIVEPATCH
4444 int module_kallsyms_on_each_symbol(int (*fn)(void *, const char *,
4445 struct module *, unsigned long),
4452 mutex_lock(&module_mutex);
4453 list_for_each_entry(mod, &modules, list) {
4454 /* We hold module_mutex: no need for rcu_dereference_sched */
4455 struct mod_kallsyms *kallsyms = mod->kallsyms;
4457 if (mod->state == MODULE_STATE_UNFORMED)
4459 for (i = 0; i < kallsyms->num_symtab; i++) {
4460 const Elf_Sym *sym = &kallsyms->symtab[i];
4462 if (sym->st_shndx == SHN_UNDEF)
4465 ret = fn(data, kallsyms_symbol_name(kallsyms, i),
4466 mod, kallsyms_symbol_value(sym));
4471 mutex_unlock(&module_mutex);
4474 #endif /* CONFIG_LIVEPATCH */
4475 #endif /* CONFIG_KALLSYMS */
4477 /* Maximum number of characters written by module_flags() */
4478 #define MODULE_FLAGS_BUF_SIZE (TAINT_FLAGS_COUNT + 4)
4480 /* Keep in sync with MODULE_FLAGS_BUF_SIZE !!! */
4481 static char *module_flags(struct module *mod, char *buf)
4485 BUG_ON(mod->state == MODULE_STATE_UNFORMED);
4487 mod->state == MODULE_STATE_GOING ||
4488 mod->state == MODULE_STATE_COMING) {
4490 bx += module_flags_taint(mod, buf + bx);
4491 /* Show a - for module-is-being-unloaded */
4492 if (mod->state == MODULE_STATE_GOING)
4494 /* Show a + for module-is-being-loaded */
4495 if (mod->state == MODULE_STATE_COMING)
4504 #ifdef CONFIG_PROC_FS
4505 /* Called by the /proc file system to return a list of modules. */
4506 static void *m_start(struct seq_file *m, loff_t *pos)
4508 mutex_lock(&module_mutex);
4509 return seq_list_start(&modules, *pos);
4512 static void *m_next(struct seq_file *m, void *p, loff_t *pos)
4514 return seq_list_next(p, &modules, pos);
4517 static void m_stop(struct seq_file *m, void *p)
4519 mutex_unlock(&module_mutex);
4522 static int m_show(struct seq_file *m, void *p)
4524 struct module *mod = list_entry(p, struct module, list);
4525 char buf[MODULE_FLAGS_BUF_SIZE];
4528 /* We always ignore unformed modules. */
4529 if (mod->state == MODULE_STATE_UNFORMED)
4532 seq_printf(m, "%s %u",
4533 mod->name, mod->init_layout.size + mod->core_layout.size);
4534 print_unload_info(m, mod);
4536 /* Informative for users. */
4537 seq_printf(m, " %s",
4538 mod->state == MODULE_STATE_GOING ? "Unloading" :
4539 mod->state == MODULE_STATE_COMING ? "Loading" :
4541 /* Used by oprofile and other similar tools. */
4542 value = m->private ? NULL : mod->core_layout.base;
4543 seq_printf(m, " 0x%px", value);
4547 seq_printf(m, " %s", module_flags(mod, buf));
4554 * Format: modulename size refcount deps address
4556 * Where refcount is a number or -, and deps is a comma-separated list
4559 static const struct seq_operations modules_op = {
4567 * This also sets the "private" pointer to non-NULL if the
4568 * kernel pointers should be hidden (so you can just test
4569 * "m->private" to see if you should keep the values private).
4571 * We use the same logic as for /proc/kallsyms.
4573 static int modules_open(struct inode *inode, struct file *file)
4575 int err = seq_open(file, &modules_op);
4578 struct seq_file *m = file->private_data;
4579 m->private = kallsyms_show_value(file->f_cred) ? NULL : (void *)8ul;
4585 static const struct proc_ops modules_proc_ops = {
4586 .proc_flags = PROC_ENTRY_PERMANENT,
4587 .proc_open = modules_open,
4588 .proc_read = seq_read,
4589 .proc_lseek = seq_lseek,
4590 .proc_release = seq_release,
4593 static int __init proc_modules_init(void)
4595 proc_create("modules", 0, NULL, &modules_proc_ops);
4598 module_init(proc_modules_init);
4601 /* Given an address, look for it in the module exception tables. */
4602 const struct exception_table_entry *search_module_extables(unsigned long addr)
4604 const struct exception_table_entry *e = NULL;
4608 mod = __module_address(addr);
4612 if (!mod->num_exentries)
4615 e = search_extable(mod->extable,
4622 * Now, if we found one, we are running inside it now, hence
4623 * we cannot unload the module, hence no refcnt needed.
4629 * is_module_address() - is this address inside a module?
4630 * @addr: the address to check.
4632 * See is_module_text_address() if you simply want to see if the address
4633 * is code (not data).
4635 bool is_module_address(unsigned long addr)
4640 ret = __module_address(addr) != NULL;
4647 * __module_address() - get the module which contains an address.
4648 * @addr: the address.
4650 * Must be called with preempt disabled or module mutex held so that
4651 * module doesn't get freed during this.
4653 struct module *__module_address(unsigned long addr)
4657 if (addr < module_addr_min || addr > module_addr_max)
4660 module_assert_mutex_or_preempt();
4662 mod = mod_find(addr);
4664 BUG_ON(!within_module(addr, mod));
4665 if (mod->state == MODULE_STATE_UNFORMED)
4672 * is_module_text_address() - is this address inside module code?
4673 * @addr: the address to check.
4675 * See is_module_address() if you simply want to see if the address is
4676 * anywhere in a module. See kernel_text_address() for testing if an
4677 * address corresponds to kernel or module code.
4679 bool is_module_text_address(unsigned long addr)
4684 ret = __module_text_address(addr) != NULL;
4691 * __module_text_address() - get the module whose code contains an address.
4692 * @addr: the address.
4694 * Must be called with preempt disabled or module mutex held so that
4695 * module doesn't get freed during this.
4697 struct module *__module_text_address(unsigned long addr)
4699 struct module *mod = __module_address(addr);
4701 /* Make sure it's within the text section. */
4702 if (!within(addr, mod->init_layout.base, mod->init_layout.text_size)
4703 && !within(addr, mod->core_layout.base, mod->core_layout.text_size))
4709 /* Don't grab lock, we're oopsing. */
4710 void print_modules(void)
4713 char buf[MODULE_FLAGS_BUF_SIZE];
4715 printk(KERN_DEFAULT "Modules linked in:");
4716 /* Most callers should already have preempt disabled, but make sure */
4718 list_for_each_entry_rcu(mod, &modules, list) {
4719 if (mod->state == MODULE_STATE_UNFORMED)
4721 pr_cont(" %s%s", mod->name, module_flags(mod, buf));
4724 if (last_unloaded_module[0])
4725 pr_cont(" [last unloaded: %s]", last_unloaded_module);
4729 #ifdef CONFIG_MODVERSIONS
4731 * Generate the signature for all relevant module structures here.
4732 * If these change, we don't want to try to parse the module.
4734 void module_layout(struct module *mod,
4735 struct modversion_info *ver,
4736 struct kernel_param *kp,
4737 struct kernel_symbol *ks,
4738 struct tracepoint * const *tp)
4741 EXPORT_SYMBOL(module_layout);