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.
8 #define INCLUDE_VERMAGIC
10 #include <linux/export.h>
11 #include <linux/extable.h>
12 #include <linux/moduleloader.h>
13 #include <linux/module_signature.h>
14 #include <linux/trace_events.h>
15 #include <linux/init.h>
16 #include <linux/kallsyms.h>
17 #include <linux/file.h>
19 #include <linux/sysfs.h>
20 #include <linux/kernel.h>
21 #include <linux/kernel_read_file.h>
22 #include <linux/slab.h>
23 #include <linux/vmalloc.h>
24 #include <linux/elf.h>
25 #include <linux/proc_fs.h>
26 #include <linux/security.h>
27 #include <linux/seq_file.h>
28 #include <linux/syscalls.h>
29 #include <linux/fcntl.h>
30 #include <linux/rcupdate.h>
31 #include <linux/capability.h>
32 #include <linux/cpu.h>
33 #include <linux/moduleparam.h>
34 #include <linux/errno.h>
35 #include <linux/err.h>
36 #include <linux/vermagic.h>
37 #include <linux/notifier.h>
38 #include <linux/sched.h>
39 #include <linux/device.h>
40 #include <linux/string.h>
41 #include <linux/mutex.h>
42 #include <linux/rculist.h>
43 #include <linux/uaccess.h>
44 #include <asm/cacheflush.h>
45 #include <linux/set_memory.h>
46 #include <asm/mmu_context.h>
47 #include <linux/license.h>
48 #include <asm/sections.h>
49 #include <linux/tracepoint.h>
50 #include <linux/ftrace.h>
51 #include <linux/livepatch.h>
52 #include <linux/async.h>
53 #include <linux/percpu.h>
54 #include <linux/kmemleak.h>
55 #include <linux/jump_label.h>
56 #include <linux/pfn.h>
57 #include <linux/bsearch.h>
58 #include <linux/dynamic_debug.h>
59 #include <linux/audit.h>
60 #include <uapi/linux/module.h>
61 #include "module-internal.h"
63 #define CREATE_TRACE_POINTS
64 #include <trace/events/module.h>
66 #ifndef ARCH_SHF_SMALL
67 #define ARCH_SHF_SMALL 0
71 * Modules' sections will be aligned on page boundaries
72 * to ensure complete separation of code and data, but
73 * only when CONFIG_ARCH_HAS_STRICT_MODULE_RWX=y
75 #ifdef CONFIG_ARCH_HAS_STRICT_MODULE_RWX
76 # define debug_align(X) ALIGN(X, PAGE_SIZE)
78 # define debug_align(X) (X)
81 /* If this is set, the section belongs in the init part of the module */
82 #define INIT_OFFSET_MASK (1UL << (BITS_PER_LONG-1))
86 * 1) List of modules (also safely readable with preempt_disable),
87 * 2) module_use links,
88 * 3) module_addr_min/module_addr_max.
89 * (delete and add uses RCU list operations). */
90 DEFINE_MUTEX(module_mutex);
91 EXPORT_SYMBOL_GPL(module_mutex);
92 static LIST_HEAD(modules);
94 /* Work queue for freeing init sections in success case */
95 static struct work_struct init_free_wq;
96 static struct 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(void)
260 lockdep_assert_held(&module_mutex);
263 static void module_assert_mutex_or_preempt(void)
265 #ifdef CONFIG_LOCKDEP
266 if (unlikely(!debug_locks))
269 WARN_ON_ONCE(!rcu_read_lock_sched_held() &&
270 !lockdep_is_held(&module_mutex));
274 static bool sig_enforce = IS_ENABLED(CONFIG_MODULE_SIG_FORCE);
275 module_param(sig_enforce, bool_enable_only, 0644);
278 * Export sig_enforce kernel cmdline parameter to allow other subsystems rely
279 * on that instead of directly to CONFIG_MODULE_SIG_FORCE config.
281 bool is_module_sig_enforced(void)
285 EXPORT_SYMBOL(is_module_sig_enforced);
287 void set_module_sig_enforced(void)
292 /* Block module loading/unloading? */
293 int modules_disabled = 0;
294 core_param(nomodule, modules_disabled, bint, 0);
296 /* Waiting for a module to finish initializing? */
297 static DECLARE_WAIT_QUEUE_HEAD(module_wq);
299 static BLOCKING_NOTIFIER_HEAD(module_notify_list);
301 int register_module_notifier(struct notifier_block *nb)
303 return blocking_notifier_chain_register(&module_notify_list, nb);
305 EXPORT_SYMBOL(register_module_notifier);
307 int unregister_module_notifier(struct notifier_block *nb)
309 return blocking_notifier_chain_unregister(&module_notify_list, nb);
311 EXPORT_SYMBOL(unregister_module_notifier);
314 * We require a truly strong try_module_get(): 0 means success.
315 * Otherwise an error is returned due to ongoing or failed
316 * initialization etc.
318 static inline int strong_try_module_get(struct module *mod)
320 BUG_ON(mod && mod->state == MODULE_STATE_UNFORMED);
321 if (mod && mod->state == MODULE_STATE_COMING)
323 if (try_module_get(mod))
329 static inline void add_taint_module(struct module *mod, unsigned flag,
330 enum lockdep_ok lockdep_ok)
332 add_taint(flag, lockdep_ok);
333 set_bit(flag, &mod->taints);
337 * A thread that wants to hold a reference to a module only while it
338 * is running can call this to safely exit. nfsd and lockd use this.
340 void __noreturn __module_put_and_exit(struct module *mod, long code)
345 EXPORT_SYMBOL(__module_put_and_exit);
347 /* Find a module section: 0 means not found. */
348 static unsigned int find_sec(const struct load_info *info, const char *name)
352 for (i = 1; i < info->hdr->e_shnum; i++) {
353 Elf_Shdr *shdr = &info->sechdrs[i];
354 /* Alloc bit cleared means "ignore it." */
355 if ((shdr->sh_flags & SHF_ALLOC)
356 && strcmp(info->secstrings + shdr->sh_name, name) == 0)
362 /* Find a module section, or NULL. */
363 static void *section_addr(const struct load_info *info, const char *name)
365 /* Section 0 has sh_addr 0. */
366 return (void *)info->sechdrs[find_sec(info, name)].sh_addr;
369 /* Find a module section, or NULL. Fill in number of "objects" in section. */
370 static void *section_objs(const struct load_info *info,
375 unsigned int sec = find_sec(info, name);
377 /* Section 0 has sh_addr 0 and sh_size 0. */
378 *num = info->sechdrs[sec].sh_size / object_size;
379 return (void *)info->sechdrs[sec].sh_addr;
382 /* Provided by the linker */
383 extern const struct kernel_symbol __start___ksymtab[];
384 extern const struct kernel_symbol __stop___ksymtab[];
385 extern const struct kernel_symbol __start___ksymtab_gpl[];
386 extern const struct kernel_symbol __stop___ksymtab_gpl[];
387 extern const struct kernel_symbol __start___ksymtab_gpl_future[];
388 extern const struct kernel_symbol __stop___ksymtab_gpl_future[];
389 extern const s32 __start___kcrctab[];
390 extern const s32 __start___kcrctab_gpl[];
391 extern const s32 __start___kcrctab_gpl_future[];
392 #ifdef CONFIG_UNUSED_SYMBOLS
393 extern const struct kernel_symbol __start___ksymtab_unused[];
394 extern const struct kernel_symbol __stop___ksymtab_unused[];
395 extern const struct kernel_symbol __start___ksymtab_unused_gpl[];
396 extern const struct kernel_symbol __stop___ksymtab_unused_gpl[];
397 extern const s32 __start___kcrctab_unused[];
398 extern const s32 __start___kcrctab_unused_gpl[];
401 #ifndef CONFIG_MODVERSIONS
402 #define symversion(base, idx) NULL
404 #define symversion(base, idx) ((base != NULL) ? ((base) + (idx)) : NULL)
407 static bool each_symbol_in_section(const struct symsearch *arr,
408 unsigned int arrsize,
409 struct module *owner,
410 bool (*fn)(const struct symsearch *syms,
411 struct module *owner,
417 for (j = 0; j < arrsize; j++) {
418 if (fn(&arr[j], owner, data))
425 /* Returns true as soon as fn returns true, otherwise false. */
426 static bool each_symbol_section(bool (*fn)(const struct symsearch *arr,
427 struct module *owner,
432 static const struct symsearch arr[] = {
433 { __start___ksymtab, __stop___ksymtab, __start___kcrctab,
434 NOT_GPL_ONLY, false },
435 { __start___ksymtab_gpl, __stop___ksymtab_gpl,
436 __start___kcrctab_gpl,
438 { __start___ksymtab_gpl_future, __stop___ksymtab_gpl_future,
439 __start___kcrctab_gpl_future,
440 WILL_BE_GPL_ONLY, false },
441 #ifdef CONFIG_UNUSED_SYMBOLS
442 { __start___ksymtab_unused, __stop___ksymtab_unused,
443 __start___kcrctab_unused,
444 NOT_GPL_ONLY, true },
445 { __start___ksymtab_unused_gpl, __stop___ksymtab_unused_gpl,
446 __start___kcrctab_unused_gpl,
451 module_assert_mutex_or_preempt();
453 if (each_symbol_in_section(arr, ARRAY_SIZE(arr), NULL, fn, data))
456 list_for_each_entry_rcu(mod, &modules, list,
457 lockdep_is_held(&module_mutex)) {
458 struct symsearch arr[] = {
459 { mod->syms, mod->syms + mod->num_syms, mod->crcs,
460 NOT_GPL_ONLY, false },
461 { mod->gpl_syms, mod->gpl_syms + mod->num_gpl_syms,
464 { mod->gpl_future_syms,
465 mod->gpl_future_syms + mod->num_gpl_future_syms,
466 mod->gpl_future_crcs,
467 WILL_BE_GPL_ONLY, false },
468 #ifdef CONFIG_UNUSED_SYMBOLS
470 mod->unused_syms + mod->num_unused_syms,
472 NOT_GPL_ONLY, true },
473 { mod->unused_gpl_syms,
474 mod->unused_gpl_syms + mod->num_unused_gpl_syms,
475 mod->unused_gpl_crcs,
480 if (mod->state == MODULE_STATE_UNFORMED)
483 if (each_symbol_in_section(arr, ARRAY_SIZE(arr), mod, fn, data))
489 struct find_symbol_arg {
496 struct module *owner;
498 const struct kernel_symbol *sym;
499 enum mod_license license;
502 static bool check_exported_symbol(const struct symsearch *syms,
503 struct module *owner,
504 unsigned int symnum, void *data)
506 struct find_symbol_arg *fsa = data;
509 if (syms->license == GPL_ONLY)
511 if (syms->license == WILL_BE_GPL_ONLY && fsa->warn) {
512 pr_warn("Symbol %s is being used by a non-GPL module, "
513 "which will not be allowed in the future\n",
518 #ifdef CONFIG_UNUSED_SYMBOLS
519 if (syms->unused && fsa->warn) {
520 pr_warn("Symbol %s is marked as UNUSED, however this module is "
521 "using it.\n", fsa->name);
522 pr_warn("This symbol will go away in the future.\n");
523 pr_warn("Please evaluate if this is the right api to use and "
524 "if it really is, submit a report to the linux kernel "
525 "mailing list together with submitting your code for "
531 fsa->crc = symversion(syms->crcs, symnum);
532 fsa->sym = &syms->start[symnum];
533 fsa->license = syms->license;
537 static unsigned long kernel_symbol_value(const struct kernel_symbol *sym)
539 #ifdef CONFIG_HAVE_ARCH_PREL32_RELOCATIONS
540 return (unsigned long)offset_to_ptr(&sym->value_offset);
546 static const char *kernel_symbol_name(const struct kernel_symbol *sym)
548 #ifdef CONFIG_HAVE_ARCH_PREL32_RELOCATIONS
549 return offset_to_ptr(&sym->name_offset);
555 static const char *kernel_symbol_namespace(const struct kernel_symbol *sym)
557 #ifdef CONFIG_HAVE_ARCH_PREL32_RELOCATIONS
558 if (!sym->namespace_offset)
560 return offset_to_ptr(&sym->namespace_offset);
562 return sym->namespace;
566 static int cmp_name(const void *name, const void *sym)
568 return strcmp(name, kernel_symbol_name(sym));
571 static bool find_exported_symbol_in_section(const struct symsearch *syms,
572 struct module *owner,
575 struct find_symbol_arg *fsa = data;
576 struct kernel_symbol *sym;
578 sym = bsearch(fsa->name, syms->start, syms->stop - syms->start,
579 sizeof(struct kernel_symbol), cmp_name);
581 if (sym != NULL && check_exported_symbol(syms, owner,
582 sym - syms->start, data))
588 /* Find an exported symbol and return it, along with, (optional) crc and
589 * (optional) module which owns it. Needs preempt disabled or module_mutex. */
590 static const struct kernel_symbol *find_symbol(const char *name,
591 struct module **owner,
593 enum mod_license *license,
597 struct find_symbol_arg fsa;
603 if (each_symbol_section(find_exported_symbol_in_section, &fsa)) {
609 *license = fsa.license;
613 pr_debug("Failed to find symbol %s\n", name);
618 * Search for module by name: must hold module_mutex (or preempt disabled
619 * for read-only access).
621 static struct module *find_module_all(const char *name, size_t len,
626 module_assert_mutex_or_preempt();
628 list_for_each_entry_rcu(mod, &modules, list,
629 lockdep_is_held(&module_mutex)) {
630 if (!even_unformed && mod->state == MODULE_STATE_UNFORMED)
632 if (strlen(mod->name) == len && !memcmp(mod->name, name, len))
638 struct module *find_module(const char *name)
640 module_assert_mutex();
641 return find_module_all(name, strlen(name), false);
643 EXPORT_SYMBOL_GPL(find_module);
647 static inline void __percpu *mod_percpu(struct module *mod)
652 static int percpu_modalloc(struct module *mod, struct load_info *info)
654 Elf_Shdr *pcpusec = &info->sechdrs[info->index.pcpu];
655 unsigned long align = pcpusec->sh_addralign;
657 if (!pcpusec->sh_size)
660 if (align > PAGE_SIZE) {
661 pr_warn("%s: per-cpu alignment %li > %li\n",
662 mod->name, align, PAGE_SIZE);
666 mod->percpu = __alloc_reserved_percpu(pcpusec->sh_size, align);
668 pr_warn("%s: Could not allocate %lu bytes percpu data\n",
669 mod->name, (unsigned long)pcpusec->sh_size);
672 mod->percpu_size = pcpusec->sh_size;
676 static void percpu_modfree(struct module *mod)
678 free_percpu(mod->percpu);
681 static unsigned int find_pcpusec(struct load_info *info)
683 return find_sec(info, ".data..percpu");
686 static void percpu_modcopy(struct module *mod,
687 const void *from, unsigned long size)
691 for_each_possible_cpu(cpu)
692 memcpy(per_cpu_ptr(mod->percpu, cpu), from, size);
695 bool __is_module_percpu_address(unsigned long addr, unsigned long *can_addr)
702 list_for_each_entry_rcu(mod, &modules, list) {
703 if (mod->state == MODULE_STATE_UNFORMED)
705 if (!mod->percpu_size)
707 for_each_possible_cpu(cpu) {
708 void *start = per_cpu_ptr(mod->percpu, cpu);
709 void *va = (void *)addr;
711 if (va >= start && va < start + mod->percpu_size) {
713 *can_addr = (unsigned long) (va - start);
714 *can_addr += (unsigned long)
715 per_cpu_ptr(mod->percpu,
729 * is_module_percpu_address - test whether address is from module static percpu
730 * @addr: address to test
732 * Test whether @addr belongs to module static percpu area.
735 * %true if @addr is from module static percpu area
737 bool is_module_percpu_address(unsigned long addr)
739 return __is_module_percpu_address(addr, NULL);
742 #else /* ... !CONFIG_SMP */
744 static inline void __percpu *mod_percpu(struct module *mod)
748 static int percpu_modalloc(struct module *mod, struct load_info *info)
750 /* UP modules shouldn't have this section: ENOMEM isn't quite right */
751 if (info->sechdrs[info->index.pcpu].sh_size != 0)
755 static inline void percpu_modfree(struct module *mod)
758 static unsigned int find_pcpusec(struct load_info *info)
762 static inline void percpu_modcopy(struct module *mod,
763 const void *from, unsigned long size)
765 /* pcpusec should be 0, and size of that section should be 0. */
768 bool is_module_percpu_address(unsigned long addr)
773 bool __is_module_percpu_address(unsigned long addr, unsigned long *can_addr)
778 #endif /* CONFIG_SMP */
780 #define MODINFO_ATTR(field) \
781 static void setup_modinfo_##field(struct module *mod, const char *s) \
783 mod->field = kstrdup(s, GFP_KERNEL); \
785 static ssize_t show_modinfo_##field(struct module_attribute *mattr, \
786 struct module_kobject *mk, char *buffer) \
788 return scnprintf(buffer, PAGE_SIZE, "%s\n", mk->mod->field); \
790 static int modinfo_##field##_exists(struct module *mod) \
792 return mod->field != NULL; \
794 static void free_modinfo_##field(struct module *mod) \
799 static struct module_attribute modinfo_##field = { \
800 .attr = { .name = __stringify(field), .mode = 0444 }, \
801 .show = show_modinfo_##field, \
802 .setup = setup_modinfo_##field, \
803 .test = modinfo_##field##_exists, \
804 .free = free_modinfo_##field, \
807 MODINFO_ATTR(version);
808 MODINFO_ATTR(srcversion);
810 static char last_unloaded_module[MODULE_NAME_LEN+1];
812 #ifdef CONFIG_MODULE_UNLOAD
814 EXPORT_TRACEPOINT_SYMBOL(module_get);
816 /* MODULE_REF_BASE is the base reference count by kmodule loader. */
817 #define MODULE_REF_BASE 1
819 /* Init the unload section of the module. */
820 static int module_unload_init(struct module *mod)
823 * Initialize reference counter to MODULE_REF_BASE.
824 * refcnt == 0 means module is going.
826 atomic_set(&mod->refcnt, MODULE_REF_BASE);
828 INIT_LIST_HEAD(&mod->source_list);
829 INIT_LIST_HEAD(&mod->target_list);
831 /* Hold reference count during initialization. */
832 atomic_inc(&mod->refcnt);
837 /* Does a already use b? */
838 static int already_uses(struct module *a, struct module *b)
840 struct module_use *use;
842 list_for_each_entry(use, &b->source_list, source_list) {
843 if (use->source == a) {
844 pr_debug("%s uses %s!\n", a->name, b->name);
848 pr_debug("%s does not use %s!\n", a->name, b->name);
854 * - we add 'a' as a "source", 'b' as a "target" of module use
855 * - the module_use is added to the list of 'b' sources (so
856 * 'b' can walk the list to see who sourced them), and of 'a'
857 * targets (so 'a' can see what modules it targets).
859 static int add_module_usage(struct module *a, struct module *b)
861 struct module_use *use;
863 pr_debug("Allocating new usage for %s.\n", a->name);
864 use = kmalloc(sizeof(*use), GFP_ATOMIC);
870 list_add(&use->source_list, &b->source_list);
871 list_add(&use->target_list, &a->target_list);
875 /* Module a uses b: caller needs module_mutex() */
876 static int ref_module(struct module *a, struct module *b)
880 if (b == NULL || already_uses(a, b))
883 /* If module isn't available, we fail. */
884 err = strong_try_module_get(b);
888 err = add_module_usage(a, b);
896 /* Clear the unload stuff of the module. */
897 static void module_unload_free(struct module *mod)
899 struct module_use *use, *tmp;
901 mutex_lock(&module_mutex);
902 list_for_each_entry_safe(use, tmp, &mod->target_list, target_list) {
903 struct module *i = use->target;
904 pr_debug("%s unusing %s\n", mod->name, i->name);
906 list_del(&use->source_list);
907 list_del(&use->target_list);
910 mutex_unlock(&module_mutex);
913 #ifdef CONFIG_MODULE_FORCE_UNLOAD
914 static inline int try_force_unload(unsigned int flags)
916 int ret = (flags & O_TRUNC);
918 add_taint(TAINT_FORCED_RMMOD, LOCKDEP_NOW_UNRELIABLE);
922 static inline int try_force_unload(unsigned int flags)
926 #endif /* CONFIG_MODULE_FORCE_UNLOAD */
928 /* Try to release refcount of module, 0 means success. */
929 static int try_release_module_ref(struct module *mod)
933 /* Try to decrement refcnt which we set at loading */
934 ret = atomic_sub_return(MODULE_REF_BASE, &mod->refcnt);
937 /* Someone can put this right now, recover with checking */
938 ret = atomic_add_unless(&mod->refcnt, MODULE_REF_BASE, 0);
943 static int try_stop_module(struct module *mod, int flags, int *forced)
945 /* If it's not unused, quit unless we're forcing. */
946 if (try_release_module_ref(mod) != 0) {
947 *forced = try_force_unload(flags);
952 /* Mark it as dying. */
953 mod->state = MODULE_STATE_GOING;
959 * module_refcount - return the refcount or -1 if unloading
961 * @mod: the module we're checking
964 * -1 if the module is in the process of unloading
965 * otherwise the number of references in the kernel to the module
967 int module_refcount(struct module *mod)
969 return atomic_read(&mod->refcnt) - MODULE_REF_BASE;
971 EXPORT_SYMBOL(module_refcount);
973 /* This exists whether we can unload or not */
974 static void free_module(struct module *mod);
976 SYSCALL_DEFINE2(delete_module, const char __user *, name_user,
980 char name[MODULE_NAME_LEN];
983 if (!capable(CAP_SYS_MODULE) || modules_disabled)
986 if (strncpy_from_user(name, name_user, MODULE_NAME_LEN-1) < 0)
988 name[MODULE_NAME_LEN-1] = '\0';
990 audit_log_kern_module(name);
992 if (mutex_lock_interruptible(&module_mutex) != 0)
995 mod = find_module(name);
1001 if (!list_empty(&mod->source_list)) {
1002 /* Other modules depend on us: get rid of them first. */
1007 /* Doing init or already dying? */
1008 if (mod->state != MODULE_STATE_LIVE) {
1009 /* FIXME: if (force), slam module count damn the torpedoes */
1010 pr_debug("%s already dying\n", mod->name);
1015 /* If it has an init func, it must have an exit func to unload */
1016 if (mod->init && !mod->exit) {
1017 forced = try_force_unload(flags);
1019 /* This module can't be removed */
1025 /* Stop the machine so refcounts can't move and disable module. */
1026 ret = try_stop_module(mod, flags, &forced);
1030 mutex_unlock(&module_mutex);
1031 /* Final destruction now no one is using it. */
1032 if (mod->exit != NULL)
1034 blocking_notifier_call_chain(&module_notify_list,
1035 MODULE_STATE_GOING, mod);
1036 klp_module_going(mod);
1037 ftrace_release_mod(mod);
1039 async_synchronize_full();
1041 /* Store the name of the last unloaded module for diagnostic purposes */
1042 strlcpy(last_unloaded_module, mod->name, sizeof(last_unloaded_module));
1045 /* someone could wait for the module in add_unformed_module() */
1046 wake_up_all(&module_wq);
1049 mutex_unlock(&module_mutex);
1053 static inline void print_unload_info(struct seq_file *m, struct module *mod)
1055 struct module_use *use;
1056 int printed_something = 0;
1058 seq_printf(m, " %i ", module_refcount(mod));
1061 * Always include a trailing , so userspace can differentiate
1062 * between this and the old multi-field proc format.
1064 list_for_each_entry(use, &mod->source_list, source_list) {
1065 printed_something = 1;
1066 seq_printf(m, "%s,", use->source->name);
1069 if (mod->init != NULL && mod->exit == NULL) {
1070 printed_something = 1;
1071 seq_puts(m, "[permanent],");
1074 if (!printed_something)
1078 void __symbol_put(const char *symbol)
1080 struct module *owner;
1083 if (!find_symbol(symbol, &owner, NULL, NULL, true, false))
1088 EXPORT_SYMBOL(__symbol_put);
1090 /* Note this assumes addr is a function, which it currently always is. */
1091 void symbol_put_addr(void *addr)
1093 struct module *modaddr;
1094 unsigned long a = (unsigned long)dereference_function_descriptor(addr);
1096 if (core_kernel_text(a))
1100 * Even though we hold a reference on the module; we still need to
1101 * disable preemption in order to safely traverse the data structure.
1104 modaddr = __module_text_address(a);
1106 module_put(modaddr);
1109 EXPORT_SYMBOL_GPL(symbol_put_addr);
1111 static ssize_t show_refcnt(struct module_attribute *mattr,
1112 struct module_kobject *mk, char *buffer)
1114 return sprintf(buffer, "%i\n", module_refcount(mk->mod));
1117 static struct module_attribute modinfo_refcnt =
1118 __ATTR(refcnt, 0444, show_refcnt, NULL);
1120 void __module_get(struct module *module)
1124 atomic_inc(&module->refcnt);
1125 trace_module_get(module, _RET_IP_);
1129 EXPORT_SYMBOL(__module_get);
1131 bool try_module_get(struct module *module)
1137 /* Note: here, we can fail to get a reference */
1138 if (likely(module_is_live(module) &&
1139 atomic_inc_not_zero(&module->refcnt) != 0))
1140 trace_module_get(module, _RET_IP_);
1148 EXPORT_SYMBOL(try_module_get);
1150 void module_put(struct module *module)
1156 ret = atomic_dec_if_positive(&module->refcnt);
1157 WARN_ON(ret < 0); /* Failed to put refcount */
1158 trace_module_put(module, _RET_IP_);
1162 EXPORT_SYMBOL(module_put);
1164 #else /* !CONFIG_MODULE_UNLOAD */
1165 static inline void print_unload_info(struct seq_file *m, struct module *mod)
1167 /* We don't know the usage count, or what modules are using. */
1168 seq_puts(m, " - -");
1171 static inline void module_unload_free(struct module *mod)
1175 static int ref_module(struct module *a, struct module *b)
1177 return strong_try_module_get(b);
1180 static inline int module_unload_init(struct module *mod)
1184 #endif /* CONFIG_MODULE_UNLOAD */
1186 static size_t module_flags_taint(struct module *mod, char *buf)
1191 for (i = 0; i < TAINT_FLAGS_COUNT; i++) {
1192 if (taint_flags[i].module && test_bit(i, &mod->taints))
1193 buf[l++] = taint_flags[i].c_true;
1199 static ssize_t show_initstate(struct module_attribute *mattr,
1200 struct module_kobject *mk, char *buffer)
1202 const char *state = "unknown";
1204 switch (mk->mod->state) {
1205 case MODULE_STATE_LIVE:
1208 case MODULE_STATE_COMING:
1211 case MODULE_STATE_GOING:
1217 return sprintf(buffer, "%s\n", state);
1220 static struct module_attribute modinfo_initstate =
1221 __ATTR(initstate, 0444, show_initstate, NULL);
1223 static ssize_t store_uevent(struct module_attribute *mattr,
1224 struct module_kobject *mk,
1225 const char *buffer, size_t count)
1229 rc = kobject_synth_uevent(&mk->kobj, buffer, count);
1230 return rc ? rc : count;
1233 struct module_attribute module_uevent =
1234 __ATTR(uevent, 0200, NULL, store_uevent);
1236 static ssize_t show_coresize(struct module_attribute *mattr,
1237 struct module_kobject *mk, char *buffer)
1239 return sprintf(buffer, "%u\n", mk->mod->core_layout.size);
1242 static struct module_attribute modinfo_coresize =
1243 __ATTR(coresize, 0444, show_coresize, NULL);
1245 static ssize_t show_initsize(struct module_attribute *mattr,
1246 struct module_kobject *mk, char *buffer)
1248 return sprintf(buffer, "%u\n", mk->mod->init_layout.size);
1251 static struct module_attribute modinfo_initsize =
1252 __ATTR(initsize, 0444, show_initsize, NULL);
1254 static ssize_t show_taint(struct module_attribute *mattr,
1255 struct module_kobject *mk, char *buffer)
1259 l = module_flags_taint(mk->mod, buffer);
1264 static struct module_attribute modinfo_taint =
1265 __ATTR(taint, 0444, show_taint, NULL);
1267 static struct module_attribute *modinfo_attrs[] = {
1270 &modinfo_srcversion,
1275 #ifdef CONFIG_MODULE_UNLOAD
1281 static const char vermagic[] = VERMAGIC_STRING;
1283 static int try_to_force_load(struct module *mod, const char *reason)
1285 #ifdef CONFIG_MODULE_FORCE_LOAD
1286 if (!test_taint(TAINT_FORCED_MODULE))
1287 pr_warn("%s: %s: kernel tainted.\n", mod->name, reason);
1288 add_taint_module(mod, TAINT_FORCED_MODULE, LOCKDEP_NOW_UNRELIABLE);
1295 #ifdef CONFIG_MODVERSIONS
1297 static u32 resolve_rel_crc(const s32 *crc)
1299 return *(u32 *)((void *)crc + *crc);
1302 static int check_version(const struct load_info *info,
1303 const char *symname,
1307 Elf_Shdr *sechdrs = info->sechdrs;
1308 unsigned int versindex = info->index.vers;
1309 unsigned int i, num_versions;
1310 struct modversion_info *versions;
1312 /* Exporting module didn't supply crcs? OK, we're already tainted. */
1316 /* No versions at all? modprobe --force does this. */
1318 return try_to_force_load(mod, symname) == 0;
1320 versions = (void *) sechdrs[versindex].sh_addr;
1321 num_versions = sechdrs[versindex].sh_size
1322 / sizeof(struct modversion_info);
1324 for (i = 0; i < num_versions; i++) {
1327 if (strcmp(versions[i].name, symname) != 0)
1330 if (IS_ENABLED(CONFIG_MODULE_REL_CRCS))
1331 crcval = resolve_rel_crc(crc);
1334 if (versions[i].crc == crcval)
1336 pr_debug("Found checksum %X vs module %lX\n",
1337 crcval, versions[i].crc);
1341 /* Broken toolchain. Warn once, then let it go.. */
1342 pr_warn_once("%s: no symbol version for %s\n", info->name, symname);
1346 pr_warn("%s: disagrees about version of symbol %s\n",
1347 info->name, symname);
1351 static inline int check_modstruct_version(const struct load_info *info,
1357 * Since this should be found in kernel (which can't be removed), no
1358 * locking is necessary -- use preempt_disable() to placate lockdep.
1361 if (!find_symbol("module_layout", NULL, &crc, NULL, true, false)) {
1366 return check_version(info, "module_layout", mod, crc);
1369 /* First part is kernel version, which we ignore if module has crcs. */
1370 static inline int same_magic(const char *amagic, const char *bmagic,
1374 amagic += strcspn(amagic, " ");
1375 bmagic += strcspn(bmagic, " ");
1377 return strcmp(amagic, bmagic) == 0;
1380 static inline int check_version(const struct load_info *info,
1381 const char *symname,
1388 static inline int check_modstruct_version(const struct load_info *info,
1394 static inline int same_magic(const char *amagic, const char *bmagic,
1397 return strcmp(amagic, bmagic) == 0;
1399 #endif /* CONFIG_MODVERSIONS */
1401 static char *get_modinfo(const struct load_info *info, const char *tag);
1402 static char *get_next_modinfo(const struct load_info *info, const char *tag,
1405 static int verify_namespace_is_imported(const struct load_info *info,
1406 const struct kernel_symbol *sym,
1409 const char *namespace;
1410 char *imported_namespace;
1412 namespace = kernel_symbol_namespace(sym);
1413 if (namespace && namespace[0]) {
1414 imported_namespace = get_modinfo(info, "import_ns");
1415 while (imported_namespace) {
1416 if (strcmp(namespace, imported_namespace) == 0)
1418 imported_namespace = get_next_modinfo(
1419 info, "import_ns", imported_namespace);
1421 #ifdef CONFIG_MODULE_ALLOW_MISSING_NAMESPACE_IMPORTS
1426 "%s: module uses symbol (%s) from namespace %s, but does not import it.\n",
1427 mod->name, kernel_symbol_name(sym), namespace);
1428 #ifndef CONFIG_MODULE_ALLOW_MISSING_NAMESPACE_IMPORTS
1435 static bool inherit_taint(struct module *mod, struct module *owner)
1437 if (!owner || !test_bit(TAINT_PROPRIETARY_MODULE, &owner->taints))
1440 if (mod->using_gplonly_symbols) {
1441 pr_err("%s: module using GPL-only symbols uses symbols from proprietary module %s.\n",
1442 mod->name, owner->name);
1446 if (!test_bit(TAINT_PROPRIETARY_MODULE, &mod->taints)) {
1447 pr_warn("%s: module uses symbols from proprietary module %s, inheriting taint.\n",
1448 mod->name, owner->name);
1449 set_bit(TAINT_PROPRIETARY_MODULE, &mod->taints);
1454 /* Resolve a symbol for this module. I.e. if we find one, record usage. */
1455 static const struct kernel_symbol *resolve_symbol(struct module *mod,
1456 const struct load_info *info,
1460 struct module *owner;
1461 const struct kernel_symbol *sym;
1463 enum mod_license license;
1467 * The module_mutex should not be a heavily contended lock;
1468 * if we get the occasional sleep here, we'll go an extra iteration
1469 * in the wait_event_interruptible(), which is harmless.
1471 sched_annotate_sleep();
1472 mutex_lock(&module_mutex);
1473 sym = find_symbol(name, &owner, &crc, &license,
1474 !(mod->taints & (1 << TAINT_PROPRIETARY_MODULE)), true);
1478 if (license == GPL_ONLY)
1479 mod->using_gplonly_symbols = true;
1481 if (!inherit_taint(mod, owner)) {
1486 if (!check_version(info, name, mod, crc)) {
1487 sym = ERR_PTR(-EINVAL);
1491 err = verify_namespace_is_imported(info, sym, mod);
1497 err = ref_module(mod, owner);
1504 /* We must make copy under the lock if we failed to get ref. */
1505 strncpy(ownername, module_name(owner), MODULE_NAME_LEN);
1507 mutex_unlock(&module_mutex);
1511 static const struct kernel_symbol *
1512 resolve_symbol_wait(struct module *mod,
1513 const struct load_info *info,
1516 const struct kernel_symbol *ksym;
1517 char owner[MODULE_NAME_LEN];
1519 if (wait_event_interruptible_timeout(module_wq,
1520 !IS_ERR(ksym = resolve_symbol(mod, info, name, owner))
1521 || PTR_ERR(ksym) != -EBUSY,
1523 pr_warn("%s: gave up waiting for init of module %s.\n",
1530 * /sys/module/foo/sections stuff
1531 * J. Corbet <corbet@lwn.net>
1535 #ifdef CONFIG_KALLSYMS
1536 static inline bool sect_empty(const Elf_Shdr *sect)
1538 return !(sect->sh_flags & SHF_ALLOC) || sect->sh_size == 0;
1541 struct module_sect_attr {
1542 struct bin_attribute battr;
1543 unsigned long address;
1546 struct module_sect_attrs {
1547 struct attribute_group grp;
1548 unsigned int nsections;
1549 struct module_sect_attr attrs[];
1552 #define MODULE_SECT_READ_SIZE (3 /* "0x", "\n" */ + (BITS_PER_LONG / 4))
1553 static ssize_t module_sect_read(struct file *file, struct kobject *kobj,
1554 struct bin_attribute *battr,
1555 char *buf, loff_t pos, size_t count)
1557 struct module_sect_attr *sattr =
1558 container_of(battr, struct module_sect_attr, battr);
1559 char bounce[MODULE_SECT_READ_SIZE + 1];
1566 * Since we're a binary read handler, we must account for the
1567 * trailing NUL byte that sprintf will write: if "buf" is
1568 * too small to hold the NUL, or the NUL is exactly the last
1569 * byte, the read will look like it got truncated by one byte.
1570 * Since there is no way to ask sprintf nicely to not write
1571 * the NUL, we have to use a bounce buffer.
1573 wrote = scnprintf(bounce, sizeof(bounce), "0x%px\n",
1574 kallsyms_show_value(file->f_cred)
1575 ? (void *)sattr->address : NULL);
1576 count = min(count, wrote);
1577 memcpy(buf, bounce, count);
1582 static void free_sect_attrs(struct module_sect_attrs *sect_attrs)
1584 unsigned int section;
1586 for (section = 0; section < sect_attrs->nsections; section++)
1587 kfree(sect_attrs->attrs[section].battr.attr.name);
1591 static void add_sect_attrs(struct module *mod, const struct load_info *info)
1593 unsigned int nloaded = 0, i, size[2];
1594 struct module_sect_attrs *sect_attrs;
1595 struct module_sect_attr *sattr;
1596 struct bin_attribute **gattr;
1598 /* Count loaded sections and allocate structures */
1599 for (i = 0; i < info->hdr->e_shnum; i++)
1600 if (!sect_empty(&info->sechdrs[i]))
1602 size[0] = ALIGN(struct_size(sect_attrs, attrs, nloaded),
1603 sizeof(sect_attrs->grp.bin_attrs[0]));
1604 size[1] = (nloaded + 1) * sizeof(sect_attrs->grp.bin_attrs[0]);
1605 sect_attrs = kzalloc(size[0] + size[1], GFP_KERNEL);
1606 if (sect_attrs == NULL)
1609 /* Setup section attributes. */
1610 sect_attrs->grp.name = "sections";
1611 sect_attrs->grp.bin_attrs = (void *)sect_attrs + size[0];
1613 sect_attrs->nsections = 0;
1614 sattr = §_attrs->attrs[0];
1615 gattr = §_attrs->grp.bin_attrs[0];
1616 for (i = 0; i < info->hdr->e_shnum; i++) {
1617 Elf_Shdr *sec = &info->sechdrs[i];
1618 if (sect_empty(sec))
1620 sysfs_bin_attr_init(&sattr->battr);
1621 sattr->address = sec->sh_addr;
1622 sattr->battr.attr.name =
1623 kstrdup(info->secstrings + sec->sh_name, GFP_KERNEL);
1624 if (sattr->battr.attr.name == NULL)
1626 sect_attrs->nsections++;
1627 sattr->battr.read = module_sect_read;
1628 sattr->battr.size = MODULE_SECT_READ_SIZE;
1629 sattr->battr.attr.mode = 0400;
1630 *(gattr++) = &(sattr++)->battr;
1634 if (sysfs_create_group(&mod->mkobj.kobj, §_attrs->grp))
1637 mod->sect_attrs = sect_attrs;
1640 free_sect_attrs(sect_attrs);
1643 static void remove_sect_attrs(struct module *mod)
1645 if (mod->sect_attrs) {
1646 sysfs_remove_group(&mod->mkobj.kobj,
1647 &mod->sect_attrs->grp);
1648 /* We are positive that no one is using any sect attrs
1649 * at this point. Deallocate immediately. */
1650 free_sect_attrs(mod->sect_attrs);
1651 mod->sect_attrs = NULL;
1656 * /sys/module/foo/notes/.section.name gives contents of SHT_NOTE sections.
1659 struct module_notes_attrs {
1660 struct kobject *dir;
1662 struct bin_attribute attrs[];
1665 static ssize_t module_notes_read(struct file *filp, struct kobject *kobj,
1666 struct bin_attribute *bin_attr,
1667 char *buf, loff_t pos, size_t count)
1670 * The caller checked the pos and count against our size.
1672 memcpy(buf, bin_attr->private + pos, count);
1676 static void free_notes_attrs(struct module_notes_attrs *notes_attrs,
1679 if (notes_attrs->dir) {
1681 sysfs_remove_bin_file(notes_attrs->dir,
1682 ¬es_attrs->attrs[i]);
1683 kobject_put(notes_attrs->dir);
1688 static void add_notes_attrs(struct module *mod, const struct load_info *info)
1690 unsigned int notes, loaded, i;
1691 struct module_notes_attrs *notes_attrs;
1692 struct bin_attribute *nattr;
1694 /* failed to create section attributes, so can't create notes */
1695 if (!mod->sect_attrs)
1698 /* Count notes sections and allocate structures. */
1700 for (i = 0; i < info->hdr->e_shnum; i++)
1701 if (!sect_empty(&info->sechdrs[i]) &&
1702 (info->sechdrs[i].sh_type == SHT_NOTE))
1708 notes_attrs = kzalloc(struct_size(notes_attrs, attrs, notes),
1710 if (notes_attrs == NULL)
1713 notes_attrs->notes = notes;
1714 nattr = ¬es_attrs->attrs[0];
1715 for (loaded = i = 0; i < info->hdr->e_shnum; ++i) {
1716 if (sect_empty(&info->sechdrs[i]))
1718 if (info->sechdrs[i].sh_type == SHT_NOTE) {
1719 sysfs_bin_attr_init(nattr);
1720 nattr->attr.name = mod->sect_attrs->attrs[loaded].battr.attr.name;
1721 nattr->attr.mode = S_IRUGO;
1722 nattr->size = info->sechdrs[i].sh_size;
1723 nattr->private = (void *) info->sechdrs[i].sh_addr;
1724 nattr->read = module_notes_read;
1730 notes_attrs->dir = kobject_create_and_add("notes", &mod->mkobj.kobj);
1731 if (!notes_attrs->dir)
1734 for (i = 0; i < notes; ++i)
1735 if (sysfs_create_bin_file(notes_attrs->dir,
1736 ¬es_attrs->attrs[i]))
1739 mod->notes_attrs = notes_attrs;
1743 free_notes_attrs(notes_attrs, i);
1746 static void remove_notes_attrs(struct module *mod)
1748 if (mod->notes_attrs)
1749 free_notes_attrs(mod->notes_attrs, mod->notes_attrs->notes);
1754 static inline void add_sect_attrs(struct module *mod,
1755 const struct load_info *info)
1759 static inline void remove_sect_attrs(struct module *mod)
1763 static inline void add_notes_attrs(struct module *mod,
1764 const struct load_info *info)
1768 static inline void remove_notes_attrs(struct module *mod)
1771 #endif /* CONFIG_KALLSYMS */
1773 static void del_usage_links(struct module *mod)
1775 #ifdef CONFIG_MODULE_UNLOAD
1776 struct module_use *use;
1778 mutex_lock(&module_mutex);
1779 list_for_each_entry(use, &mod->target_list, target_list)
1780 sysfs_remove_link(use->target->holders_dir, mod->name);
1781 mutex_unlock(&module_mutex);
1785 static int add_usage_links(struct module *mod)
1788 #ifdef CONFIG_MODULE_UNLOAD
1789 struct module_use *use;
1791 mutex_lock(&module_mutex);
1792 list_for_each_entry(use, &mod->target_list, target_list) {
1793 ret = sysfs_create_link(use->target->holders_dir,
1794 &mod->mkobj.kobj, mod->name);
1798 mutex_unlock(&module_mutex);
1800 del_usage_links(mod);
1805 static void module_remove_modinfo_attrs(struct module *mod, int end);
1807 static int module_add_modinfo_attrs(struct module *mod)
1809 struct module_attribute *attr;
1810 struct module_attribute *temp_attr;
1814 mod->modinfo_attrs = kzalloc((sizeof(struct module_attribute) *
1815 (ARRAY_SIZE(modinfo_attrs) + 1)),
1817 if (!mod->modinfo_attrs)
1820 temp_attr = mod->modinfo_attrs;
1821 for (i = 0; (attr = modinfo_attrs[i]); i++) {
1822 if (!attr->test || attr->test(mod)) {
1823 memcpy(temp_attr, attr, sizeof(*temp_attr));
1824 sysfs_attr_init(&temp_attr->attr);
1825 error = sysfs_create_file(&mod->mkobj.kobj,
1837 module_remove_modinfo_attrs(mod, --i);
1839 kfree(mod->modinfo_attrs);
1843 static void module_remove_modinfo_attrs(struct module *mod, int end)
1845 struct module_attribute *attr;
1848 for (i = 0; (attr = &mod->modinfo_attrs[i]); i++) {
1849 if (end >= 0 && i > end)
1851 /* pick a field to test for end of list */
1852 if (!attr->attr.name)
1854 sysfs_remove_file(&mod->mkobj.kobj, &attr->attr);
1858 kfree(mod->modinfo_attrs);
1861 static void mod_kobject_put(struct module *mod)
1863 DECLARE_COMPLETION_ONSTACK(c);
1864 mod->mkobj.kobj_completion = &c;
1865 kobject_put(&mod->mkobj.kobj);
1866 wait_for_completion(&c);
1869 static int mod_sysfs_init(struct module *mod)
1872 struct kobject *kobj;
1874 if (!module_sysfs_initialized) {
1875 pr_err("%s: module sysfs not initialized\n", mod->name);
1880 kobj = kset_find_obj(module_kset, mod->name);
1882 pr_err("%s: module is already loaded\n", mod->name);
1888 mod->mkobj.mod = mod;
1890 memset(&mod->mkobj.kobj, 0, sizeof(mod->mkobj.kobj));
1891 mod->mkobj.kobj.kset = module_kset;
1892 err = kobject_init_and_add(&mod->mkobj.kobj, &module_ktype, NULL,
1895 mod_kobject_put(mod);
1897 /* delay uevent until full sysfs population */
1902 static int mod_sysfs_setup(struct module *mod,
1903 const struct load_info *info,
1904 struct kernel_param *kparam,
1905 unsigned int num_params)
1909 err = mod_sysfs_init(mod);
1913 mod->holders_dir = kobject_create_and_add("holders", &mod->mkobj.kobj);
1914 if (!mod->holders_dir) {
1919 err = module_param_sysfs_setup(mod, kparam, num_params);
1921 goto out_unreg_holders;
1923 err = module_add_modinfo_attrs(mod);
1925 goto out_unreg_param;
1927 err = add_usage_links(mod);
1929 goto out_unreg_modinfo_attrs;
1931 add_sect_attrs(mod, info);
1932 add_notes_attrs(mod, info);
1934 kobject_uevent(&mod->mkobj.kobj, KOBJ_ADD);
1937 out_unreg_modinfo_attrs:
1938 module_remove_modinfo_attrs(mod, -1);
1940 module_param_sysfs_remove(mod);
1942 kobject_put(mod->holders_dir);
1944 mod_kobject_put(mod);
1949 static void mod_sysfs_fini(struct module *mod)
1951 remove_notes_attrs(mod);
1952 remove_sect_attrs(mod);
1953 mod_kobject_put(mod);
1956 static void init_param_lock(struct module *mod)
1958 mutex_init(&mod->param_lock);
1960 #else /* !CONFIG_SYSFS */
1962 static int mod_sysfs_setup(struct module *mod,
1963 const struct load_info *info,
1964 struct kernel_param *kparam,
1965 unsigned int num_params)
1970 static void mod_sysfs_fini(struct module *mod)
1974 static void module_remove_modinfo_attrs(struct module *mod, int end)
1978 static void del_usage_links(struct module *mod)
1982 static void init_param_lock(struct module *mod)
1985 #endif /* CONFIG_SYSFS */
1987 static void mod_sysfs_teardown(struct module *mod)
1989 del_usage_links(mod);
1990 module_remove_modinfo_attrs(mod, -1);
1991 module_param_sysfs_remove(mod);
1992 kobject_put(mod->mkobj.drivers_dir);
1993 kobject_put(mod->holders_dir);
1994 mod_sysfs_fini(mod);
1998 * LKM RO/NX protection: protect module's text/ro-data
1999 * from modification and any data from execution.
2001 * General layout of module is:
2002 * [text] [read-only-data] [ro-after-init] [writable data]
2003 * text_size -----^ ^ ^ ^
2004 * ro_size ------------------------| | |
2005 * ro_after_init_size -----------------------------| |
2006 * size -----------------------------------------------------------|
2008 * These values are always page-aligned (as is base)
2012 * Since some arches are moving towards PAGE_KERNEL module allocations instead
2013 * of PAGE_KERNEL_EXEC, keep frob_text() and module_enable_x() outside of the
2014 * CONFIG_STRICT_MODULE_RWX block below because they are needed regardless of
2015 * whether we are strict.
2017 #ifdef CONFIG_ARCH_HAS_STRICT_MODULE_RWX
2018 static void frob_text(const struct module_layout *layout,
2019 int (*set_memory)(unsigned long start, int num_pages))
2021 BUG_ON((unsigned long)layout->base & (PAGE_SIZE-1));
2022 BUG_ON((unsigned long)layout->text_size & (PAGE_SIZE-1));
2023 set_memory((unsigned long)layout->base,
2024 layout->text_size >> PAGE_SHIFT);
2027 static void module_enable_x(const struct module *mod)
2029 frob_text(&mod->core_layout, set_memory_x);
2030 frob_text(&mod->init_layout, set_memory_x);
2032 #else /* !CONFIG_ARCH_HAS_STRICT_MODULE_RWX */
2033 static void module_enable_x(const struct module *mod) { }
2034 #endif /* CONFIG_ARCH_HAS_STRICT_MODULE_RWX */
2036 #ifdef CONFIG_STRICT_MODULE_RWX
2037 static void frob_rodata(const struct module_layout *layout,
2038 int (*set_memory)(unsigned long start, int num_pages))
2040 BUG_ON((unsigned long)layout->base & (PAGE_SIZE-1));
2041 BUG_ON((unsigned long)layout->text_size & (PAGE_SIZE-1));
2042 BUG_ON((unsigned long)layout->ro_size & (PAGE_SIZE-1));
2043 set_memory((unsigned long)layout->base + layout->text_size,
2044 (layout->ro_size - layout->text_size) >> PAGE_SHIFT);
2047 static void frob_ro_after_init(const struct module_layout *layout,
2048 int (*set_memory)(unsigned long start, int num_pages))
2050 BUG_ON((unsigned long)layout->base & (PAGE_SIZE-1));
2051 BUG_ON((unsigned long)layout->ro_size & (PAGE_SIZE-1));
2052 BUG_ON((unsigned long)layout->ro_after_init_size & (PAGE_SIZE-1));
2053 set_memory((unsigned long)layout->base + layout->ro_size,
2054 (layout->ro_after_init_size - layout->ro_size) >> PAGE_SHIFT);
2057 static void frob_writable_data(const struct module_layout *layout,
2058 int (*set_memory)(unsigned long start, int num_pages))
2060 BUG_ON((unsigned long)layout->base & (PAGE_SIZE-1));
2061 BUG_ON((unsigned long)layout->ro_after_init_size & (PAGE_SIZE-1));
2062 BUG_ON((unsigned long)layout->size & (PAGE_SIZE-1));
2063 set_memory((unsigned long)layout->base + layout->ro_after_init_size,
2064 (layout->size - layout->ro_after_init_size) >> PAGE_SHIFT);
2067 static void module_enable_ro(const struct module *mod, bool after_init)
2069 if (!rodata_enabled)
2072 set_vm_flush_reset_perms(mod->core_layout.base);
2073 set_vm_flush_reset_perms(mod->init_layout.base);
2074 frob_text(&mod->core_layout, set_memory_ro);
2076 frob_rodata(&mod->core_layout, set_memory_ro);
2077 frob_text(&mod->init_layout, set_memory_ro);
2078 frob_rodata(&mod->init_layout, set_memory_ro);
2081 frob_ro_after_init(&mod->core_layout, set_memory_ro);
2084 static void module_enable_nx(const struct module *mod)
2086 frob_rodata(&mod->core_layout, set_memory_nx);
2087 frob_ro_after_init(&mod->core_layout, set_memory_nx);
2088 frob_writable_data(&mod->core_layout, set_memory_nx);
2089 frob_rodata(&mod->init_layout, set_memory_nx);
2090 frob_writable_data(&mod->init_layout, set_memory_nx);
2093 static int module_enforce_rwx_sections(Elf_Ehdr *hdr, Elf_Shdr *sechdrs,
2094 char *secstrings, struct module *mod)
2096 const unsigned long shf_wx = SHF_WRITE|SHF_EXECINSTR;
2099 for (i = 0; i < hdr->e_shnum; i++) {
2100 if ((sechdrs[i].sh_flags & shf_wx) == shf_wx)
2107 #else /* !CONFIG_STRICT_MODULE_RWX */
2108 static void module_enable_nx(const struct module *mod) { }
2109 static void module_enable_ro(const struct module *mod, bool after_init) {}
2110 static int module_enforce_rwx_sections(Elf_Ehdr *hdr, Elf_Shdr *sechdrs,
2111 char *secstrings, struct module *mod)
2115 #endif /* CONFIG_STRICT_MODULE_RWX */
2117 #ifdef CONFIG_LIVEPATCH
2119 * Persist Elf information about a module. Copy the Elf header,
2120 * section header table, section string table, and symtab section
2121 * index from info to mod->klp_info.
2123 static int copy_module_elf(struct module *mod, struct load_info *info)
2125 unsigned int size, symndx;
2128 size = sizeof(*mod->klp_info);
2129 mod->klp_info = kmalloc(size, GFP_KERNEL);
2130 if (mod->klp_info == NULL)
2134 size = sizeof(mod->klp_info->hdr);
2135 memcpy(&mod->klp_info->hdr, info->hdr, size);
2137 /* Elf section header table */
2138 size = sizeof(*info->sechdrs) * info->hdr->e_shnum;
2139 mod->klp_info->sechdrs = kmemdup(info->sechdrs, size, GFP_KERNEL);
2140 if (mod->klp_info->sechdrs == NULL) {
2145 /* Elf section name string table */
2146 size = info->sechdrs[info->hdr->e_shstrndx].sh_size;
2147 mod->klp_info->secstrings = kmemdup(info->secstrings, size, GFP_KERNEL);
2148 if (mod->klp_info->secstrings == NULL) {
2153 /* Elf symbol section index */
2154 symndx = info->index.sym;
2155 mod->klp_info->symndx = symndx;
2158 * For livepatch modules, core_kallsyms.symtab is a complete
2159 * copy of the original symbol table. Adjust sh_addr to point
2160 * to core_kallsyms.symtab since the copy of the symtab in module
2161 * init memory is freed at the end of do_init_module().
2163 mod->klp_info->sechdrs[symndx].sh_addr = \
2164 (unsigned long) mod->core_kallsyms.symtab;
2169 kfree(mod->klp_info->sechdrs);
2171 kfree(mod->klp_info);
2175 static void free_module_elf(struct module *mod)
2177 kfree(mod->klp_info->sechdrs);
2178 kfree(mod->klp_info->secstrings);
2179 kfree(mod->klp_info);
2181 #else /* !CONFIG_LIVEPATCH */
2182 static int copy_module_elf(struct module *mod, struct load_info *info)
2187 static void free_module_elf(struct module *mod)
2190 #endif /* CONFIG_LIVEPATCH */
2192 void __weak module_memfree(void *module_region)
2195 * This memory may be RO, and freeing RO memory in an interrupt is not
2196 * supported by vmalloc.
2198 WARN_ON(in_interrupt());
2199 vfree(module_region);
2202 void __weak module_arch_cleanup(struct module *mod)
2206 void __weak module_arch_freeing_init(struct module *mod)
2210 /* Free a module, remove from lists, etc. */
2211 static void free_module(struct module *mod)
2213 trace_module_free(mod);
2215 mod_sysfs_teardown(mod);
2217 /* We leave it in list to prevent duplicate loads, but make sure
2218 * that noone uses it while it's being deconstructed. */
2219 mutex_lock(&module_mutex);
2220 mod->state = MODULE_STATE_UNFORMED;
2221 mutex_unlock(&module_mutex);
2223 /* Remove dynamic debug info */
2224 ddebug_remove_module(mod->name);
2226 /* Arch-specific cleanup. */
2227 module_arch_cleanup(mod);
2229 /* Module unload stuff */
2230 module_unload_free(mod);
2232 /* Free any allocated parameters. */
2233 destroy_params(mod->kp, mod->num_kp);
2235 if (is_livepatch_module(mod))
2236 free_module_elf(mod);
2238 /* Now we can delete it from the lists */
2239 mutex_lock(&module_mutex);
2240 /* Unlink carefully: kallsyms could be walking list. */
2241 list_del_rcu(&mod->list);
2242 mod_tree_remove(mod);
2243 /* Remove this module from bug list, this uses list_del_rcu */
2244 module_bug_cleanup(mod);
2245 /* Wait for RCU-sched synchronizing before releasing mod->list and buglist. */
2247 mutex_unlock(&module_mutex);
2249 /* This may be empty, but that's OK */
2250 module_arch_freeing_init(mod);
2251 module_memfree(mod->init_layout.base);
2253 percpu_modfree(mod);
2255 /* Free lock-classes; relies on the preceding sync_rcu(). */
2256 lockdep_free_key_range(mod->core_layout.base, mod->core_layout.size);
2258 /* Finally, free the core (containing the module structure) */
2259 module_memfree(mod->core_layout.base);
2262 void *__symbol_get(const char *symbol)
2264 struct module *owner;
2265 const struct kernel_symbol *sym;
2268 sym = find_symbol(symbol, &owner, NULL, NULL, true, true);
2269 if (sym && strong_try_module_get(owner))
2273 return sym ? (void *)kernel_symbol_value(sym) : NULL;
2275 EXPORT_SYMBOL_GPL(__symbol_get);
2278 * Ensure that an exported symbol [global namespace] does not already exist
2279 * in the kernel or in some other module's exported symbol table.
2281 * You must hold the module_mutex.
2283 static int verify_exported_symbols(struct module *mod)
2286 struct module *owner;
2287 const struct kernel_symbol *s;
2289 const struct kernel_symbol *sym;
2292 { mod->syms, mod->num_syms },
2293 { mod->gpl_syms, mod->num_gpl_syms },
2294 { mod->gpl_future_syms, mod->num_gpl_future_syms },
2295 #ifdef CONFIG_UNUSED_SYMBOLS
2296 { mod->unused_syms, mod->num_unused_syms },
2297 { mod->unused_gpl_syms, mod->num_unused_gpl_syms },
2301 for (i = 0; i < ARRAY_SIZE(arr); i++) {
2302 for (s = arr[i].sym; s < arr[i].sym + arr[i].num; s++) {
2303 if (find_symbol(kernel_symbol_name(s), &owner, NULL,
2304 NULL, true, false)) {
2305 pr_err("%s: exports duplicate symbol %s"
2307 mod->name, kernel_symbol_name(s),
2308 module_name(owner));
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))
2335 /* We compiled with -fno-common. These are not
2336 supposed to happen. */
2337 pr_debug("Common symbol: %s\n", name);
2338 pr_warn("%s: please compile with -fno-common\n",
2344 /* Don't need to do anything */
2345 pr_debug("Absolute symbol: 0x%08lx\n",
2346 (long)sym[i].st_value);
2350 /* Livepatch symbols are resolved by livepatch */
2354 ksym = resolve_symbol_wait(mod, info, name);
2355 /* Ok if resolved. */
2356 if (ksym && !IS_ERR(ksym)) {
2357 sym[i].st_value = kernel_symbol_value(ksym);
2362 if (!ksym && ELF_ST_BIND(sym[i].st_info) == STB_WEAK)
2365 ret = PTR_ERR(ksym) ?: -ENOENT;
2366 pr_warn("%s: Unknown symbol %s (err %d)\n",
2367 mod->name, name, ret);
2371 /* Divert to percpu allocation if a percpu var. */
2372 if (sym[i].st_shndx == info->index.pcpu)
2373 secbase = (unsigned long)mod_percpu(mod);
2375 secbase = info->sechdrs[sym[i].st_shndx].sh_addr;
2376 sym[i].st_value += secbase;
2384 static int apply_relocations(struct module *mod, const struct load_info *info)
2389 /* Now do relocations. */
2390 for (i = 1; i < info->hdr->e_shnum; i++) {
2391 unsigned int infosec = info->sechdrs[i].sh_info;
2393 /* Not a valid relocation section? */
2394 if (infosec >= info->hdr->e_shnum)
2397 /* Don't bother with non-allocated sections */
2398 if (!(info->sechdrs[infosec].sh_flags & SHF_ALLOC))
2401 if (info->sechdrs[i].sh_flags & SHF_RELA_LIVEPATCH)
2402 err = klp_apply_section_relocs(mod, info->sechdrs,
2407 else if (info->sechdrs[i].sh_type == SHT_REL)
2408 err = apply_relocate(info->sechdrs, info->strtab,
2409 info->index.sym, i, mod);
2410 else if (info->sechdrs[i].sh_type == SHT_RELA)
2411 err = apply_relocate_add(info->sechdrs, info->strtab,
2412 info->index.sym, i, mod);
2419 /* Additional bytes needed by arch in front of individual sections */
2420 unsigned int __weak arch_mod_section_prepend(struct module *mod,
2421 unsigned int section)
2423 /* default implementation just returns zero */
2427 /* Update size with this section: return offset. */
2428 static long get_offset(struct module *mod, unsigned int *size,
2429 Elf_Shdr *sechdr, unsigned int section)
2433 *size += arch_mod_section_prepend(mod, section);
2434 ret = ALIGN(*size, sechdr->sh_addralign ?: 1);
2435 *size = ret + sechdr->sh_size;
2439 /* Lay out the SHF_ALLOC sections in a way not dissimilar to how ld
2440 might -- code, read-only data, read-write data, small data. Tally
2441 sizes, and place the offsets into sh_entsize fields: high bit means it
2443 static void layout_sections(struct module *mod, struct load_info *info)
2445 static unsigned long const masks[][2] = {
2446 /* NOTE: all executable code must be the first section
2447 * in this array; otherwise modify the text_size
2448 * finder in the two loops below */
2449 { SHF_EXECINSTR | SHF_ALLOC, ARCH_SHF_SMALL },
2450 { SHF_ALLOC, SHF_WRITE | ARCH_SHF_SMALL },
2451 { SHF_RO_AFTER_INIT | SHF_ALLOC, ARCH_SHF_SMALL },
2452 { SHF_WRITE | SHF_ALLOC, ARCH_SHF_SMALL },
2453 { ARCH_SHF_SMALL | SHF_ALLOC, 0 }
2457 for (i = 0; i < info->hdr->e_shnum; i++)
2458 info->sechdrs[i].sh_entsize = ~0UL;
2460 pr_debug("Core section allocation order:\n");
2461 for (m = 0; m < ARRAY_SIZE(masks); ++m) {
2462 for (i = 0; i < info->hdr->e_shnum; ++i) {
2463 Elf_Shdr *s = &info->sechdrs[i];
2464 const char *sname = info->secstrings + s->sh_name;
2466 if ((s->sh_flags & masks[m][0]) != masks[m][0]
2467 || (s->sh_flags & masks[m][1])
2468 || s->sh_entsize != ~0UL
2469 || module_init_section(sname))
2471 s->sh_entsize = get_offset(mod, &mod->core_layout.size, s, i);
2472 pr_debug("\t%s\n", sname);
2475 case 0: /* executable */
2476 mod->core_layout.size = debug_align(mod->core_layout.size);
2477 mod->core_layout.text_size = mod->core_layout.size;
2479 case 1: /* RO: text and ro-data */
2480 mod->core_layout.size = debug_align(mod->core_layout.size);
2481 mod->core_layout.ro_size = mod->core_layout.size;
2483 case 2: /* RO after init */
2484 mod->core_layout.size = debug_align(mod->core_layout.size);
2485 mod->core_layout.ro_after_init_size = mod->core_layout.size;
2487 case 4: /* whole core */
2488 mod->core_layout.size = debug_align(mod->core_layout.size);
2493 pr_debug("Init section allocation order:\n");
2494 for (m = 0; m < ARRAY_SIZE(masks); ++m) {
2495 for (i = 0; i < info->hdr->e_shnum; ++i) {
2496 Elf_Shdr *s = &info->sechdrs[i];
2497 const char *sname = info->secstrings + s->sh_name;
2499 if ((s->sh_flags & masks[m][0]) != masks[m][0]
2500 || (s->sh_flags & masks[m][1])
2501 || s->sh_entsize != ~0UL
2502 || !module_init_section(sname))
2504 s->sh_entsize = (get_offset(mod, &mod->init_layout.size, s, i)
2505 | INIT_OFFSET_MASK);
2506 pr_debug("\t%s\n", sname);
2509 case 0: /* executable */
2510 mod->init_layout.size = debug_align(mod->init_layout.size);
2511 mod->init_layout.text_size = mod->init_layout.size;
2513 case 1: /* RO: text and ro-data */
2514 mod->init_layout.size = debug_align(mod->init_layout.size);
2515 mod->init_layout.ro_size = mod->init_layout.size;
2519 * RO after init doesn't apply to init_layout (only
2520 * core_layout), so it just takes the value of ro_size.
2522 mod->init_layout.ro_after_init_size = mod->init_layout.ro_size;
2524 case 4: /* whole init */
2525 mod->init_layout.size = debug_align(mod->init_layout.size);
2531 static void set_license(struct module *mod, const char *license)
2534 license = "unspecified";
2536 if (!license_is_gpl_compatible(license)) {
2537 if (!test_taint(TAINT_PROPRIETARY_MODULE))
2538 pr_warn("%s: module license '%s' taints kernel.\n",
2539 mod->name, license);
2540 add_taint_module(mod, TAINT_PROPRIETARY_MODULE,
2541 LOCKDEP_NOW_UNRELIABLE);
2545 /* Parse tag=value strings from .modinfo section */
2546 static char *next_string(char *string, unsigned long *secsize)
2548 /* Skip non-zero chars */
2551 if ((*secsize)-- <= 1)
2555 /* Skip any zero padding. */
2556 while (!string[0]) {
2558 if ((*secsize)-- <= 1)
2564 static char *get_next_modinfo(const struct load_info *info, const char *tag,
2568 unsigned int taglen = strlen(tag);
2569 Elf_Shdr *infosec = &info->sechdrs[info->index.info];
2570 unsigned long size = infosec->sh_size;
2573 * get_modinfo() calls made before rewrite_section_headers()
2574 * must use sh_offset, as sh_addr isn't set!
2576 char *modinfo = (char *)info->hdr + infosec->sh_offset;
2579 size -= prev - modinfo;
2580 modinfo = next_string(prev, &size);
2583 for (p = modinfo; p; p = next_string(p, &size)) {
2584 if (strncmp(p, tag, taglen) == 0 && p[taglen] == '=')
2585 return p + taglen + 1;
2590 static char *get_modinfo(const struct load_info *info, const char *tag)
2592 return get_next_modinfo(info, tag, NULL);
2595 static void setup_modinfo(struct module *mod, struct load_info *info)
2597 struct module_attribute *attr;
2600 for (i = 0; (attr = modinfo_attrs[i]); i++) {
2602 attr->setup(mod, get_modinfo(info, attr->attr.name));
2606 static void free_modinfo(struct module *mod)
2608 struct module_attribute *attr;
2611 for (i = 0; (attr = modinfo_attrs[i]); i++) {
2617 #ifdef CONFIG_KALLSYMS
2619 /* Lookup exported symbol in given range of kernel_symbols */
2620 static const struct kernel_symbol *lookup_exported_symbol(const char *name,
2621 const struct kernel_symbol *start,
2622 const struct kernel_symbol *stop)
2624 return bsearch(name, start, stop - start,
2625 sizeof(struct kernel_symbol), cmp_name);
2628 static int is_exported(const char *name, unsigned long value,
2629 const struct module *mod)
2631 const struct kernel_symbol *ks;
2633 ks = lookup_exported_symbol(name, __start___ksymtab, __stop___ksymtab);
2635 ks = lookup_exported_symbol(name, mod->syms, mod->syms + mod->num_syms);
2637 return ks != NULL && kernel_symbol_value(ks) == value;
2641 static char elf_type(const Elf_Sym *sym, const struct load_info *info)
2643 const Elf_Shdr *sechdrs = info->sechdrs;
2645 if (ELF_ST_BIND(sym->st_info) == STB_WEAK) {
2646 if (ELF_ST_TYPE(sym->st_info) == STT_OBJECT)
2651 if (sym->st_shndx == SHN_UNDEF)
2653 if (sym->st_shndx == SHN_ABS || sym->st_shndx == info->index.pcpu)
2655 if (sym->st_shndx >= SHN_LORESERVE)
2657 if (sechdrs[sym->st_shndx].sh_flags & SHF_EXECINSTR)
2659 if (sechdrs[sym->st_shndx].sh_flags & SHF_ALLOC
2660 && sechdrs[sym->st_shndx].sh_type != SHT_NOBITS) {
2661 if (!(sechdrs[sym->st_shndx].sh_flags & SHF_WRITE))
2663 else if (sechdrs[sym->st_shndx].sh_flags & ARCH_SHF_SMALL)
2668 if (sechdrs[sym->st_shndx].sh_type == SHT_NOBITS) {
2669 if (sechdrs[sym->st_shndx].sh_flags & ARCH_SHF_SMALL)
2674 if (strstarts(info->secstrings + sechdrs[sym->st_shndx].sh_name,
2681 static bool is_core_symbol(const Elf_Sym *src, const Elf_Shdr *sechdrs,
2682 unsigned int shnum, unsigned int pcpundx)
2684 const Elf_Shdr *sec;
2686 if (src->st_shndx == SHN_UNDEF
2687 || src->st_shndx >= shnum
2691 #ifdef CONFIG_KALLSYMS_ALL
2692 if (src->st_shndx == pcpundx)
2696 sec = sechdrs + src->st_shndx;
2697 if (!(sec->sh_flags & SHF_ALLOC)
2698 #ifndef CONFIG_KALLSYMS_ALL
2699 || !(sec->sh_flags & SHF_EXECINSTR)
2701 || (sec->sh_entsize & INIT_OFFSET_MASK))
2708 * We only allocate and copy the strings needed by the parts of symtab
2709 * we keep. This is simple, but has the effect of making multiple
2710 * copies of duplicates. We could be more sophisticated, see
2711 * linux-kernel thread starting with
2712 * <73defb5e4bca04a6431392cc341112b1@localhost>.
2714 static void layout_symtab(struct module *mod, struct load_info *info)
2716 Elf_Shdr *symsect = info->sechdrs + info->index.sym;
2717 Elf_Shdr *strsect = info->sechdrs + info->index.str;
2719 unsigned int i, nsrc, ndst, strtab_size = 0;
2721 /* Put symbol section at end of init part of module. */
2722 symsect->sh_flags |= SHF_ALLOC;
2723 symsect->sh_entsize = get_offset(mod, &mod->init_layout.size, symsect,
2724 info->index.sym) | INIT_OFFSET_MASK;
2725 pr_debug("\t%s\n", info->secstrings + symsect->sh_name);
2727 src = (void *)info->hdr + symsect->sh_offset;
2728 nsrc = symsect->sh_size / sizeof(*src);
2730 /* Compute total space required for the core symbols' strtab. */
2731 for (ndst = i = 0; i < nsrc; i++) {
2732 if (i == 0 || is_livepatch_module(mod) ||
2733 is_core_symbol(src+i, info->sechdrs, info->hdr->e_shnum,
2734 info->index.pcpu)) {
2735 strtab_size += strlen(&info->strtab[src[i].st_name])+1;
2740 /* Append room for core symbols at end of core part. */
2741 info->symoffs = ALIGN(mod->core_layout.size, symsect->sh_addralign ?: 1);
2742 info->stroffs = mod->core_layout.size = info->symoffs + ndst * sizeof(Elf_Sym);
2743 mod->core_layout.size += strtab_size;
2744 info->core_typeoffs = mod->core_layout.size;
2745 mod->core_layout.size += ndst * sizeof(char);
2746 mod->core_layout.size = debug_align(mod->core_layout.size);
2748 /* Put string table section at end of init part of module. */
2749 strsect->sh_flags |= SHF_ALLOC;
2750 strsect->sh_entsize = get_offset(mod, &mod->init_layout.size, strsect,
2751 info->index.str) | INIT_OFFSET_MASK;
2752 pr_debug("\t%s\n", info->secstrings + strsect->sh_name);
2754 /* We'll tack temporary mod_kallsyms on the end. */
2755 mod->init_layout.size = ALIGN(mod->init_layout.size,
2756 __alignof__(struct mod_kallsyms));
2757 info->mod_kallsyms_init_off = mod->init_layout.size;
2758 mod->init_layout.size += sizeof(struct mod_kallsyms);
2759 info->init_typeoffs = mod->init_layout.size;
2760 mod->init_layout.size += nsrc * sizeof(char);
2761 mod->init_layout.size = debug_align(mod->init_layout.size);
2765 * We use the full symtab and strtab which layout_symtab arranged to
2766 * be appended to the init section. Later we switch to the cut-down
2769 static void add_kallsyms(struct module *mod, const struct load_info *info)
2771 unsigned int i, ndst;
2775 Elf_Shdr *symsec = &info->sechdrs[info->index.sym];
2777 /* Set up to point into init section. */
2778 mod->kallsyms = mod->init_layout.base + info->mod_kallsyms_init_off;
2780 mod->kallsyms->symtab = (void *)symsec->sh_addr;
2781 mod->kallsyms->num_symtab = symsec->sh_size / sizeof(Elf_Sym);
2782 /* Make sure we get permanent strtab: don't use info->strtab. */
2783 mod->kallsyms->strtab = (void *)info->sechdrs[info->index.str].sh_addr;
2784 mod->kallsyms->typetab = mod->init_layout.base + info->init_typeoffs;
2787 * Now populate the cut down core kallsyms for after init
2788 * and set types up while we still have access to sections.
2790 mod->core_kallsyms.symtab = dst = mod->core_layout.base + info->symoffs;
2791 mod->core_kallsyms.strtab = s = mod->core_layout.base + info->stroffs;
2792 mod->core_kallsyms.typetab = mod->core_layout.base + info->core_typeoffs;
2793 src = mod->kallsyms->symtab;
2794 for (ndst = i = 0; i < mod->kallsyms->num_symtab; i++) {
2795 mod->kallsyms->typetab[i] = elf_type(src + i, info);
2796 if (i == 0 || is_livepatch_module(mod) ||
2797 is_core_symbol(src+i, info->sechdrs, info->hdr->e_shnum,
2798 info->index.pcpu)) {
2799 mod->core_kallsyms.typetab[ndst] =
2800 mod->kallsyms->typetab[i];
2802 dst[ndst++].st_name = s - mod->core_kallsyms.strtab;
2803 s += strlcpy(s, &mod->kallsyms->strtab[src[i].st_name],
2807 mod->core_kallsyms.num_symtab = ndst;
2810 static inline void layout_symtab(struct module *mod, struct load_info *info)
2814 static void add_kallsyms(struct module *mod, const struct load_info *info)
2817 #endif /* CONFIG_KALLSYMS */
2819 static void dynamic_debug_setup(struct module *mod, struct _ddebug *debug, unsigned int num)
2823 ddebug_add_module(debug, num, mod->name);
2826 static void dynamic_debug_remove(struct module *mod, struct _ddebug *debug)
2829 ddebug_remove_module(mod->name);
2832 void * __weak module_alloc(unsigned long size)
2834 return __vmalloc_node_range(size, 1, VMALLOC_START, VMALLOC_END,
2835 GFP_KERNEL, PAGE_KERNEL_EXEC, VM_FLUSH_RESET_PERMS,
2836 NUMA_NO_NODE, __builtin_return_address(0));
2839 bool __weak module_init_section(const char *name)
2841 return strstarts(name, ".init");
2844 bool __weak module_exit_section(const char *name)
2846 return strstarts(name, ".exit");
2849 #ifdef CONFIG_DEBUG_KMEMLEAK
2850 static void kmemleak_load_module(const struct module *mod,
2851 const struct load_info *info)
2855 /* only scan the sections containing data */
2856 kmemleak_scan_area(mod, sizeof(struct module), GFP_KERNEL);
2858 for (i = 1; i < info->hdr->e_shnum; i++) {
2859 /* Scan all writable sections that's not executable */
2860 if (!(info->sechdrs[i].sh_flags & SHF_ALLOC) ||
2861 !(info->sechdrs[i].sh_flags & SHF_WRITE) ||
2862 (info->sechdrs[i].sh_flags & SHF_EXECINSTR))
2865 kmemleak_scan_area((void *)info->sechdrs[i].sh_addr,
2866 info->sechdrs[i].sh_size, GFP_KERNEL);
2870 static inline void kmemleak_load_module(const struct module *mod,
2871 const struct load_info *info)
2876 #ifdef CONFIG_MODULE_SIG
2877 static int module_sig_check(struct load_info *info, int flags)
2880 const unsigned long markerlen = sizeof(MODULE_SIG_STRING) - 1;
2882 const void *mod = info->hdr;
2885 * Require flags == 0, as a module with version information
2886 * removed is no longer the module that was signed
2889 info->len > markerlen &&
2890 memcmp(mod + info->len - markerlen, MODULE_SIG_STRING, markerlen) == 0) {
2891 /* We truncate the module to discard the signature */
2892 info->len -= markerlen;
2893 err = mod_verify_sig(mod, info);
2898 info->sig_ok = true;
2901 /* We don't permit modules to be loaded into trusted kernels
2902 * without a valid signature on them, but if we're not
2903 * enforcing, certain errors are non-fatal.
2906 reason = "Loading of unsigned module";
2909 reason = "Loading of module with unsupported crypto";
2912 reason = "Loading of module with unavailable key";
2914 if (is_module_sig_enforced()) {
2915 pr_notice("%s: %s is rejected\n", info->name, reason);
2916 return -EKEYREJECTED;
2919 return security_locked_down(LOCKDOWN_MODULE_SIGNATURE);
2921 /* All other errors are fatal, including nomem, unparseable
2922 * signatures and signature check failures - even if signatures
2929 #else /* !CONFIG_MODULE_SIG */
2930 static int module_sig_check(struct load_info *info, int flags)
2934 #endif /* !CONFIG_MODULE_SIG */
2936 /* Sanity checks against invalid binaries, wrong arch, weird elf version. */
2937 static int elf_header_check(struct load_info *info)
2939 if (info->len < sizeof(*(info->hdr)))
2942 if (memcmp(info->hdr->e_ident, ELFMAG, SELFMAG) != 0
2943 || info->hdr->e_type != ET_REL
2944 || !elf_check_arch(info->hdr)
2945 || info->hdr->e_shentsize != sizeof(Elf_Shdr))
2948 if (info->hdr->e_shoff >= info->len
2949 || (info->hdr->e_shnum * sizeof(Elf_Shdr) >
2950 info->len - info->hdr->e_shoff))
2956 #define COPY_CHUNK_SIZE (16*PAGE_SIZE)
2958 static int copy_chunked_from_user(void *dst, const void __user *usrc, unsigned long len)
2961 unsigned long n = min(len, COPY_CHUNK_SIZE);
2963 if (copy_from_user(dst, usrc, n) != 0)
2973 #ifdef CONFIG_LIVEPATCH
2974 static int check_modinfo_livepatch(struct module *mod, struct load_info *info)
2976 if (get_modinfo(info, "livepatch")) {
2978 add_taint_module(mod, TAINT_LIVEPATCH, LOCKDEP_STILL_OK);
2979 pr_notice_once("%s: tainting kernel with TAINT_LIVEPATCH\n",
2985 #else /* !CONFIG_LIVEPATCH */
2986 static int check_modinfo_livepatch(struct module *mod, struct load_info *info)
2988 if (get_modinfo(info, "livepatch")) {
2989 pr_err("%s: module is marked as livepatch module, but livepatch support is disabled",
2996 #endif /* CONFIG_LIVEPATCH */
2998 static void check_modinfo_retpoline(struct module *mod, struct load_info *info)
3000 if (retpoline_module_ok(get_modinfo(info, "retpoline")))
3003 pr_warn("%s: loading module not compiled with retpoline compiler.\n",
3007 /* Sets info->hdr and info->len. */
3008 static int copy_module_from_user(const void __user *umod, unsigned long len,
3009 struct load_info *info)
3014 if (info->len < sizeof(*(info->hdr)))
3017 err = security_kernel_load_data(LOADING_MODULE, true);
3021 /* Suck in entire file: we'll want most of it. */
3022 info->hdr = __vmalloc(info->len, GFP_KERNEL | __GFP_NOWARN);
3026 if (copy_chunked_from_user(info->hdr, umod, info->len) != 0) {
3031 err = security_kernel_post_load_data((char *)info->hdr, info->len,
3032 LOADING_MODULE, "init_module");
3040 static void free_copy(struct load_info *info)
3045 static int rewrite_section_headers(struct load_info *info, int flags)
3049 /* This should always be true, but let's be sure. */
3050 info->sechdrs[0].sh_addr = 0;
3052 for (i = 1; i < info->hdr->e_shnum; i++) {
3053 Elf_Shdr *shdr = &info->sechdrs[i];
3054 if (shdr->sh_type != SHT_NOBITS
3055 && info->len < shdr->sh_offset + shdr->sh_size) {
3056 pr_err("Module len %lu truncated\n", info->len);
3060 /* Mark all sections sh_addr with their address in the
3062 shdr->sh_addr = (size_t)info->hdr + shdr->sh_offset;
3064 #ifndef CONFIG_MODULE_UNLOAD
3065 /* Don't load .exit sections */
3066 if (module_exit_section(info->secstrings+shdr->sh_name))
3067 shdr->sh_flags &= ~(unsigned long)SHF_ALLOC;
3071 /* Track but don't keep modinfo and version sections. */
3072 info->sechdrs[info->index.vers].sh_flags &= ~(unsigned long)SHF_ALLOC;
3073 info->sechdrs[info->index.info].sh_flags &= ~(unsigned long)SHF_ALLOC;
3079 * Set up our basic convenience variables (pointers to section headers,
3080 * search for module section index etc), and do some basic section
3083 * Set info->mod to the temporary copy of the module in info->hdr. The final one
3084 * will be allocated in move_module().
3086 static int setup_load_info(struct load_info *info, int flags)
3090 /* Set up the convenience variables */
3091 info->sechdrs = (void *)info->hdr + info->hdr->e_shoff;
3092 info->secstrings = (void *)info->hdr
3093 + info->sechdrs[info->hdr->e_shstrndx].sh_offset;
3095 /* Try to find a name early so we can log errors with a module name */
3096 info->index.info = find_sec(info, ".modinfo");
3097 if (info->index.info)
3098 info->name = get_modinfo(info, "name");
3100 /* Find internal symbols and strings. */
3101 for (i = 1; i < info->hdr->e_shnum; i++) {
3102 if (info->sechdrs[i].sh_type == SHT_SYMTAB) {
3103 info->index.sym = i;
3104 info->index.str = info->sechdrs[i].sh_link;
3105 info->strtab = (char *)info->hdr
3106 + info->sechdrs[info->index.str].sh_offset;
3111 if (info->index.sym == 0) {
3112 pr_warn("%s: module has no symbols (stripped?)\n",
3113 info->name ?: "(missing .modinfo section or name field)");
3117 info->index.mod = find_sec(info, ".gnu.linkonce.this_module");
3118 if (!info->index.mod) {
3119 pr_warn("%s: No module found in object\n",
3120 info->name ?: "(missing .modinfo section or name field)");
3123 /* This is temporary: point mod into copy of data. */
3124 info->mod = (void *)info->hdr + info->sechdrs[info->index.mod].sh_offset;
3127 * If we didn't load the .modinfo 'name' field earlier, fall back to
3128 * on-disk struct mod 'name' field.
3131 info->name = info->mod->name;
3133 if (flags & MODULE_INIT_IGNORE_MODVERSIONS)
3134 info->index.vers = 0; /* Pretend no __versions section! */
3136 info->index.vers = find_sec(info, "__versions");
3138 info->index.pcpu = find_pcpusec(info);
3143 static int check_modinfo(struct module *mod, struct load_info *info, int flags)
3145 const char *modmagic = get_modinfo(info, "vermagic");
3148 if (flags & MODULE_INIT_IGNORE_VERMAGIC)
3151 /* This is allowed: modprobe --force will invalidate it. */
3153 err = try_to_force_load(mod, "bad vermagic");
3156 } else if (!same_magic(modmagic, vermagic, info->index.vers)) {
3157 pr_err("%s: version magic '%s' should be '%s'\n",
3158 info->name, modmagic, vermagic);
3162 if (!get_modinfo(info, "intree")) {
3163 if (!test_taint(TAINT_OOT_MODULE))
3164 pr_warn("%s: loading out-of-tree module taints kernel.\n",
3166 add_taint_module(mod, TAINT_OOT_MODULE, LOCKDEP_STILL_OK);
3169 check_modinfo_retpoline(mod, info);
3171 if (get_modinfo(info, "staging")) {
3172 add_taint_module(mod, TAINT_CRAP, LOCKDEP_STILL_OK);
3173 pr_warn("%s: module is from the staging directory, the quality "
3174 "is unknown, you have been warned.\n", mod->name);
3177 err = check_modinfo_livepatch(mod, info);
3181 /* Set up license info based on the info section */
3182 set_license(mod, get_modinfo(info, "license"));
3187 static int find_module_sections(struct module *mod, struct load_info *info)
3189 mod->kp = section_objs(info, "__param",
3190 sizeof(*mod->kp), &mod->num_kp);
3191 mod->syms = section_objs(info, "__ksymtab",
3192 sizeof(*mod->syms), &mod->num_syms);
3193 mod->crcs = section_addr(info, "__kcrctab");
3194 mod->gpl_syms = section_objs(info, "__ksymtab_gpl",
3195 sizeof(*mod->gpl_syms),
3196 &mod->num_gpl_syms);
3197 mod->gpl_crcs = section_addr(info, "__kcrctab_gpl");
3198 mod->gpl_future_syms = section_objs(info,
3199 "__ksymtab_gpl_future",
3200 sizeof(*mod->gpl_future_syms),
3201 &mod->num_gpl_future_syms);
3202 mod->gpl_future_crcs = section_addr(info, "__kcrctab_gpl_future");
3204 #ifdef CONFIG_UNUSED_SYMBOLS
3205 mod->unused_syms = section_objs(info, "__ksymtab_unused",
3206 sizeof(*mod->unused_syms),
3207 &mod->num_unused_syms);
3208 mod->unused_crcs = section_addr(info, "__kcrctab_unused");
3209 mod->unused_gpl_syms = section_objs(info, "__ksymtab_unused_gpl",
3210 sizeof(*mod->unused_gpl_syms),
3211 &mod->num_unused_gpl_syms);
3212 mod->unused_gpl_crcs = section_addr(info, "__kcrctab_unused_gpl");
3214 #ifdef CONFIG_CONSTRUCTORS
3215 mod->ctors = section_objs(info, ".ctors",
3216 sizeof(*mod->ctors), &mod->num_ctors);
3218 mod->ctors = section_objs(info, ".init_array",
3219 sizeof(*mod->ctors), &mod->num_ctors);
3220 else if (find_sec(info, ".init_array")) {
3222 * This shouldn't happen with same compiler and binutils
3223 * building all parts of the module.
3225 pr_warn("%s: has both .ctors and .init_array.\n",
3231 mod->noinstr_text_start = section_objs(info, ".noinstr.text", 1,
3232 &mod->noinstr_text_size);
3234 #ifdef CONFIG_TRACEPOINTS
3235 mod->tracepoints_ptrs = section_objs(info, "__tracepoints_ptrs",
3236 sizeof(*mod->tracepoints_ptrs),
3237 &mod->num_tracepoints);
3239 #ifdef CONFIG_TREE_SRCU
3240 mod->srcu_struct_ptrs = section_objs(info, "___srcu_struct_ptrs",
3241 sizeof(*mod->srcu_struct_ptrs),
3242 &mod->num_srcu_structs);
3244 #ifdef CONFIG_BPF_EVENTS
3245 mod->bpf_raw_events = section_objs(info, "__bpf_raw_tp_map",
3246 sizeof(*mod->bpf_raw_events),
3247 &mod->num_bpf_raw_events);
3249 #ifdef CONFIG_JUMP_LABEL
3250 mod->jump_entries = section_objs(info, "__jump_table",
3251 sizeof(*mod->jump_entries),
3252 &mod->num_jump_entries);
3254 #ifdef CONFIG_EVENT_TRACING
3255 mod->trace_events = section_objs(info, "_ftrace_events",
3256 sizeof(*mod->trace_events),
3257 &mod->num_trace_events);
3258 mod->trace_evals = section_objs(info, "_ftrace_eval_map",
3259 sizeof(*mod->trace_evals),
3260 &mod->num_trace_evals);
3262 #ifdef CONFIG_TRACING
3263 mod->trace_bprintk_fmt_start = section_objs(info, "__trace_printk_fmt",
3264 sizeof(*mod->trace_bprintk_fmt_start),
3265 &mod->num_trace_bprintk_fmt);
3267 #ifdef CONFIG_FTRACE_MCOUNT_RECORD
3268 /* sechdrs[0].sh_size is always zero */
3269 mod->ftrace_callsites = section_objs(info, FTRACE_CALLSITE_SECTION,
3270 sizeof(*mod->ftrace_callsites),
3271 &mod->num_ftrace_callsites);
3273 #ifdef CONFIG_FUNCTION_ERROR_INJECTION
3274 mod->ei_funcs = section_objs(info, "_error_injection_whitelist",
3275 sizeof(*mod->ei_funcs),
3276 &mod->num_ei_funcs);
3278 #ifdef CONFIG_KPROBES
3279 mod->kprobes_text_start = section_objs(info, ".kprobes.text", 1,
3280 &mod->kprobes_text_size);
3281 mod->kprobe_blacklist = section_objs(info, "_kprobe_blacklist",
3282 sizeof(unsigned long),
3283 &mod->num_kprobe_blacklist);
3285 #ifdef CONFIG_HAVE_STATIC_CALL_INLINE
3286 mod->static_call_sites = section_objs(info, ".static_call_sites",
3287 sizeof(*mod->static_call_sites),
3288 &mod->num_static_call_sites);
3290 mod->extable = section_objs(info, "__ex_table",
3291 sizeof(*mod->extable), &mod->num_exentries);
3293 if (section_addr(info, "__obsparm"))
3294 pr_warn("%s: Ignoring obsolete parameters\n", mod->name);
3296 info->debug = section_objs(info, "__dyndbg",
3297 sizeof(*info->debug), &info->num_debug);
3302 static int move_module(struct module *mod, struct load_info *info)
3307 /* Do the allocs. */
3308 ptr = module_alloc(mod->core_layout.size);
3310 * The pointer to this block is stored in the module structure
3311 * which is inside the block. Just mark it as not being a
3314 kmemleak_not_leak(ptr);
3318 memset(ptr, 0, mod->core_layout.size);
3319 mod->core_layout.base = ptr;
3321 if (mod->init_layout.size) {
3322 ptr = module_alloc(mod->init_layout.size);
3324 * The pointer to this block is stored in the module structure
3325 * which is inside the block. This block doesn't need to be
3326 * scanned as it contains data and code that will be freed
3327 * after the module is initialized.
3329 kmemleak_ignore(ptr);
3331 module_memfree(mod->core_layout.base);
3334 memset(ptr, 0, mod->init_layout.size);
3335 mod->init_layout.base = ptr;
3337 mod->init_layout.base = NULL;
3339 /* Transfer each section which specifies SHF_ALLOC */
3340 pr_debug("final section addresses:\n");
3341 for (i = 0; i < info->hdr->e_shnum; i++) {
3343 Elf_Shdr *shdr = &info->sechdrs[i];
3345 if (!(shdr->sh_flags & SHF_ALLOC))
3348 if (shdr->sh_entsize & INIT_OFFSET_MASK)
3349 dest = mod->init_layout.base
3350 + (shdr->sh_entsize & ~INIT_OFFSET_MASK);
3352 dest = mod->core_layout.base + shdr->sh_entsize;
3354 if (shdr->sh_type != SHT_NOBITS)
3355 memcpy(dest, (void *)shdr->sh_addr, shdr->sh_size);
3356 /* Update sh_addr to point to copy in image. */
3357 shdr->sh_addr = (unsigned long)dest;
3358 pr_debug("\t0x%lx %s\n",
3359 (long)shdr->sh_addr, info->secstrings + shdr->sh_name);
3365 static int check_module_license_and_versions(struct module *mod)
3367 int prev_taint = test_taint(TAINT_PROPRIETARY_MODULE);
3370 * ndiswrapper is under GPL by itself, but loads proprietary modules.
3371 * Don't use add_taint_module(), as it would prevent ndiswrapper from
3372 * using GPL-only symbols it needs.
3374 if (strcmp(mod->name, "ndiswrapper") == 0)
3375 add_taint(TAINT_PROPRIETARY_MODULE, LOCKDEP_NOW_UNRELIABLE);
3377 /* driverloader was caught wrongly pretending to be under GPL */
3378 if (strcmp(mod->name, "driverloader") == 0)
3379 add_taint_module(mod, TAINT_PROPRIETARY_MODULE,
3380 LOCKDEP_NOW_UNRELIABLE);
3382 /* lve claims to be GPL but upstream won't provide source */
3383 if (strcmp(mod->name, "lve") == 0)
3384 add_taint_module(mod, TAINT_PROPRIETARY_MODULE,
3385 LOCKDEP_NOW_UNRELIABLE);
3387 if (!prev_taint && test_taint(TAINT_PROPRIETARY_MODULE))
3388 pr_warn("%s: module license taints kernel.\n", mod->name);
3390 #ifdef CONFIG_MODVERSIONS
3391 if ((mod->num_syms && !mod->crcs)
3392 || (mod->num_gpl_syms && !mod->gpl_crcs)
3393 || (mod->num_gpl_future_syms && !mod->gpl_future_crcs)
3394 #ifdef CONFIG_UNUSED_SYMBOLS
3395 || (mod->num_unused_syms && !mod->unused_crcs)
3396 || (mod->num_unused_gpl_syms && !mod->unused_gpl_crcs)
3399 return try_to_force_load(mod,
3400 "no versions for exported symbols");
3406 static void flush_module_icache(const struct module *mod)
3409 * Flush the instruction cache, since we've played with text.
3410 * Do it before processing of module parameters, so the module
3411 * can provide parameter accessor functions of its own.
3413 if (mod->init_layout.base)
3414 flush_icache_range((unsigned long)mod->init_layout.base,
3415 (unsigned long)mod->init_layout.base
3416 + mod->init_layout.size);
3417 flush_icache_range((unsigned long)mod->core_layout.base,
3418 (unsigned long)mod->core_layout.base + mod->core_layout.size);
3421 int __weak module_frob_arch_sections(Elf_Ehdr *hdr,
3429 /* module_blacklist is a comma-separated list of module names */
3430 static char *module_blacklist;
3431 static bool blacklisted(const char *module_name)
3436 if (!module_blacklist)
3439 for (p = module_blacklist; *p; p += len) {
3440 len = strcspn(p, ",");
3441 if (strlen(module_name) == len && !memcmp(module_name, p, len))
3448 core_param(module_blacklist, module_blacklist, charp, 0400);
3450 static struct module *layout_and_allocate(struct load_info *info, int flags)
3456 err = check_modinfo(info->mod, info, flags);
3458 return ERR_PTR(err);
3460 /* Allow arches to frob section contents and sizes. */
3461 err = module_frob_arch_sections(info->hdr, info->sechdrs,
3462 info->secstrings, info->mod);
3464 return ERR_PTR(err);
3466 err = module_enforce_rwx_sections(info->hdr, info->sechdrs,
3467 info->secstrings, info->mod);
3469 return ERR_PTR(err);
3471 /* We will do a special allocation for per-cpu sections later. */
3472 info->sechdrs[info->index.pcpu].sh_flags &= ~(unsigned long)SHF_ALLOC;
3475 * Mark ro_after_init section with SHF_RO_AFTER_INIT so that
3476 * layout_sections() can put it in the right place.
3477 * Note: ro_after_init sections also have SHF_{WRITE,ALLOC} set.
3479 ndx = find_sec(info, ".data..ro_after_init");
3481 info->sechdrs[ndx].sh_flags |= SHF_RO_AFTER_INIT;
3483 * Mark the __jump_table section as ro_after_init as well: these data
3484 * structures are never modified, with the exception of entries that
3485 * refer to code in the __init section, which are annotated as such
3486 * at module load time.
3488 ndx = find_sec(info, "__jump_table");
3490 info->sechdrs[ndx].sh_flags |= SHF_RO_AFTER_INIT;
3492 /* Determine total sizes, and put offsets in sh_entsize. For now
3493 this is done generically; there doesn't appear to be any
3494 special cases for the architectures. */
3495 layout_sections(info->mod, info);
3496 layout_symtab(info->mod, info);
3498 /* Allocate and move to the final place */
3499 err = move_module(info->mod, info);
3501 return ERR_PTR(err);
3503 /* Module has been copied to its final place now: return it. */
3504 mod = (void *)info->sechdrs[info->index.mod].sh_addr;
3505 kmemleak_load_module(mod, info);
3509 /* mod is no longer valid after this! */
3510 static void module_deallocate(struct module *mod, struct load_info *info)
3512 percpu_modfree(mod);
3513 module_arch_freeing_init(mod);
3514 module_memfree(mod->init_layout.base);
3515 module_memfree(mod->core_layout.base);
3518 int __weak module_finalize(const Elf_Ehdr *hdr,
3519 const Elf_Shdr *sechdrs,
3525 static int post_relocation(struct module *mod, const struct load_info *info)
3527 /* Sort exception table now relocations are done. */
3528 sort_extable(mod->extable, mod->extable + mod->num_exentries);
3530 /* Copy relocated percpu area over. */
3531 percpu_modcopy(mod, (void *)info->sechdrs[info->index.pcpu].sh_addr,
3532 info->sechdrs[info->index.pcpu].sh_size);
3534 /* Setup kallsyms-specific fields. */
3535 add_kallsyms(mod, info);
3537 /* Arch-specific module finalizing. */
3538 return module_finalize(info->hdr, info->sechdrs, mod);
3541 /* Is this module of this name done loading? No locks held. */
3542 static bool finished_loading(const char *name)
3548 * The module_mutex should not be a heavily contended lock;
3549 * if we get the occasional sleep here, we'll go an extra iteration
3550 * in the wait_event_interruptible(), which is harmless.
3552 sched_annotate_sleep();
3553 mutex_lock(&module_mutex);
3554 mod = find_module_all(name, strlen(name), true);
3555 ret = !mod || mod->state == MODULE_STATE_LIVE;
3556 mutex_unlock(&module_mutex);
3561 /* Call module constructors. */
3562 static void do_mod_ctors(struct module *mod)
3564 #ifdef CONFIG_CONSTRUCTORS
3567 for (i = 0; i < mod->num_ctors; i++)
3572 /* For freeing module_init on success, in case kallsyms traversing */
3573 struct mod_initfree {
3574 struct llist_node node;
3578 static void do_free_init(struct work_struct *w)
3580 struct llist_node *pos, *n, *list;
3581 struct mod_initfree *initfree;
3583 list = llist_del_all(&init_free_list);
3587 llist_for_each_safe(pos, n, list) {
3588 initfree = container_of(pos, struct mod_initfree, node);
3589 module_memfree(initfree->module_init);
3594 static int __init modules_wq_init(void)
3596 INIT_WORK(&init_free_wq, do_free_init);
3597 init_llist_head(&init_free_list);
3600 module_init(modules_wq_init);
3603 * This is where the real work happens.
3605 * Keep it uninlined to provide a reliable breakpoint target, e.g. for the gdb
3606 * helper command 'lx-symbols'.
3608 static noinline int do_init_module(struct module *mod)
3611 struct mod_initfree *freeinit;
3613 freeinit = kmalloc(sizeof(*freeinit), GFP_KERNEL);
3618 freeinit->module_init = mod->init_layout.base;
3621 * We want to find out whether @mod uses async during init. Clear
3622 * PF_USED_ASYNC. async_schedule*() will set it.
3624 current->flags &= ~PF_USED_ASYNC;
3627 /* Start the module */
3628 if (mod->init != NULL)
3629 ret = do_one_initcall(mod->init);
3631 goto fail_free_freeinit;
3634 pr_warn("%s: '%s'->init suspiciously returned %d, it should "
3635 "follow 0/-E convention\n"
3636 "%s: loading module anyway...\n",
3637 __func__, mod->name, ret, __func__);
3641 /* Now it's a first class citizen! */
3642 mod->state = MODULE_STATE_LIVE;
3643 blocking_notifier_call_chain(&module_notify_list,
3644 MODULE_STATE_LIVE, mod);
3647 * We need to finish all async code before the module init sequence
3648 * is done. This has potential to deadlock. For example, a newly
3649 * detected block device can trigger request_module() of the
3650 * default iosched from async probing task. Once userland helper
3651 * reaches here, async_synchronize_full() will wait on the async
3652 * task waiting on request_module() and deadlock.
3654 * This deadlock is avoided by perfomring async_synchronize_full()
3655 * iff module init queued any async jobs. This isn't a full
3656 * solution as it will deadlock the same if module loading from
3657 * async jobs nests more than once; however, due to the various
3658 * constraints, this hack seems to be the best option for now.
3659 * Please refer to the following thread for details.
3661 * http://thread.gmane.org/gmane.linux.kernel/1420814
3663 if (!mod->async_probe_requested && (current->flags & PF_USED_ASYNC))
3664 async_synchronize_full();
3666 ftrace_free_mem(mod, mod->init_layout.base, mod->init_layout.base +
3667 mod->init_layout.size);
3668 mutex_lock(&module_mutex);
3669 /* Drop initial reference. */
3671 trim_init_extable(mod);
3672 #ifdef CONFIG_KALLSYMS
3673 /* Switch to core kallsyms now init is done: kallsyms may be walking! */
3674 rcu_assign_pointer(mod->kallsyms, &mod->core_kallsyms);
3676 module_enable_ro(mod, true);
3677 mod_tree_remove_init(mod);
3678 module_arch_freeing_init(mod);
3679 mod->init_layout.base = NULL;
3680 mod->init_layout.size = 0;
3681 mod->init_layout.ro_size = 0;
3682 mod->init_layout.ro_after_init_size = 0;
3683 mod->init_layout.text_size = 0;
3685 * We want to free module_init, but be aware that kallsyms may be
3686 * walking this with preempt disabled. In all the failure paths, we
3687 * call synchronize_rcu(), but we don't want to slow down the success
3688 * path. module_memfree() cannot be called in an interrupt, so do the
3689 * work and call synchronize_rcu() in a work queue.
3691 * Note that module_alloc() on most architectures creates W+X page
3692 * mappings which won't be cleaned up until do_free_init() runs. Any
3693 * code such as mark_rodata_ro() which depends on those mappings to
3694 * be cleaned up needs to sync with the queued work - ie
3697 if (llist_add(&freeinit->node, &init_free_list))
3698 schedule_work(&init_free_wq);
3700 mutex_unlock(&module_mutex);
3701 wake_up_all(&module_wq);
3708 /* Try to protect us from buggy refcounters. */
3709 mod->state = MODULE_STATE_GOING;
3712 blocking_notifier_call_chain(&module_notify_list,
3713 MODULE_STATE_GOING, mod);
3714 klp_module_going(mod);
3715 ftrace_release_mod(mod);
3717 wake_up_all(&module_wq);
3721 static int may_init_module(void)
3723 if (!capable(CAP_SYS_MODULE) || modules_disabled)
3730 * We try to place it in the list now to make sure it's unique before
3731 * we dedicate too many resources. In particular, temporary percpu
3732 * memory exhaustion.
3734 static int add_unformed_module(struct module *mod)
3739 mod->state = MODULE_STATE_UNFORMED;
3742 mutex_lock(&module_mutex);
3743 old = find_module_all(mod->name, strlen(mod->name), true);
3745 if (old->state != MODULE_STATE_LIVE) {
3746 /* Wait in case it fails to load. */
3747 mutex_unlock(&module_mutex);
3748 err = wait_event_interruptible(module_wq,
3749 finished_loading(mod->name));
3757 mod_update_bounds(mod);
3758 list_add_rcu(&mod->list, &modules);
3759 mod_tree_insert(mod);
3763 mutex_unlock(&module_mutex);
3768 static int complete_formation(struct module *mod, struct load_info *info)
3772 mutex_lock(&module_mutex);
3774 /* Find duplicate symbols (must be called under lock). */
3775 err = verify_exported_symbols(mod);
3779 /* This relies on module_mutex for list integrity. */
3780 module_bug_finalize(info->hdr, info->sechdrs, mod);
3782 module_enable_ro(mod, false);
3783 module_enable_nx(mod);
3784 module_enable_x(mod);
3786 /* Mark state as coming so strong_try_module_get() ignores us,
3787 * but kallsyms etc. can see us. */
3788 mod->state = MODULE_STATE_COMING;
3789 mutex_unlock(&module_mutex);
3794 mutex_unlock(&module_mutex);
3798 static int prepare_coming_module(struct module *mod)
3802 ftrace_module_enable(mod);
3803 err = klp_module_coming(mod);
3807 err = blocking_notifier_call_chain_robust(&module_notify_list,
3808 MODULE_STATE_COMING, MODULE_STATE_GOING, mod);
3809 err = notifier_to_errno(err);
3811 klp_module_going(mod);
3816 static int unknown_module_param_cb(char *param, char *val, const char *modname,
3819 struct module *mod = arg;
3822 if (strcmp(param, "async_probe") == 0) {
3823 mod->async_probe_requested = true;
3827 /* Check for magic 'dyndbg' arg */
3828 ret = ddebug_dyndbg_module_param_cb(param, val, modname);
3830 pr_warn("%s: unknown parameter '%s' ignored\n", modname, param);
3834 /* Allocate and load the module: note that size of section 0 is always
3835 zero, and we rely on this for optional sections. */
3836 static int load_module(struct load_info *info, const char __user *uargs,
3843 err = elf_header_check(info);
3847 err = setup_load_info(info, flags);
3851 if (blacklisted(info->name)) {
3856 err = module_sig_check(info, flags);
3860 err = rewrite_section_headers(info, flags);
3864 /* Check module struct version now, before we try to use module. */
3865 if (!check_modstruct_version(info, info->mod)) {
3870 /* Figure out module layout, and allocate all the memory. */
3871 mod = layout_and_allocate(info, flags);
3877 audit_log_kern_module(mod->name);
3879 /* Reserve our place in the list. */
3880 err = add_unformed_module(mod);
3884 #ifdef CONFIG_MODULE_SIG
3885 mod->sig_ok = info->sig_ok;
3887 pr_notice_once("%s: module verification failed: signature "
3888 "and/or required key missing - tainting "
3889 "kernel\n", mod->name);
3890 add_taint_module(mod, TAINT_UNSIGNED_MODULE, LOCKDEP_STILL_OK);
3894 /* To avoid stressing percpu allocator, do this once we're unique. */
3895 err = percpu_modalloc(mod, info);
3899 /* Now module is in final location, initialize linked lists, etc. */
3900 err = module_unload_init(mod);
3904 init_param_lock(mod);
3906 /* Now we've got everything in the final locations, we can
3907 * find optional sections. */
3908 err = find_module_sections(mod, info);
3912 err = check_module_license_and_versions(mod);
3916 /* Set up MODINFO_ATTR fields */
3917 setup_modinfo(mod, info);
3919 /* Fix up syms, so that st_value is a pointer to location. */
3920 err = simplify_symbols(mod, info);
3924 err = apply_relocations(mod, info);
3928 err = post_relocation(mod, info);
3932 flush_module_icache(mod);
3934 /* Now copy in args */
3935 mod->args = strndup_user(uargs, ~0UL >> 1);
3936 if (IS_ERR(mod->args)) {
3937 err = PTR_ERR(mod->args);
3938 goto free_arch_cleanup;
3941 dynamic_debug_setup(mod, info->debug, info->num_debug);
3943 /* Ftrace init must be called in the MODULE_STATE_UNFORMED state */
3944 ftrace_module_init(mod);
3946 /* Finally it's fully formed, ready to start executing. */
3947 err = complete_formation(mod, info);
3949 goto ddebug_cleanup;
3951 err = prepare_coming_module(mod);
3955 /* Module is ready to execute: parsing args may do that. */
3956 after_dashes = parse_args(mod->name, mod->args, mod->kp, mod->num_kp,
3958 unknown_module_param_cb);
3959 if (IS_ERR(after_dashes)) {
3960 err = PTR_ERR(after_dashes);
3961 goto coming_cleanup;
3962 } else if (after_dashes) {
3963 pr_warn("%s: parameters '%s' after `--' ignored\n",
3964 mod->name, after_dashes);
3967 /* Link in to sysfs. */
3968 err = mod_sysfs_setup(mod, info, mod->kp, mod->num_kp);
3970 goto coming_cleanup;
3972 if (is_livepatch_module(mod)) {
3973 err = copy_module_elf(mod, info);
3978 /* Get rid of temporary copy. */
3982 trace_module_load(mod);
3984 return do_init_module(mod);
3987 mod_sysfs_teardown(mod);
3989 mod->state = MODULE_STATE_GOING;
3990 destroy_params(mod->kp, mod->num_kp);
3991 blocking_notifier_call_chain(&module_notify_list,
3992 MODULE_STATE_GOING, mod);
3993 klp_module_going(mod);
3995 /* module_bug_cleanup needs module_mutex protection */
3996 mutex_lock(&module_mutex);
3997 module_bug_cleanup(mod);
3998 mutex_unlock(&module_mutex);
4001 ftrace_release_mod(mod);
4002 dynamic_debug_remove(mod, info->debug);
4006 module_arch_cleanup(mod);
4010 module_unload_free(mod);
4012 mutex_lock(&module_mutex);
4013 /* Unlink carefully: kallsyms could be walking list. */
4014 list_del_rcu(&mod->list);
4015 mod_tree_remove(mod);
4016 wake_up_all(&module_wq);
4017 /* Wait for RCU-sched synchronizing before releasing mod->list. */
4019 mutex_unlock(&module_mutex);
4021 /* Free lock-classes; relies on the preceding sync_rcu() */
4022 lockdep_free_key_range(mod->core_layout.base, mod->core_layout.size);
4024 module_deallocate(mod, info);
4030 SYSCALL_DEFINE3(init_module, void __user *, umod,
4031 unsigned long, len, const char __user *, uargs)
4034 struct load_info info = { };
4036 err = may_init_module();
4040 pr_debug("init_module: umod=%p, len=%lu, uargs=%p\n",
4043 err = copy_module_from_user(umod, len, &info);
4047 return load_module(&info, uargs, 0);
4050 SYSCALL_DEFINE3(finit_module, int, fd, const char __user *, uargs, int, flags)
4052 struct load_info info = { };
4056 err = may_init_module();
4060 pr_debug("finit_module: fd=%d, uargs=%p, flags=%i\n", fd, uargs, flags);
4062 if (flags & ~(MODULE_INIT_IGNORE_MODVERSIONS
4063 |MODULE_INIT_IGNORE_VERMAGIC))
4066 err = kernel_read_file_from_fd(fd, 0, &hdr, INT_MAX, NULL,
4073 return load_module(&info, uargs, flags);
4076 static inline int within(unsigned long addr, void *start, unsigned long size)
4078 return ((void *)addr >= start && (void *)addr < start + size);
4081 #ifdef CONFIG_KALLSYMS
4083 * This ignores the intensely annoying "mapping symbols" found
4084 * in ARM ELF files: $a, $t and $d.
4086 static inline int is_arm_mapping_symbol(const char *str)
4088 if (str[0] == '.' && str[1] == 'L')
4090 return str[0] == '$' && strchr("axtd", str[1])
4091 && (str[2] == '\0' || str[2] == '.');
4094 static const char *kallsyms_symbol_name(struct mod_kallsyms *kallsyms, unsigned int symnum)
4096 return kallsyms->strtab + kallsyms->symtab[symnum].st_name;
4100 * Given a module and address, find the corresponding symbol and return its name
4101 * while providing its size and offset if needed.
4103 static const char *find_kallsyms_symbol(struct module *mod,
4105 unsigned long *size,
4106 unsigned long *offset)
4108 unsigned int i, best = 0;
4109 unsigned long nextval, bestval;
4110 struct mod_kallsyms *kallsyms = rcu_dereference_sched(mod->kallsyms);
4112 /* At worse, next value is at end of module */
4113 if (within_module_init(addr, mod))
4114 nextval = (unsigned long)mod->init_layout.base+mod->init_layout.text_size;
4116 nextval = (unsigned long)mod->core_layout.base+mod->core_layout.text_size;
4118 bestval = kallsyms_symbol_value(&kallsyms->symtab[best]);
4120 /* Scan for closest preceding symbol, and next symbol. (ELF
4121 starts real symbols at 1). */
4122 for (i = 1; i < kallsyms->num_symtab; i++) {
4123 const Elf_Sym *sym = &kallsyms->symtab[i];
4124 unsigned long thisval = kallsyms_symbol_value(sym);
4126 if (sym->st_shndx == SHN_UNDEF)
4129 /* We ignore unnamed symbols: they're uninformative
4130 * and inserted at a whim. */
4131 if (*kallsyms_symbol_name(kallsyms, i) == '\0'
4132 || is_arm_mapping_symbol(kallsyms_symbol_name(kallsyms, i)))
4135 if (thisval <= addr && thisval > bestval) {
4139 if (thisval > addr && thisval < nextval)
4147 *size = nextval - bestval;
4149 *offset = addr - bestval;
4151 return kallsyms_symbol_name(kallsyms, best);
4154 void * __weak dereference_module_function_descriptor(struct module *mod,
4160 /* For kallsyms to ask for address resolution. NULL means not found. Careful
4161 * not to lock to avoid deadlock on oopses, simply disable preemption. */
4162 const char *module_address_lookup(unsigned long addr,
4163 unsigned long *size,
4164 unsigned long *offset,
4168 const char *ret = NULL;
4172 mod = __module_address(addr);
4175 *modname = mod->name;
4177 ret = find_kallsyms_symbol(mod, addr, size, offset);
4179 /* Make a copy in here where it's safe */
4181 strncpy(namebuf, ret, KSYM_NAME_LEN - 1);
4189 int lookup_module_symbol_name(unsigned long addr, char *symname)
4194 list_for_each_entry_rcu(mod, &modules, list) {
4195 if (mod->state == MODULE_STATE_UNFORMED)
4197 if (within_module(addr, mod)) {
4200 sym = find_kallsyms_symbol(mod, addr, NULL, NULL);
4204 strlcpy(symname, sym, KSYM_NAME_LEN);
4214 int lookup_module_symbol_attrs(unsigned long addr, unsigned long *size,
4215 unsigned long *offset, char *modname, char *name)
4220 list_for_each_entry_rcu(mod, &modules, list) {
4221 if (mod->state == MODULE_STATE_UNFORMED)
4223 if (within_module(addr, mod)) {
4226 sym = find_kallsyms_symbol(mod, addr, size, offset);
4230 strlcpy(modname, mod->name, MODULE_NAME_LEN);
4232 strlcpy(name, sym, KSYM_NAME_LEN);
4242 int module_get_kallsym(unsigned int symnum, unsigned long *value, char *type,
4243 char *name, char *module_name, int *exported)
4248 list_for_each_entry_rcu(mod, &modules, list) {
4249 struct mod_kallsyms *kallsyms;
4251 if (mod->state == MODULE_STATE_UNFORMED)
4253 kallsyms = rcu_dereference_sched(mod->kallsyms);
4254 if (symnum < kallsyms->num_symtab) {
4255 const Elf_Sym *sym = &kallsyms->symtab[symnum];
4257 *value = kallsyms_symbol_value(sym);
4258 *type = kallsyms->typetab[symnum];
4259 strlcpy(name, kallsyms_symbol_name(kallsyms, symnum), KSYM_NAME_LEN);
4260 strlcpy(module_name, mod->name, MODULE_NAME_LEN);
4261 *exported = is_exported(name, *value, mod);
4265 symnum -= kallsyms->num_symtab;
4271 /* Given a module and name of symbol, find and return the symbol's value */
4272 static unsigned long find_kallsyms_symbol_value(struct module *mod, const char *name)
4275 struct mod_kallsyms *kallsyms = rcu_dereference_sched(mod->kallsyms);
4277 for (i = 0; i < kallsyms->num_symtab; i++) {
4278 const Elf_Sym *sym = &kallsyms->symtab[i];
4280 if (strcmp(name, kallsyms_symbol_name(kallsyms, i)) == 0 &&
4281 sym->st_shndx != SHN_UNDEF)
4282 return kallsyms_symbol_value(sym);
4287 /* Look for this name: can be of form module:name. */
4288 unsigned long module_kallsyms_lookup_name(const char *name)
4292 unsigned long ret = 0;
4294 /* Don't lock: we're in enough trouble already. */
4296 if ((colon = strnchr(name, MODULE_NAME_LEN, ':')) != NULL) {
4297 if ((mod = find_module_all(name, colon - name, false)) != NULL)
4298 ret = find_kallsyms_symbol_value(mod, colon+1);
4300 list_for_each_entry_rcu(mod, &modules, list) {
4301 if (mod->state == MODULE_STATE_UNFORMED)
4303 if ((ret = find_kallsyms_symbol_value(mod, name)) != 0)
4311 int module_kallsyms_on_each_symbol(int (*fn)(void *, const char *,
4312 struct module *, unsigned long),
4319 module_assert_mutex();
4321 list_for_each_entry(mod, &modules, list) {
4322 /* We hold module_mutex: no need for rcu_dereference_sched */
4323 struct mod_kallsyms *kallsyms = mod->kallsyms;
4325 if (mod->state == MODULE_STATE_UNFORMED)
4327 for (i = 0; i < kallsyms->num_symtab; i++) {
4328 const Elf_Sym *sym = &kallsyms->symtab[i];
4330 if (sym->st_shndx == SHN_UNDEF)
4333 ret = fn(data, kallsyms_symbol_name(kallsyms, i),
4334 mod, kallsyms_symbol_value(sym));
4341 #endif /* CONFIG_KALLSYMS */
4343 /* Maximum number of characters written by module_flags() */
4344 #define MODULE_FLAGS_BUF_SIZE (TAINT_FLAGS_COUNT + 4)
4346 /* Keep in sync with MODULE_FLAGS_BUF_SIZE !!! */
4347 static char *module_flags(struct module *mod, char *buf)
4351 BUG_ON(mod->state == MODULE_STATE_UNFORMED);
4353 mod->state == MODULE_STATE_GOING ||
4354 mod->state == MODULE_STATE_COMING) {
4356 bx += module_flags_taint(mod, buf + bx);
4357 /* Show a - for module-is-being-unloaded */
4358 if (mod->state == MODULE_STATE_GOING)
4360 /* Show a + for module-is-being-loaded */
4361 if (mod->state == MODULE_STATE_COMING)
4370 #ifdef CONFIG_PROC_FS
4371 /* Called by the /proc file system to return a list of modules. */
4372 static void *m_start(struct seq_file *m, loff_t *pos)
4374 mutex_lock(&module_mutex);
4375 return seq_list_start(&modules, *pos);
4378 static void *m_next(struct seq_file *m, void *p, loff_t *pos)
4380 return seq_list_next(p, &modules, pos);
4383 static void m_stop(struct seq_file *m, void *p)
4385 mutex_unlock(&module_mutex);
4388 static int m_show(struct seq_file *m, void *p)
4390 struct module *mod = list_entry(p, struct module, list);
4391 char buf[MODULE_FLAGS_BUF_SIZE];
4394 /* We always ignore unformed modules. */
4395 if (mod->state == MODULE_STATE_UNFORMED)
4398 seq_printf(m, "%s %u",
4399 mod->name, mod->init_layout.size + mod->core_layout.size);
4400 print_unload_info(m, mod);
4402 /* Informative for users. */
4403 seq_printf(m, " %s",
4404 mod->state == MODULE_STATE_GOING ? "Unloading" :
4405 mod->state == MODULE_STATE_COMING ? "Loading" :
4407 /* Used by oprofile and other similar tools. */
4408 value = m->private ? NULL : mod->core_layout.base;
4409 seq_printf(m, " 0x%px", value);
4413 seq_printf(m, " %s", module_flags(mod, buf));
4419 /* Format: modulename size refcount deps address
4421 Where refcount is a number or -, and deps is a comma-separated list
4424 static const struct seq_operations modules_op = {
4432 * This also sets the "private" pointer to non-NULL if the
4433 * kernel pointers should be hidden (so you can just test
4434 * "m->private" to see if you should keep the values private).
4436 * We use the same logic as for /proc/kallsyms.
4438 static int modules_open(struct inode *inode, struct file *file)
4440 int err = seq_open(file, &modules_op);
4443 struct seq_file *m = file->private_data;
4444 m->private = kallsyms_show_value(file->f_cred) ? NULL : (void *)8ul;
4450 static const struct proc_ops modules_proc_ops = {
4451 .proc_flags = PROC_ENTRY_PERMANENT,
4452 .proc_open = modules_open,
4453 .proc_read = seq_read,
4454 .proc_lseek = seq_lseek,
4455 .proc_release = seq_release,
4458 static int __init proc_modules_init(void)
4460 proc_create("modules", 0, NULL, &modules_proc_ops);
4463 module_init(proc_modules_init);
4466 /* Given an address, look for it in the module exception tables. */
4467 const struct exception_table_entry *search_module_extables(unsigned long addr)
4469 const struct exception_table_entry *e = NULL;
4473 mod = __module_address(addr);
4477 if (!mod->num_exentries)
4480 e = search_extable(mod->extable,
4487 * Now, if we found one, we are running inside it now, hence
4488 * we cannot unload the module, hence no refcnt needed.
4494 * is_module_address - is this address inside a module?
4495 * @addr: the address to check.
4497 * See is_module_text_address() if you simply want to see if the address
4498 * is code (not data).
4500 bool is_module_address(unsigned long addr)
4505 ret = __module_address(addr) != NULL;
4512 * __module_address - get the module which contains an address.
4513 * @addr: the address.
4515 * Must be called with preempt disabled or module mutex held so that
4516 * module doesn't get freed during this.
4518 struct module *__module_address(unsigned long addr)
4522 if (addr < module_addr_min || addr > module_addr_max)
4525 module_assert_mutex_or_preempt();
4527 mod = mod_find(addr);
4529 BUG_ON(!within_module(addr, mod));
4530 if (mod->state == MODULE_STATE_UNFORMED)
4537 * is_module_text_address - is this address inside module code?
4538 * @addr: the address to check.
4540 * See is_module_address() if you simply want to see if the address is
4541 * anywhere in a module. See kernel_text_address() for testing if an
4542 * address corresponds to kernel or module code.
4544 bool is_module_text_address(unsigned long addr)
4549 ret = __module_text_address(addr) != NULL;
4556 * __module_text_address - get the module whose code contains an address.
4557 * @addr: the address.
4559 * Must be called with preempt disabled or module mutex held so that
4560 * module doesn't get freed during this.
4562 struct module *__module_text_address(unsigned long addr)
4564 struct module *mod = __module_address(addr);
4566 /* Make sure it's within the text section. */
4567 if (!within(addr, mod->init_layout.base, mod->init_layout.text_size)
4568 && !within(addr, mod->core_layout.base, mod->core_layout.text_size))
4574 /* Don't grab lock, we're oopsing. */
4575 void print_modules(void)
4578 char buf[MODULE_FLAGS_BUF_SIZE];
4580 printk(KERN_DEFAULT "Modules linked in:");
4581 /* Most callers should already have preempt disabled, but make sure */
4583 list_for_each_entry_rcu(mod, &modules, list) {
4584 if (mod->state == MODULE_STATE_UNFORMED)
4586 pr_cont(" %s%s", mod->name, module_flags(mod, buf));
4589 if (last_unloaded_module[0])
4590 pr_cont(" [last unloaded: %s]", last_unloaded_module);
4594 #ifdef CONFIG_MODVERSIONS
4595 /* Generate the signature for all relevant module structures here.
4596 * If these change, we don't want to try to parse the module. */
4597 void module_layout(struct module *mod,
4598 struct modversion_info *ver,
4599 struct kernel_param *kp,
4600 struct kernel_symbol *ks,
4601 struct tracepoint * const *tp)
4604 EXPORT_SYMBOL(module_layout);